opencode-work-context 0.13.0 → 0.14.1

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/README.md CHANGED
@@ -216,6 +216,42 @@ Schema 1 string arrays and schema 2 `{ id, text }` records remain readable.
216
216
  Schema 3 is selected when details first appear and remains the record version if
217
217
  the final detail is later cleared. Set structured edit `details` to `null` to
218
218
  clear it.
219
+
220
+ ### Checklist Commit Mode
221
+
222
+ Workspace metadata persists `commit_mode` as `manual` (the default) or
223
+ `per_item`. A stage may override this setting, or clear its override to inherit
224
+ the workspace value:
225
+
226
+ ```text
227
+ /wc workspace commit-mode 000001 per_item
228
+ /wc stage commit-mode 000001 02 manual
229
+ /wc stage commit-mode 000001 02 clear
230
+ ```
231
+
232
+ Legacy schema-1 workspace and stage records without `commit_mode` remain
233
+ readable as `manual`; reads do not migrate them. The effective mode and whether
234
+ it comes from the workspace or stage are returned on resume.
235
+
236
+ `per_item` is persistent authorization, not an implicit Git side effect. Before
237
+ each direct commit or candidate fallback, the agent must read the effective mode
238
+ again and proceed only while it returns `per_item`. This is an agent-policy
239
+ preflight, not atomic Git enforcement. Before completing Current, the agent must
240
+ define an explicit patch boundary, run relevant verification, and create a safe
241
+ direct commit. Candidate publication remains separate. The user-only
242
+ `commited <SHA>` acknowledgement contract is independent of agent-created
243
+ per-item commits.
244
+
245
+ In startup mode, the agent first inspects pending candidates related to the
246
+ current stage and assesses direct publication. Only a ready `exact` candidate
247
+ explicitly related to the current stage may substitute when direct publication
248
+ is unsafe but the patch is separable. `shared_foundation` and `integration`
249
+ candidates do not satisfy Current completion. A real patch or merge conflict,
250
+ failed verification, or incoherent boundary remains a blocker and Current must
251
+ not be completed. This policy never authorizes unrelated changes.
252
+
253
+ `complete-current` remains an atomic ledger-only operation: it never runs Git
254
+ or creates a commit itself.
219
255
  After completing Current, read the latest revision and use `complete-current` to
220
256
  move it to Completed and promote the next Queued item. Update the ledger at
221
257
  meaningful boundaries, not after every edit. Checklist state never completes a
@@ -437,6 +473,28 @@ nothing. A failed canonical start removes the newly created OpenCode session
437
473
  when the host supports deletion; a navigation failure leaves the new linked
438
474
  session available for a later switch.
439
475
 
476
+ `work_context_start_session` never rebinds the OpenCode session that invokes it.
477
+ If that native session is already associated with another active stage, the
478
+ operation fails atomically with
479
+ `CURRENT_OPENCODE_SESSION_ALREADY_ASSOCIATED`. The error identifies the current
480
+ and requested stage sessions and directs the caller to open a separate OpenCode
481
+ session or explicitly hand off or close the current stage first. Repeating the
482
+ operation for the already-associated stage retains the existing
483
+ `ACTIVE_SESSION_EXISTS` result and never creates a duplicate.
484
+ The same association invariant applies when the core creates a workspace; the
485
+ structured create tool leaves a new workspace unassociated when invoked from an
486
+ already-associated OpenCode session.
487
+
488
+ Read-only stage and workspace snapshots include `sessionDiagnostics`. Legacy
489
+ event streams in which one OpenCode session is associated with multiple active
490
+ stage sessions report `SESSION_ASSOCIATION_SPLIT_BRAIN` and non-destructive
491
+ recovery guidance. Recovery treats the earliest active association as the
492
+ presumed original pending review and never recommends force-closing it merely
493
+ because a later conflicting association exists.
494
+ Contextual mutations that omit an ambiguous workspace or stage fail with the
495
+ same `SESSION_ASSOCIATION_SPLIT_BRAIN` code. Recovery must name the incorrect
496
+ workspace and stage explicitly before handing it off or closing it.
497
+
440
498
  The command palette still exposes `work_context.actions` for the broader action
441
499
  modal. Its command actions only prepare visible `/wc` commands and never submit
442
500
  or invoke an LLM. The switcher uses OpenCode's public structured session-command
package/commands/wc.md CHANGED
@@ -3,7 +3,7 @@ description: Explicit work-context lifecycle commands backed by structured tools
3
3
  subtask: false
4
4
  ---
5
5
 
6
- <!-- opencode-work-context-protocol: {"schema":1,"major":1,"minor":3,"descriptor_hash":"sha256:08ec85ffd42546b86bd07ce8f924ddc3f1e671c54211c161751e4af8b91fae32"} -->
6
+ <!-- opencode-work-context-protocol: {"schema":1,"major":1,"minor":5,"descriptor_hash":"sha256:69c90783d3bc08ffd46dc764ba93a0feabaaf10f1e4d7fe0b170c633e6dd20e0"} -->
7
7
 
8
8
  Interpret `/wc $ARGUMENTS` as an explicit work-context operation. Use the matching
9
9
  `work_context_*` custom tool registered by the installed package plugin with structured arguments. Never edit work-context
@@ -31,6 +31,8 @@ Use these exact tool mappings; do not invent shortened tool names:
31
31
  - `workspace list <workspace>` or `<workspace> list` -> `work_context_workspace_list`
32
32
  - `workspace rename <workspace> "title"` -> `work_context_rename_workspace`
33
33
  - `workspace mode <workspace> <standard|startup>` -> `work_context_set_workspace_mode`
34
+ - `workspace commit-mode <workspace> <manual|per_item>` -> `work_context_set_workspace_commit_mode`
35
+ - `stage commit-mode read [<workspace>] [<stage>]` -> `work_context_read_effective_commit_mode`
34
36
  - `candidate create <workspace> "title" ["message"] [strategy <exact|shared_foundation|integration>] [stages <stage>...]` -> `work_context_create_candidate`
35
37
  - `candidate capture <workspace> <candidateId> paths <path>...` or `candidate capture <workspace> <candidateId> patch "patch"` -> `work_context_capture_candidate`
36
38
  - `candidate preview <workspace> <candidateId>` -> `work_context_preview_candidate`
@@ -55,6 +57,7 @@ Use these exact tool mappings; do not invent shortened tool names:
55
57
  - `profiles reset` -> ask for global or project scope and confirmation, then `work_context_reset_capability_profiles`
56
58
  - `stage add [<workspace>] ...` -> `work_context_add_stage` (optional `prompt`; infer missing execution capability and depth from the complete stage context before calling the tool)
57
59
  - `stage profiles [<workspace>] [<stage>] [execution <routine|implementation|architecture|security|review> depth <light|standard|deep>|clear] [review <routine|implementation|architecture|security|review|clear>]` -> `work_context_set_stage_profiles`
60
+ - `stage commit-mode [<workspace>] [<stage>] <manual|per_item|clear>` -> `work_context_set_stage_commit_mode`
58
61
  - `stage profiles refresh <workspace> [<stage>] [--include-explicit]` -> inspect current stage context, infer classifications, then `work_context_refresh_stage_profiles`
59
62
  - `stage reopen <workspace> <stage> "reason"` -> `work_context_reopen_stage`
60
63
  - `stage restore <workspace> <stage> "reason"` -> `work_context_restore_stage`
@@ -80,6 +83,8 @@ Supported syntax:
80
83
  - `workspace list <workspace>`
81
84
  - `workspace rename <workspace> "title"`
82
85
  - `workspace mode <workspace> <standard|startup>`
86
+ - `workspace commit-mode <workspace> <manual|per_item>`
87
+ - `stage commit-mode read [<workspace>] [<stage>]`
83
88
  - `candidate create <workspace> "title" ["message"] [strategy <exact|shared_foundation|integration>] [stages <stage>...]`
84
89
  - `candidate capture <workspace> <candidateId> paths <path>...`
