Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.
JavaScript ai-codingclaudeclaude-codeclaude-code-pluginclicoding-agentsdeveloper-toolsgitllmtypescript
feat(shape): add a Before / After table and draw diagrams across files
Eren0d7352cf9a77
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5086df8..b3f3abb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,7 +5,14 @@ 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 third Shape tool, **Before / After**: a table with one row per case, saying how the change behaved before and how it behaves now. The side model adds it for a fix or any change you can see; a pure refactor gets none.++### Changed+- A change that touches two or more files gets a diagram of its path as well as the steps, instead of the writer usually stopping at the steps. A record holding a Shape tool this CLI does not know still loads, and the map shows that tool as text.+### Fixed+- A Mermaid diagram with long labels is drawn again: the node limit counted every word in a label as a node, so most real diagrams were shown as source.- A long diff on the Code tab of **Open** scrolls inside the window instead of running past its bottom edge.## [0.25.0] - 2026-10-31diff --git a/docs/schema/session-input.json b/docs/schema/session-input.jsonindex 9a9d1ab..b4b4e86 100644--- a/docs/schema/session-input.json+++ b/docs/schema/session-input.json@@ -263,7 +263,8 @@"type": "string","enum": ["pseudo",- "mermaid"+ "mermaid",+ "table"]},"text": {diff --git a/docs/schema/session.json b/docs/schema/session.jsonindex f421c62..10b8a0f 100644--- a/docs/schema/session.json+++ b/docs/schema/session.json@@ -303,10 +303,8 @@"properties": {"kind": {"type": "string",- "enum": [- "pseudo",- "mermaid"- ]+ "minLength": 1,+ "maxLength": 40},"text": {"type": "string",diff --git a/packages/cli/skills/record/SKILL.md b/packages/cli/skills/record/SKILL.mdindex bc39975..fa5a9f1 100644--- a/packages/cli/skills/record/SKILL.md+++ b/packages/cli/skills/record/SKILL.md@@ -88,13 +88,17 @@ message's node, with the node's commit hashes:"shape": { "tools": [{ "kind": "pseudo", "text": "1. ...\n2. ..." }], "commits": ["abc1234"] }```-Two tools:+Three tools:-- `pseudo`: numbered plain-language steps of the new logic, naming the functions and files.- `mermaid`: a Mermaid `flowchart TD` (or `LR`) of the new path between files or functions,at most 15 nodes. Quote labels that hold spaces or punctuation.+- `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.+- `pseudo`: numbered plain-language steps of the new logic, naming the functions and files.-Pick one, both, or none (`{ "tools": [] }` means nothing worth showing). Skip messages whose+A change across two or more files gets the diagram and the steps; a visible behaviour change+also gets the table; order them diagram, table, steps. `{ "tools": [] }` means nothing worth+showing. Skip messages whosecommits are only release/version bumps, lockfiles or CHANGELOG, or change fewer than 5 linesin total. Write it in the conversation's language; the CLI validates each output and keeps aninvalid diagram as text.diff --git a/packages/cli/src/schema/session.ts b/packages/cli/src/schema/session.tsindex 61d3f15..1236288 100644--- a/packages/cli/src/schema/session.ts+++ b/packages/cli/src/schema/session.ts@@ -31,10 +31,10 @@ export const AgentDecision = z.object({export const MESSAGE_ID = /^m[1-9][0-9]*$/;/**- * How a Shape shows what a change does (Story 13.6). Two tools today; the- * registry in `shape.ts` says when each fits and validates its output.+ * 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"]);+export const ShapeKind = z.enum(["pseudo", "mermaid", "table"]);export type ShapeKind = z.infer<typeof ShapeKind>;/**@@ -43,7 +43,9 @@ export type ShapeKind = z.infer<typeof ShapeKind>;* text (so nothing is lost) and the map shows it as text instead of drawing it.*/export const ShapeTool = z.object({- kind: ShapeKind,+ // Any kind is stored: a tool a newer CLI added must not make this record+ // unreadable here. A kind this CLI does not know is shown as text.+ kind: z.string().min(1).max(40),text: z.string().min(1).max(4000),valid: z.boolean().optional(),});@@ -68,7 +70,8 @@ export const Shape = z.object({/** What a writer sends for a Shape: the tools' answers and the commits they cover. */export const ShapeInput = Shape.omit({ by: true, at: true }).extend({- tools: z.array(ShapeTool.omit({ valid: true })).max(3),+ // A writer names a tool this CLI knows; the record keeps any kind it is given.+ tools: z.array(ShapeTool.omit({ valid: true }).extend({ kind: ShapeKind })).max(3),});/**diff --git a/packages/cli/src/shape.ts b/packages/cli/src/shape.tsindex 74a6ee0..1efc967 100644--- a/packages/cli/src/shape.ts+++ b/packages/cli/src/shape.ts@@ -1,4 +1,5 @@import type { LineageNode, Shape, ShapeInput, ShapeKind, ShapeTool } from "./schema/session.js";+import { tableRows } from "./view/shape.js";/*** The Shape catalogue (Story 13.6): a Shape sits between a message's Intent@@ -45,10 +46,21 @@ const MERMAID_KEYWORDS = new Set(["linkstyle",]);-/** A rough node count: identifiers plus shapes; enough to keep a diagram small. */+/**+ * A rough node count: the identifiers left once labels are taken out (quoted+ * text, `[…]`, `(…)`, `{…}` shapes and `|…|` edge labels), so the words of a+ * label never count as nodes. Enough to keep a diagram small.+ */export function mermaidNodeCount(text: string): number {+ const bare = text+ .replace(/%%.*$/gm, "")+ .replace(/"[^"\n]*"/g, "")+ .replace(/\|[^|\n]*\|/g, "")+ .replace(/\[[^\]\n]*\]/g, "")+ .replace(/\([^)\n]*\)/g, "")+ .replace(/\{[^}\n]*\}/g, "");const ids = new Set<string>();- for (const match of text.matchAll(/\b[A-Za-z_][\w-]*\b/g)) {+ for (const match of bare.matchAll(/\b[A-Za-z_][\w-]*\b/g)) {const word = match[0];if (!MERMAID_KEYWORDS.has(word.toLowerCase())) ids.add(word);}@@ -73,6 +85,19 @@ export const SHAPE_TOOLS: readonly ShapeToolSpec[] = [return text.length <= 3000;},},+ {+ kind: "table",+ name: "Before / After",+ when:+ "The change alters behaviour someone can see: a fix, a new default, a rule that now " ++ "says yes or no. One row per case: what happens, how it behaved before, how it behaves now.",+ output:+ '{"kind": "table", "text": "A commit lands before its message is recorded | it never gets a Shape | it waits, then gets one"}',+ validate(text) {+ const rows = tableRows(text);+ return rows !== undefined && rows.length >= 1 && rows.length <= TABLE_MAX_ROWS;+ },+ },{kind: "mermaid",name: "Diagram",@@ -91,6 +116,12 @@ export const SHAPE_TOOLS: readonly ShapeToolSpec[] = [},];+/** Rows a Before / After table may carry. */+export const TABLE_MAX_ROWS = 8;++/** A tool a writer sent, after validation: its kind is one this CLI knows. */+export type KnownShapeTool = ShapeTool & { kind: ShapeKind };+/** The registry entry for a kind, or undefined for a kind this CLI does not know. */export function shapeToolSpec(kind: string): ShapeToolSpec | undefined {return SHAPE_TOOLS.find((tool) => tool.kind === kind);@@ -100,7 +131,7 @@ export function shapeToolSpec(kind: string): ShapeToolSpec | undefined {* Stamps each tool's validation result. The text is always kept: a diagram the* map cannot draw is shown as source, which is more useful than nothing.*/-export function validateShapeTools(tools: ShapeInput["tools"]): ShapeTool[] {+export function validateShapeTools(tools: ShapeInput["tools"]): KnownShapeTool[] {return tools.map((tool) => {const spec = shapeToolSpec(tool.kind);return { kind: tool.kind, text: tool.text, valid: spec?.validate(tool.text) ?? false };@@ -111,7 +142,11 @@ export function validateShapeTools(tools: ShapeInput["tools"]): ShapeTool[] {* A writer's Shape as the record stores it: the CLI owns `by` and `at`, and* every tool carries its validation result.*/-export function stampShape(shape: ShapeInput, by: "agent" | "side", at: string): Shape {+export function stampShape(+ shape: ShapeInput,+ by: "agent" | "side",+ at: string,+): Shape & { tools: KnownShapeTool[] } {return {tools: validateShapeTools(shape.tools),commits: [...new Set(shape.commits)],@@ -218,7 +253,10 @@ export function shapePrompt(opts: {toolCatalogue(),"","Rules:",- "- Pick the tool that fits; both only when each adds something; none when the change is a small fix not worth a picture.",+ "- When the change touches two or more files, give a diagram of the path and the steps; a single-file change takes the one tool that fits.",+ "- When the change alters behaviour someone can see (a fix, a new default, a rule), add a Before / After table; a pure refactor takes none.",+ "- A table has no header row (the map adds Case / Before / After); every line is one case.",+ "- Order the tools diagram, table, steps; at most three. 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.`,`- The Mermaid source must start with "flowchart TD" (or LR) and stay under ${MERMAID_MAX_NODES} nodes; quote labels that hold spaces or punctuation.`,"- Describe what the code does now, not the steps of the conversation.",diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.tsindex 7ff1c26..9bafd34 100644--- a/packages/cli/src/view/model.ts+++ b/packages/cli/src/view/model.ts@@ -77,7 +77,8 @@ export interface ViewChange {/** What a message's change does, between Intent and Code (Story 13.6). */export interface ViewShapeTool {- kind: "pseudo" | "mermaid";+ /** `pseudo`, `mermaid`, `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. */valid?: boolean | undefined;diff --git a/packages/cli/src/view/shape.ts b/packages/cli/src/view/shape.tsindex 1e313f2..693d4dc 100644--- a/packages/cli/src/view/shape.ts+++ b/packages/cli/src/view/shape.ts@@ -20,14 +20,36 @@ export function shapeState(shape: ViewShape | undefined, enabled: boolean): Shapreturn shape.tools.length === 0 ? "empty" : "ready";}-/** The first lines of a pseudo-code answer, for the panel preview. */+/**+ * The panel preview: the first lines of the steps, or else of the Before /+ * After table as `case: before → after`. A diagram alone has no text preview.+ */export function shapePreview(shape: ViewShape | undefined, lines = 3): string | undefined {- const pseudo = shape?.tools.find((tool) => tool.kind === "pseudo");- if (pseudo === undefined) return undefined;- const kept = pseudo.text- .split("\n")- .map((line) => line.trim())- .filter((line) => line !== "")- .slice(0, lines);- return kept.length === 0 ? undefined : kept.join("\n");+ const text = (kind: string) => shape?.tools.find((tool) => tool.kind === kind)?.text;+ const pseudo = text("pseudo");+ const table = text("table");+ const kept =+ pseudo !== undefined+ ? pseudo.split("\n").map((line) => line.trim())+ : (table?.split("\n") ?? []).map((line) => {+ const cells = line.split("|").map((cell) => cell.trim());+ return cells.length === 3 ? `${cells[0]}: ${cells[1]} → ${cells[2]}` : line.trim();+ });+ const shown = kept.filter((line) => line !== "").slice(0, lines);+ return shown.length === 0 ? undefined : shown.join("\n");+}++/**+ * A Before / After table's rows, `case | before | after` per line; undefined+ * when a line does not have exactly three filled cells.+ */+export function tableRows(text: string): [string, string, string][] | undefined {+ const rows: [string, string, string][] = [];+ for (const line of text.split("\n")) {+ if (line.trim() === "") continue;+ const cells = line.split("|").map((cell) => cell.trim());+ if (cells.length !== 3 || cells.some((cell) => cell === "")) return undefined;+ rows.push(cells as [string, string, string]);+ }+ return rows;}diff --git a/packages/cli/test/schema.test.ts b/packages/cli/test/schema.test.tsindex dbcba04..2614698 100644--- a/packages/cli/test/schema.test.ts+++ b/packages/cli/test/schema.test.ts@@ -31,6 +31,23 @@ describe("Session schema", () => {expect(s.nodes).toEqual([]);});+ it("keeps a Shape tool a newer CLI wrote, but takes only known tools from a writer", () => {+ const shape = { tools: [{ kind: "timeline", text: "x" }], commits: [] };+ const stored = Session.safeParse({+ schema: 1,+ sessionId: "abc",+ startedAt: T0,+ updatedAt: T0,+ nodes: [{ id: "m1", parent: null, kind: "message", title: "t", shape }],+ });+ expect(stored.success).toBe(true);+ const sent = SessionInput.safeParse({+ sessionId: "abc",+ nodes: [{ id: "m1", kind: "message", title: "t", shape }],+ });+ expect(sent.success).toBe(false);+ });+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.tsindex 9dfa7a2..ee5a3b1 100644--- a/packages/cli/test/shape.test.ts+++ b/packages/cli/test/shape.test.ts@@ -7,6 +7,7 @@ import { sessionWrite } from "../src/commands/session.js";import { needsShape, nextShapeNode } from "../src/commands/shape.js";import type { LineageNode } from "../src/schema/session.js";import {+ mermaidNodeCount,parseShapeAnswer,SHAPE_DIFF_LIMIT,shapePrompt,@@ -16,6 +17,7 @@ import {validateShapeTools,} from "../src/shape.js";import { loadSession } from "../src/store/stores.js";+import { 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";@@ -55,6 +57,69 @@ describe("the Shape tool catalogue", () => {}});+ it("counts a diagram's nodes, not the words in its labels", () => {+ const labelled = [+ "flowchart TD",+ ' A["doctor.ts newestTranscript"] --> B["skip(file) for each transcript"]',+ " B --> C[isHeadlessTranscript reads the first lines]",+ ' C --> E{"entrypoint starts with sdk?"}',+ " E -->|yes, a headless run| F(skip it)",+ " E -->|no| G[newest transcript] %% a note with many words in it",+ ].join("\n");+ expect(mermaidNodeCount(labelled)).toBe(6);+ expect(validateShapeTools([{ kind: "mermaid", text: labelled }])[0]?.valid).toBe(true);+ });++ it("accepts a Before / After table and rejects rows without three cells", () => {+ const ok =+ "Commit before record | no Shape | queued, then shaped\nSkipped message | blocks the rest | passed over";+ expect(validateShapeTools([{ kind: "table", text: ok }])[0]?.valid).toBe(true);+ for (const bad of [+ "only | two",+ "a | b | c | d",+ " | before | after",+ "",+ Array.from({ length: 9 }, (_, i) => `case ${i} | a | b`).join("\n"),+ ]) {+ expect(validateShapeTools([{ kind: "table", text: bad }])[0]?.valid).toBe(false);+ }+ });++ it("previews the steps, or else the table's rows", () => {+ const tools = (list: { kind: string; text: string }[]) => ({ tools: list, commits: [] });+ expect(shapePreview(tools([{ kind: "table", text: "Diff | overflows | scrolls\nx" }]))).toBe(+ "Diff: overflows → scrolls\nx",+ );+ expect(+ shapePreview(+ tools([+ { kind: "table", text: "a | b | c" },+ { kind: "pseudo", text: "1. one\n2. two" },+ ]),+ ),+ ).toBe("1. one\n2. two");+ expect(+ shapePreview(tools([{ kind: "mermaid", text: "flowchart TD\nA --> B" }])),+ ).toBeUndefined();+ expect(tableRows("a | b | c\n\nd | e | f")).toEqual([+ ["a", "b", "c"],+ ["d", "e", "f"],+ ]);+ });++ it("asks for the diagram and the steps across files, and a table for a visible change", () => {+ const prompt = shapePrompt({+ node: message(),+ commits: [],+ diff: "",+ diffTruncated: false,+ language: "auto",+ });+ expect(prompt).toContain("two or more files, give a diagram of the path and the steps");+ expect(prompt).toContain("add a Before / After table");+ expect(prompt).toContain('"table" (Before / After)');+ });+it("names both tools and says when to use each", () => {const catalogue = toolCatalogue();expect(catalogue).toContain('"pseudo"');diff --git a/packages/template/src/ShapeModal.tsx b/packages/template/src/ShapeModal.tsxindex 343be24..d3e110e 100644--- a/packages/template/src/ShapeModal.tsx+++ b/packages/template/src/ShapeModal.tsx@@ -1,6 +1,6 @@import { type ReactNode, useEffect, useRef, useState } from "react";import type { ViewNode } from "../../cli/src/view/model.js";-import { shapePreview, shapeState } from "../../cli/src/view/shape.js";+import { shapePreview, shapeState, tableRows } from "../../cli/src/view/shape.js";import { DiffView } from "./DiffView.js";import { isLivePage } from "./data.js";import { MermaidDiagram } from "./MermaidDiagram.js";@@ -99,7 +99,38 @@ function IntentLayer({ node }: { node: ShapeNode }) {);}-/** The Shape layer: the tools' output, Mermaid drawn in the page. */+/** How a tool's output is named when it is shown as plain text. */+const TEXT_CAPTION: Record<string, string> = {+ pseudo: "Steps",+ mermaid: "Diagram source (not drawn)",+ table: "Before / After (as written)",+};++/** A Before / After table: one row per case. */+function BeforeAfter({ rows }: { rows: readonly (readonly [string, string, string])[] }) {+ return (+ <table className="shape-table">+ <thead>+ <tr>+ <th scope="col">Case</th>+ <th scope="col">Before</th>+ <th scope="col">After</th>+ </tr>+ </thead>+ <tbody>+ {rows.map(([what, before, after], index) => (+ <tr key={`${index}-${what}`}>+ <th scope="row">{what}</th>+ <td>{before}</td>+ <td>{after}</td>+ </tr>+ ))}+ </tbody>+ </table>+ );+}++/** The Shape layer: each tool's output; Mermaid drawn, the table laid out. */function ShapeLayer({node,enabled,@@ -121,21 +152,31 @@ function ShapeLayer({}return (<div className="shape-tools">- {node.shape?.tools.map((tool, index) =>- tool.kind === "mermaid" && tool.valid !== false ? (- <figure key={`${tool.kind}-${index}`} className="shape-figure">- {renderMermaid(tool.text)}- <figcaption>Diagram</figcaption>- </figure>- ) : (- <figure key={`${tool.kind}-${index}`} className="shape-figure">+ {node.shape?.tools.map((tool, index) => {+ const key = `${tool.kind}-${index}`;+ if (tool.kind === "mermaid" && tool.valid !== false)+ return (+ <figure key={key} className="shape-figure">+ {renderMermaid(tool.text)}+ <figcaption>Diagram</figcaption>+ </figure>+ );+ const rows =+ tool.kind === "table" && tool.valid !== false ? tableRows(tool.text) : undefined;+ if (rows !== undefined)+ return (+ <figure key={key} className="shape-figure">+ <BeforeAfter rows={rows} />+ <figcaption>Before / After</figcaption>+ </figure>+ );+ return (+ <figure key={key} className="shape-figure"><pre className={`shape-source is-${tool.kind}`}>{tool.text}</pre>- <figcaption>- {tool.kind === "pseudo" ? "Steps" : "Diagram source (not drawn)"}- </figcaption>+ <figcaption>{TEXT_CAPTION[tool.kind] ?? tool.kind}</figcaption></figure>- ),- )}+ );+ })}{node.shape?.by ? (<p className="shape-by">Written by {node.shape.by === "side" ? "the side model" : "the agent"}.diff --git a/packages/template/src/styles.css b/packages/template/src/styles.cssindex 06e9c1e..8137309 100644--- a/packages/template/src/styles.css+++ b/packages/template/src/styles.css@@ -2650,6 +2650,35 @@ time {padding-left: 18px;}+.shape-table {+ width: 100%;+ border-collapse: collapse;+ font-size: 13px;+ line-height: 1.5;+}++.shape-table th,+.shape-table td {+ padding: 7px 10px;+ text-align: left;+ vertical-align: top;+ border: 1px solid var(--chip-line);+}++.shape-table thead th {+ color: var(--muted);+ font-size: 11px;+ font-weight: 600;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ background: var(--chip-bg);+}++.shape-table tbody th {+ width: 26%;+ font-weight: 600;+}+.shape-figure {margin: 0 0 16px;}diff --git a/packages/template/test/shape-modal.test.tsx b/packages/template/test/shape-modal.test.tsxindex 136cede..260a4c5 100644--- a/packages/template/test/shape-modal.test.tsx+++ b/packages/template/test/shape-modal.test.tsx@@ -84,6 +84,35 @@ describe("Intent, Shape and Code", () => {expect(invalid).toContain("Diagram source (not drawn)");});+ it("lays out a Before / After table and shows an unknown tool as text", () => {+ const html = render("shape", {+ shape: {+ tools: [+ {+ kind: "table",+ text: "Long diff | runs past the window | scrolls inside it",+ valid: true,+ },+ { kind: "timeline", text: "a newer tool", valid: false },+ ],+ commits: [],+ },+ });+ expect(html).toContain('<table class="shape-table">');+ expect(html).toContain('<th scope="row">Long diff</th><td>runs past the window</td>');+ expect(html).toContain("Before / After");+ expect(html).toContain("a newer tool");+ expect(html).toContain("<figcaption>timeline</figcaption>");+ });++ it("shows a table the registry refused as written", () => {+ const html = render("shape", {+ shape: { tools: [{ kind: "table", text: "only | two", valid: false }], commits: [] },+ });+ expect(html).toContain("Before / After (as written)");+ expect(html).not.toContain("<table");+ });+it("has three named tabs", () => {const html = render("shape");expect(html).toContain("Intent");