opencode-work-context 0.14.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/candidates.js CHANGED
@@ -10,11 +10,25 @@ const candidatePattern = /^CC-(\d{6})$/;
10
10
  const statuses = new Set(["draft", "ready", "discarded", "committed"]);
11
11
  const strategies = new Set(["exact", "shared_foundation", "integration"]);
12
12
  const projectionCandidateLimit = 10;
13
+ const projectionCoverageLimit = 10;
13
14
  const projectionTitleLimit = 120;
14
15
  const deliveryCandidateLimit = 20;
16
+ const coverageStageLimit = 20;
17
+ const executionItemPattern = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|legacy-[0-9a-f]{24})$/;
15
18
  const timestamp = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
16
19
  const metadataKeys = ["schema", "candidate", "workspace", "title", "message", "base_head", "status", "created_at", "updated_at", "selected_paths", "patch_file"];
17
- const optionalMetadataKeys = ["strategy", "related_stages"];
20
+ const optionalMetadataKeys = ["strategy", "related_stages", "coverage"];
21
+
22
+ const validCoverage = (coverage) => coverage && typeof coverage === "object" && !Array.isArray(coverage)
23
+ && Object.keys(coverage).every((key) => ["schema", "confirmed_at", "entries"].includes(key))
24
+ && coverage.schema === 1 && timestamp(coverage.confirmed_at)
25
+ && Array.isArray(coverage.entries) && coverage.entries.length >= 2 && coverage.entries.length <= coverageStageLimit
26
+ && coverage.entries.every((entry) => entry && typeof entry === "object" && !Array.isArray(entry)
27
+ && Object.keys(entry).every((key) => ["stage", "current_item_id", "execution_revision"].includes(key))
28
+ && /^\d{2}$/.test(entry.stage) && entry.stage !== "00" && executionItemPattern.test(entry.current_item_id)
29
+ && Number.isInteger(entry.execution_revision) && entry.execution_revision >= 0)
30
+ && new Set(coverage.entries.map((entry) => entry.stage)).size === coverage.entries.length
31
+ && coverage.entries.every((entry, index) => index === 0 || coverage.entries[index - 1].stage.localeCompare(entry.stage) < 0);
18
32
 
19
33
  function validateCandidate(data, expectedId = null) {
20
34
  const valid = data && typeof data === "object" && !Array.isArray(data)
@@ -32,6 +46,7 @@ function validateCandidate(data, expectedId = null) {
32
46
  && (!Object.hasOwn(data, "strategy") || (strategies.has(data.strategy)
33
47
  && Array.isArray(data.related_stages) && data.related_stages.every((stage) => /^\d{2}$/.test(stage) && stage !== "00")
34
48
  && new Set(data.related_stages).size === data.related_stages.length))
49
+ && (!Object.hasOwn(data, "coverage") || (data.strategy === "integration" && validCoverage(data.coverage)))
35
50
  && (data.status === "committed"
36
51
  ? /^[0-9a-f]{40,64}$/.test(data.commit_hash) && timestamp(data.committed_at)
37
52
  : !Object.hasOwn(data, "commit_hash") && !Object.hasOwn(data, "committed_at"));
@@ -172,10 +187,108 @@ export class CandidateStore {
172
187
  related_stages: candidate.related_stages || [],
173
188
  commit_hash: candidate.commit_hash,
174
189
  committed_at: candidate.committed_at,
190
+ ...(candidate.coverage ? { coverage: candidate.coverage } : {}),
175
191
  })),
176
192
  };
177
193
  }
178
194
 