85
90
  - `candidate capture <workspace> <candidateId> patch "patch"`
@@ -105,6 +110,7 @@ Supported syntax:
105
110
  - `profiles reset`
106
111
  - `stage add [<workspace>] "title" ["prompt"] [execution <routine|implementation|architecture|security|review> depth <light|standard|deep>] [review <routine|implementation|architecture|security|review>]`
107
112
  - `stage profiles [<workspace>] [<stage>] [execution <routine|implementation|architecture|security|review> depth <light|standard|deep>|clear] [review <routine|implementation|architecture|security|review|clear>]`
113
+ - `stage commit-mode [<workspace>] [<stage>] <manual|per_item|clear>`
108
114
  - `stage profiles refresh <workspace> [<stage>] [--include-explicit]`
109
115
  - `stage reopen <workspace> <stage> "reason"`
110
116
  - `stage restore <workspace> <stage> "reason"`
@@ -147,6 +153,9 @@ Supported syntax:
147
153
  - update execution state after meaningful scope changes, decisions, substantial work, blockers, or verification changes and before handoff; do not update it for every trivial edit or tool call
148
154
  - work only on Current by default. Do not combine Queued items into one change set unless the user explicitly asks to batch them
149
155
  - after completing a meaningful Current item, read the latest revision and call `stage execution complete-current`; it atomically moves only Current to Completed and promotes the next queued item. Retain ordering and briefly report the transition in normal output
156
+ - workspace `commit_mode` is persistent checklist commit authorization with `manual` as the default and `per_item` as the only commit policy. A stage may override it or use `clear` to inherit. It does not make `stage execution complete-current` perform Git work.
157
+ - in effective `per_item` mode, immediately before each direct commit or candidate fallback, call `stage commit-mode read` and proceed only when it still returns `per_item`. This is an agent-policy preflight, not atomic Git enforcement. Define an explicit patch boundary, run relevant verification, and create a safe direct commit before complete-current. Candidate publication remains separate.
158
+ - in startup plus `per_item` mode, inspect pending candidates related to the current stage and assess direct publication first. Only a ready `exact` candidate explicitly related to the current stage may substitute when direct publication is unsafe but separable; `shared_foundation` and `integration` candidates do not satisfy Current completion. Reconcile stale related candidate intent after a direct commit. A true patch or merge conflict, failed verification, or incoherent boundary is a blocker: record it and do not complete Current. Authorization never includes unrelated changes.
150
159
  - `resume` returns `resume.presentation` and `resume.context`; before doing any work, report a concise human-oriented summary in the user's language with the stage title, a plain-language Goal, previous progress when useful, and the immediate next action
151
160
  - when the saved prompt contains several clear deliverables, add `In this stage we will` with 2-5 short outcome-oriented bullets derived only from the prompt, previous result, and workspace knowledge; do not invent scope, and omit this block for a small stage
152
161
  - do not expose raw workspace/stage/session identifiers, ordinals, `ok` flags, or absent error codes in the user-facing resume summary
@@ -155,13 +164,17 @@ Supported syntax:
155
164
  - Planning-stage resume may include `resume.context.delivery_context`, a bounded workspace-level summary of committed candidates and environment checkpoints; it is release coordination context, not stage ownership
156
165
  - when the user asks how to deploy from Planning, inspect the exact commit range and the repository's own deployment documentation, scripts, infrastructure, migrations, container definitions, configuration examples, and CI; produce ordered prerequisites, deployment, verification, rollback, and unresolved blockers instead of assuming that push or one generic command is sufficient
157
166
  - delivery planning must never persist secret values; mention only required secret or configuration names, ask one focused question when environment or baseline is ambiguous, and never mark delivery merely because commit, push, or CI succeeded
158
- - an associated OpenCode session resumed in a `startup` workspace receives `resume.context.workflow_policy`; follow it as active agent policy: a shared dirty worktree and concurrent stages are expected, stages do not own files or commits, and ready work should be captured promptly into an explicit candidate; once a coherent commit intent exists, create or refresh its draft candidate before switching stages or handing off; on resume inspect `resume.context.pending_candidates` before creating a duplicate or another commit boundary; prefer an `exact` candidate when safely separable, use `shared_foundation` when several stages use one coherent change, and use `integration` when intertwined changes form one reviewable and testable result; mixed provenance and complete files containing unrelated stage work are not reasons to require prior commits or stop; stop only for a concrete patch conflict, an incoherent candidate boundary, or failed required verification
167
+ - an associated OpenCode session resumed in a `startup` workspace receives `resume.context.workflow_policy`; follow it as active agent policy. Under effective `manual` commit mode, a shared dirty worktree and concurrent stages are expected, stages do not own files or commits, and ready work should be captured promptly into an explicit candidate; once a coherent commit intent exists, create or refresh its draft candidate before switching stages or handing off; on resume inspect `resume.context.pending_candidates` before creating a duplicate or another commit boundary; prefer an `exact` candidate when safely separable, use `shared_foundation` when several stages use one coherent change, and use `integration` when intertwined changes form one reviewable and testable result; mixed provenance and complete files containing unrelated stage work are not reasons to require prior commits or stop; stop only for a concrete patch conflict, an incoherent candidate boundary, or failed required verification. Under effective `per_item` mode, use the direct-first and exact-related fallback policy above instead.
159
168
  - standard-mode and unassociated core sessions do not receive startup policy; retain the existing conservative worktree behavior there
160
169
  - after presenting the summary, continue work immediately when `resume.next_action` is `start_work`; do not ask for generic confirmation
161
170
  - a stage may require confirmation only with an exact standalone `RESUME_CONFIRMATION: required` line in its saved prompt; when `resume.next_action` is `await_confirmation`, present the summary and wait before inspecting or modifying application code
162
171
  - `create` enters the new workspace's Planning stage in the current OpenCode session only when that session is not yet in a workspace; otherwise it only creates the workspace and its planning session
163
172
  - `stage add` creates a stage; when the current OpenCode session is not associated with a workspace, it also enters the new stage in that session
164
173
  - when `stage add` is invoked from an associated session, it only creates a planned stage and leaves the current stage unchanged; enter it later with an explicit `resume <workspace> <stage>` in a separate OpenCode session
174
+ - `resume` never rebinds the OpenCode session that invokes it: while that session is associated with active stage A, attempting to start stage B must fail atomically with `CURRENT_OPENCODE_SESSION_ALREADY_ASSOCIATED`; open a separate OpenCode session or explicitly hand off or close A first, and never hide the transition behind automatic handoff
175
+ - a repeated `resume` for the stage already associated with the current OpenCode session returns the existing typed `ACTIVE_SESSION_EXISTS` result and must not create a duplicate stage session
176
+ - read-only session diagnostics report legacy duplicate active associations for one OpenCode session as `SESSION_ASSOCIATION_SPLIT_BRAIN`; preserve the earliest association as the presumed original until reviewed, explicitly hand off or close only the incorrect later association, and never force-close the presumed original merely because the conflict exists
177
+ - while `SESSION_ASSOCIATION_SPLIT_BRAIN` is present, contextual mutations must fail closed when omitted identifiers are ambiguous; recovery must explicitly name both the incorrect workspace and stage before handoff or close
165
178
  - `resume` returns `resume.next_action` and `resume.instruction`; begin or continue implementation when the stage prompt is non-empty unless it explicitly requires confirmation or contains an unresolved decision that genuinely blocks progress
166
179
  - `commited` is intentionally spelled with one `t`. It is a deterministic light control-plane acknowledgement for a user-created current-HEAD commit in the active stage session. Call the structured tool directly and return its compact result without a second analysis response. It validates the supplied short or full SHA, attached branch, fast-forward checkpoint, and absence of Git operations; it never infers ownership or changes candidates.
167
180
  - when `resume.next_action` is `ask_questions`, do not inspect or modify application code and ask the user focused questions needed to make the prompt actionable
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "opencode-work-context",
3
3
  "type": "module",
4
- "version": "0.13.0",
4
+ "version": "0.14.1",
5
5
  "description": "Filesystem work-context core and OpenCode adapter",
