opencode-work-context 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,254 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { validateEventStream } from "./storage.js";
5
+ import { nativeSessionId, reduceSessions } from "./sessions.js";
6
+
7
+ const SCHEMA = 1;
8
+ const MAX_FILE_BYTES = 64 * 1024;
9
+ const MAX_SESSIONS_BYTES = 4 * 1024 * 1024;
10
+ const MAX_NOTICES = 32;
11
+ const MAX_DELIVERIES = 32;
12
+ const RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
13
+ const candidatePattern = /^CC-\d{6}$/;
14
+ const hashPattern = /^[0-9a-f]{40,64}$/;
15
+ const workspacePattern = /^\d{6}$/;
16
+ const stagePattern = /^\d{2}$/;
17
+ const sessionPattern = /^[A-Za-z0-9._:-]{1,128}$/;
18
+ const itemPattern = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|legacy-[0-9a-f]{24})$/;
19
+ const timestampPattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
20
+
21
+ const isObject = (value) => value && typeof value === "object" && !Array.isArray(value);
22
+ const timestamp = (value) => typeof value === "string" && timestampPattern.test(value) && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
23
+ const within = (base, target) => target === base || target.startsWith(`${base}${path.sep}`);
24
+
25
+ function noticePaths(projectRoot, personalRoot = null) {
26
+ const project = path.resolve(projectRoot);
27
+ const local = path.resolve(personalRoot || path.join(project, ".work-context", "local"));
28
+ return { project, local, queue: path.join(local, "integration-notices.json"), deliveries: path.join(local, "integration-notice-delivery"), lock: path.join(local, ".integration-notices.lock"), sessions: path.join(local, "sessions.jsonl") };
29
+ }
30
+
31
+ function safeDirectory(directory, create = false) {
32
+ const resolved = path.resolve(directory);
33
+ const parts = resolved.slice(path.parse(resolved).root.length).split(path.sep).filter(Boolean);
34
+ let current = path.parse(resolved).root;
35
+ for (const part of parts) {
36
+ current = path.join(current, part);
37
+ try {
38
+ const stat = fs.lstatSync(current);
39
+ if (stat.isSymbolicLink() || !stat.isDirectory()) return false;
40
+ } catch (error) {
41
+ if (error.code !== "ENOENT" || !create) return false;
42
+ try { fs.mkdirSync(current); } catch (mkdirError) { if (mkdirError.code !== "EEXIST") return false; }
43
+ }
44
+ }
45
+ return true;
46
+ }
47
+
48
+ function safeFile(file, maxBytes = MAX_FILE_BYTES) {
49
+ try {
50
+ const stat = fs.lstatSync(file);
51
+ return stat.isFile() && !stat.isSymbolicLink() && stat.size <= maxBytes;
52
+ } catch (error) { return error.code === "ENOENT"; }
53
+ }
54
+
55
+ function validNotice(item) {
56
+ return isObject(item)
57
+ && Object.keys(item).every((key) => ["id", "workspace", "stage", "native_session_id", "candidate", "commit_hash", "current_item_id", "other_stages", "created_at", "delivered_to"].includes(key))
58
+ && typeof item.id === "string" && /^[0-9a-f-]{36}$/.test(item.id)
59
+ && workspacePattern.test(item.workspace) && stagePattern.test(item.stage)
60
+ && sessionPattern.test(item.native_session_id) && candidatePattern.test(item.candidate) && hashPattern.test(item.commit_hash) && itemPattern.test(item.current_item_id)
61
+ && Array.isArray(item.other_stages) && item.other_stages.length <= 20 && item.other_stages.every((stage) => stagePattern.test(stage) && stage !== "00" && stage !== item.stage) && new Set(item.other_stages).size === item.other_stages.length
62
+ && timestamp(item.created_at)
63
+ && Array.isArray(item.delivered_to) && item.delivered_to.length <= MAX_DELIVERIES && item.delivered_to.every((session) => sessionPattern.test(session)) && new Set(item.delivered_to).size === item.delivered_to.length;
64
+ }
65
+
66
+ function readQueue(file) {
67
+ if (!safeFile(file)) return null;
68
+ try {
69
+ if (!fs.existsSync(file)) return { schema: SCHEMA, notices: [] };
70
+ const data = JSON.parse(fs.readFileSync(file, "utf8"));
71
+ if (!isObject(data) || data.schema !== SCHEMA || Object.keys(data).some((key) => !["schema", "notices"].includes(key)) || !Array.isArray(data.notices) || data.notices.length > MAX_NOTICES || !data.notices.every(validNotice)) return null;
72
+ return data;
73
+ } catch { return null; }
74
+ }
75
+
76
+ function writeQueue(file, queue) {
77
+ const content = `${JSON.stringify(queue, null, 2)}\n`;
78
+ if (Buffer.byteLength(content, "utf8") > MAX_FILE_BYTES) return false;
79
+ const temporary = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${randomUUID()}.tmp`);
80
+ try {
81
+ fs.writeFileSync(temporary, content, { encoding: "utf8", flag: "wx", mode: 0o600 });
82
+ fs.renameSync(temporary, file);
83
+ return true;
84
+ } catch {
85
+ try { fs.rmSync(temporary, { force: true }); } catch {}
86
+ return false;
87
+ }
88
+ }
89
+
90
+ function withLock(paths, operation, create = false) {
91
+ if (!within(paths.project, paths.local) || !safeDirectory(path.dirname(paths.local), create) || !safeDirectory(paths.local, create)) return null;
92
+ const acquire = () => {
93
+ try { fs.mkdirSync(paths.lock, { mode: 0o700 }); return true; }
94
+ catch { return false; }
95
+ };
96
+ if (!acquire()) return null;
97
+ const token = randomUUID();
98
+ try { fs.writeFileSync(path.join(paths.lock, "owner"), JSON.stringify({ token, pid: process.pid }), { encoding: "utf8", flag: "wx", mode: 0o600 }); }
99
+ catch { try { fs.rmSync(paths.lock, { recursive: true, force: true }); } catch {} return null; }
100
+ try { return operation(); }
101
+ catch { return null; }
102
+ finally {
103
+ try {
104
+ if (JSON.parse(fs.readFileSync(path.join(paths.lock, "owner"), "utf8")).token === token) fs.rmSync(paths.lock, { recursive: true, force: true });
105
+ } catch {}
106
+ }
107
+ }
108
+
109
+ const wait = (milliseconds) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
110
+
111
+ function withLockRetry(paths, operation, create, attempts) {
112
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
113
+ const result = withLock(paths, operation, create);
114
+ if (result !== null) return result;
115
+ if (attempt + 1 < attempts) wait(10);
116
+ }
117
+ return null;
118
+ }
119
+
120
+ function activeAssociations(sessionsFile) {
121
+ if (!safeFile(sessionsFile, MAX_SESSIONS_BYTES)) return null;
122
+ let rows;
123
+ try {
124
+ if (!fs.existsSync(sessionsFile)) return [];
125
+ rows = fs.readFileSync(sessionsFile, "utf8").split("\n").filter(Boolean);
126
+ if (rows.length > 10000) return null;
127
+ rows = rows.map((line) => JSON.parse(line));
128
+ } catch { return null; }
129
+ try { validateEventStream(rows); } catch { return null; }
130
+ return reduceSessions(rows)
131
+ .filter((session) => session.state === "active" && sessionPattern.test(nativeSessionId(session) || ""))
132
+ .map((session) => ({ workspace: session.workspace, stage: session.stage, native: nativeSessionId(session) }));
133
+ }
134
+
135
+ function associationFor(paths, workspace, stage, nativeSessionId = null) {
136
+ const active = activeAssociations(paths.sessions);
137
+ if (!active) return null;
138
+ const matching = active.filter((session) => session.workspace === workspace && session.stage === stage && (!nativeSessionId || session.native === nativeSessionId));
139
+ if (matching.length !== 1) return null;
140
+ const nativeMatches = active.filter((session) => session.native === matching[0].native);
141
+ return nativeMatches.length === 1 ? matching[0] : null;
142
+ }
143
+
144
+ function ordered(notices) {
145
+ return [...notices].sort((left, right) => left.created_at.localeCompare(right.created_at) || left.id.localeCompare(right.id));
146
+ }
147
+
148
+ const noticeKey = (notice) => `${notice.workspace}:${notice.stage}:${notice.native_session_id}:${notice.candidate}:${notice.commit_hash}:${notice.current_item_id}`;
149
+
150
+ const deliveryFile = (paths, nativeSessionId) => path.join(paths.deliveries, `${createHash("sha256").update(nativeSessionId).digest("hex")}.json`);
151
+ const readDelivery = (paths, nativeSessionId) => {
152
+ const file = deliveryFile(paths, nativeSessionId);
153
+ if (!safeFile(file)) return null;
154
+ if (!fs.existsSync(file)) return { schema: 1, native_session_id: nativeSessionId, delivered: [] };
155
+ try {
156
+ const data = JSON.parse(fs.readFileSync(file, "utf8"));
157
+ if (!isObject(data) || data.schema !== 1 || data.native_session_id !== nativeSessionId || Object.keys(data).some((key) => !["schema", "native_session_id", "delivered"].includes(key))
158
+ || !Array.isArray(data.delivered) || data.delivered.length > 20 || data.delivered.some((key) => typeof key !== "string" || key.length > 300) || new Set(data.delivered).size !== data.delivered.length) return null;
159
+ return data;
160
+ } catch { return null; }
161
+ };
162
+ const writeDelivery = (paths, delivery) => {
163
+ if (!safeDirectory(paths.deliveries, true)) return false;
164
+ return writeQueue(deliveryFile(paths, delivery.native_session_id), delivery);
165
+ };
166
+
167
+ function retained(notices, now, preserve = new Set()) {
168
+ return ordered(notices).filter((notice) => preserve.has(noticeKey(notice)) || Date.parse(notice.created_at) + RETENTION_MS >= now).slice(-MAX_NOTICES);
169
+ }
170
+
171
+ export function enqueueIntegrationNotice(projectRoot, { workspace, stage, candidate, commitHash, currentItemId, selectedStages = [], personalRoot = null } = {}) {
172
+ if (typeof projectRoot !== "string") return false;
173
+ if (!workspacePattern.test(workspace) || !stagePattern.test(stage) || stage === "00" || !candidatePattern.test(candidate) || !hashPattern.test(commitHash) || !itemPattern.test(currentItemId) || !Array.isArray(selectedStages) || selectedStages.length > 21 || selectedStages.some((item) => !stagePattern.test(item) || item === "00") || new Set(selectedStages).size !== selectedStages.length) return false;
174
+ const paths = noticePaths(projectRoot, personalRoot);
175
+ return withLockRetry(paths, () => {
176
+ const association = associationFor(paths, workspace, stage);
177
+ const queue = readQueue(paths.queue);
178
+ if (!association || !queue) return false;
179
+ const now = new Date().toISOString();
180
+ const notice = { id: randomUUID(), workspace, stage, native_session_id: association.native, candidate, commit_hash: commitHash, current_item_id: currentItemId, other_stages: selectedStages.filter((item) => item !== stage).sort(), created_at: now, delivered_to: [] };
181
+ return writeQueue(paths.queue, { schema: SCHEMA, notices: retained([...queue.notices, notice], Date.now()) });
182
+ }, true, 100) === true;
183
+ }
184
+
185
+ export function consumeIntegrationNotices(projectRoot, nativeSessionId, { personalRoot = null, coverage = null } = {}) {
186
+ if (typeof projectRoot !== "string" || !sessionPattern.test(nativeSessionId)) return [];
187
+ const paths = noticePaths(projectRoot, personalRoot);
188
+ if (coverage === null && !fs.existsSync(paths.queue)) return [];
189
+ const consumed = withLockRetry(paths, () => {
190
+ const queue = readQueue(paths.queue);
191
+ if (!queue) return [];
192
+ const active = activeAssociations(paths.sessions);
193
+ if (!active || active.filter((session) => session.native === nativeSessionId).length !== 1) return [];
194
+ const association = active.find((session) => session.native === nativeSessionId);
195
+ if (active.filter((session) => session.workspace === association.workspace && session.stage === association.stage).length !== 1) return [];
196
+ const authoritative = Array.isArray(coverage) ? coverage.filter((item) => item && candidatePattern.test(item.candidate) && hashPattern.test(item.commit_hash) && itemPattern.test(item.current_item_id)
197
+ && Array.isArray(item.covered_stages) && item.covered_stages.includes(association.stage)
198
+ && item.covered_stages.length <= 20 && item.covered_stages.every((stage) => stagePattern.test(stage) && stage !== "00")) : [];
199
+ const preserve = new Set(authoritative.map((item) => `${association.workspace}:${association.stage}:${nativeSessionId}:${item.candidate}:${item.commit_hash}:${item.current_item_id}`));
200
+ let notices = retained(queue.notices, Date.now(), preserve);
201
+ for (const item of authoritative) {
202
+ const key = `${association.workspace}:${association.stage}:${nativeSessionId}:${item.candidate}:${item.commit_hash}:${item.current_item_id}`;
203
+ if (!notices.some((notice) => noticeKey(notice) === key)) notices.push({
204
+ id: randomUUID(),
205
+ workspace: association.workspace,
206
+ stage: association.stage,
207
+ native_session_id: nativeSessionId,
208
+ candidate: item.candidate,
209
+ commit_hash: item.commit_hash,
210
+ current_item_id: item.current_item_id,
211
+ other_stages: item.covered_stages.filter((stage) => stage !== association.stage).sort(),
212
+ created_at: item.committed_at && timestamp(item.committed_at) ? item.committed_at : new Date().toISOString(),
213
+ delivered_to: [],
214
+ });
215
+ }
216
+ notices = retained(notices, Date.now(), preserve);
217
+ if (Array.isArray(coverage)) notices = notices.filter((notice) => preserve.has(noticeKey(notice)) || notice.workspace !== association.workspace || notice.stage !== association.stage || notice.native_session_id !== nativeSessionId);
218
+ const delivery = Array.isArray(coverage) ? readDelivery(paths, nativeSessionId) : null;
219
+ if (Array.isArray(coverage) && !delivery) return [];
220
+ const delivered = new Set(delivery?.delivered || []);
221
+ const ready = notices.filter((notice) => notice.workspace === association.workspace && notice.stage === association.stage && notice.native_session_id === nativeSessionId && !notice.delivered_to.includes(nativeSessionId) && !delivered.has(noticeKey(notice)));
222
+ if (!ready.length) return [];
223
+ if (delivery && !writeDelivery(paths, { ...delivery, delivered: [...delivered, ...ready.map(noticeKey)].filter((key) => preserve.has(key)).slice(-20) })) return [];
224
+ const deliveredIds = new Set(ready.map((notice) => notice.id));
225
+ writeQueue(paths.queue, { schema: SCHEMA, notices: notices.map((notice) => deliveredIds.has(notice.id) ? { ...notice, delivered_to: [...notice.delivered_to, nativeSessionId] } : notice) });
226
+ return ordered(ready);
227
+ }, false, 100);
228
+ return Array.isArray(consumed) ? consumed : [];
229
+ }
230
+
231
+ export function integrationNoticeText(notice) {
232
+ if (!validNotice(notice)) return null;
233
+ const stages = notice.other_stages.length ? ` Other selected stages: ${notice.other_stages.join(", ")}.` : "";
234
+ return `Integration coverage: candidate ${notice.candidate} was published as ${notice.commit_hash.slice(0, 8)}. Current was already published. Do not publish it again or reconstruct publication provenance. Verify only the remaining integration coverage, then call complete-current separately.${stages}`;
235
+ }
236
+
237
+ export const queueIntegrationNotice = enqueueIntegrationNotice;
238
+
239
+ export function canAppendIntegrationNotices(system) {
240
+ if (!Array.isArray(system) || Object.isFrozen(system) || !Object.isExtensible(system)) return false;
241
+ try {
242
+ const length = system.length;
243
+ system.push("");
244
+ system.length = length;
245
+ return true;
246
+ } catch { return false; }
247
+ }
248
+
249
+ export function appendIntegrationNotices(system, notices) {
250
+ if (!Array.isArray(system) || !Array.isArray(notices)) return 0;
251
+ const text = notices.map(integrationNoticeText).filter(Boolean);
252
+ system.push(...text);
253
+ return text.length;
254
+ }
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: 5,
6
+ minor: 6,
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", "commit_mode.workspace.set", "commit_mode.stage.set", "commit_mode.effective.read", "execution.complete_current"]),
16
+ operations: Object.freeze(["delivery.doctor", "commit.acknowledge", "commit.inspect_all", "commit.all", "candidate.confirm_coverage", "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,52 @@
1
+ import { nativeSessionId, sessionsByOpenCodeId } 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 sessionsByOpenCodeId(events, opencodeSessionId)) {
16
+ const sessionId = nativeSessionId(session);
17
+ if (!sessionId) continue;
18
+ const grouped = groups.get(sessionId) || [];
19
+ grouped.push(session);
20
+ groups.set(sessionId, grouped);
21
+ }
22
+
23
+ const findings = [...groups.entries()].flatMap(([nativeSessionId, sessions]) => {
24
+ const original = sessions[0];
25
+ const active = sessions.filter((session) => session.state === "active");
26
+ const activeAtAffinity = active.filter((session) => session.workspace === original.workspace && session.stage === original.stage);
27
+ const conflicting = [
28
+ ...active.filter((session) => session.workspace !== original.workspace || session.stage !== original.stage),
29
+ ...activeAtAffinity.slice(1),
30
+ ];
31
+ if (!conflicting.length) return [];
32
+ return [{
33
+ code: SESSION_ASSOCIATION_SPLIT_BRAIN,
34
+ severity: "error",
35
+ message: "One OpenCode session has an active association that conflicts with its immutable work-context stage affinity.",
36
+ opencode_session_id: nativeSessionId,
37
+ presumed_original_association: association(original),
38
+ conflicting_associations: conflicting.map(association),
39
+ recovery: {
40
+ status: "manual_recovery_required",
41
+ steps: [
42
+ "Treat the earliest historical association as the presumed original affinity until the session history is reviewed.",
43
+ "Explicitly hand off or close only the incorrect later association.",
44
+ "Do not force-close the presumed original association merely because a later association exists.",
45
+ "Open a separate OpenCode session before resuming another stage.",
46
+ ],
47
+ },
48
+ }];
49
+ });
50
+
51
+ return { schema: 1, status: findings.length ? "conflict" : "ok", findings };
52
+ }
package/src/sessions.js CHANGED
@@ -15,6 +15,11 @@ export function reduceSessions(events) {
15
15
  }
16
16
  return [...sessions.values()];
17
17
  }
18
+ export const nativeSessionId = (session) => session.opencode_session_id
19
+ || (!Object.hasOwn(session, "opencode_session_id") ? session.session_id : null);
20
+ export const sessionsByOpenCodeId = (events, opencodeSessionId) => reduceSessions(events)
21
+ .filter((session) => opencodeSessionId === null || opencodeSessionId === undefined || nativeSessionId(session) === opencodeSessionId);
22
+ export const openCodeSessionAffinity = (events, opencodeSessionId) => sessionsByOpenCodeId(events, opencodeSessionId)[0] || null;
18
23
  export const activeSession = (events, workspace, stage) => reduceSessions(events).find((item) => item.workspace === workspace && item.stage === stage && item.state === "active");
19
24
  export function event(event, workspace, stage, ordinal, sessionId, actor, data = {}) { return { schema: 1, event_id: randomUUID(), event, occurred_at: new Date().toISOString(), session_id: sessionId, workspace, stage, ordinal, actor, data }; }
20
25
  export function assertActive(events, workspace, stage, sessionId) { const session = reduceSessions(events).find((item) => item.session_id === sessionId && item.workspace === workspace && item.stage === stage); if (!session || session.state !== "active") fail(ERROR_CODES.SESSION_NOT_ACTIVE, "Session is not active"); return session; }
@@ -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" });
19
- let session = sessionId ? context.sessionById(sessionId) : null;
20
+ const sessionDiagnostics = context.diagnoseSessionAssociations(sessionId || null).data;
21
+ let session = sessionId ? context.sessionAffinityByOpenCodeId(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.sessionById(sessionId);
26
27
  }
27
28
  if (!session) {
28
29
  const activeWorkspaces = context.listWorkspaces().data.filter((workspace) => workspace.status === "in_progress");
@@ -32,12 +33,13 @@ 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";
39
40
  const commitMode = workspace.commit_mode || "manual";
40
41
  const candidateProjection = mode === "startup" ? context.candidates().activeProjection(session.workspace) : null;
42
+ const coverageProjection = mode === "startup" ? context.candidates().committedCoverageProjection(session.workspace) : null;
41
43
  const deliveryProjection = context.deliveries().projection(session.workspace);
42
44
  const delivery = deliveryProjection.committed.count || deliveryProjection.environments.length || deliveryProjection.unavailable
43
45
  ? { committed: deliveryProjection.committed.count, plan_needed: deliveryProjection.plan_needed, environments: deliveryProjection.environments, ...(deliveryProjection.unavailable ? { unavailable: true } : {}) }
@@ -58,6 +60,7 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
58
60
  ...(stage.commit_mode ? { commit_mode: stage.commit_mode } : {}),
59
61
  ...stageCapabilityProfiles(context.storage, stage, capabilityMappings),
60
62
  ...(candidateProjection?.by_stage[stage.stage] ? { candidates: candidateProjection.by_stage[stage.stage] } : {}),
63
+ ...(coverageProjection?.by_stage[stage.stage] ? { committed_coverage: coverageProjection.by_stage[stage.stage] } : {}),
61
64
  current: stage.stage === session.stage,
62
65
  }));
63
66
  const currentStage = stages.some((stage) => stage.current) ? session.stage : null;
@@ -73,6 +76,7 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
73
76
  workspace: { id: workspace.workspace, title: workspace.title, status: workspace.status, mode, commit_mode: commitMode, ...(candidateProjection ? { candidates: candidateProjection.summary } : {}), ...(delivery ? { delivery } : {}) },
74
77
  stages,
75
78
  currentStage,
79
+ sessionDiagnostics,
76
80
  generatedAt: new Date().toISOString(),
77
81
  },
78
82
  };
package/src/storage.js CHANGED
@@ -61,7 +61,7 @@ const validateEvent = (item) => {
61
61
  const allowed = item.event === "session.started" ? ["summary", "opencode_session_id", "branch"] : item.event === "session.renamed" ? ["summary"] : ["reason", "forced"];
62
62
  if (keys.some((key) => !allowed.includes(key)) || (item.event === "session.started" && (typeof item.data.summary !== "string" || !item.data.summary.trim() || (item.data.opencode_session_id !== null && item.data.opencode_session_id !== undefined && typeof item.data.opencode_session_id !== "string") || (item.data.branch !== null && item.data.branch !== undefined && typeof item.data.branch !== "string"))) || (item.event === "session.renamed" && (typeof item.data.summary !== "string" || !item.data.summary.trim())) || (item.event !== "session.started" && item.event !== "session.renamed" && (typeof item.data.reason !== "string" || !item.data.reason.trim()) || (item.data.forced !== undefined && typeof item.data.forced !== "boolean"))) fail(ERROR_CODES.STORAGE_ERROR, "Invalid session event data");
63
63
  };
64
- const validateEventStream = (events) => {
64
+ export const validateEventStream = (events) => {
65
65
  const ids = new Set();
66
66
  const sessions = new Map();
67
67
  const stages = new Map();
@@ -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
+ const affinity = ctx.sessionAffinityByOpenCodeId(ctx.options.sessionId);
66
+ return affinity && (!workspace || affinity.workspace === workspace) ? affinity : null;
67
+ };
58
68
  const workspaceFromSession = (ctx, workspace) => {
59
69
  if (workspace !== undefined) return normalizeWorkspaceId(workspace);
60
70
  const session = sessionFromContext(ctx);
@@ -67,25 +77,16 @@ const stageFromSession = (ctx, workspace, stage) => {
67
77
  if (!session) fail(ERROR_CODES.STAGE_CONTEXT_REQUIRED, "Stage is required when the current session is not associated with a stage");
68
78
  return session.stage;
69
79
  };
70
- const sessionFor = (ctx, oc, workspace, stage) => ctx.sessionById(oc.sessionID)?.workspace === workspace
71
- && ctx.sessionById(oc.sessionID)?.stage === stage
72
- ? oc.sessionID
73
- : ctx.sessionByOpenCodeId(oc.sessionID, workspace, stage)?.session_id || oc.sessionID;
74
- const addStageFromTool = (ctx, args, oc) => {
75
- const currentSession = sessionFromContext(ctx);
80
+ const activeSessionFromContext = (ctx, workspace, stage) => {
81
+ const associated = ctx.sessionByOpenCodeId(ctx.options.sessionId, workspace, stage);
82
+ if (associated) return associated;
83
+ const direct = ctx.sessionById(ctx.options.sessionId);
84
+ return direct?.workspace === workspace && direct.stage === stage && direct.state === "active" ? direct : null;
85
+ };
86
+ const sessionFor = (ctx, oc, workspace, stage) => activeSessionFromContext(ctx, workspace, stage)?.session_id || oc.sessionID;
87
+ const addStageFromTool = (ctx, args) => {
76
88
  const workspace = workspaceFromSession(ctx, args.workspace);
77
- const created = ctx.addStage(workspace, args.title, { goal: args.goal, prompt: args.prompt, dependsOn: args.dependsOn, executionProfile: args.executionProfile, executionDepth: args.executionDepth, classification: args.classification, reviewProfile: args.reviewProfile });
78
- if (currentSession) return created;
79
-
80
- const started = ctx.startSession(workspace, created.data.stage, {
81
- sessionId: randomUUID(),
82
- opencodeSessionId: oc.sessionID,
83
- summary: `started ${args.title.trim()}`,
84
- });
85
- return {
86
- ...started,
87
- data: { ...started.data, status: "in_progress", session_started: true, resume_required: false },
88
- };
89
+ return ctx.addStage(workspace, args.title, { goal: args.goal, prompt: args.prompt, dependsOn: args.dependsOn, executionProfile: args.executionProfile, executionDepth: args.executionDepth, classification: args.classification, reviewProfile: args.reviewProfile });
89
90
  };
90
91
  export const work_context_list_workspaces = tool({ description: "List work-context workspaces.", args: {}, execute: run((ctx) => ctx.listWorkspaces()) });
91
92
  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)) });
@@ -99,6 +100,7 @@ export const work_context_preview_candidate = tool({ description: "Preview a can
99
100
  export const work_context_show_candidate = tool({ description: "Show local candidate metadata and its exact captured patch.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string() }, execute: run((ctx, a) => ctx.showCandidate(a.workspace, a.candidateId)) });
100
101
  export const work_context_list_candidates = tool({ description: "List local commit candidates associated with a startup-mode workspace.", args: { workspace: tool.schema.string() }, execute: run((ctx, a) => ctx.listCandidates(a.workspace)) });
101
102
  export const work_context_ready_candidate = tool({ description: "Mark a captured draft candidate ready for a later explicit commit operation.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string() }, execute: run((ctx, a) => ctx.readyCandidate(a.workspace, a.candidateId)) });
103
+ export const work_context_confirm_candidate_coverage = tool({ description: "Explicitly confirm that one ready integration candidate covers the stable Current items of selected stages. Requires INTEGRATION_COVERAGE_CONFIRMED.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string(), stages: tool.schema.array(tool.schema.string()), confirmation: tool.schema.string() }, execute: run((ctx, a) => ctx.confirmCandidateCoverage(a.workspace, a.candidateId, a.stages, a.confirmation)) });
102
104
  export const work_context_commit_candidate = tool({ description: "Commit a ready candidate atomically without using the ordinary Git index. Uses its stored message unless message is provided.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string(), message: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.commitCandidate(a.workspace, a.candidateId, a.message)) });
103
105
  export const work_context_inspect_commit_all = tool({ description: "Inspect a repository-local integration boundary and return a confirmation fingerprint without changing Git or candidate state.", args: { workspace: tool.schema.string(), relatedStages: tool.schema.array(tool.schema.string()).optional(), excludePaths: tool.schema.array(tool.schema.string()).optional(), message: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.inspectCommitAll(a.workspace, { relatedStages: a.relatedStages, excludePaths: a.excludePaths, message: a.message })) });
104
106
  export const work_context_commit_all = tool({ description: "Reproduce and atomically publish a previously inspected repository-local integration plan after exact explicit confirmation.", args: { workspace: tool.schema.string(), expectedFingerprint: tool.schema.string(), confirmation: tool.schema.string(), relatedStages: tool.schema.array(tool.schema.string()).optional(), excludePaths: tool.schema.array(tool.schema.string()).optional(), message: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.commitAll(a.workspace, a.expectedFingerprint, a.confirmation, { relatedStages: a.relatedStages, excludePaths: a.excludePaths, message: a.message })) });
@@ -116,17 +118,18 @@ export const work_context_doctor_delivery = createDoctorDeliveryTool();
116
118
  export const work_context_mark_delivery = tool({ description: "Record a confirmed environment delivery checkpoint without executing deployment. Requires DELIVERY_CONFIRMED.", args: { workspace: tool.schema.string(), environment: tool.schema.string(), commit: tool.schema.string(), confirmation: tool.schema.string() }, execute: run((ctx, a) => ctx.markDelivery(a.workspace, a.environment, a.commit, a.confirmation)) });
117
119
  export const work_context_workspace_finish = tool({ description: "Finish a workspace after all stages are completed.", args: { workspace: tool.schema.string() }, execute: run((ctx, a) => ctx.finishWorkspace(a.workspace)) });
118
120
  export const work_context_reopen_workspace = tool({ description: "Reopen a completed workspace with a required reason and durable history.", args: { workspace: tool.schema.string(), reason: tool.schema.string() }, execute: run((ctx, a) => ctx.reopenWorkspace(a.workspace, a.reason)) });
119
- export const work_context_create_workspace = tool({ description: "Create a workspace; enter its planning stage only when the current OpenCode session is not associated with a workspace.", args: { title: tool.schema.string(), mode: tool.schema.enum(["standard", "startup"]).optional() }, execute: run((ctx, a, oc) => {
120
- const currentSession = ctx.sessionByOpenCodeId(oc.sessionID);
121
- return ctx.createWorkspace(a.title, { sessionId: randomUUID(), mode: a.mode, ...(currentSession ? {} : { opencodeSessionId: oc.sessionID }) });
121
+ export const work_context_create_workspace = tool({ description: "Create a workspace; enter its planning stage only when the native OpenCode session has no active or historical work-context stage affinity.", args: { title: tool.schema.string(), mode: tool.schema.enum(["standard", "startup"]).optional() }, execute: run((ctx, a, oc) => {
122
+ const currentSession = ctx.sessionAffinityByOpenCodeId(oc.sessionID);
123
+ return ctx.createWorkspace(a.title, { mode: a.mode, ...(currentSession ? { startSession: false } : { sessionId: randomUUID(), opencodeSessionId: oc.sessionID }) });
122
124
  }) });
123
- export const work_context_start_session = tool({ description: "Start a new active session for a stage and return its human-oriented presentation, prompt, active workspace knowledge, and startup policy when applicable.", args: { ...common, summary: tool.schema.string().optional() }, execute: run((ctx, a, oc) => ctx.startSession(a.workspace, a.stage, { sessionId: randomUUID(), opencodeSessionId: oc.sessionID, summary: a.summary, takeover: true })) });
125
+ export const work_context_start_session = tool({ description: "Start a new active session for the stage permanently associated with this OpenCode session and return its human-oriented presentation, prompt, active workspace knowledge, and startup policy when applicable. A different stage requires a separate OpenCode session.", args: { ...common, summary: tool.schema.string().optional() }, execute: run((ctx, a, oc) => ctx.startSession(a.workspace, a.stage, { sessionId: randomUUID(), opencodeSessionId: oc.sessionID, summary: a.summary, takeover: true })) });
124
126
  export const work_context_acknowledge_commit = tool({ description: "Acknowledge a user-created current-HEAD commit for the active session using a short or full commit hash. This is a deterministic light control-plane operation and does not infer ownership.", args: { sha: tool.schema.string() }, execute: run((ctx, a) => {
125
- const session = sessionFromContext(ctx);
127
+ const affinity = sessionFromContext(ctx);
128
+ const session = affinity && activeSessionFromContext(ctx, affinity.workspace, affinity.stage);
126
129
  if (!session) fail(ERROR_CODES.STAGE_CONTEXT_REQUIRED, "An active work-context stage is required to acknowledge a commit");
127
130
  return ctx.acknowledgeCommit(session.workspace, session.stage, session.session_id, a.sha);
128
131
  }) });
129
- 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) });
132
+ export const work_context_add_stage = tool({ description: "Add a planned stage without starting or changing a stage session. When the user did not specify execution capability and depth, 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) });
130
133
  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 } : {}) }); }) });
131
134
  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); }) });
132
135
  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 })) });
@@ -158,7 +161,7 @@ export const work_context_add_knowledge = tool({ description: "Add a durable kno
158
161
  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)) });
159
162
  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) ) });
160
163
 
161
- 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 };
164
+ 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_confirm_candidate_coverage, 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 };
162
165
 
163
166
  export function createToolDefinitions(options = {}) {
164
167
  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,8 +22,9 @@ const errorResult = (error) => ({
21
22
 
22
23
  const sessionFor = (context, sessionId) => {
23
24
  if (!sessionId) return null;
24
- return context.sessionById(sessionId)
25
- || context.sessionByOpenCodeId(sessionId, null, null, null);
25
+ const conflict = context.diagnoseSessionAssociations(sessionId).data.findings[0];
26
+ if (conflict) return context.sessionById(conflict.presumed_original_association.stage_session_id);
27
+ return context.sessionAffinityByOpenCodeId(sessionId) || context.sessionById(sessionId);
26
28
  };
27
29
 
28
30
  const readWorkspace = (context, record, currentSession, capabilityMappings) => {
@@ -35,6 +37,7 @@ const readWorkspace = (context, record, currentSession, capabilityMappings) => {
35
37
  const mode = record.mode || "standard";
36
38
  const commitMode = record.commit_mode || "manual";
37
39
  const candidateProjection = mode === "startup" ? context.candidates().activeProjection(record.workspace) : null;
40
+ const coverageProjection = mode === "startup" ? context.candidates().committedCoverageProjection(record.workspace) : null;
38
41
  const deliveryProjection = context.deliveries().projection(record.workspace);
39
42
  const delivery = deliveryProjection.committed.count || deliveryProjection.environments.length || deliveryProjection.unavailable
40
43
  ? { committed: deliveryProjection.committed.count, plan_needed: deliveryProjection.plan_needed, environments: deliveryProjection.environments, ...(deliveryProjection.unavailable ? { unavailable: true } : {}) }
@@ -62,6 +65,7 @@ const readWorkspace = (context, record, currentSession, capabilityMappings) => {
62
65
  ...(stage.commit_mode ? { commit_mode: stage.commit_mode } : {}),
63
66
  ...stageCapabilityProfiles(context.storage, stage, capabilityMappings),
64
67
  ...(candidateProjection?.by_stage[stage.stage] ? { candidates: candidateProjection.by_stage[stage.stage] } : {}),
68
+ ...(coverageProjection?.by_stage[stage.stage] ? { committed_coverage: coverageProjection.by_stage[stage.stage] } : {}),
65
69
  current: stage.stage === currentStage,
66
70
  })),
67
71
  currentStage,
@@ -75,6 +79,7 @@ export function readWorkContextSnapshot({ projectRoot, sessionId } = {}) {
75
79
  try {
76
80
  const context = WorkContext.openExisting(projectRoot, { sessionId, actor: "OpenCode TUI" });
77
81
  const currentSession = sessionFor(context, sessionId);
82
+ const sessionDiagnostics = context.diagnoseSessionAssociations(sessionId || null).data;
78
83
  const capabilityMappings = capabilityProfileMode(context.storage) === "advisory" ? readCapabilityMappings(context.storage) : null;
79
84
  const workspaces = context.listWorkspaces().data
80
85
  .sort((left, right) => left.workspace.localeCompare(right.workspace))
@@ -92,6 +97,7 @@ export function readWorkContextSnapshot({ projectRoot, sessionId } = {}) {
92
97
  currentStage: currentWorkspace
93
98
  ? workspaces.find((workspace) => workspace.id === currentWorkspace)?.currentStage || null
94
99
  : null,
100
+ sessionDiagnostics,
95
101
  generatedAt: new Date().toISOString(),
96
102
  },
97
103
  };
@@ -0,0 +1 @@
1
+ export { work_context_confirm_candidate_coverage as default } from "../src/tool-definitions.js";