Skip to content

armgit / cogit

Public Imported from GitHub
0

Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.

feat(shape): draw a Flow from universal kinds with a legend

Erena70cc1d69e48
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 393d0da..fc3b2e9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
+### Added
+- A **Flow** Shape tool: the writer names each box's kind (function, data store, event, condition, …) with the project's own label, and cogit draws the fixed symbol and shape. A legend above the tools shows the kinds a Shape uses, and the Flow/Steps help lists all of them.
+
+### Changed
+- The Shape writer no longer gets the raw Mermaid flowchart and sequence tools; Flow replaces them, and old records still validate and draw. Steps start each line with its kind's symbol.
## [0.25.3] - 2026-10-31
### Added
diff --git a/docs/guide/map.md b/docs/guide/map.md
index 9210624..b580210 100644
--- a/docs/guide/map.md
+++ b/docs/guide/map.md
@@ -87,17 +87,20 @@ A message that landed commits has three layers, in that order:
- **Intent** — the record: the decision, the reason you gave, who decided, and the options
that were rejected. It is read as recorded, never rewritten here.
- **Shape** — a small representation of what the change *does*, in up to three of these:
- - a **Flowchart** of a path through the code, or a **Sequence** diagram when work is handed
- between a hook, a queue, a server or a background job;
+ - a **Flow** of the path through the code: each box is one kind of thing (a function, a
+ store, a hook, an outside system) with its fixed symbol, and the arrows are the work
+ handed between them;
- a **Before / After** table for a fix or any change you can see, and an **Interface**
table for a command, flag, exported function, config key or schema field that changed;
- an **Example**, one concrete run with real values (every new command gets one);
- - **Steps**, numbered plain-language steps naming the functions and files.
-
- The recorder writes it, not you, and a tiny change or a pure refactor gets none. The
- diagrams are drawn when the map is opened with `cogit open`; a map opened from the file
- shows their source. `cogit shape --commit <sha> --dry-run` prints the Shape a commit would
- get without saving it.
+ - **Steps**, numbered plain-language steps naming the functions and files, each starting
+ with its kind's symbol.
+
+ A legend above the tools lists the kinds the Shape uses, symbol and name. The recorder
+ writes it, not you, and a tiny change or a pure refactor gets none. The diagrams are drawn
+ when the map is opened with `cogit open`; a map opened from the file shows their source.
+ `cogit shape --commit <sha> --dry-run` prints the Shape a commit would get without saving
+ it.
- **Code** — the message's commits and their diffs, the same patches the panel opens.
The message details show a short preview and an **Open** button. Open shows the three layers
diff --git a/docs/schema/session-input.json b/docs/schema/session-input.json
index 4cb2429..a804181 100644
--- a/docs/schema/session-input.json
+++ b/docs/schema/session-input.json
@@ -267,7 +267,8 @@
"table",
"sequence",
"interface",
- "example"
+ "example",
+ "flow"
]
},
"text": {
diff --git a/packages/cli/skills/record/SKILL.md b/packages/cli/skills/record/SKILL.md
index d8c04ec..1eccbcc 100644
--- a/packages/cli/skills/record/SKILL.md
+++ b/packages/cli/skills/record/SKILL.md
@@ -85,15 +85,20 @@ between its Intent (the decision and reason above) and its Code (the diff). Add
message's node, with the node's commit hashes:
```json
-"shape": { "tools": [{ "kind": "pseudo", "text": "1. ...\n2. ..." }], "commits": ["abc1234"] }
+"shape": { "tools": [{ "kind": "pseudo", "text": "1. ⚡ ...\n2. ƒ ..." }], "commits": ["abc1234"] }
```
Tools (at most three, the ones that say the most; never two that tell the same thing):
-- `mermaid`: a Mermaid `flowchart TD` (or `LR`) of a path through code, at most 10 nodes.
- Quote labels that hold spaces or punctuation.
-- `sequence`: a Mermaid `sequenceDiagram` when work is handed between actors over time (a hook
- starting a job, a client and a server, a queue drained later), at most 6 participants.
+- `flow`: a path through code as JSON. Every node has a `kind` from the table below and a
+ `label` in the project's own words; at most 12 nodes and 16 edges; ids are short lowercase
+ words (`a`, `hook`), unique, and every edge names two of them. Set `ordered: true` when the
+ edges are steps over time and work is handed between parts (the map numbers them 1, 2, 3…).
+
+ ```json
+ {"kind": "flow", "text": "{\"nodes\":[{\"id\":\"a\",\"kind\":\"event\",\"label\":\"after a commit\"}],\"edges\":[{\"from\":\"a\",\"to\":\"b\",\"label\":\"no\"}],\"ordered\":false}"}
+ ```
+
- `table`: Before / After, one `case | before | after` line per case (at most 8), for a
change someone can see: a fix, a new default, a rule that now says yes or no.
- `interface`: one `item | before | after` line per command, flag, exported function, config
@@ -101,18 +106,35 @@ Tools (at most three, the ones that say the most; never two that tell the same t
`—` for nothing.
- `example`: one concrete case with real values, each result on its own line after `→`. A new
or changed command or flag always gets one that runs it.
-- `pseudo`: numbered plain-language steps of the new logic, naming the functions and files.
-
-Write names the same way in every tool: a role in plain words (`Git`, `cogit`, `Record`), a
-file with its extension (`session.ts`), a function with `()`, a field with its owner
-(`node.commits`), a command after `$`, printed text in quotes. In a diagram, name actors and
-boxes by role with the code name in parentheses (`Queue (shape-queue.ts)`) and label arrows
-with plain verbs. Tables have no header row. Order the tools diagram, tables, example, steps.
+- `pseudo`: numbered plain-language steps of the new logic, each starting with the symbol of
+ its kind after its number (`1. ⚡ After a commit, …`), naming the functions and files.
+
+Kinds (one per Flow node, and the symbol a step starts with; the map draws the symbol, you
+never draw it):
+
+| id | symbol | name | means |
+|---|---|---|---|
+| fn | ƒ | Function | a function or method |
+| var | x | Variable | a variable, field or setting |
+| cond | ◇ | Condition | a question the code asks; its arrows are the answers |
+| loop | ↻ | Loop | repeats for each item |
+| event | ⚡ | Event | something that starts the work: a hook, a click, a timer |
+| store | ▤ | Data store | a file, database, queue or cache that keeps data |
+| type | ▭ | Type | a type, class or schema |
+| ext | ◎ | External system | another program or service: git, a browser, an API, an AI model |
+| person | ☺ | Person | someone using it |
+| async | ⇢ | Background job | work started without waiting for it |
+| out | ↩ | Output | what is returned or shown |
+| error | ✕ | Error | an error or a refusal |
+
+A Flow node's label names the thing in the project's own words (`shape-queue.ts`,
+`enqueueShape()`), never a role word — the symbol already says what kind it is. Tables have
+no header row. Order the tools diagram, tables, example, steps.
`{ "tools": [] }` means nothing worth showing: give it for a change nobody would notice from
outside (a refactor, a rename). Skip messages whose commits are only release/version bumps,
lockfiles or CHANGELOG, or change fewer than 5 lines in total. Write it in the conversation's
-language; the CLI validates each output and keeps an invalid diagram as text.
+language; the CLI validates each output and keeps an invalid output as text.
## Branch summary
diff --git a/packages/cli/src/schema/session.ts b/packages/cli/src/schema/session.ts
index 315ee2e..36a8089 100644
--- a/packages/cli/src/schema/session.ts
+++ b/packages/cli/src/schema/session.ts
@@ -34,13 +34,22 @@ export const MESSAGE_ID = /^m[1-9][0-9]*$/;
* How a Shape shows what a change does (Story 13.6). The registry in `shape.ts`
* says when each tool fits and validates its output.
*/
-export const ShapeKind = z.enum(["pseudo", "mermaid", "table", "sequence", "interface", "example"]);
+export const ShapeKind = z.enum([
+ "pseudo",
+ "mermaid",
+ "table",
+ "sequence",
+ "interface",
+ "example",
+ "flow",
+]);
export type ShapeKind = z.infer<typeof ShapeKind>;
/**
- * One tool's answer: plain-language pseudo-code, or Mermaid source. `valid` is
- * set by the CLI, never by a writer: an output the registry refused keeps its
- * text (so nothing is lost) and the map shows it as text instead of drawing it.
+ * One tool's answer: numbered steps, a table, a Flow's JSON, or Mermaid source
+ * (the two diagram tools kept for old records). `valid` is set by the CLI,
+ * never by a writer: an output the registry refused keeps its text (so nothing
+ * is lost) and the map shows it as text instead of drawing it.
*/
export const ShapeTool = z.object({
// Any kind is stored: a tool a newer CLI added must not make this record
diff --git a/packages/cli/src/shape.ts b/packages/cli/src/shape.ts
index 21f2bd7..32d42f3 100644
--- a/packages/cli/src/shape.ts
+++ b/packages/cli/src/shape.ts
@@ -1,5 +1,11 @@
import type { LineageNode, Shape, ShapeInput, ShapeKind, ShapeTool } from "./schema/session.js";
-import { SHAPE_NOTATION, tableRows } from "./view/shape.js";
+import {
+ FLOW_MAX_EDGES,
+ FLOW_MAX_NODES,
+ parseFlow,
+ tableRows,
+ UNIVERSAL_KINDS,
+} from "./view/shape.js";
/**
* The Shape catalogue (Story 13.6): a Shape sits between a message's Intent
@@ -21,6 +27,11 @@ export interface ShapeToolSpec {
when: string;
/** The JSON shape of one answer, as the prompt shows it. */
output: string;
+ /**
+ * False for tools kept only so old records still validate and draw: the
+ * writer is no longer offered them in the catalogue.
+ */
+ offered?: boolean;
/** True when the output can be shown as designed. */
validate(text: string): boolean;
}
@@ -71,6 +82,21 @@ export function mermaidNodeCount(text: string): number {
export const SEQUENCE_MAX_ACTORS = 6;
export const SHAPE_TOOLS: readonly ShapeToolSpec[] = [
+ {
+ kind: "flow",
+ name: "Flow",
+ when:
+ "The change is a path through code across files: the functions, files, stores, hooks and " +
+ "outside calls it moves between. Every node gets a kind from the list below and a label " +
+ "in the project's own words; the map draws the symbol, never you. Set `ordered` true " +
+ "when the edges are steps over time and work is handed between parts. Node ids are short " +
+ `lowercase words; at most ${FLOW_MAX_NODES} nodes and ${FLOW_MAX_EDGES} edges.`,
+ output:
+ '{"kind": "flow", "text": "{\\"nodes\\":[{\\"id\\":\\"a\\",\\"kind\\":\\"event\\",\\"label\\":\\"after a commit\\"}],\\"edges\\":[{\\"from\\":\\"a\\",\\"to\\":\\"b\\",\\"label\\":\\"no\\"}],\\"ordered\\":false}"}',
+ validate(text) {
+ return parseFlow(text) !== undefined;
+ },
+ },
{
kind: "pseudo",
name: "Steps",
@@ -103,6 +129,8 @@ export const SHAPE_TOOLS: readonly ShapeToolSpec[] = [
},
{
kind: "mermaid",
+ // Kept so old records still validate and draw; the writer gets Flow instead.
+ offered: false,
name: "Flowchart",
when:
`The change is a flow between files or functions (a request path, a queue, a state ` +
@@ -119,6 +147,8 @@ export const SHAPE_TOOLS: readonly ShapeToolSpec[] = [
},
{
kind: "sequence",
+ // Kept so old records still validate and draw; the writer gets Flow instead.
+ offered: false,
name: "Sequence",
when:
"The change is a flow over time between actors that hand work to each other: a hook " +
@@ -271,11 +301,11 @@ export function shapeWanted(commits: readonly ShapeCommitInfo[]): {
/** How much of the diff the side writer reads; enough to name the path, not the file. */
export const SHAPE_DIFF_LIMIT = 7000;
-/** The tool catalogue as the prompt lists it. */
+/** The tool catalogue as the prompt lists it; retired tools are left out. */
export function toolCatalogue(): string {
- return SHAPE_TOOLS.map(
- (tool) => `- "${tool.kind}" (${tool.name}): ${tool.when}\n Output: ${tool.output}`,
- ).join("\n");
+ return SHAPE_TOOLS.filter((tool) => tool.offered !== false)
+ .map((tool) => `- "${tool.kind}" (${tool.name}): ${tool.when}\n Output: ${tool.output}`)
+ .join("\n");
}
/** The record's Intent for one message, as plain lines. */
@@ -316,20 +346,20 @@ export function shapePrompt(opts: {
"Tools:",
toolCatalogue(),
"",
+ "Kinds (one per Flow node; the map draws the symbol, you never draw it):",
+ ...UNIVERSAL_KINDS.map((kind) => `- ${kind.id} (${kind.symbol} ${kind.name}): ${kind.means}`),
+ "",
"Rules:",
"- Give at most three tools, the ones that say the most about this change; never two that tell the same thing.",
- "- A diagram for a change across two or more files: a sequence diagram when work is handed between actors over time, a flowchart for a path through code.",
+ "- A Flow for a change across two or more files: every node gets a kind from the list above and a label in the project's own words. Set `ordered` true when the edges are steps over time and work is handed between parts.",
"- A Before / After table when behaviour someone can see changes (a fix, a new default, a rule).",
"- A change nobody would notice from outside (a refactor, a rename, moved code, a wording tweak in a prompt or comment) takes no tool at all: return none.",
"- An Interface table only for what is reached from outside the changed module: a CLI command or flag, an exported function or type other packages use, a config key, a stored schema field, an HTTP route. Never an internal helper, a component prop or a view-model field.",
"- A new or changed command or flag always gets an example that runs it and shows what it prints, with real values from the diff; a file path in it must be one the diff touches, never an invented one. Otherwise an example only when one concrete case shows the change faster than steps.",
- "- Steps only when the logic itself is the point and no other tool says it.",
- `- Write names the same way in every tool: ${SHAPE_NOTATION.map((entry) => `${entry.sample} = ${entry.means}`).join("; ")}.`,
- "- In a diagram, name actors and boxes by their role in plain words; put the code name after it in parentheses, written as above: Queue (shape-queue.ts). Arrow labels are plain verbs: puts it in the queue (enqueueShape()).",
+ "- Steps only when the logic itself is the point and no other tool says it; each step starts with the symbol of its kind after its number, e.g. `1. ⚡ After a commit, …`.",
"- Tables have no header row (the map adds one); every line is one row of three cells split by |.",
"- Order the tools: diagram, tables, example, steps. Return none when the change is a small fix not worth a picture.",
`- Name real functions, files and modules from the diff. Never invent a path.`,
- `- A flowchart starts with "flowchart TD" (or LR) and stays under ${MERMAID_MAX_NODES} nodes; quote labels that hold spaces or punctuation. A sequence diagram starts with "sequenceDiagram", names at most ${SEQUENCE_MAX_ACTORS} participants with short ids, and puts no semicolons or # in message text.`,
"- Describe what the code does now, not the steps of the conversation.",
`- Write the text in ${writing}; JSON keys stay English. Never write secrets, credentials or personal data.`,
"",
diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.ts
index 9bafd34..00f2d8d 100644
--- a/packages/cli/src/view/model.ts
+++ b/packages/cli/src/view/model.ts
@@ -77,7 +77,7 @@ export interface ViewChange {
/** What a message's change does, between Intent and Code (Story 13.6). */
export interface ViewShapeTool {
- /** `pseudo`, `mermaid`, `table`, or a kind a newer CLI wrote (shown as text). */
+ /** `pseudo`, `flow`, `table`, or a kind a newer CLI wrote (shown as text). */
kind: string;
text: string;
/** False when the registry refused the output; the map shows it as text. */
diff --git a/packages/cli/src/view/shape.ts b/packages/cli/src/view/shape.ts
index ac0ad73..dbbfad0 100644
--- a/packages/cli/src/view/shape.ts
+++ b/packages/cli/src/view/shape.ts
@@ -55,38 +55,210 @@ export function tableRows(text: string): [string, string, string][] | undefined
}
/**
- * How names are written in every Shape tool, so a reader tells a role from a
- * file, a function, a field, a command and the text it prints at a glance.
- * The writer's prompt and the map's "?" read the same list.
+ * One kind every codebase has, with a fixed symbol cogit draws (Story 13.7).
+ * The writer names the kind and the map draws its symbol, so a box reads the
+ * same in any project. Shared by the writer's prompt and the map's legend.
*/
-export const SHAPE_NOTATION: readonly { sample: string; means: string }[] = [
- { sample: "Git, cogit, Record", means: "a role: a program, a person or a store that acts" },
- { sample: "session.ts", means: "a file, with its extension" },
- { sample: "drainShapeQueue()", means: "a function, with ()" },
- { sample: "node.commits", means: "a field, variable or setting, with its owner and a dot" },
- { sample: "$ cogit shape", means: "a command you type, after $" },
- { sample: '"queued ba654e8"', means: "text the program shows, in quotes" },
+export interface UniversalKind {
+ id: string;
+ symbol: string;
+ name: string;
+ means: string;
+}
+
+export const UNIVERSAL_KINDS: readonly UniversalKind[] = [
+ { id: "fn", symbol: "ƒ", name: "Function", means: "a function or method" },
+ { id: "var", symbol: "x", name: "Variable", means: "a variable, field or setting" },
+ {
+ id: "cond",
+ symbol: "◇",
+ name: "Condition",
+ means: "a question the code asks; its arrows are the answers",
+ },
+ { id: "loop", symbol: "↻", name: "Loop", means: "repeats for each item" },
+ {
+ id: "event",
+ symbol: "⚡",
+ name: "Event",
+ means: "something that starts the work: a hook, a click, a timer",
+ },
+ {
+ id: "store",
+ symbol: "▤",
+ name: "Data store",
+ means: "a file, database, queue or cache that keeps data",
+ },
+ { id: "type", symbol: "▭", name: "Type", means: "a type, class or schema" },
+ {
+ id: "ext",
+ symbol: "◎",
+ name: "External system",
+ means: "another program or service: git, a browser, an API, an AI model",
+ },
+ { id: "person", symbol: "☺", name: "Person", means: "someone using it" },
+ {
+ id: "async",
+ symbol: "⇢",
+ name: "Background job",
+ means: "work started without waiting for it",
+ },
+ { id: "out", symbol: "↩", name: "Output", means: "what is returned or shown" },
+ { id: "error", symbol: "✕", name: "Error", means: "an error or a refusal" },
];
+/** A Flow's node and edge, as the writer's JSON holds them. */
+export interface FlowNode {
+ id: string;
+ kind: string;
+ label: string;
+}
+
+export interface FlowEdge {
+ from: string;
+ to: string;
+ label?: string;
+}
+
+export interface FlowShape {
+ nodes: FlowNode[];
+ edges: FlowEdge[];
+ ordered: boolean;
+}
+
+/** A node id: a lowercase letter, then up to 15 letters, digits or underscores. */
+const FLOW_ID = /^[a-z][a-z0-9_]{0,15}$/;
+
+/** Nodes and edges a Flow may carry. */
+export const FLOW_MAX_NODES = 12;
+export const FLOW_MAX_EDGES = 16;
+
+const FLOW_KIND_IDS = new Set(UNIVERSAL_KINDS.map((kind) => kind.id));
+
+/**
+ * Parses a Flow's JSON and checks every rule (Story 13.7); undefined for bad
+ * JSON or any violation. The validator, the renderer and the legend all read
+ * the same rules here, so a Flow the map draws is one the CLI accepted.
+ */
+export function parseFlow(text: string): FlowShape | undefined {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ return undefined;
+ }
+ if (typeof parsed !== "object" || parsed === null) return undefined;
+ const { nodes, edges, ordered } = parsed as {
+ nodes?: unknown;
+ edges?: unknown;
+ ordered?: unknown;
+ };
+ if (!Array.isArray(nodes) || nodes.length === 0 || nodes.length > FLOW_MAX_NODES)
+ return undefined;
+ if (!Array.isArray(edges) || edges.length > FLOW_MAX_EDGES) return undefined;
+ if (ordered !== undefined && typeof ordered !== "boolean") return undefined;
+
+ const ids = new Set<string>();
+ const parsedNodes: FlowNode[] = [];
+ for (const node of nodes) {
+ if (typeof node !== "object" || node === null) return undefined;
+ const { id, kind, label } = node as { id?: unknown; kind?: unknown; label?: unknown };
+ if (typeof id !== "string" || !FLOW_ID.test(id) || ids.has(id)) return undefined;
+ ids.add(id);
+ if (typeof kind !== "string" || !FLOW_KIND_IDS.has(kind)) return undefined;
+ if (typeof label !== "string" || label.length < 1 || label.length > 60) return undefined;
+ parsedNodes.push({ id, kind, label });
+ }
+
+ const parsedEdges: FlowEdge[] = [];
+ for (const edge of edges) {
+ if (typeof edge !== "object" || edge === null) return undefined;
+ const { from, to, label } = edge as { from?: unknown; to?: unknown; label?: unknown };
+ if (typeof from !== "string" || !ids.has(from)) return undefined;
+ if (typeof to !== "string" || !ids.has(to)) return undefined;
+ if (label !== undefined && (typeof label !== "string" || label.length > 40)) return undefined;
+ parsedEdges.push({ from, to, ...(label === undefined ? {} : { label }) });
+ }
+ return { nodes: parsedNodes, edges: parsedEdges, ordered: ordered === true };
+}
+
+/** The Mermaid open/close per Flow kind; the rest draw as a plain rectangle. */
+const FLOW_NODE_SHAPE: Readonly<Record<string, readonly [string, string]>> = {
+ cond: ["{", "}"],
+ store: ["[(", ")]"],
+ event: [">", "]"],
+ ext: ["[[", "]]"],
+ person: ["([", ")]"],
+ error: ["[/", "/]"],
+};
+
+/** A label as Mermaid reads it: no double quotes, # or ; left to break the parse. */
+function flowLabel(text: string): string {
+ return text.replace(/"/g, "'").replace(/#/g, "").replace(/;/g, "");
+}
+
+/**
+ * The deterministic `flowchart TD` a Flow draws (Story 13.7): one node per box
+ * with its kind's symbol and shape, one edge per arrow; `ordered` numbers the
+ * edge labels 1, 2, 3… in the order given. Undefined for input the rules
+ * refuse. The same input is always byte-identical.
+ */
+export function flowToMermaid(text: string): string | undefined {
+ const flow = parseFlow(text);
+ if (flow === undefined) return undefined;
+ const symbol = (kind: string) => UNIVERSAL_KINDS.find((entry) => entry.id === kind)?.symbol ?? "";
+ const lines = ["flowchart TD"];
+ for (const node of flow.nodes) {
+ const [open, close] = FLOW_NODE_SHAPE[node.kind] ?? ["[", "]"];
+ lines.push(` ${node.id}${open}"${symbol(node.kind)} ${flowLabel(node.label)}"${close}`);
+ }
+ flow.edges.forEach((edge, index) => {
+ // Ordered edges keep their words after the step number: "2. puts it in the queue".
+ const label = flow.ordered ? `${index + 1}. ${edge.label ?? ""}`.trim() : edge.label;
+ if (label !== undefined && label !== "")
+ lines.push(` ${edge.from} -->|"${flowLabel(label)}"| ${edge.to}`);
+ else lines.push(` ${edge.from} --> ${edge.to}`);
+ });
+ return lines.join("\n");
+}
+
+/**
+ * The kinds a Shape actually uses, in `UNIVERSAL_KINDS` order: a Flow's node
+ * kinds, plus the symbol at the start of each Steps line. The map's legend
+ * shows only these.
+ */
+export function shapeKindsUsed(tools: readonly { kind: string; text: string }[]): UniversalKind[] {
+ const used = new Set<string>();
+ for (const tool of tools) {
+ if (tool.kind === "flow") {
+ const flow = parseFlow(tool.text);
+ for (const node of flow?.nodes ?? []) used.add(node.kind);
+ } else if (tool.kind === "pseudo") {
+ for (const line of tool.text.split("\n")) {
+ const symbol = /^\s*\d+[.)]\s+(\S)/.exec(line)?.[1];
+ const kind =
+ symbol === undefined
+ ? undefined
+ : UNIVERSAL_KINDS.find((entry) => entry.symbol === symbol);
+ if (kind !== undefined) used.add(kind.id);
+ }
+ }
+ }
+ return UNIVERSAL_KINDS.filter((kind) => used.has(kind.id));
+}
+
/** What each tool shows and how to read it, for the "?" beside its caption. */
export const SHAPE_READING: Readonly<Record<string, string>> = {
mermaid:
"Follow the arrows from the top. A box is a step; a diamond is a question, and the arrows leaving it are its answers.",
sequence:
"Each column is an actor, named at the top. Read from top to bottom: each arrow is one actor handing work to another at that moment, and a dashed arrow is a reply.",
+ flow: "Follow the arrows from the top. Each box's symbol says what kind of thing it is — the legend above lists them; a ◇ is a question, and the arrows leaving it are its answers.",
table:
"One row per case: what happens, how it behaved before this change, and how it behaves now.",
interface:
"One row per thing other code or people use: a command, flag, function, setting or stored field. — means it did not exist before, or is gone now.",
example:
"One concrete run. The first line is what you do or what happens; each line after → is what you would see.",
- pseudo: "What the code does now, in order, one step per line.",
+ pseudo:
+ "What the code does now, in order, one step per line; each step starts with the symbol of what it is.",
};
-
-/** Tools whose text names roles, files and functions, so their "?" shows the notation. */
-export const NOTATION_KINDS: ReadonlySet<string> = new Set([
- "mermaid",
- "sequence",
- "example",
- "pseudo",
-]);
diff --git a/packages/cli/test/schema.test.ts b/packages/cli/test/schema.test.ts
index 2614698..9f4196f 100644
--- a/packages/cli/test/schema.test.ts
+++ b/packages/cli/test/schema.test.ts
@@ -48,6 +48,20 @@ describe("Session schema", () => {
expect(sent.success).toBe(false);
});
+ it("accepts a Flow tool from a writer", () => {
+ const shape = {
+ tools: [
+ { kind: "flow", text: '{"nodes":[{"id":"a","kind":"event","label":"x"}],"edges":[]}' },
+ ],
+ commits: [],
+ };
+ const sent = SessionInput.safeParse({
+ sessionId: "abc",
+ nodes: [{ id: "m1", kind: "message", title: "t", shape }],
+ });
+ expect(sent.success).toBe(true);
+ });
+
it("rejects ids that are not safe slugs", () => {
for (const sessionId of ["../etc", "a/b", "", ".hidden"]) {
expect(SessionInput.safeParse({ sessionId }).success).toBe(false);
diff --git a/packages/cli/test/shape.test.ts b/packages/cli/test/shape.test.ts
index ed1e0fc..285fe13 100644
--- a/packages/cli/test/shape.test.ts
+++ b/packages/cli/test/shape.test.ts
@@ -18,7 +18,7 @@ import {
validateShapeTools,
} from "../src/shape.js";
import { loadSession } from "../src/store/stores.js";
-import { shapePreview, tableRows } from "../src/view/shape.js";
+import { flowToMermaid, shapeKindsUsed, shapePreview, tableRows } from "../src/view/shape.js";
import { envFor, fakeIo, T0, tempDir } from "./helpers.js";
const PSEUDO = "1. Read the record\n2. Merge the node";
@@ -151,7 +151,7 @@ describe("the Shape tool catalogue", () => {
]);
});
- it("asks for the diagram and the steps across files, and a table for a visible change", () => {
+ it("asks for a Flow, steps and a table, and lists the kinds", () => {
const prompt = shapePrompt({
node: message(),
commits: [],
@@ -159,28 +159,33 @@ describe("the Shape tool catalogue", () => {
diffTruncated: false,
language: "auto",
});
- expect(prompt).toContain("A diagram for a change across two or more files");
+ expect(prompt).toContain("A Flow for a change across two or more files");
expect(prompt).toContain("A Before / After table when behaviour someone can see changes");
expect(prompt).toContain("A new or changed command or flag always gets an example");
expect(prompt).toContain("Never an internal helper");
expect(prompt).toContain("takes no tool at all");
expect(prompt).toContain("never an invented one");
- expect(prompt).toContain("drainShapeQueue() = a function, with ()");
- expect(prompt).toContain("Arrow labels are plain verbs");
+ expect(prompt).toContain("fn (ƒ Function): a function or method");
+ expect(prompt).toContain("event (⚡ Event): something that starts the work");
+ expect(prompt).toContain("each step starts with the symbol of its kind after its number");
expect(prompt).toContain('"table" (Before / After)');
- expect(prompt).toContain('"sequence" (Sequence)');
+ expect(prompt).toContain('"flow" (Flow)');
expect(prompt).toContain('"interface" (Interface)');
expect(prompt).toContain('"example" (Example)');
- expect(prompt).toContain("a sequence diagram when work is handed between actors");
+ // The retired Mermaid tools are no longer offered to the writer.
+ expect(prompt).not.toContain("mermaid");
+ expect(prompt).not.toContain("sequence");
});
- it("names both tools and says when to use each", () => {
+ it("names the offered tools and says when to use each", () => {
const catalogue = toolCatalogue();
+ expect(catalogue).toContain('"flow"');
expect(catalogue).toContain('"pseudo"');
- expect(catalogue).toContain('"mermaid"');
- expect(catalogue).toContain("10 nodes");
+ expect(catalogue).toContain('{"kind": "flow"');
expect(catalogue).toContain('{"kind": "pseudo"');
- expect(catalogue).toContain('{"kind": "mermaid"');
+ // The retired Mermaid tools stay in the registry but out of the catalogue.
+ expect(catalogue).not.toContain('"mermaid"');
+ expect(catalogue).not.toContain('"sequence"');
});
it("stamps who wrote it, when, and each answer's validity", () => {
@@ -204,6 +209,113 @@ describe("the Shape tool catalogue", () => {
});
});
+describe("the Flow tool", () => {
+ const flow = (nodes: unknown, edges: unknown, ordered: unknown = false) =>
+ JSON.stringify({ nodes, edges, ordered });
+
+ it("accepts a valid Flow and refuses bad JSON, an unknown kind, a duplicate id, a missing endpoint and too many nodes", () => {
+ const valid = flow(
+ [
+ { id: "a", kind: "event", label: "after a commit" },
+ { id: "b", kind: "fn", label: "write the shape" },
+ ],
+ [{ from: "a", to: "b", label: "yes" }],
+ );
+ expect(validateShapeTools([{ kind: "flow", text: valid }])[0]?.valid).toBe(true);
+
+ for (const bad of [
+ "not json",
+ flow([{ id: "a", kind: "wizard", label: "x" }], []),
+ flow(
+ [
+ { id: "a", kind: "event", label: "x" },
+ { id: "a", kind: "fn", label: "y" },
+ ],
+ [{ from: "a", to: "a" }],
+ ),
+ flow([{ id: "a", kind: "event", label: "x" }], [{ from: "a", to: "c" }]),
+ flow(
+ Array.from({ length: 13 }, (_, i) => ({ id: `n${i}`, kind: "fn", label: "x" })),
+ [],
+ ),
+ flow([{ id: "a", kind: "event", label: "x" }], [], "yes"),
+ ]) {
+ expect(validateShapeTools([{ kind: "flow", text: bad }])[0]?.valid).toBe(false);
+ }
+ });
+
+ it("draws a Flow deterministically, quoting labels and shaping each kind", () => {
+ const text = JSON.stringify({
+ nodes: [
+ { id: "a", kind: "event", label: "after a commit" },
+ { id: "b", kind: "cond", label: 'was it "recorded"?' },
+ { id: "c", kind: "store", label: "shape queue" },
+ ],
+ edges: [
+ { from: "a", to: "b" },
+ { from: "b", to: "c", label: "no" },
+ ],
+ ordered: false,
+ });
+ expect(flowToMermaid(text)).toBe(
+ [
+ "flowchart TD",
+ ' a>"⚡ after a commit"]',
+ ` b{"◇ was it 'recorded'?"}`,
+ ' c[("▤ shape queue")]',
+ " a --> b",
+ ' b -->|"no"| c',
+ ].join("\n"),
+ );
+ });
+
+ it("numbers the edge labels when ordered, and refuses invalid input", () => {
+ const ordered = JSON.stringify({
+ nodes: [
+ { id: "a", kind: "event", label: "after a commit" },
+ { id: "b", kind: "fn", label: "enqueue" },
+ { id: "c", kind: "store", label: "queue" },
+ ],
+ edges: [
+ { from: "a", to: "b" },
+ { from: "b", to: "c", label: "puts it in" },
+ ],
+ ordered: true,
+ });
+ expect(flowToMermaid(ordered)).toBe(
+ [
+ "flowchart TD",
+ ' a>"⚡ after a commit"]',
+ ' b["ƒ enqueue"]',
+ ' c[("▤ queue")]',
+ ' a -->|"1."| b',
+ ' b -->|"2. puts it in"| c',
+ ].join("\n"),
+ );
+ expect(flowToMermaid("not json")).toBeUndefined();
+ expect(flowToMermaid(JSON.stringify({ nodes: [], edges: [] }))).toBeUndefined();
+ });
+
+ it("derives the kinds a Flow and its Steps use, in the universal order", () => {
+ const tools = [
+ {
+ kind: "flow",
+ text: JSON.stringify({
+ nodes: [
+ { id: "a", kind: "event", label: "after a commit" },
+ { id: "b", kind: "store", label: "queue" },
+ ],
+ edges: [{ from: "a", to: "b" }],
+ ordered: false,
+ }),
+ },
+ { kind: "pseudo", text: "1. ⚡ After a commit\n2. ƒ enqueue the shape" },
+ ];
+ expect(shapeKindsUsed(tools).map((kind) => kind.id)).toEqual(["fn", "event", "store"]);
+ expect(shapeKindsUsed([])).toEqual([]);
+ });
+});
+
describe("the Shape skip rules", () => {
const base = {
hash: "a".repeat(40),
diff --git a/packages/template/src/ShapeModal.tsx b/packages/template/src/ShapeModal.tsx
index 82650d7..68e99f8 100644
--- a/packages/template/src/ShapeModal.tsx
+++ b/packages/template/src/ShapeModal.tsx
@@ -1,12 +1,13 @@
import { type ReactNode, useEffect, useRef, useState } from "react";
import type { ViewNode } from "../../cli/src/view/model.js";
import {
- NOTATION_KINDS,
- SHAPE_NOTATION,
+ flowToMermaid,
SHAPE_READING,
+ shapeKindsUsed,
shapePreview,
shapeState,
tableRows,
+ UNIVERSAL_KINDS,
} from "../../cli/src/view/shape.js";
import { DiffView } from "./DiffView.js";
import { isLivePage } from "./data.js";
@@ -111,29 +112,34 @@ function IntentLayer({ node }: { node: ShapeNode }) {
const TEXT_CAPTION: Record<string, string> = {
pseudo: "Steps",
example: "Example",
+ flow: "Flow source (not drawn)",
mermaid: "Flowchart source (not drawn)",
sequence: "Sequence source (not drawn)",
table: "Before / After (as written)",
interface: "Interface (as written)",
};
+/** Tools whose "?" lists every kind, so the reader can decode the symbols. */
+const KINDS_CAPTIONS = new Set(["flow", "pseudo"]);
+
/**
- * A tool's caption with a "?" that says how to read it; tools that name roles,
- * files and functions also list how those names are written.
+ * A tool's caption with a "?" that says how to read it; a Flow or Steps also
+ * lists every kind, so the symbols name themselves.
*/
function ToolCaption({ id, kind, label }: { id: string; kind: string; label: string }) {
const reading = SHAPE_READING[kind];
+ const listsKinds = KINDS_CAPTIONS.has(kind);
return (
<figcaption className="shape-caption">
<span>{label}</span>
{reading ? (
<HelpTip id={`shape-${id}`} label={`How to read the ${label}`}>
<span className="shape-reading">{reading}</span>
- {NOTATION_KINDS.has(kind) ? (
- <span className="shape-notation">
- {SHAPE_NOTATION.map((entry) => (
- <span key={entry.sample} className="shape-notation-row">
- <code>{entry.sample}</code> {entry.means}
+ {listsKinds ? (
+ <span className="shape-kinds">
+ {UNIVERSAL_KINDS.map((kind) => (
+ <span key={kind.id} className="shape-kind-row">
+ <code>{kind.symbol}</code> {kind.name} — {kind.means}
</span>
))}
</span>
@@ -144,8 +150,15 @@ function ToolCaption({ id, kind, label }: { id: string; kind: string; label: str
);
}
-/** Tools Mermaid draws. */
-const DIAGRAM_KINDS = new Set(["mermaid", "sequence"]);
+/** Tools Mermaid draws; a Flow is turned into Mermaid source first. */
+const DIAGRAM_KINDS = new Set(["flow", "mermaid", "sequence"]);
+
+/** A diagram tool's caption, distinct from the plain-text fallback caption. */
+function diagramLabel(kind: string): string {
+ if (kind === "sequence") return "Sequence";
+ if (kind === "flow") return "Flow";
+ return "Flowchart";
+}
/** The header of each table tool; the writer sends only the rows. */
const TABLE_COLUMNS: Record<string, readonly [string, string, string]> = {
@@ -205,19 +218,28 @@ function ShapeLayer({
if (state === "empty") {
return <p className="muted">Nothing to show: the change was too small to draw.</p>;
}
+ const tools = node.shape?.tools ?? [];
+ const kinds = shapeKindsUsed(tools);
return (
<div className="shape-tools">
- {node.shape?.tools.map((tool, index) => {
+ {kinds.length > 0 ? (
+ <div className="shape-legend" aria-label="Kinds in this Shape">
+ {kinds.map((kind) => (
+ <span key={kind.id} className="shape-kind">
+ <span className="shape-kind-symbol">{kind.symbol}</span>
+ {kind.name}
+ </span>
+ ))}
+ </div>
+ ) : null}
+ {tools.map((tool, index) => {
const key = `${tool.kind}-${index}`;
- if (DIAGRAM_KINDS.has(tool.kind) && tool.valid !== false)
+ const source = tool.kind === "flow" ? flowToMermaid(tool.text) : tool.text;
+ if (DIAGRAM_KINDS.has(tool.kind) && tool.valid !== false && source !== undefined)
return (
<figure key={key} className="shape-figure">
- {renderMermaid(tool.text)}
- <ToolCaption
- id={key}
- kind={tool.kind}
- label={tool.kind === "sequence" ? "Sequence" : "Flowchart"}
- />
+ {renderMermaid(source)}
+ <ToolCaption id={key} kind={tool.kind} label={diagramLabel(tool.kind)} />
</figure>
);
const columns = TABLE_COLUMNS[tool.kind];
@@ -396,14 +418,20 @@ export function ShapeSection({
const diagram = node.shape?.tools.find(
(tool) => DIAGRAM_KINDS.has(tool.kind) && tool.valid !== false,
);
+ const diagramSource =
+ diagram === undefined
+ ? undefined
+ : diagram.kind === "flow"
+ ? flowToMermaid(diagram.text)
+ : diagram.text;
return (
<section className="shape-section">
<h3>Intent, Shape and Code</h3>
{state === "ready" ? (
preview ? (
<pre className="shape-preview">{preview}</pre>
- ) : diagram ? (
- <MermaidDiagram source={diagram.text} className="shape-preview-diagram" />
+ ) : diagramSource !== undefined ? (
+ <MermaidDiagram source={diagramSource} className="shape-preview-diagram" />
) : null
) : state === "off" ? (
<p className="muted">Shapes are off.</p>
diff --git a/packages/template/src/styles.css b/packages/template/src/styles.css
index e5eea30..062b484 100644
--- a/packages/template/src/styles.css
+++ b/packages/template/src/styles.css
@@ -2650,6 +2650,32 @@ time {
padding-left: 18px;
}
+/* The kinds a Shape uses, above its tools (Story 13.7). */
+.shape-legend {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin: 0 0 14px;
+ padding-bottom: 10px;
+ border-bottom: 1px solid var(--line);
+ color: var(--muted);
+ font-size: 12px;
+}
+
+.shape-kind {
+ display: inline-flex;
+ align-items: baseline;
+ gap: 5px;
+ padding: 2px 9px;
+ background: var(--chip-bg);
+ border: 1px solid var(--chip-line);
+ border-radius: 999px;
+}
+
+.shape-kind-symbol {
+ font-size: 13px;
+}
+
.shape-table {
width: 100%;
border-collapse: collapse;
@@ -2686,18 +2712,18 @@ time {
}
.shape-reading,
-.shape-notation,
-.shape-notation-row {
+.shape-kinds,
+.shape-kind-row {
display: block;
}
-.shape-notation {
+.shape-kinds {
margin-top: 8px;
padding-top: 8px;
border-top: 1px solid var(--line);
}
-.shape-notation-row + .shape-notation-row {
+.shape-kind-row + .shape-kind-row {
margin-top: 3px;
}
@@ -2706,7 +2732,7 @@ time {
line-height: 1.5;
}
-.shape-notation code {
+.shape-kinds code {
font-size: 11px;
}
diff --git a/packages/template/test/shape-modal.test.tsx b/packages/template/test/shape-modal.test.tsx
index adc2ab4..2b18ecf 100644
--- a/packages/template/test/shape-modal.test.tsx
+++ b/packages/template/test/shape-modal.test.tsx
@@ -85,6 +85,34 @@ describe("Intent, Shape and Code", () => {
expect(invalid).toContain("Flowchart source (not drawn)");
});
+ it("draws a Flow with a legend of the kinds it uses, and still draws an old flowchart", () => {
+ const flowText = JSON.stringify({
+ nodes: [
+ { id: "a", kind: "event", label: "after a commit" },
+ { id: "b", kind: "store", label: "queue" },
+ ],
+ edges: [{ from: "a", to: "b" }],
+ ordered: false,
+ });
+ const html = render("shape", {
+ shape: {
+ tools: [
+ { kind: "flow", text: flowText, valid: true },
+ { kind: "mermaid", text: "flowchart TD\nA --> B", valid: true },
+ ],
+ commits: [],
+ },
+ });
+ expect(html).toContain("<span>Flow</span>");
+ expect(html).toContain("<span>Flowchart</span>");
+ expect(html).toContain("diagram");
+ // The legend names only the kinds the Shape uses: event and store.
+ expect(html).toContain('class="shape-legend"');
+ expect(html).toContain("⚡");
+ expect(html).toContain("Data store");
+ expect(html).not.toContain("Function");
+ });
+
it("lays out a Before / After table and shows an unknown tool as text", () => {
const html = render("shape", {
shape: {