opencode-work-context 0.14.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -55,12 +55,12 @@ Then create a task and its first stage in OpenCode:
55
55
  /wc resume 000001 02
56
56
  ```
57
57
 
58
- `stage add` creates a stage and, when run from a new OpenCode session that is
59
- not associated with a workspace, immediately enters the new stage in that
60
- session. From an already associated session it only creates a `planned` stage;
61
- use `/wc resume <workspace> <stage>` in a separate OpenCode session to enter it.
62
- Multiple sessions may work on the same non-terminal stage through explicit
63
- resume and handoff operations.
58
+ `stage add` only creates a `planned` stage. It never starts a stage session or
59
+ changes the invoking OpenCode session's current stage, regardless of whether
60
+ that session is already associated with a workspace. Use
61
+ `/wc resume <workspace> <stage>` in a separate OpenCode session to enter the new
62
+ stage. Multiple sessions may work on the same non-terminal stage through
63
+ explicit resume and handoff operations.
64
64
 
65
65
  Stages remain in progress until the user explicitly requests `/wc stage finish`.
66
66
  Do not infer that request from completed work. Automatic completion is allowed
@@ -245,10 +245,12 @@ per-item commits.
245
245
  In startup mode, the agent first inspects pending candidates related to the
246
246
  current stage and assesses direct publication. Only a ready `exact` candidate
247
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.
248
+ is unsafe but the patch is separable. Ordinary `shared_foundation` and
249
+ `integration` candidates do not satisfy Current completion. The narrow
250
+ multi-stage integration-coverage exception is described below. A real patch or
251
+ merge conflict, failed verification, or incoherent boundary remains a blocker
252
+ and Current must not be completed. This policy never authorizes unrelated
253
+ changes.
252
254
 
253
255
  `complete-current` remains an atomic ledger-only operation: it never runs Git
254
256
  or creates a commit itself.
@@ -474,26 +476,30 @@ when the host supports deletion; a navigation failure leaves the new linked
474
476
  session available for a later switch.
475
477
 
476
478
  `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
+ The first work-context stage associated with a native OpenCode session becomes
480
+ that session's immutable stage affinity. If the session later requests any
481
+ other stage, the operation fails atomically with
479
482
  `CURRENT_OPENCODE_SESSION_ALREADY_ASSOCIATED`. The error identifies the current
480
483
  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
484
+ session. Handoff, close, finish, abandon, archive, workspace completion, and
485
+ stage restoration never transfer or clear affinity. Repeating the operation
486
+ for the already-associated stage retains the existing
483
487
  `ACTIVE_SESSION_EXISTS` result and never creates a duplicate.
484
488
  The same association invariant applies when the core creates a workspace; the
485
489
  structured create tool leaves a new workspace unassociated when invoked from an
486
- already-associated OpenCode session.
490
+ OpenCode session with either an active or historical affinity.
487
491
 
488
492
  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.
493
+ event streams in which an active association conflicts with the earliest
494
+ historical affinity report `SESSION_ASSOCIATION_SPLIT_BRAIN` and non-destructive
495
+ recovery guidance. Recovery treats the earliest historical association as the
496
+ presumed original affinity and never recommends force-closing it merely because
497
+ a later conflicting association exists.
494
498
  Contextual mutations that omit an ambiguous workspace or stage fail with the
495
499
  same `SESSION_ASSOCIATION_SPLIT_BRAIN` code. Recovery must name the incorrect
496
- workspace and stage explicitly before handing it off or closing it.
500
+ workspace and stage explicitly before handing it off or closing it. Closing the
501
+ incorrect association restores normal access to the original affinity but does
502
+ not authorize the native session to bind to the incorrect stage again.
497
503
 
498
504
  The command palette still exposes `work_context.actions` for the broader action
499
505
  modal. Its command actions only prepare visible `/wc` commands and never submit
@@ -720,6 +726,46 @@ separate those edits by provenance. Use an integration candidate only when the
720
726
  combined patch is coherent and verified; otherwise stop and establish a safe
721
727
  candidate boundary before publication.
722
728
 
