Language reference
Status: architecture (week 1), flow (week 4), sequence (week 5) and erd (week 6) are implemented, with pin and the formatter (ink fmt). Changes after the week-3 freeze need an ADR; the type sections below were finalised with that week's grammar additions (see "Grammar changes in v0.2").
Example
diagram architecture "Checkout platform"
direction right
theme slate
person shopper "Customer"
zone aws "AWS eu-west-1" {
service api "Orders API" use=aws/ecs
store orders "Orders DB" use=aws/rds
queue events "Order events" use=aws/sqs
fn mailer "Email worker" use=aws/lambda
}
shopper -> api : HTTPS
api -> orders : SQL
api ~> events : publish # ~> is async
events ~> mailer : consumeLexical rules
| Token | Rule |
|---|---|
| Identifier | [A-Za-z_][A-Za-z0-9_-]*. Case-sensitive. A - followed by >, < or - ends it. |
| String | "…" on one line; escapes \" \\ \n. |
| Number | -?[0-9]+(\.[0-9]+)? |
| Comment | # to end of line. Kept by the formatter and by source edits. Exception: =# followed by 3–8 hex digits (color=#B4500B) is a colour value. |
| Newline | Ends a statement. Indentation is not significant. |
; | Ends a statement, like a newline (box a; box b). |
| Punctuation | { } : = , / . ( ) [ ] |
| Arrows | -> ~> <-> -- --> -< >- >-< - --|> ..|> *-- o-- ..> (longest match; which ones a type uses below) |
The single - arrow needs spaces around it (a - b), because a-b is one identifier. o-- (UML aggregation) is an arrow only after an edge end and a space (Order o-- Customer); elsewhere o is a name.
Class bodies (class, interface, abstract, enum in diagram class) are lexed by rows: each row up to a newline, ; or the closing } is kept whole, so +, #, <…> and (…) need no quoting. In a class body a # at the start of a row is the protected visibility; a # after a space later in the row starts a comment (+ id: UUID # key). Put whole-line comments outside the class.
Document structure
document := header statement*
header := "diagram" TYPE STRING? END
statement := setting | node | edge | pin | directive
END := NEWLINE | ";"
setting := ("direction" DIR | "theme" IDENT) END
| STYLE "=" COLOUR END -- diagram colour overrides
STYLE := background | accent | boxfill | boxstroke | textcolor | edgecolor
COLOUR := palette name | #hex (3, 6 or 8 digits; lexed as a value after "=")
node := KIND ID STRING? attribute* block? END
block := "{" statement* "}" -- containers
| "{" row (END row)* "}" -- row-block kinds (ERD `table`)
row := CELL+ -- tokens written without spaces form one CELL
edge := REF (ARROW REF)+ attribute* (":" label)? END
REF := ID ("." ID)? -- `table.column` in ERD
label := STRING | free text to end of line (stops at "#")
attribute := IDENT "=" (IDENT | STRING | NUMBER | path)
path := IDENT ("/" IDENT)+
pin := "pin" ID "at" NUMBER "," NUMBER END
directive := KEYWORD (WORD | STRING | NUMBER | ",")* (":" label)? ("{" statement* "}")? END
DIR := right | down | left | upDirectives are type-specific statements whose first word the diagram type registers (sequence: note, group, alt, else, opt, loop, par). In other types those words are ordinary identifiers. A continuation directive (else) may follow a closing } on the same line.
Edge attributes go before the : because everything after it is the label, e.g. api -> db color=red : SQL over TLS. Use a quoted label to include #.
diagram must be the first statement. Edge chains (a -> b -> c) create one edge per pair, all sharing the label. Edges are numbered e0, e1, … in source order (ModelEdge order).
Settings
| Setting | Values | Default |
|---|---|---|
direction | right, down, left, up | per type: down for flow, else right |
theme | slate, light, dark, ink | slate |
ink is the brand theme: white paper, cobalt ink. Sequence diagrams ignore direction.
Diagram colour overrides
Any theme can be recoloured with override lines, written name=value (like attributes, so #hex lexes as a value rather than a comment). Each takes a palette name or #hex; unset ones come from the theme. diagramStyleTokens lists them.
diagram architecture "Checkout"
theme dark
background=#0B1120
accent=#14B8A6
boxfill=#111A2E
boxstroke=#1E3A5F
textcolor=#E2E8F0
edgecolor=#64748B| Override | Sets |
|---|---|
background | Canvas and edge-label background |
accent | Every kind colour (icon tiles, flow outlines, title bands), async edges, container tint |
boxfill | Box fill |
boxstroke | Box border |
textcolor | Box text, and the preferred tone for canvas text and edge labels |
edgecolor | Edges and their markers |
Dependent tones are derived, not fixed: container fills, borders and titles are mixed from the accent (or the theme's container colour) over the background; frames, lifelines, row stripes and muted text follow the background, box fill and text; text on derived fills (edge labels, container titles, title bands, text on accent) is picked for WCAG AA. A named value uses its palette tone (fill for background/boxfill, text for textcolor, stroke otherwise). An invalid value is INK2006 and ignored; a later line for the same override wins. INK2026 warns when box text on the box fill, or text on the background, is below 4.5:1 in the diagram's theme. edits.setDiagramStyle(source, { token: value | null }) writes them in one edit: existing lines are updated in place, new ones are added after the last setting (or the header) in token order, null removes a line; it is idempotent, keeps comments, and fails (source unchanged) on an unknown token or invalid value.
Pins
pin <id> at x, y fixes a node's top-left corner at (x, y) in scene coordinates — the same numbers SceneNode.x/y report, so a canvas can write back exactly what it shows. The canvas is unbounded: negative values are kept as written (pin api at -120,-40), here and in every other written position (at x,y on stickies, shapes, text and frames, line … from x,y to x,y, sketch paths). Each pin, at and from … to coordinate must lie in −100000…100000, else INK2027 (error) and the item or pin is not applied; the edit API refuses such values and leaves the text unchanged. Pins on containers and in sequence diagrams are ignored with INK2016; a second pin for the same id wins, also with INK2016.
Some boxes pinned (architecture, flow, ERD): everything is laid out automatically first; the pinned boxes then move to their pins, containers holding them refit around their children, and the edges touching a pinned box are re-routed by the edge router below.
Every box pinned — freeform. When every non-container node of a layered diagram has a pin, the automatic layout is skipped entirely: boxes sit at their pins, containers are fitted around their children (20 px on the sides and bottom, a 40 px title band on top, at least as wide as the title; nested containers innermost first), the edge router draws every line, and the canvas is sized from the content. Nothing moves except what the source moves, and layout is synchronous and fast (about 9–10 ms for compile + layout + SVG of 101 boxes on the dev machine).
Canvas origin. The drawing's canvas covers its content plus padding (24 px by default). It starts at 0,0 unless content reaches into negative coordinates; then, per axis, it starts the padding before the content (Scene.originX / originY, whole pixels, absent when 0). The SVG viewBox is originX originY width height, and the backdrop rectangle starts at the origin, so nothing is clipped. Diagrams with no negative content keep a 0 0 origin and render exactly as before.
Edge routing
Used for freeform diagrams and for edges touching pinned boxes.
- Edges to containers. A zone, group, package or composite can be an edge end. Between a box (or container) and a container that does not hold it, the edge meets the container's border like a box. Between a box and a container around it (
orders -> awswithordersinsideaws), the edge runs straight from the box to the nearest border of that container that has room for the arrow (and label) and passes no other box; its label sits just outside that border. A container's edge to itself is a loop over its top edge. - No edge vanishes. Every connection is drawn: an edge the automatic layout gives no route is drawn by the router. If one still cannot be drawn,
render()warnsINK2025for it.
- Ports. Each end leaves from the side of its box that faces the other box. When the two facing sides overlap, both ends share one coordinate inside the overlap and the edge is a single straight line. Ends on one side keep at least 16 px apart (arrowheads never stack), ordered by where the other end lies; a side that cannot hold them all passes its most off-axis ends to the neighbouring side facing their target. ERD relations attach to the named row.
- Paths. Orthogonal; 16 px clear of boxes where possible, never closer than 2 px; around stickies, container title bands and containers that hold neither end. Fewer bends first, then shorter, then fewer crossings and no running along another edge's line. Shortest edges are routed first; edges left with crossings are ripped up and re-routed once (bounded, deterministic). Parallel runs of different edges are nudged 16 px apart. Every arrowhead has a straight run of at least 16 px (less only where two facing sides are closer than 32 px: then the edge is one clean Z).
- Labels. On the edge's own path (longest segment first, several spots), else beside a segment; never over a box, title band, sticky, other label, arrowhead (6 px clear) or another edge's line.
Sizes
w=<px> and h=<px> give a box an explicit size (architecture and flow nodes, all shapes; ERD tables take w only — their height follows the rows). On zone / group containers they are a minimum: the container still grows to fit its children. Values are whole numbers from the shape's minimum to 2000:
| Shape | Minimum w × h |
|---|---|
| Architecture box | 84 × 40 (padding, glyph and a little label) |
| Flow box | 60 × 40 |
| Flow decision | 80 × 48 |
| Container | 80 × 60 |
| ERD table | w ≥ 120 |
Anything else is INK2021. The label re-wraps inside the given size: as many lines as fit the height (at least one), … beyond. Both automatic and freeform layout use the sizes.
A box larger than its content keeps the content in the middle: an architecture box centres its icon and text as one group (text lines stay left-aligned within the group, and a description stays under its label); flow, state, class, free-form shapes and ERD/class headers centre their text. A box that is just big enough keeps the usual 12 px padding. Container titles stay at the top left.
Text
Node labels wrap at spaces to at most two lines inside a 220 px box (architecture), 180 px of text (flow) or 130 px (flow decisions); words longer than a line break between characters; text that still does not fit ends in …. Edge labels wrap the same way at 160 px. \n in a quoted label forces a break. Widths come from an exact Inter (v4.1) advance-width table generated from the fonts @inkline/export bundles, so SVG, PNG and PDF agree.
Architecture type
| Kind | Meaning | Default glyph |
|---|---|---|
person | Human actor | person |
client | Browser, mobile app | screen |
service | Running service / API | hexagon |
fn | Serverless function / worker | bolt |
store | Database | cylinder |
cache | Cache | stack |
queue | Queue / topic / stream | bars |
external | Third-party system | cloud |
box | Anything else | square |
zone | Container: region, VPC, account (takes a {} block) | — |
group | Container: logical grouping (takes a {} block) | — |
| Arrow | Meaning | Drawn as |
|---|---|---|
-> | Synchronous call | solid, arrow head |
~> | Asynchronous message | dashed, accent colour, arrow head |
<-> | Two-way | solid, heads both ends |
-- | Association | solid, no heads |
Attributes: use=<icon> (see Icons), color= / fill= / stroke= / text= (see Colours), note="…". Unknown attributes are a warning, not an error.
AI building blocks
AI systems are ordinary systems with a few extra parts, so they live in architecture diagrams. Each kind draws its own original glyph (the ai-ml/<kind> icon) on its own accent colour (a theme token in every theme).
| Kind | Meaning | Glyph |
|---|---|---|
llm | A language model endpoint | chat bubble, spark |
model | Any other ML model (classifier, hosted embedding model) | boxed network |
agent | An LLM-driven loop that plans and calls tools | robot head |
orchestrator | Coordinates several agents or steps | hierarchy |
tool | A function / API an agent can call | wrench |
mcp | An MCP server exposing tools / resources | plug |
prompt | Prompt template / system prompt | terminal prompt |
memory | Conversation or long-term memory | stacked cards |
vectordb | Vector database / index | cylinder with dots |
embedder | Embedding step | text → vector |
retriever | Retrieval step (vector, keyword or hybrid) | page and magnifier |
reranker | Re-ranking step | ranked bars, arrows |
corpus | Source documents / knowledge base | books |
chunker | Document splitting / ingestion step | page → chunks |
guardrail | Input / output safety, policy or PII filter | shield with check |
eval | Evaluation suite / judge | clipboard check |
tracer | Observability: traces, logs, token / cost metrics | span waterfall |
cache (above) doubles as a semantic or response cache. Arrows keep their meaning: -> call, ~> async / stream, <-> a two-way loop (agent ↔ tool), -- association. Zones model boundaries ("Agent harness", "Offline / online path").
A box with more edges on one side than fit 16 px apart is drawn taller (wider in down/up layouts) so its edges fan out. A hub (six or more connections, such as an agent wired to its model, tools, memory and guards) has its leaf neighbours balanced on both sides — inputs and context (prompt, memory, box, caches, stores, guardrails) before it, tools and models after it — and its lines drawn straight where the boxes face each other; arrows keep their written direction. A person or client that starts a flow stays first even when the answer comes back to it.
Icons
use= puts an icon in a node's tile instead of the kind glyph. A reference is one of:
<category>/<icon>from the built-in library: 17 categories (compute, containers, storage, database, networking, security, messaging, analytics, ai-ml, devices, people, business, finance, logistics, health, general, arrows), 8 icons each exceptai-ml(25: one per AI kind plus brain, sparkle, neural-net, experiment, dataset, vector). All are original generic stroke drawings — no vendor artwork (CLAUDE.md rule 8).iconLibrarylists them;iconSvg(ref)returns one.- A vendor-style alias that maps to a generic icon, e.g.
aws/ecs→containers/container,aws/rds→database/database,aws/sqs→messaging/queue,aws/lambda→compute/function,aws/s3→storage/bucket,azure/cosmosdb→database/document-db,gcp/pubsub→messaging/topic(about 120 aliases across aws/azure/gcp/k8s). The vendor name is only a hint; the drawing is generic. - AI vendor references map to the generic AI glyphs:
aws/bedrock,azure/openai,gcp/geminiand anyopenai/…,anthropic/…,mistral/…,cohere/…,ollama/…→ai-ml/llm;gcp/vertex,huggingface/…→ai-ml/model;langchain/…→ai-ml/agent;langgraph/…,crewai/…,autogen/…→ai-ml/orchestrator;llamaindex/…→ai-ml/retriever;pinecone,weaviate,qdrant,chroma,milvus,pgvector,faiss,lancedb(bare or with/…) →ai-ml/vectordb;langsmith,langfuse,arize,helicone→ai-ml/tracer;ragas,promptfoo→ai-ml/eval; plus specific ones such asopenai/embeddings→ai-ml/embedderandcohere/rerank→ai-ml/reranker. Theai-mlcategory holds an icon for every AI kind. custom/<name>([a-z0-9-]{1,40}): a workspace icon passed torender()ascustomIcons: { "custom/<name>": "<svg …>" }. The engine sanitises it again (see Icon sanitiser below).sanitizeIconSvg(svg)is the same check.
Vendor icon packs (ADR-0009). use=aws/…, use=azure/…, use=gcp/… and use=logos/… name icons from the official AWS, Azure and Google Cloud sets and Simple Icons. The engine bundles none of them: the host loads the icons a diagram needs (iconRefs(model) lists them) and passes them as RenderOptions.icons: { "<pack>/<id>": "<svg …>" }. A supplied pack icon is drawn in the box's icon square without the coloured tile (official icons carry their own colour and frame), scaled to fit 28×28. A pack ref that was not supplied falls back to its generic alias (aws/lambda → compute/function) and, without one, to the kind glyph with INK2018 at render time. Pack refs never warn at compile time (the host may load the pack).
Container icons. Zones, groups and other containers accept use= too: an 18 px icon is drawn before the title (vendor icons as they are, generic glyphs in the title colour) and the container reserves room for it.
Icon sanitiser. Every icon that is not built in (custom uploads and the vendor packs of ADR-0009) goes through one allow-list; the input is parsed and re-serialised, never passed through.
- Elements:
svg g path circle rect ellipse line polyline polygon, and for paint and clippingdefs linearGradient radialGradient stop clipPath mask(their content is geometry only).title/desc/metadataare dropped with their text. - Attributes: geometry,
transform,viewBox,fill/stroke(colours, or a localurl(#id)),stroke-*,fill-rule/clip-rule, opacities,stop-color/stop-opacity/offset,gradientUnits/gradientTransform/spreadMethod,x1 y1 x2 y2 cx cy r fx fy fr,clip-path/mask(localurl(#id)only),id. Unknown presentation attributes are dropped. style="…"and<style>with.class { … }rules are accepted when every declaration is an allowed attribute with an allowed value; they are inlined as attributes (class rules, then the style attribute, override plain attributes) and never emitted.- A gradient's
href/xlink:hrefto another gradient of the same icon (#id) is inlined (stops and settings copied); nohrefis ever emitted. - Every
url(#id)must point at an element of the same icon; ids must be unique. Unreferenced ids are dropped. - Rejected outright: scripts, event handlers, any other
href/xlink:*(including<use>),foreignObject,image,text, external orjavascript:url(…),data:, CSS at-rules, other selectors or unknown properties, doctype/entities/CDATA/processing instructions, more than 64 KB, 2,000 elements, or elements nested more than 32 levels deep (the root is level 1). - When drawn, each embed's ids and
url(#id)get a deterministic per-embed prefix (ink0-,ink1-, … in drawing order), so two icons — or the same icon twice — never share an id.
References are case-insensitive. One that does not resolve warns INK2018 and the kind glyph is drawn; a custom/… icon that is missing or fails the check warns INK2018 from render().
Annotations
Architecture and flow diagrams can carry free-floating stickies and freehand sketches. They use absolute scene coordinates, are drawn above everything, and never affect layout (the canvas grows to include them).
sticky n1 "Check retry policy" at 420,40 color=yellow w=180 # a paper, a palette name or #hex
sketch s1 "M10 10 L40 60 L90 20" color=#B4500B width=2| Statement | Form | Attributes |
|---|---|---|
sticky | sticky <id> "text" at <x>, <y> | color = a paper — yellow (default), blue, green, pink, grey — or any palette name or #hex (the paper fill; edge mixed from it, text picked for AA); w = width 80–600 (default 180) |
sketch | sketch <id> "<path>" — absolute commands M L H V C S Q T Z, starting with M | color = #hex or a palette name (default auto: the theme's edge colour); width = 0.5–20 (default 2) |
Sticky text wraps to the width (up to 8 lines). Ids share the node namespace (INK2003). Malformed forms or paths are INK2017; bad attribute values INK2006; unknown attributes INK2005; annotations in sequence or ERD diagrams warn INK2019 and are ignored.
Descriptions and edge label placement
desc="…"on an architecture box or container (\nbreaks lines): smaller muted text under the label. A box with a description puts its icon at the top left and stacks the label and up to four description lines beside it ("…" beyond), growing to fit (at most 300 px wide). Withw=/h=the size wins and the description keeps the lines that fit. On a container the description sits under the title and the container makes room for it.labelpos=inlineon an edge puts its label on the line, centred on the longest segment, with the label's background breaking the line;labelpos=sidekeeps the automatic placement and is the default in every diagram type and layout, freeform included (automatic placement keeps labels clear of boxes, other labels and lines). Anything else isINK2006.
Colours
Every box kind in every diagram type — architecture boxes (including the 17 AI kinds), flow shapes, sequence participants, ERD tables, class boxes, state shapes, free-form shapes — and every container (zone, group, package, composite) and free-form frame takes colours:
service api "Orders API" color=teal
store db "Orders DB" fill=#0F172A stroke=#38BDF8 text=#E0F2FE
api -> db color=purple width=3 dash=true : SQLA colour value is a palette name — grey blue green yellow orange red pink purple teal (the same in every theme; namedColours lists each one's fill, stroke and text tones) — or #hex with 3, 6 or 8 digits. Anything else is INK2006 and the attribute is dropped, so no unchecked value reaches the SVG.
| Attribute | On | Effect |
|---|---|---|
color | boxes, containers | Tints the fill (12 % of the colour over the theme fill; 8 % for containers and frames), colours the border, the icon tile, title bands (ERD, class) and solid marks (flow start/end, state dots and bars). |
fill | boxes, containers | The fill (a name uses its light fill tone). Overrides color's tint. |
stroke | boxes, containers | The border (a name uses its stroke tone). On a shape, solid/dashed/dotted is still the outline style. |
text | boxes, containers | The label colour (a name uses its dark text tone). |
color | edges, line | The line and its ends (arrowheads, crow's feet, UML diamonds and triangles). stroke= is an alias on edges. |
width | edges, line | Line width in px: 1–8 on edges (lines keep 0.5–12). Arrowheads grow with it. |
dash | edges, line | true / false (edges also take solid, dashed, dotted); false makes ~> solid. |
text | edges | The label colour. |
Without text=, label colour is picked for WCAG AA contrast (4.5:1) with the fill the box actually gets, in light and dark themes alike (near-black or white, else pure black, which always reaches AA). When text= and fill= are both written and their contrast is below 4.5:1, INK2026 warns (the colours are kept).
Editing. edits.setStyle(source, ids, change) writes these attributes in one text edit (one undo step). ids mixes node / free-form ids and edge ids (model.edges[i].id; a bound line's edge id styles that line). change keys: fill, stroke, text, color, width, dash; null removes the attribute. Only the attribute words change (formatting and comments stay), the edit is idempotent, and a styled segment of a chain (a -> b -> c) is split onto its own line. Keys an item cannot take are skipped (a shape keeps a stroke=dashed style; stickies and sketches take color, sketches also width); unknown ids are skipped. An unknown key or invalid value fails with the source unchanged.
Document notes
A file may carry Markdown notes in a doc block, by convention at the end:
doc """
# Option 2
Windows VM + Azure SQL + PostgreSQL pgvector + AI Foundry.
""""""…"""is a multi-line string: newlines are kept,#inside is text, and the only escape is\"""for three quotes. Unterminated isINK1002.- The notes are kept in the model (
model.doc, with the first/last blank line and the shared indentation removed), never drawn, and preserved verbatim by the formatter. Onedocblock per file (a second isINK2017).edits.setDoc(source, markdown)adds, replaces or (with"") removes it.
Free-form items
Architecture and flow diagrams can carry free-form items at absolute coordinates, like stickies. Their ids share the node namespace.
frame f1 "Option 2" at 20,10 w=1200 h=700 subtitle="PROD ~SGD 539 / month"
shape s1 rect "Legacy system" at 40,300 w=160 h=60 color=grey
text t1 "Read-only after cut-over" at 40,20 size=18 weight=bold
line l1 from 300,120 to 420,120 arrow=end dash=true color=#B4500B label="planned"
line l2 from api to s1 arrow=both color=purple| Statement | Form | Attributes |
|---|---|---|
shape | shape <id> <type> ["label"] at <x>,<y> — one of the 31 types below | w h (10–2000; default per type), color, fill, text, stroke (solid dashed dotted or a colour) |
text | text <id> "words" at <x>,<y> (top-left; \n breaks lines) | size (8–96, default 14), weight (normal medium bold), color |
line | line <id> from <x>,<y> to <x>,<y> or line <id> from <item> to <item> | arrow (none end start both, default none), dash (true false), color, width (0.5–12, default 2), label |
frame | frame <id> "title" at <x>,<y> | w h (40–10000; default 480×320), subtitle, color |
Shape types (shapeTypes lists them with name, category and default size; shapeGeometry gives the exact outline the renderer and edge clipping use):
| Category | Types (default w×h) |
|---|---|
| basic | rect 160×60, round 160×60, square 80×80, pill 160×50, circle 80×80, ellipse 160×80, triangle 120×100, triangle-down 120×100, diamond 120×90, pentagon 110×100, hexagon 150×70, octagon 100×100, star 110×105, cross 90×90, parallelogram 160×60, trapezoid 160×70, cube 140×90, cylinder 110×90, database-2 (horizontal cylinder) 160×70, cloud 170×100 |
| flow | document 160×80, multi-document 170×90, delay 140×70, manual-input 160×70 |
| arrows | arrow-right 150×70, arrow-left 150×70, chevron 140×60 |
| annotation | note 160×90, callout 170×90, brace 180×120, bracket 180×120 |
Every type has its own text area (the label wraps and centres inside it, e.g. under a triangle's apex, on a cube's front face, on an arrow's shaft); a resized shape keeps its label inside that area. Edges end on the visible outline, not the bounding box. brace and bracket are open marks at the left of their box with the label beside them.
- Shapes are nodes with a fixed position: ordinary edges connect to them (
api -> s1), the router draws those edges and goes around shapes. The automatic layout ignores them. - Lines between points are drawn as written; lines between items are routed like edges and drawn in their own look (they count as connections; removing an item removes its lines).
- Frames are titled backgrounds drawn beneath everything; they contain nothing structurally.
- Text is drawn above everything, left-aligned from its top-left corner.
- Colours:
#hexor a palette name (see Colours). Shapes and frames are tinted with it like boxes and containers; lines and text use it (a named text colour stays readable on dark themes). - In other diagram types these statements warn
INK2019and are ignored. Malformed forms areINK2017; bad valuesINK2006; a line to an unknown itemINK2004.
Flow type
diagram flow "Sign up"
start form "Form sent"
step create "Create account"
decision valid "Email valid?"
io mail "Send welcome email"
step fix "Ask for a corrected address"
end done "Done"
form -> create -> valid
valid -> mail : yes
valid -> fix : no
fix -> valid : retry
mail -> done| Kind | Meaning | Drawn as |
|---|---|---|
start | Where the flow begins | filled pill |
end | Where it finishes | filled pill |
step | An action | rounded rectangle |
decision | A question with branches | diamond; arrows meet its edges |
io | Input / output | parallelogram |
sub | A sub-process defined elsewhere | rectangle with double sides |
group | Container (takes a {} block) | — |
Arrows as in architecture (->, ~>, <->, --). Branch names are edge labels (: yes). Layout: ELK layered, direction down by default. In a cycle the edge written later is the one drawn as the loop back, so fix -> valid : retry loops up while the main path flows down.
Rules: a flow without a start warns (INK2012); a decision with fewer than two outgoing branches warns (INK2013). Attributes: color, note.
Sequence type
diagram sequence "Login"
actor user "User"
participant web "Web app"
participant api "Auth API"
user -> web : open /login
web -> api : POST /token
note over web, api : TLS everywhere
alt "password matches" {
api --> web : 200 JWT
web -> web : store token
} else "wrong password" {
api --> web : 401
note right of web : show the error inline
}| Kind | Meaning | Drawn as |
|---|---|---|
actor | A person | box with the person glyph |
participant | A system or component | outlined box |
| Arrow | Meaning | Drawn as |
|---|---|---|
-> | Call | solid, filled head |
--> | Reply | dashed, open head |
~> | Async signal | dashed, accent colour, head |
a -> a is a self-message (a loop to the right). Participants are placed left to right in declaration order; every message, note and frame takes the next row down. The layout is the engine's own (no ELK) and deterministic.
| Directive | Meaning |
|---|---|
note over a : text | Note centred on a's lifeline |
note over a, b : text | Note spanning two lifelines |
note left of a : text | Note to the left of a (right of likewise) |
group "title" { … } | Titled frame around messages |
alt "if" { … } else "else" { … } | Alternatives; any number of else, each } else "…" { |
opt / loop / par "title" { … } | Optional, repeated or parallel frames |
Frames nest. Pins are ignored (INK2016); containers do not exist (INK2007). Malformed directives (unknown note position, wrong number of targets, missing text or block, else not after alt) are INK2017.
ERD type
diagram erd "Shop"
table users { id uuid pk; email text unique }
table orders {
id uuid pk
user_id uuid fk
total numeric(12,2)
}
users.id -< orders.user_id| Kind | Meaning |
|---|---|
table | A table; its { } block holds one column per row (; or newline between rows) |
A column row is name type? flag*. Flags: pk, fk, unique (shown as PK / FK / UQ; with several, the strongest is drawn: pk > fk > unique). Tokens written without spaces are one cell, so numeric(12,2) and text[] are types. Unknown flags warn (INK2015); a repeated column name is INK2003.
| Arrow | Meaning | Ends drawn (crow's foot) |
|---|---|---|
- | one-to-one | bar — bar |
-< | one-to-many | bar — crow's foot |
>- | many-to-one | crow's foot — bar |
>-< | many-to-many | crow's foot — crow's foot |
Relation ends are table or table.column; with a column, the line meets that row, in every direction (in down/up layouts lines leave from the right side and arrive on the left). A column that does not exist is INK2014. Layout: ELK layered, direction right by default.
Class type
diagram class "Ordering"
class Order {
+ id: UUID
- items: List<Item>
+ total(): Money
+ {static} create(c: Customer): Order
}
interface Payable {
+ pay(amount: Money): Receipt
}
abstract class Vehicle {
# wheels: int
+ {abstract} size(): int
}
enum Status { OPEN; PAID; SHIPPED }
Order *-- Item from="1" to="1..*" : contains
Order o-- Customer
Car --|> Vehicle
Order ..|> Payable
Order --> Payment : uses
Order ..> Logger| Kind | Meaning | Drawn as |
|---|---|---|
class | A class | title band, fields and methods compartments |
interface | An interface | «interface» over the name |
abstract | An abstract class (write abstract class Name) | «abstract» over the name, name in italics |
enum | An enumeration; its body holds plain values | «enumeration», one compartment of values |
package | Container (takes a {} block of statements) | titled box |
abstract class Vehicle is kind abstract (the word class after abstract is optional; the formatter keeps what was written). A body row is a member:
- field:
[+|-|#|~] name[: Type]; - method:
[+|-|#|~] name(params)[: Type](anything with(…)after the name); {static}(drawn underlined) and{abstract}(drawn in italics) may appear anywhere in the row;- enum rows are values.
Visibility is drawn as the UML symbol (+ public, − private, # protected, ~ package); the type is drawn muted. A row with no name is INK2022; an unknown {modifier} warns INK2023. Members too long for the box (at most 380 px wide, or w=) end in "…".
| Arrow | Relation | Drawn as |
|---|---|---|
--|> | inheritance | solid, hollow triangle at the target |
..|> | realisation | dashed, hollow triangle at the target |
*-- | composition | solid, filled diamond at the source |
o-- | aggregation | solid, hollow diamond at the source |
--> | directed association | solid, open arrow at the target |
-- | association | solid, no ends |
..> | dependency | dashed, open arrow at the target |
Edge attributes from="…" and to="…" are multiplicities, drawn beside each end (on a chain a *-- b *-- c, from belongs to the first segment and to to the last). Layout: ELK layered, direction down by default; inheritance and realisation are laid out with the parent above the child. w= sets a class box's width; its height always fits the members. Edits add relations with --> when no arrow is given.
State type
diagram state "Order lifecycle"
start s
state draft "Draft"
state review "In review"
choice ok "Approved?"
state paid "Paid"
end done
composite fulfilment "Fulfilment" {
state picking "Picking"
state shipped "Shipped"
picking -> shipped : dispatched
}
s -> draft
draft -> draft : edit / save draft
draft -> review : submit [items > 0] / notify reviewer
review -> ok
ok -> paid : [approved]
ok -> draft : [rejected]
paid -> fulfilment
fulfilment -> done| Kind | Meaning | Drawn as |
|---|---|---|
start | Initial state | filled dot (no label) |
end | Final state | ringed dot (no label) |
state | A state | rounded box, label centred |
choice | Choice point | diamond; a written label is shown beside it |
fork | Splits into parallel regions | bar across the flow |
join | Joins parallel regions | bar across the flow |
composite | Container: a state with sub-states ({}) | titled box |
Transitions use ->. A label is free text in the UML form event [guard] / action: the guard ([…]) and the action (from / to the end) are drawn in their own theme colours. A transition from a state to itself is drawn as a loop over the box with its label above. start, end and choice have a fixed size; fork / join bars run across the layout direction. Warnings (INK2024): a transition into a start, out of an end, or a choice with fewer than two ways out. Layout: ELK layered, direction right by default.
Size limits
compile(), render() and quickRender() refuse diagrams that would be expensive to lay out, with error INK2020, before any layout runs. Defaults (DEFAULT_LIMITS), all configurable through limits in the options (Infinity turns one off; callers opt out explicitly):
| Limit | Default | Checked |
|---|---|---|
maxSourceBytes | 200 000 (UTF-8) | before parsing |
maxNodes | 500 items (boxes and containers) | after validation |
maxEdges | 1000 connections (chains expanded) | after validation |
maxLayoutWork | 250 000 = items × (connections + 1) | after validation |
The work limit is calibrated on the dev machine: about 3 s of layout at 440 items / 515 connections (work ≈ 227 000), about 4.4 s at 550 / 643 (≈ 354 000). The 1,500-item diagram from the security review (88 KB) is refused in under 10 ms. Servers should still run renders in a worker with a timeout; the limits only bound the work a single request can ask for.
Formatter (ink fmt, format())
Canonical form: header at column 0, statements indented two spaces per block level, one statement per line (; lines are split), single spaces between words, a -> b : label spacing. Runs of consecutive lines of the same shape (node declarations, single-arrow edges, pins, table rows) are aligned in columns; a blank line, a comment line or a block ends a run. At most one blank line is kept between statements; blank lines at the start and end of blocks are dropped. Comments stay on their line (trailing comments get two spaces before #). One-line ERD tables stay on one line. } else "…" { is joined. Quoted labels stay quoted. Stickies print as sticky id "text" at x,y …. The formatter is idempotent and never changes tokens or comments; with syntax errors it returns the input unchanged plus the diagnostics.
Grammar changes in v0.2
Added after the week-1 draft (all backwards compatible): ; as a statement end; arrows -->, -<, >-, >-<, -; .-qualified edge ends; ( ) [ ] punctuation (inside ERD cells); row blocks; directives registered per type. INK2009 is retired because pin is implemented. Round 2 (weeks 25–29 engine work): directive attributes (name=value after the args), the =#hex lexical rule, sticky/sketch statements, use= icon resolution, INK2018/INK2019. Phase 4b: arrows --|> ..|> *-- o-- ..>; the two-word kind abstract class; member rows in class bodies (lexed whole); diagram class and diagram state; 17 AI kinds in architecture; INK2022–INK2024 (from the accepted proposal docs/spec/proposals/ai-systems-hld-lld.md). Colour round (2026-11-21, backwards compatible): fill=/stroke=/text= on boxes, width=/dash= on edges, stickies take any palette name or #hex, diagram colour override settings (background=… etc., the STYLE "=" COLOUR setting form), INK2026. Negative coordinates (2026-11-21, backwards compatible): negative positions in pin, at x,y and line from x,y to x,y are kept instead of clamped to 0, the canvas origin follows content into negative space, INK2027 bounds positions to ±100000.
Diagnostics
Every problem has a stable code. Severity: E error (no render on CLI), W warning.
| Code | Sev | Message |
|---|---|---|
| INK1001 | E | Unexpected character {c}. |
| INK1002 | E | Unterminated string. |
| INK1003 | E | Expected {expected}, found {found}. |
| INK1004 | E | The file must start with diagram <type>. |
| INK1005 | E | Missing } to close the block opened on line {n}. |
| INK1006 | E | Unexpected }. |
| INK2001 | E | Unknown diagram type {t}. Did you mean {s}? |
| INK2002 | E | Unknown kind {k} for {type} diagrams. Did you mean {s}? |
| INK2003 | E | {id} is declared twice (first on line {n}). Also duplicate columns. |
| INK2004 | E | {id} is used but never declared. Did you mean {s}? |
| INK2005 | W | Unknown attribute {a}; it is ignored. |
| INK2006 | E | Invalid value {v} for {setting}. Expected one of {values}. (Also colours.) |
| INK2007 | E | {kind} cannot contain other items; only zone and group can. |
| INK2008 | W | Unknown theme {t}; using slate. |
| INK2009 | — | Retired (was "pin is ignored for now"). Never reused. |
| INK2010 | W | A diagram has no items. |
| INK2011 | E | Arrow {op} is not used in {type} diagrams. Use one of: {arrows}. |
| INK2012 | W | The flow has no start step. |
| INK2013 | W | Decision {id} has fewer than two branches. |
| INK2014 | E | {table} has no column {c} (or: columns are only for erd tables). |
| INK2015 | W | Unknown column flag {f}; expected pk, fk or unique. |
| INK2016 | W | pin on {id} is not applied: {reason}. |
| INK2017 | E | Malformed {directive}: {reason}. |
| INK2018 | W | Unknown icon {ref}; drawing the kind glyph instead. |
| INK2019 | W | sticky / sketch is ignored in {type} diagrams. |
| INK2020 | E | The diagram has {n} items (or connections, or source bytes); the limit is {m}. |
| INK2021 | E | Invalid width/height {v} for {id}: use a whole number from {min} to 2000. |
| INK2022 | E | {row} is not a member (class bodies: + name: Type or + name(args): Type). |
| INK2023 | W | Unknown member modifier {m}; expected {static} or {abstract}. |
| INK2024 | W | Transition into a start, out of an end, or a choice with < 2 ways out. |
| INK2025 | W | The connection {a} → {b} could not be drawn (safety net; not expected). |
| INK2026 | W | Low contrast (< 4.5:1): text= on fill=, or box text / canvas text with diagram overrides. |
| INK2027 | E | Position {v} for {id} is out of range: use a number from -100000 to 100000. |
| INK3001 | E | Layout failed: {reason}. |
| INK4001 | E | Export failed: {reason}. |