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): regenerate a message's Shape from the map
Eren16a27e41a2b6
diff --git a/docs/guide/map.md b/docs/guide/map.mdindex 4cdcd98..2eee05d 100644--- a/docs/guide/map.md+++ b/docs/guide/map.md@@ -101,7 +101,9 @@ A message that landed commits has three layers, in that order:writes it, not you, and a tiny change or a pure refactor gets none. The diagrams are drawnwhen 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.+ it. Under the Shape, **Regenerate** asks the side model to write it again — for the answer+ a small model missed, or one you want differently; it replaces a Shape the agent wrote+ too.- **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 layersdiff --git a/packages/cli/src/commands/session.ts b/packages/cli/src/commands/session.tsindex d14e911..e947947 100644--- a/packages/cli/src/commands/session.ts+++ b/packages/cli/src/commands/session.ts@@ -63,6 +63,11 @@ export interface SessionWriteOptions {* The side model may only fill empty fields and correct its own parents.*/by?: "agent" | "side";+ /**+ * The user asked for this Shape by hand (the map's Regenerate button), so it+ * replaces one the agent wrote too. Only `shape` is forced.+ */+ forceShape?: boolean;}/**@@ -142,6 +147,7 @@ export async function sessionWrite(crossTargets,by,sideOwnsParent: sideOwnedParents(events, base?.nodes),+ forceShape: opts.forceShape === true,});warnings = merged.warnings;const changes = structureChanges(merged.session, base, io.now(), by);diff --git a/packages/cli/src/commands/shape.ts b/packages/cli/src/commands/shape.tsindex 906e27b..99f77c0 100644--- a/packages/cli/src/commands/shape.ts+++ b/packages/cli/src/commands/shape.ts@@ -212,6 +212,57 @@ async function runShape(root: string, sessionId: string, config: Config, io: Io)}}+/**+ * The map's Regenerate button: the same side-model pass the hook runs, asked+ * for by name, for a message that already has a Shape or was passed over. The+ * session's shape lock is taken as usual, so a hook run and the button never+ * write the same record at once. It answers with the reason when nothing was+ * written, and the write replaces a Shape the agent wrote too.+ */+export async function regenerateShape(+ root: string,+ sessionId: string,+ nodeId: string,+ io: Io,+): Promise<{ ok: true } | { ok: false; reason: string }> {+ const loaded = await loadSession(root, sessionId);+ if (!loaded.found || !loaded.ok) return { ok: false, reason: "no such session" };+ const gitRoot = await findGitRoot(root);+ if (gitRoot === undefined) return { ok: false, reason: "not a git repository" };+ // The trailers link commits the record has not listed yet, as in the hook path.+ const [session] = attachThoughtTrailers(+ [loaded.data],+ await readThoughtTrailers(root, { env: io.env }),+ );+ const node = session?.nodes.find(+ (candidate) => candidate.kind === "message" && candidate.id === nodeId,+ );+ if (node === undefined) return { ok: false, reason: "no such message" };+ const config = await loadConfig(io.env);+ const said: string[] = [];+ const quiet: Io = {+ ...io,+ out: (line) => said.push(line),+ warn: (line) => said.push(line),+ };+ let wrote = false;+ try {+ await withLock(+ projectPaths(root).lock(`shape-${sessionId}`),+ async () => {+ wrote = await shapeNode(root, gitRoot, sessionId, node, config, quiet, true);+ },+ // A hook run may be holding the lock just now; give it a moment, then say so.+ { timeoutMs: 2000 },+ );+ } catch (err) {+ if (!(err instanceof LockBusyError)) throw err;+ return { ok: false, reason: "a shape is already being written" };+ }+ if (!wrote) return { ok: false, reason: said.at(-1) ?? "no shape was written" };+ return { ok: true };+}+/*** Writes one message's Shape; false when the skip rules turned it down. With* no session it prints the validated tools as JSON instead (`--dry-run`).@@ -223,6 +274,8 @@ async function shapeNode(node: LineageNode,config: Config,io: Io,+ /** Replace a Shape the agent wrote too: the user asked for this one. */+ force = false,): Promise<boolean> {const hashes = node.commits ?? [];const [changes, subjects] = await Promise.all([@@ -275,6 +328,10 @@ async function shapeNode(},],};- await sessionWrite({ dir: root, by: "side" }, io, async () => JSON.stringify(payload));+ await sessionWrite(+ { dir: root, by: "side", ...(force ? { forceShape: true } : {}) },+ io,+ async () => JSON.stringify(payload),+ );return true;}diff --git a/packages/cli/src/schema/merge.ts b/packages/cli/src/schema/merge.tsindex 7541364..b0e3f27 100644--- a/packages/cli/src/schema/merge.ts+++ b/packages/cli/src/schema/merge.ts@@ -35,6 +35,12 @@ export interface MergeOptions {* correction is never undone by a later side run.*/sideOwnsParent?: ReadonlySet<string>;+ /**+ * The user asked for this Shape (the map's Regenerate button), so a side+ * write replaces `shape` even when the agent wrote it. Every other field+ * keeps the usual rule.+ */+ forceShape?: boolean;}/**@@ -71,14 +77,14 @@ function isEmptyValue(value: unknown): boolean {* Merges one side-model node into the stored one: a field is written only when* empty or already the side model's, so the agent's notes are never overwritten.*/-function mergeSide(prev: LineageNode, input: LineageNodeInput): LineageNode {+function mergeSide(prev: LineageNode, input: LineageNodeInput, forceShape = false): LineageNode {const next: LineageNode = { ...prev };const marks: Record<string, "side"> = {};for (const field of SIDE_FIELDS) {const value = input[field];- if (value === undefined || (!isEmptyValue(prev[field]) && prev.by?.[field] !== "side")) {- continue;- }+ if (value === undefined) continue;+ const forced = forceShape && field === "shape";+ if (!forced && !isEmptyValue(prev[field]) && prev.by?.[field] !== "side") continue;(next as unknown as Record<SideField, unknown>)[field] = value;marks[field] = "side";}@@ -146,7 +152,7 @@ export function mergeSession(if (side && prev) {// The side model fills notes but never rewrites the agent's: it may only// correct a parent it wrote itself (Story 12.1).- const merged = mergeSide(prev, n);+ const merged = mergeSide(prev, n, opts.forceShape === true);const nextParent =parent !== undefined && own !== null && (opts.sideOwnsParent?.has(n.id) ?? false)? checkParent(n.id, parent, own, recorded, messageWarnings, label, opts.crossTargets)diff --git a/packages/cli/src/server.ts b/packages/cli/src/server.tsindex c988527..bd17edc 100644--- a/packages/cli/src/server.ts+++ b/packages/cli/src/server.ts@@ -14,6 +14,7 @@ import { fileURLToPath } from "node:url";import pkg from "../package.json" with { type: "json" };import { defaultAgent } from "./agents/index.js";import { buildProject } from "./commands/build.js";+import { regenerateShape } from "./commands/shape.js";import { diffTooLarge, isDiffSha, readCommitDiff } from "./diff.js";import { defaultsPrompter, type Io } from "./io.js";import { Config } from "./schema/config.js";@@ -25,7 +26,12 @@ import { globalPaths, projectPaths } from "./store/paths.js";import { setMessageRead } from "./store/read-state.js";import { loadConfig, loadRegistry, updateConfig } from "./store/stores.js";import { builtBy } from "./view/lineage.js";-import { isPanelEditableKey, LIVE_META_NAME, TOKEN_META_NAME } from "./view/model.js";+import {+ isPanelEditableKey,+ LIVE_META_NAME,+ TOKEN_HEADER_NAME,+ TOKEN_META_NAME,+} from "./view/model.js";import { buildPanel, panelSettings } from "./view/panel.js";import { editableSettings } from "./view/settings.js";@@ -42,7 +48,7 @@ const HOST = "127.0.0.1";const LIVE_META = `<meta name="${LIVE_META_NAME}" content="1">`;/** Header a settings write must carry, with the token from the panel page. */-export const CONFIG_TOKEN_HEADER = "x-cogit-token";+export const CONFIG_TOKEN_HEADER = TOKEN_HEADER_NAME;/** A settings write is a tiny JSON object; anything larger is not ours. */export const CONFIG_BODY_LIMIT = 4096;@@ -661,6 +667,84 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>res.end(JSON.stringify({ ok: true, id, read }));}+ /**+ * `POST /api/shape/regenerate` { dir, sessionId, nodeId }: the Shape modal's+ * Regenerate button. Runs the side model for that message the way the+ * post-commit hook does — behind the session's shape lock — and then rebuilds+ * the open maps, so the page shows the Shape it wrote. Every check a write+ * carries holds here too; the model call can take a minute.+ */+ async function writeShapeRegenerate(+ req: IncomingMessage,+ res: ServerResponse,+ port: number,+ ): Promise<void> {+ if (+ !originAllowed(req.headers.origin, port) ||+ !tokenMatches(req.headers[CONFIG_TOKEN_HEADER])+ ) {+ respond(res, 403, "forbidden");+ return;+ }+ const type = req.headers["content-type"];+ if (+ typeof type !== "string" ||+ type.split(";")[0]?.trim().toLowerCase() !== "application/json"+ ) {+ respond(res, 415, "content-type must be application/json");+ return;+ }+ const body = await readLimitedBody(req);+ if (body === null) {+ respond(res, 413, "request body too large");+ return;+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(body);+ } catch {+ respond(res, 400, "invalid JSON");+ return;+ }+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {+ respond(res, 400, "expected a JSON object");+ return;+ }+ const { dir, sessionId, nodeId } = parsed as Record<string, unknown>;+ if (+ typeof dir !== "string" ||+ typeof sessionId !== "string" ||+ typeof nodeId !== "string" ||+ !/^[A-Za-z0-9._:-]{1,128}$/.test(sessionId) ||+ !/^h[0-9a-f]{12}$/.test(nodeId)+ ) {+ respond(res, 400, "expected { dir, sessionId, nodeId }");+ return;+ }+ const root = await registeredRoot(env, dir);+ if (root === null) {+ respond(res, 403, "not a registered project");+ return;+ }+ let result: Awaited<ReturnType<typeof regenerateShape>>;+ try {+ result = await regenerateShape(root, sessionId, nodeId, buildIo);+ } catch (err) {+ respond(res, 500, err instanceof Error ? err.message : "could not regenerate the shape");+ return;+ }+ if (!result.ok) {+ respond(res, result.reason.startsWith("no such") ? 404 : 409, result.reason);+ return;+ }+ res.writeHead(200, {+ "content-type": "application/json",+ "cache-control": "no-store",+ });+ res.end(JSON.stringify({ ok: true, sessionId, nodeId }));+ void queueRebuild();+ }+/*** `POST /api/inbox/dismiss` { dir, sessionId, at } (Story 11.1): the inbox's* dismiss button. It writes the project's local state file, and the turn time@@ -888,6 +972,10 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>await writeOpenSessions(req, res, port);return;}+ if (url.pathname === "/api/shape/regenerate") {+ await writeShapeRegenerate(req, res, port);+ return;+ }if (url.pathname !== "/api/config") {respond(res, 405, "method not allowed");return;diff --git a/packages/cli/src/shape.ts b/packages/cli/src/shape.tsindex 1d5652f..b91db81 100644--- a/packages/cli/src/shape.ts+++ b/packages/cli/src/shape.ts@@ -373,7 +373,7 @@ export function shapePrompt(opts: {`Diff${opts.diffTruncated ? " (cut to fit; the commits above are complete)" : ""}:`,opts.diff,"",- 'Return only one JSON object, no code fences: {"tools": [{"kind": "pseudo", "text": "1. ...\\n2. ..."}]}. Return {"tools": []} when nothing here is worth showing.',+ 'Return only one JSON object, no code fences: {"tools": [{"kind": "pseudo", "text": "1. ...\\n2. ..."}]}. A change across two or more files always includes a Flow; return {"tools": []} only for a change that is not worth showing.',].join("\n");}diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.tsindex 00f2d8d..3bfa75c 100644--- a/packages/cli/src/view/model.ts+++ b/packages/cli/src/view/model.ts@@ -25,6 +25,9 @@ export const LIVE_META_NAME = "cogit-live";*/export const TOKEN_META_NAME = "cogit-token";+/** Request header that echoes {@link TOKEN_META_NAME} back on a write (a page cannot read it off another site). */+export const TOKEN_HEADER_NAME = "x-cogit-token";+/*** Settings the panel may change over the local server (Story 8.9). The rest are* setup-time or security-adjacent and stay on `cogit config set`.diff --git a/packages/cli/test/server.test.ts b/packages/cli/test/server.test.tsindex 8f5e3be..b3c3f1c 100644--- a/packages/cli/test/server.test.ts+++ b/packages/cli/test/server.test.ts@@ -1,5 +1,5 @@import { execFile } from "node:child_process";-import { mkdir, readFile, rm, writeFile } from "node:fs/promises";+import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";import {type ClientRequest,createServer as createHttpServer,@@ -34,10 +34,10 @@ import { readInboxDismissed } from "../src/store/inbox-state.js";import { readMapView } from "../src/store/map-view.js";import { globalPaths, projectPaths } from "../src/store/paths.js";import { readReadState } from "../src/store/read-state.js";-import { loadConfig, updateConfig } from "../src/store/stores.js";+import { loadConfig, loadSession, updateConfig } from "../src/store/stores.js";import { builtBy } from "../src/view/lineage.js";import { DATA_ELEMENT_ID, LIVE_META_NAME, TOKEN_META_NAME } from "../src/view/model.js";-import { envFor, fakeIo, noGitProject, tempDir } from "./helpers.js";+import { envFor, fakeIo, noGitProject, T0, tempDir } from "./helpers.js";const TEMPLATE = `<!doctype html><html><head><title>cogit</title></head><body><div id="root"></div><script id="${DATA_ELEMENT_ID}" type="application/json"></script></body></html>`;@@ -852,6 +852,138 @@ describe("read marks (10.3)", () => {});});+describe("shape regenerate endpoint", () => {+ const NODE = "h111111111111";++ function regenerateWrite(+ server: MapServer,+ token: string,+ payload: unknown,+ overrides: Record<string, string> = {},+ ): Promise<Reply> {+ return postConfig(`${server.url}/api/shape/regenerate`, JSON.stringify(payload), {+ origin: `http://127.0.0.1:${server.port}`,+ [CONFIG_TOKEN_HEADER]: token,+ ...overrides,+ });+ }++ it("refuses a foreign project, a bad body, a bad token and an unknown session", async () => {+ const server = await start();+ const token = await panelToken(server);+ expect(+ (+ await regenerateWrite(server, token, {+ dir: join(dir, "elsewhere"),+ sessionId: "s1",+ nodeId: NODE,+ })+ ).status,+ ).toBe(403);+ expect(+ (await regenerateWrite(server, token, { dir: root, sessionId: "s1", nodeId: "m1" })).status,+ ).toBe(400);+ expect((await regenerateWrite(server, token, { dir: root, nodeId: NODE })).status).toBe(400);+ expect(+ (await regenerateWrite(server, "nope", { dir: root, sessionId: "s1", nodeId: NODE })).status,+ ).toBe(403);+ const missing = await regenerateWrite(server, token, {+ dir: root,+ sessionId: "s1",+ nodeId: NODE,+ });+ expect(missing.status).toBe(404);+ expect(missing.body).toContain("no such session");+ });++ it("writes the message's Shape again with the side model", async () => {+ const run = promisify(execFile);+ const git = (...args: string[]): Promise<string> =>+ run("git", ["-C", root, ...args], {+ env: { ...process.env, GIT_CONFIG_NOSYSTEM: "1", HOME: dir },+ }).then((result) => result.stdout.trim());+ await git("init", "-q");+ await writeFile(join(root, "a.ts"), `${"a\n".repeat(12)}a.ts`);+ await writeFile(join(root, "b.ts"), `${"b\n".repeat(12)}b.ts`);+ await git("add", "a.ts", "b.ts");+ await git(+ "-c",+ "[email protected]",+ "-c",+ "user.name=Tester",+ "commit",+ "-q",+ "--no-verify",+ "-m",+ "feat: work",+ );+ const sha = await git("rev-parse", "HEAD");+ // A record the agent shaped already: the hook would leave it alone.+ await mkdir(projectPaths(root).sessions, { recursive: true });+ await writeFile(+ projectPaths(root).session("s1"),+ JSON.stringify({+ schema: 1,+ sessionId: "s1",+ agent: "claude-code",+ title: "Ship it",+ startedAt: T0,+ updatedAt: T0,+ status: { goal: "", done: [], pending: [], next: "" },+ nodes: [+ {+ id: NODE,+ kind: "message",+ parent: null,+ title: "Work",+ at: T0,+ commits: [sha],+ shape: {+ tools: [{ kind: "table", text: "a | b | c", valid: true }],+ commits: [sha],+ by: "agent",+ at: T0,+ },+ },+ ],+ }),+ "utf8",+ );+ // A fake side model that answers with a Flow.+ const bin = join(dir, "bin");+ await mkdir(bin, { recursive: true });+ const flow = JSON.stringify({+ nodes: [+ { id: "a", kind: "event", label: "after a commit" },+ { id: "b", kind: "fn", label: "write the shape" },+ ],+ edges: [{ from: "a", to: "b", label: "once the message is recorded" }],+ ordered: false,+ });+ const answer = JSON.stringify({ tools: [{ kind: "flow", text: flow }] });+ await writeFile(+ join(bin, "claude"),+ `#!/usr/bin/env node+process.stdin.resume();+process.stdin.on("end", () => {+ process.stdout.write(JSON.stringify({ type: "result", subtype: "success", result: ${JSON.stringify(answer)} }));+});+`,+ );+ await chmod(join(bin, "claude"), 0o755);+ env = { ...env, PATH: `${bin}:${process.env.PATH ?? ""}` };+ const server = await start();+ const token = await panelToken(server);+ const reply = await regenerateWrite(server, token, { dir: root, sessionId: "s1", nodeId: NODE });+ expect(reply.status).toBe(200);+ const loaded = await loadSession(root, "s1");+ if (!loaded.found || !loaded.ok) throw new Error("no record");+ const shape = loaded.data.nodes.find((node) => node.id === NODE)?.shape;+ expect(shape?.by).toBe("side");+ expect(shape?.tools[0]).toMatchObject({ kind: "flow", valid: true });+ });+});+describe("inbox dismiss endpoint (Story 11.1)", () => {const AT = "2026-10-21T10:00:00.000Z";const SESSION = "3f2b1c4d-0000-4000-8000-000000000001";diff --git a/packages/cli/test/session.test.ts b/packages/cli/test/session.test.tsindex b4a96fb..9acae12 100644--- a/packages/cli/test/session.test.ts+++ b/packages/cli/test/session.test.ts@@ -132,6 +132,45 @@ describe("session write", () => {expect((await stored()).lastRecordedBy).toBe("side");});+ it("keeps the agent's Shape until the user asks for a new one by hand", async () => {+ const shape = (kind: string, text: string) => ({ tools: [{ kind, text }], commits: [] });+ await write({+ sessionId: "s1",+ nodes: [+ {+ id: "m1",+ kind: "message",+ parent: null,+ title: "Ship it",+ shape: shape("table", "a | b | c"),+ },+ ],+ });+ // The usual side rule: the agent's Shape stays.+ await side({+ sessionId: "s1",+ nodes: [+ { id: "m1", kind: "message", title: "Ship it", shape: shape("pseudo", "1. one\n2. two") },+ ],+ });+ expect((await node("m1"))?.shape?.tools[0]?.kind).toBe("table");+ // The map's Regenerate button asks for this one, so it replaces it.+ await sessionWrite({ dir: root, by: "side", forceShape: true }, io, async () =>+ JSON.stringify({+ sessionId: "s1",+ nodes: [+ {+ id: "m1",+ kind: "message",+ title: "Ship it",+ shape: shape("pseudo", "1. one\n2. two"),+ },+ ],+ }),+ );+ expect((await node("m1"))?.shape?.tools[0]).toMatchObject({ kind: "pseudo", valid: true });+ });+it("lets the side model fill a field the agent left empty", async () => {await write({sessionId: "s1",diff --git a/packages/cli/test/shape-commit.test.ts b/packages/cli/test/shape-commit.test.tsindex 3ff41c6..34ef29a 100644--- a/packages/cli/test/shape-commit.test.ts+++ b/packages/cli/test/shape-commit.test.ts@@ -5,7 +5,7 @@ import { join } from "node:path";import { promisify } from "node:util";import { beforeEach, describe, expect, it } from "vitest";import { init } from "../src/commands/init.js";-import { shapeMessage } from "../src/commands/shape.js";+import { regenerateShape, shapeMessage } from "../src/commands/shape.js";import { runGitHook } from "../src/git-hooks.js";import { createProgram } from "../src/program.js";import type { Session } from "../src/schema/session.js";@@ -207,6 +207,59 @@ process.stdin.on("end", () => {expect(io.lines).toEqual(["a shape for s1 is already being written"]);});+ it("writes a Shape again when the map asks, even for one the message already has", async () => {+ const a = await commit("a.txt", 12, THOUGHT);+ const b = await commit("b.txt", 12, THOUGHT);+ await writeRecord([+ {+ id: THOUGHT,+ kind: "message",+ title: "Work",+ parent: null,+ commits: [a, b],+ // The hook would leave this alone: it already covers both commits, and+ // the agent wrote it — the user's ask still replaces it.+ shape: {+ tools: [{ kind: "table", text: "a | b | c" }],+ commits: [a, b],+ by: "agent",+ at: T0,+ },+ },+ ]);+ const io = fakeIo(await fakeClaude());+ expect(await regenerateShape(root, "s1", THOUGHT, io)).toEqual({ ok: true });+ const shape = await shapeOf(THOUGHT);+ expect(shape?.by).toBe("side");+ expect(shape?.commits).toEqual([a, b]);+ expect(shape?.tools[0]).toMatchObject({ kind: "pseudo", valid: true });+ });++ it("says why a regenerate wrote nothing, and refuses an unknown message", async () => {+ const tiny = await commit("a.txt", 1, THOUGHT);+ await writeRecord([+ {+ id: THOUGHT,+ kind: "message",+ title: "Tiny",+ parent: null,+ commits: [tiny],+ },+ ]);+ expect(await regenerateShape(root, "s1", THOUGHT, fakeIo(env))).toEqual({+ ok: false,+ reason: `no shape for ${THOUGHT}: only 1 changed line`,+ });+ expect(await regenerateShape(root, "s1", OLDER, fakeIo(env))).toEqual({+ ok: false,+ reason: "no such message",+ });+ expect(await regenerateShape(root, "nope", THOUGHT, fakeIo(env))).toEqual({+ ok: false,+ reason: "no such session",+ });+ });+it("prints a dry run without saving or queueing, for a recorded message or a bare commit", async () => {const sha = await commit("a.txt", 12, THOUGHT);const claudeEnv = await fakeClaude();diff --git a/packages/cli/test/shape.test.ts b/packages/cli/test/shape.test.tsindex da9d80a..a336a6b 100644--- a/packages/cli/test/shape.test.ts+++ b/packages/cli/test/shape.test.ts@@ -160,6 +160,8 @@ describe("the Shape tool catalogue", () => {language: "auto",});expect(prompt).toContain("A Flow for a change across two or more files");+ // The last line the writer reads says it again, since a small model forgets.+ expect(prompt).toContain("A change across two or more files always includes a Flow");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");diff --git a/packages/template/src/ShapeModal.tsx b/packages/template/src/ShapeModal.tsxindex 4e896e7..71a6b89 100644--- a/packages/template/src/ShapeModal.tsx+++ b/packages/template/src/ShapeModal.tsx@@ -1,5 +1,5 @@import { type ReactNode, useEffect, useRef, useState } from "react";-import type { ViewNode } from "../../cli/src/view/model.js";+import { TOKEN_HEADER_NAME, type ViewNode } from "../../cli/src/view/model.js";import {flowToMermaid,parseFlow,@@ -11,7 +11,7 @@ import {UNIVERSAL_KINDS,} from "../../cli/src/view/shape.js";import { DiffView } from "./DiffView.js";-import { isLivePage } from "./data.js";+import { isLivePage, pageToken } from "./data.js";import { HelpTip } from "./HelpTip.js";import { MermaidDiagram } from "./MermaidDiagram.js";@@ -35,6 +35,9 @@ export interface ShapeNode {commits?: string[] | undefined;commitTags?: ViewNode["commitTags"];shape?: ViewNode["shape"];+ /** The owning session and the message's id: what the Regenerate button posts. */+ sessionId?: string | undefined;+ nodeId?: string | undefined;}const TABS: { id: ShapeTab; number: string; label: string }[] = [@@ -289,6 +292,64 @@ function ShapeLayer({);}+/** What the Regenerate button posts: the message and the project it belongs to. */+export interface RegenerateRequest {+ dir: string;+ sessionId: string;+ nodeId: string;+}++/** The POST the button makes; the token is the one the served page carries. */+async function requestShape(request: RegenerateRequest): Promise<void> {+ const token = pageToken();+ if (token === null) throw new Error("Open the map with `cogit open` to regenerate a Shape.");+ const response = await fetch("/api/shape/regenerate", {+ method: "POST",+ headers: { "content-type": "application/json", [TOKEN_HEADER_NAME]: token },+ body: JSON.stringify(request),+ });+ if (response.ok) return;+ const text = (await response.text()).trim();+ throw new Error(text === "" ? `the Shape was not written (${response.status})` : text);+}++/**+ * Asks the side model to write this message's Shape again, for the answer a+ * small model missed or one the reader wants differently. The server holds the+ * request until the model answers and then rebuilds the open maps, so the layer+ * swaps in the new Shape by itself; this only shows whether the ask is running.+ */+function RegenerateButton({ request }: { request: RegenerateRequest }) {+ const [state, setState] = useState<"idle" | "running" | "done" | "error">("idle");+ const [error, setError] = useState("");+ const run = async (): Promise<void> => {+ setState("running");+ setError("");+ try {+ await requestShape(request);+ setState("done");+ } catch (err) {+ setState("error");+ setError(err instanceof Error ? err.message : String(err));+ }+ };+ return (+ <div className="shape-regenerate">+ <button+ type="button"+ className="shape-regenerate-button"+ title="Ask the side model to write this Shape again"+ onClick={() => void run()}+ disabled={state === "running"}+ >+ {state === "running" ? "Regenerating…" : "Regenerate"}+ </button>+ {state === "done" ? <span className="muted">Written again.</span> : null}+ {state === "error" ? <span className="shape-regenerate-error">{error}</span> : null}+ </div>+ );+}+/** The Code layer: the message's commits and their patches. */function CodeLayer({ node, root }: { node: ShapeNode; root: string }) {const live = typeof document !== "undefined" && isLivePage();@@ -321,6 +382,7 @@ export function ShapeLayers({tab,enabled,onTab,+ regenerate,renderMermaid = (source) => <MermaidDiagram source={source} />,}: {node: ShapeNode;@@ -328,6 +390,8 @@ export function ShapeLayers({tab: ShapeTab;enabled: boolean;onTab: (tab: ShapeTab) => void;+ /** Set on a served page for a message that can be shaped again. */+ regenerate?: RegenerateRequest | undefined;renderMermaid?: (source: string) => ReactNode;}) {return (@@ -353,7 +417,10 @@ export function ShapeLayers({>{tab === "intent" ? <IntentLayer node={node} /> : null}{tab === "shape" ? (- <ShapeLayer node={node} enabled={enabled} renderMermaid={renderMermaid} />+ <>+ <ShapeLayer node={node} enabled={enabled} renderMermaid={renderMermaid} />+ {regenerate === undefined ? null : <RegenerateButton request={regenerate} />}+ </>) : null}{tab === "code" ? <CodeLayer node={node} root={root} /> : null}</div>@@ -366,11 +433,13 @@ export function ShapeModal({node,root,enabled,+ regenerate,onClose,}: {node: ShapeNode;root: string;enabled: boolean;+ regenerate?: RegenerateRequest | undefined;onClose: () => void;}) {const [tab, setTab] = useState<ShapeTab>("shape");@@ -410,7 +479,14 @@ export function ShapeModal({×</button></header>- <ShapeLayers node={node} root={root} tab={tab} enabled={enabled} onTab={setTab} />+ <ShapeLayers+ node={node}+ root={root}+ tab={tab}+ enabled={enabled}+ onTab={setTab}+ regenerate={regenerate}+ /></div></div>);@@ -433,6 +509,13 @@ export function ShapeSection({const [open, setOpen] = useState(false);const state = shapeState(node.shape, enabled);const preview = shapePreview(node.shape);+ // Only a page the local server served can ask for a new Shape: over+ // `file://` nothing would answer, and the button stays out.+ const live = typeof document !== "undefined" && isLivePage();+ const regenerate =+ enabled && live && node.sessionId !== undefined && node.nodeId !== undefined+ ? { dir: root, sessionId: node.sessionId, nodeId: node.nodeId }+ : undefined;const diagram = node.shape?.tools.find((tool) => DIAGRAM_KINDS.has(tool.kind) && tool.valid !== false,);@@ -462,7 +545,13 @@ export function ShapeSection({Open</button>{open ? (- <ShapeModal node={node} root={root} enabled={enabled} onClose={() => setOpen(false)} />+ <ShapeModal+ node={node}+ root={root}+ enabled={enabled}+ regenerate={regenerate}+ onClose={() => setOpen(false)}+ />) : null}</section>);diff --git a/packages/template/src/styles.css b/packages/template/src/styles.cssindex 062b484..7276eff 100644--- a/packages/template/src/styles.css+++ b/packages/template/src/styles.css@@ -2788,6 +2788,37 @@ time {font-size: 11px;}+/* The Regenerate ask: a small button and where its answer goes. */+.shape-regenerate {+ display: flex;+ gap: 8px;+ align-items: center;+ margin-top: 14px;+ padding-top: 10px;+ border-top: 1px solid var(--line);+ font-size: 12px;+}++.shape-regenerate-button {+ padding: 4px 12px;+ color: var(--text);+ font: inherit;+ font-size: 12px;+ background: var(--chip-bg);+ border: 1px solid var(--chip-line);+ border-radius: 4px;+ cursor: pointer;+}++.shape-regenerate-button:disabled {+ cursor: progress;+ opacity: 0.7;+}++.shape-regenerate-error {+ color: var(--danger, #d9483b);+}+.shape-code section {margin-bottom: 14px;}diff --git a/packages/template/test/shape-modal.test.tsx b/packages/template/test/shape-modal.test.tsxindex 50d1a0a..b834236 100644--- a/packages/template/test/shape-modal.test.tsx+++ b/packages/template/test/shape-modal.test.tsx@@ -63,6 +63,22 @@ describe("Intent, Shape and Code", () => {expect(html).toContain("Shapes are off");});+ it("offers Regenerate only on a served page that names the message", () => {+ expect(render("shape")).not.toContain("Regenerate");+ const html = renderToStaticMarkup(+ createElement(ShapeLayers, {+ node,+ root: "/tmp/project",+ tab: "shape",+ enabled: true,+ onTab: () => {},+ regenerate: { dir: "/tmp/project", sessionId: "s1", nodeId: node.id },+ renderMermaid: () => createElement("div", null, "diagram"),+ }),+ );+ expect(html).toContain(">Regenerate</button>");+ });+it("says nothing is worth showing for an empty answer", () => {const html = render("shape", { shape: { tools: [], commits: ["abc1234"] } });expect(html).toContain("Nothing to show");