6
6
  "license": "MIT",
7
7
  "author": {
@@ -103,7 +103,7 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention,
103
103
  stage.tracker_links?.length && `Tasks: ${stage.tracker_links.map(trackerLinkText).join(", ")}`,
104
104
  stage.depends_on?.length && `Deps: ${formatStageIds(stage.depends_on)}`,
105
105
  ].filter(Boolean).join(" · ");
106
- const metadata = showDependencies ? [recommendation, stageMetadata, stageCandidateText(stage), stage.current && checklistSummaryText(stage.execution)].filter(Boolean).join("\n") : "";
106
+ const metadata = showDependencies ? [recommendation, stage.commit_mode && `Commits: ${stage.commit_mode.replace("_", "-")} (override)`, stageMetadata, stageCandidateText(stage), stage.current && checklistSummaryText(stage.execution)].filter(Boolean).join("\n") : "";
107
107
  const attentionSignal = attentionSummaryText(unread);
108
108
  const onMouseDown = (event) => {
109
109
  if (event?.button != null && event.button !== 0) return;
package/src/core.js CHANGED
@@ -4,6 +4,7 @@ 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
6
  import { event, reduceSessions, activeSession, assertActive } 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";
@@ -18,6 +19,15 @@ import { rollbackCommitRef } from "./git-candidates.js";
18
19
 
19
20
  const actor = (options) => options.actor || "OpenCode";
20
21
  const workspaceMode = (data) => data.mode || "standard";
22
+ const COMMIT_MODES = ["manual", "per_item"];
23
+ const workspaceCommitMode = (data) => data.commit_mode || "manual";
24
+ const effectiveCommitMode = (workspace, stage) => ({
25
+ mode: stage.commit_mode || workspaceCommitMode(workspace),
26
+ source: stage.commit_mode ? "stage" : "workspace",
27
+ });
28
+ const assertCommitMode = (value, name = "commit mode") => {
29
+ if (!COMMIT_MODES.includes(value)) fail(ERROR_CODES.INVALID_ARGUMENT, `${name} must be one of: ${COMMIT_MODES.join(", ")}`);
30
+ };
21
31
  const assertCapabilityProfile = (value, name) => {
22
32
  if (value !== undefined && value !== null && !CAPABILITY_PROFILES.includes(value)) fail(ERROR_CODES.INVALID_ARGUMENT, `${name} must be one of: ${CAPABILITY_PROFILES.join(", ")}`);
23
33
  };
@@ -45,9 +55,16 @@ const preservedStageResult = (record) => stageResult(record)
45
55
  const appendHistory = (bodyText, heading, entry) => `${bodyText.trimEnd()}${bodyText.includes(`\n## ${heading}\n`) ? "" : `\n\n## ${heading}\n`}\n- ${entry}\n`;
46
56
  const automaticFinishAllowed = (storage, workspace) => /(?:^|\n)AUTO_STAGE_FINISH:\s*allowed\s*$/mi.test(storage.readStage(workspace, "01").data.prompt || "");
47
57
  const resumeConfirmationRequired = (prompt) => /(?:^|\r?\n)RESUME_CONFIRMATION: required(?=\r?\n|$)/.test(prompt || "");
48
- const startupWorkflowPolicy = () => ({
58
+ const startupWorkflowPolicy = (commitMode = { mode: "manual" }) => ({
49
59
  mode: "startup",
50
- guidance: [
60
+ guidance: commitMode.mode === "per_item" ? [
61
+ "A shared dirty worktree and concurrent stages are expected; stages do not own files or commits.",
62
+ "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
+ "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.",
65
+ "After a direct commit, reconcile any stale related candidate intent before completing Current.",
66
+ "A true patch or merge conflict, failed required verification, or incoherent boundary is a blocker; record it and do not complete Current.",
67
+ ] : [
51
68
  "A shared dirty worktree and concurrent stages are expected; stages do not own files or commits.",
52
69
  "Capture ready work promptly as an explicit commit candidate while unrelated work remains in progress.",
53
70
  "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.",
@@ -75,7 +92,30 @@ const executionInstruction = (record) => {
75
92
  : "\nQueued checklist items: none";
76
93
  return `\n\nCurrent stage execution state:${current}${queued}\n${JSON.stringify(execution, null, 2)}\nTreat this bounded stage-local ledger as the current operational checkpoint. Work only on the Current checklist item by default. Do not combine Queued items into the same change set unless the user explicitly asks. Update it after meaningful scope changes, decisions, substantial work, blockers, or verification changes, and before handoff; do not update it for trivial tool calls.`;
77
94
  };
95
+ const commitModeInstruction = (commitMode) => {
96
+ 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.`;
98
+ };
78
99
  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
+ const assertOpenCodeSessionAvailable = (events, opencodeSessionId, workspace, stage) => {
101
+ 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;
106
+ fail(
107
+ ERROR_CODES.CURRENT_OPENCODE_SESSION_ALREADY_ASSOCIATED,
108
+ "The current OpenCode session is already associated with another active work-context stage",
109
+ {
110
+ current_workspace: conflicting.workspace,
111
+ current_stage: conflicting.stage,
112
+ current_stage_session_id: conflicting.session_id,
113
+ requested_workspace: workspace,
114
+ 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.",
116
+ },
117
+ );
118
+ };
79
119
  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; } } };
80
120
 
81
121
  function parseIssue(url) {
@@ -149,7 +189,7 @@ export class WorkContext {
149
189
  .filter((entry) => entry.isDirectory() && /^\d{6}$/.test(entry.name))
150
190
  .map((entry) => {
151
191
  const data = this.storage.readWorkspace(entry.name).data;
152
- return { ...data, mode: workspaceMode(data) };
192
+ return { ...data, mode: workspaceMode(data), commit_mode: workspaceCommitMode(data) };
153
193
  });
154
194
  return { ok: true, data };
155
195
  }
@@ -178,7 +218,7 @@ export class WorkContext {
178
218
  };
179
219
  for (const stage of ids) visit(stage);
180
220
  const workspaceData = this.storage.readWorkspace(workspace).data;
181
- return { ok: true, data: { workspace, title: workspaceData.title, status: workspaceData.status, mode: workspaceMode(workspaceData), stages, sessions: reduceSessions(this.storage.readEvents()).filter((session) => session.workspace === workspace) } };
221
+ return { ok: true, data: { workspace, title: workspaceData.title, status: workspaceData.status, mode: workspaceMode(workspaceData), commit_mode: workspaceCommitMode(workspaceData), stages, sessions: reduceSessions(this.storage.readEvents()).filter((session) => session.workspace === workspace) } };
182
222
  }
183
223
 
184
224
  finishWorkspace(workspace) {
@@ -229,6 +269,11 @@ export class WorkContext {
229
269
  && (!state || session.state === state)).at(-1) || null;
230
270
  }
231
271
 
272
+ diagnoseSessionAssociations(opencodeSessionId = null) {
273
+ this.storage.assertNoSymlinks();
274
+ return { ok: true, data: diagnoseSessionAssociations(this.storage.readEvents(), opencodeSessionId) };
275
+ }
276
+
232
277
  assertDependenciesCompleted(workspace, stageRecord) {
233
278
  const stages = this.listStages(workspace).data.stages;
234
279
  for (const dependency of stageRecord.data.depends_on) {
@@ -246,8 +291,9 @@ export class WorkContext {
246
291
  const workspace = requestedWorkspace === undefined ? this.nextWorkspace() : normalizeWorkspaceId(requestedWorkspace);
247
292
  const now = new Date().toISOString();
248
293
  if (fs.existsSync(this.storage.workspaceDir(workspace))) fail(ERROR_CODES.CONFLICT, "Workspace already exists");
294
+ assertOpenCodeSessionAvailable(this.storage.readEvents(), options.opencodeSessionId, workspace, "01");
249
295
  fs.mkdirSync(path.join(this.storage.workspaceDir(workspace), "stages"), { recursive: true });
250
- this.storage.writeMarkdown(this.storage.workspaceFile(workspace), { schema: 1, workspace, title: title.trim(), status: "in_progress", mode, created_at: now, updated_at: now, tracker_links: [] }, body(title));
296
+ 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));
251
297
  const planningGoal = "Clarify the work goal and constraints";
252
298
  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.";
253
299
  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));
@@ -259,7 +305,8 @@ export class WorkContext {
259
305
  generateProjections(this.storage);
260
306
  return this.result({
261
307
  workspace,
262
- mode,
308
+ mode,
309
+ commit_mode: "manual",
263
310
  stage: "01",
264
311
  session_id: sessionId,
265
312
  ordinal: "01/01",
@@ -314,6 +361,30 @@ export class WorkContext {
314
361
  });
315
362
  }
316
363
 
364
+ setWorkspaceCommitMode(workspace, commitMode) {
365
+ workspace = normalizeWorkspaceId(workspace);
366
+ assertCommitMode(commitMode, "commitMode");
367
+ return this.transact(`workspace-${workspace}`, () => {
368
+ const record = this.storage.readWorkspace(workspace);
369
+ if (workspaceCommitMode(record.data) === commitMode && record.data.commit_mode === commitMode) return this.result({ workspace, commit_mode: commitMode }, []);
370
+ record.data.commit_mode = commitMode;
371
+ record.data.updated_at = new Date().toISOString();
372
+ this.storage.writeMarkdown(this.storage.workspaceFile(workspace), record.data, record.body);
373
+ generateProjections(this.storage);
374
+ return this.result({ workspace, commit_mode: commitMode }, [workspace]);
375
+ });
376
+ }
377
+
378
+ readEffectiveCommitMode(workspace, stage) {
379
+ workspace = normalizeWorkspaceId(workspace);
380
+ stage = normalizeStageId(stage);
381
+ this.storage.assertNoSymlinks();
382
+ const workspaceRecord = this.storage.readWorkspace(workspace).data;
383
+ const stageRecord = this.storage.readStage(workspace, stage).data;
384
+ const effective = effectiveCommitMode(workspaceRecord, stageRecord);
385
+ return { ok: true, data: { workspace, stage, mode: effective.mode, source: effective.source } };
386
+ }
387
+
317
388
  candidates() { return new CandidateStore(this); }
318
389
  deliveries() { return new DeliveryStore(this); }
319
390
 
@@ -402,9 +473,10 @@ export class WorkContext {
402
473
  stage = normalizeStageId(stage);
403
474
  const sessionId = options.sessionId || randomUUID();
404
475
  return this.transact(`stage-${workspace}-${stage}`, () => {
476
+ const events = this.storage.readEvents();
477
+ assertOpenCodeSessionAvailable(events, options.opencodeSessionId, workspace, stage);
405
478
  const stageRecord = this.storage.readStage(workspace, stage);
406
479
  this.assertDependenciesCompleted(workspace, stageRecord);
407
- const events = this.storage.readEvents();
408
480
  const current = activeSession(events, workspace, stage);
409
481
  if (current) {
410
482
  const canTakeOver = options.takeover
@@ -435,7 +507,8 @@ export class WorkContext {
435
507
  const previousResult = preservedStageResult(stageRecord);
436
508
  const workspaceRecord = this.storage.readWorkspace(workspace).data;
437
509
  const workspaceTitle = workspaceRecord.title;
438
- const workflowPolicy = workspaceMode(workspaceRecord) === "startup" && options.opencodeSessionId ? startupWorkflowPolicy() : null;
510
+ const commitMode = effectiveCommitMode(workspaceRecord, stageRecord.data);
511
+ const workflowPolicy = workspaceMode(workspaceRecord) === "startup" && options.opencodeSessionId ? startupWorkflowPolicy(commitMode) : null;
439
512
  const pendingCandidates = workflowPolicy ? this.candidates().activeProjection(workspace).by_stage[stage] || null : null;
440
513
  const deliveryContext = stage === "01" ? this.deliveries().projection(workspace) : null;
441
514
  const hasDeliveryContext = deliveryContext && (deliveryContext.committed.count || deliveryContext.environments.length || deliveryContext.unavailable);
@@ -463,7 +536,8 @@ export class WorkContext {
463
536
  goal: stageRecord.data.goal || stageRecord.data.title,
464
537
  scope: stageRecord.data.prompt || null,
465
538
  previous_result: previousResult,
466
- previous_session_summary: previousSessionSummary,
539
+ previous_session_summary: previousSessionSummary,
540
+ commit_mode: commitMode,
467
541
  ...(execution ? { execution_state: executionReadModel(execution) } : {}),
468
542
  ...(recommendations ? { capability_profiles: recommendations } : {}),
469
543
  },
@@ -471,7 +545,8 @@ export class WorkContext {
471
545
  essence: stageRecord.data.goal || stageRecord.data.title,
472
546
  previous: previousSessionSummary || previousResult || "No previous progress was recorded.",
473
547
  now: hasPrompt ? stageRecord.data.prompt : "First clarify the task and work plan with the user.",
474
- workspace_knowledge: workspaceKnowledge,
548
+ workspace_knowledge: workspaceKnowledge,
549
+ commit_mode: commitMode,
475
550
  ...(execution ? { execution_state: executionReadModel(execution) } : {}),
476
551
  ...(recommendations ? { capability_profiles: recommendations } : {}),
477
552
  ...(pendingCandidates ? { pending_candidates: pendingCandidates } : {}),
@@ -480,9 +555,9 @@ export class WorkContext {
480
555
  lifecycle: { automatic_finish_allowed: automaticFinish },
481
556
  },
482
557
  next_action: hasPrompt ? confirmationRequired ? "await_confirmation" : "start_work" : "ask_questions",
483
- instruction: `${hasPrompt
484
- ? `${resumePresentationInstruction({ confirmationRequired })}\n\nSaved working prompt:\n${stageRecord.data.prompt}${executionInstruction(execution)}${startupWorkflowInstruction(workflowPolicy)}${stage === "01" ? deliveryPlanningInstruction : ""}`
485
- : `This stage has no non-empty prompt. Give the user a concise plain-language summary of the stage title and goal, then ask focused questions needed to define the intended outcome and scope. Do not inspect or modify application code yet. Do not report raw operation metadata or identifiers.`}\n\nDo not invoke stage finish unless the user explicitly requests the lifecycle command. Automatic completion is permitted only when lifecycle.automatic_finish_allowed is true, which requires the exact AUTO_STAGE_FINISH: allowed line in this workspace's Planning-stage prompt.`,
558
+ instruction: `${hasPrompt
559
+ ? `${resumePresentationInstruction({ confirmationRequired })}\n\nSaved working prompt:\n${stageRecord.data.prompt}${executionInstruction(execution)}${startupWorkflowInstruction(workflowPolicy)}${stage === "01" ? deliveryPlanningInstruction : ""}`
560
+ : `This stage has no non-empty prompt. Give the user a concise plain-language summary of the stage title and goal, then ask focused questions needed to define the intended outcome and scope. Do not inspect or modify application code yet. Do not report raw operation metadata or identifiers.`}${commitModeInstruction(commitMode)}\n\nDo not invoke stage finish unless the user explicitly requests the lifecycle command. Automatic completion is permitted only when lifecycle.automatic_finish_allowed is true, which requires the exact AUTO_STAGE_FINISH: allowed line in this workspace's Planning-stage prompt.`,
486
561
  },
487
562
  }, [workspace, stage]);
488
563
  });
@@ -560,6 +635,27 @@ export class WorkContext {
560
635
  });
561
636
  }
562
637
 
638
+ setStageCommitMode(workspace, stage, commitMode) {
639
+ workspace = normalizeWorkspaceId(workspace);
640
+ stage = normalizeStageId(stage);
641
+ if (commitMode !== null) assertCommitMode(commitMode, "commitMode");
642
+ return this.transact(`stage-${workspace}-${stage}`, () => {
643
+ const workspaceRecord = this.storage.readWorkspace(workspace).data;
644
+ const record = this.storage.readStage(workspace, stage);
645
+ let changed = false;
646
+ if (commitMode === null) {
647
+ if (record.data.commit_mode !== undefined) { delete record.data.commit_mode; changed = true; }
648
+ } else if (record.data.commit_mode !== commitMode) { record.data.commit_mode = commitMode; changed = true; }
649
+ if (changed) {
650
+ record.data.updated_at = new Date().toISOString();
651
+ this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, record.body);
652
+ generateProjections(this.storage);
653
+ }
654
+ const effective = effectiveCommitMode(workspaceRecord, record.data);
655
+ return this.result({ workspace, stage, commit_mode: record.data.commit_mode || null, effective_commit_mode: effective.mode, commit_mode_source: effective.source }, changed ? [workspace, stage] : []);
656
+ });
657
+ }
658
+
563
659
  refreshStageProfiles(workspace, recommendations, options = {}) {
564
660
  workspace = normalizeWorkspaceId(workspace);
565
661
  if (!Array.isArray(recommendations) || !recommendations.length || recommendations.length > 99) fail(ERROR_CODES.INVALID_ARGUMENT, "recommendations must contain 1 to 99 stage classifications");
@@ -1049,8 +1145,8 @@ export class WorkContext {
1049
1145
  help(command = "") {
1050
1146
  return this.result({
1051
1147
  command,
1052
- syntax: "/wc [create|list|workspace list|workspace rename|workspace 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]",
1053
- note: "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.",
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.",
1054
1150
  }, []);
1055
1151
  }
1056
1152
 
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",
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";
package/src/protocol.js CHANGED
@@ -3,7 +3,7 @@ import { createHash } from "node:crypto";
3
3
  export const WORK_CONTEXT_PROTOCOL = Object.freeze({
4
4
  schema: 1,
5
5
  major: 1,
6
- minor: 3,
6
+ minor: 5,
7
7
  });
8
8
 
9
9
  export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR = Object.freeze({
@@ -13,7 +13,7 @@ export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR = Object.freeze({
13
13
  major: WORK_CONTEXT_PROTOCOL.major,
14
14
  minor: WORK_CONTEXT_PROTOCOL.minor,
15
15
  }),
16
- operations: Object.freeze(["delivery.doctor", "commit.acknowledge", "commit.inspect_all", "commit.all", "execution.complete_current"]),
16
+ operations: Object.freeze(["delivery.doctor", "commit.acknowledge", "commit.inspect_all", "commit.all", "commit_mode.workspace.set", "commit_mode.stage.set", "commit_mode.effective.read", "execution.complete_current"]),
17
17
  });
18
18
 
19
19
  export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR_BYTES = JSON.stringify(WORK_CONTEXT_PROTOCOL_DESCRIPTOR);
@@ -0,0 +1,44 @@
1
+ import { reduceSessions } from "./sessions.js";
2
+ import { ERROR_CODES } from "./errors.js";
3
+
4
+ export const SESSION_ASSOCIATION_SPLIT_BRAIN = ERROR_CODES.SESSION_ASSOCIATION_SPLIT_BRAIN;
5
+
6
+ const association = (session) => ({
7
+ workspace: session.workspace,
8
+ stage: session.stage,
9
+ stage_session_id: session.session_id,
10
+ started_at: session.started_at,
11
+ });
12
+
13
+ export function diagnoseSessionAssociations(events, opencodeSessionId = null) {
14
+ const groups = new Map();
15
+ for (const session of reduceSessions(events)) {
16
+ if (session.state !== "active" || !session.opencode_session_id) continue;
17
+ if (opencodeSessionId && session.opencode_session_id !== opencodeSessionId) continue;
18
+ const grouped = groups.get(session.opencode_session_id) || [];
19
+ grouped.push(session);
20
+ groups.set(session.opencode_session_id, grouped);
21
+ }
22
+
23
+ const findings = [...groups.entries()]
24
+ .filter(([, sessions]) => sessions.length > 1)
25
+ .map(([nativeSessionId, sessions]) => ({
26
+ code: SESSION_ASSOCIATION_SPLIT_BRAIN,
27
+ severity: "error",
28
+ message: "One OpenCode session is associated with multiple active work-context stage sessions.",
29
+ opencode_session_id: nativeSessionId,
30
+ presumed_original_association: association(sessions[0]),
31
+ conflicting_associations: sessions.slice(1).map(association),
32
+ recovery: {
33
+ status: "manual_recovery_required",
34
+ steps: [
35
+ "Treat the earliest active association as the presumed original until the session history is reviewed.",
36
+ "Explicitly hand off or close only the incorrect later association.",
37
+ "Do not force-close the presumed original association merely because a later association exists.",
38
+ "Open a separate OpenCode session before resuming another stage.",
39
+ ],
40
+ },
41
+ }));
42
+
43
+ return { schema: 1, status: findings.length ? "conflict" : "ok", findings };
44
+ }
@@ -34,8 +34,10 @@ const workspaceCandidateSummary = (candidates) => {
34
34
  ].filter(Boolean);
35
35
  return `Candidates ${states.join(" ")}`;
36
36
  };
37
+ const commitModeLabel = (mode) => (mode || "manual").replace("_", "-");
37
38
  export const workspaceStatusLines = (workspace, attention = "") => [
38
- `${workspace.mode || "standard"}${attention ? ` · Attention ${attention}` : ""}`,
39
+ `${workspace.mode || "standard"} · commits: ${commitModeLabel(workspace.commit_mode)}`,
40
+ attention ? `Attention ${attention}` : null,
39
41
  workspaceCandidateSummary(workspace.candidates),
40
42
  deliverySummary(workspace.delivery),
41
43
  ].filter(Boolean);
@@ -56,7 +58,7 @@ export const formatStageIds = (ids = []) => {
56
58
  flush();
57
59
  return ranges.join(", ");
58
60
  };
59
- const profileSummary = (stage) => {
61
+ const profileSummary = (stage) => {
60
62
  return stage.execution_profile && stage.execution_depth
61
63
  ? [capitalize(stage.execution_profile), capitalize(stage.execution_depth), stage.recommended_model && capitalize(stage.recommended_model)].filter(Boolean).join(" · ")
62
64
  : null;
@@ -116,7 +118,7 @@ export function renderStagesPanel(result) {
116
118
  for (const stage of snapshot.stages) {
117
119
  const pending = candidateSummary(stage);
118
120
  const profiles = profileSummary(stage);
119
- lines.push(`${statusMarker(stage.status)} ${stage.id}. ${stage.title}${profiles ? `\n${profiles}` : ""}${stage.depends_on?.length ? `\nDeps: ${formatStageIds(stage.depends_on)}` : ""}${pending ? `\n${pending}` : ""}`);
121
+ lines.push(`${statusMarker(stage.status)} ${stage.id}. ${stage.title}${profiles ? `\n${profiles}` : ""}${stage.commit_mode ? `\nCommits: ${commitModeLabel(stage.commit_mode)} (override)` : ""}${stage.depends_on?.length ? `\nDeps: ${formatStageIds(stage.depends_on)}` : ""}${pending ? `\n${pending}` : ""}`);
120
122
  }
121
123
  if (result.stale) lines.push(`! stale: ${result.error?.code || "STORAGE_ERROR"}`);
122
124
  return lines.join("\n");
@@ -6,6 +6,7 @@ const emptySnapshot = () => ({
6
6
  workspace: null,
7
7
  stages: [],
8
8
  currentStage: null,
9
+ sessionDiagnostics: { schema: 1, status: "ok", findings: [] },
9
10
  generatedAt: new Date().toISOString(),
10
11
  });
11
12
 
@@ -16,13 +17,13 @@ const emptySnapshot = () => ({
16
17
  export function readStagesSnapshot({ projectRoot, sessionId }) {
17
18
  try {
18
19
  const context = WorkContext.openExisting(projectRoot, { sessionId, actor: "OpenCode TUI" });
20
+ const sessionDiagnostics = context.diagnoseSessionAssociations(sessionId || null).data;
19
21
  let session = sessionId ? context.sessionById(sessionId) : null;
20
22
  if (!session && sessionId) {
21
- for (const workspace of context.listWorkspaces().data) {
22
- const candidate = context.listStages(workspace.workspace).data.sessions
23
- .filter((item) => item.opencode_session_id === sessionId).at(-1);
24
- if (candidate) { session = candidate; break; }
25
- }
23
+ const conflict = sessionDiagnostics.findings[0];
24
+ session = conflict
25
+ ? context.sessionById(conflict.presumed_original_association.stage_session_id)
26
+ : context.sessionByOpenCodeId(sessionId) || context.sessionByOpenCodeId(sessionId, null, null, null);
26
27
  }
27
28
  if (!session) {
28
29
  const activeWorkspaces = context.listWorkspaces().data.filter((workspace) => workspace.status === "in_progress");
@@ -32,10 +33,11 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
32
33
  if (!session) session = { workspace: activeWorkspaces[0].workspace, stage: null };
33
34
  }
34
35
  }
35
- if (!session) return { ok: true, data: emptySnapshot() };
36
+ if (!session) return { ok: true, data: { ...emptySnapshot(), sessionDiagnostics } };
36
37
 
37
38
  const workspace = context.storage.readWorkspace(session.workspace).data;
38
39
  const mode = workspace.mode || "standard";
40
+ const commitMode = workspace.commit_mode || "manual";
39
41
  const candidateProjection = mode === "startup" ? context.candidates().activeProjection(session.workspace) : null;
40
42
  const deliveryProjection = context.deliveries().projection(session.workspace);
41
43
  const delivery = deliveryProjection.committed.count || deliveryProjection.environments.length || deliveryProjection.unavailable
@@ -53,7 +55,8 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
53
55
  status: stage.status,
54
56
  description: stage.description,
55
57
  depends_on: stage.depends_on.filter((dependency) => visibleStageIds.has(dependency)),
56
- tracker_links: stage.tracker_links || [],
58
+ tracker_links: stage.tracker_links || [],
59
+ ...(stage.commit_mode ? { commit_mode: stage.commit_mode } : {}),
57
60
  ...stageCapabilityProfiles(context.storage, stage, capabilityMappings),
58
61
  ...(candidateProjection?.by_stage[stage.stage] ? { candidates: candidateProjection.by_stage[stage.stage] } : {}),
59
62
  current: stage.stage === session.stage,
@@ -68,9 +71,10 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
68
71
  ok: true,
69
72
  data: {
70
73
  schema: 1,
71
- workspace: { id: workspace.workspace, title: workspace.title, status: workspace.status, mode, ...(candidateProjection ? { candidates: candidateProjection.summary } : {}), ...(delivery ? { delivery } : {}) },
74
+ workspace: { id: workspace.workspace, title: workspace.title, status: workspace.status, mode, commit_mode: commitMode, ...(candidateProjection ? { candidates: candidateProjection.summary } : {}), ...(delivery ? { delivery } : {}) },
72
75
  stages,
73
76
  currentStage,
77
+ sessionDiagnostics,
74
78
  generatedAt: new Date().toISOString(),
75
79
  },
76
80
  };
package/src/storage.js CHANGED
@@ -91,13 +91,13 @@ const validateEventStream = (events) => {
91
91
  }
92
92
  };
93
93
  function validateMetadata(data, kind, workspace, stage = null) {
94
- const allowed = kind === "workspace" ? ["schema", "workspace", "title", "status", "mode", "created_at", "updated_at", "tracker_links", "reopen_history"] : ["schema", "workspace", "stage", "title", "status", "goal", "prompt", "depends_on", "owner", "execution_profile", "execution_depth", "execution_classification", "review_profile", "created_at", "updated_at", "tracker_links", "reopen_history", "archive_history"];
94
+ const allowed = kind === "workspace" ? ["schema", "workspace", "title", "status", "mode", "commit_mode", "created_at", "updated_at", "tracker_links", "reopen_history"] : ["schema", "workspace", "stage", "title", "status", "goal", "prompt", "depends_on", "owner", "commit_mode", "execution_profile", "execution_depth", "execution_classification", "review_profile", "created_at", "updated_at", "tracker_links", "reopen_history", "archive_history"];
95
95
  if (Object.keys(data).some((key) => !allowed.includes(key)) || data.schema !== 1 || !requiredString(data, "workspace") || !/^\d{6}$/.test(data.workspace) || data.workspace !== workspace) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} metadata`);
96
96
  if (!requiredString(data, "title") || !validTimestamp(data.created_at) || !validTimestamp(data.updated_at) || Date.parse(data.updated_at) < Date.parse(data.created_at) || !Array.isArray(data.tracker_links)) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} metadata`);
97
97
  if (!validTrackerLinks(data.tracker_links) || data.tracker_links.some((link) => !link.provider.trim() || !link.project.trim() || ((link.provider === "gitlab" || link.provider === "github") ? (!Number.isInteger(link.iid) || link.iid < 1) : !link.key?.trim()))) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} tracker links`);
98
98
  const statuses = kind === "workspace" ? ["in_progress", "completed", "cancelled"] : ["planned", "in_progress", "completed", "cancelled", "archived"];
99
99
  if (!statuses.includes(data.status)) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} status`);
100
- const invalidWorkspaceHistory = kind === "workspace" && ((data.mode !== undefined && !["standard", "startup"].includes(data.mode)) || (data.reopen_history !== undefined && !validReopenHistory(data.reopen_history)));
100
+ const invalidWorkspaceHistory = kind === "workspace" && ((data.mode !== undefined && !["standard", "startup"].includes(data.mode)) || (data.commit_mode !== undefined && !["manual", "per_item"].includes(data.commit_mode)) || (data.reopen_history !== undefined && !validReopenHistory(data.reopen_history)));
101
101
  const invalidStageMetadata = kind === "stage" && (
102
102
  data.stage !== stage || !/^\d{2}$/.test(data.stage) || !requiredString(data, "goal")
103
103
  || (data.prompt !== undefined && !requiredString(data, "prompt")) || !requiredString(data, "owner")
@@ -109,6 +109,7 @@ function validateMetadata(data, kind, workspace, stage = null) {
109
109
  || (data.execution_depth !== undefined && !CAPABILITY_DEPTHS.includes(data.execution_depth))
110
110
  || (data.execution_classification !== undefined && !CAPABILITY_CLASSIFICATIONS.includes(data.execution_classification))
111
111
  || (data.review_profile !== undefined && !CAPABILITY_PROFILES.includes(data.review_profile))
112
+ || (data.commit_mode !== undefined && !["manual", "per_item"].includes(data.commit_mode))
112
113
  || (data.execution_depth !== undefined && data.execution_profile === undefined)
113
114
  || (data.execution_classification !== undefined && (data.execution_profile === undefined || data.execution_depth === undefined))
114
115
  || (data.execution_profile !== undefined && data.execution_depth !== undefined && data.execution_classification === undefined)
@@ -38,6 +38,7 @@ const common = { workspace: tool.schema.string(), stage: tool.schema.string() };
38
38
  const contextualStage = { workspace: tool.schema.string().optional(), stage: tool.schema.string().optional() };
39
39
  const capabilityProfile = tool.schema.enum(["routine", "implementation", "architecture", "security", "review"]);
40
40
  const capabilityDepth = tool.schema.enum(["light", "standard", "deep"]);
41
+ const commitMode = tool.schema.enum(["manual", "per_item"]);
41
42
  const deliveryFinding = tool.schema.object({
42
43
  id: tool.schema.string(),
43
44
  severity: tool.schema.enum(["info", "warning", "error"]),
@@ -52,8 +53,18 @@ const executionEdit = tool.schema.object({ id: tool.schema.string(), text: tool.
52
53
  const executionSections = Object.fromEntries(["scope", "completed", "remaining", "decisions", "blockers", "verification"].map((section) => [section, tool.schema.array(executionItem).optional()]));
53
54
  const executionRemovalSections = Object.fromEntries(["scope", "completed", "remaining", "decisions", "blockers", "verification"].map((section) => [section, tool.schema.array(executionRemoval).optional()]));
54
55
  const executionEditSections = Object.fromEntries(["scope", "completed", "remaining", "decisions", "blockers", "verification"].map((section) => [section, tool.schema.array(executionEdit).optional()]));
55
- const sessionFromContext = (ctx, workspace) => ctx.sessionByOpenCodeId(ctx.options.sessionId, workspace || null, null, null)
56
- || (!workspace ? ctx.sessionById(ctx.options.sessionId) : null);
56
+ const sessionFromContext = (ctx, workspace) => {
57
+ const finding = ctx.diagnoseSessionAssociations(ctx.options.sessionId).data.findings[0];
58
+ if (finding) {
59
+ const associations = [finding.presumed_original_association, ...finding.conflicting_associations];
60
+ fail(ERROR_CODES.SESSION_ASSOCIATION_SPLIT_BRAIN, "The current OpenCode session has multiple active work-context associations", {
61
+ associations,
62
+ next_action: "Specify both workspace and stage to hand off or close the incorrect association after reviewing the session history.",
63
+ });
64
+ }
65
+ return ctx.sessionByOpenCodeId(ctx.options.sessionId, workspace || null, null, null)
66
+ || (!workspace ? ctx.sessionById(ctx.options.sessionId) : null);
67
+ };
57
68
  const workspaceFromSession = (ctx, workspace) => {
58
69
  if (workspace !== undefined) return normalizeWorkspaceId(workspace);
59
70
  const session = sessionFromContext(ctx);
@@ -90,6 +101,8 @@ export const work_context_list_workspaces = tool({ description: "List work-conte
90
101
  export const work_context_workspace_list = tool({ description: "List a workspace with stage descriptions and sessions.", args: { workspace: tool.schema.string() }, execute: run((ctx, a) => ctx.listStages(a.workspace)) });
91
102
  export const work_context_rename_workspace = tool({ description: "Rename a workspace.", args: { workspace: tool.schema.string(), title: tool.schema.string() }, execute: run((ctx, a) => ctx.renameWorkspace(a.workspace, a.title)) });
92
103
  export const work_context_set_workspace_mode = tool({ description: "Set a workspace workflow mode.", args: { workspace: tool.schema.string(), mode: tool.schema.enum(["standard", "startup"]) }, execute: run((ctx, a) => ctx.setWorkspaceMode(a.workspace, a.mode)) });
104
+ export const work_context_set_workspace_commit_mode = tool({ description: "Set persistent workspace checklist commit authorization.", args: { workspace: tool.schema.string(), commitMode }, execute: run((ctx, a) => ctx.setWorkspaceCommitMode(a.workspace, a.commitMode)) });
105
+ export const work_context_read_effective_commit_mode = tool({ description: "Read the effective checklist commit mode immediately before a direct commit or candidate fallback.", args: contextualStage, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.readEffectiveCommitMode(workspace, stageFromSession(ctx, workspace, a.stage)); }) });
93
106
  export const work_context_create_candidate = tool({ description: "Create an exact, shared-foundation, or integration draft candidate. Related stages are optional traceability and never ownership.", args: { workspace: tool.schema.string(), title: tool.schema.string(), message: tool.schema.string().optional(), strategy: tool.schema.enum(["exact", "shared_foundation", "integration"]).optional(), relatedStages: tool.schema.array(tool.schema.string()).optional() }, execute: run((ctx, a) => ctx.createCandidate(a.workspace, a.title, a.message, { strategy: a.strategy, relatedStages: a.relatedStages })) });
94
107
  export const work_context_capture_candidate = tool({ description: "Capture explicit complete paths or an exact unified patch into a draft commit candidate.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string(), paths: tool.schema.array(tool.schema.string()).optional(), patch: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.captureCandidate(a.workspace, a.candidateId, { paths: a.paths, patch: a.patch })) });
95
108
  export const work_context_preview_candidate = tool({ description: "Preview a candidate using an isolated temporary Git index.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string() }, execute: run((ctx, a) => ctx.previewCandidate(a.workspace, a.candidateId)) });
@@ -125,6 +138,7 @@ export const work_context_acknowledge_commit = tool({ description: "Acknowledge
125
138
  }) });
126
139
  export const work_context_add_stage = tool({ description: "Add a stage with an optional execution capability and depth. When the user did not specify them, infer both from the prompt and pass classification: inferred. Explicit user choices use classification: explicit.", args: { workspace: tool.schema.string().optional(), title: tool.schema.string(), goal: tool.schema.string().optional(), prompt: tool.schema.string().optional(), dependsOn: tool.schema.array(tool.schema.string()).optional(), executionProfile: capabilityProfile.optional(), executionDepth: capabilityDepth.optional(), classification: tool.schema.enum(["inferred", "explicit"]).optional(), reviewProfile: capabilityProfile.optional() }, execute: run(addStageFromTool) });
127
140
  export const work_context_set_stage_profiles = tool({ description: "Explicitly set or clear a stage execution capability and depth. Omitted fields are unchanged; pass null for both execution fields to clear them. Review profile remains optional metadata.", args: { ...contextualStage, executionProfile: capabilityProfile.nullable().optional(), executionDepth: capabilityDepth.nullable().optional(), reviewProfile: capabilityProfile.nullable().optional() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.setStageProfiles(workspace, stageFromSession(ctx, workspace, a.stage), { ...(Object.hasOwn(a, "executionProfile") ? { executionProfile: a.executionProfile } : {}), ...(Object.hasOwn(a, "executionDepth") ? { executionDepth: a.executionDepth } : {}), ...(Object.hasOwn(a, "reviewProfile") ? { reviewProfile: a.reviewProfile } : {}) }); }) });
141
+ export const work_context_set_stage_commit_mode = tool({ description: "Set or clear a stage checklist commit-mode override; null inherits the workspace mode.", args: { ...contextualStage, commitMode: commitMode.nullable() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.setStageCommitMode(workspace, stageFromSession(ctx, workspace, a.stage), a.commitMode); }) });
128
142
  export const work_context_refresh_stage_profiles = tool({ description: "Atomically apply agent-inferred execution capability and depth recommendations. Ordinary refresh preserves explicit classifications; includeExplicit permits an explicitly requested override.", args: { workspace: tool.schema.string(), recommendations: tool.schema.array(tool.schema.object({ stage: tool.schema.string(), executionProfile: capabilityProfile, executionDepth: capabilityDepth })), includeExplicit: tool.schema.boolean().optional() }, execute: run((ctx, a) => ctx.refreshStageProfiles(a.workspace, a.recommendations, { includeExplicit: a.includeExplicit })) });
129
143
  export const work_context_show_capability_profiles = tool({ description: "Show capability recommendation mode and validated user-local depth mappings.", args: {}, execute: run((ctx) => ctx.showCapabilityProfiles()) });
130
144
  export const work_context_configure_capability_profiles = tool({ description: "Atomically configure either capability recommendation mode or global/project light, standard, and deep advisory labels. Interactive setup calls it separately for mode and mappings after gathering preferences.", args: { mode: tool.schema.enum(["advisory", "off"]).optional(), mappings: tool.schema.object({ light: tool.schema.string().optional(), standard: tool.schema.string().optional(), deep: tool.schema.string().optional() }).strict().optional(), scope: tool.schema.enum(["global", "project"]).optional() }, execute: run((ctx, a) => ctx.configureCapabilityProfiles(a)) });
@@ -154,7 +168,7 @@ export const work_context_add_knowledge = tool({ description: "Add a durable kno
154
168
  export const work_context_update_knowledge = tool({ description: "Update a durable knowledge entry.", args: { workspace: tool.schema.string(), knowledgeId: tool.schema.string(), title: tool.schema.string().optional(), kind: tool.schema.string().optional(), status: tool.schema.string().optional(), text: tool.schema.string().optional(), sources: tool.schema.array(tool.schema.string()).optional(), replacement: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.updateKnowledge(a.workspace, a.knowledgeId, a)) });
155
169
  export const work_context_supersede_knowledge = tool({ description: "Supersede a durable knowledge entry.", args: { workspace: tool.schema.string(), knowledgeId: tool.schema.string(), replacement: tool.schema.string() }, execute: run((ctx, a) => ctx.supersedeKnowledge(a.workspace, a.knowledgeId, a.replacement) ) });
156
170
 
157
- const defaultTools = { work_context_list_workspaces, work_context_workspace_list, work_context_rename_workspace, work_context_set_workspace_mode, work_context_create_candidate, work_context_capture_candidate, work_context_preview_candidate, work_context_show_candidate, work_context_list_candidates, work_context_ready_candidate, work_context_commit_candidate, work_context_inspect_commit_all, work_context_commit_all, work_context_discard_candidate, work_context_read_delivery, work_context_explain_delivery, work_context_doctor_delivery, work_context_mark_delivery, work_context_workspace_finish, work_context_reopen_workspace, work_context_create_workspace, work_context_start_session, work_context_acknowledge_commit, work_context_add_stage, work_context_set_stage_profiles, work_context_refresh_stage_profiles, work_context_show_capability_profiles, work_context_configure_capability_profiles, work_context_reset_capability_profiles, work_context_rename_stage, work_context_update_stage, work_context_update_stage_prompt, work_context_update_stage_result, work_context_read_stage_execution, work_context_replace_stage_execution, work_context_update_stage_execution, work_context_complete_current, work_context_archive_stage, work_context_reopen_stage, work_context_restore_stage, work_context_link_issue, work_context_unlink_issue, work_context_rename_session, work_context_close_session, work_context_force_close_session, work_context_handoff_stage, work_context_abandon_stage, work_context_finish_stage, work_context_help, work_context_list_knowledge, work_context_add_knowledge, work_context_update_knowledge, work_context_supersede_knowledge };
171
+ const defaultTools = { work_context_list_workspaces, work_context_workspace_list, work_context_rename_workspace, work_context_set_workspace_mode, work_context_set_workspace_commit_mode, work_context_read_effective_commit_mode, work_context_create_candidate, work_context_capture_candidate, work_context_preview_candidate, work_context_show_candidate, work_context_list_candidates, work_context_ready_candidate, work_context_commit_candidate, work_context_inspect_commit_all, work_context_commit_all, work_context_discard_candidate, work_context_read_delivery, work_context_explain_delivery, work_context_doctor_delivery, work_context_mark_delivery, work_context_workspace_finish, work_context_reopen_workspace, work_context_create_workspace, work_context_start_session, work_context_acknowledge_commit, work_context_add_stage, work_context_set_stage_profiles, work_context_set_stage_commit_mode, work_context_refresh_stage_profiles, work_context_show_capability_profiles, work_context_configure_capability_profiles, work_context_reset_capability_profiles, work_context_rename_stage, work_context_update_stage, work_context_update_stage_prompt, work_context_update_stage_result, work_context_read_stage_execution, work_context_replace_stage_execution, work_context_update_stage_execution, work_context_complete_current, work_context_archive_stage, work_context_reopen_stage, work_context_restore_stage, work_context_link_issue, work_context_unlink_issue, work_context_rename_session, work_context_close_session, work_context_force_close_session, work_context_handoff_stage, work_context_abandon_stage, work_context_finish_stage, work_context_help, work_context_list_knowledge, work_context_add_knowledge, work_context_update_knowledge, work_context_supersede_knowledge };
158
172
 
159
173
  export function createToolDefinitions(options = {}) {
160
174
  return { ...defaultTools, work_context_doctor_delivery: createDoctorDeliveryTool(options) };
@@ -6,6 +6,7 @@ const emptySnapshot = () => ({
6
6
  workspaces: [],
7
7
  currentWorkspace: null,
8
8
  currentStage: null,
9
+ sessionDiagnostics: { schema: 1, status: "ok", findings: [] },
9
10
  generatedAt: new Date().toISOString(),
10
11
  });
11
12
 
@@ -21,7 +22,11 @@ const errorResult = (error) => ({
21
22
 
22
23
  const sessionFor = (context, sessionId) => {
23
24
  if (!sessionId) return null;
24
- return context.sessionById(sessionId)
25
+ const direct = context.sessionById(sessionId);
26
+ if (direct) return direct;
27
+ const conflict = context.diagnoseSessionAssociations(sessionId).data.findings[0];
28
+ if (conflict) return context.sessionById(conflict.presumed_original_association.stage_session_id);
29
+ return context.sessionByOpenCodeId(sessionId)
25
30
  || context.sessionByOpenCodeId(sessionId, null, null, null);
26
31
  };
27
32
 
@@ -33,6 +38,7 @@ const readWorkspace = (context, record, currentSession, capabilityMappings) => {
33
38
  : sessions.find((session) => session.session_id === currentSession?.session_id);
34
39
  const currentStage = matchingSession?.stage || null;
35
40
  const mode = record.mode || "standard";
41
+ const commitMode = record.commit_mode || "manual";
36
42
  const candidateProjection = mode === "startup" ? context.candidates().activeProjection(record.workspace) : null;
37
43
  const deliveryProjection = context.deliveries().projection(record.workspace);
38
44
  const delivery = deliveryProjection.committed.count || deliveryProjection.environments.length || deliveryProjection.unavailable
@@ -47,6 +53,7 @@ const readWorkspace = (context, record, currentSession, capabilityMappings) => {
47
53
  title: record.title,
48
54
  status: record.status,
49
55
  mode,
56
+ commit_mode: commitMode,
50
57
  ...(candidateProjection ? { candidates: candidateProjection.summary } : {}),
51
58
  ...(delivery ? { delivery } : {}),
52
59
  stages: visibleStages
@@ -57,6 +64,7 @@ const readWorkspace = (context, record, currentSession, capabilityMappings) => {
57
64
  description: stage.description,
58
65
  depends_on: stage.depends_on.filter((dependency) => visibleStageIds.has(dependency)),
59
66
  tracker_links: stage.tracker_links || [],
67
+ ...(stage.commit_mode ? { commit_mode: stage.commit_mode } : {}),
60
68
  ...stageCapabilityProfiles(context.storage, stage, capabilityMappings),
61
69
  ...(candidateProjection?.by_stage[stage.stage] ? { candidates: candidateProjection.by_stage[stage.stage] } : {}),
62
70
  current: stage.stage === currentStage,
@@ -72,6 +80,7 @@ export function readWorkContextSnapshot({ projectRoot, sessionId } = {}) {
72
80
  try {
73
81
  const context = WorkContext.openExisting(projectRoot, { sessionId, actor: "OpenCode TUI" });
74
82
  const currentSession = sessionFor(context, sessionId);
83
+ const sessionDiagnostics = context.diagnoseSessionAssociations(sessionId || null).data;
75
84
  const capabilityMappings = capabilityProfileMode(context.storage) === "advisory" ? readCapabilityMappings(context.storage) : null;
76
85
  const workspaces = context.listWorkspaces().data
77
86
  .sort((left, right) => left.workspace.localeCompare(right.workspace))
@@ -89,6 +98,7 @@ export function readWorkContextSnapshot({ projectRoot, sessionId } = {}) {
89
98
  currentStage: currentWorkspace
90
99
  ? workspaces.find((workspace) => workspace.id === currentWorkspace)?.currentStage || null
91
100
  : null,
101
+ sessionDiagnostics,
92
102
  generatedAt: new Date().toISOString(),
93
103
  },
94
104
  };
@@ -0,0 +1 @@
1
+ export { work_context_read_effective_commit_mode as default } from "../src/tool-definitions.js";
@@ -0,0 +1 @@
1
+ export { work_context_set_stage_commit_mode as default } from "../src/tool-definitions.js";
@@ -0,0 +1 @@
1
+ export { work_context_set_workspace_commit_mode as default } from "../src/tool-definitions.js";