195
+ effectiveCommitMode(workspaceRecord, stageRecord) {
196
+ return stageRecord.commit_mode || workspaceRecord.commit_mode || "manual";
197
+ }
198
+
199
+ coverageEntry(workspace, stage, stale = false) {
200
+ const stageRecord = this.context.storage.readStage(workspace, stage).data;
201
+ const execution = this.context.storage.readStageExecution(workspace, stage);
202
+ const current = execution ? this.context.readStageExecution(workspace, stage).data.current : null;
203
+ if (!current) {
204
+ const code = stale ? ERROR_CODES.CANDIDATE_COVERAGE_STALE : ERROR_CODES.CANDIDATE_COVERAGE_CURRENT_REQUIRED;
205
+ fail(code, stale ? "Confirmed integration coverage no longer matches a Current item" : "Every covered stage must have a Current execution item", { stage });
206
+ }
207
+ const workspaceRecord = this.context.storage.readWorkspace(workspace).data;
208
+ if (this.effectiveCommitMode(workspaceRecord, stageRecord) !== "per_item") {
209
+ const code = stale ? ERROR_CODES.CANDIDATE_COVERAGE_STALE : ERROR_CODES.INVALID_STATE;
210
+ fail(code, stale ? "Confirmed integration coverage no longer has per-item authorization" : "Every covered stage must use per_item commit mode", { stage });
211
+ }
212
+ if (["completed", "cancelled", "archived"].includes(stageRecord.status)) {
213
+ const code = stale ? ERROR_CODES.CANDIDATE_COVERAGE_STALE : ERROR_CODES.INVALID_STATE;
214
+ fail(code, stale ? "Confirmed integration coverage includes a terminal stage" : "Covered stages must be actionable", { stage, status: stageRecord.status });
215
+ }
216
+ return { stage, current_item_id: current.id, execution_revision: execution.revision };
217
+ }
218
+
219
+ confirmCoverage(workspace, id, selectedStages, confirmation) {
220
+ workspace = this.assertStartup(workspace);
221
+ if (confirmation !== "INTEGRATION_COVERAGE_CONFIRMED") fail(ERROR_CODES.CANDIDATE_COVERAGE_CONFIRMATION_REQUIRED, "Candidate coverage requires the exact INTEGRATION_COVERAGE_CONFIRMED confirmation");
222
+ const data = this.read(id, workspace, true);
223
+ if (data.strategy !== "integration") fail(ERROR_CODES.INVALID_STATE, "Only integration candidates can receive multi-stage Current coverage");
224
+ if (data.status !== "ready") fail(ERROR_CODES.INVALID_STATE, "Only ready candidates can receive multi-stage Current coverage", { status: data.status });
225
+ if (!Array.isArray(selectedStages)) fail(ERROR_CODES.INVALID_ARGUMENT, "Covered stages must be an array");
226
+ const stages = selectedStages.map(normalizeStageId);
227
+ if (stages.length < 2 || stages.length > coverageStageLimit) fail(ERROR_CODES.INVALID_ARGUMENT, `Coverage requires between 2 and ${coverageStageLimit} stages`);
228
+ if (new Set(stages).size !== stages.length) fail(ERROR_CODES.INVALID_ARGUMENT, "Covered stages must be unique");
229
+ const entries = [...stages].sort().map((stage) => this.coverageEntry(workspace, stage));
230
+ if (data.coverage && JSON.stringify(data.coverage.entries) === JSON.stringify(entries)) {
231
+ const { patch, ...metadata } = data;
232
+ return metadata;
233
+ }
234
+ data.coverage = { schema: 1, confirmed_at: new Date().toISOString(), entries };
235
+ data.updated_at = data.coverage.confirmed_at;
236
+ const { patch, ...metadata } = data;
237
+ this.write(metadata);
238
+ return metadata;
239
+ }
240
+
241
+ validateCoverage(workspace, data) {
242
+ if (!data.coverage) return null;
243
+ const actual = data.coverage.entries.map((entry) => {
244
+ try { return this.coverageEntry(workspace, entry.stage, true); }
245
+ catch (error) {
246
+ if (error.code === ERROR_CODES.NOT_FOUND) fail(ERROR_CODES.CANDIDATE_COVERAGE_STALE, "A stage from confirmed integration coverage is no longer available", { stage: entry.stage });
247
+ throw error;
248
+ }
249
+ });
250
+ const stale = actual.find((entry, index) => entry.current_item_id !== data.coverage.entries[index].current_item_id
251
+ || entry.execution_revision !== data.coverage.entries[index].execution_revision);
252
+ if (stale) fail(ERROR_CODES.CANDIDATE_COVERAGE_STALE, "Confirmed integration coverage changed before publication", {
253
+ stage: stale.stage,
254
+ expected: data.coverage.entries.find((entry) => entry.stage === stale.stage),
255
+ actual: stale,
256
+ });
257
+ const duplicate = this.projectionRecords(workspace)
258
+ .filter((candidate) => candidate.candidate !== data.candidate && candidate.status === "committed" && candidate.coverage)
259
+ .flatMap((candidate) => candidate.coverage.entries.map((entry) => ({ candidate: candidate.candidate, commit_hash: candidate.commit_hash, ...entry })))
260
+ .find((entry) => data.coverage.entries.some((covered) => covered.stage === entry.stage && covered.current_item_id === entry.current_item_id));
261
+ if (duplicate) fail(ERROR_CODES.CANDIDATE_COVERAGE_STALE, "A selected Current item was already published by confirmed integration coverage", duplicate);
262
+ return data.coverage;
263
+ }
264
+
265
+ committedCoverageProjection(workspace) {
266
+ const projection = { count: 0, by_stage: {} };
267
+ for (const candidate of this.projectionRecords(workspace)) {
268
+ if (candidate.status !== "committed" || !candidate.coverage) continue;
269
+ for (const entry of candidate.coverage.entries) {
270
+ let current = null;
271
+ try {
272
+ const execution = this.context.storage.readStageExecution(workspace, entry.stage);
273
+ current = execution ? this.context.readStageExecution(workspace, entry.stage).data.current : null;
274
+ } catch { continue; }
275
+ if (current?.id !== entry.current_item_id) continue;
276
+ projection.count += 1;
277
+ const stageProjection = projection.by_stage[entry.stage] ||= { count: 0, truncated: false, items: [] };
278
+ stageProjection.count += 1;
279
+ if (stageProjection.items.length >= projectionCoverageLimit) { stageProjection.truncated = true; continue; }
280
+ stageProjection.items.push({
281
+ candidate: candidate.candidate,
282
+ commit_hash: candidate.commit_hash,
283
+ current_item_id: entry.current_item_id,
284
+ covered_stages: candidate.coverage.entries.map((item) => item.stage),
285
+ committed_at: candidate.committed_at,
286
+ });
287
+ }
288
+ }
289
+ return projection;
290
+ }
291
+
179
292
  capture(workspace, id, input, options = {}) {
180
293
  workspace = options.allowStandard ? this.assertWorkspace(workspace) : this.assertStartup(workspace);
181
294
  const data = this.read(id, workspace);
@@ -220,6 +333,7 @@ export class CandidateStore {
220
333
  if (data.status !== "ready") fail(ERROR_CODES.INVALID_STATE, "Only ready candidates can be committed", { status: data.status });
221
334
  if (message !== undefined && (typeof message !== "string" || !message.trim())) fail(ERROR_CODES.INVALID_ARGUMENT, "Commit message must be a non-empty string");
222
335
  const commitMessage = message === undefined ? data.message : message.trim();
336
+ this.validateCoverage(workspace, data);
223
337
  let metadata;
224
338
  const published = commitPatch(this.context.storage.projectRoot, data.base_head, data.patch, commitMessage, {
225
339
  expectedHead: options.expectedHead,
@@ -319,7 +433,7 @@ export class CandidateStore {
319
433
  options.beforeCandidate?.(inspection);
320
434
  if (repositoryState(this.context.storage.projectRoot).head !== inspection.base_head) fail(ERROR_CODES.COMMIT_ALL_STALE_PLAN, "Git HEAD no longer matches the confirmed commit-all plan", { expected_head: inspection.base_head });
321
435
  const patchHash = (value) => createHash("sha256").update(value).digest("hex");
322
- const duplicate = this.projectionRecords(workspace).filter((candidate) => ["draft", "ready"].includes(candidate.status)
436
+ const duplicate = this.projectionRecords(workspace).filter((candidate) => ["draft", "ready"].includes(candidate.status) && !candidate.coverage
323
437
  && candidate.strategy === "integration" && candidate.base_head === inspection.base_head
324
438
  && candidate.message === inspection.message && JSON.stringify(candidate.related_stages || []) === JSON.stringify(inspection.contributing_stages.map((item) => item.stage)))
325
439
  .find((candidate) => {
package/src/core.js CHANGED
@@ -3,7 +3,7 @@ import path from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { FileStorage, atomicWrite, withLock, defaultConfig, loadConfig } from "./storage.js";
5
5
  import { ERROR_CODES, fail } from "./errors.js";
6
- import { event, reduceSessions, activeSession, assertActive } from "./sessions.js";
6
+ import { event, reduceSessions, activeSession, assertActive, nativeSessionId, openCodeSessionAffinity } from "./sessions.js";
7
7
  import { diagnoseSessionAssociations } from "./session-diagnostics.js";
8
8
  import { generateProjections, renderSessions } from "./projections.js";
9
9
  import { nextKnowledgeId, parseKnowledge, renderKnowledge, validateKnowledgeInput, validateKnowledgeRecords } from "./knowledge.js";
@@ -15,9 +15,27 @@ import { doctorDelivery as runDeliveryDoctor } from "./delivery-doctor.js";
15
15
  import { applyExecutionItemPatch, applyExecutionTextPatchItems, assertExecutionSize, EXECUTION_SECTIONS, executionInputUsesItems, executionItems, executionItemsFromState, executionPatchUsesItems, executionReadModel, executionSchemaFor, normalizeExecutionItemState, normalizeExecutionState } from "./stage-execution.js";
16
16
  import { CAPABILITY_CLASSIFICATIONS, CAPABILITY_DEPTHS, CAPABILITY_PROFILES, capabilityProfileMode, capabilityRecommendations, configureCapabilityMappings, readCapabilityMappings, resetCapabilityMappings, validateCapabilityMappings } from "./capability-profiles.js";
17
17
  import { acknowledgeGitCommit, initializeGitCheckpoint } from "./git-acknowledgement.js";
18
- import { rollbackCommitRef } from "./git-candidates.js";
18
+ import { isCommitAncestor, repositoryState, rollbackCommitRef } from "./git-candidates.js";
19
+ import { enqueueIntegrationNotice } from "./integration-notices.js";
19
20
 
20
21
  const actor = (options) => options.actor || "OpenCode";
22
+ const enqueueCoverageNotices = (storage, publication) => {
23
+ const coverage = publication?.candidate_record?.coverage;
24
+ if (!coverage) return { queued: 0, skipped: 0 };
25
+ let queued = 0;
26
+ for (const entry of coverage.entries) {
27
+ if (enqueueIntegrationNotice(storage.projectRoot, {
28
+ workspace: publication.candidate_record.workspace,
29
+ stage: entry.stage,
30
+ candidate: publication.candidate_record.candidate,
31
+ commitHash: publication.commit,
32
+ currentItemId: entry.current_item_id,
33
+ selectedStages: coverage.entries.map((item) => item.stage),
34
+ personalRoot: storage.personalRoot,
35
+ })) queued += 1;
36
+ }
37
+ return { queued, skipped: coverage.entries.length - queued };
38
+ };
21
39
  const workspaceMode = (data) => data.mode || "standard";
22
40
  const COMMIT_MODES = ["manual", "per_item"];
23
41
  const workspaceCommitMode = (data) => data.commit_mode || "manual";
@@ -59,13 +77,17 @@ const startupWorkflowPolicy = (commitMode = { mode: "manual" }) => ({
59
77
  mode: "startup",
60
78
  guidance: commitMode.mode === "per_item" ? [
61
79
  "A shared dirty worktree and concurrent stages are expected; stages do not own files or commits.",
80
+ "When changes appear mixed or overlapping, report only a bounded, explicitly uncertain list of likely affected stages supported by deterministic local evidence; never infer file or hunk ownership.",
62
81
  "Before each direct commit or candidate fallback, read the effective commit mode again. Proceed only while per_item remains effective; this is an agent policy preflight, not atomic Git enforcement.",
63
82
  "Inspect pending candidates related to this stage, then assess direct publication of the explicit Current-item patch first.",
64
- "Only a ready exact candidate explicitly related to this stage may substitute when direct publication is unsafe but the patch is separable. Shared foundation and integration candidates do not satisfy Current completion.",
83
+ "Only a ready exact candidate explicitly related to this stage may ordinarily substitute when direct publication is unsafe but the patch is separable. Shared foundation and unconfirmed integration candidates do not satisfy Current completion.",
84
+ "A committed integration candidate satisfies publication only when explicit coverage still names this exact Current item. Do not republish or reconstruct provenance; perform remaining verification and complete Current separately.",
85
+ "Never convert an exact candidate into a multi-stage boundary automatically. Explicit user direction and the dedicated coverage confirmation are required.",
65
86
  "After a direct commit, reconcile any stale related candidate intent before completing Current.",
66
87
  "A true patch or merge conflict, failed required verification, or incoherent boundary is a blocker; record it and do not complete Current.",
67
88
  ] : [
68
89
  "A shared dirty worktree and concurrent stages are expected; stages do not own files or commits.",
90
+ "When changes appear mixed or overlapping, report only a bounded, explicitly uncertain list of likely affected stages supported by deterministic local evidence; never infer file or hunk ownership.",
69
91
  "Capture ready work promptly as an explicit commit candidate while unrelated work remains in progress.",
70
92
  "Once a coherent commit intent exists, create or refresh its draft candidate before switching stages or handing off so pending publication remains visible in related stage context.",
71
93
  "On resume, inspect related pending candidates before creating a duplicate or starting another commit boundary.",
@@ -94,25 +116,23 @@ const executionInstruction = (record) => {
94
116
  };
95
117
  const commitModeInstruction = (commitMode) => {
96
118
  if (commitMode.mode !== "per_item") return "";
97
- return `\n\nChecklist commit policy: per_item (${commitMode.source}). This is persistent authorization to publish an explicit, coherent Current-item patch; it never authorizes unrelated changes. Immediately before each direct commit or candidate fallback, call work_context_read_effective_commit_mode and proceed only if it still returns per_item. This is an agent policy preflight, not atomic Git enforcement. Before completing Current, define its explicit patch boundary and run relevant verification. When a direct commit is safe, create it before complete-current. Candidate publication remains separate. A true patch or merge conflict, failed verification, or incoherent boundary is a blocker: record it and do not complete Current.`;
119
+ return `\n\nChecklist commit policy: per_item (${commitMode.source}). This is persistent authorization to publish an explicit, coherent Current-item patch; it never authorizes unrelated changes. Immediately before each direct commit or candidate fallback, call work_context_read_effective_commit_mode and proceed only if it still returns per_item. This is an agent policy preflight, not atomic Git enforcement. Before completing Current, define its explicit patch boundary and run relevant verification. When a direct commit is safe, create it before complete-current. Candidate publication remains separate. A committed integration candidate is a narrow substitute only when explicit durable coverage still names this exact Current item; do not publish it again, and complete Current only after remaining verification. Ordinary integration relations are traceability-only. A true patch or merge conflict, failed verification, or incoherent boundary is a blocker: record it and do not complete Current.`;
98
120
  };
99
121
  const deliveryPlanningInstruction = `\n\nDelivery planning policy:\n- When the user asks how to deploy, treat this as workspace-level delivery planning across all relevant committed changes, not as ownership by the current stage.\n- Inspect the exact commit range and the repository's own deployment documentation, scripts, infrastructure, migrations, container definitions, configuration examples, and CI before proposing commands.\n- Produce an ordered plan covering prerequisites, deployment, verification, rollback, and unresolved blockers. Ask one focused question when the target environment or baseline is genuinely ambiguous.\n- Never persist secret values. Mention only required secret or configuration names.\n- Never mark delivery from a successful commit or push alone. Use explicit delivery confirmation only after the user confirms that the target environment was updated successfully.`;
100
122
  const assertOpenCodeSessionAvailable = (events, opencodeSessionId, workspace, stage) => {
101
123
  if (!opencodeSessionId) return;
102
- const conflicting = reduceSessions(events).find((session) => session.opencode_session_id === opencodeSessionId
103
- && session.state === "active"
104
- && (session.workspace !== workspace || session.stage !== stage));
105
- if (!conflicting) return;
124
+ const affinity = openCodeSessionAffinity(events, opencodeSessionId);
125
+ if (!affinity || (affinity.workspace === workspace && affinity.stage === stage)) return;
106
126
  fail(
107
127
  ERROR_CODES.CURRENT_OPENCODE_SESSION_ALREADY_ASSOCIATED,
108
- "The current OpenCode session is already associated with another active work-context stage",
128
+ "The current OpenCode session has immutable affinity to another work-context stage",
109
129
  {
110
- current_workspace: conflicting.workspace,
111
- current_stage: conflicting.stage,
112
- current_stage_session_id: conflicting.session_id,
130
+ current_workspace: affinity.workspace,
131
+ current_stage: affinity.stage,
132
+ current_stage_session_id: affinity.session_id,
113
133
  requested_workspace: workspace,
114
134
  requested_stage: stage,
115
- next_action: "Open a separate OpenCode session for the requested stage, or explicitly hand off or close the current stage before resuming it here.",
135
+ next_action: "Open a separate OpenCode session for the requested stage. Handoff, close, finish, abandon, and archive do not transfer this session's stage affinity.",
116
136
  },
117
137
  );
118
138
  };
@@ -263,12 +283,16 @@ export class WorkContext {
263
283
  }
264
284
 
265
285
  sessionByOpenCodeId(opencodeSessionId, workspace = null, stage = null, state = "active") {
266
- return reduceSessions(this.storage.readEvents()).filter((session) => session.opencode_session_id === opencodeSessionId
286
+ return reduceSessions(this.storage.readEvents()).filter((session) => nativeSessionId(session) === opencodeSessionId
267
287
  && (!workspace || session.workspace === workspace)
268
288
  && (!stage || session.stage === stage)
269
289
  && (!state || session.state === state)).at(-1) || null;
270
290
  }
271
291
 
292
+ sessionAffinityByOpenCodeId(opencodeSessionId) {
293
+ return openCodeSessionAffinity(this.storage.readEvents(), opencodeSessionId);
294
+ }
295
+
272
296
  diagnoseSessionAssociations(opencodeSessionId = null) {
273
297
  this.storage.assertNoSymlinks();
274
298
  return { ok: true, data: diagnoseSessionAssociations(this.storage.readEvents(), opencodeSessionId) };
@@ -287,6 +311,7 @@ export class WorkContext {
287
311
  const mode = options.mode === undefined ? "standard" : options.mode;
288
312
  if (!["standard", "startup"].includes(mode)) fail(ERROR_CODES.INVALID_ARGUMENT, "Workspace mode must be 'standard' or 'startup'");
289
313
  const requestedWorkspace = options.workspace;
314
+ const startSession = options.startSession !== false;
290
315
  return this.transact("workspace-create", () => {
291
316
  const workspace = requestedWorkspace === undefined ? this.nextWorkspace() : normalizeWorkspaceId(requestedWorkspace);
292
317
  const now = new Date().toISOString();
@@ -297,12 +322,25 @@ export class WorkContext {
297
322
  const planningGoal = "Clarify the work goal and constraints";
298
323
  const planningPrompt = "Diagnose and plan the task without functional changes. Planning stage 01 is a continuously available coordination surface, never a prerequisite gate: do not make implementation, research, review, or other working stages depend on it. Discuss possible solutions, record durable workspace-wide facts, decisions, constraints, important files, and risks through explicit knowledge operations, and decompose the work into the following stages. For each new implementation stage, write a separate detailed prompt with local context, concrete actions, constraints, completion criteria, and the expected result; do not duplicate shared knowledge that every stage receives in resume.context.workspace_knowledge. Ask clarifying questions only when genuinely blocked. Stages must remain in progress until the user explicitly requests stage finish. If the user explicitly agrees to automatic completion for this workspace, add the exact standalone line AUTO_STAGE_FINISH: allowed to this Planning-stage prompt.";
299
324
  this.storage.writeMarkdown(this.storage.stageFile(workspace, "01"), { schema: 1, workspace, stage: "01", title: "Planning", status: "in_progress", goal: planningGoal, prompt: planningPrompt, depends_on: [], owner: actor(this.options), created_at: now, updated_at: now, tracker_links: [] }, body("Planning", planningGoal, planningPrompt));
300
- const sessionId = options.sessionId || randomUUID();
325
+ const sessionId = startSession ? options.sessionId || randomUUID() : null;
301
326
  const workflowPolicy = mode === "startup" && options.opencodeSessionId ? startupWorkflowPolicy() : null;
302
- if (this.storage.readEvents().some((item) => item.session_id === sessionId)) fail(ERROR_CODES.CONFLICT, "Session ID already exists");
303
- this.writeEvents([event("session.started", workspace, "01", 1, sessionId, actor(this.options), { summary: `planning ${title.trim()}`, opencode_session_id: options.opencodeSessionId || null, branch: options.branch || null })]);
304
- initializeGitCheckpoint(this.storage, { workspace, stage: "01", sessionId });
305
- generateProjections(this.storage);
327
+ if (startSession) {
328
+ if (this.storage.readEvents().some((item) => item.session_id === sessionId)) fail(ERROR_CODES.CONFLICT, "Session ID already exists");
329
+ this.writeEvents([event("session.started", workspace, "01", 1, sessionId, actor(this.options), { summary: `planning ${title.trim()}`, opencode_session_id: options.opencodeSessionId || null, branch: options.branch || null })]);
330
+ initializeGitCheckpoint(this.storage, { workspace, stage: "01", sessionId });
331
+ }
332
+ generateProjections(this.storage);
333
+ if (!startSession) return this.result({
334
+ workspace,
335
+ mode,
336
+ commit_mode: "manual",
337
+ stage: "01",
338
+ title: "Planning",
339
+ description: planningGoal,
340
+ session_id: null,
341
+ started: false,
342
+ next_action: "start_new_opencode_session_and_resume",
343
+ }, [workspace, "01"]);
306
344
  return this.result({
307
345
  workspace,
308
346
  mode,
@@ -410,6 +448,13 @@ export class WorkContext {
410
448
  return this.transact("candidate-ready", () => this.result(this.candidates().setStatus(workspace, candidate, "ready"), ["local:candidates"]));
411
449
  }
412
450
 
451
+ confirmCandidateCoverage(workspace, candidate, selectedStages, confirmation) {
452
+ return this.transact("candidate-confirm-coverage", () => this.result(
453
+ this.candidates().confirmCoverage(workspace, candidate, selectedStages, confirmation),
454
+ ["local:candidates"],
455
+ ));
456
+ }
457
+
413
458
  discardCandidate(workspace, candidate) {
414
459
  return this.transact("candidate-discard", () => this.result(this.candidates().setStatus(workspace, candidate, "discarded"), ["local:candidates"]));
415
460
  }
@@ -417,9 +462,36 @@ export class WorkContext {
417
462
  commitCandidate(workspace, candidate, message = undefined, options = {}) {
418
463
  this.storage.assertSafeRoots();
419
464
  // Operations needing both locks always acquire candidate-git before write.
420
- return withLock(this.storage.lockPath("candidate-git"), () => this.transact("candidate-commit", () =>
421
- this.result(this.candidates().commit(workspace, candidate, message, options), ["local:candidates"])
422
- ), { session: this.options.sessionId, owner: actor(this.options) });
465
+ return withLock(this.storage.lockPath("candidate-git"), () => {
466
+ let publication;
467
+ try {
468
+ const result = this.transact("candidate-commit", () => this.result(this.candidates().commit(workspace, candidate, message, {
469
+ ...options,
470
+ afterUpdateRef: (published) => {
471
+ publication = published;
472
+ options.afterUpdateRef?.(published);
473
+ },
474
+ }), ["local:candidates"]));
475
+ const noticeDelivery = enqueueCoverageNotices(this.storage, publication);
476
+ return publication?.candidate_record?.coverage ? { ...result, data: { ...result.data, notice_delivery: noticeDelivery } } : result;
477
+ } catch (error) {
478
+ if (publication) {
479
+ try { rollbackCommitRef(this.storage.projectRoot, publication); }
480
+ catch (rollbackError) {
481
+ const head = repositoryState(this.storage.projectRoot).head;
482
+ if (isCommitAncestor(this.storage.projectRoot, publication.commit, head)) {
483
+ this.transact("candidate-commit-recovery", () => {
484
+ this.candidates().write(publication.candidate_record, publication.patch);
485
+ return this.result(publication.candidate_record, ["local:candidates"]);
486
+ });
487
+ enqueueCoverageNotices(this.storage, publication);
488
+ }
489
+ throw rollbackError;
490
+ }
491
+ }
492
+ throw error;
493
+ }
494
+ }, { session: this.options.sessionId, owner: actor(this.options) });
423
495
  }
424
496
 
425
497
  inspectCommitAll(workspace, options = {}) { return { ok: true, data: this.candidates().inspectAll(workspace, options) }; }
@@ -437,7 +509,13 @@ export class WorkContext {
437
509
  if (publication) {
438
510
  try { rollbackCommitRef(this.storage.projectRoot, publication); }
439
511
  catch (rollbackError) {
440
- this.candidates().write(publication.candidate_record, publication.patch);
512
+ const head = repositoryState(this.storage.projectRoot).head;
513
+ if (isCommitAncestor(this.storage.projectRoot, publication.commit, head)) {
514
+ this.transact("commit-all-recovery", () => {
515
+ this.candidates().write(publication.candidate_record, publication.patch);
516
+ return this.result(publication.candidate_record, ["local:candidates"]);
517
+ });
518
+ }
441
519
  throw rollbackError;
442
520
  }
443
521
  }
@@ -481,7 +559,7 @@ export class WorkContext {
481
559
  if (current) {
482
560
  const canTakeOver = options.takeover
483
561
  && current.session_id !== sessionId
484
- && current.opencode_session_id !== options.opencodeSessionId;
562
+ && nativeSessionId(current) !== options.opencodeSessionId;
485
563
  if (!canTakeOver) fail(ERROR_CODES.ACTIVE_SESSION_EXISTS, "Stage already has an active session");
486
564
  this.writeEvents([event("session.handed_off", workspace, stage, current.ordinal, current.session_id, actor(this.options), { reason: "resumed in a new OpenCode session" })]);
487
565
  }
@@ -510,6 +588,7 @@ export class WorkContext {
510
588
  const commitMode = effectiveCommitMode(workspaceRecord, stageRecord.data);
511
589
  const workflowPolicy = workspaceMode(workspaceRecord) === "startup" && options.opencodeSessionId ? startupWorkflowPolicy(commitMode) : null;
512
590
  const pendingCandidates = workflowPolicy ? this.candidates().activeProjection(workspace).by_stage[stage] || null : null;
591
+ const committedCoverage = workflowPolicy ? this.candidates().committedCoverageProjection(workspace).by_stage[stage] || null : null;
513
592
  const deliveryContext = stage === "01" ? this.deliveries().projection(workspace) : null;
514
593
  const hasDeliveryContext = deliveryContext && (deliveryContext.committed.count || deliveryContext.environments.length || deliveryContext.unavailable);
515
594
  const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
@@ -549,7 +628,8 @@ export class WorkContext {
549
628
  commit_mode: commitMode,
550
629
  ...(execution ? { execution_state: executionReadModel(execution) } : {}),
551
630
  ...(recommendations ? { capability_profiles: recommendations } : {}),
552
- ...(pendingCandidates ? { pending_candidates: pendingCandidates } : {}),
631
+ ...(pendingCandidates ? { pending_candidates: pendingCandidates } : {}),
632
+ ...(committedCoverage ? { committed_integration_coverage: committedCoverage } : {}),
553
633
  ...(hasDeliveryContext ? { delivery_context: deliveryContext } : {}),
554
634
  ...(workflowPolicy ? { workflow_policy: workflowPolicy } : {}),
555
635
  lifecycle: { automatic_finish_allowed: automaticFinish },
@@ -1145,8 +1225,8 @@ export class WorkContext {
1145
1225
  help(command = "") {
1146
1226
  return this.result({
1147
1227
  command,
1148
- syntax: "/wc [create|list|workspace list|workspace rename|workspace mode|workspace commit-mode|stage commit-mode|candidate create|candidate capture|candidate preview|candidate show|candidate list|candidate ready|candidate commit|candidate discard|commit all|commit all confirm|delivery read|delivery explain|delivery doctor|delivery mark|profiles show|profiles setup|profiles reset|workspace finish|workspace reopen|resume|stage add|stage profiles|stage profiles refresh|stage reopen|stage restore|stage rename|stage update|stage update-prompt|stage update-result|stage execution read|stage execution replace|stage execution update|stage execution complete-current|stage force-close|stage archive|stage handoff|stage abandon|stage finish|link-issue|unlink-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]",
1149
- note: "Workspace commit mode is manual or per_item; stages may override or clear to inherit it. Read the effective mode immediately before each direct commit or candidate fallback because this agent-policy preflight is not atomic Git enforcement. Per-item mode authorizes commits only for explicit coherent Current-item boundaries and does not make complete-current perform Git work. Execution recommendations combine a vendor-neutral capability with light, standard, or deep depth; Planning agents infer missing values before stage creation, ordinary refresh updates missing/inferred classifications while preserving explicit assignments, and local depth mappings resolve only an advisory model label; profiles setup gathers mode and mappings through questions, off mode suppresses presentation and resolution, and no profile operation changes a model, agent, reviewer, or session; delivery context is workspace-level local operational state; exact Git range inspection runs only for explicit immutable hashes; stage execution state is a bounded stage-local operational checkpoint; associated startup sessions receive the shared-worktree candidate policy; stage finish requires an explicit user lifecycle request unless Planning contains AUTO_STAGE_FINISH: allowed; recovery operations preserve lifecycle history.",
1228
+ syntax: "/wc [create|list|workspace list|workspace rename|workspace mode|workspace commit-mode|stage commit-mode|candidate create|candidate capture|candidate preview|candidate show|candidate list|candidate ready|candidate confirm-coverage|candidate commit|candidate discard|commit all|commit all confirm|delivery read|delivery explain|delivery doctor|delivery mark|profiles show|profiles setup|profiles reset|workspace finish|workspace reopen|resume|stage add|stage profiles|stage profiles refresh|stage reopen|stage restore|stage rename|stage update|stage update-prompt|stage update-result|stage execution read|stage execution replace|stage execution update|stage execution complete-current|stage force-close|stage archive|stage handoff|stage abandon|stage finish|link-issue|unlink-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]",
1229
+ note: "Workspace commit mode is manual or per_item; stages may override or clear to inherit it. Read the effective mode immediately before each direct commit or candidate fallback because this agent-policy preflight is not atomic Git enforcement. Per-item mode authorizes commits only for explicit coherent Current-item boundaries and does not make complete-current perform Git work. A committed integration candidate is a narrow substitute only after explicit revision-safe multi-stage coverage confirmation; relations alone remain traceability. Execution recommendations combine a vendor-neutral capability with light, standard, or deep depth; Planning agents infer missing values before stage creation, ordinary refresh updates missing/inferred classifications while preserving explicit assignments, and local depth mappings resolve only an advisory model label; profiles setup gathers mode and mappings through questions, off mode suppresses presentation and resolution, and no profile operation changes a model, agent, reviewer, or session; delivery context is workspace-level local operational state; exact Git range inspection runs only for explicit immutable hashes; stage execution state is a bounded stage-local operational checkpoint; associated startup sessions receive the shared-worktree candidate policy; stage finish requires an explicit user lifecycle request unless Planning contains AUTO_STAGE_FINISH: allowed; recovery operations preserve lifecycle history.",
1150
1230
  }, []);
1151
1231
  }
1152
1232
 
package/src/errors.js CHANGED
@@ -15,6 +15,9 @@ export const ERROR_CODES = Object.freeze({
15
15
  CANDIDATE_UNSUPPORTED: "CANDIDATE_UNSUPPORTED", CANDIDATE_STALE_BASE: "CANDIDATE_STALE_BASE",
16
16
  CANDIDATE_CONFLICT: "CANDIDATE_CONFLICT", CANDIDATE_DETACHED_HEAD: "CANDIDATE_DETACHED_HEAD",
17
17
  CANDIDATE_REF_RACE: "CANDIDATE_REF_RACE", CANDIDATE_COMMIT_FAILED: "CANDIDATE_COMMIT_FAILED",
18
+ CANDIDATE_COVERAGE_CONFIRMATION_REQUIRED: "CANDIDATE_COVERAGE_CONFIRMATION_REQUIRED",
19
+ CANDIDATE_COVERAGE_CURRENT_REQUIRED: "CANDIDATE_COVERAGE_CURRENT_REQUIRED",
20
+ CANDIDATE_COVERAGE_STALE: "CANDIDATE_COVERAGE_STALE",
18
21
  COMMIT_ALL_CONFIRMATION_REQUIRED: "COMMIT_ALL_CONFIRMATION_REQUIRED", COMMIT_ALL_NO_CHANGES: "COMMIT_ALL_NO_CHANGES",
19
22
  COMMIT_ALL_UNSAFE_STATE: "COMMIT_ALL_UNSAFE_STATE", COMMIT_ALL_INCOHERENT_BOUNDARY: "COMMIT_ALL_INCOHERENT_BOUNDARY",
20
23
  COMMIT_ALL_STALE_PLAN: "COMMIT_ALL_STALE_PLAN", COMMIT_ALL_VERIFICATION_FAILED: "COMMIT_ALL_VERIFICATION_FAILED",