729
+ ### Confirmed Integration Coverage
730
+
731
+ Confirmed coverage is the only exception that lets one integration candidate
732
+ stand in for the Current work of multiple `per_item` stages. It is available
733
+ only in a startup workspace and requires one ready `integration` candidate,
734
+ 2-20 explicit unique selected stages, and a Current execution item in every
735
+ selected stage:
736
+
737
+ ```text
738
+ /wc candidate confirm-coverage 000123 CC-000001 stages 02 04 INTEGRATION_COVERAGE_CONFIRMED
739
+ ```
740
+
741
+ The confirmation snapshots each selected stage's stable Current item ID and
742
+ execution revision. Every selected stage must have effective `per_item` mode and
743
+ be actionable. Candidate `relatedStages` remains traceability only: it does not
744
+ select stages, prove coverage, or authorize completion. At publication, Work
745
+ Context revalidates the snapshots before any Git mutation. If a Current item,
746
+ execution revision, effective mode, or stage status changed, it returns
747
+ `CANDIDATE_COVERAGE_STALE`, leaves the candidate ready, and creates no commit.
748
+
749
+ On success, the committed candidate durably records the selected coverage and
750
+ commit SHA, but does not advance a checklist or stage lifecycle. Each selected
751
+ stage must verify the remaining integration result and separately run
752
+ `complete-current`. Coverage remains visible in resume and sidebar state only
753
+ while that exact Current item remains current; it clears for a stage as soon as
754
+ that stage advances Current.
755
+
756
+ An already-active, unambiguous native session receives one bounded system notice
757
+ before its next model request after covered publication. Inactive and newly
758
+ resumed sessions use the durable resume/sidebar coverage state instead. This
759
+ notice never changes prompts, turns, or attention indicators. Standard-mode
760
+ workspaces, manual commit mode, ordinary unconfirmed integration or
761
+ shared-foundation candidates, and repository-local `commit all` retain their
762
+ existing behavior.
763
+
764
+ Before discarding an exact draft for an integration candidate, prove the
765
+ replacement covers the exact draft's intended work through capture, preview,
766
+ readiness, and explicit coverage confirmation when it will substitute for
767
+ multiple Current items. Related-stage metadata alone is not proof.
768
+
723
769
  ### Repository-local commit all
724
770
 
725
771
  `commit all` is the explicit fast path for one coherent repository-wide
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":5,"descriptor_hash":"sha256:69c90783d3bc08ffd46dc764ba93a0feabaaf10f1e4d7fe0b170c633e6dd20e0"} -->
6
+ <!-- opencode-work-context-protocol: {"schema":1,"major":1,"minor":6,"descriptor_hash":"sha256:f36697c79f083633f0afeeb4a7701f40abf261e488c967fc868867288d11262c"} -->
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
@@ -39,6 +39,7 @@ Use these exact tool mappings; do not invent shortened tool names:
39
39
  - `candidate show <workspace> <candidateId>` -> `work_context_show_candidate`
40
40
  - `candidate list <workspace>` -> `work_context_list_candidates`
41
41
  - `candidate ready <workspace> <candidateId>` -> `work_context_ready_candidate`
42
+ - `candidate confirm-coverage <workspace> <candidateId> stages <stage>... INTEGRATION_COVERAGE_CONFIRMED` -> `work_context_confirm_candidate_coverage`
42
43
  - `candidate commit <workspace> <candidateId> ["message"]` -> `work_context_commit_candidate`
43
44
  - `candidate discard <workspace> <candidateId>` -> `work_context_discard_candidate`
44
45
  - `commit all <workspace> ["message"] [stages <stage>...] [exclude <path>...]` -> `work_context_inspect_commit_all`
@@ -92,6 +93,7 @@ Supported syntax:
92
93
  - `candidate show <workspace> <candidateId>`
93
94
  - `candidate list <workspace>`
94
95
  - `candidate ready <workspace> <candidateId>`
96
+ - `candidate confirm-coverage <workspace> <candidateId> stages <stage>... INTEGRATION_COVERAGE_CONFIRMED`
95
97
  - `candidate commit <workspace> <candidateId> ["message"]`
96
98
  - `candidate discard <workspace> <candidateId>`
97
99
  - `commit all <workspace> ["message"] [stages <stage>...] [exclude <path>...]`
@@ -155,7 +157,11 @@ Supported syntax:
155
157
  - 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
158
  - 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
159
  - 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.
160
+ - 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. An ordinary `shared_foundation` or `integration` candidate does not satisfy Current completion. The narrow exception is committed, confirmed integration coverage described below. 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.
161
+ - `candidate confirm-coverage` is available only in a startup workspace for one ready `integration` candidate. It requires an explicit selection of 2-20 unique actionable stages, the exact `INTEGRATION_COVERAGE_CONFIRMED` token, effective `per_item` mode, and a Current item for every selected stage. It snapshots each selected stage's stable Current item ID and execution revision. `relatedStages` remains traceability-only and neither selects nor authorizes coverage.
162
+ - candidate publication revalidates confirmed coverage before any Git mutation. A changed Current item, execution revision, effective mode, or terminal stage returns `CANDIDATE_COVERAGE_STALE`; the candidate remains ready and no commit is created. A successful publication stores the durable coverage and commit SHA but never advances execution state or stage lifecycle. Each selected stage verifies its remaining integration result and calls `complete-current` separately.
163
+ - committed coverage remains visible for exactly the covered Current item, then disappears for that stage when that Current advances. An already-active, unambiguous native session receives one bounded system notice before its next model request. Inactive or new sessions receive the durable resume/sidebar coverage fallback. Coverage never repurposes prompts, turns, or attention signals.
164
+ - before discarding an existing exact draft in favor of an integration candidate, prove the integration replacement covers the exact draft's intended work through capture, preview, readiness, and, when it substitutes for multiple Current items, explicit coverage confirmation. Do not discard the exact draft based only on related-stage metadata.
159
165
  - `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
160
166
  - 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
161
167
  - do not expose raw workspace/stage/session identifiers, ordinals, `ok` flags, or absent error codes in the user-facing resume summary
@@ -168,12 +174,11 @@ Supported syntax:
168
174
  - standard-mode and unassociated core sessions do not receive startup policy; retain the existing conservative worktree behavior there
169
175
  - after presenting the summary, continue work immediately when `resume.next_action` is `start_work`; do not ask for generic confirmation
170
176
  - 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
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
- - `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
- - 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
177
+ - `create` enters the new workspace's Planning stage in the current OpenCode session only when that native session has no active or historical work-context stage affinity; otherwise it creates the workspace without rebinding the current OpenCode session
178
+ - `stage add` only creates a planned stage; it never starts a stage session or changes the invoking OpenCode session's current stage, regardless of whether that session is associated with a workspace. Enter the new stage later with an explicit `resume <workspace> <stage>` in a separate OpenCode session
179
+ - `resume` never rebinds the OpenCode session that invokes it: the first associated work-context stage becomes that native session's immutable affinity, and attempting to start any different stage must fail atomically with `CURRENT_OPENCODE_SESSION_ALREADY_ASSOCIATED`; open a separate OpenCode session for the requested stage. Handoff, close, finish, abandon, archive, workspace completion, stage reopen, and stage restore never transfer or clear affinity
175
180
  - 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
