import assert from "node:assert/strict"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { execFileSync } from "node:child_process"; import test from "node:test"; import { WorkContext } from "../src/core.js"; import { ERROR_CODES } from "../src/errors.js"; import { consumeIntegrationNotices } from "../src/integration-notices.js"; import { readStagesSnapshot } from "../src/stages-snapshot.js"; import tools from "../src/tool-definitions.js"; import { WORK_CONTEXT_PROTOCOL_DESCRIPTOR } from "../src/protocol.js"; import plugin from "../plugin/work-context.js"; const git = (root, args) => execFileSync("git", args, { cwd: root, encoding: "utf8" }).trim(); const repository = () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "candidate-coverage-")); git(root, ["init", "-q"]); git(root, ["config", "user.name", "Coverage Test"]); git(root, ["config", "user.email", "coverage@example.test"]); fs.writeFileSync(path.join(root, ".gitignore"), ".work-context/local/*\n!.work-context/local/.gitignore\n"); fs.writeFileSync(path.join(root, "app.txt"), "before\n"); git(root, ["add", "."]); git(root, ["commit", "-qm", "initial"]); return root; }; const setup = () => { const root = repository(); const context = WorkContext.open(root, { actor: "test" }); context.createWorkspace("Coverage", { workspace: "999901", sessionId: "stage-one", opencodeSessionId: "oc-one", mode: "startup" }); context.setWorkspaceCommitMode("999901", "per_item"); const second = context.addStage("999901", "Second", { prompt: "Second current." }).data.stage; context.startSession("999901", second, { sessionId: "stage-two", opencodeSessionId: "oc-two" }); context.replaceStageExecution("999901", "01", "stage-one", 0, { remaining: ["First current"] }); context.replaceStageExecution("999901", "02", "stage-two", 0, { remaining: ["Second current"] }); fs.writeFileSync(path.join(root, "app.txt"), "after\n"); const candidate = context.createCandidate("999901", "Integrated change", null, { strategy: "integration" }).data.candidate; context.captureCandidate("999901", candidate, { paths: ["app.txt"] }); context.readyCandidate("999901", candidate); return { root, context, candidate }; }; test("coverage confirmation is explicit, stage-bounded, idempotent, and available as a structured tool", async () => { const { root, context, candidate } = setup(); try { assert.throws(() => context.confirmCandidateCoverage("999901", candidate, ["01", "02"], "yes"), (error) => error.code === ERROR_CODES.CANDIDATE_COVERAGE_CONFIRMATION_REQUIRED); assert.throws(() => context.confirmCandidateCoverage("999901", candidate, ["01", "01"], "INTEGRATION_COVERAGE_CONFIRMED"), (error) => error.code === ERROR_CODES.INVALID_ARGUMENT); const first = context.confirmCandidateCoverage("999901", candidate, ["02", "01"], "INTEGRATION_COVERAGE_CONFIRMED").data; const second = context.confirmCandidateCoverage("999901", candidate, ["01", "02"], "INTEGRATION_COVERAGE_CONFIRMED").data; assert.deepEqual(first.coverage.entries.map((entry) => entry.stage), ["01", "02"]); assert.deepEqual(second.coverage, first.coverage); assert.deepEqual(first.coverage.entries.map((entry) => entry.execution_revision), [1, 1]); const toolResult = JSON.parse((await tools.work_context_confirm_candidate_coverage.execute({ workspace: "999901", candidateId: candidate, stages: ["01", "02"], confirmation: "INTEGRATION_COVERAGE_CONFIRMED", }, { worktree: root, directory: root, sessionID: "oc-one", metadata: async () => {} })).output); assert.equal(toolResult.ok, true); assert.deepEqual(toolResult.data.coverage, first.coverage); assert.equal(WORK_CONTEXT_PROTOCOL_DESCRIPTOR.operations.includes("candidate.confirm_coverage"), true); assert.equal((await import("../tools/work_context_confirm_candidate_coverage.js")).default, tools.work_context_confirm_candidate_coverage); } finally { fs.rmSync(root, { recursive: true, force: true }); } }); test("coverage requires a ready integration candidate and a Current item in every selected stage", () => { const { root, context, candidate } = setup(); try { const exact = context.createCandidate("999901", "Exact").data.candidate; assert.throws(() => context.confirmCandidateCoverage("999901", exact, ["01", "02"], "INTEGRATION_COVERAGE_CONFIRMED"), (error) => error.code === ERROR_CODES.INVALID_STATE); context.completeCurrentExecution("999901", "02", "stage-two", 1); assert.throws(() => context.confirmCandidateCoverage("999901", candidate, ["01", "02"], "INTEGRATION_COVERAGE_CONFIRMED"), (error) => error.code === ERROR_CODES.CANDIDATE_COVERAGE_CURRENT_REQUIRED); } finally { fs.rmSync(root, { recursive: true, force: true }); } }); test("stale confirmed coverage fails before Git publication", () => { const { root, context, candidate } = setup(); try { context.confirmCandidateCoverage("999901", candidate, ["01", "02"], "INTEGRATION_COVERAGE_CONFIRMED"); const head = git(root, ["rev-parse", "HEAD"]); context.updateStageExecution("999901", "02", "stage-two", 1, { add: { verification: ["Focused checks pass"] } }); assert.throws(() => context.commitCandidate("999901", candidate), (error) => error.code === ERROR_CODES.CANDIDATE_COVERAGE_STALE); assert.equal(git(root, ["rev-parse", "HEAD"]), head); assert.equal(context.showCandidate("999901", candidate).data.status, "ready"); } finally { fs.rmSync(root, { recursive: true, force: true }); } }); test("coverage becomes stale when per-item authorization is removed", () => { const { root, context, candidate } = setup(); try { context.confirmCandidateCoverage("999901", candidate, ["01", "02"], "INTEGRATION_COVERAGE_CONFIRMED"); const head = git(root, ["rev-parse", "HEAD"]); context.setWorkspaceCommitMode("999901", "manual"); assert.throws(() => context.commitCandidate("999901", candidate), (error) => error.code === ERROR_CODES.CANDIDATE_COVERAGE_STALE); assert.equal(git(root, ["rev-parse", "HEAD"]), head); } finally { fs.rmSync(root, { recursive: true, force: true }); } }); test("covered publication rollback cannot expose a false live notice", () => { const { root, context, candidate } = setup(); try { context.confirmCandidateCoverage("999901", candidate, ["01", "02"], "INTEGRATION_COVERAGE_CONFIRMED"); const head = git(root, ["rev-parse", "HEAD"]); assert.throws(() => context.commitCandidate("999901", candidate, undefined, { afterUpdateRef: () => { assert.deepEqual(consumeIntegrationNotices(root, "oc-one"), []); throw new Error("post-ref failure"); } }), /post-ref failure/); assert.equal(git(root, ["rev-parse", "HEAD"]), head); assert.equal(context.showCandidate("999901", candidate).data.status, "ready"); assert.deepEqual(consumeIntegrationNotices(root, "oc-one"), []); } finally { fs.rmSync(root, { recursive: true, force: true }); } }); test("commit all never reuses or publishes a coverage-confirmed candidate", () => { const { root, context, candidate } = setup(); try { context.confirmCandidateCoverage("999901", candidate, ["01", "02"], "INTEGRATION_COVERAGE_CONFIRMED"); const inspection = context.inspectCommitAll("999901", { message: "Integrated change", relatedStages: [] }).data; const committed = context.commitAll("999901", inspection.fingerprint, "COMMIT_ALL_CONFIRMED", { message: "Integrated change", relatedStages: [] }).data; assert.notEqual(committed.candidate, candidate); assert.equal(context.showCandidate("999901", candidate).data.status, "ready"); assert.equal(context.showCandidate("999901", committed.candidate).data.coverage, undefined); } finally { fs.rmSync(root, { recursive: true, force: true }); } }); test("only one confirmed candidate can publish the same Current items", () => { const { root, context, candidate } = setup(); try { const duplicate = context.createCandidate("999901", "Duplicate integration", null, { strategy: "integration" }).data.candidate; context.captureCandidate("999901", duplicate, { paths: ["app.txt"] }); context.readyCandidate("999901", duplicate); context.confirmCandidateCoverage("999901", candidate, ["01", "02"], "INTEGRATION_COVERAGE_CONFIRMED"); context.confirmCandidateCoverage("999901", duplicate, ["01", "02"], "INTEGRATION_COVERAGE_CONFIRMED"); context.commitCandidate("999901", candidate); const head = git(root, ["rev-parse", "HEAD"]); assert.throws(() => context.commitCandidate("999901", duplicate), (error) => error.code === ERROR_CODES.CANDIDATE_COVERAGE_STALE); assert.equal(git(root, ["rev-parse", "HEAD"]), head); assert.equal(context.showCandidate("999901", duplicate).data.status, "ready"); } finally { fs.rmSync(root, { recursive: true, force: true }); } }); test("committed coverage is durable without advancing execution and clears after separate completion", async () => { const { root, context, candidate } = setup(); try { const before = context.readStageExecution("999901", "01").data; context.confirmCandidateCoverage("999901", candidate, ["01", "02"], "INTEGRATION_COVERAGE_CONFIRMED"); const committed = context.commitCandidate("999901", candidate).data; assert.match(committed.commit_hash, /^[0-9a-f]{40}$/); assert.equal(context.readStageExecution("999901", "01").data.revision, before.revision); assert.equal(context.readStageExecution("999901", "01").data.current.id, before.current.id); assert.equal(context.candidates().committedCoverageProjection("999901").by_stage["01"].items[0].candidate, candidate); const snapshot = readStagesSnapshot({ projectRoot: root, sessionId: "oc-one" }); assert.equal(snapshot.data.stages.find((stage) => stage.id === "01").committed_coverage.items[0].candidate, candidate); assert.equal(snapshot.data.stages.find((stage) => stage.id === "02").committed_coverage.items[0].candidate, candidate); fs.rmSync(path.join(root, ".work-context", "local", "integration-notices.json"), { force: true }); const hooks = await plugin({ client: { session: {} }, directory: root, worktree: root }); const firstOutput = { system: ["base"] }; const secondOutput = { system: ["base"] }; await hooks["experimental.chat.system.transform"]({ sessionID: "oc-one", model: "test" }, firstOutput); await hooks["experimental.chat.system.transform"]({ sessionID: "oc-two", model: "test" }, secondOutput); assert.match(firstOutput.system[1], new RegExp(candidate)); assert.match(secondOutput.system[1], new RegExp(candidate)); fs.rmSync(path.join(root, ".work-context", "local", "integration-notices.json"), { force: true }); const repeated = { system: ["base"] }; await hooks["experimental.chat.system.transform"]({ sessionID: "oc-one", model: "test" }, repeated); assert.deepEqual(repeated.system, ["base"]); context.handoff("999901", "01", "stage-one"); const resumed = context.startSession("999901", "01", { sessionId: "stage-one-next", opencodeSessionId: "oc-one-next" }).data; assert.equal(resumed.resume.context.committed_integration_coverage.items[0].candidate, candidate); context.completeCurrentExecution("999901", "01", "stage-one-next", before.revision); assert.equal(context.candidates().committedCoverageProjection("999901").by_stage["01"], undefined); assert.equal(context.candidates().committedCoverageProjection("999901").by_stage["02"].items[0].candidate, candidate); } finally { fs.rmSync(root, { recursive: true, force: true }); } }); test("a queued notice is suppressed after its covered Current advances", async () => { const { root, context, candidate } = setup(); try { context.confirmCandidateCoverage("999901", candidate, ["01", "02"], "INTEGRATION_COVERAGE_CONFIRMED"); context.commitCandidate("999901", candidate); context.completeCurrentExecution("999901", "01", "stage-one", 1); const hooks = await plugin({ client: { session: {} }, directory: root, worktree: root }); const output = { system: ["base"] }; await hooks["experimental.chat.system.transform"]({ sessionID: "oc-one", model: "test" }, output); assert.deepEqual(output.system, ["base"]); } finally { fs.rmSync(root, { recursive: true, force: true }); } }); test("committed coverage projection is bounded and reports truncation", () => { const { root, context, candidate } = setup(); try { context.confirmCandidateCoverage("999901", candidate, ["01", "02"], "INTEGRATION_COVERAGE_CONFIRMED"); context.commitCandidate("999901", candidate); const directory = path.join(root, ".work-context", "local", "candidates"); const original = JSON.parse(fs.readFileSync(path.join(directory, `${candidate}.json`), "utf8")); for (let number = 2; number <= 12; number += 1) { const id = `CC-${String(number).padStart(6, "0")}`; fs.writeFileSync(path.join(directory, `${id}.json`), `${JSON.stringify({ ...original, candidate: id, patch_file: `${id}.patch`, title: `Legacy duplicate ${number}` }, null, 2)}\n`); } const projection = context.candidates().committedCoverageProjection("999901").by_stage["01"]; assert.equal(projection.count, 12); assert.equal(projection.items.length, 10); assert.equal(projection.truncated, true); } finally { fs.rmSync(root, { recursive: true, force: true }); } });