diff --git a/AGENTS.md b/AGENTS.md index 82109058..233981fe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -426,3 +426,5 @@ Three tools for launching, monitoring, and cancelling detached background jobs. - **ADL is an append-log, not a document row.** Read it with `goop_adl({ action: "read" })`. `goop_read_db({ doc_type: "adl" })` returns "No adl document found" — the ADL is stored as structured events, not a full document. - **`goop_write_wave` accepts `verifications[]` and `traceability[]` in two forms, and the distinction matters.** With `task_updates[]` (the common case), supply them as top-level fields — they are processed atomically alongside task updates. With `items[]`, supply them **per-item** — each `items[]` entry can carry its own `verifications[]` and `traceability[]`. A traceability row omitting `wave_number` inherits the enclosing item's wave; an explicit value overrides. A verification omitting `wave_id` defaults to the enclosing item's resolved wave row; an explicit id wins. Everything is written in one transaction — any failure rolls back rows *and* events, so no orphan events survive. Supplying top-level `verifications`/`traceability` **alongside** `items[]` is rejected deliberately, because those payloads would otherwise be silently dropped. + +- **Compaction hook replaces `output.prompt`, does not append to `output.context`.** The `experimental.session.compacting` hook (V1-only) overwrites `output.prompt` with a bounded continuation prompt from the shared formatter (`src/shared/continuation-prompt.ts`). `output.prompt` is last-writer-wins — earlier prompt content is not preserved or merged. `output.context` is never touched by the hook; if the host does not read `output.context` after compaction, context entries from other hooks are silently discarded. The hook stands down without mutating either field when no valid workflow can be resolved. diff --git a/packages/opencode-plugin/references/core-protocol.md b/packages/opencode-plugin/references/core-protocol.md index 1c11ccfc..0fa48cb7 100644 --- a/packages/opencode-plugin/references/core-protocol.md +++ b/packages/opencode-plugin/references/core-protocol.md @@ -64,7 +64,9 @@ When `goop_compact` queues a compaction, it captures a `CompactionHandoffSnapsho - The `next_step` string provided by the caller. - A `capturedAtMs` timestamp. -This snapshot is stored in the in-process `compactionHandoff` map keyed by session ID. When the compaction survival hook fires (`experimental.session.compacting`), it reads the snapshot, reconciles the active workflow binding (rebinding to the snapshot's workflow if the live binding has drifted), and builds a survival block that is pushed into `output.context`. The snapshot is consumed once and deleted. +This snapshot is stored in the in-process `compactionHandoff` map keyed by session ID. When the compaction survival hook fires (`experimental.session.compacting`), it reads the snapshot, reconciles the active workflow binding (rebinding to the snapshot's workflow if the live binding has drifted), and **replaces `output.prompt`** with a bounded continuation prompt built by the shared formatter (`src/shared/continuation-prompt.ts`). The hook does not append to `output.context`; the snapshot is consumed once and deleted. + +**`output.prompt` is last-writer-wins.** The compaction hook overwrites any prompt content the host or an earlier hook placed in `output.prompt`; earlier content is not preserved or merged. `output.context` is never modified by the hook — if the host does not read `output.context` after compaction, any context entries pushed by other hooks are silently discarded. The hook stands down without mutating either field when no valid workflow can be resolved. ### Pre-Flush Before Compaction diff --git a/packages/opencode-plugin/src/core/hooks-v2.test.ts b/packages/opencode-plugin/src/core/hooks-v2.test.ts index 6b30c045..55333e29 100644 --- a/packages/opencode-plugin/src/core/hooks-v2.test.ts +++ b/packages/opencode-plugin/src/core/hooks-v2.test.ts @@ -361,6 +361,35 @@ describe("registerHooksV2()", () => { env.cleanup(); }); + it("keeps experimental.session.compacting in the V2 skipped list and registers no compaction capability (AD8, NFR4)", async () => { + const ctx = createMockPluginContext(); + contexts.push(ctx); + const registrations: Registrations = { + agentTransforms: 0, + catalogTransforms: 0, + agentReloads: 0, + catalogReloads: 0, + }; + const runtimeCtx = createRuntimeContext(registrations); + const session = runtimeCtx.session; + const tool = runtimeCtx.tool; + if (!session || !tool) throw new Error("test setup: session and tool must be present"); + const sessionHookSpy = spyOn(session, "hook"); + const toolHookSpy = spyOn(tool, "hook"); + + await registerHooksV2(runtimeCtx, ctx); + + // AD8/NFR4: experimental.session.compacting is V1-only. The V2 adapter + // must never register a compaction handler with either runtime capability. + const sessionEvents = sessionHookSpy.mock.calls.map((call) => call[0]); + expect(sessionEvents).not.toContain("experimental.session.compacting"); + expect(sessionEvents).toEqual(["request"]); + + const toolEvents = toolHookSpy.mock.calls.map((call) => call[0]); + expect(toolEvents).not.toContain("experimental.session.compacting"); + expect(toolEvents).toEqual(expect.arrayContaining(["execute.before", "execute.after"])); + }); + it("logs the V2 lazy-autopilot limitation without claiming a fallback", async () => { const ctx = createMockPluginContext(); contexts.push(ctx); diff --git a/packages/opencode-plugin/src/core/tools-v2.test.ts b/packages/opencode-plugin/src/core/tools-v2.test.ts index fea1de2b..920d8d24 100644 --- a/packages/opencode-plugin/src/core/tools-v2.test.ts +++ b/packages/opencode-plugin/src/core/tools-v2.test.ts @@ -75,6 +75,24 @@ describe("registerToolsV2()", () => { expect(registrations).toHaveLength(38); }); + it("omits goop_compact when client.session exists but summarize is not a function (NFR4)", async () => { + const ctx = createMockPluginContext(); + contexts.push(ctx); + // The capability gate checks typeof client.session.summarize === "function". + // A session object without summarize must still be treated as incapable. + Object.defineProperty(ctx.sdk, "client", { + configurable: true, + value: { session: {} }, + }); + const registrations: V2ToolDefinition[] = []; + + await registerToolsV2(createRuntimeContext(registrations), ctx); + + const names = registrations.map((definition) => definition.name); + expect(names).not.toContain("goop_compact"); + expect(names).toContain("goop_status"); + }); + it("converts goop_status arguments with Zod's native JSON Schema support", () => { const ctx = createMockPluginContext(); contexts.push(ctx); diff --git a/packages/opencode-plugin/src/core/types.ts b/packages/opencode-plugin/src/core/types.ts index 6cf9114e..fcd8cc13 100644 --- a/packages/opencode-plugin/src/core/types.ts +++ b/packages/opencode-plugin/src/core/types.ts @@ -92,10 +92,34 @@ export interface PendingLazyAutopilotNudge { source: "prompt-async" | "system-transform"; } +/** + * A single task row projected into a compaction handoff snapshot. + */ +export interface CompactionHandoffTask { + readonly index: number; + readonly description: string; + readonly status: string; + readonly agent: string | undefined; +} + +/** + * A single open blocker projected into a compaction handoff snapshot. + */ +export interface CompactionHandoffBlocker { + readonly id: number; + readonly severity: string; + readonly description: string; +} + /** * Durable-in-memory workflow context captured when a compaction is queued. * `nextStep` remains directly consumable by the compaction hook rather than * requiring consumers to decode an opaque serialized payload. + * + * The optional fields (`currentWaveTitle` … `prUrl`) are populated from the + * GoopSpecDB at queue time when the current wave has a row. They are + * `undefined` when the DB is empty, the current wave is 0, or a DB accessor + * throws. The core fields are always present on a valid snapshot. */ export interface CompactionHandoffSnapshot { readonly workflowId: string; @@ -112,6 +136,12 @@ export interface CompactionHandoffSnapshot { readonly branch: string | undefined; readonly nextStep: string; readonly capturedAtMs: number; + readonly currentWaveTitle?: string; + readonly currentWaveStatus?: string; + readonly tasks?: ReadonlyArray; + readonly openBlockers?: ReadonlyArray; + readonly prBranch?: string; + readonly prUrl?: string; } // --------------------------------------------------------------------------- diff --git a/packages/opencode-plugin/src/hooks/compaction-hook.test.ts b/packages/opencode-plugin/src/hooks/compaction-hook.test.ts index 6fdc7f33..d30a1872 100644 --- a/packages/opencode-plugin/src/hooks/compaction-hook.test.ts +++ b/packages/opencode-plugin/src/hooks/compaction-hook.test.ts @@ -4,232 +4,24 @@ import { createDefaultWorkflowState, createMockCompactionHandoff, createMockPluginContext, - setupTestEnvironment, } from "../test-utils.js"; -import { - MAX_NEXT_STEP_CHARS, - buildWorkflowSurvivalBlock, - createCompactionHook, -} from "./compaction-hook.js"; +import { createCompactionHook } from "./compaction-hook.js"; // --------------------------------------------------------------------------- -// buildWorkflowSurvivalBlock +// createCompactionHook — replacement contract (output.prompt, not output.context) // --------------------------------------------------------------------------- -describe("buildWorkflowSurvivalBlock", () => { - it("includes phase, workflow id, and wave progress", () => { - const ctx = createMockPluginContext({ - state: { - activeWorkflowId: "feat-auth", - workflows: { - "feat-auth": createDefaultWorkflowState({ - phase: "execute", - mode: "standard", - depth: "deep", - specLocked: true, - interviewComplete: true, - acceptanceConfirmed: true, - currentWave: 3, - totalWaves: 5, - }), - }, - }, - }); - - const block = buildWorkflowSurvivalBlock(ctx); - - expect(block).toContain("feat-auth"); - expect(block).toContain("EXECUTE"); - expect(block).toContain("execute"); - expect(block).toContain("standard"); - expect(block).toContain("deep"); - expect(block).toContain("Spec Locked: yes"); - expect(block).toContain("Interview Complete: yes"); - expect(block).toContain("Acceptance Confirmed: yes"); - expect(block).toContain("Lazy Autopilot: false"); - expect(block).toContain("Wave: 3 of 5"); - }); - - it("includes autopilot directive when autopilot is true", () => { - const ctx = createMockPluginContext({ - state: { - activeWorkflowId: "default", - workflows: { - default: createDefaultWorkflowState({ - phase: "execute", - autopilot: true, - }), - }, - }, - }); - - const block = buildWorkflowSurvivalBlock(ctx); - - expect(block).toContain("AUTOPILOT ACTIVE"); - expect(block).toContain("Continue to the next phase immediately"); - expect(block).toContain("Hard stops still apply per phase-gates"); - expect(block).toContain("AUTOPILOT SESSION RULES"); - }); - - it("includes lazy autopilot directives when lazyAutopilot is true", () => { - const ctx = createMockPluginContext({ - state: { - activeWorkflowId: "default", - workflows: { - default: createDefaultWorkflowState({ - phase: "execute", - autopilot: true, - lazyAutopilot: true, - }), - }, - }, - }); - - const block = buildWorkflowSurvivalBlock(ctx); - - expect(block).toContain("LAZY AUTOPILOT ACTIVE"); - expect(block).toContain("Do NOT ask the user any questions"); - expect(block).toContain( - "ONLY stop for: (1) missing credentials/secrets, (2) ambiguous destructive/irreversible operations.", - ); - expect(block).toContain( - "On a Rule 4 architectural decision, decide autonomously using best judgment.", - ); - expect(block).toContain("Log full rationale to ADL via goop_adl"); - // Old stop-list items should NOT appear in the ONLY-stop-for list - expect(block).not.toContain("external blockers"); - // "Rule 4" appears in the autonomous-decision sentence, not in the stop list - expect(block).toContain("AUTOPILOT SESSION RULES"); - expect(block).toContain("Do NOT warn about context length or token limits"); - // Lazy mode must NOT re-emit the regular autopilot Rule-4-as-stop wording - expect(block).not.toContain("Hard stops still apply per phase-gates: Rule 4"); - }); - - it("omits autopilot directives when autopilot is false", () => { - const ctx = createMockPluginContext({ - state: { - activeWorkflowId: "default", - workflows: { - default: createDefaultWorkflowState({ - phase: "execute", - autopilot: false, - lazyAutopilot: false, - }), - }, - }, - }); - - const block = buildWorkflowSurvivalBlock(ctx); - - expect(block).not.toContain("AUTOPILOT ACTIVE"); - expect(block).not.toContain("LAZY AUTOPILOT ACTIVE"); - expect(block).not.toContain("AUTOPILOT SESSION RULES"); - }); - - it("includes a declared next step only when non-empty", () => { - const ctx = createMockPluginContext(); - - expect(buildWorkflowSurvivalBlock(ctx, undefined, "Resume wave verification.")).toContain( - "IMMEDIATE NEXT STEP (declared before compaction): Resume wave verification.", - ); - expect(buildWorkflowSurvivalBlock(ctx)).not.toContain("IMMEDIATE NEXT STEP"); - expect(buildWorkflowSurvivalBlock(ctx, undefined, " ")).not.toContain("IMMEDIATE NEXT STEP"); - }); - - it("collapses whitespace and bounds an oversized next step", () => { - const ctx = createMockPluginContext(); - const block = buildWorkflowSurvivalBlock( - ctx, - undefined, - ` Review\n\n ${"changes ".repeat(40)}then verify. `, - ); - const line = block.split("\n").find((value) => value.startsWith("IMMEDIATE NEXT STEP")); - const prefix = "IMMEDIATE NEXT STEP (declared before compaction): "; - - expect(line).toBeDefined(); - expect(line).not.toContain("\n"); - expect(line).not.toMatch(/\s{2,}/); - expect(line?.slice(prefix.length).length).toBeLessThanOrEqual(MAX_NEXT_STEP_CHARS); - expect(line?.endsWith("…")).toBeTrue(); - }); - - it("includes document pointers for re-hydration", () => { - const ctx = createMockPluginContext({ - state: { - activeWorkflowId: "feat-auth", - workflows: { - "feat-auth": createDefaultWorkflowState({ phase: "plan" }), - }, - }, - }); - - const block = buildWorkflowSurvivalBlock(ctx); - - expect(block).toContain(".goopspec/feat-auth/SPEC.md"); - expect(block).toContain(".goopspec/feat-auth/BLUEPRINT.md"); - expect(block).toContain(".goopspec/feat-auth/CHRONICLE.md"); - expect(block).toContain("goop_status"); - }); - - it("uses root .goopspec/ path for default workflow", () => { - const ctx = createMockPluginContext({ - state: { - activeWorkflowId: "default", - workflows: { - default: createDefaultWorkflowState({ phase: "idle" }), - }, - }, - }); - - const block = buildWorkflowSurvivalBlock(ctx); - - expect(block).toContain(".goopspec/SPEC.md"); - expect(block).not.toContain(".goopspec/default/"); - }); - - it("returns empty string when active workflow is missing", () => { - const ctx = createMockPluginContext({ - state: { - activeWorkflowId: "nonexistent", - workflows: {}, - }, - }); - - const block = buildWorkflowSurvivalBlock(ctx); - expect(block).toBe(""); - }); - - it("includes all four newly reported identity fields", () => { - const ctx = createMockPluginContext({ - state: { - activeWorkflowId: "feat-auth", - workflows: { - "feat-auth": createDefaultWorkflowState({ - phase: "execute", - interviewComplete: true, - acceptanceConfirmed: true, - lazyAutopilot: true, - }), - }, - }, - }); - - const block = buildWorkflowSurvivalBlock(ctx); - - expect(block).toContain("Interview Complete: yes"); - expect(block).toContain("Acceptance Confirmed: yes"); - expect(block).toContain("Lazy Autopilot: true"); - // Branch is live-state-only here and mock context has no branch, so it is omitted. - expect(block).not.toContain("Git Branch:"); - }); +describe("createCompactionHook", () => { + // --- Replacement contract: prompt is set, context is untouched --- - it("includes the git branch from a snapshot", () => { + it("sets a non-empty prompt from a valid snapshot with sanitized next step and leaves context empty", async () => { const ctx = createMockPluginContext({ state: { activeWorkflowId: "feat-auth", workflows: { "feat-auth": createDefaultWorkflowState({ phase: "execute", + specLocked: true, currentWave: 2, totalWaves: 4, }), @@ -249,113 +41,77 @@ describe("buildWorkflowSurvivalBlock", () => { totalWaves: 4, autopilot: false, lazyAutopilot: false, - branch: "fix/compaction-state-handoff", - nextStep: "Continue implementation.", + branch: "feat/auth", + nextStep: " Review\n the hook changes. ", capturedAtMs: Date.now(), }; + ctx.compactionHandoff.set("s1", snapshot); - const block = buildWorkflowSurvivalBlock(ctx, snapshot, snapshot.nextStep); + const hooks = createCompactionHook(ctx); + const output: { context: string[]; prompt?: string } = { context: [] }; + await hooks["experimental.session.compacting"]?.({ sessionID: "s1" }, output); - expect(block).toContain("Git Branch: fix/compaction-state-handoff"); + expect(output.prompt).toBeDefined(); + expect(output.prompt).not.toBe(""); + expect(output.prompt).toContain("feat-auth"); + expect(output.prompt).toContain("execute"); + // Whitespace collapsed by the sanitizer + expect(output.prompt).toContain("1. Review the hook changes."); + // Context is unchanged (empty) + expect(output.context).toHaveLength(0); }); - it("prefers snapshot values over live state when a snapshot is provided", () => { + it("derives the goop_status directive when only live state is available", async () => { const ctx = createMockPluginContext({ state: { activeWorkflowId: "feat-auth", workflows: { "feat-auth": createDefaultWorkflowState({ - phase: "plan", - mode: "standard", - depth: "standard", - specLocked: false, - interviewComplete: false, - acceptanceConfirmed: false, - currentWave: 0, - totalWaves: 0, - autopilot: false, - lazyAutopilot: false, + phase: "execute", + specLocked: true, + currentWave: 2, + totalWaves: 4, }), }, }, }); - const snapshot: CompactionHandoffSnapshot = { - workflowId: "feat-auth", - phase: "execute", - mode: "comprehensive", - depth: "deep", - specLocked: true, - interviewComplete: true, - acceptanceConfirmed: true, - currentWave: 2, - totalWaves: 5, - autopilot: true, - lazyAutopilot: true, - branch: "feat/snapshot-source", - nextStep: "Proceed from snapshot.", - capturedAtMs: Date.now(), - }; + const hooks = createCompactionHook(ctx); + const output: { context: string[]; prompt?: string } = { context: [] }; + await hooks["experimental.session.compacting"]?.({ sessionID: "s1" }, output); - const block = buildWorkflowSurvivalBlock(ctx, snapshot, snapshot.nextStep); - - expect(block).toContain("Active Workflow: feat-auth"); - expect(block).toContain("EXECUTE"); - expect(block).toContain("Mode: comprehensive"); - expect(block).toContain("Depth: deep"); - expect(block).toContain("Spec Locked: yes"); - expect(block).toContain("Interview Complete: yes"); - expect(block).toContain("Acceptance Confirmed: yes"); - expect(block).toContain("Wave: 2 of 5"); - expect(block).toContain("Git Branch: feat/snapshot-source"); - expect(block).toContain("Lazy Autopilot: true"); - expect(block).toContain("LAZY AUTOPILOT ACTIVE"); - expect(block).toContain( - "IMMEDIATE NEXT STEP (declared before compaction): Proceed from snapshot.", - ); + expect(output.prompt).toBeDefined(); + expect(output.prompt).toContain("goop_status"); + expect(output.prompt).toContain("derive the gate-appropriate action"); + expect(output.context).toHaveLength(0); }); - it("falls back to live state when no snapshot is provided", () => { + it("leaves both output fields untouched when no active workflow exists", async () => { const ctx = createMockPluginContext({ state: { - activeWorkflowId: "live-wf", - workflows: { - "live-wf": createDefaultWorkflowState({ - phase: "execute", - mode: "standard", - depth: "deep", - specLocked: true, - interviewComplete: true, - acceptanceConfirmed: true, - currentWave: 4, - totalWaves: 6, - autopilot: true, - lazyAutopilot: false, - }), - }, + activeWorkflowId: "ghost", + workflows: {}, }, }); - const block = buildWorkflowSurvivalBlock(ctx); + const hooks = createCompactionHook(ctx); + const output: { context: string[]; prompt?: string } = { context: [] }; + await hooks["experimental.session.compacting"]?.({ sessionID: "s1" }, output); - expect(block).toContain("Active Workflow: live-wf"); - expect(block).toContain("EXECUTE"); - expect(block).toContain("Depth: deep"); - expect(block).toContain("Spec Locked: yes"); - expect(block).toContain("Interview Complete: yes"); - expect(block).toContain("Acceptance Confirmed: yes"); - expect(block).toContain("Wave: 4 of 6"); - expect(block).toContain("Lazy Autopilot: false"); + expect(output.prompt).toBeUndefined(); + expect(output.context).toHaveLength(0); }); - it("rebinds live active workflow to snapshot workflow when they diverge", () => { + // --- Snapshot fallback paths --- + + it("logs and falls back to live state for a malformed snapshot", async () => { const ctx = createMockPluginContext({ state: { - activeWorkflowId: "live-wf", + activeWorkflowId: "feat-auth", workflows: { - "live-wf": createDefaultWorkflowState({ phase: "plan" }), - "snapshot-wf": createDefaultWorkflowState({ + "feat-auth": createDefaultWorkflowState({ phase: "execute", + specLocked: true, currentWave: 2, totalWaves: 4, }), @@ -363,32 +119,23 @@ describe("buildWorkflowSurvivalBlock", () => { }, }); - const snapshot: CompactionHandoffSnapshot = { - workflowId: "snapshot-wf", - phase: "execute", - mode: "standard", - depth: "standard", - specLocked: true, - interviewComplete: true, - acceptanceConfirmed: true, - currentWave: 2, - totalWaves: 4, - autopilot: false, - lazyAutopilot: false, - branch: undefined, - nextStep: "Resume from snapshot workflow.", - capturedAtMs: Date.now(), - }; + const consoleSpy = spyOn(console, "error").mockImplementation(() => {}); + ctx.compactionHandoff.set("s1", { nextStep: "incomplete" } as never); - const block = buildWorkflowSurvivalBlock(ctx, snapshot, snapshot.nextStep); + const hooks = createCompactionHook(ctx); + const output: { context: string[]; prompt?: string } = { context: [] }; + await hooks["experimental.session.compacting"]?.({ sessionID: "s1" }, output); - expect(block).toContain("Active Workflow: snapshot-wf"); - expect(block).toContain("EXECUTE"); - expect(block).toContain("Wave: 2 of 4"); - expect(ctx.stateManager.getActiveWorkflowId()).toBe("snapshot-wf"); + expect(consoleSpy).toHaveBeenCalled(); + // Falls back to live state + expect(output.prompt).toBeDefined(); + expect(output.prompt).toContain("feat-auth"); + // Handoff consumed even when malformed + expect(ctx.compactionHandoff.has("s1")).toBeFalse(); + consoleSpy.mockRestore(); }); - it("falls back to live state when snapshot workflow does not exist in live state", () => { + it("falls back to the live workflow when the snapshot workflow is absent live", async () => { const ctx = createMockPluginContext({ state: { activeWorkflowId: "live-wf", @@ -418,123 +165,48 @@ describe("buildWorkflowSurvivalBlock", () => { nextStep: "Should not appear for a missing workflow.", capturedAtMs: Date.now(), }; + ctx.compactionHandoff.set("s1", snapshot); const consoleSpy = spyOn(console, "error").mockImplementation(() => {}); - const block = buildWorkflowSurvivalBlock(ctx, snapshot, snapshot.nextStep); + const hooks = createCompactionHook(ctx); + const output: { context: string[]; prompt?: string } = { context: [] }; + await hooks["experimental.session.compacting"]?.({ sessionID: "s1" }, output); - expect(block).toContain("Active Workflow: live-wf"); - expect(block).toContain("EXECUTE"); - expect(block).toContain("Wave: 1 of 3"); - expect(block).not.toContain("missing-wf"); - expect(block).not.toContain("ACCEPT"); + // Falls back to live workflow + expect(output.prompt).toBeDefined(); + expect(output.prompt).toContain("live-wf"); + expect(output.prompt).not.toContain("missing-wf"); + // Live binding unchanged expect(ctx.stateManager.getActiveWorkflowId()).toBe("live-wf"); - expect(consoleSpy).toHaveBeenCalled(); consoleSpy.mockRestore(); }); - it("rebinds via a real StateManager and reports the restored workflow", async () => { - const env = setupTestEnvironment("compaction-survival-rebind"); - const { createStateManager } = await import("../features/state-manager/index.js"); - const stateManager = createStateManager({ - projectDir: env.testDir, - db: env.db, - }); - stateManager.createWorkflow("snapshot-wf"); - stateManager.updateWorkflow({ - phase: "execute", - currentWave: 2, - totalWaves: 3, - }); - - // Simulate drift: another workflow became active after the snapshot was captured. - stateManager.createWorkflow("other-wf"); - stateManager.setActiveWorkflow("other-wf"); - - const ctx = createMockPluginContext({ - testDir: env.testDir, - db: env.db, - stateManager, - }); - - const snapshot: CompactionHandoffSnapshot = { - workflowId: "snapshot-wf", - phase: "execute", - mode: "standard", - depth: "standard", - specLocked: true, - interviewComplete: true, - acceptanceConfirmed: true, - currentWave: 2, - totalWaves: 3, - autopilot: false, - lazyAutopilot: false, - branch: "fix/real-rebind", - nextStep: "Resume after real rebind.", - capturedAtMs: Date.now(), - }; - - const block = buildWorkflowSurvivalBlock(ctx, snapshot, snapshot.nextStep); + // --- Consume-once and halt clearing --- - expect(block).toContain("Active Workflow: snapshot-wf"); - expect(block).toContain("Git Branch: fix/real-rebind"); - expect(stateManager.getActiveWorkflowId()).toBe("snapshot-wf"); - env.cleanup(); - }); - - it("omits wave line when both currentWave and totalWaves are 0", () => { - const ctx = createMockPluginContext({ - state: { - activeWorkflowId: "default", - workflows: { - default: createDefaultWorkflowState({ - phase: "plan", - currentWave: 0, - totalWaves: 0, - }), - }, - }, - }); - - const block = buildWorkflowSurvivalBlock(ctx); - expect(block).not.toContain("Wave:"); - }); -}); - -// --------------------------------------------------------------------------- -// createCompactionHook (factory + handler) -// --------------------------------------------------------------------------- - -describe("createCompactionHook", () => { - it("pushes context block onto output.context (not output.prompt)", async () => { - const ctx = createMockPluginContext({ - state: { - activeWorkflowId: "feat-auth", - workflows: { - "feat-auth": createDefaultWorkflowState({ - phase: "execute", - specLocked: true, - currentWave: 2, - totalWaves: 4, - }), - }, - }, - }); + it("consumes the handoff snapshot once per session", async () => { + const ctx = createMockPluginContext(); + ctx.compactionHandoff.set( + "session-a", + createMockCompactionHandoff("Run the focused hook tests."), + ); const hooks = createCompactionHook(ctx); - const handler = hooks["experimental.session.compacting"]; - expect(handler).toBeDefined(); - const output: { context: string[]; prompt?: string } = { context: [] }; - await handler?.({ sessionID: "s1" }, output); + await hooks["experimental.session.compacting"]?.({ sessionID: "session-a" }, output); - expect(output.context.length).toBeGreaterThan(0); - expect(output.context[0]).toContain("feat-auth"); - expect(output.context[0]).toContain("EXECUTE"); - // Must NOT set prompt - expect(output.prompt).toBeUndefined(); + // Handoff consumed + expect(ctx.compactionHandoff.get("session-a")).toBeUndefined(); + // First invocation contains the declared next step + expect(output.prompt).toContain("1. Run the focused hook tests."); + + // Second invocation does not see the handoff + const secondOutput: { context: string[]; prompt?: string } = { context: [] }; + await hooks["experimental.session.compacting"]?.({ sessionID: "session-a" }, secondOutput); + + expect(secondOutput.prompt).not.toContain("Run the focused hook tests."); }); - it("includes and clears the declared next step for its session", async () => { + it("clears pending compactions and halt state for the session", async () => { const ctx = createMockPluginContext(); ctx.compactionHandoff.set( "session-a", @@ -550,20 +222,11 @@ describe("createCompactionHook", () => { const output: { context: string[]; prompt?: string } = { context: [] }; await hooks["experimental.session.compacting"]?.({ sessionID: "session-a" }, output); - expect(output.context.join("\n")).toContain( - "IMMEDIATE NEXT STEP (declared before compaction): Run the focused hook tests.", - ); - expect(ctx.compactionHandoff.get("session-a")).toBeUndefined(); expect(ctx.pendingCompactions.has("session-a")).toBeFalse(); - - const secondOutput: { context: string[]; prompt?: string } = { - context: [], - }; - await hooks["experimental.session.compacting"]?.({ sessionID: "session-a" }, secondOutput); - expect(secondOutput.context.join("\n")).not.toContain("IMMEDIATE NEXT STEP"); + expect(ctx.compactionHandoff.has("session-a")).toBeFalse(); }); - it("does not use a handoff declared for another session", async () => { + it("does not consume a handoff declared for another session", async () => { const ctx = createMockPluginContext(); ctx.compactionHandoff.set( "session-a", @@ -574,81 +237,88 @@ describe("createCompactionHook", () => { const output: { context: string[]; prompt?: string } = { context: [] }; await hooks["experimental.session.compacting"]?.({ sessionID: "session-b" }, output); - expect(output.context.join("\n")).not.toContain("IMMEDIATE NEXT STEP"); + // Session A's handoff is not consumed expect(ctx.compactionHandoff.get("session-a")?.nextStep).toBe( "Only session A may resume this step.", ); + // Session B's prompt does not contain session A's next step + expect(output.prompt).not.toContain("Only session A may resume this step."); }); - it("omits the next step when no handoff exists for the session", async () => { - const ctx = createMockPluginContext(); - const hooks = createCompactionHook(ctx); - const output: { context: string[]; prompt?: string } = { context: [] }; - - await hooks["experimental.session.compacting"]?.({ sessionID: "session-a" }, output); - - expect(output.context.join("\n")).not.toContain("IMMEDIATE NEXT STEP"); - }); - - it("logs and degrades without throwing for a malformed handoff snapshot", async () => { - const ctx = createMockPluginContext(); - const consoleSpy = spyOn(console, "error").mockImplementation(() => {}); - ctx.compactionHandoff.set("session-a", { nextStep: "incomplete" } as never); - const output: { context: string[]; prompt?: string } = { context: [] }; - - await expect( - createCompactionHook(ctx)["experimental.session.compacting"]?.( - { sessionID: "session-a" }, - output, - ), - ).resolves.toBeUndefined(); - - expect(consoleSpy).toHaveBeenCalled(); - expect(output.context.join("\n")).not.toContain("IMMEDIATE NEXT STEP"); - expect(ctx.compactionHandoff.has("session-a")).toBeFalse(); - consoleSpy.mockRestore(); - }); + // --- Graceful degradation (NFR3: never throw, never mutate on failure) --- - it("includes regular autopilot survival directive when autopilot is active without lazy", async () => { + it("resolves without throwing or mutating output when the state manager throws", async () => { const ctx = createMockPluginContext({ state: { - activeWorkflowId: "default", + activeWorkflowId: "feat-auth", workflows: { - default: createDefaultWorkflowState({ + "feat-auth": createDefaultWorkflowState({ phase: "execute", - autopilot: true, - lazyAutopilot: false, + specLocked: true, + currentWave: 2, + totalWaves: 4, }), }, }, }); + const originalGetState = ctx.stateManager.getState; + (ctx.stateManager as unknown as { getState: () => never }).getState = () => { + throw new Error("state explosion"); + }; + + const consoleSpy = spyOn(console, "error").mockImplementation(() => {}); const hooks = createCompactionHook(ctx); const output: { context: string[]; prompt?: string } = { context: [] }; + + // Should not throw await hooks["experimental.session.compacting"]?.({ sessionID: "s1" }, output); - const joined = output.context.join("\n"); - expect(joined).toContain("AUTOPILOT ACTIVE"); - expect(joined).toContain("Continue to the next phase immediately"); - expect(joined).toContain("Do NOT warn about context length or token limits"); + // No mutation + expect(output.prompt).toBeUndefined(); + expect(output.context).toHaveLength(0); + + consoleSpy.mockRestore(); + (ctx.stateManager as unknown as { getState: typeof originalGetState }).getState = + originalGetState; }); - it("does not push empty block when workflow is missing", async () => { + it("resolves without throwing or mutating output when the DB accessor throws", async () => { const ctx = createMockPluginContext({ state: { - activeWorkflowId: "ghost", - workflows: {}, + activeWorkflowId: "feat-auth", + workflows: { + "feat-auth": createDefaultWorkflowState({ + phase: "execute", + specLocked: true, + currentWave: 2, + totalWaves: 4, + }), + }, }, }); + const originalGetWaves = ctx.db.getWaves; + ctx.db.getWaves = (() => { + throw new Error("db explosion"); + }) as typeof ctx.db.getWaves; + + const consoleSpy = spyOn(console, "error").mockImplementation(() => {}); const hooks = createCompactionHook(ctx); const output: { context: string[]; prompt?: string } = { context: [] }; + + // Should not throw await hooks["experimental.session.compacting"]?.({ sessionID: "s1" }, output); + // NFR3: no mutation when collection fails + expect(output.prompt).toBeUndefined(); expect(output.context).toHaveLength(0); + + consoleSpy.mockRestore(); + ctx.db.getWaves = originalGetWaves; }); - it("does not throw when output.context is undefined (defensive guard)", async () => { + it("does not touch an undefined output.context", async () => { const ctx = createMockPluginContext({ state: { activeWorkflowId: "feat-auth", @@ -664,42 +334,10 @@ describe("createCompactionHook", () => { }); const hooks = createCompactionHook(ctx); - const handler = hooks["experimental.session.compacting"]; - expect(handler).toBeDefined(); - - // Simulate abnormal path where context is undefined const output = {} as { context: string[]; prompt?: string }; - await handler?.({ sessionID: "s1" }, output); - - // Should have initialised context and pushed the block - expect(Array.isArray(output.context)).toBe(true); - expect(output.context.length).toBeGreaterThan(0); - expect(output.context[0]).toContain("feat-auth"); - expect(output.context[0]).toContain("EXECUTE"); - }); - - it("gracefully handles errors without throwing", async () => { - const ctx = createMockPluginContext(); - // Sabotage the state manager to throw - const originalGetState = ctx.stateManager.getState; - (ctx.stateManager as unknown as { getState: () => never }).getState = () => { - throw new Error("state explosion"); - }; - - const consoleSpy = spyOn(console, "error").mockImplementation(() => {}); - - const hooks = createCompactionHook(ctx); - const output: { context: string[]; prompt?: string } = { context: [] }; - - // Should not throw await hooks["experimental.session.compacting"]?.({ sessionID: "s1" }, output); - // safeHandler catches the error - expect(consoleSpy).toHaveBeenCalled(); - consoleSpy.mockRestore(); - - // Restore - (ctx.stateManager as unknown as { getState: typeof originalGetState }).getState = - originalGetState; + expect(output.context).toBeUndefined(); + expect(output.prompt).toContain("feat-auth"); }); }); diff --git a/packages/opencode-plugin/src/hooks/compaction-hook.ts b/packages/opencode-plugin/src/hooks/compaction-hook.ts index 7473cc19..d786c6ef 100644 --- a/packages/opencode-plugin/src/hooks/compaction-hook.ts +++ b/packages/opencode-plugin/src/hooks/compaction-hook.ts @@ -1,25 +1,27 @@ /** * Compaction Hook — preserves GoopSpec workflow state across session compaction. * - * Uses the `experimental.session.compacting` hook to push a survival block - * onto `output.context` (string[]). This ensures the post-compaction model - * knows the active workflow, phase, wave progress, autopilot directives, - * and where to find key documents. + * Uses the `experimental.session.compacting` hook to replace `output.prompt` + * with a bounded continuation prompt. This ensures the post-compaction model + * receives the active workflow, phase, wave progress, and next action. * - * CRITICAL: pushes to `output.context` (appended to default compaction prompt). - * Does NOT set `output.prompt` (that would replace the default prompt entirely). + * If no valid workflow can be resolved, the hook stands down without mutating + * either output field. * * @module hooks/compaction-hook */ import type { CompactionHandoffSnapshot, PluginContext } from "../core/types.js"; +import { + type WorkflowContinuationDetail, + buildContinuationPrompt, + collectContinuationDetail, +} from "../shared/continuation-prompt.js"; import { log, logError } from "../shared/logger.js"; import { clearCompactionHaltState } from "./compaction-halt/index.js"; import type { HookFactory, Hooks } from "./types.js"; import { safeHandler } from "./utils.js"; -export const MAX_NEXT_STEP_CHARS = 200; - function isCompactionHandoffSnapshot(value: unknown): value is CompactionHandoffSnapshot { if (value === null || typeof value !== "object") return false; const handoff = value as Partial; @@ -41,66 +43,6 @@ function isCompactionHandoffSnapshot(value: unknown): value is CompactionHandoff ); } -function sanitizeNextStep(nextStep?: string): string | undefined { - const sanitized = nextStep?.replace(/\s+/g, " ").trim(); - if (!sanitized) return undefined; - if (sanitized.length <= MAX_NEXT_STEP_CHARS) return sanitized; - return `${sanitized.slice(0, MAX_NEXT_STEP_CHARS - 1).trimEnd()}…`; -} - -/** Minimal workflow state needed to render the survival block. */ -interface WorkflowStateLike { - phase: string; - mode: string; - depth: string; - specLocked: boolean; - interviewComplete: boolean; - acceptanceConfirmed: boolean; - currentWave: number; - totalWaves: number; - autopilot: boolean; - lazyAutopilot: boolean; - branch: string | undefined; -} - -/** Resolve the effective workflow state, preferring the handoff snapshot when present and valid. */ -function resolveSurvivalState( - ctx: PluginContext, - handoff: CompactionHandoffSnapshot | undefined, -): { workflowId: string; workflow: WorkflowStateLike; fromSnapshot: boolean } | undefined { - if (handoff !== undefined) { - return { - workflowId: handoff.workflowId, - workflow: { - phase: handoff.phase, - mode: handoff.mode, - depth: handoff.depth, - specLocked: handoff.specLocked, - interviewComplete: handoff.interviewComplete, - acceptanceConfirmed: handoff.acceptanceConfirmed, - currentWave: handoff.currentWave, - totalWaves: handoff.totalWaves, - autopilot: handoff.autopilot, - lazyAutopilot: handoff.lazyAutopilot, - branch: handoff.branch, - }, - fromSnapshot: true, - }; - } - - const live = ctx.stateManager.getState(); - const workflowId = live.activeWorkflowId; - const workflow = live.workflows[workflowId]; - if (!workflow) { - return undefined; - } - return { - workflowId, - workflow: { ...workflow, branch: undefined }, - fromSnapshot: false, - }; -} - /** * Rebind the live active-workflow binding to the snapshot workflow when they differ. * Returns the workflowId that should be reported in the survival block. @@ -132,131 +74,14 @@ function reconcileActiveWorkflowBinding( return { workflowId: liveActiveId, rebound: false }; } -// --------------------------------------------------------------------------- -// Survival block builder -// --------------------------------------------------------------------------- - -/** - * Build the workflow-state survival block that gets injected into compaction - * context. Includes phase, workflow progress, spec lock, autopilot directives, - * and pointers to key documents. - */ -export function buildWorkflowSurvivalBlock( - ctx: PluginContext, - handoff?: CompactionHandoffSnapshot, - nextStep?: string, -): string { - const resolved = resolveSurvivalState(ctx, handoff); - if (!resolved) { - return ""; - } - - let { workflowId, workflow, fromSnapshot } = resolved; - - if (fromSnapshot) { - const reconciliation = reconcileActiveWorkflowBinding(ctx, workflowId); - if (reconciliation.workflowId !== workflowId) { - // Snapshot workflow did not exist in live state; fall back to live binding and its workflow. - const live = ctx.stateManager.getState(); - const liveWorkflow = live.workflows[reconciliation.workflowId]; - if (!liveWorkflow) { - return ""; - } - workflowId = reconciliation.workflowId; - workflow = { ...liveWorkflow, branch: undefined }; - } - } - - const docPrefix = workflowId === "default" ? ".goopspec/" : `.goopspec/${workflowId}/`; - const safeNextStep = sanitizeNextStep(nextStep); - - const lines: string[] = []; - - lines.push("## GoopSpec Workflow State (Compaction Survival)"); - lines.push(""); - lines.push(`RESUME FROM THIS POINT. You are in the ${workflow.phase.toUpperCase()} phase.`); - if (safeNextStep) { - lines.push(`IMMEDIATE NEXT STEP (declared before compaction): ${safeNextStep}`); - } - lines.push(""); - lines.push("Current Status:"); - lines.push(`- Active Workflow: ${workflowId}`); - lines.push(`- Phase: ${workflow.phase}`); - lines.push(`- Mode: ${workflow.mode}`); - lines.push(`- Depth: ${workflow.depth}`); - lines.push(`- Spec Locked: ${workflow.specLocked ? "yes" : "no"}`); - lines.push(`- Interview Complete: ${workflow.interviewComplete ? "yes" : "no"}`); - lines.push(`- Acceptance Confirmed: ${workflow.acceptanceConfirmed ? "yes" : "no"}`); - - if (workflow.branch) { - lines.push(`- Git Branch: ${workflow.branch}`); - } - - // Expose the raw lazyAutopilot boolean so later runtime hooks can gate behavior directly. - lines.push(`- Lazy Autopilot: ${workflow.lazyAutopilot ? "true" : "false"}`); - - if (workflow.currentWave !== 0 || workflow.totalWaves !== 0) { - lines.push(`- Wave: ${workflow.currentWave} of ${workflow.totalWaves}`); - } - - // Autopilot directives — CRITICAL for surviving compaction - if (workflow.autopilot && !workflow.lazyAutopilot) { - lines.push(""); - lines.push( - "AUTOPILOT ACTIVE: Do not pause between phases. Continue to the next phase immediately. " + - "Do not suggest starting a new session. Keep driving phase transitions unattended.", - ); - lines.push( - "Hard stops still apply per phase-gates: Rule 4 architectural decisions, credentials/secrets, " + - "and destructive/irreversible operations.", - ); - } - - if (workflow.autopilot && workflow.lazyAutopilot) { - lines.push(""); - lines.push("LAZY AUTOPILOT ACTIVE. Rules:"); - lines.push("- Do NOT ask the user any questions."); - lines.push("- Do NOT pause for phase confirmations or reviews."); - lines.push("- Do NOT request clarifications — infer from context."); - lines.push( - "- ONLY stop for: (1) missing credentials/secrets, " + - "(2) ambiguous destructive/irreversible operations.", - ); - lines.push( - "- On a Rule 4 architectural decision, decide autonomously using best judgment. " + - "Log full rationale to ADL via goop_adl (rule, issue, decision, reasoning, affected files) — do not pause.", - ); - lines.push("- For ALL other situations: make your best inference and continue."); - } - - if (workflow.autopilot || workflow.lazyAutopilot) { - lines.push(""); - lines.push( - "AUTOPILOT SESSION RULES: Do NOT warn about context length or token limits. " + - "Do NOT suggest starting a new session. Continue working until complete or a permitted stop condition.", - ); - } - - // Document pointers for re-hydration - lines.push(""); - lines.push("Key Documents (reload after compaction):"); - lines.push(`- Spec: ${docPrefix}SPEC.md`); - lines.push(`- Blueprint: ${docPrefix}BLUEPRINT.md`); - lines.push(`- Chronicle: ${docPrefix}CHRONICLE.md`); - lines.push(""); - lines.push("Run `goop_status` to restore full workflow context before taking any action."); - - return lines.join("\n"); -} - // --------------------------------------------------------------------------- // Hook factory // --------------------------------------------------------------------------- /** - * Create the compaction hook that preserves workflow state across compaction. + * Create the compaction hook that replaces the default continuation prompt. * - * Pushes the survival block onto `output.context` (never sets `output.prompt`). + * It leaves both output fields unchanged when workflow state is unavailable. */ export const createCompactionHook: HookFactory = (ctx: PluginContext): Partial => { const handler = safeHandler( @@ -268,7 +93,6 @@ export const createCompactionHook: HookFactory = (ctx: PluginContext): Partial 0) { - if (!Array.isArray(output.context)) { - output.context = []; - log("compaction output.context was absent, initialising"); + let detail: WorkflowContinuationDetail | undefined; + if (snapshot) { + const reconciliation = reconcileActiveWorkflowBinding(ctx, snapshot.workflowId); + detail = collectContinuationDetail( + ctx, + reconciliation.workflowId === snapshot.workflowId ? snapshot : undefined, + ); + } else { + detail = collectContinuationDetail(ctx); } - output.context.push(block); + + if (detail === undefined) return; + + const prompt = buildContinuationPrompt(detail); + if (!prompt.trim()) return; + + output.prompt = prompt; + } catch (error) { + logError("compaction continuation prompt failed; continuing without it", error); } }, ); diff --git a/packages/opencode-plugin/src/hooks/index.test.ts b/packages/opencode-plugin/src/hooks/index.test.ts index 2e0d8f5f..c30f74cf 100644 --- a/packages/opencode-plugin/src/hooks/index.test.ts +++ b/packages/opencode-plugin/src/hooks/index.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, spyOn } from "bun:test"; import { createMockPluginContext, setupTestEnvironment } from "../test-utils.js"; -import { createHooks, mergeHooks, registerHookFactory } from "./index.js"; +import { DEFAULT_HOOK_FACTORIES, createHooks, mergeHooks, registerHookFactory } from "./index.js"; import type { HookFactory, Hooks } from "./types.js"; // --------------------------------------------------------------------------- @@ -272,3 +272,26 @@ describe("registerHookFactory", () => { } }); }); + +// --------------------------------------------------------------------------- +// AD7 boundary — experimental.compaction.autocontinue deferral +// --------------------------------------------------------------------------- + +describe("DEFAULT_HOOK_FACTORIES — AD7 boundary", () => { + it("no factory registers experimental.compaction.autocontinue (SPEC AD7)", () => { + const { testDir, cleanup } = setupTestEnvironment("ad7-autocontinue"); + try { + const ctx = createMockPluginContext({ testDir }); + + for (const factory of DEFAULT_HOOK_FACTORIES) { + const partial = factory(ctx); + // SPEC AD7: experimental.compaction.autocontinue is deliberately NOT + // implemented. If this assertion fails, a factory was added that + // registers the autocontinue hook — revisit AD7 before doing so. + expect(partial["experimental.compaction.autocontinue"]).toBeUndefined(); + } + } finally { + cleanup(); + } + }); +}); diff --git a/packages/opencode-plugin/src/shared/continuation-prompt.test.ts b/packages/opencode-plugin/src/shared/continuation-prompt.test.ts new file mode 100644 index 00000000..67afffc1 --- /dev/null +++ b/packages/opencode-plugin/src/shared/continuation-prompt.test.ts @@ -0,0 +1,236 @@ +import { afterEach, beforeEach, describe, expect, it } from "bun:test"; +import type { CompactionHandoffSnapshot, PluginContext } from "../core/types.js"; +import { + createDefaultWorkflowState, + createMockPluginContext, + setupTestEnvironment, +} from "../test-utils.js"; +import { + MAX_CONTINUATION_PROMPT_CHARS, + buildContinuationPrompt, + collectContinuationDetail, +} from "./continuation-prompt.js"; + +const REQUIRED_HEADINGS = [ + "## Objective", + "## GoopSpec Workflow State", + "## Important Details", + "## Work State", + "### Completed", + "### Active", + "### Blocked", + "## Next Move", + "## Relevant Files", +]; + +function fullSnapshot( + overrides: Partial = {}, +): CompactionHandoffSnapshot { + return { + workflowId: "workflow-42", + phase: "execute", + mode: "standard", + depth: "deep", + specLocked: true, + interviewComplete: true, + acceptanceConfirmed: false, + currentWave: 2, + totalWaves: 4, + autopilot: true, + lazyAutopilot: true, + branch: "feat/continuation-prompt", + nextStep: "Run `bun test packages/opencode-plugin/src/shared/continuation-prompt.test.ts`.", + capturedAtMs: 1, + currentWaveTitle: "Build formatter", + currentWaveStatus: "in_progress", + tasks: [ + { + index: 2, + description: "Render replacement prompt", + status: "in_progress", + agent: "executor", + }, + ], + openBlockers: [ + { id: 7, severity: "high", description: "Need a credential only if deployment begins" }, + ], + prBranch: "feat/continuation-prompt", + prUrl: "https://example.test/pr/42", + ...overrides, + }; +} + +describe("continuation prompt", () => { + let ctx: PluginContext; + let cleanup: () => void; + + beforeEach(() => { + const env = setupTestEnvironment("continuation-prompt"); + cleanup = env.cleanup; + ctx = createMockPluginContext({ testDir: env.testDir, db: env.db }); + }); + afterEach(() => cleanup()); + + it("renders every required heading and a complete snapshot verbatim block", () => { + const detail = collectContinuationDetail(ctx, fullSnapshot()); + const prompt = buildContinuationPrompt(detail!); + + for (const heading of REQUIRED_HEADINGS) expect(prompt).toContain(heading); + expect(prompt).toContain("Reproduce the following block verbatim, changing nothing:"); + expect(prompt).toContain("Workflow ID: workflow-42"); + expect(prompt).toContain("Git Branch: feat/continuation-prompt"); + expect(prompt).toContain("PR URL: https://example.test/pr/42"); + expect(prompt).toContain("Lazy Autopilot: true"); + expect(prompt).toContain( + "1. Run `bun test packages/opencode-plugin/src/shared/continuation-prompt.test.ts`.", + ); + }); + + it("prioritizes recent user instructions and the last explicit task direction for snapshots and live state", () => { + const snapshotPrompt = buildContinuationPrompt(collectContinuationDetail(ctx, fullSnapshot())!); + + ctx = createMockPluginContext({ + testDir: ctx.sdk.directory, + db: ctx.db, + state: { + activeWorkflowId: "live-workflow", + workflows: { + "live-workflow": createDefaultWorkflowState({ currentWave: 1, totalWaves: 2 }), + }, + }, + }); + const livePrompt = buildContinuationPrompt(collectContinuationDetail(ctx)!); + + for (const prompt of [snapshotPrompt, livePrompt]) { + expect(prompt).toContain("most recent user instructions"); + expect(prompt).toContain("last explicit task direction"); + } + }); + + it("retains both the anchored baseline and no-verbatim-reproduction directives", () => { + const prompt = buildContinuationPrompt(collectContinuationDetail(ctx, fullSnapshot())!); + + expect(prompt).toContain( + "use it as the anchored baseline: preserve still-true details, drop stale ones, and merge new facts.", + ); + expect(prompt).toContain( + "Never reproduce an earlier GoopSpec continuation brief verbatim; use it only as the anchored baseline.", + ); + }); + + it("requires authoritative live-state re-queries through both workflow tools", () => { + const prompt = buildContinuationPrompt(collectContinuationDetail(ctx, fullSnapshot())!); + + expect(prompt).toContain("workspace and GoopSpecDB persist and are authoritative"); + expect(prompt).toContain("`goop_status`"); + expect(prompt).toContain("`goop_read_db`"); + }); + + it("prohibits tool use during continuation-brief generation", () => { + const prompt = buildContinuationPrompt(collectContinuationDetail(ctx, fullSnapshot())!); + + expect(prompt).toContain("No tools are available or should be invoked on this turn"); + }); + + it("keeps the frozen formatter caps unchanged", async () => { + const source = await Bun.file(new URL("./continuation-prompt.ts", import.meta.url)).text(); + + expect(MAX_CONTINUATION_PROMPT_CHARS).toBe(10_000); + expect(source).toMatch(/const MAX_TEXT_CHARS = 340;/); + expect(source).toMatch(/const MAX_IDENTIFIER_CHARS = 160;/); + expect(source).toMatch(/const MAX_TASKS = 8;/); + expect(source).toMatch(/const MAX_BLOCKERS = 5;/); + }); + + it("collects live state and guarded current-wave data without a snapshot", () => { + const workflowId = "live-workflow"; + ctx.db.upsertWave(workflowId, { + wave_number: 1, + title: "Live wave", + status: "in_progress", + }); + const waveId = ctx.db.getWave(workflowId, 1)?.id; + ctx.db.upsertWaveTask({ + wave_id: waveId!, + workflow_id: workflowId, + task_index: 1, + description: "Live task", + status: "in_progress", + }); + ctx = createMockPluginContext({ + testDir: ctx.sdk.directory, + db: ctx.db, + state: { + activeWorkflowId: workflowId, + workflows: { [workflowId]: createDefaultWorkflowState({ currentWave: 1, totalWaves: 2 }) }, + }, + }); + + const detail = collectContinuationDetail(ctx); + const prompt = buildContinuationPrompt(detail!); + expect(detail?.tasks[0]?.description).toBe("Live task"); + expect(prompt).toContain( + "Run `goop_status` and derive the gate-appropriate action before acting.", + ); + }); + + it("stands down when neither a snapshot nor an active workflow is valid", () => { + ctx = createMockPluginContext({ state: { activeWorkflowId: "missing", workflows: {} } }); + expect(collectContinuationDetail(ctx)).toBeUndefined(); + expect( + collectContinuationDetail(ctx, { workflowId: "bad" } as CompactionHandoffSnapshot), + ).toBeUndefined(); + }); + + it("preserves strict and lazy autopilot directives but omits them otherwise", () => { + const lazy = buildContinuationPrompt(collectContinuationDetail(ctx, fullSnapshot())!); + const strict = buildContinuationPrompt( + collectContinuationDetail(ctx, fullSnapshot({ lazyAutopilot: false }))!, + ); + const disabled = buildContinuationPrompt( + collectContinuationDetail(ctx, fullSnapshot({ autopilot: false, lazyAutopilot: false }))!, + ); + expect(lazy).toContain("LAZY AUTOPILOT ACTIVE"); + expect(lazy).toContain("Decide Rule 4 architectural questions autonomously"); + expect(strict).toContain("AUTOPILOT ACTIVE: Do not pause between phases"); + expect(strict).not.toContain("LAZY AUTOPILOT ACTIVE"); + expect(disabled).not.toContain("AUTOPILOT ACTIVE"); + expect(disabled).not.toContain("AUTOPILOT SESSION RULES"); + }); + + it("renders empty task and blocker collections without placeholder noise", () => { + const prompt = buildContinuationPrompt( + collectContinuationDetail(ctx, fullSnapshot({ tasks: [], openBlockers: [] }))!, + ); + expect(prompt).toContain("Current-Wave Tasks: none"); + expect(prompt).toContain("Open Blockers: none"); + }); + + it("bounds oversized variable data deterministically while retaining every heading", () => { + const long = "overflow ".repeat(200); + const snapshot = fullSnapshot({ + nextStep: long, + tasks: Array.from({ length: 30 }, (_, index) => ({ + index, + description: long, + status: long, + agent: long, + })), + openBlockers: Array.from({ length: 30 }, (_, index) => ({ + id: index, + severity: long, + description: long, + })), + }); + const prompt = buildContinuationPrompt(collectContinuationDetail(ctx, snapshot)!); + expect(prompt.length).toBeLessThanOrEqual(MAX_CONTINUATION_PROMPT_CHARS); + expect(prompt).toContain("…"); + for (const heading of REQUIRED_HEADINGS) expect(prompt).toContain(heading); + expect(prompt).not.toContain("#8 ["); + }); + + it("has no environment or filesystem imports", async () => { + const source = await Bun.file(new URL("./continuation-prompt.ts", import.meta.url)).text(); + expect(source).not.toMatch(/process\.env|node:fs|from ["']fs["']/); + }); +}); diff --git a/packages/opencode-plugin/src/shared/continuation-prompt.ts b/packages/opencode-plugin/src/shared/continuation-prompt.ts new file mode 100644 index 00000000..5c1af55a --- /dev/null +++ b/packages/opencode-plugin/src/shared/continuation-prompt.ts @@ -0,0 +1,285 @@ +/** + * Typed, bounded continuation-prompt construction for the V1 compaction hook. + * This module intentionally has no host, environment, or filesystem dependencies. + */ + +import type { + CompactionHandoffBlocker, + CompactionHandoffSnapshot, + CompactionHandoffTask, + PluginContext, +} from "../core/types.js"; +import { logError } from "./logger.js"; + +/** Hard upper bound for the replacement prompt replayed into future turns. */ +export const MAX_CONTINUATION_PROMPT_CHARS = 10_000; + +const MAX_TEXT_CHARS = 340; +const MAX_IDENTIFIER_CHARS = 160; +const MAX_TASKS = 8; +const MAX_BLOCKERS = 5; + +/** The complete allowlisted data surface accepted by the formatter. */ +export interface WorkflowContinuationDetail { + readonly workflowId: string; + readonly phase: string; + readonly mode: string; + readonly depth: string; + readonly specLocked: boolean; + readonly interviewComplete: boolean; + readonly acceptanceConfirmed: boolean; + readonly currentWave: number; + readonly totalWaves: number; + readonly autopilot: boolean; + readonly lazyAutopilot: boolean; + readonly branch?: string; + readonly nextStep?: string; + readonly currentWaveTitle?: string; + readonly currentWaveStatus?: string; + readonly tasks: readonly CompactionHandoffTask[]; + readonly openBlockers: readonly CompactionHandoffBlocker[]; + readonly prBranch?: string; + readonly prUrl?: string; +} + +function isSnapshot( + value: CompactionHandoffSnapshot | undefined, +): value is CompactionHandoffSnapshot { + if (value === undefined) return false; + return ( + typeof value.workflowId === "string" && + typeof value.phase === "string" && + typeof value.mode === "string" && + typeof value.depth === "string" && + typeof value.specLocked === "boolean" && + typeof value.interviewComplete === "boolean" && + typeof value.acceptanceConfirmed === "boolean" && + typeof value.currentWave === "number" && + typeof value.totalWaves === "number" && + typeof value.autopilot === "boolean" && + typeof value.lazyAutopilot === "boolean" && + (typeof value.branch === "string" || value.branch === undefined) && + typeof value.nextStep === "string" + ); +} + +function fromSnapshot(snapshot: CompactionHandoffSnapshot): WorkflowContinuationDetail { + return { + workflowId: snapshot.workflowId, + phase: snapshot.phase, + mode: snapshot.mode, + depth: snapshot.depth, + specLocked: snapshot.specLocked, + interviewComplete: snapshot.interviewComplete, + acceptanceConfirmed: snapshot.acceptanceConfirmed, + currentWave: snapshot.currentWave, + totalWaves: snapshot.totalWaves, + autopilot: snapshot.autopilot, + lazyAutopilot: snapshot.lazyAutopilot, + branch: snapshot.branch, + nextStep: snapshot.nextStep, + currentWaveTitle: snapshot.currentWaveTitle, + currentWaveStatus: snapshot.currentWaveStatus, + tasks: snapshot.tasks ?? [], + openBlockers: snapshot.openBlockers ?? [], + prBranch: snapshot.prBranch, + prUrl: snapshot.prUrl, + }; +} + +/** + * Resolve only workflow fields suitable for a continuation prompt. A snapshot + * is authoritative; live state uses a best-effort current-wave database read. + */ +export function collectContinuationDetail( + ctx: PluginContext, + snapshot?: CompactionHandoffSnapshot, +): WorkflowContinuationDetail | undefined { + try { + if (snapshot !== undefined) return isSnapshot(snapshot) ? fromSnapshot(snapshot) : undefined; + + const state = ctx.stateManager.getState(); + const workflowId = state.activeWorkflowId; + const workflow = state.workflows[workflowId]; + if (!workflowId || !workflow) return undefined; + + let currentWaveTitle: string | undefined; + let currentWaveStatus: string | undefined; + let tasks: readonly CompactionHandoffTask[] = []; + let openBlockers: readonly CompactionHandoffBlocker[] = []; + let prBranch: string | undefined; + let prUrl: string | undefined; + + try { + const wave = + workflow.currentWave > 0 + ? ctx.db.getWaves(workflowId, [workflow.currentWave])[0] + : undefined; + if (wave) { + currentWaveTitle = wave.title || undefined; + currentWaveStatus = wave.status; + tasks = ctx.db.getWaveTasks(wave.id).map((task) => ({ + index: task.task_index, + description: task.description, + status: task.status, + agent: task.agent ?? undefined, + })); + prBranch = wave.pr_branch ?? undefined; + prUrl = wave.pr_url ?? undefined; + } + openBlockers = ctx.db.getBlockers(workflowId, "open").map((blocker) => ({ + id: blocker.id, + severity: blocker.severity, + description: blocker.description, + })); + } catch (error) { + logError("continuation prompt could not collect current-wave metadata", error); + return undefined; + } + + return { + workflowId, + phase: workflow.phase, + mode: workflow.mode, + depth: workflow.depth, + specLocked: workflow.specLocked, + interviewComplete: workflow.interviewComplete, + acceptanceConfirmed: workflow.acceptanceConfirmed, + currentWave: workflow.currentWave, + totalWaves: workflow.totalWaves, + autopilot: workflow.autopilot, + lazyAutopilot: workflow.lazyAutopilot, + currentWaveTitle, + currentWaveStatus, + tasks, + openBlockers, + prBranch, + prUrl, + }; + } catch (error) { + logError("continuation prompt could not resolve workflow state", error); + return undefined; + } +} + +function bounded(value: string | undefined, maximum = MAX_TEXT_CHARS): string | undefined { + const normalized = value?.replace(/\s+/g, " ").trim(); + if (!normalized) return undefined; + if (normalized.length <= maximum) return normalized; + return `${normalized.slice(0, maximum - 1).trimEnd()}…`; +} + +function required(value: string, maximum = MAX_IDENTIFIER_CHARS): string { + return bounded(value, maximum) ?? "unknown"; +} + +function workflowStateLines(detail: WorkflowContinuationDetail): string[] { + const lines = [ + `- Workflow ID: ${required(detail.workflowId)}`, + `- Phase: ${required(detail.phase, 80)}`, + `- Mode: ${required(detail.mode, 80)}`, + `- Depth: ${required(detail.depth, 80)}`, + `- Spec Locked: ${detail.specLocked ? "true" : "false"}`, + `- Interview Complete: ${detail.interviewComplete ? "true" : "false"}`, + `- Acceptance Confirmed: ${detail.acceptanceConfirmed ? "true" : "false"}`, + `- Wave: ${detail.currentWave} of ${detail.totalWaves}`, + `- Lazy Autopilot: ${detail.lazyAutopilot ? "true" : "false"}`, + ]; + const optional: [string, string | undefined][] = [ + ["Git Branch", bounded(detail.branch, MAX_IDENTIFIER_CHARS)], + ["Current Wave", bounded(detail.currentWaveTitle)], + ["Current Wave Status", bounded(detail.currentWaveStatus, 80)], + ["PR Branch", bounded(detail.prBranch, MAX_IDENTIFIER_CHARS)], + ["PR URL", bounded(detail.prUrl, MAX_IDENTIFIER_CHARS)], + ]; + for (const [label, value] of optional) if (value) lines.push(`- ${label}: ${value}`); + + const tasks = detail.tasks.slice(0, MAX_TASKS); + lines.push(`- Current-Wave Tasks: ${tasks.length === 0 ? "none" : ""}`.trimEnd()); + for (const task of tasks) { + const agent = bounded(task.agent, 80); + lines.push( + ` - ${task.index}. [${required(task.status, 80)}] ${required(task.description)}${agent ? ` (${agent})` : ""}`, + ); + } + + const blockers = detail.openBlockers.slice(0, MAX_BLOCKERS); + lines.push(`- Open Blockers: ${blockers.length === 0 ? "none" : ""}`.trimEnd()); + for (const blocker of blockers) { + lines.push( + ` - #${blocker.id} [${required(blocker.severity, 80)}] ${required(blocker.description)}`, + ); + } + + if (detail.autopilot && !detail.lazyAutopilot) { + lines.push( + "- AUTOPILOT ACTIVE: Do not pause between phases. Continue to the next phase immediately.", + ); + lines.push( + "- Hard stops still apply per phase-gates: Rule 4 architectural decisions, credentials/secrets, and destructive/irreversible operations.", + ); + } + if (detail.autopilot && detail.lazyAutopilot) { + lines.push( + "- LAZY AUTOPILOT ACTIVE: Do not ask questions or pause for phase confirmations or reviews.", + ); + lines.push( + "- Decide Rule 4 architectural questions autonomously and log full rationale to ADL; stop only for missing credentials/secrets or ambiguous destructive/irreversible operations.", + ); + } + if (detail.autopilot || detail.lazyAutopilot) { + lines.push( + "- AUTOPILOT SESSION RULES: Do not warn about context limits or suggest a new session; continue until complete or a permitted stop condition.", + ); + } + return lines; +} + +/** Build the bounded replacement prompt with the upstream-compatible heading skeleton. */ +export function buildContinuationPrompt(detail: WorkflowContinuationDetail): string { + const nextStep = bounded(detail.nextStep, MAX_TEXT_CHARS); + const lines = [ + "Create a continuation brief using EXACTLY the structure below. Keep every heading, even when its section is empty.", + "- Use terse bullets. Preserve exact file paths, commands, and identifiers.", + "- Do not mention summarizing or compaction.", + "- If an earlier GoopSpec continuation brief appears in the history, use it as the anchored baseline: preserve still-true details, drop stale ones, and merge new facts.", + "- Never reproduce an earlier GoopSpec continuation brief verbatim; use it only as the anchored baseline.", + "- The workspace and GoopSpecDB persist and are authoritative: re-query with `goop_status` and `goop_read_db`, not this brief alone.", + "- No tools are available or should be invoked on this turn; reply with brief text only.", + "", + "## Objective", + "- Preserve the active workflow handoff and the immediate safe action.", + "", + "## GoopSpec Workflow State", + "Reproduce the following block verbatim, changing nothing:", + ...workflowStateLines(detail), + "", + "## Important Details", + "- Preserve factual workflow state exactly as provided above.", + "- Put the most recent user instructions and last explicit task direction here near-verbatim, above older details; preserve exact identifiers, paths, and commands.", + "", + "## Work State", + "### Completed", + "- Record completed work supported by the conversation history.", + "### Active", + "- Record the current work in progress from the conversation history.", + "### Blocked", + "- Record only active blockers from the workflow state or conversation history.", + "", + "## Next Move", + nextStep + ? `1. ${nextStep}` + : "1. Run `goop_status` and derive the gate-appropriate action before acting.", + "", + "## Relevant Files", + "- Preserve relevant exact paths from the conversation history.", + ]; + const prompt = lines.join("\n"); + + // All untrusted fields and collections are bounded above, so this guard is + // defensive rather than a section-dropping truncation path. + if (prompt.length > MAX_CONTINUATION_PROMPT_CHARS) { + return `${prompt.slice(0, MAX_CONTINUATION_PROMPT_CHARS - 1).trimEnd()}…`; + } + return prompt; +} diff --git a/packages/opencode-plugin/src/tools/goop-compact/index.test.ts b/packages/opencode-plugin/src/tools/goop-compact/index.test.ts index 74af527c..b3e16bc2 100644 --- a/packages/opencode-plugin/src/tools/goop-compact/index.test.ts +++ b/packages/opencode-plugin/src/tools/goop-compact/index.test.ts @@ -280,7 +280,8 @@ describe("createGoopCompactTool", () => { expect(handlerSnapshot?.branch).toBeUndefined(); expect(handlerSnapshot?.nextStep).toBe(nextStep); expect(typeof handlerSnapshot?.capturedAtMs).toBe("number"); - expect(output.context.join("\n")).toContain(nextStep); + expect(output.prompt).toContain(`1. ${nextStep}`); + expect(output.context).toHaveLength(0); expect(ctx.compactionHandoff.has(sessionID)).toBeFalse(); }); @@ -528,4 +529,275 @@ describe("createGoopCompactTool", () => { expect(ctx.pendingCompactions.get(otherSessionID)?.status).toBe("queued"); consoleSpy.mockRestore(); }); + + it("populates current-wave task, blocker, and PR metadata from the DB", async () => { + const sessionID = "session-wave-metadata"; + const nextStep = "Continue after compaction with full context."; + + const env = setupTestEnvironment("goop-compact-wave-metadata"); + const { createStateManager } = await import("../../features/state-manager/index.js"); + const realStateManager = createStateManager({ projectDir: env.testDir, db: env.db }); + realStateManager.updateWorkflow({ + phase: "execute", + mode: "standard", + depth: "standard", + interviewComplete: true, + specLocked: true, + acceptanceConfirmed: false, + currentWave: 2, + totalWaves: 4, + autopilot: true, + lazyAutopilot: true, + }); + + env.db.upsertWave("default", { + wave_number: 2, + title: "Wave 2: Implementation", + status: "in_progress", + pr_branch: "feat/compaction-continuation-prompt", + pr_url: "https://github.com/example/repo/pull/123", + }); + + const wave = env.db.getWave("default", 2); + if (!wave) throw new Error("Test setup failed: wave not found"); + + env.db.upsertWaveTask({ + wave_id: wave.id, + workflow_id: "default", + task_index: 0, + description: "Extend snapshot type", + agent: "goop-executor-medium", + status: "in_progress", + }); + env.db.upsertWaveTask({ + wave_id: wave.id, + workflow_id: "default", + task_index: 1, + description: "Build formatter", + agent: "goop-executor-high", + status: "pending", + }); + + env.db.upsertBlocker("default", { + description: "DB schema migration needed", + severity: "high", + status: "open", + wave_id: wave.id, + }); + env.db.upsertBlocker("default", { + description: "Type mismatch in types.ts", + severity: "medium", + status: "open", + }); + env.db.upsertBlocker("default", { + description: "Already resolved", + severity: "low", + status: "resolved", + }); + + const realCtx = createMockPluginContext({ + testDir: env.testDir, + db: env.db, + stateManager: realStateManager, + }); + setCompactionClient(realCtx, { + session: { messages: modelMessages, summarize: mock(async () => ({ data: true })) }, + }); + + await createGoopCompactTool(realCtx).execute( + { next_step: nextStep }, + createMockToolContext({ sessionID }), + ); + + const snapshot = realCtx.compactionHandoff.get(sessionID); + expect(snapshot).toBeDefined(); + expect(snapshot?.currentWaveTitle).toBe("Wave 2: Implementation"); + expect(snapshot?.currentWaveStatus).toBe("in_progress"); + expect(snapshot?.prBranch).toBe("feat/compaction-continuation-prompt"); + expect(snapshot?.prUrl).toBe("https://github.com/example/repo/pull/123"); + + expect(snapshot?.tasks).toHaveLength(2); + expect(snapshot?.tasks?.[0]).toEqual({ + index: 0, + description: "Extend snapshot type", + status: "in_progress", + agent: "goop-executor-medium", + }); + expect(snapshot?.tasks?.[1]).toEqual({ + index: 1, + description: "Build formatter", + status: "pending", + agent: "goop-executor-high", + }); + + expect(snapshot?.openBlockers).toHaveLength(2); + expect(snapshot?.openBlockers).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + severity: "high", + description: "DB schema migration needed", + }), + expect.objectContaining({ + severity: "medium", + description: "Type mismatch in types.ts", + }), + ]), + ); + expect(snapshot?.openBlockers?.every((b) => b.description !== "Already resolved")).toBeTrue(); + + env.cleanup(); + }); + + it("bounds tasks to 8 and open blockers to 5 in the snapshot", async () => { + const sessionID = "session-bounded-metadata"; + const nextStep = "Resume with bounded context."; + + const env = setupTestEnvironment("goop-compact-bounded"); + const { createStateManager } = await import("../../features/state-manager/index.js"); + const realStateManager = createStateManager({ projectDir: env.testDir, db: env.db }); + realStateManager.updateWorkflow({ + phase: "execute", + currentWave: 1, + totalWaves: 3, + interviewComplete: true, + specLocked: true, + }); + + env.db.upsertWave("default", { wave_number: 1, title: "Wave 1", status: "in_progress" }); + const wave = env.db.getWave("default", 1); + if (!wave) throw new Error("Test setup failed: wave not found"); + + for (let i = 0; i < 10; i++) { + env.db.upsertWaveTask({ + wave_id: wave.id, + workflow_id: "default", + task_index: i, + description: `Task ${i}`, + status: i < 5 ? "done" : "pending", + }); + } + for (let i = 0; i < 7; i++) { + env.db.upsertBlocker("default", { + description: `Blocker ${i}`, + severity: "medium", + status: "open", + }); + } + + const realCtx = createMockPluginContext({ + testDir: env.testDir, + db: env.db, + stateManager: realStateManager, + }); + setCompactionClient(realCtx, { + session: { messages: modelMessages, summarize: mock(async () => ({ data: true })) }, + }); + + await createGoopCompactTool(realCtx).execute( + { next_step: nextStep }, + createMockToolContext({ sessionID }), + ); + + const snapshot = realCtx.compactionHandoff.get(sessionID); + expect(snapshot).toBeDefined(); + expect(snapshot?.tasks).toHaveLength(8); + expect(snapshot?.openBlockers).toHaveLength(5); + + env.cleanup(); + }); + + it("produces undefined optional fields when the DB has no wave data", async () => { + const sessionID = "session-empty-db"; + const nextStep = "Resume with minimal context."; + + const env = setupTestEnvironment("goop-compact-empty-db"); + const { createStateManager } = await import("../../features/state-manager/index.js"); + const realStateManager = createStateManager({ projectDir: env.testDir, db: env.db }); + realStateManager.updateWorkflow({ + phase: "execute", + currentWave: 1, + totalWaves: 3, + interviewComplete: true, + specLocked: true, + }); + + const realCtx = createMockPluginContext({ + testDir: env.testDir, + db: env.db, + stateManager: realStateManager, + }); + setCompactionClient(realCtx, { + session: { messages: modelMessages, summarize: mock(async () => ({ data: true })) }, + }); + + await createGoopCompactTool(realCtx).execute( + { next_step: nextStep }, + createMockToolContext({ sessionID }), + ); + + const snapshot = realCtx.compactionHandoff.get(sessionID); + expect(snapshot).toBeDefined(); + expect(snapshot?.currentWaveTitle).toBeUndefined(); + expect(snapshot?.currentWaveStatus).toBeUndefined(); + expect(snapshot?.tasks).toBeUndefined(); + expect(snapshot?.openBlockers).toBeUndefined(); + expect(snapshot?.prBranch).toBeUndefined(); + expect(snapshot?.prUrl).toBeUndefined(); + expect(snapshot?.workflowId).toBe("default"); + expect(snapshot?.currentWave).toBe(1); + expect(snapshot?.nextStep).toBe(nextStep); + + env.cleanup(); + }); + + it("produces a valid core snapshot when DB accessors throw", async () => { + const sessionID = "session-throwing-db"; + const nextStep = "Resume despite DB failure."; + + const env = setupTestEnvironment("goop-compact-throwing-db"); + const { createStateManager } = await import("../../features/state-manager/index.js"); + const realStateManager = createStateManager({ projectDir: env.testDir, db: env.db }); + realStateManager.updateWorkflow({ + phase: "execute", + currentWave: 2, + totalWaves: 4, + interviewComplete: true, + specLocked: true, + }); + + const realCtx = createMockPluginContext({ + testDir: env.testDir, + db: env.db, + stateManager: realStateManager, + }); + setCompactionClient(realCtx, { + session: { messages: modelMessages, summarize: mock(async () => ({ data: true })) }, + }); + + const dbSpy = spyOn(realCtx.db, "getWaves").mockImplementation(() => { + throw new Error("database is locked"); + }); + const consoleSpy = spyOn(console, "error").mockImplementation(() => {}); + + await createGoopCompactTool(realCtx).execute( + { next_step: nextStep }, + createMockToolContext({ sessionID }), + ); + + const snapshot = realCtx.compactionHandoff.get(sessionID); + expect(snapshot).toBeDefined(); + expect(snapshot?.workflowId).toBe("default"); + expect(snapshot?.currentWave).toBe(2); + expect(snapshot?.nextStep).toBe(nextStep); + expect(snapshot?.currentWaveTitle).toBeUndefined(); + expect(snapshot?.currentWaveStatus).toBeUndefined(); + expect(snapshot?.tasks).toBeUndefined(); + expect(snapshot?.openBlockers).toBeUndefined(); + expect(snapshot?.prBranch).toBeUndefined(); + expect(snapshot?.prUrl).toBeUndefined(); + + dbSpy.mockRestore(); + consoleSpy.mockRestore(); + env.cleanup(); + }); }); diff --git a/packages/opencode-plugin/src/tools/goop-compact/index.ts b/packages/opencode-plugin/src/tools/goop-compact/index.ts index 6ede13e9..bf335bf4 100644 --- a/packages/opencode-plugin/src/tools/goop-compact/index.ts +++ b/packages/opencode-plugin/src/tools/goop-compact/index.ts @@ -10,10 +10,22 @@ import { } from "../../core/pending-compaction.js"; import { tool } from "../../core/sdk-compat.js"; import type { ToolContext, ToolDefinition } from "../../core/sdk-compat.js"; -import type { CompactionHandoffSnapshot, GoopState, PluginContext } from "../../core/types.js"; +import type { + CompactionHandoffBlocker, + CompactionHandoffSnapshot, + CompactionHandoffTask, + GoopState, + PluginContext, +} from "../../core/types.js"; import { COMPACT_RECONCILIATION_DIRECTIVE } from "../../shared/compact-reminder.js"; import { log, logError } from "../../shared/logger.js"; +/** Maximum task rows projected into the snapshot (current wave only). */ +const MAX_SNAPSHOT_TASKS = 8; + +/** Maximum open-blocker rows projected into the snapshot. */ +const MAX_SNAPSHOT_BLOCKERS = 5; + interface ModelRef { providerID: string; modelID: string; @@ -163,6 +175,70 @@ function detectDivergence(cached: GoopState, persisted: GoopState): DivergenceCh return { divergentFields, persistedState: persisted }; } +interface CurrentWaveMetadata { + readonly currentWaveTitle: string | undefined; + readonly currentWaveStatus: string | undefined; + readonly tasks: ReadonlyArray; + readonly openBlockers: ReadonlyArray; + readonly prBranch: string | undefined; + readonly prUrl: string | undefined; +} + +/** + * Collect current-wave task, blocker, and PR metadata from the GoopSpecDB. + * + * Returns `undefined` when the current wave has no row, the wave number is 0, + * or any DB accessor throws. The caller must never fail to produce a valid + * core snapshot because of a DB error — the optional fields simply drop out. + */ +function collectCurrentWaveMetadata( + ctx: PluginContext, + workflowId: string, + currentWave: number, +): CurrentWaveMetadata | undefined { + if (currentWave <= 0) return undefined; + + try { + const waves = ctx.db.getWaves(workflowId, [currentWave]); + const wave = waves[0]; + if (!wave) return undefined; + + const tasks: CompactionHandoffTask[] = ctx.db + .getWaveTasks(wave.id) + .slice(0, MAX_SNAPSHOT_TASKS) + .map((t) => ({ + index: t.task_index, + description: t.description, + status: t.status, + agent: t.agent ?? undefined, + })); + + const openBlockers: CompactionHandoffBlocker[] = ctx.db + .getBlockers(workflowId, "open") + .slice(0, MAX_SNAPSHOT_BLOCKERS) + .map((b) => ({ + id: b.id, + severity: b.severity, + description: b.description, + })); + + return { + currentWaveTitle: wave.title || undefined, + currentWaveStatus: wave.status, + tasks, + openBlockers, + prBranch: wave.pr_branch ?? undefined, + prUrl: wave.pr_url ?? undefined, + }; + } catch (error) { + logError( + "goop_compact could not collect current-wave metadata for the handoff snapshot", + error, + ); + return undefined; + } +} + async function captureCompactionHandoff( ctx: PluginContext, nextStep: string, @@ -174,6 +250,8 @@ async function captureCompactionHandoff( throw new Error(`Active workflow ${state.activeWorkflowId} was not found`); } + const metadata = collectCurrentWaveMetadata(ctx, state.activeWorkflowId, workflow.currentWave); + return { workflowId: state.activeWorkflowId, phase: workflow.phase, @@ -189,6 +267,12 @@ async function captureCompactionHandoff( branch: await resolveCurrentBranch(ctx.sdk.worktree), nextStep, capturedAtMs: Date.now(), + currentWaveTitle: metadata?.currentWaveTitle, + currentWaveStatus: metadata?.currentWaveStatus, + tasks: metadata?.tasks, + openBlockers: metadata?.openBlockers, + prBranch: metadata?.prBranch, + prUrl: metadata?.prUrl, }; } catch (error) { logError("goop_compact could not capture the compaction handoff snapshot", error);