opencode-work-context 0.14.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
@@ -473,6 +473,28 @@ nothing. A failed canonical start removes the newly created OpenCode session
473
473
  when the host supports deletion; a navigation failure leaves the new linked
474
474
  session available for a later switch.
475
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
+
476
498
  The command palette still exposes `work_context.actions` for the broader action
477
499
  modal. Its command actions only prepare visible `/wc` commands and never submit
478
500
  or invoke an LLM. The switcher uses OpenCode's public structured session-command
package/commands/wc.md CHANGED
@@ -171,6 +171,10 @@ Supported syntax:
171
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
172
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
173
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
174
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
175
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.
176
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.14.0",
4
+ "version": "0.14.1",
5
5
  "description": "Filesystem work-context core and OpenCode adapter",
6
6
  "license": "MIT",
7
7
  "author": {
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";
@@ -96,6 +97,25 @@ const commitModeInstruction = (commitMode) => {
96
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.`;
97
98
  };
98
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
+ };
99
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; } } };
100
120
 
101
121
  function parseIssue(url) {
@@ -249,6 +269,11 @@ export class WorkContext {
249
269
  && (!state || session.state === state)).at(-1) || null;
250
270
  }
251
271
 
272
+ diagnoseSessionAssociations(opencodeSessionId = null) {
273
+ this.storage.assertNoSymlinks();
274
+ return { ok: true, data: diagnoseSessionAssociations(this.storage.readEvents(), opencodeSessionId) };
275
+ }
276
+
252
277
  assertDependenciesCompleted(workspace, stageRecord) {
253
278
  const stages = this.listStages(workspace).data.stages;
254
279
  for (const dependency of stageRecord.data.depends_on) {
@@ -266,6 +291,7 @@ export class WorkContext {
266
291
  const workspace = requestedWorkspace === undefined ? this.nextWorkspace() : normalizeWorkspaceId(requestedWorkspace);
267
292
  const now = new Date().toISOString();
268
293
  if (fs.existsSync(this.storage.workspaceDir(workspace))) fail(ERROR_CODES.CONFLICT, "Workspace already exists");
294
+ assertOpenCodeSessionAvailable(this.storage.readEvents(), options.opencodeSessionId, workspace, "01");
269
295
  fs.mkdirSync(path.join(this.storage.workspaceDir(workspace), "stages"), { recursive: true });
270
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));
271
297
  const planningGoal = "Clarify the work goal and constraints";
@@ -447,9 +473,10 @@ export class WorkContext {
447
473
  stage = normalizeStageId(stage);
448
474
  const sessionId = options.sessionId || randomUUID();
449
475
  return this.transact(`stage-${workspace}-${stage}`, () => {
476
+ const events = this.storage.readEvents();
477
+ assertOpenCodeSessionAvailable(events, options.opencodeSessionId, workspace, stage);
450
478
  const stageRecord = this.storage.readStage(workspace, stage);
451
479
  this.assertDependenciesCompleted(workspace, stageRecord);
452
- const events = this.storage.readEvents();
453
480
  const current = activeSession(events, workspace, stage);
454
481
  if (current) {
455
482
  const canTakeOver = options.takeover
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";
@@ -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
+ }
@@ -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,7 +33,7 @@ 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";
@@ -73,6 +74,7 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
73
74
  workspace: { id: workspace.workspace, title: workspace.title, status: workspace.status, mode, commit_mode: commitMode, ...(candidateProjection ? { candidates: candidateProjection.summary } : {}), ...(delivery ? { delivery } : {}) },
74
75
  stages,
75
76
  currentStage,
77
+ sessionDiagnostics,
76
78
  generatedAt: new Date().toISOString(),
77
79
  },
78
80
  };
@@ -53,8 +53,18 @@ const executionEdit = tool.schema.object({ id: tool.schema.string(), text: tool.
53
53
  const executionSections = Object.fromEntries(["scope", "completed", "remaining", "decisions", "blockers", "verification"].map((section) => [section, tool.schema.array(executionItem).optional()]));
54
54
  const executionRemovalSections = Object.fromEntries(["scope", "completed", "remaining", "decisions", "blockers", "verification"].map((section) => [section, tool.schema.array(executionRemoval).optional()]));
55
55
  const executionEditSections = Object.fromEntries(["scope", "completed", "remaining", "decisions", "blockers", "verification"].map((section) => [section, tool.schema.array(executionEdit).optional()]));
56
- const sessionFromContext = (ctx, workspace) => ctx.sessionByOpenCodeId(ctx.options.sessionId, workspace || null, null, null)
57
- || (!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
+ };
58
68
  const workspaceFromSession = (ctx, workspace) => {
59
69
  if (workspace !== undefined) return normalizeWorkspaceId(workspace);
60
70
  const session = sessionFromContext(ctx);
@@ -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
 
@@ -75,6 +80,7 @@ export function readWorkContextSnapshot({ projectRoot, sessionId } = {}) {
75
80
  try {
76
81
  const context = WorkContext.openExisting(projectRoot, { sessionId, actor: "OpenCode TUI" });
77
82
  const currentSession = sessionFor(context, sessionId);
83
+ const sessionDiagnostics = context.diagnoseSessionAssociations(sessionId || null).data;
78
84
  const capabilityMappings = capabilityProfileMode(context.storage) === "advisory" ? readCapabilityMappings(context.storage) : null;
79
85
  const workspaces = context.listWorkspaces().data
80
86
  .sort((left, right) => left.workspace.localeCompare(right.workspace))
@@ -92,6 +98,7 @@ export function readWorkContextSnapshot({ projectRoot, sessionId } = {}) {
92
98
  currentStage: currentWorkspace
93
99
  ? workspaces.find((workspace) => workspace.id === currentWorkspace)?.currentStage || null
94
100
  : null,
101
+ sessionDiagnostics,
95
102
  generatedAt: new Date().toISOString(),
96
103
  },
97
104
  };