181
+ - read-only session diagnostics report a legacy active association that conflicts with the earliest historical affinity as `SESSION_ASSOCIATION_SPLIT_BRAIN`; preserve the earliest historical association as the presumed original affinity, explicitly hand off or close only the incorrect later active association, and never force-close the presumed original merely because the conflict exists
177
182
  - 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
178
183
  - `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
179
184
  - `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.
@@ -187,7 +192,7 @@ Supported syntax:
187
192
  - `stage reopen <workspace> <stage> "reason"` applies only to a completed stage, preserves its result and completion history, records the reason, changes it to `in_progress`, and does not start a session or affect downstream stages; use an explicit separate-session `resume` to work on it again
188
193
  - `stage restore <workspace> <stage> "reason"` applies only to an archived stage and restores its saved pre-archive status. New archives preserve that status; legacy archives restore to `in_progress`. It records the reason, preserves stage content and results, does not start a session, and requires explicit separate-session `resume` when restored to `planned` or `in_progress`.
189
194
  - `workspace reopen <workspace> "reason"` applies only to a completed workspace, changes it to `in_progress`, and records durable recovery history. Cancelled workspaces cannot be reopened.
190
- - candidate operations require `startup` workflow mode and store metadata and patch payloads only under `.work-context/local/`; create accepts an optional strategy and related stages, which are normalized references for traceability only and never ownership or lifecycle; active candidates explicitly related to the resumed stage appear as bounded metadata in `resume.context.pending_candidates` and in expanded sidebar details; capture requires exactly one explicit list of complete paths or one Git unified patch and never infers stage ownership; commit requires a ready candidate, uses its stored message unless a non-empty override is supplied, serializes Git publication, bypasses hooks and signing, and never uses the ordinary Git index
195
+ - candidate operations require `startup` workflow mode and store metadata and patch payloads only under `.work-context/local/`; create accepts an optional strategy and related stages, which are normalized references for traceability only and never ownership or lifecycle; active candidates explicitly related to the resumed stage appear as bounded metadata in `resume.context.pending_candidates` and in expanded sidebar details; capture requires exactly one explicit list of complete paths or one Git unified patch and never infers stage ownership; commit requires a ready candidate, uses its stored message unless a non-empty override is supplied, serializes Git publication, bypasses hooks and signing, and never uses the ordinary Git index. Confirmed integration coverage is an additional startup-only, per-item contract; it does not broaden standard-mode candidates, manual mode, or `commit all`.
191
196
  - `commit all` is an explicit two-phase repository-local integration operation available in standard and startup workspaces: first call inspection, report its included and excluded paths, traceability, proposed message, verification summary, and fingerprint, then wait for the user's exact `COMMIT_ALL_CONFIRMED` confirmation before calling publication with the same message, stages, exclusions, and fingerprint
192
197
  - commit-all inspection is read-only and never treats stages as file ownership; user-selected stages are traceability and message context, paths without defensible attribution remain explicit, `exclude` leaves known unrelated work outside the patch, and an omitted message uses the diff-derived proposal
193
198
  - commit-all publication re-inspects under the Git lock and returns `COMMIT_ALL_STALE_PLAN` when HEAD, patch content, exclusions, traceability, or message no longer match the confirmed fingerprint; never infer confirmation from tests, candidate readiness, preview success, or lifecycle state
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "opencode-work-context",
3
3
  "type": "module",
4
- "version": "0.14.1",
4
+ "version": "0.15.0",
5
5
  "description": "Filesystem work-context core and OpenCode adapter",
6
6
  "license": "MIT",
