opencode-work-context 0.14.0 → 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,8 @@ 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
+ import { diagnoseSessionAssociations } from "./session-diagnostics.js";
7
8
  import { generateProjections, renderSessions } from "./projections.js";
8
9
  import { nextKnowledgeId, parseKnowledge, renderKnowledge, validateKnowledgeInput, validateKnowledgeRecords } from "./knowledge.js";
9
10
  import { normalizeStageId, normalizeWorkspaceId } from "./identifiers.js";
@@ -14,9 +15,27 @@ import { doctorDelivery as runDeliveryDoctor } from "./delivery-doctor.js";
14
15
  import { applyExecutionItemPatch, applyExecutionTextPatchItems, assertExecutionSize, EXECUTION_SECTIONS, executionInputUsesItems, executionItems, executionItemsFromState, executionPatchUsesItems, executionReadModel, executionSchemaFor, normalizeExecutionItemState, normalizeExecutionState } from "./stage-execution.js";
15
16
  import { CAPABILITY_CLASSIFICATIONS, CAPABILITY_DEPTHS, CAPABILITY_PROFILES, capabilityProfileMode, capabilityRecommendations, configureCapabilityMappings, readCapabilityMappings, resetCapabilityMappings, validateCapabilityMappings } from "./capability-profiles.js";
16
17
  import { acknowledgeGitCommit, initializeGitCheckpoint } from "./git-acknowledgement.js";
17
- import { rollbackCommitRef } from "./git-candidates.js";
18
+ import { isCommitAncestor, repositoryState, rollbackCommitRef } from "./git-candidates.js";
19
+ import { enqueueIntegrationNotice } from "./integration-notices.js";
18
20
 
19
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
+ };
20
39
  const workspaceMode = (data) => data.mode || "standard";
21
40
  const COMMIT_MODES = ["manual", "per_item"];
22
41
  const workspaceCommitMode = (data) => data.commit_mode || "manual";
