opencode-work-context 0.14.1 → 0.16.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.
@@ -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 { appendDependencyNotices, appendIntegrationNotices, canAppendIntegrationNotices, consumeDependencyNotices, 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,31 @@ 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 { integration: [], dependency: [] };
23
+ const session = context.sessionByOpenCodeId(sessionID);
24
+ if (!session) return { integration: [], dependency: [] };
25
+ const coverage = context.candidates().committedCoverageProjection(session.workspace).by_stage[session.stage]?.items || [];
26
+ const stages = context.listStages(session.workspace).data.stages;
27
+ const stage = stages.find((item) => item.stage === session.stage);
28
+ return {
29
+ integration: consumeIntegrationNotices(projectRoot, sessionID, { personalRoot: context.storage.personalRoot, coverage }),
30
+ dependency: consumeDependencyNotices(projectRoot, sessionID, { personalRoot: context.storage.personalRoot, records: context.handoffs().read(session.workspace).records, dependencies: stage?.depends_on || [], dependencyGenerations: Object.fromEntries((stage?.depends_on || []).map((dependency) => [dependency, stage.dependency_epochs?.[dependency]?.generation || 1])) }),
31
+ };
32
+ }, { owner: "work-context integration notice", session: sessionID });
33
+ appendIntegrationNotices(output.system, notices.integration);
34
+ appendDependencyNotices(output.system, notices.dependency);
35
+ } catch {
36
+ // Local notice delivery is best effort and must not interrupt a model request.
37
+ }
38
+ },
11
39
  event: async ({ event }) => {
12
40
  if (event.type !== "session.updated") return;
13
41
  const info = event.properties?.info;
@@ -24,7 +52,10 @@ export default async ({ client, directory, worktree }) => ({
24
52
  async function updateSessionTitle(client, projectRoot, directory, sessionId) {
25
53
  try {
26
54
  const context = contextFor(projectRoot, sessionId);
27
- const session = context.sessionById(sessionId) || context.sessionByOpenCodeId(sessionId, null, null, null);
55
+ const affinity = context.sessionAffinityByOpenCodeId(sessionId);
56
+ const session = affinity
57
+ ? context.sessionByOpenCodeId(sessionId, affinity.workspace, affinity.stage) || affinity
58
+ : context.sessionById(sessionId);
28
59
  if (!session) return;
29
60
  const title = titleFor(context, session.workspace, session.stage, sessionId, session, readTuiState(projectRoot).sidebar_dependencies === true);
30
61
  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 } = {}) => {
package/src/candidates.js CHANGED
@@ -10,11 +10,25 @@ const candidatePattern = /^CC-(\d{6})$/;
10
10
  const statuses = new Set(["draft", "ready", "discarded", "committed"]);
11
11
  const strategies = new Set(["exact", "shared_foundation", "integration"]);
12
12
  const projectionCandidateLimit = 10;
13
+ const projectionCoverageLimit = 10;
13
14
  const projectionTitleLimit = 120;
14
15
  const deliveryCandidateLimit = 20;
16
+ const coverageStageLimit = 20;
17
+ const executionItemPattern = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|legacy-[0-9a-f]{24})$/;
15
18
  const timestamp = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
16
19
  const metadataKeys = ["schema", "candidate", "workspace", "title", "message", "base_head", "status", "created_at", "updated_at", "selected_paths", "patch_file"];
17
- const optionalMetadataKeys = ["strategy", "related_stages"];
20
+ const optionalMetadataKeys = ["strategy", "related_stages", "coverage"];
21
+
22
+ const validCoverage = (coverage) => coverage && typeof coverage === "object" && !Array.isArray(coverage)
23
+ && Object.keys(coverage).every((key) => ["schema", "confirmed_at", "entries"].includes(key))
24
+ && coverage.schema === 1 && timestamp(coverage.confirmed_at)
25
+ && Array.isArray(coverage.entries) && coverage.entries.length >= 2 && coverage.entries.length <= coverageStageLimit
26
+ && coverage.entries.every((entry) => entry && typeof entry === "object" && !Array.isArray(entry)
27
+ && Object.keys(entry).every((key) => ["stage", "current_item_id", "execution_revision"].includes(key))
28
+ && /^\d{2}$/.test(entry.stage) && entry.stage !== "00" && executionItemPattern.test(entry.current_item_id)
29
+ && Number.isInteger(entry.execution_revision) && entry.execution_revision >= 0)
30
+ && new Set(coverage.entries.map((entry) => entry.stage)).size === coverage.entries.length
31
+ && coverage.entries.every((entry, index) => index === 0 || coverage.entries[index - 1].stage.localeCompare(entry.stage) < 0);
18
32
 
19
33
  function validateCandidate(data, expectedId = null) {
20
34
  const valid = data && typeof data === "object" && !Array.isArray(data)
@@ -32,6 +46,7 @@ function validateCandidate(data, expectedId = null) {
32
46
  && (!Object.hasOwn(data, "strategy") || (strategies.has(data.strategy)
33
47
  && Array.isArray(data.related_stages) && data.related_stages.every((stage) => /^\d{2}$/.test(stage) && stage !== "00")
34
48
  && new Set(data.related_stages).size === data.related_stages.length))
49
+ && (!Object.hasOwn(data, "coverage") || (data.strategy === "integration" && validCoverage(data.coverage)))
35
50
  && (data.status === "committed"
36
51
  ? /^[0-9a-f]{40,64}$/.test(data.commit_hash) && timestamp(data.committed_at)
37
52
  : !Object.hasOwn(data, "commit_hash") && !Object.hasOwn(data, "committed_at"));
@@ -172,10 +187,108 @@ export class CandidateStore {
172
187
  related_stages: candidate.related_stages || [],
173
188
  commit_hash: candidate.commit_hash,
174
189
  committed_at: candidate.committed_at,
190
+ ...(candidate.coverage ? { coverage: candidate.coverage } : {}),
175
191
  })),
176
192
  };
177
193
  }
178
194
 
195
+ effectiveCommitMode(workspaceRecord, stageRecord) {
196
+ return stageRecord.commit_mode || workspaceRecord.commit_mode || "manual";
197
+ }
198
+
199
+ coverageEntry(workspace, stage, stale = false) {
200
+ const stageRecord = this.context.storage.readStage(workspace, stage).data;
201
+ const execution = this.context.storage.readStageExecution(workspace, stage);
202
+ const current = execution ? this.context.readStageExecution(workspace, stage).data.current : null;
203
+ if (!current) {
204
+ const code = stale ? ERROR_CODES.CANDIDATE_COVERAGE_STALE : ERROR_CODES.CANDIDATE_COVERAGE_CURRENT_REQUIRED;
205
+ fail(code, stale ? "Confirmed integration coverage no longer matches a Current item" : "Every covered stage must have a Current execution item", { stage });
206
+ }
207
+ const workspaceRecord = this.context.storage.readWorkspace(workspace).data;
208
+ if (this.effectiveCommitMode(workspaceRecord, stageRecord) !== "per_item") {
209
+ const code = stale ? ERROR_CODES.CANDIDATE_COVERAGE_STALE : ERROR_CODES.INVALID_STATE;
210
+ fail(code, stale ? "Confirmed integration coverage no longer has per-item authorization" : "Every covered stage must use per_item commit mode", { stage });
211
+ }
212
+ if (["completed", "cancelled", "archived"].includes(stageRecord.status)) {
213
+ const code = stale ? ERROR_CODES.CANDIDATE_COVERAGE_STALE : ERROR_CODES.INVALID_STATE;
214
+ fail(code, stale ? "Confirmed integration coverage includes a terminal stage" : "Covered stages must be actionable", { stage, status: stageRecord.status });
215
+ }
216
+ return { stage, current_item_id: current.id, execution_revision: execution.revision };
217
+ }
218
+
219
+ confirmCoverage(workspace, id, selectedStages, confirmation) {
220
+ workspace = this.assertStartup(workspace);
221
+ if (confirmation !== "INTEGRATION_COVERAGE_CONFIRMED") fail(ERROR_CODES.CANDIDATE_COVERAGE_CONFIRMATION_REQUIRED, "Candidate coverage requires the exact INTEGRATION_COVERAGE_CONFIRMED confirmation");
222
+ const data = this.read(id, workspace, true);
223
+ if (data.strategy !== "integration") fail(ERROR_CODES.INVALID_STATE, "Only integration candidates can receive multi-stage Current coverage");
224
+ if (data.status !== "ready") fail(ERROR_CODES.INVALID_STATE, "Only ready candidates can receive multi-stage Current coverage", { status: data.status });
225
+ if (!Array.isArray(selectedStages)) fail(ERROR_CODES.INVALID_ARGUMENT, "Covered stages must be an array");
226
+ const stages = selectedStages.map(normalizeStageId);
227
+ if (stages.length < 2 || stages.length > coverageStageLimit) fail(ERROR_CODES.INVALID_ARGUMENT, `Coverage requires between 2 and ${coverageStageLimit} stages`);
228
+ if (new Set(stages).size !== stages.length) fail(ERROR_CODES.INVALID_ARGUMENT, "Covered stages must be unique");
229
+ const entries = [...stages].sort().map((stage) => this.coverageEntry(workspace, stage));
230
+ if (data.coverage && JSON.stringify(data.coverage.entries) === JSON.stringify(entries)) {
231
+ const { patch, ...metadata } = data;
232
+ return metadata;
233
+ }
234
+ data.coverage = { schema: 1, confirmed_at: new Date().toISOString(), entries };
235
+ data.updated_at = data.coverage.confirmed_at;
236
+ const { patch, ...metadata } = data;
237
+ this.write(metadata);
238
+ return metadata;
239
+ }
240
+
241
+ validateCoverage(workspace, data) {
242
+ if (!data.coverage) return null;
243
+ const actual = data.coverage.entries.map((entry) => {
244
+ try { return this.coverageEntry(workspace, entry.stage, true); }
245
+ catch (error) {
246
+ if (error.code === ERROR_CODES.NOT_FOUND) fail(ERROR_CODES.CANDIDATE_COVERAGE_STALE, "A stage from confirmed integration coverage is no longer available", { stage: entry.stage });
247
+ throw error;
248
+ }
249
+ });
250
+ const stale = actual.find((entry, index) => entry.current_item_id !== data.coverage.entries[index].current_item_id
251
+ || entry.execution_revision !== data.coverage.entries[index].execution_revision);
252
+ if (stale) fail(ERROR_CODES.CANDIDATE_COVERAGE_STALE, "Confirmed integration coverage changed before publication", {
253
+ stage: stale.stage,
254
+ expected: data.coverage.entries.find((entry) => entry.stage === stale.stage),
255
+ actual: stale,
256
+ });
257
+ const duplicate = this.projectionRecords(workspace)
258
+ .filter((candidate) => candidate.candidate !== data.candidate && candidate.status === "committed" && candidate.coverage)
259
+ .flatMap((candidate) => candidate.coverage.entries.map((entry) => ({ candidate: candidate.candidate, commit_hash: candidate.commit_hash, ...entry })))
260
+ .find((entry) => data.coverage.entries.some((covered) => covered.stage === entry.stage && covered.current_item_id === entry.current_item_id));
261
+ if (duplicate) fail(ERROR_CODES.CANDIDATE_COVERAGE_STALE, "A selected Current item was already published by confirmed integration coverage", duplicate);
262
+ return data.coverage;
263
+ }
264
+
265
+ committedCoverageProjection(workspace) {
266
+ const projection = { count: 0, by_stage: {} };
267
+ for (const candidate of this.projectionRecords(workspace)) {
268
+ if (candidate.status !== "committed" || !candidate.coverage) continue;
269
+ for (const entry of candidate.coverage.entries) {
270
+ let current = null;
271
+ try {
272
+ const execution = this.context.storage.readStageExecution(workspace, entry.stage);
273
+ current = execution ? this.context.readStageExecution(workspace, entry.stage).data.current : null;
274
+ } catch { continue; }
275
+ if (current?.id !== entry.current_item_id) continue;
276
+ projection.count += 1;
277
+ const stageProjection = projection.by_stage[entry.stage] ||= { count: 0, truncated: false, items: [] };
278
+ stageProjection.count += 1;
279
+ if (stageProjection.items.length >= projectionCoverageLimit) { stageProjection.truncated = true; continue; }
280
+ stageProjection.items.push({
281
+ candidate: candidate.candidate,
282
+ commit_hash: candidate.commit_hash,
283
+ current_item_id: entry.current_item_id,
284
+ covered_stages: candidate.coverage.entries.map((item) => item.stage),
285
+ committed_at: candidate.committed_at,
286
+ });
287
+ }
288
+ }
289
+ return projection;
290
+ }
291
+
179
292
  capture(workspace, id, input, options = {}) {
180
293
  workspace = options.allowStandard ? this.assertWorkspace(workspace) : this.assertStartup(workspace);
181
294
  const data = this.read(id, workspace);
@@ -220,6 +333,7 @@ export class CandidateStore {
220
333
  if (data.status !== "ready") fail(ERROR_CODES.INVALID_STATE, "Only ready candidates can be committed", { status: data.status });
221
334
  if (message !== undefined && (typeof message !== "string" || !message.trim())) fail(ERROR_CODES.INVALID_ARGUMENT, "Commit message must be a non-empty string");
222
335
  const commitMessage = message === undefined ? data.message : message.trim();
336
+ this.validateCoverage(workspace, data);
223
337
  let metadata;
224
338
  const published = commitPatch(this.context.storage.projectRoot, data.base_head, data.patch, commitMessage, {
225
339
  expectedHead: options.expectedHead,
@@ -319,7 +433,7 @@ export class CandidateStore {
319
433
  options.beforeCandidate?.(inspection);
320
434
  if (repositoryState(this.context.storage.projectRoot).head !== inspection.base_head) fail(ERROR_CODES.COMMIT_ALL_STALE_PLAN, "Git HEAD no longer matches the confirmed commit-all plan", { expected_head: inspection.base_head });
321
435
  const patchHash = (value) => createHash("sha256").update(value).digest("hex");
322
- const duplicate = this.projectionRecords(workspace).filter((candidate) => ["draft", "ready"].includes(candidate.status)
436
+ const duplicate = this.projectionRecords(workspace).filter((candidate) => ["draft", "ready"].includes(candidate.status) && !candidate.coverage
323
437
  && candidate.strategy === "integration" && candidate.base_head === inspection.base_head
324
438
  && candidate.message === inspection.message && JSON.stringify(candidate.related_stages || []) === JSON.stringify(inspection.contributing_stages.map((item) => item.stage)))
325
439
  .find((candidate) => {