7
7
  "author": {
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import path from "node:path";
3
3
  import { loadConfig } from "../src/storage.js";
4
4
  import { readWorkContextSnapshot } from "../src/work-context-snapshot.js";
5
+ import { nativeSessionId } from "../src/sessions.js";
5
6
  import { createGlobalAttentionChannel } from "./global-attention.js";
6
7
  import { createAttentionActivator } from "./attention-activation.js";
7
8
  import { createDesktopNotifier } from "./notifier.js";
@@ -293,13 +294,13 @@ const currentSessionId = (api) => api?.route?.current?.name === "session"
293
294
  ? api.route.current.params?.sessionID || api.route.current.params?.sessionId || api.route.current.params?.session_id
294
295
  : undefined;
295
296
  const linkedSessionIds = (snapshot) => new Set((snapshot?.data?.workspaces || []).flatMap((workspace) =>
296
- (workspace.sessions || []).map((session) => session.opencode_session_id).filter(Boolean)));
297
+ (workspace.sessions || []).map(nativeSessionId).filter(Boolean)));
297
298
  const visibleSessionRecords = (snapshot, sessionId) => (snapshot?.workspaces || []).flatMap((workspace) => {
298
299
  const visibleStages = new Set((workspace.stages || [])
299
300
  .filter((stage) => stage.status !== "archived")
300
301
  .map((stage) => stage.id));
301
302
  return (workspace.sessions || [])
302
- .filter((session) => session.opencode_session_id === sessionId && visibleStages.has(session.stage))
303
+ .filter((session) => nativeSessionId(session) === sessionId && visibleStages.has(session.stage))
303
304
  .map((session) => ({ workspace, session }));
304
305
  });
305
306
  const activeVisibleSessionRecords = (snapshot, sessionId) => visibleSessionRecords(snapshot, sessionId)
@@ -1,4 +1,5 @@
1
1
  import { readWorkContextSnapshot } from "../src/work-context-snapshot.js";
2
+ import { nativeSessionId } from "../src/sessions.js";
2
3
  import { acknowledgeNavigation, attentionForSession, attentionIndicatorText, attentionReasonText } from "./attention.js";
3
4
 
4
5
  const SESSION_STATE_RANK = { active: 0, handed_off: 1, abandoned: 2, closed: 3 };
@@ -9,11 +10,11 @@ const projectRoot = (api) => api?.state?.path?.worktree || api?.state?.path?.dir
9
10
  const sessionTime = (session) => String(session.updated_at || session.started_at || "");
10
11
 