@@ -58,13 +77,17 @@ const startupWorkflowPolicy = (commitMode = { mode: "manual" }) => ({
58
77
  mode: "startup",
59
78
  guidance: commitMode.mode === "per_item" ? [
60
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.",
61
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.",
62
82
  "Inspect pending candidates related to this stage, then assess direct publication of the explicit Current-item patch first.",
63
- "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.",
64
86
  "After a direct commit, reconcile any stale related candidate intent before completing Current.",
65
87
  "A true patch or merge conflict, failed required verification, or incoherent boundary is a blocker; record it and do not complete Current.",
66
88
  ] : [
67
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.",
68
91
  "Capture ready work promptly as an explicit commit candidate while unrelated work remains in progress.",
69
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.",
70
93
  "On resume, inspect related pending candidates before creating a duplicate or starting another commit boundary.",
@@ -93,9 +116,26 @@ const executionInstruction = (record) => {
93
116
  };
94
117
  const commitModeInstruction = (commitMode) => {
95
118
  if (commitMode.mode !== "per_item") return "";
96
- 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.`;
97
120
  };
98
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.`;
122
+ const assertOpenCodeSessionAvailable = (events, opencodeSessionId, workspace, stage) => {
123
+ if (!opencodeSessionId) return;
124
+ const affinity = openCodeSessionAffinity(events, opencodeSessionId);
125
+ if (!affinity || (affinity.workspace === workspace && affinity.stage === stage)) return;
126
+ fail(
127
+ ERROR_CODES.CURRENT_OPENCODE_SESSION_ALREADY_ASSOCIATED,
128
+ "The current OpenCode session has immutable affinity to another work-context stage",
129
+ {
130
+ current_workspace: affinity.workspace,
131
+ current_stage: affinity.stage,
132
+ current_stage_session_id: affinity.session_id,
133
+ requested_workspace: workspace,
134
+ requested_stage: stage,
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.",
136
+ },
137
+ );
138
+ };
99
139
  const assertNoSymlinkPath = (file) => { let current = path.parse(file).root; for (const part of file.slice(current.length).split(path.sep).filter(Boolean)) { current = path.join(current, part); try { if (fs.lstatSync(current).isSymbolicLink()) fail(ERROR_CODES.STORAGE_ERROR, `Symlink path component is not supported: ${current}`); } catch (error) { if (error.code !== "ENOENT") throw error; break; } } };
100
140
 
101
141
  function parseIssue(url) {
@@ -243,12 +283,21 @@ export class WorkContext {
243
283
  }
244
284
 
245
285
  sessionByOpenCodeId(opencodeSessionId, workspace = null, stage = null, state = "active") {
246
- return reduceSessions(this.storage.readEvents()).filter((session) => session.opencode_session_id === opencodeSessionId
286
+ return reduceSessions(this.storage.readEvents()).filter((session) => nativeSessionId(session) === opencodeSessionId
247
287
  && (!workspace || session.workspace === workspace)
248
288
  && (!stage || session.stage === stage)
249
289
  && (!state || session.state === state)).at(-1) || null;
250
290
  }
251
291
 
292
+ sessionAffinityByOpenCodeId(opencodeSessionId) {
293
+ return openCodeSessionAffinity(this.storage.readEvents(), opencodeSessionId);
294
+ }
295
+
296
+ diagnoseSessionAssociations(opencodeSessionId = null) {
297
+ this.storage.assertNoSymlinks();
298
+ return { ok: true, data: diagnoseSessionAssociations(this.storage.readEvents(), opencodeSessionId) };
299
+ }
300
+
252
301
  assertDependenciesCompleted(workspace, stageRecord) {
253
302
  const stages = this.listStages(workspace).data.stages;
254
303
  for (const dependency of stageRecord.data.depends_on) {
@@ -262,21 +311,36 @@ export class WorkContext {
262
311
  const mode = options.mode === undefined ? "standard" : options.mode;
263
312
  if (!["standard", "startup"].includes(mode)) fail(ERROR_CODES.INVALID_ARGUMENT, "Workspace mode must be 'standard' or 'startup'");
264
313
  const requestedWorkspace = options.workspace;
314
+ const startSession = options.startSession !== false;
265
315
  return this.transact("workspace-create", () => {
266
316
  const workspace = requestedWorkspace === undefined ? this.nextWorkspace() : normalizeWorkspaceId(requestedWorkspace);
267
317
  const now = new Date().toISOString();
268
318
  if (fs.existsSync(this.storage.workspaceDir(workspace))) fail(ERROR_CODES.CONFLICT, "Workspace already exists");
319
+ assertOpenCodeSessionAvailable(this.storage.readEvents(), options.opencodeSessionId, workspace, "01");
269
320
  fs.mkdirSync(path.join(this.storage.workspaceDir(workspace), "stages"), { recursive: true });
270
321
  this.storage.writeMarkdown(this.storage.workspaceFile(workspace), { schema: 1, workspace, title: title.trim(), status: "in_progress", mode, commit_mode: "manual", created_at: now, updated_at: now, tracker_links: [] }, body(title));
271
322
  const planningGoal = "Clarify the work goal and constraints";
272
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.";
273
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));
274
- const sessionId = options.sessionId || randomUUID();
325
+ const sessionId = startSession ? options.sessionId || randomUUID() : null;
275
326
  const workflowPolicy = mode === "startup" && options.opencodeSessionId ? startupWorkflowPolicy() : null;
276
- if (this.storage.readEvents().some((item) => item.session_id === sessionId)) fail(ERROR_CODES.CONFLICT, "Session ID already exists");
277
- 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 })]);
278
- initializeGitCheckpoint(this.storage, { workspace, stage: "01", sessionId });
279
- 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"]);
280
344
  return this.result({
281
345
  workspace,
282
346
  mode,
@@ -384,6 +448,13 @@ export class WorkContext {
384
448
  return this.transact("candidate-ready", () => this.result(this.candidates().setStatus(workspace, candidate, "ready"), ["local:candidates"]));
385
449
  }
386
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
+
387
458
  discardCandidate(workspace, candidate) {
388
459
  return this.transact("candidate-discard", () => this.result(this.candidates().setStatus(workspace, candidate, "discarded"), ["local:candidates"]));
389
460
  }
@@ -391,9 +462,36 @@ export class WorkContext {
391
462
  commitCandidate(workspace, candidate, message = undefined, options = {}) {
392
463
  this.storage.assertSafeRoots();
393
464
  // Operations needing both locks always acquire candidate-git before write.
394
- return withLock(this.storage.lockPath("candidate-git"), () => this.transact("candidate-commit", () =>
395
- this.result(this.candidates().commit(workspace, candidate, message, options), ["local:candidates"])
396
- ), { 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) });
397
495
  }
398
496
 
399
497
  inspectCommitAll(workspace, options = {}) { return { ok: true, data: this.candidates().inspectAll(workspace, options) }; }
@@ -411,7 +509,13 @@ export class WorkContext {
411
509
  if (publication) {
412
510
  try { rollbackCommitRef(this.storage.projectRoot, publication); }
413
511
  catch (rollbackError) {
414
- 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
+ }
415
519
  throw rollbackError;
416
520
  }
417
521
  }
@@ -447,14 +551,15 @@ export class WorkContext {
447
551
  stage = normalizeStageId(stage);
448
552
  const sessionId = options.sessionId || randomUUID();
449
553
  return this.transact(`stage-${workspace}-${stage}`, () => {
554
+ const events = this.storage.readEvents();
555
+ assertOpenCodeSessionAvailable(events, options.opencodeSessionId, workspace, stage);
450
556
  const stageRecord = this.storage.readStage(workspace, stage);
451
557
  this.assertDependenciesCompleted(workspace, stageRecord);
452
- const events = this.storage.readEvents();
453
558
  const current = activeSession(events, workspace, stage);
454
559
  if (current) {
455
560
  const canTakeOver = options.takeover
456
561
  && current.session_id !== sessionId
457
- && current.opencode_session_id !== options.opencodeSessionId;
562
+ && nativeSessionId(current) !== options.opencodeSessionId;
458
563
  if (!canTakeOver) fail(ERROR_CODES.ACTIVE_SESSION_EXISTS, "Stage already has an active session");
459
564
  this.writeEvents([event("session.handed_off", workspace, stage, current.ordinal, current.session_id, actor(this.options), { reason: "resumed in a new OpenCode session" })]);
460
565
  }
@@ -483,6 +588,7 @@ export class WorkContext {
483
588
  const commitMode = effectiveCommitMode(workspaceRecord, stageRecord.data);
484
589
  const workflowPolicy = workspaceMode(workspaceRecord) === "startup" && options.opencodeSessionId ? startupWorkflowPolicy(commitMode) : null;
485
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;
486
592
  const deliveryContext = stage === "01" ? this.deliveries().projection(workspace) : null;
487
593
  const hasDeliveryContext = deliveryContext && (deliveryContext.committed.count || deliveryContext.environments.length || deliveryContext.unavailable);
488
594
  const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
@@ -522,7 +628,8 @@ export class WorkContext {
522
628
  commit_mode: commitMode,
523
629
  ...(execution ? { execution_state: executionReadModel(execution) } : {}),
524
630
  ...(recommendations ? { capability_profiles: recommendations } : {}),
525
- ...(pendingCandidates ? { pending_candidates: pendingCandidates } : {}),
631
+ ...(pendingCandidates ? { pending_candidates: pendingCandidates } : {}),
632
+ ...(committedCoverage ? { committed_integration_coverage: committedCoverage } : {}),
526
633
  ...(hasDeliveryContext ? { delivery_context: deliveryContext } : {}),
527
634
  ...(workflowPolicy ? { workflow_policy: workflowPolicy } : {}),
528
635
  lifecycle: { automatic_finish_allowed: automaticFinish },
@@ -1118,8 +1225,8 @@ export class WorkContext {
1118
1225
  help(command = "") {
1119
1226
  return this.result({
1120
1227
  command,
1121
- 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]",
1122
- 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.",
1123
1230
  }, []);
1124
1231
  }
1125
1232
 
package/src/errors.js CHANGED
@@ -1,6 +1,8 @@
1
1
  export const ERROR_CODES = Object.freeze({
2
2
  NOT_FOUND: "NOT_FOUND", INVALID_ARGUMENT: "INVALID_ARGUMENT", INVALID_STATE: "INVALID_STATE",
3
3
  ACTIVE_SESSION_EXISTS: "ACTIVE_SESSION_EXISTS", SESSION_NOT_ACTIVE: "SESSION_NOT_ACTIVE",
4
+ CURRENT_OPENCODE_SESSION_ALREADY_ASSOCIATED: "CURRENT_OPENCODE_SESSION_ALREADY_ASSOCIATED",
5
+ SESSION_ASSOCIATION_SPLIT_BRAIN: "SESSION_ASSOCIATION_SPLIT_BRAIN",
4
6
  LOCKED: "LOCKED", STALE_LOCK: "STALE_LOCK", CONFLICT: "CONFLICT", INVALID_ISSUE_URL: "INVALID_ISSUE_URL",
5
7
  ADAPTER_UNAVAILABLE: "ADAPTER_UNAVAILABLE", STORAGE_ERROR: "STORAGE_ERROR", CONFIRMATION_REQUIRED: "CONFIRMATION_REQUIRED",
6
8
  STAGE_CONTEXT_REQUIRED: "STAGE_CONTEXT_REQUIRED",
@@ -13,6 +15,9 @@ export const ERROR_CODES = Object.freeze({
13
15
  CANDIDATE_UNSUPPORTED: "CANDIDATE_UNSUPPORTED", CANDIDATE_STALE_BASE: "CANDIDATE_STALE_BASE",
14
16
  CANDIDATE_CONFLICT: "CANDIDATE_CONFLICT", CANDIDATE_DETACHED_HEAD: "CANDIDATE_DETACHED_HEAD",
15
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",
16
21
  COMMIT_ALL_CONFIRMATION_REQUIRED: "COMMIT_ALL_CONFIRMATION_REQUIRED", COMMIT_ALL_NO_CHANGES: "COMMIT_ALL_NO_CHANGES",
17
22
  COMMIT_ALL_UNSAFE_STATE: "COMMIT_ALL_UNSAFE_STATE", COMMIT_ALL_INCOHERENT_BOUNDARY: "COMMIT_ALL_INCOHERENT_BOUNDARY",
18
23
  COMMIT_ALL_STALE_PLAN: "COMMIT_ALL_STALE_PLAN", COMMIT_ALL_VERIFICATION_FAILED: "COMMIT_ALL_VERIFICATION_FAILED",
package/src/index.js CHANGED
@@ -3,6 +3,7 @@ export * from "./identifiers.js";
3
3
  export * from "./markdown.js";
4
4
  export * from "./storage.js";
5
5
  export * from "./sessions.js";
6
+ export * from "./session-diagnostics.js";
6
7
  export * from "./projections.js";
7
8
  export * from "./title.js";
8
9
  export * from "./core.js";