From 7780f81a219813fcf54e6b5dd612a7d40e31d32b Mon Sep 17 00:00:00 2001 From: grim <75869731+ripgrim@users.noreply.github.com> Date: Fri, 7 Aug 2026 16:53:23 -0700 Subject: [PATCH 1/6] feat(agent): bound agent builder retries and improve chat scrolling (#89) --- apps/agent/agent/hooks/builder-delegation.ts | 26 ++ apps/agent/agent/instructions/task.ts | 2 +- apps/agent/agent/lib/builder-delegation.ts | 45 +++ apps/agent/agent/lib/builder-runtime.ts | 14 +- .../agent/subagents/agent_builder/agent.ts | 31 +- .../agent_builder/hooks/execution-guard.ts | 29 ++ .../subagents/agent_builder/instructions.md | 33 +- .../agent_builder/lib/draft-input.ts | 81 +++++ .../agent_builder/lib/execution-state.ts | 117 +++++++ .../agent_builder/tools/ask_question.ts | 3 - .../agent_builder/tools/save_agent_draft.ts | 57 +--- .../agent_builder/tools/write_agent_file.ts | 2 + apps/agent/test/custom-agent-runtime.spec.ts | 298 +++++++++++++++++- .../agent-builder/agent-builder-chat.tsx | 293 ++++++++++------- docs/agent.md | 15 +- 15 files changed, 837 insertions(+), 209 deletions(-) create mode 100644 apps/agent/agent/hooks/builder-delegation.ts create mode 100644 apps/agent/agent/lib/builder-delegation.ts create mode 100644 apps/agent/agent/subagents/agent_builder/hooks/execution-guard.ts create mode 100644 apps/agent/agent/subagents/agent_builder/lib/draft-input.ts create mode 100644 apps/agent/agent/subagents/agent_builder/lib/execution-state.ts delete mode 100644 apps/agent/agent/subagents/agent_builder/tools/ask_question.ts diff --git a/apps/agent/agent/hooks/builder-delegation.ts b/apps/agent/agent/hooks/builder-delegation.ts new file mode 100644 index 00000000..036060bc --- /dev/null +++ b/apps/agent/agent/hooks/builder-delegation.ts @@ -0,0 +1,26 @@ +import { defineHook } from "eve/hooks"; +import { + builderDelegationState, + recordBuilderDelegation, +} from "../lib/builder-delegation"; +import { attribute, purposeOf } from "../lib/session-purpose"; + +export default defineHook({ + events: { + "actions.requested"(event, ctx) { + if ( + purposeOf(ctx) !== "builder" || + attribute(ctx, "commandType") !== "CREATE_AGENT" + ) { + return; + } + + const next = recordBuilderDelegation( + builderDelegationState.get(), + event.data.turnId, + event.data.actions, + ); + builderDelegationState.update(() => next); + }, + }, +}); diff --git a/apps/agent/agent/instructions/task.ts b/apps/agent/agent/instructions/task.ts index a22b7afd..3cf99d13 100644 --- a/apps/agent/agent/instructions/task.ts +++ b/apps/agent/agent/instructions/task.ts @@ -64,7 +64,7 @@ export function builderTaskMarkdown( ): string { const task = commandType === "CREATE_AGENT" - ? `This private CRM chat turn is authorized to create or revise an agent. Call agent_builder exactly once. Pass the complete request, the conversation's relevant decisions, every tagged resource, and your understanding of any attachment. Do not call research tools or mutate CRM records yourself. If the specialist returns needs_input, call ask_question with exactly its question, options, and freeform policy instead of replying with a plain-text question. Ask exactly one decision at a time and never bundle several missing details into one prompt. After the answer, ask another question only if the build remains materially blocked. Ask only when the answer materially changes the trigger, records, integrations, schedule, outcome, or side effect. Do not interrupt a sufficiently specific request or ask about optional polish. If the specialist returns draft_ready, relay its concise summary and explain that the draft is ready for human review and is not deployed yet.` + ? `This private CRM chat turn is authorized to create or revise an agent. Call agent_builder exactly once. Pass the complete request, the conversation's relevant decisions, every tagged resource, and your understanding of any attachment. Do not call research tools or mutate CRM records yourself. The specialist asks any essential clarification directly through ask_question and returns only when the draft is ready. Never retry agent_builder in the same turn. If the specialist fails, explain that the build could not finish and ask the user to try again instead of delegating again. If the specialist returns draft_ready, relay its concise summary and explain that the draft is ready for human review and is not deployed yet.` : `This is a private CRM assistant chat. Answer the user's question directly. Use tagged records as scope and use available read-only CRM and research tools when evidence is needed. Use list_deals for pipeline-wide, open-deal, or inactivity questions and follow its pagination until the requested scope is complete. The chat renders list_deals output as a structured deal list. Do not restate or enumerate individual deal rows in prose, bullets, or tables; the structured list is the sole row-level presentation. Give only a concise synthesis, caveats, and useful next actions after the tool results. If one materially necessary decision is missing, call ask_question with one focused follow-up instead of guessing; do not interrupt for optional detail. Do not call agent_builder, create an agent draft, or mutate CRM records on this turn. Agent creation begins only from an explicit request to create or build one. Be concise, distinguish CRM evidence from inference, and say when the CRM does not contain the answer.`; return needsTitle diff --git a/apps/agent/agent/lib/builder-delegation.ts b/apps/agent/agent/lib/builder-delegation.ts new file mode 100644 index 00000000..30695531 --- /dev/null +++ b/apps/agent/agent/lib/builder-delegation.ts @@ -0,0 +1,45 @@ +import { defineState } from "eve/context"; + +type BuilderDelegationAction = { + callId: string; + kind: string; + subagentName?: string; +}; + +type BuilderDelegationState = { + turnId: string | null; + callIds: string[]; +}; + +export const builderDelegationState = defineState( + "crm.builder-delegation", + () => ({ turnId: null, callIds: [] }), +); + +export function recordBuilderDelegation( + state: BuilderDelegationState, + turnId: string, + actions: readonly BuilderDelegationAction[], +): BuilderDelegationState { + const current = + state.turnId === turnId ? state : { turnId, callIds: [] as string[] }; + const callIds = new Set(current.callIds); + + for (const action of actions) { + if ( + action.kind !== "subagent-call" || + action.subagentName !== "agent_builder" || + callIds.has(action.callId) + ) { + continue; + } + if (callIds.size > 0) { + throw new Error( + "The agent builder can be delegated only once per creation turn.", + ); + } + callIds.add(action.callId); + } + + return { turnId, callIds: [...callIds] }; +} diff --git a/apps/agent/agent/lib/builder-runtime.ts b/apps/agent/agent/lib/builder-runtime.ts index 2a30b816..434e59ff 100644 --- a/apps/agent/agent/lib/builder-runtime.ts +++ b/apps/agent/agent/lib/builder-runtime.ts @@ -460,9 +460,21 @@ async function validateDraft( .filter((resource) => resource.kind !== "integration") .map((resource) => `${resource.kind}:${resource.id}`), ); + const taggedRecordLabels = new Map( + taggedResources + .filter((resource) => resource.kind !== "integration") + .map((resource) => [`${resource.kind}:${resource.id}`, resource.label]), + ); for (const resource of recordResources) { - if (!taggedRecordKeys.has(`${resource.kind}:${resource.id}`)) { + const key = `${resource.kind}:${resource.id}`; + if (!taggedRecordKeys.has(key)) { issues.push(`${resource.label} was not tagged in this builder chat.`); + continue; + } + if (taggedRecordLabels.get(key) !== resource.label) { + issues.push( + `${resource.kind} ${resource.id} must use its exact tagged label.`, + ); } } diff --git a/apps/agent/agent/subagents/agent_builder/agent.ts b/apps/agent/agent/subagents/agent_builder/agent.ts index 19b75699..4318264f 100644 --- a/apps/agent/agent/subagents/agent_builder/agent.ts +++ b/apps/agent/agent/subagents/agent_builder/agent.ts @@ -10,30 +10,15 @@ export default defineAgent({ fallback: DEFAULT_AGENT_MODEL.id, events: { "session.started": () => selectedModel() }, }), - outputSchema: z.discriminatedUnion("status", [ - z.object({ - status: z.literal("needs_input"), - question: z.string().min(1).max(500), - options: z - .array( - z.object({ - id: z.string().min(1).max(80), - label: z.string().min(1).max(120), - }), - ) - .max(4), - allowFreeform: z.boolean(), - }), - z.object({ - status: z.literal("draft_ready"), - summary: z.string().min(1).max(1000), - agentId: z.string().min(1), - versionId: z.string().min(1), - }), - ]), + outputSchema: z.object({ + status: z.literal("draft_ready"), + summary: z.string().min(1).max(1000), + agentId: z.string().min(1), + versionId: z.string().min(1), + }), limits: { - maxInputTokensPerSession: 250_000, - maxOutputTokensPerSession: 20_000, + maxInputTokensPerSession: 100_000, + maxOutputTokensPerSession: 10_000, sessionTimeoutMs: 24 * 60 * 60 * 1000, }, }); diff --git a/apps/agent/agent/subagents/agent_builder/hooks/execution-guard.ts b/apps/agent/agent/subagents/agent_builder/hooks/execution-guard.ts new file mode 100644 index 00000000..754d6fc9 --- /dev/null +++ b/apps/agent/agent/subagents/agent_builder/hooks/execution-guard.ts @@ -0,0 +1,29 @@ +import { defineHook } from "eve/hooks"; +import { + builderExecutionState, + markBuilderDraftSaveFinished, + recordBuilderActions, +} from "../lib/execution-state"; + +export default defineHook({ + events: { + "actions.requested"(event) { + const next = recordBuilderActions( + builderExecutionState.get(), + event.data.turnId, + event.data.stepIndex, + event.data.actions, + ); + builderExecutionState.update(() => next); + }, + "action.result"(event) { + if ( + event.data.status !== "completed" && + event.data.result.kind === "tool-result" && + event.data.result.toolName === "save_agent_draft" + ) { + markBuilderDraftSaveFinished(false); + } + }, + }, +}); diff --git a/apps/agent/agent/subagents/agent_builder/instructions.md b/apps/agent/agent/subagents/agent_builder/instructions.md index 6506c68e..1742462f 100644 --- a/apps/agent/agent/subagents/agent_builder/instructions.md +++ b/apps/agent/agent/subagents/agent_builder/instructions.md @@ -31,23 +31,29 @@ not report. If no safe and useful draft is possible because an essential target, explicitly requested connection, schedule, outcome, or side effect remains ambiguous, do -not call `save_agent_draft`. Return `needs_input` with one focused question for -the parent to ask the user. Include two to four mutually exclusive options when -they clarify a real choice, and set `allowFreeform` when a custom answer is -valid. Ask only when the answer materially changes the bounded behavior and the -least-privilege defaults above do not resolve it. Return exactly one decision -per pause; never bundle several missing details into one question. After the -answer, ask the next question only if the build is still materially blocked. Do -not interrupt for a name, wording, optional polish, or another choice that can -be safely represented in the reviewable draft. For a schedule, calculate a -future `nextRunAt` from the supplied current time and provide its recurrence in -minutes. +not call `save_agent_draft`. Call `ask_question` directly with one focused +question. Include two to four mutually exclusive options when they clarify a +real choice, and allow freeform input when a custom answer is valid. Ask only +when the answer materially changes the bounded behavior and the least-privilege +defaults above do not resolve it. Ask exactly one decision per pause; never +bundle several missing details into one question. After the answer, ask the next +question only if the build is still materially blocked. Do not interrupt for a +name, wording, optional polish, or another choice that can be safely represented +in the reviewable draft. For a schedule, calculate a future `nextRunAt` from the +supplied current time and provide its recurrence in minutes. Choose the record scope explicitly. Use `SELECTED` only for the exact tagged CRM records reported by `inspect_context`. Use `WORKSPACE` only when the user clearly asks for workspace-wide CRM access. Never treat an empty selected scope as workspace access. +The `save_agent_draft` resource contract is exact. Copy only tagged companies, +contacts, and deals from `inspect_context` into `resources`, preserving each +kind, id, and label byte for byte. Put read-only sources in `integrations` using +only `gmail` or `calendar`, and only when `availableConnections` reports that +source. Never put CRM, Gmail, Google Calendar, or another integration in +`resources`. The runtime derives the human-readable access list. + For `crm.activity.create`, list the exact allowed activity types. Authorize `NOTE`, `TASK`, or both only when the request calls for them. A prose summary never grants an activity type by itself. @@ -60,5 +66,6 @@ call when necessary. Never put credentials, tokens, or secret values in a file. After the three files agree, call `save_agent_draft` once with the exact same behavior. A successful save creates exact final file snapshots and an immutable version in READY state for human review. It does not deploy it. -Return `draft_ready` with the saved agent and version ids plus a plain-language -summary of the trigger, data scope, action, and access. +After a successful save, call no tool except `final_output`. Return +`draft_ready` immediately with the saved agent and version ids plus a +plain-language summary of the trigger, data scope, action, and access. diff --git a/apps/agent/agent/subagents/agent_builder/lib/draft-input.ts b/apps/agent/agent/subagents/agent_builder/lib/draft-input.ts new file mode 100644 index 00000000..a25f2c43 --- /dev/null +++ b/apps/agent/agent/subagents/agent_builder/lib/draft-input.ts @@ -0,0 +1,81 @@ +import { z } from "zod"; +import type { DraftAgentInput } from "../../../lib/builder-runtime"; + +const recordResource = z.object({ + kind: z.enum(["company", "contact", "deal"]), + id: z.string().min(1), + label: z.string().min(1).max(120), +}); + +const trigger = z.object({ + type: z.enum(["MANUAL", "SCHEDULE"]), + name: z.string().trim().min(1).max(120), + summary: z.string().trim().min(1).max(240), + nextRunAt: z.string().nullish(), + intervalMinutes: z.number().int().min(1).max(525_600).nullish(), +}); + +const action = z.discriminatedUnion("type", [ + z.object({ + type: z.literal("crm.activity.create"), + provider: z.literal("crm"), + summary: z.string().trim().min(1).max(240), + activityTypes: z + .array(z.enum(["NOTE", "TASK"])) + .min(1) + .max(2), + }), + z.object({ + type: z.literal("run.summary"), + provider: z.literal("crm"), + summary: z.string().trim().min(1).max(240), + }), +]); + +export const builderDraftToolInput = z.object({ + name: z.string().trim().min(1).max(100), + description: z.string().trim().min(1).max(320), + instructions: z.string().trim().min(40).max(20_000), + trigger, + recordScope: z.enum(["SELECTED", "WORKSPACE"]), + resources: z.array(recordResource).max(30), + integrations: z.array(z.enum(["gmail", "calendar"])).max(2), + actions: z.array(action).min(1).max(10), +}); + +type BuilderDraftToolInput = z.infer; + +const INTEGRATIONS = { + gmail: { kind: "integration", id: "google:gmail", label: "Gmail" }, + calendar: { + kind: "integration", + id: "google:calendar", + label: "Google Calendar", + }, +} as const; + +export function draftInputFromTool( + input: BuilderDraftToolInput, +): DraftAgentInput { + const { integrations: requestedIntegrations, ...draft } = input; + const integrations = [...new Set(requestedIntegrations)]; + const access = [ + input.recordScope === "WORKSPACE" + ? "Read workspace CRM records" + : "Read selected CRM records", + ...integrations.map((integration) => + integration === "gmail" + ? "Read connected Gmail messages" + : "Read connected Google Calendar events", + ), + ]; + + return { + ...draft, + resources: [ + ...input.resources, + ...integrations.map((integration) => INTEGRATIONS[integration]), + ], + access, + }; +} diff --git a/apps/agent/agent/subagents/agent_builder/lib/execution-state.ts b/apps/agent/agent/subagents/agent_builder/lib/execution-state.ts new file mode 100644 index 00000000..bfa845ad --- /dev/null +++ b/apps/agent/agent/subagents/agent_builder/lib/execution-state.ts @@ -0,0 +1,117 @@ +import { defineState } from "eve/context"; + +type BuilderAction = { + callId: string; + kind: string; + toolName?: string; +}; + +type BuilderExecutionState = { + turnId: string | null; + stepIndex: number | null; + callIds: string[]; + stepCallIds: string[]; + saveCallIds: string[]; + savePending: boolean; + saved: boolean; +}; + +export const builderExecutionState = defineState( + "crm.agent-builder.execution", + () => ({ + turnId: null, + stepIndex: null, + callIds: [], + stepCallIds: [], + saveCallIds: [], + savePending: false, + saved: false, + }), +); + +export function recordBuilderActions( + state: BuilderExecutionState, + turnId: string, + stepIndex: number, + actions: readonly BuilderAction[], +): BuilderExecutionState { + const current = + state.turnId === turnId + ? state + : { + turnId, + stepIndex: null, + callIds: [], + stepCallIds: [], + saveCallIds: [], + savePending: false, + saved: state.saved, + }; + const callIds = new Set(current.callIds); + const stepCallIds = new Set( + current.stepIndex === stepIndex ? current.stepCallIds : [], + ); + const saveCallIds = new Set(current.saveCallIds); + let savePending = current.savePending; + + for (const action of actions) { + if (callIds.has(action.callId)) continue; + if (current.saved && action.toolName !== "final_output") { + throw new Error( + "The draft is already saved. Return the saved draft now without calling another tool.", + ); + } + if (!current.saved && action.toolName === "final_output") { + throw new Error("Save the draft before returning draft_ready."); + } + if (savePending) { + throw new Error( + "Wait for save_agent_draft to finish before calling another tool.", + ); + } + if (callIds.size >= 12) { + throw new Error("The agent builder exceeded its tool-call budget."); + } + if (action.toolName === "save_agent_draft") { + if (stepCallIds.size > 0) { + throw new Error("Call save_agent_draft by itself in a model step."); + } + if (saveCallIds.size >= 2) { + throw new Error("The agent builder exceeded its draft-save budget."); + } + saveCallIds.add(action.callId); + savePending = true; + } + callIds.add(action.callId); + stepCallIds.add(action.callId); + } + + return { + turnId, + stepIndex, + callIds: [...callIds], + stepCallIds: [...stepCallIds], + saveCallIds: [...saveCallIds], + savePending, + saved: current.saved, + }; +} + +export function finishBuilderDraftSave( + state: BuilderExecutionState, + saved: boolean, +): BuilderExecutionState { + return { ...state, savePending: false, saved: state.saved || saved }; +} + +export function markBuilderDraftSaveFinished(saved: boolean): void { + builderExecutionState.update((state) => finishBuilderDraftSave(state, saved)); +} + +export function assertBuilderDraftOpen(): void { + if (builderExecutionState.get().saved) { + throw new Error( + "The draft is already saved. Return the saved draft now without changing files.", + ); + } +} diff --git a/apps/agent/agent/subagents/agent_builder/tools/ask_question.ts b/apps/agent/agent/subagents/agent_builder/tools/ask_question.ts deleted file mode 100644 index 04bd0544..00000000 --- a/apps/agent/agent/subagents/agent_builder/tools/ask_question.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { disableTool } from "eve/tools"; - -export default disableTool(); diff --git a/apps/agent/agent/subagents/agent_builder/tools/save_agent_draft.ts b/apps/agent/agent/subagents/agent_builder/tools/save_agent_draft.ts index 3528a620..8ed3c0aa 100644 --- a/apps/agent/agent/subagents/agent_builder/tools/save_agent_draft.ts +++ b/apps/agent/agent/subagents/agent_builder/tools/save_agent_draft.ts @@ -1,57 +1,24 @@ import { defineTool } from "eve/tools"; -import { z } from "zod"; import { saveBuilderDraft } from "../../../lib/builder-runtime"; import { requireBuilderAttribute } from "../../../lib/session-purpose"; - -const resource = z.object({ - kind: z.enum(["integration", "company", "contact", "deal"]), - id: z.string().min(1), - label: z.string().min(1).max(120), -}); - -const trigger = z.object({ - type: z.enum(["MANUAL", "SCHEDULE"]), - name: z.string().min(1).max(120), - summary: z.string().min(1).max(240), - nextRunAt: z.string().nullish(), - intervalMinutes: z.number().int().min(1).max(525_600).nullish(), -}); - -const action = z.discriminatedUnion("type", [ - z.object({ - type: z.literal("crm.activity.create"), - provider: z.literal("crm"), - summary: z.string().min(1).max(240), - activityTypes: z - .array(z.enum(["NOTE", "TASK"])) - .min(1) - .max(2), - }), - z.object({ - type: z.literal("run.summary"), - provider: z.literal("crm"), - summary: z.string().min(1).max(240), - }), -]); +import { builderDraftToolInput, draftInputFromTool } from "../lib/draft-input"; +import { + assertBuilderDraftOpen, + markBuilderDraftSaveFinished, +} from "../lib/execution-state"; export default defineTool({ description: - "Validate and save one immutable agent version for human review. This never deploys the agent.", - inputSchema: z.object({ - name: z.string().trim().min(1).max(100), - description: z.string().trim().min(1).max(320), - instructions: z.string().trim().min(40).max(20_000), - trigger, - recordScope: z.enum(["SELECTED", "WORKSPACE"]), - resources: z.array(resource).max(30), - actions: z.array(action).min(1).max(10), - access: z.array(z.string().trim().min(1).max(120)).max(20), - }), + "Validate and save one immutable agent version for human review. Copy selected CRM records exactly into resources. Put connected read sources only in integrations. This never deploys the agent.", + inputSchema: builderDraftToolInput, async execute(input, ctx) { - return saveBuilderDraft( + assertBuilderDraftOpen(); + const result = await saveBuilderDraft( requireBuilderAttribute(ctx, "conversationId"), requireBuilderAttribute(ctx, "userId"), - input, + draftInputFromTool(input), ); + markBuilderDraftSaveFinished(result.saved); + return result; }, }); diff --git a/apps/agent/agent/subagents/agent_builder/tools/write_agent_file.ts b/apps/agent/agent/subagents/agent_builder/tools/write_agent_file.ts index 8e46d38a..9d938012 100644 --- a/apps/agent/agent/subagents/agent_builder/tools/write_agent_file.ts +++ b/apps/agent/agent/subagents/agent_builder/tools/write_agent_file.ts @@ -5,6 +5,7 @@ import { writeBuilderArtifact, } from "../../../lib/builder-runtime"; import { requireBuilderAttribute } from "../../../lib/session-purpose"; +import { assertBuilderDraftOpen } from "../lib/execution-state"; export default defineTool({ description: @@ -14,6 +15,7 @@ export default defineTool({ content: z.string().min(1).max(40_000), }), async execute(input, ctx) { + assertBuilderDraftOpen(); return writeBuilderArtifact( requireBuilderAttribute(ctx, "conversationId"), requireBuilderAttribute(ctx, "userId"), diff --git a/apps/agent/test/custom-agent-runtime.spec.ts b/apps/agent/test/custom-agent-runtime.spec.ts index 963136fa..fde444e8 100644 --- a/apps/agent/test/custom-agent-runtime.spec.ts +++ b/apps/agent/test/custom-agent-runtime.spec.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "bun:test"; import { builderTaskMarkdown } from "../agent/instructions/task"; +import { recordBuilderDelegation } from "../agent/lib/builder-delegation"; import { builderCommandType, builderDeliveryMessage, @@ -16,6 +17,14 @@ import { requireBuilderAttribute, requireTeamAgentAttribute, } from "../agent/lib/session-purpose"; +import { + builderDraftToolInput, + draftInputFromTool, +} from "../agent/subagents/agent_builder/lib/draft-input"; +import { + finishBuilderDraftSave, + recordBuilderActions, +} from "../agent/subagents/agent_builder/lib/execution-state"; const context = (purpose?: string, commandType?: string) => ({ session: { @@ -149,11 +158,8 @@ describe("builder command routing", () => { it("delegates only the explicit creation command to the agent builder", () => { const creation = builderTaskMarkdown("CREATE_AGENT"); expect(creation).toContain("Call agent_builder exactly once"); - expect(creation).toContain("call ask_question"); - expect(creation).toContain("exactly one decision at a time"); - expect(creation).toContain( - "Do not interrupt a sufficiently specific request", - ); + expect(creation).toContain("Never retry agent_builder in the same turn"); + expect(creation).toContain("asks any essential clarification directly"); const chat = builderTaskMarkdown("CHAT"); expect(chat).toContain("Do not call agent_builder"); expect(chat).toContain("call ask_question"); @@ -171,3 +177,285 @@ describe("builder command routing", () => { expect(builderTaskMarkdown("CHAT", false)).not.toContain("set_chat_title"); }); }); + +describe("builder delegation guard", () => { + it("allows one idempotent builder delegation per turn", () => { + const first = recordBuilderDelegation( + { turnId: null, callIds: [] }, + "turn-1", + [ + { + kind: "subagent-call", + callId: "call-1", + subagentName: "agent_builder", + }, + ], + ); + + expect( + recordBuilderDelegation(first, "turn-1", [ + { + kind: "subagent-call", + callId: "call-1", + subagentName: "agent_builder", + }, + ]), + ).toEqual(first); + expect(() => + recordBuilderDelegation(first, "turn-1", [ + { + kind: "subagent-call", + callId: "call-2", + subagentName: "agent_builder", + }, + ]), + ).toThrow("only once"); + expect( + recordBuilderDelegation(first, "turn-2", [ + { + kind: "subagent-call", + callId: "call-2", + subagentName: "agent_builder", + }, + ]), + ).toEqual({ turnId: "turn-2", callIds: ["call-2"] }); + }); +}); + +describe("agent builder execution guard", () => { + it("bounds save attempts and permits only final output after saving", () => { + const initial = { + turnId: null, + stepIndex: null, + callIds: [], + stepCallIds: [], + saveCallIds: [], + savePending: false, + saved: false, + }; + const first = recordBuilderActions(initial, "turn-1", 0, [ + { + kind: "tool-call", + callId: "save-1", + toolName: "save_agent_draft", + }, + ]); + const second = recordBuilderActions( + finishBuilderDraftSave(first, false), + "turn-1", + 1, + [ + { + kind: "tool-call", + callId: "save-2", + toolName: "save_agent_draft", + }, + ], + ); + + expect(() => + recordBuilderActions(finishBuilderDraftSave(second, false), "turn-1", 2, [ + { + kind: "tool-call", + callId: "save-3", + toolName: "save_agent_draft", + }, + ]), + ).toThrow("draft-save budget"); + + const saved = finishBuilderDraftSave(first, true); + expect(() => + recordBuilderActions(saved, "turn-2", 0, [ + { + kind: "tool-call", + callId: "write-1", + toolName: "write_agent_file", + }, + ]), + ).toThrow("already saved"); + expect(() => + recordBuilderActions(saved, "turn-2", 0, [ + { + kind: "tool-call", + callId: "final-1", + toolName: "final_output", + }, + ]), + ).not.toThrow(); + }); + + it("requires draft saving to run by itself", () => { + const initial = { + turnId: null, + stepIndex: null, + callIds: [], + stepCallIds: [], + saveCallIds: [], + savePending: false, + saved: false, + }; + + expect(() => + recordBuilderActions(initial, "turn-1", 0, [ + { + kind: "tool-call", + callId: "save-1", + toolName: "save_agent_draft", + }, + { + kind: "tool-call", + callId: "write-1", + toolName: "write_agent_file", + }, + ]), + ).toThrow("Wait for save_agent_draft"); + expect(() => + recordBuilderActions(initial, "turn-1", 0, [ + { + kind: "tool-call", + callId: "write-1", + toolName: "write_agent_file", + }, + { + kind: "tool-call", + callId: "save-1", + toolName: "save_agent_draft", + }, + ]), + ).toThrow("by itself"); + }); +}); + +describe("agent builder draft input", () => { + it("separates canonical integrations from exact CRM resources", () => { + const parsed = builderDraftToolInput.parse({ + name: "Renewal prep", + description: "Prepare a renewal call brief.", + instructions: + "Run manually. Read the selected deal and summarize renewal risks for review.", + trigger: { + type: "MANUAL", + name: "Prepare renewal brief", + summary: "Run before a renewal call", + }, + recordScope: "SELECTED", + resources: [{ kind: "deal", id: "deal-1", label: "Acme renewal" }], + integrations: ["gmail", "calendar"], + actions: [ + { + type: "run.summary", + provider: "crm", + summary: "Write a reviewable renewal brief", + }, + ], + }); + + expect(draftInputFromTool(parsed)).toMatchObject({ + resources: [ + { kind: "deal", id: "deal-1", label: "Acme renewal" }, + { kind: "integration", id: "google:gmail", label: "Gmail" }, + { + kind: "integration", + id: "google:calendar", + label: "Google Calendar", + }, + ], + access: [ + "Read selected CRM records", + "Read connected Gmail messages", + "Read connected Google Calendar events", + ], + }); + }); + + it("rejects guessed integration resource objects", () => { + const result = builderDraftToolInput.safeParse({ + name: "Renewal prep", + description: "Prepare a renewal call brief.", + instructions: + "Run manually. Read the selected deal and summarize renewal risks for review.", + trigger: { + type: "MANUAL", + name: "Prepare renewal brief", + summary: "Run before a renewal call", + }, + recordScope: "SELECTED", + resources: [{ kind: "integration", id: "gmail", label: "gmail" }], + integrations: [], + actions: [ + { + type: "run.summary", + provider: "crm", + summary: "Write a reviewable renewal brief", + }, + ], + }); + + expect(result.success).toBe(false); + expect( + builderDraftToolInput.safeParse({ + name: "Renewal prep", + description: "Prepare a renewal call brief.", + instructions: + "Run manually. Read workspace deals and summarize renewal risks for review.", + trigger: { + type: "MANUAL", + name: "Prepare renewal brief", + summary: "Run before a renewal call", + }, + recordScope: "WORKSPACE", + resources: [], + integrations: ["crm"], + actions: [ + { + type: "run.summary", + provider: "crm", + summary: "Write a reviewable renewal brief", + }, + ], + }).success, + ).toBe(false); + }); + + it("trims trigger metadata and rejects blank text", () => { + const base = { + name: "Renewal prep", + description: "Prepare a renewal call brief.", + instructions: + "Run manually. Read workspace deals and summarize renewal risks for review.", + recordScope: "WORKSPACE" as const, + resources: [], + integrations: [], + actions: [ + { + type: "run.summary" as const, + provider: "crm" as const, + summary: " Write a reviewable renewal brief ", + }, + ], + }; + + expect( + builderDraftToolInput.safeParse({ + ...base, + trigger: { + type: "MANUAL", + name: " ", + summary: "Run before a renewal call", + }, + }).success, + ).toBe(false); + + const parsed = builderDraftToolInput.parse({ + ...base, + trigger: { + type: "MANUAL", + name: " Prepare renewal brief ", + summary: " Run before a renewal call ", + }, + }); + expect(parsed.trigger.name).toBe("Prepare renewal brief"); + expect(parsed.trigger.summary).toBe("Run before a renewal call"); + expect(parsed.actions[0]?.summary).toBe("Write a reviewable renewal brief"); + }); +}); diff --git a/apps/app/components/agent-builder/agent-builder-chat.tsx b/apps/app/components/agent-builder/agent-builder-chat.tsx index 6bca17f7..a4eaea97 100644 --- a/apps/app/components/agent-builder/agent-builder-chat.tsx +++ b/apps/app/components/agent-builder/agent-builder-chat.tsx @@ -22,6 +22,14 @@ import { import { Button } from "@crm/ui/components/button"; import { Icon } from "@crm/ui/components/icon"; import { Markdown } from "@crm/ui/components/markdown"; +import { + MessageScroller, + MessageScrollerButton, + MessageScrollerContent, + MessageScrollerItem, + MessageScrollerProvider, + MessageScrollerViewport, +} from "@crm/ui/components/message-scroller"; import { Reasoning } from "@crm/ui/components/reasoning"; import { useMountEffect } from "@crm/ui/hooks/use-mount-effect"; import { cn } from "@crm/ui/lib/utils"; @@ -282,84 +290,125 @@ export function AgentBuilderChat({ creatingAgent={creatingAgent} /> -
-
- {timeline.map((item) => - item.kind === "submission" ? ( - - ) : ( - - ), - )} - - {working && creatingAgent ? ( - - ) : null} - - {creatingAgent && data.builderArtifacts.length > 0 ? ( - - ) : null} - - {!working && - failure && - creatingAgent && - !reviewVersion && - data.agent?.status !== "LIVE" ? ( - send(retryPrompt) : null} - /> - ) : null} - - {!working && failure && !creatingAgent ? ( - send(retryPrompt) : null} - /> - ) : null} - - {creatingAgent && !working && reviewVersion ? ( - - ) : null} + + + + + {timeline.map((item) => ( + + {item.kind === "submission" ? ( + + ) : ( + + )} + + ))} - {creatingAgent && data.agent?.status === "LIVE" && !reviewVersion ? ( - - send({ - commandType: "CHAT", - message, - resources: [], - attachments: [], - }) - } - /> - ) : null} -
-
+ {working && creatingAgent ? ( + + + + ) : null} + + {creatingAgent && data.builderArtifacts.length > 0 ? ( + + + + ) : null} + + {!working && + failure && + creatingAgent && + !reviewVersion && + data.agent?.status !== "LIVE" ? ( + + send(retryPrompt) : null} + /> + + ) : null} + + {!working && failure && !creatingAgent ? ( + + send(retryPrompt) : null} + /> + + ) : null} + + {creatingAgent && !working && reviewVersion ? ( + + + + ) : null} + + {creatingAgent && + data.agent?.status === "LIVE" && + !reviewVersion ? ( + + + send({ + commandType: "CHAT", + message, + resources: [], + attachments: [], + }) + } + /> + + ) : null} + + + + +
@@ -463,43 +512,63 @@ function SharedAgentChat({ Read-only -
-
-
-

Shared by {conversation.ownerName}

-

- You can read this builder chat, but only its owner can continue or - change it. -

-
+ + + + + +
+

+ Shared by {conversation.ownerName} +

+

+ You can read this builder chat, but only its owner can + continue or change it. +

+
+
- {timeline.map((item) => - item.kind === "submission" ? ( - - ) : ( - - ), - )} + {timeline.map((item) => ( + + {item.kind === "submission" ? ( + + ) : ( + + )} + + ))} - {conversation.builderArtifacts.length > 0 ? ( - - ) : null} -
-
+ {conversation.builderArtifacts.length > 0 ? ( + + + + ) : null} + + + + + ); } diff --git a/docs/agent.md b/docs/agent.md index 358faacb..6003b621 100644 --- a/docs/agent.md +++ b/docs/agent.md @@ -220,9 +220,11 @@ delegation paths for custom agents. - **Creation requires the current `CREATE_AGENT` turn.** Every builder tool checks the purpose and command type in session auth. A normal builder chat cannot create a draft by prompt alone. -- **Builder output is typed.** `needs_input` carries one question and its choices for - the parent to surface through eve HITL. `draft_ready` carries the immutable version - ids. The specialist cannot ask directly because its `ask_question` is disabled. +- **Builder clarification is durable HITL.** The specialist calls eve's built-in + `ask_question` directly; descendant input requests are proxied to the root channel, + and the same child turn resumes when the user answers. The authored + `tools/ask_question.ts` disable override must stay absent. Builder task output is + typed as `draft_ready` and carries the immutable version ids only after save. - **Empty never means all.** A version chooses `SELECTED` or `WORKSPACE` record scope. Selected scope requires at least one record tagged in that private conversation; workspace scope is an explicit grant and cannot also list selected records. @@ -244,9 +246,10 @@ delegation paths for custom agents. and current run state. Every runner tool also checks the `team-agent` purpose and revalidates scope and action permission. - **No generic execution surface.** Both specialists disable shell, file, arbitrary - web, todo and direct-question built-ins. CRM access exists only through their small - authored tool sets. Tool code runs in the trusted app runtime; the sandbox remains - isolated and deny-all. + web and todo built-ins. The runner also disables direct questions; the builder keeps + only `ask_question` for durable clarification. CRM access exists only through their + small authored tool sets. Tool code runs in the trusted app runtime; the sandbox + remains isolated and deny-all. Runner manifests fail closed when either the explicit record-scope mode or an activity type grant is missing. Versions created before these typed permissions were From 0e68e45909182c875ea58ba18fb89d9a87032e11 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 8 Aug 2026 00:38:08 -0700 Subject: [PATCH 2/6] fix(app): render agent transcript chronologically with anchored tool results (#92) Co-authored-by: grim <75869731+ripgrim@users.noreply.github.com> Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> --- .../agent-builder/agent-builder-chat.tsx | 562 +++++++++--------- .../components/agent-builder/agent-result.tsx | 93 +++ .../agent-builder/agent-scope-badges.tsx | 42 +- apps/app/lib/agent-results.ts | 36 ++ apps/app/lib/agent-tool-display.ts | 41 ++ apps/app/lib/agent-transcript.ts | 44 ++ apps/app/test/agent-results.spec.ts | 125 ++++ apps/app/test/agent-tool-display.spec.ts | 59 ++ apps/app/test/agent-transcript.spec.ts | 58 ++ packages/ui/src/components/badge.tsx | 1 + packages/ui/src/components/dot-matrix.tsx | 46 ++ packages/ui/src/components/logo.tsx | 2 +- 12 files changed, 801 insertions(+), 308 deletions(-) create mode 100644 apps/app/components/agent-builder/agent-result.tsx create mode 100644 apps/app/lib/agent-results.ts create mode 100644 apps/app/lib/agent-tool-display.ts create mode 100644 apps/app/test/agent-results.spec.ts create mode 100644 apps/app/test/agent-tool-display.spec.ts create mode 100644 packages/ui/src/components/dot-matrix.tsx diff --git a/apps/app/components/agent-builder/agent-builder-chat.tsx b/apps/app/components/agent-builder/agent-builder-chat.tsx index a4eaea97..de6e1398 100644 --- a/apps/app/components/agent-builder/agent-builder-chat.tsx +++ b/apps/app/components/agent-builder/agent-builder-chat.tsx @@ -5,7 +5,6 @@ import Application from "@carbon/icons-react/es/Application"; import ArrowRight from "@carbon/icons-react/es/ArrowRight"; import Building from "@carbon/icons-react/es/Building"; import Checkmark from "@carbon/icons-react/es/Checkmark"; -import CheckmarkFilled from "@carbon/icons-react/es/CheckmarkFilled"; import Copy from "@carbon/icons-react/es/Copy"; import Partnership from "@carbon/icons-react/es/Partnership"; import Play from "@carbon/icons-react/es/Play"; @@ -19,7 +18,9 @@ import { AsyncButtonContent, useAsyncAction, } from "@crm/ui/components/async-action"; +import { Badge } from "@crm/ui/components/badge"; import { Button } from "@crm/ui/components/button"; +import { DotMatrix } from "@crm/ui/components/dot-matrix"; import { Icon } from "@crm/ui/components/icon"; import { Markdown } from "@crm/ui/components/markdown"; import { @@ -37,7 +38,7 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { Client, type MessageStreamEvent } from "eve/client"; import type { EveMessage, EveMessageInputRequest } from "eve/react"; import Link from "next/link"; -import { type ReactNode, useState } from "react"; +import { Fragment, type ReactNode, useState } from "react"; import { toast } from "sonner"; import { AgentClarificationComposer, @@ -55,16 +56,16 @@ import { latestCompletedArtifactVersionId, reviewVersionId, } from "@/lib/agent-builder-state"; +import { toolLabel } from "@/lib/agent-tool-display"; import { type AgentTurnFailure, conversationTimeline, - dealListResultOf, eventStreamSettled, latestTurnFailure, - mergeDealListResultPages, messagesFromEvents, pendingQuestion, splitMarkdownTable, + type TranscriptItem, toTranscript, } from "@/lib/agent-transcript"; import { isSharedChatToken } from "@/lib/chat-route"; @@ -73,13 +74,17 @@ import type { RouterOutputs } from "@/lib/trpc/types"; import { useWorkspaceUrl } from "@/lib/use-workspace-url"; import { AgentCodeWorkspace } from "./agent-code-workspace"; import { AgentComposer, type BuilderPrompt } from "./agent-composer"; +import { + agentResultSkeleton, + agentResultsByItem, + hasAgentResult, +} from "./agent-result"; import { AgentScopeBadges } from "./agent-scope-badges"; import { ChatAttachmentChip, ChatCommandChip, ChatReferenceChip, } from "./chat-chips"; -import { DealListResultTable } from "./deal-list-result"; import { DeleteChatAction } from "./delete-chat-action"; import { ShareChatDialog } from "./share-chat-dialog"; @@ -87,6 +92,12 @@ type Conversation = RouterOutputs["conversations"]["builderById"]; type SharedConversation = RouterOutputs["conversations"]["shared"]; const BUILDER_STEPS = ["Scope", "Instructions", "Manifest", "Review"] as const; +const BUILDER_STEP_ARTIFACTS = [ + null, + "agent/instructions.md", + "agent/manifest.json", + "agent/README.md", +] as const; type DraftVersion = { id: string; status: string; @@ -282,6 +293,11 @@ export function AgentBuilderChat({ : [event], })) } + onEnded={() => + setLiveStream((current) => + current?.key === streamKey ? null : current, + ) + } /> ) : null} void; onEvent: (event: MessageStreamEvent) => void; + onEnded: () => void; }) { useMountEffect(() => { const controller = new AbortController(); - const session = new Client({ + const client = new Client({ headers: { "x-crm-builder-conversation": conversationId }, host: "", - }).session({ sessionId, streamIndex: 0 }); + }); const follow = async () => { + const session = client.session({ sessionId, streamIndex: 0 }); const snapshot = await session.snapshot({ signal: controller.signal }); if (controller.signal.aborted) return; onSnapshot(snapshot.events); @@ -466,11 +485,13 @@ function BuilderEventFollower({ } }; - void follow().catch((error: unknown) => { - if (!controller.signal.aborted) { - console.error(error); - } - }); + void follow() + .catch((error: unknown) => { + if (!controller.signal.aborted) console.error(error); + }) + .finally(() => { + if (!controller.signal.aborted) onEnded(); + }); return () => controller.abort(); }); @@ -478,6 +499,40 @@ function BuilderEventFollower({ return null; } +function withoutTable(text: string): string { + const { before, after } = splitMarkdownTable(text); + return [before, after].filter(Boolean).join("\n\n").trim(); +} + +function AgentToolStep({ + item, +}: { + item: Extract; +}) { + return ( +
+
+ {item.pending ? ( + + ) : item.tone === "warning" ? ( + + ) : ( + + )} + {toolLabel(item)} +
+ {item.errorText ? ( +

+ {item.errorText} +

+ ) : null} + {hasAgentResult(item.tool) && item.pending + ? agentResultSkeleton(item.tool) + : null} +
+ ); +} + function appendEvent( events: readonly MessageStreamEvent[], event: MessageStreamEvent, @@ -707,130 +762,57 @@ function AssistantMessage({ if (item.kind === "said") textParts.push(item.text); } const markdown = textParts.join("\n\n"); - const activity = transcript.items.filter( - (item) => item.kind === "reasoned" || item.kind === "did", - ); - const reasoningCount = activity.filter( - (item) => item.kind === "reasoned", - ).length; - const toolCount = activity.filter((item) => item.kind === "did").length; - const dealResults = mergeDealListResultPages( - activity.flatMap((item) => { - if (item.kind !== "did" || item.tool !== "list_deals") return []; - const result = dealListResultOf(item.output); - return result ? [result] : []; - }), - ); - const dealMarkdown = - dealResults.length > 0 ? splitMarkdownTable(markdown) : null; - const streaming = - message.metadata?.status === "streaming" || - activity.some( - (item) => - (item.kind === "reasoned" && item.streaming) || - (item.kind === "did" && item.pending), - ); - const reasoningLabel = - reasoningCount > 0 && toolCount > 0 - ? "Reasoning and activity" - : reasoningCount > 0 - ? "Reasoning" - : "Activity"; + const results = agentResultsByItem(transcript.items); return (
- {activity.length > 0 ? ( - -
- {activity.map((item) => { - if (item.kind === "reasoned") { - return ( - - {item.text} - - ); - } - - return ( -
- {item.pending ? ( - - ) : item.tone === "warning" ? ( - - ) : ( - - )} - {item.label} -
- ); - })} -
-
- ) : null} - {dealMarkdown ? ( - <> - {dealMarkdown.before ? ( - - {dealMarkdown.before} - - ) : null} - {dealResults.map((result) => ( - - ))} - {dealMarkdown.after ? ( - - {dealMarkdown.after} - - ) : null} - {transcript.items.map((item) => - item.kind === "asked" && - (conversation === null || - answeredQuestionIds.has(item.question.requestId)) ? ( - - ) : null, - )} - - ) : ( - transcript.items.map((item) => { - if (item.kind === "said") { - const text = item.text; - if (!text) return null; - - return ( - - {text} + {transcript.items.map((item) => { + if (item.kind === "reasoned") { + return ( + + + {item.text} - ); - } + + ); + } - if (item.kind === "asked") { - return conversation === null || - answeredQuestionIds.has(item.question.requestId) ? ( - - ) : null; - } + if (item.kind === "did") { + return ( + + + {results.get(item.id)} + + ); + } + + if (item.kind === "said") { + const text = results.size > 0 ? withoutTable(item.text) : item.text; + if (!text) return null; + + return ( + + {text} + + ); + } - return null; - }) - )} + return conversation === null || + answeredQuestionIds.has(item.question.requestId) ? ( + + ) : null; + })} {markdown ? ( conversation ? ( toast.error("The agent could not be stopped. Try again."), }); + const writingPath = + artifacts.find((artifact) => artifact.status === "WRITING")?.path ?? null; + return ( -
-
-
- +
+
+
Building the agent - + {completed} of 4
-
    +
      {BUILDER_STEPS.map((label, index) => { const done = index < completed; const active = index === completed && completed < BUILDER_STEPS.length; + const artifact = BUILDER_STEP_ARTIFACTS[index]; return (
    1. - - {done ? ( - - ) : active ? ( - - ) : ( - index + 1 - )} - - - {label} - - - {done ? "Done" : active ? "Working" : "Queued"} - +
      + + {done ? ( + + ) : active ? ( + + ) : ( + index + 1 + )} + + + {label} + + + {done && artifact + ? artifact.replace("agent/", "") + : done + ? "Done" + : active + ? "Working" + : "Queued"} + +
      + {active && writingPath ? ( +

      + Writing {writingPath} +

      + ) : null}
    2. ); })}
    -
    +

    Runs in the background

    -
+ +
+ + + + + +
+ + + +
+
+ ); +} + +function AgentCardShell({ + name, + status, + children, +}: { + name: string; + status: string; + children: ReactNode; +}) { + return ( +
+
+

+ {name} +

+ {status}
+ {children} +
+ ); +} + +function AgentCardFooter({ + note, + children, +}: { + note: string; + children: ReactNode; +}) { + return ( +
+

{note}

+
{children}
); } @@ -1196,15 +1209,15 @@ function ReviewRow({ children, }: { label: string; - value?: string; + value?: ReactNode; children?: ReactNode; }) { return ( -
- +
+ {label} -
+
{children ?? value}
@@ -1246,33 +1259,16 @@ function DeployedAgentCard({ return (
-
+

{agent.name} is live.

I created the Eve agent, applied its bounded CRM and integration access, and scheduled its first run.

-
-
-
-
- -

- {agent.name} -

- Live -
-

- Team agent · created by {agent.createdBy.name} -

-
- -
-
- +
+ - - + +
-
-

- The chat remains private. The agent is now team-owned. -

- -
-
+ + + Run now + + + +
+ +

@@ -1351,30 +1345,6 @@ function DeployedAgentCard({ ); } -function DeployedStat({ - label, - value, - last = false, -}: { - label: string; - value: ReactNode; - last?: boolean; -}) { - return ( -

- {label} - - {value} - -
- ); -} - function ChatUnavailable() { const workspaceUrl = useWorkspaceUrl(); diff --git a/apps/app/components/agent-builder/agent-result.tsx b/apps/app/components/agent-builder/agent-result.tsx new file mode 100644 index 00000000..29ebcac4 --- /dev/null +++ b/apps/app/components/agent-builder/agent-result.tsx @@ -0,0 +1,93 @@ +import { Skeleton } from "@crm/ui/components/skeleton"; +import type { ReactNode } from "react"; +import { anchorResults } from "@/lib/agent-results"; +import { + type DealListResult, + dealListResultOf, + groupDealListPages, + type TranscriptItem, +} from "@/lib/agent-transcript"; +import { DealListResultTable } from "./deal-list-result"; + +type ResultEntry = { + anchor: (items: readonly TranscriptItem[]) => Map; + skeleton: ReactNode; +}; + +function defineResult({ + tool, + validate, + group, + render, + skeleton, +}: { + tool: string; + validate: (output: unknown) => T | null; + group?: ( + results: readonly { itemId: string; value: T }[], + ) => readonly { itemId: string; value: T }[]; + render: (result: T, key: string) => ReactNode; + skeleton: ReactNode; +}): ResultEntry { + return { + skeleton, + anchor: (items) => { + const anchored = anchorResults({ items, tool, validate, group }); + const rendered = new Map(); + + for (const [itemId, values] of anchored) { + rendered.set( + itemId, + values.map((value, index) => + render(value, `${tool}-${itemId}-${index}`), + ), + ); + } + + return rendered; + }, + }; +} + +const listSkeleton = ( +
+ + + + +
+); + +const REGISTRY: Record = { + list_deals: defineResult({ + tool: "list_deals", + validate: dealListResultOf, + group: groupDealListPages, + render: (result, key) => , + skeleton: listSkeleton, + }), +}; + +export function hasAgentResult(tool: string): boolean { + return tool in REGISTRY; +} + +export function agentResultSkeleton(tool: string): ReactNode { + return REGISTRY[tool]?.skeleton ?? null; +} + +export function agentResultsByItem( + items: readonly TranscriptItem[], +): Map { + const rendered = new Map(); + + for (const entry of Object.values(REGISTRY)) { + for (const [itemId, nodes] of entry.anchor(items)) { + const bucket = rendered.get(itemId); + if (bucket) bucket.push(...nodes); + else rendered.set(itemId, nodes); + } + } + + return rendered; +} diff --git a/apps/app/components/agent-builder/agent-scope-badges.tsx b/apps/app/components/agent-builder/agent-scope-badges.tsx index ac3bf0d2..7e30c874 100644 --- a/apps/app/components/agent-builder/agent-scope-badges.tsx +++ b/apps/app/components/agent-builder/agent-scope-badges.tsx @@ -1,4 +1,17 @@ import { Badge } from "@crm/ui/components/badge"; +import GoogleLogo from "@crm/ui/components/brand-logos/google"; +import SlackLogo from "@crm/ui/components/brand-logos/slack"; +import CompLogo from "@crm/ui/components/logo"; +import type { ComponentType, SVGProps } from "react"; + +const BRANDS: Array<{ + match: RegExp; + Logo: ComponentType>; +}> = [ + { match: /\bcrm\b/i, Logo: CompLogo }, + { match: /\bslack\b/i, Logo: SlackLogo }, + { match: /\b(gmail|google)\b/i, Logo: GoogleLogo }, +]; export function AgentScopeBadges({ scopes, @@ -12,17 +25,24 @@ export function AgentScopeBadges({ return (
- {uniqueScopes.map((scope) => ( - - {scope} - - ))} + {uniqueScopes.map((scope) => { + const brand = BRANDS.find((candidate) => candidate.match.test(scope)); + + return ( + + {brand ? ( + + ); + })}
); } diff --git a/apps/app/lib/agent-results.ts b/apps/app/lib/agent-results.ts new file mode 100644 index 00000000..b70410b4 --- /dev/null +++ b/apps/app/lib/agent-results.ts @@ -0,0 +1,36 @@ +import type { TranscriptItem } from "./agent-transcript"; + +export type AnchoredResult = { itemId: string; value: T }; + +export function anchorResults({ + items, + tool, + validate, + group, +}: { + items: readonly TranscriptItem[]; + tool: string; + validate: (output: unknown) => T | null; + group?: ( + results: readonly AnchoredResult[], + ) => readonly AnchoredResult[]; +}): Map { + const valid: AnchoredResult[] = []; + + for (const item of items) { + if (item.kind !== "did" || item.tool !== tool || item.pending) continue; + const value = validate(item.output); + if (value !== null) valid.push({ itemId: item.id, value }); + } + + const anchored = group ? group(valid) : valid; + const byAnchor = new Map(); + + for (const { itemId, value } of anchored) { + const bucket = byAnchor.get(itemId); + if (bucket) bucket.push(value); + else byAnchor.set(itemId, [value]); + } + + return byAnchor; +} diff --git a/apps/app/lib/agent-tool-display.ts b/apps/app/lib/agent-tool-display.ts new file mode 100644 index 00000000..90016b5b --- /dev/null +++ b/apps/app/lib/agent-tool-display.ts @@ -0,0 +1,41 @@ +const ARTIFACT_NAMES: Record = { + "agent/instructions.md": "instructions", + "agent/manifest.json": "the manifest", + "agent/README.md": "the readme", +}; + +type LabelInput = { + tool: string; + input: Record | null; + label: string; + pending: boolean; +}; + +const INPUT_LABELS: Record< + string, + (input: Record, pending: boolean) => string | null +> = { + write_agent_file: (input, pending) => { + const path = typeof input.path === "string" ? input.path : null; + if (!path) return null; + const name = ARTIFACT_NAMES[path] ?? path; + return pending ? `Writing ${name}` : `Wrote ${name}`; + }, + save_agent_draft: (input, pending) => { + const name = typeof input.name === "string" ? input.name.trim() : ""; + const verb = pending ? "Saving draft" : "Saved draft"; + return name ? `${verb} · ${name}` : verb; + }, + set_chat_title: (input, pending) => { + const title = typeof input.title === "string" ? input.title.trim() : ""; + const verb = pending ? "Naming this chat" : "Named this chat"; + return title ? `${verb} · ${title}` : verb; + }, +}; + +export function toolLabel(item: LabelInput): string { + const fromInput = item.input + ? INPUT_LABELS[item.tool]?.(item.input, item.pending) + : null; + return fromInput ?? item.label; +} diff --git a/apps/app/lib/agent-transcript.ts b/apps/app/lib/agent-transcript.ts index cc985657..8c8ef744 100644 --- a/apps/app/lib/agent-transcript.ts +++ b/apps/app/lib/agent-transcript.ts @@ -18,11 +18,13 @@ export type TranscriptItem = kind: "did"; id: string; label: string; + input: Record | null; output: unknown; tone: Tone; pending: boolean; sources: Source[]; tool: string; + errorText: string | null; }; export type Tone = "neutral" | "success" | "warning"; @@ -239,7 +241,9 @@ export function toTranscript( kind: "did", id, label: describe(part), + input: input(part), output: output(part), + errorText: errorTextOf(part), tone: outcomeTone(part), pending: state === "input-streaming" || @@ -382,6 +386,18 @@ function output(part: EveMessagePart): Record | null { : null; } +function input(part: EveMessagePart): Record | null { + return "input" in part && part.input && typeof part.input === "object" + ? (part.input as Record) + : null; +} + +function errorTextOf(part: EveMessagePart): string | null { + if (!("errorText" in part)) return null; + const text = part.errorText; + return typeof text === "string" && text.trim() ? text : null; +} + function recordOf(value: unknown): Record { return value && typeof value === "object" && !Array.isArray(value) ? (value as Record) @@ -474,6 +490,34 @@ export function dealListResultOf(value: unknown): DealListResult | null { }; } +export function groupDealListPages( + pages: readonly { itemId: string; value: DealListResult }[], +): { itemId: string; value: DealListResult }[] { + const groups = new Map< + string, + { itemId: string; value: DealListResult; order: number } + >(); + + for (const [index, page] of pages.entries()) { + const key = JSON.stringify(page.value.criteria); + const previous = groups.get(key); + const [merged] = mergeDealListResultPages( + previous ? [previous.value, page.value] : [page.value], + ); + if (!merged) continue; + + groups.set(key, { + itemId: page.itemId, + value: merged, + order: previous?.order ?? index, + }); + } + + return [...groups.values()] + .sort((left, right) => left.order - right.order) + .map(({ itemId, value }) => ({ itemId, value })); +} + export function mergeDealListResultPages( results: readonly DealListResult[], ): DealListResult[] { diff --git a/apps/app/test/agent-results.spec.ts b/apps/app/test/agent-results.spec.ts new file mode 100644 index 00000000..0e781baf --- /dev/null +++ b/apps/app/test/agent-results.spec.ts @@ -0,0 +1,125 @@ +import { describe, expect, it } from "bun:test"; +import { anchorResults } from "../lib/agent-results"; +import { + type DealListResult, + dealListResultOf, + groupDealListPages, + type TranscriptItem, +} from "../lib/agent-transcript"; + +const page = (status: string, ids: string[]) => ({ + asOf: "2026-08-07T00:00:00.000Z", + criteria: { + status, + inactiveForDays: null, + companyId: null, + ownerId: null, + }, + deals: ids.map((id) => ({ + id, + name: id, + stage: "Discovery", + amount: null, + currency: "USD", + company: { id: "c1", name: "Acme" }, + owner: null, + daysSinceLastActivity: 3, + expectedCloseDate: null, + })), +}); + +const did = ( + id: string, + output: unknown, + extra: Partial> = {}, +): TranscriptItem => ({ + kind: "did", + id, + label: "Listed deals", + input: null, + output, + errorText: null, + tone: "neutral", + pending: false, + sources: [], + tool: "list_deals", + ...extra, +}); + +const said = (id: string, text: string): TranscriptItem => ({ + kind: "said", + id, + mine: false, + text, +}); + +const anchorDeals = (items: readonly TranscriptItem[]) => + anchorResults({ + items, + tool: "list_deals", + validate: dealListResultOf, + group: groupDealListPages, + }); + +describe("anchorResults", () => { + it("leaves a finished result under its own call when a pending one follows", () => { + const anchored = anchorDeals([ + did("a", page("OPEN", ["d1"])), + did("b", null, { pending: true, output: null }), + ]); + + expect([...anchored.keys()]).toEqual(["a"]); + }); + + it("never anchors to a failed call", () => { + const anchored = anchorDeals([ + did("a", page("OPEN", ["d1"])), + did("b", { broken: true }, { tone: "warning", errorText: "Nope." }), + ]); + + expect([...anchored.keys()]).toEqual(["a"]); + }); + + it("keeps two different criteria under their own calls", () => { + const anchored = anchorDeals([ + did("a", page("OPEN", ["d1"])), + said("t", "And the won ones:"), + did("b", page("WON", ["d2"])), + ]); + + expect([...anchored.keys()]).toEqual(["a", "b"]); + expect(anchored.get("a")?.[0]?.criteria.status).toBe("OPEN"); + expect(anchored.get("b")?.[0]?.criteria.status).toBe("WON"); + }); + + it("anchors paginated pages of one criteria to the final page", () => { + const anchored = anchorDeals([ + did("a", page("OPEN", ["d1"])), + did("b", page("OPEN", ["d2"])), + ]); + + expect([...anchored.keys()]).toEqual(["b"]); + expect(anchored.get("b")?.[0]?.deals.map((deal) => deal.id)).toEqual([ + "d1", + "d2", + ]); + }); + + it("anchors pagination to the last valid page, not a later failure", () => { + const anchored = anchorDeals([ + did("a", page("OPEN", ["d1"])), + did("b", page("OPEN", ["d2"])), + did("c", { broken: true }), + ]); + + expect([...anchored.keys()]).toEqual(["b"]); + }); + + it("ignores calls belonging to another tool", () => { + const anchored = anchorDeals([ + did("a", page("OPEN", ["d1"]), { tool: "list_companies" }), + ]); + + expect(anchored.size).toBe(0); + }); +}); diff --git a/apps/app/test/agent-tool-display.spec.ts b/apps/app/test/agent-tool-display.spec.ts new file mode 100644 index 00000000..92fd7452 --- /dev/null +++ b/apps/app/test/agent-tool-display.spec.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from "bun:test"; +import { toolLabel } from "../lib/agent-tool-display"; + +const base = { label: "Ran a tool", pending: false }; + +describe("toolLabel", () => { + it("names the artifact a builder file write produced", () => { + expect( + toolLabel({ + ...base, + tool: "write_agent_file", + input: { path: "agent/instructions.md" }, + pending: true, + }), + ).toBe("Writing instructions"); + }); + + it("switches to the past tense once the write finished", () => { + expect( + toolLabel({ + ...base, + tool: "write_agent_file", + input: { path: "agent/manifest.json" }, + }), + ).toBe("Wrote the manifest"); + }); + + it("falls back to the raw path for an unmapped artifact", () => { + expect( + toolLabel({ + ...base, + tool: "write_agent_file", + input: { path: "agent/other.md" }, + }), + ).toBe("Wrote agent/other.md"); + }); + + it("labels the draft save under the tool the builder actually calls", () => { + expect( + toolLabel({ + ...base, + tool: "save_agent_draft", + input: { name: "Collections nudge" }, + }), + ).toBe("Saved draft · Collections nudge"); + }); + + it("keeps the generic label when the tool has no mapping", () => { + expect( + toolLabel({ ...base, tool: "web_search", input: { query: "acme" } }), + ).toBe("Ran a tool"); + }); + + it("keeps the generic label when the input is missing", () => { + expect(toolLabel({ ...base, tool: "write_agent_file", input: null })).toBe( + "Ran a tool", + ); + }); +}); diff --git a/apps/app/test/agent-transcript.spec.ts b/apps/app/test/agent-transcript.spec.ts index 09b4d006..147a9365 100644 --- a/apps/app/test/agent-transcript.spec.ts +++ b/apps/app/test/agent-transcript.spec.ts @@ -660,3 +660,61 @@ describe("every tool has a line of English", () => { } }); }); + +describe("tool call details", () => { + it("keeps the tool input so the label can describe the work", () => { + const [row] = toTranscript([ + message([ + tool("write_agent_file", { + input: { path: "agent/manifest.json" }, + output: {}, + }), + ]), + ]); + + expect(row?.items[0]).toMatchObject({ + kind: "did", + input: { path: "agent/manifest.json" }, + }); + }); + + it("surfaces the failure text instead of dropping it", () => { + const [row] = toTranscript([ + message([ + tool("write_agent_file", { + state: "output-error", + errorText: "Draft is closed.", + }), + ]), + ]); + + expect(row?.items[0]).toMatchObject({ + kind: "did", + errorText: "Draft is closed.", + }); + }); + + it("leaves errorText null when the call succeeded", () => { + const [row] = toTranscript([ + message([tool("write_agent_file", { output: {} })]), + ]); + + expect(row?.items[0]).toMatchObject({ kind: "did", errorText: null }); + }); + + it("keeps text, tools and text in the order they happened", () => { + const [row] = toTranscript([ + message([ + { type: "text", text: "Looking." }, + tool("write_agent_file", { input: { path: "a" }, output: {} }), + { type: "text", text: "Done." }, + ]), + ]); + + expect(row?.items.map((item) => item.kind)).toEqual([ + "said", + "did", + "said", + ]); + }); +}); diff --git a/packages/ui/src/components/badge.tsx b/packages/ui/src/components/badge.tsx index ca36ed7c..b5d6737e 100644 --- a/packages/ui/src/components/badge.tsx +++ b/packages/ui/src/components/badge.tsx @@ -20,6 +20,7 @@ const badgeVariants = cva( "hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50", link: "text-primary underline-offset-4 hover:underline", mono: "rounded-sm bg-muted font-mono font-normal text-muted-foreground", + token: "rounded-sm border-border font-normal text-foreground", }, }, defaultVariants: { diff --git a/packages/ui/src/components/dot-matrix.tsx b/packages/ui/src/components/dot-matrix.tsx new file mode 100644 index 00000000..60e4a6d0 --- /dev/null +++ b/packages/ui/src/components/dot-matrix.tsx @@ -0,0 +1,46 @@ +import { cn } from "@crm/ui/lib/utils"; + +const GRID = 5; +const CELLS = Array.from({ length: GRID * GRID }, (_, index) => index); +const CENTER = (GRID - 1) / 2; +const CYCLE_MS = 1400; + +function delayFor(index: number): number { + const row = Math.floor(index / GRID); + const column = index % GRID; + const distance = Math.max(Math.abs(row - CENTER), Math.abs(column - CENTER)); + return (distance / CENTER) * (CYCLE_MS / 2); +} + +export function DotMatrix({ + className, + label = "Loading", + decorative = false, +}: { + className?: string; + label?: string; + decorative?: boolean; +}) { + return ( + + {CELLS.map((index) => ( + + ))} + + ); +} diff --git a/packages/ui/src/components/logo.tsx b/packages/ui/src/components/logo.tsx index 99c1726c..503c32dd 100644 --- a/packages/ui/src/components/logo.tsx +++ b/packages/ui/src/components/logo.tsx @@ -7,8 +7,8 @@ const Logo = (props: React.SVGProps) => ( height={512} viewBox="0 0 512 512" fill="none" - {...props} aria-label="Comp AI Logo" + {...props} > Date: Sat, 8 Aug 2026 01:08:28 -0700 Subject: [PATCH 3/6] fix(agent): declare granted write actions in draft access summary (#93) Co-authored-by: grim <75869731+ripgrim@users.noreply.github.com> --- .../agent_builder/lib/draft-input.ts | 15 +++ apps/agent/test/custom-agent-runtime.spec.ts | 92 +++++++++++++++++++ 2 files changed, 107 insertions(+) diff --git a/apps/agent/agent/subagents/agent_builder/lib/draft-input.ts b/apps/agent/agent/subagents/agent_builder/lib/draft-input.ts index a25f2c43..e2d55ea5 100644 --- a/apps/agent/agent/subagents/agent_builder/lib/draft-input.ts +++ b/apps/agent/agent/subagents/agent_builder/lib/draft-input.ts @@ -45,6 +45,13 @@ export const builderDraftToolInput = z.object({ type BuilderDraftToolInput = z.infer; +const ACTIVITY_ACCESS = { + NOTE: "Write notes on CRM records", + TASK: "Create tasks on CRM records", +} as const; + +const ACTIVITY_ORDER = ["NOTE", "TASK"] as const; + const INTEGRATIONS = { gmail: { kind: "integration", id: "google:gmail", label: "Gmail" }, calendar: { @@ -59,6 +66,11 @@ export function draftInputFromTool( ): DraftAgentInput { const { integrations: requestedIntegrations, ...draft } = input; const integrations = [...new Set(requestedIntegrations)]; + const activityTypes = new Set( + input.actions.flatMap((entry) => + entry.type === "crm.activity.create" ? entry.activityTypes : [], + ), + ); const access = [ input.recordScope === "WORKSPACE" ? "Read workspace CRM records" @@ -68,6 +80,9 @@ export function draftInputFromTool( ? "Read connected Gmail messages" : "Read connected Google Calendar events", ), + ...ACTIVITY_ORDER.filter((type) => activityTypes.has(type)).map( + (type) => ACTIVITY_ACCESS[type], + ), ]; return { diff --git a/apps/agent/test/custom-agent-runtime.spec.ts b/apps/agent/test/custom-agent-runtime.spec.ts index fde444e8..c1e2d467 100644 --- a/apps/agent/test/custom-agent-runtime.spec.ts +++ b/apps/agent/test/custom-agent-runtime.spec.ts @@ -459,3 +459,95 @@ describe("agent builder draft input", () => { expect(parsed.actions[0]?.summary).toBe("Write a reviewable renewal brief"); }); }); + +describe("agent builder draft access", () => { + const draft = (actions: unknown[]) => + builderDraftToolInput.parse({ + name: "Handoff", + description: "Hand new customers to onboarding.", + instructions: + "Run on demand. Read closed-won deals and record the handoff for onboarding.", + trigger: { + type: "MANUAL", + name: "Run handoff", + summary: "Run for new customers", + }, + recordScope: "WORKSPACE", + resources: [], + integrations: [], + actions, + }); + + it("declares the writes a draft was granted, not just its reads", () => { + expect( + draftInputFromTool( + draft([ + { + type: "crm.activity.create", + provider: "crm", + summary: "Log the handoff brief", + activityTypes: ["NOTE", "TASK"], + }, + ]), + ).access, + ).toEqual([ + "Read workspace CRM records", + "Write notes on CRM records", + "Create tasks on CRM records", + ]); + }); + + it("only declares the activity types actually granted", () => { + expect( + draftInputFromTool( + draft([ + { + type: "crm.activity.create", + provider: "crm", + summary: "Log the handoff brief", + activityTypes: ["NOTE"], + }, + ]), + ).access, + ).toEqual(["Read workspace CRM records", "Write notes on CRM records"]); + }); + + it("keeps a read-only draft read-only", () => { + expect( + draftInputFromTool( + draft([ + { + type: "run.summary", + provider: "crm", + summary: "Return a run summary", + }, + ]), + ).access, + ).toEqual(["Read workspace CRM records"]); + }); + + it("does not repeat an activity type granted by two actions", () => { + expect( + draftInputFromTool( + draft([ + { + type: "crm.activity.create", + provider: "crm", + summary: "Log the handoff brief", + activityTypes: ["NOTE"], + }, + { + type: "crm.activity.create", + provider: "crm", + summary: "Log a follow-up", + activityTypes: ["NOTE", "TASK"], + }, + ]), + ).access, + ).toEqual([ + "Read workspace CRM records", + "Write notes on CRM records", + "Create tasks on CRM records", + ]); + }); +}); From 506074d1cb025a24dcdd9ed26794c47f975902a9 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 8 Aug 2026 19:49:00 -0400 Subject: [PATCH 4/6] chore(main): release 1.5.0 (#91) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- .github/.release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ package.json | 2 +- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/.github/.release-please-manifest.json b/.github/.release-please-manifest.json index 5c0ece22..8b4d9c87 100644 --- a/.github/.release-please-manifest.json +++ b/.github/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.4.0" + ".": "1.5.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 9916af4b..3ab95d52 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## [1.5.0](https://github.com/trycompai/crm/compare/v1.4.0...v1.5.0) (2026-08-08) + + +### Features + +* **agent:** bound agent builder retries and improve chat scrolling ([#89](https://github.com/trycompai/crm/issues/89)) ([7780f81](https://github.com/trycompai/crm/commit/7780f81a219813fcf54e6b5dd612a7d40e31d32b)) + + +### Fixes + +* **agent:** declare granted write actions in draft access summary ([#93](https://github.com/trycompai/crm/issues/93)) ([ad4f9f3](https://github.com/trycompai/crm/commit/ad4f9f31c81fd6bdad89abb6adb5a208d51c19ed)) +* **app:** render agent transcript chronologically with anchored tool results ([#92](https://github.com/trycompai/crm/issues/92)) ([0e68e45](https://github.com/trycompai/crm/commit/0e68e45909182c875ea58ba18fb89d9a87032e11)) + ## [1.4.0](https://github.com/trycompai/crm/compare/v1.3.0...v1.4.0) (2026-08-07) diff --git a/package.json b/package.json index 253e0a85..b8026d65 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "crm", "private": true, "license": "MIT", - "version": "1.4.0", + "version": "1.5.0", "scripts": { "prepare": "git rev-parse --git-dir >/dev/null 2>&1 && git config core.hooksPath .githooks || true", "build": "turbo run build", From f445c68a815ad1635498591daa494d18d9508ccf Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 8 Aug 2026 19:49:28 -0400 Subject: [PATCH 5/6] fix(api): warn when the deployed schema does not match schema.prisma (#88) Co-authored-by: Lewis Carhart --- apps/api/scripts/build-func.mjs | 47 ++++++++++++++++++++++++++++++--- docs/setup.md | 22 +++++++++++++++ 2 files changed, 66 insertions(+), 3 deletions(-) diff --git a/apps/api/scripts/build-func.mjs b/apps/api/scripts/build-func.mjs index 25740c26..ea6e1583 100644 --- a/apps/api/scripts/build-func.mjs +++ b/apps/api/scripts/build-func.mjs @@ -1,4 +1,4 @@ -import { execSync } from "node:child_process"; +import { execSync, spawnSync } from "node:child_process"; import { cpSync, existsSync, @@ -182,11 +182,52 @@ if (!process.env.VERCEL) { } else if (!directDatabaseUrl) { console.log("• no database URL at build time — skipping migrations"); } else { + const dbDir = join(repoRoot, "packages/db"); + const dbEnv = { ...process.env, DATABASE_URL: directDatabaseUrl }; + console.log("• applying migrations (prisma migrate deploy)..."); execSync(`${bun} x prisma migrate deploy`, { - cwd: join(repoRoot, "packages/db"), + cwd: dbDir, stdio: "inherit", - env: { ...process.env, DATABASE_URL: directDatabaseUrl }, + env: dbEnv, }); console.log("✓ migrations applied"); + + console.log("• checking the deployed schema against schema.prisma..."); + const drift = spawnSync( + bun, + [ + "x", + "prisma", + "migrate", + "diff", + "--from-config-datasource", + "--to-schema", + join("prisma", "schema.prisma"), + "--exit-code", + ], + { cwd: dbDir, encoding: "utf8", env: dbEnv }, + ); + + if (drift.status === 0) { + console.log("✓ schema matches"); + } else if (drift.status === 2) { + console.log(""); + console.log("!! THE PRODUCTION SCHEMA DOES NOT MATCH schema.prisma !!"); + console.log( + " Every migration is recorded as applied, so `migrate deploy` will keep reporting", + ); + console.log( + " nothing pending while queries fail on columns that are not there. Reconcile with", + ); + console.log( + " `prisma migrate diff --from-config-datasource --to-schema prisma/schema.prisma --script`.", + ); + console.log(""); + console.log(drift.stdout || ""); + } else { + console.log( + `• could not compare the schema (${drift.stderr?.trim() || "unknown error"})`, + ); + } } diff --git a/docs/setup.md b/docs/setup.md index a3e398b8..e953fcc0 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -113,6 +113,28 @@ builds, and the pages that touch them fail. Test schema changes locally, where worse: every preview applied its own migrations to the production database, so on 2026-08-07 the live schema ran six migrations ahead of the live code all day. +### `migrate deploy` is not proof the schema is right + +The build follows the deploy with `prisma migrate diff --exit-code` against +`schema.prisma` and shouts in the build log when they disagree. **`No pending +migrations to apply` only means `_prisma_migrations` has a row for every file** — +it says nothing about what the tables actually look like. + +They came apart once. A `prisma db push` shaped production from a laptop, the +migration rows were recorded as applied without their SQL ever running, and +`agentConversationAttachment` went live without its `position` column. Every deploy +reported nothing pending, for days, while `conversations.builderById` returned 500. +The tell is an object in the database that no migration defines — there was an +`agentConversationAttachment_submissionId_createdAt_idx` that appears in no +migration file, only in a `db push` of an older schema. + +Reconciling is one command, and it is worth reading before running: + +```sh +DATABASE_URL="…" bunx prisma migrate diff \ + --from-config-datasource --to-schema prisma/schema.prisma --script +``` + ## Secrets hygiene `.gitignore` ignores `.env` and `.env.*` with one negation for `.env.example`, so From 372a1a682452595661ff01da8c97bfe6d9f20712 Mon Sep 17 00:00:00 2001 From: grim <75869731+ripgrim@users.noreply.github.com> Date: Sat, 8 Aug 2026 16:49:52 -0700 Subject: [PATCH 6/6] CMP-62 chore: add gh-stack skill (#96) --- .agents/skills/gh-stack/SKILL.md | 183 ++++++++++++++++++ .../skills/gh-stack/references/commands.md | 179 +++++++++++++++++ .../gh-stack/references/stack-design.md | 97 ++++++++++ .../gh-stack/references/troubleshooting.md | 159 +++++++++++++++ 4 files changed, 618 insertions(+) create mode 100644 .agents/skills/gh-stack/SKILL.md create mode 100644 .agents/skills/gh-stack/references/commands.md create mode 100644 .agents/skills/gh-stack/references/stack-design.md create mode 100644 .agents/skills/gh-stack/references/troubleshooting.md diff --git a/.agents/skills/gh-stack/SKILL.md b/.agents/skills/gh-stack/SKILL.md new file mode 100644 index 00000000..96aab643 --- /dev/null +++ b/.agents/skills/gh-stack/SKILL.md @@ -0,0 +1,183 @@ +--- +name: gh-stack +description: > + Manages stacked PRs and splits multi-part work into reviewable branches with gh-stack. + Use for stack creation, viewing, edits, push, submit, sync, rebase, merge, or checkout; + when asked to split or isolate work for review; whenever a user mentions a stack, + branch layers, dependent PRs, or gh stack; or when a stack is checked out. +metadata: + author: github + version: "0.1.0" +--- + +# gh-stack + +`gh stack` is a [GitHub CLI](https://cli.github.com/) extension for stacked branches and pull +requests. A stack is an ordered chain of branches rooted on a trunk, where each branch has one PR +based on the branch below it, so a reviewer sees only that layer's diff. + +`gh stack` prints a stack trunk-first, left to right: + +``` +(main) <- auth <- api <- frontend +``` + +Left is the **bottom**, right is the **top**. `auth` is based on `main` and merges first; +`frontend` merges last. `up` moves toward the top, away from trunk; `down` moves toward it. +Foundational work belongs at the bottom, code that depends on it above. For how to choose the +layers, read `references/stack-design.md`. + +## Setup + +```bash +gh extension install github/gh-stack +git config rerere.enabled true # remember conflict resolutions +git config remote.pushDefault origin # required if the repo has more than one remote +``` + +## Non-interactive use + +`gh stack` branches on whether **stdout is a TTY**. Piped, most commands error cleanly or print +static text; under a PTY the same commands open a prompt or a full-screen TUI and block forever. +Agent harnesses differ, so always pass the flags below instead of relying on that detection. + +**Multiple remotes:** never run `push`, `submit`, `sync`, `rebase`, or `link` without +`--remote ` unless `remote.pushDefault` is configured. `checkout` and `trunk` have no +`--remote` flag and require the config. + +| Always run | Never run bare | Why | +|---|---|---| +| `gh stack view --json` | `gh stack view` | opens a TUI under a PTY | +| `gh stack submit --auto` | `gh stack submit` | prompts for a title per new PR | +| `gh stack merge --yes` | `gh pr merge` | `gh pr merge` cannot merge a stack | +| `gh stack init ...` | `gh stack init` | prompts for branch names | +| `gh stack add ` | `gh stack add` | prompts for a name, and fails even when piped | +| `gh stack checkout ` | `gh stack checkout` | opens a selection menu | +| `gh stack up` / `down` / `top` / `bottom` | `gh stack switch` | `switch` is menu-only | +| — | `gh stack modify` | TUI-only, no non-interactive path | + +- `view --short` is safe in both modes, but it is formatted for humans. Use `--json` to parse. +- **`checkout ` when a different local stack already covers those branches** cannot be forced. + Run `gh stack unstack --local` first (this keeps the stack on GitHub), then retry. + +## Branch placement + +- **Starting multi-part work:** create the stack before writing files. Do not implement every + concern on trunk and split it later. Put one dependent concern in each layer, bottom to top. +- **Editing an existing stack:** check out the layer that owns the change before editing. Never + commit a lower layer's concern on the current top branch. Run `gh stack view --json`; if + ownership is unclear, inspect `git log --all -- `. Then check out the owner, edit, commit, + rebase upstack, and return to top. + +```bash +gh stack down # or: gh stack checkout api +git add ... && git commit -m "Add get-user endpoint" +gh stack rebase --upstack # replay every branch above onto the change +gh stack top # return to where you were +gh stack push +``` + +## Core loop + +```bash +gh stack init auth # create the stack and check out its branch +git add ... && git commit -m "Add auth middleware" +gh stack add api # next layer, branched from the current one +git add ... && git commit -m "Add API routes" +gh stack submit --auto # push every branch and open draft PRs +gh stack view --json # confirm +``` + +Add `--open` to `submit` to create PRs ready for review instead of drafts. Branch names are +verbatim — `gh stack add refactor/foo` creates `refactor/foo`. + +## Staying in sync + +```bash +gh stack sync # fetch, reconcile with GitHub, rebase, push, refresh PR state +gh stack sync --prune # also delete local branches for merged PRs +``` + +Pruning never happens without `--prune` when non-interactive. If the local and remote stacks have +diverged, `sync` prints both chains, makes no changes, and exits 0 with `Sync aborted` — see +`references/troubleshooting.md`. + +## Merging + +Scope the merge with an argument: + +```bash +gh stack merge 42 --yes # PR #42 plus every unmerged PR below it +gh stack merge 7 --yes # every unmerged PR in stack #7 +gh stack merge 42 --yes --squash # or --merge, --rebase, --merge-method +``` + +Pass a PR number to merge that PR and every unmerged PR below it, or a stack number to merge every +unmerged PR in that stack. The operation is all-or-nothing: if any PR in that set cannot merge, +none do. + +Without a method flag the last-used method is reused. If the base branch uses a merge queue, the +stack is queued instead and the queue picks the method, ignoring any flag you passed with a +warning; queued PRs may land in separate groups. + +## Reading state + +`gh stack view --json` writes JSON to **stdout**. Status messages go to **stderr** — do not parse +them, branch on exit codes instead. + +``` +trunk string +currentBranch string +branches[] name, head, base, isCurrent, isMerged, isQueued, needsRebase +branches[].pr number, url, state ("OPEN" | "MERGED" | "QUEUED"); absent when no PR exists +``` + +`base` is the saved SHA of the parent branch that this branch was last known to contain. It may be +older than the parent's current tip. `needsRebase` is true when the current parent tip is no longer +an ancestor of the branch. + +## Exit codes + +| Code | Meaning | Recovery | +|---|---|---| +| 0 | Success | — | +| 1 | Generic error | Read stderr | +| 2 | Not in a stack | `gh stack init`, or `gh stack checkout ` | +| 3 | Rebase conflict | Follow the Exit 3 recovery below | +| 4 | GitHub API failure | Check `gh auth status`, retry | +| 5 | Invalid arguments | Fix the invocation; see ` --help` | +| 6 | Disambiguation required | Branch is in several stacks; check out a non-shared branch | +| 7 | Rebase already in progress | `gh stack rebase --continue` or `--abort` | +| 8 | Stack file locked | Another `gh stack` process is writing; retry after ~5s | +| 9 | Stacked PRs unavailable | Not enabled on the repository; tell the user | +| 10 | Modify recovery required | `gh stack modify --abort` | + +**Exit 3 recovery:** + +- After `gh stack rebase`: resolve the files, run `git add`, then + `gh stack rebase --continue`; use `gh stack rebase --abort` to restore the stack. +- After `gh stack sync`: the stack has already been restored. Run `gh stack rebase` to recreate the + conflict, then resolve and continue as above. + +## Constraints + +- Stacks are strictly linear: one parent, at most one child. Use separate stacks for parallel work. +- There is no non-interactive reorder or removal. Errors may suggest `gh stack modify`, but it is + TUI-only — restructure with `unstack` then `init` instead. +- PR titles and bodies are auto-generated. Use `gh pr edit` afterwards to change them. +- `checkout ` resolves against local stacks only. Use a stack or PR number to pull a + stack down from GitHub. + +## More detail + +`gh stack --help` is authoritative for flags and arguments. Note that +`gh stack help ` does **not** work — it prints the top-level help. + +Open the reference whose trigger matches the task; no need to preload all three. + +- `references/stack-design.md` — read before creating a stack, when deciding how many layers to + use, what belongs in each one, or whether work belongs in a new stack. +- `references/commands.md` — read when a command fails unexpectedly or you need its preconditions, + side effects, atomicity, or ordering guarantees. +- `references/troubleshooting.md` — read on a rebase conflict, after a squash-merge, on local and + remote divergence, when restructuring a stack, or when driving stacks from another tool. diff --git a/.agents/skills/gh-stack/references/commands.md b/.agents/skills/gh-stack/references/commands.md new file mode 100644 index 00000000..46e58336 --- /dev/null +++ b/.agents/skills/gh-stack/references/commands.md @@ -0,0 +1,179 @@ +# Command behavior + +`gh stack --help` is authoritative for flags and arguments. (`gh stack help ` only prints the top-level help.) This file only covers behavior `--help` does not +explain: preconditions, side effects, atomicity, and failure modes. + +## Contents + +- [init](#init) +- [add](#add) +- [push](#push) +- [submit](#submit) +- [link](#link) +- [sync](#sync) +- [rebase](#rebase) +- [view](#view) +- [checkout](#checkout) +- [unstack](#unstack) +- [merge](#merge) +- [Navigation](#navigation) + +## init + +Creates the stack and checks out the **last** branch in the list, so a single `init` can lay down +the whole chain: `gh stack init auth api frontend`. + +`init` processes branch arguments from bottom to top. Existing branches are adopted. If the first +branch does not exist, it is created from the trunk; each later new branch is created from the +branch immediately before it. There is no separate adopt mode — existence decides. `--base` +selects a non-default trunk. + +`init` also enables `git rerere`. Under a TTY the first run in a repo asks for confirmation; set +`git config rerere.enabled true` beforehand to skip it. + +## add + +- **Must run from the top branch** of the stack (or the trunk when the stack is still empty). + Anywhere else it exits **5** with `can only add branches on top of the stack`. Run `gh stack top` + first. +- **Uncommitted changes carry over.** Without `-Am`, `add` does not touch the working tree, so + staged and unstaged changes follow you onto the new branch. Commit or stash first for a clean start. +- **`add -Am` commits in place when the current branch has no commits yet** — for example + immediately after `init` — instead of creating a branch. This is deliberate: the first layer + usually needs its content before a second layer exists. +- `-A` and `-u` are mutually exclusive, and both require `-m`. + +## push + +Pushes every active (non-merged, non-queued) branch in one multi-ref push with per-branch +`--force-with-lease`. + +**Not atomic.** Some branches may update while another is rejected. A rejection means that branch +moved on the remote; fix that branch and rerun — rerunning is safe and skips what already landed. + +`push` never creates or updates pull requests. Use `submit` for that. + +## submit + +Pushes each active branch, then creates a PR for every branch that lacks one, basing it on the +first non-merged ancestor, then links them into a Stack on GitHub. + +- **Not atomic.** Branches are pushed sequentially with per-branch `--force-with-lease`. If a later + push is rejected, earlier pushes and PR updates stand. Fix the rejection and rerun the same command. +- **A fully merged stack cannot be extended.** When every PR in the current stack is already merged, + `submit` forks the remaining unmerged branches into a **new** stack rooted at the trunk and creates + it on GitHub, leaving the merged stack untouched. +- **Title generation with `--auto`:** a branch with a single commit uses that commit's subject as + the title and its body as the PR body. A branch with multiple commits humanizes the branch name + (hyphens and underscores become spaces). There is no flag for a custom title or body; use + `gh pr edit` afterwards. +- `--open` marks new *and existing* PRs ready for review; without it new PRs are drafts. +- Requires stacked PRs to be enabled on the repository. If not, `submit` exits **9** when + non-interactive (under a TTY it offers to create ordinary unstacked PRs instead). + +## link + +Creates or updates a stack on GitHub **without any local tracking state**. This is the path for +branches managed by another tool or living in another worktree — see `troubleshooting.md`. + +- Arguments are given bottom to top. Each is a branch name or a PR number; a numeric argument is + tried as a PR number first and falls back to a branch name. +- **A numeric first argument is treated as a stack number only when a stack with that number + exists.** In that case the remaining arguments are appended to the top of that stack and you do + not re-list its current PRs: `gh stack link 7 feature-c`. Arguments already in the stack are + skipped; arguments belonging to a different stack are rejected. +- Branch arguments are pushed automatically (non-force, atomic). Missing PRs are created with + auto-generated titles and correctly chained bases; existing PRs with a wrong base are corrected. +- Stack membership is **additive only** — `link` never removes a PR from a stack. + +## sync + +The routine command. Steps, in order: + +1. **Fetch** from the remote. +2. **Reconcile with the GitHub stack.** PRs added to the stack on github.com are pulled down and + appended locally. On divergence, aborts when non-interactive (see `troubleshooting.md`). +3. **Fast-forward the trunk.** Skipped when already current; warns when diverged. +4. **Cascade rebase when needed.** This runs if the trunk moved, a stack branch was fast-forwarded + from its remote, or a branch no longer contains its expected parent. Merged PRs are handled + automatically. On conflict, **all branches are restored** to their pre-rebase state and the + command exits **3**. +5. **Push** all active branches, atomically. +6. **Refresh PR state** from GitHub. +7. **Sync the stack object** — link open PRs into a stack, additively. Only when two or more PRs + exist. `sync` never opens PRs; that is `submit`. +8. **Prune** local branches for merged PRs, only when `--prune` is passed in a non-interactive + environment. + +## rebase + +Pulls from the remote and cascade-rebases. Use it when `sync` reported a conflict or when you need +to rebase only part of the stack. + +- `--upstack` rebases from the current branch to the top. This is what you run after editing a + lower layer. +- `--downstack` rebases from the trunk to the current branch. +- `--no-trunk` skips fetching and the trunk rebase entirely, aligning stack branches with each + other only. +- `--continue` after staging resolutions; `--abort` restores every branch. +- A merged PR is detected automatically and replayed with `--onto` against the correct target, so a + squash-merged parent does not produce spurious conflicts. +- Starting a rebase while one is in progress exits **7**. + +## view + +- `--json` writes the machine-readable payload to stdout. Its schema is in `SKILL.md`. +- Bare `view` opens a full-screen TUI when stdout is a TTY, and prints static text when piped. +- `--short` prints a compact one-line-per-branch summary and never opens the TUI, but it is + formatted for humans; parse `--json` instead. +- `view` refreshes PR state from GitHub as a side effect, best-effort — it does not fail when the + API is unreachable. + +## checkout + +Accepts a stack number, PR number, PR URL, or branch name. + +- A bare number resolves as a **stack number first**, then a PR number, then a branch name. +- Stack numbers, PR numbers, and PR URLs fetch from GitHub, pull the branches down, and set the + stack up locally. +- A **branch name resolves against locally tracked stacks only** and never contacts GitHub. Use a + stack or PR number to pull a stack that is not tracked locally. +- If a local stack already exists over those branches with a different composition, `checkout` + cannot be forced past it. Run `gh stack unstack --local` first, then retry. +- `checkout` has no flags. It relies on `remote.pushDefault` when several remotes exist. + +## unstack + +Removes the stack **grouping** only. It never deletes pull requests or branches. + +- With no argument it targets the active stack — the one containing the current branch — removing + it on GitHub and locally. +- With a stack number it works from anywhere in the repository, tracked locally or not, via the API. + Local tracking is also removed when present. +- `--local` removes local tracking only and never contacts GitHub. Combining `--local` with a stack + number that is not tracked locally is an error. +- An unknown stack number exits **2**. + +## merge + +- Scope with an argument: pass a PR number to merge that PR and every unmerged PR below it in the + stack, or pass a stack number to merge every unmerged PR in that stack. +- **All-or-nothing.** If any PR in that exact merge set cannot be merged, none are, and the reason + is reported. +- The method comes from `--squash`, `--rebase`, `--merge`, or `--merge-method `. Without + one, the last-used method is reused. +- Only basic PR state is checked before merging: open and not a draft. Bypassing merge requirements + is not supported for stacks. +- **A merge queue on the base branch overrides everything.** The stack is added to the queue rather + than merged; the queue chooses the method and any method flag you passed is ignored with a + warning. Queued PRs are submitted together but land as the queue processes them, so they may merge + in separate groups rather than all at once. +- `gh pr merge` cannot merge a stack. Always use `gh stack merge`. + +## Navigation + +`up`, `down`, `top`, `bottom`, and `trunk` are always non-interactive. `up` and `down` accept a +count (`gh stack up 3`). Movement clamps at the stack bounds, and merged branches are skipped when +navigating from an active branch, so `bottom` lands on the lowest *unmerged* branch. + +`gh stack switch` is a selection menu with no non-interactive path. Use the commands above instead. diff --git a/.agents/skills/gh-stack/references/stack-design.md b/.agents/skills/gh-stack/references/stack-design.md new file mode 100644 index 00000000..f64543ac --- /dev/null +++ b/.agents/skills/gh-stack/references/stack-design.md @@ -0,0 +1,97 @@ +# Designing a stack + +How to decide what goes in each layer. Read this before running `gh stack init`. + +## Contents + +- [Plan the layers before writing code](#plan-the-layers-before-writing-code) +- [Branch naming](#branch-naming) +- [Staging changes deliberately](#staging-changes-deliberately) +- [When to add a layer](#when-to-add-a-layer) +- [One stack, one story](#one-stack-one-story) + +## Plan the layers before writing code + +A stack is a dependency chain. If code in one layer depends on code in another, the dependency must +live in the same branch or a lower one. That constraint is much cheaper to satisfy by planning than +by restructuring later, because there is no non-interactive in-place reorder — fixing the order +means`unstack` and `init` again. + +Decide the layers first, then write code into them: + +``` +(main) <- todo-app/models <- todo-app/api <- todo-app/frontend <- todo-app/integration +``` + +- `todo-app/models` — shared types and schema +- `todo-app/api` — routes that use the models +- `todo-app/frontend` — components that call the routes +- `todo-app/integration` — tests exercising the whole feature + +This is illustrative. Infer the stack topic and layer names from the actual task; do not reuse +`todo-app` or these layer names literally. + +The failure mode to avoid is writing everything on one branch and trying to split it afterwards. +If a task is large enough to warrant a stack, create the stack at the start. + +## Branch naming + +Prefer a shared topic prefix plus the layer's concern: +`/` — for example, `billing/schema`, `billing/api`, `billing/ui`. +This keeps related branches recognizable without using generic names that could belong to any +stack. **User and repository branch naming conventions take precedence; follow them instead.** + +Names are used exactly as given — nothing is prepended or transformed, and slashes are kept, so +`gh stack add refactor/foo` creates a branch literally named `refactor/foo`. + +If you pass `-m` without a branch name, the name is generated from the commit message in +date-and-slug form (for example `03-24-add_api_routes`). Prefer naming the branch yourself. + +## Staging changes deliberately + +Use `git add` and `git commit` directly rather than the `add -Am` shortcut. The point is control +over which changes land in which branch. With several modified files in the working tree, stage the +subset that belongs to the current layer, commit it, then create the next branch and stage the rest +there: + +```bash +git add internal/models/user.go internal/models/session.go +git commit -m "Add user and session models" + +gh stack add api-routes +git add internal/api/routes.go internal/api/handlers.go +git commit -m "Add user API routes" +``` + +Multiple commits per branch are fine. What matters is that every commit in a branch serves the same +concern, and that a change belonging to a different concern goes in a different branch. + +Note that `gh stack add ` without `-Am` does not touch the working tree, so uncommitted +changes carry over to the new branch. Commit or stash first if you want the new layer to start clean. + +## When to add a layer + +Add a branch when you start a **different concern that depends on what you have built so far**. +Signals: + +- Moving from backend to frontend, or from core logic to tests or documentation +- The next changes have a different reviewer audience +- The current branch's diff is already large enough to review on its own + +A layer that cannot be described in one sentence is usually two layers. + +## One stack, one story + +A stack should read as a coherent progression: a reviewer walks the PRs bottom to top and sees the +feature being built. + +**Use a single stack** when every branch serves the same feature or project, even if the layers span +different concerns. + +**Start a separate stack** for unrelated work — a different feature, an unrelated bug fix, an +independent refactor. Do not mix efforts into one stack just because you happened to work on both. +Use `gh stack init` for the new effort, or `gh stack checkout ` to move between existing +stacks. + +A trivial incidental fix can ride along in the current stack. Once it grows into its own project, it +deserves its own stack. diff --git a/.agents/skills/gh-stack/references/troubleshooting.md b/.agents/skills/gh-stack/references/troubleshooting.md new file mode 100644 index 00000000..fc97b41a --- /dev/null +++ b/.agents/skills/gh-stack/references/troubleshooting.md @@ -0,0 +1,159 @@ +# Troubleshooting and recovery + +## Contents + +- [Rebase conflicts (exit 3)](#rebase-conflicts-exit-3) +- [After a squash merge](#after-a-squash-merge) +- [Local and remote stacks have diverged](#local-and-remote-stacks-have-diverged) +- [Restructuring a stack](#restructuring-a-stack) +- [Branch belongs to several stacks (exit 6)](#branch-belongs-to-several-stacks-exit-6) +- [Driving stacks from another tool or worktree](#driving-stacks-from-another-tool-or-worktree) +- [Stack file is locked (exit 8)](#stack-file-is-locked-exit-8) +- [An interrupted modify session (exit 10)](#an-interrupted-modify-session-exit-10) + +## Rebase conflicts (exit 3) + +`rebase` and `sync` both exit 3 on conflict. `sync` restores every branch to its pre-rebase state +first, so a failed `sync` leaves nothing half-applied; a failed `rebase` stops mid-flight and waits. + +```bash +gh stack rebase +# exit 3 — conflicted paths are listed on stderr +git add +gh stack rebase --continue # repeat if the next branch also conflicts +``` + +`gh stack rebase --abort` restores every branch in the stack, not just the current one. + +Because `init` enables `git rerere`, a conflict you resolve once is replayed automatically the next +time the same conflict appears — which is common, since a change low in the stack is rebased through +every branch above it. Without `rerere`, repeated conflicts may need manual resolution on each +affected layer. + +## After a squash merge + +A squash merge replaces the branch's commits with one new commit, so the originals no longer exist +in the trunk's history and an ordinary rebase would try to replay them again. + +`gh stack sync` detects this and rebases with `--onto` against the correct target, skipping the +merged branch: + +```bash +gh stack sync +gh stack view --json # merged branch reports "isMerged": true, "state": "MERGED" +``` + +No manual action is needed. If the replay conflicts, `sync` restores all branches and exits 3. +Run `gh stack rebase` to rerun the rebase, which will stop at the conflict and allow you to resolve +and then `--continue` until complete. Use `gh stack sync --prune` to also delete local branches for +merged PRs. + +## Local and remote stacks have diverged + +Divergence means the local stack and the stack on GitHub changed in different ways — for example +branches were added locally while a PR was added to the stack on github.com. + +When non-interactive, `sync` prints both chains, changes nothing, and exits **0** with +`Sync aborted`. Success here does not mean the sync happened; check for that message, or re-run +`gh stack view --json` and compare. + +Two resolution paths: + +- **Keep the remote version.** Drop local tracking and pull the stack back down. + + ```bash + gh stack unstack --local # keeps the stack on GitHub + gh stack checkout # or a PR number + ``` + +- **Keep the local version.** Remove the grouping on GitHub, then recreate it from local state. + + ```bash + gh stack unstack # removes the grouping; PRs and branches survive + gh stack submit --auto + ``` + +Neither path deletes pull requests or branches. +Remote unstacking leaves PRs that are merging (auto-merge enabled) or are queued (in a merge queue) +stacked. If needed, clear that state before retrying. + +## Restructuring a stack + +There is no non-interactive reorder, rename, or removal. `add` run from the wrong branch suggests +`gh stack modify`, but that is TUI-only. Tear the stack down and rebuild it instead: + +```bash +gh stack unstack # removes local tracking and the GitHub grouping +# Rename or drop branches, and rewrite ancestry as needed. +gh stack init --base main branch-1 branch-2 branch-3 +gh stack submit --auto # re-link on GitHub +``` + +`init` adopts branches that already exist, so the rebuild reuses them rather than creating new ones. +Existing PRs survive. Once Git ancestry is correct, `submit` updates their base branches and +re-links the stack on GitHub. + +Changing metadata does **not** change Git ancestry. Reorder commits first, then rebuild the stack. +For example, to change `main <- models <- migration <- ui` into +`main <- migration <- models <- ui`: + +```bash +old_models=$(git rev-parse models) +old_migration=$(git rev-parse migration) +git rebase --onto main "$old_models" migration +git rebase --onto migration main models +git rebase --onto models "$old_migration" ui +gh stack unstack +gh stack init --base main migration models ui +``` + +The first rebase moves migration-only commits onto trunk, the second replays model commits above +them, and the third replays UI-only commits above models. Preserve the old boundary SHAs before +moving any branch. For a different reorder, identify each layer's range with +`git log ..`, then replay the ranges bottom to top. + +## Branch belongs to several stacks (exit 6) + +Commands exit 6 when the current branch cannot identify a single stack — typically because it is the +trunk of more than one stack. There is no flag to disambiguate. + +```bash +gh stack checkout +``` + +Then rerun. Commands that take an explicit stack number (`merge 7`, `unstack 7`) sidestep the +problem entirely, since they do not infer the stack from the current branch. + +## Driving stacks from another tool or worktree + +`gh stack link` creates and updates stacks purely through the API, with no local tracking state. +Use it when branches are managed by jj, Sapling, git-town, a separate worktree, or any workflow +where the local `.git/gh-stack` file would be wrong or absent. + +```bash +gh stack link branch-a branch-b branch-c # bottom to top +gh stack link --base develop --open a b c # non-default trunk, ready for review +gh stack link 10 20 30 # by PR number +gh stack link 7 feature-d # append to existing stack #7 +``` + +Because `link` writes no local state, the local navigation commands (`up`, `down`, `top`, `bottom`) +will not work on the result. Use `gh stack checkout ` if you later want local tracking. + +## Stack file is locked (exit 8) + +Another `gh stack` process holds the exclusive lock on `.git/gh-stack.lock`. The lock times out +after about five seconds, so wait and retry. A persistent exit 8 means another process still holds +the lock; identify and stop that process before retrying. + +## An interrupted modify session (exit 10) + +`gh stack modify` is TUI-only and should never be invoked by an agent. If a repository is left in +this state by someone else, restore it: + +```bash +gh stack modify --abort +``` + +Related: `submit` also detects a pending modify state, and under a TTY asks before overwriting the +stack on GitHub with local state.