11
12
  const compareSessions = (left, right, currentId, attention) => {
12
- const leftCurrent = left.opencode_session_id === currentId;
13
- const rightCurrent = right.opencode_session_id === currentId;
13
+ const leftCurrent = nativeSessionId(left) === currentId;
14
+ const rightCurrent = nativeSessionId(right) === currentId;
14
15
  if (leftCurrent !== rightCurrent) return leftCurrent ? -1 : 1;
15
- const leftAttention = Boolean(attention?.(left.opencode_session_id));
16
- const rightAttention = Boolean(attention?.(right.opencode_session_id));
16
+ const leftAttention = Boolean(attention?.(nativeSessionId(left)));
17
+ const rightAttention = Boolean(attention?.(nativeSessionId(right)));
17
18
  if (leftAttention !== rightAttention) return leftAttention ? -1 : 1;
18
19
  return (SESSION_STATE_RANK[left.state] ?? 9) - (SESSION_STATE_RANK[right.state] ?? 9)
19
20
  || sessionTime(right).localeCompare(sessionTime(left))
@@ -26,7 +27,7 @@ const compareSessions = (left, right, currentId, attention) => {
26
27
  export const sortSessionSwitcherEntries = (entries = [], currentId = null, attention) => {
27
28
  const selected = new Map();
28
29
  for (const entry of entries) {
29
- const id = entry.session?.opencode_session_id;
30
+ const id = nativeSessionId(entry.session || {});
30
31
  if (!id || selected.has(id) && compareSessions(selected.get(id).session, entry.session, currentId, attention) <= 0) continue;
31
32
  selected.set(id, entry);
32
33
  }
@@ -36,7 +37,7 @@ export const sortSessionSwitcherEntries = (entries = [], currentId = null, atten
36
37
  export const selectSession = (entries = [], currentId = null) => sortSessionSwitcherEntries(entries, currentId)[0]?.session || null;
37
38
 
38
39
  export const switchToSession = (api, session) => {
39
- const sessionID = session?.opencode_session_id;
40
+ const sessionID = session ? nativeSessionId(session) : null;
40
41
  if (!sessionID) return errorResult("SESSION_OPENCODE_ID_MISSING", "This work-context session has no OpenCode session ID", { session_id: session?.session_id });
41
42
  if (typeof api?.route?.navigate !== "function") return errorResult("SESSION_SWITCH_UNAVAILABLE", "This OpenCode host cannot switch sessions from a TUI plugin");
42
43
  try {
@@ -66,7 +67,7 @@ export const createSessionSwitcherFlow = (api, { read = readWorkContextSnapshot
66
67
  const currentId = currentSessionId(api);
67
68
  const attention = (id) => attentionForSession(api, id);
68
69
  const available = sortSessionSwitcherEntries(entries, currentId, attention);
69
- const unavailable = entries.filter(({ session }) => !session.opencode_session_id);
70
+ const unavailable = entries.filter(({ session }) => !nativeSessionId(session));
70
71
  const labels = { active: "Active", handed_off: "Handed off", abandoned: "Abandoned", closed: "Closed" };
71
72
  api.ui.dialog.setSize?.("medium");
72
73
  api.ui.dialog.replace(() => api.ui.DialogSelect({
@@ -74,10 +75,10 @@ export const createSessionSwitcherFlow = (api, { read = readWorkContextSnapshot
74
75
  placeholder: "Search sessions",
75
76
  options: [
76
77
  ...available.map(({ workspace, session }) => ({
77
- title: `${attentionIndicatorText(attention(session.opencode_session_id))} ${workspace.id} ${session.stage || "-"}/${String(session.ordinal || 0).padStart(2, "0")} ${session.summary || "Work session"} · ${workspace.title}`.trim(),
78
- description: `${attention(session.opencode_session_id) ? `needs attention: ${attentionReasonText(attention(session.opencode_session_id).reason)} · ` : ""}${session.state || "unknown"} · ${session.session_id || "unknown"}`,
79
- footer: session.opencode_session_id,
80
- category: session.opencode_session_id === currentId ? "Current" : labels[session.state] || session.state || "Unknown",
78
+ title: `${attentionIndicatorText(attention(nativeSessionId(session)))} ${workspace.id} ${session.stage || "-"}/${String(session.ordinal || 0).padStart(2, "0")} ${session.summary || "Work session"} · ${workspace.title}`.trim(),
79
+ description: `${attention(nativeSessionId(session)) ? `needs attention: ${attentionReasonText(attention(nativeSessionId(session)).reason)} · ` : ""}${session.state || "unknown"} · ${session.session_id || "unknown"}`,
80
+ footer: nativeSessionId(session),
81
+ category: nativeSessionId(session) === currentId ? "Current" : labels[session.state] || session.state || "Unknown",
81
82
  value: session,
82
83
  })),
83
84
  ...unavailable.map(({ workspace, session }) => ({
@@ -1,4 +1,5 @@
1
1
  import { contextFor } from "../src/opencode-adapter.js";
2
+ import { nativeSessionId } from "../src/sessions.js";
2
3
  import { isDependencySatisfied } from "../src/stage-status.js";
3
4
  import { readTuiState, updateTuiState } from "./tui-state.js";
4
5
  import { acknowledgeNavigation, attentionForSession, attentionIndicatorText, attentionReasonText } from "./attention.js";
@@ -46,8 +47,8 @@ export const rememberRecentStage = (api, workspace, stage) => {
46
47
  export const recentStageIds = (api, workspace) => [...(recentStageStore(api).get(workspace) || [])];
47
48
 
48
49
  export const selectStageSession = (sessions = [], attention) => sessions
49
- .filter((session) => session.opencode_session_id)
50
- .sort((left, right) => Number(Boolean(attention?.(right.opencode_session_id))) - Number(Boolean(attention?.(left.opencode_session_id)))
50
+ .filter((session) => nativeSessionId(session))
51
+ .sort((left, right) => Number(Boolean(attention?.(nativeSessionId(right)))) - Number(Boolean(attention?.(nativeSessionId(left))))
51
52
  || (SESSION_STATE_RANK[left.state] ?? 9) - (SESSION_STATE_RANK[right.state] ?? 9)
52
53
  || String(right.updated_at || right.started_at || "").localeCompare(String(left.updated_at || left.started_at || ""))
53
54
  || Number(right.ordinal || 0) - Number(left.ordinal || 0))[0] || null;
@@ -56,7 +57,7 @@ export const selectStageSession = (sessions = [], attention) => sessions
56
57
  export const readStageSwitcherSnapshot = ({ projectRoot: root, sessionId } = {}) => {
57
58
  try {
58
59
  const context = contextFor(root, sessionId, "OpenCode TUI");
59
- const current = context.sessionByOpenCodeId(sessionId, null, null, null) || context.sessionById(sessionId);
60
+ const current = context.sessionAffinityByOpenCodeId(sessionId) || context.sessionById(sessionId);
60
61
  if (!current) return errorResult("STAGE_CONTEXT_REQUIRED", "The current OpenCode session is not associated with a work-context stage");
61
62
  const listed = context.listStages(current.workspace).data;
62
63
  const workspace = context.listWorkspaces().data.find((item) => item.workspace === current.workspace);
@@ -141,7 +142,7 @@ export const switchToStage = async (api, stage, options = {}) => {
141
142
  if (typeof api?.route?.navigate !== "function") return errorResult("SESSION_SWITCH_UNAVAILABLE", "This OpenCode host cannot switch sessions from a TUI plugin");
142
143
  const existing = stage.selectedSession || selectStageSession(stage.sessions);
143
144
  if (existing) {
144
- const switched = navigateToSession(api, existing.opencode_session_id);
145
+ const switched = navigateToSession(api, nativeSessionId(existing));
145
146
  if (switched.ok) {
146
147
  rememberRecentStage(api, options.workspace, stage.id);
147
148
  rememberRecentStage(api, options.workspace, options.currentStage);
@@ -204,7 +205,7 @@ export const createStageSwitcherFlow = (api, { read = readStageSwitcherSnapshot,
204
205
  const needsAttention = decorated.filter((stage) => !stage.current && stage.attention);
205
206
  const ordinary = decorated.filter((stage) => !stage.current && !stage.attention);
206
207
  const optionFor = (stage, category) => {
207
- const available = (stage.sessions || []).filter((session) => session.opencode_session_id).length;
208
+ const available = (stage.sessions || []).filter((session) => nativeSessionId(session)).length;
208
209
  const state = stage.blocked ? `blocked by ${stage.blockers.join(", ")}` : stage.status;
209
210
  return {
210
211
  title: `${stage.current ? ">" : " "} ${attentionIndicatorText(stage.attention)} ${stage.id}. ${stage.title}`.replace(/ +/g, " "),
@@ -45,6 +45,14 @@ const stageCandidateText = (stage) => {
45
45
  const others = candidate.related_stages.filter((related) => related !== stage.id);
46
46
  return `Pending: ${candidate.status} · ${candidate.strategy}${others.length ? ` · also ${others.join(", ")}` : ""}`;
47
47
  };
48
+ const stageCoverageText = (stage) => {
49
+ const coverage = stage.committed_coverage;
50
+ if (!coverage?.count) return null;
51
+ if (coverage.count > 1) return `Published Current: ${coverage.count} integration commits${coverage.truncated ? " (details truncated)" : ""}`;
52
+ const [item] = coverage.items;
53
+ const others = item.covered_stages.filter((covered) => covered !== stage.id);
54
+ return `Published Current: ${item.candidate} · ${item.commit_hash.slice(0, 8)}${others.length ? ` · also ${others.join(", ")}` : ""}`;
55
+ };
48
56
  export const checklistSummaryText = (execution) => {
49
57
  if (!execution) return null;
50
58
  const done = execution.completed?.length || 0;
@@ -103,7 +111,7 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention,
103
111
  stage.tracker_links?.length && `Tasks: ${stage.tracker_links.map(trackerLinkText).join(", ")}`,
104
112
  stage.depends_on?.length && `Deps: ${formatStageIds(stage.depends_on)}`,
105
113
  ].filter(Boolean).join(" · ");
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") : "";
114
+ const metadata = showDependencies ? [recommendation, stage.commit_mode && `Commits: ${stage.commit_mode.replace("_", "-")} (override)`, stageMetadata, stageCandidateText(stage), stageCoverageText(stage), stage.current && checklistSummaryText(stage.execution)].filter(Boolean).join("\n") : "";
107
115
  const attentionSignal = attentionSummaryText(unread);
108
116
  const onMouseDown = (event) => {
109
117
  if (event?.button != null && event.button !== 0) return;
@@ -313,7 +321,10 @@ const updateSessionTitle = async (api, projectRoot) => {
313
321
  if (!sessionId || typeof api?.client?.session?.update !== "function") return;
314
322
  try {
315
323
  const context = contextFor(projectRoot, sessionId);
316
- const session = context.sessionById(sessionId) || context.sessionByOpenCodeId(sessionId, null, null, null);
324
+ const affinity = context.sessionAffinityByOpenCodeId(sessionId);
325
+ const session = affinity
326
+ ? context.sessionByOpenCodeId(sessionId, affinity.workspace, affinity.stage) || affinity
327
+ : context.sessionById(sessionId);
317
328
  if (!session) return;
318
329
  const title = titleFor(context, session.workspace, session.stage, sessionId, session, readTuiState(projectRoot).sidebar_dependencies === true);
319
330
  await api.client.session.update({ path: { id: sessionId }, query: { directory: projectRoot }, body: { title } });
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { readWorkContextSnapshot } from "../src/work-context-snapshot.js";
4
4
  import { normalizeStageId, normalizeWorkspaceId } from "../src/identifiers.js";
5
+ import { nativeSessionId } from "../src/sessions.js";
5
6
  import { jsx } from "@opentui/solid/jsx-runtime";
6
7
  import { createSignal } from "solid-js";
7
8
  import { openStageSwitcher } from "./stage-switcher.js";
@@ -294,7 +295,7 @@ export const renderWorkContextModal = (controller, theme, runtime = { jsx }, { m
294
295
  capability && line(runtime, capability, { wrapMode: "word", fg: muted }),
295
296
  line(runtime, `Sessions ${(selected.sessions || []).length}`, { fg: muted }),
296
297
  ...(selected.sessions || []).map((session) => {
297
- const unread = controller.attention?.attentionFor?.(session.opencode_session_id);
298
+ const unread = controller.attention?.attentionFor?.(nativeSessionId(session));
298
299
  return line(runtime, `${unread ? `${attentionIndicatorText(unread)} ` : ""}${session.state || "unknown"} ${session.session_id || "unknown"} stage ${session.stage || "-"}`, { wrapMode: "word", fg: muted });
299
300
  }),
300
301
  ] : []),
@@ -498,7 +499,7 @@ export const createWorkContextActionFlow = (api, { projectRoot, sessionId, read
498
499
  { title: `State ${session.state || "unknown"}`, value: "state", category: "Details", disabled: true },
499
500
  { title: `Summary ${session.summary || "No summary"}`, value: "summary", category: "Details", disabled: true },
500
501
  { title: `Session ${session.session_id}`, value: "session", category: "Details", disabled: true },
501
- ...(session.opencode_session_id ? [{ title: `OpenCode ${session.opencode_session_id}`, value: "opencode", category: "Details", disabled: true }] : []),
502
+ ...(nativeSessionId(session) ? [{ title: `OpenCode ${nativeSessionId(session)}`, value: "opencode", category: "Details", disabled: true }] : []),
502
503
  ...(session.branch ? [{ title: `Branch ${session.branch}`, value: "branch", category: "Details", disabled: true }] : []),
503
504
  ...(session.updated_at ? [{ title: `Updated ${session.updated_at}`, value: "updated", category: "Details", disabled: true }] : []),
504
505
  ];
@@ -513,21 +514,23 @@ export const createWorkContextActionFlow = (api, { projectRoot, sessionId, read
513
514
  const rank = { active: 0, handed_off: 1, abandoned: 2, closed: 3 };
514
515
  const entries = loaded.workspaces.flatMap((workspace) => (workspace.sessions || []).map((session) => ({ workspace, session })));
515
516
  if (!entries.length) { toast("No sessions found"); return; }
517
+ const currentRecord = entries.filter(({ session }) => nativeSessionId(session) === sessionId)
518
+ .sort((left, right) => (rank[left.session.state] ?? 9) - (rank[right.session.state] ?? 9)
519
+ || String(right.session.updated_at || "").localeCompare(String(left.session.updated_at || "")))[0]?.session;
516
520
  entries.sort((left, right) => {
517
- const leftCurrent = left.session.opencode_session_id === sessionId || left.session.session_id === sessionId;
518
- const rightCurrent = right.session.opencode_session_id === sessionId || right.session.session_id === sessionId;
519
- if (leftCurrent) return -1;
520
- if (rightCurrent) return 1;
521
- const leftAttention = attentionForSession(api, left.session.opencode_session_id);
522
- const rightAttention = attentionForSession(api, right.session.opencode_session_id);
521
+ const leftCurrent = left.session === currentRecord;
522
+ const rightCurrent = right.session === currentRecord;
523
+ if (leftCurrent !== rightCurrent) return leftCurrent ? -1 : 1;
524
+ const leftAttention = attentionForSession(api, nativeSessionId(left.session));
525
+ const rightAttention = attentionForSession(api, nativeSessionId(right.session));
523
526
  if (Boolean(leftAttention) !== Boolean(rightAttention)) return leftAttention ? -1 : 1;
524
527
  return (rank[left.session.state] ?? 9) - (rank[right.session.state] ?? 9)
525
528
  || String(right.session.updated_at || "").localeCompare(String(left.session.updated_at || ""));
526
529
  });
527
530
  const labels = { active: "Active", handed_off: "Handed off", abandoned: "Abandoned", closed: "Closed" };
528
531
  showSelect("Sessions", entries.map(({ workspace, session }) => {
529
- const current = session.opencode_session_id === sessionId || session.session_id === sessionId;
530
- const unread = attentionForSession(api, session.opencode_session_id);
532
+ const current = session === currentRecord;
533
+ const unread = attentionForSession(api, nativeSessionId(session));
531
534
  return {
532
535
  title: `${attentionIndicatorText(unread)} ${workspace.id} ${sessionOrdinal(session)} ${session.summary || "Work session"} · ${workspace.title}`.trim(),
533
536
  description: `${unread ? `needs attention: ${attentionReasonText(unread.reason)} · ` : ""}${session.state || "unknown"} · ${session.session_id}`,
@@ -1,6 +1,9 @@
1
+ import fs from "node:fs";
1
2
  import { createToolDefinitions } from "../src/tool-definitions.js";
2
3
  import { contextFor, runtimeSelfReport, titleFor } from "../src/opencode-adapter.js";
3
4
  import { readTuiState } from "./tui-state.js";
5
+ import { appendIntegrationNotices, canAppendIntegrationNotices, consumeIntegrationNotices } from "../src/integration-notices.js";
6
+ import { withLock } from "../src/storage.js";
4
7
 
5
8
  export default async ({ client, directory, worktree }) => ({
6
9
  tool: createToolDefinitions({ runtimeEvidence: runtimeSelfReport(worktree === "/" ? directory : (worktree || directory)) }),
@@ -8,6 +11,25 @@ export default async ({ client, directory, worktree }) => ({
8
11
  if (!tool?.startsWith("work_context_") || tool === "work_context_doctor_delivery" || !sessionID) return;
9
12
  await updateSessionTitle(client, worktree || directory, directory, sessionID);
10
13
  },
14
+ "experimental.chat.system.transform": async ({ sessionID, model }, output) => {
15
+ try {
16
+ if (!sessionID || !model || !output || !canAppendIntegrationNotices(output.system)) return;
17
+ const projectRoot = worktree === "/" ? directory : (worktree || directory);
18
+ const context = contextFor(projectRoot, sessionID);
19
+ if (!fs.existsSync(context.storage.root)) return;
20
+ const notices = withLock(context.storage.lockPath("write"), () => {
21
+ const finding = context.diagnoseSessionAssociations(sessionID).data.findings[0];
22
+ if (finding) return [];
23
+ const session = context.sessionByOpenCodeId(sessionID);
24
+ if (!session) return [];
25
+ const coverage = context.candidates().committedCoverageProjection(session.workspace).by_stage[session.stage]?.items || [];
26
+ return consumeIntegrationNotices(projectRoot, sessionID, { personalRoot: context.storage.personalRoot, coverage });
27
+ }, { owner: "work-context integration notice", session: sessionID });
28
+ appendIntegrationNotices(output.system, notices);
29
+ } catch {
30
+ // Local notice delivery is best effort and must not interrupt a model request.
31
+ }
32
+ },
11
33
  event: async ({ event }) => {
12
34
  if (event.type !== "session.updated") return;
13
35
  const info = event.properties?.info;
@@ -24,7 +46,10 @@ export default async ({ client, directory, worktree }) => ({
24
46
  async function updateSessionTitle(client, projectRoot, directory, sessionId) {
25
47
  try {
26
48
  const context = contextFor(projectRoot, sessionId);
27
- const session = context.sessionById(sessionId) || context.sessionByOpenCodeId(sessionId, null, null, null);
49
+ const affinity = context.sessionAffinityByOpenCodeId(sessionId);
50
+ const session = affinity
51
+ ? context.sessionByOpenCodeId(sessionId, affinity.workspace, affinity.stage) || affinity
52
+ : context.sessionById(sessionId);
28
53
  if (!session) return;
29
54
  const title = titleFor(context, session.workspace, session.stage, sessionId, session, readTuiState(projectRoot).sidebar_dependencies === true);
30
55
  if (!title) return;
@@ -1,4 +1,5 @@
1
1
  import { readWorkContextSnapshot } from "../src/work-context-snapshot.js";
2
+ import { nativeSessionId } from "../src/sessions.js";
2
3
  import { acknowledgeNavigation, attentionForSession, attentionIndicatorText, attentionReasonText } from "./attention.js";
3
4
 
4
5
  const SESSION_STATE_RANK = { active: 0, handed_off: 1, abandoned: 2, closed: 3 };
@@ -10,8 +11,8 @@ const projectRoot = (api) => api?.state?.path?.worktree || api?.state?.path?.dir
10
11
 
11
12
  /** Select the best existing OpenCode session without changing work-context state. */
12
13
  export const selectWorkspaceSession = (sessions = [], attention) => sessions
13
- .filter((session) => session.opencode_session_id)
14
- .sort((left, right) => Number(Boolean(attention?.(right.opencode_session_id))) - Number(Boolean(attention?.(left.opencode_session_id)))
14
+ .filter((session) => nativeSessionId(session))
15
+ .sort((left, right) => Number(Boolean(attention?.(nativeSessionId(right)))) - Number(Boolean(attention?.(nativeSessionId(left))))
15
16
  || (SESSION_STATE_RANK[left.state] ?? 9) - (SESSION_STATE_RANK[right.state] ?? 9)
16
17
  || String(right.updated_at || right.started_at || "").localeCompare(String(left.updated_at || left.started_at || ""))
17
18
  || Number(right.ordinal || 0) - Number(left.ordinal || 0))[0] || null;
@@ -42,7 +43,7 @@ const navigateToSession = (api, sessionID) => {
42
43
  export const switchToWorkspace = (api, workspace) => {
43
44
  const session = workspace.selectedSession || selectWorkspaceSession(workspace.sessions);
44
45
  if (!session) return errorResult("WORKSPACE_SESSION_UNAVAILABLE", "This workspace has no OpenCode-backed session to open", { workspace: workspace.id });
45
- return navigateToSession(api, session.opencode_session_id);
46
+ return navigateToSession(api, nativeSessionId(session));
46
47
  };
47
48
 
48
49
  export const createWorkspaceSwitcherFlow = (api, { read = readWorkContextSnapshot } = {}) => {