opencode-work-context 0.10.1 → 0.10.3

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/src/delivery.js CHANGED
@@ -5,6 +5,10 @@ import { atomicWrite } from "./storage.js";
5
5
  import { ERROR_CODES, fail } from "./errors.js";
6
6
  import { normalizeWorkspaceId } from "./identifiers.js";
7
7
  import { inspectCommitRange, isCommitAncestor, repositoryState } from "./git-candidates.js";
8
+ import { inspectDetailedCommitRange } from "./delivery-git.js";
9
+ import { DELIVERY_DIAGNOSTIC_LIMITS, DELIVERY_EXPLAIN_CONTRACT_VERSION, DELIVERY_EXPLAIN_OPERATION, deliveryDiagnosticComplete, validateDeliveryExplainEnvelope, validateDeliveryFindings } from "./delivery-contracts.js";
10
+ import { createDeliveryPathRedactor } from "./delivery-redaction.js";
11
+ import { recommendDeliverySlices } from "./delivery-slices.js";
8
12
 
9
13
  const environmentPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
10
14
  const hashPattern = /^[0-9a-f]{40,64}$/;
@@ -12,6 +16,9 @@ const candidatePattern = /^CC-\d{6}$/;
12
16
  const timestamp = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
13
17
  const maxEnvironments = 20;
14
18
  const maxCandidates = 10000;
19
+ const diagnosticCandidateLimit = DELIVERY_DIAGNOSTIC_LIMITS.commits;
20
+ const diagnosticCandidatePathLimit = DELIVERY_DIAGNOSTIC_LIMITS.paths;
21
+ const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
15
22
  const checkpointIntegrity = (checkpoint) => createHash("sha256").update(JSON.stringify({
16
23
  deployed_head: checkpoint.deployed_head,
17
24
  deployed_at: checkpoint.deployed_at,
@@ -111,6 +118,125 @@ export class DeliveryStore {
111
118
  return { workspace, environment, checkpoint, ...projection, ...(range ? { range } : {}) };
112
119
  }
113
120
 
121
+ explain(workspace, options = {}) {
122
+ workspace = this.assertWorkspace(workspace);
123
+ const findings = validateDeliveryFindings(options.findings).map((finding) => {
124
+ const affectedPaths = finding.affected_paths.map((item) => {
125
+ const normalized = item.replace(/^(?:\.\/)+/u, "");
126
+ if (path.posix.isAbsolute(normalized) || normalized.includes("\\") || normalized.split("/").some((segment) => !segment || segment === "." || segment === "..")) {
127
+ fail(ERROR_CODES.DELIVERY_INVALID_FINDINGS, "Affected paths must be repository-relative normalized paths", { id: finding.id });
128
+ }
129
+ return normalized;
130
+ });
131
+ if (new Set(affectedPaths).size !== affectedPaths.length) fail(ERROR_CODES.DELIVERY_INVALID_FINDINGS, "Affected paths must remain unique after normalization", { id: finding.id });
132
+ return { ...finding, affected_paths: affectedPaths.sort(compareText) };
133
+ });
134
+ const evidence = inspectDetailedCommitRange(this.context.storage.projectRoot, options.from, options.to);
135
+ const workspaceMode = this.context.storage.readWorkspace(workspace).data.mode || "standard";
136
+ const commitSet = new Set(evidence.commits.map(({ commit }) => commit));
137
+ const finalPathSet = new Set(evidence.paths.map(({ path: file }) => file));
138
+ const traceability = workspaceMode === "startup"
139
+ ? this.candidateTraceability(workspace, commitSet)
140
+ : { capability: "unavailable", candidates: [], direct_commits: [] };
141
+ const allPaths = [
142
+ ...evidence.paths.map(({ path: file }) => file),
143
+ ...evidence.lineage.flatMap(({ from_path: fromPath, to_path: toPath }) => [fromPath, toPath]),
144
+ ...findings.flatMap((finding) => finding.affected_paths),
145
+ ...traceability.candidates.flatMap((candidate) => candidate.paths),
146
+ ];
147
+ const redactor = createDeliveryPathRedactor(this.context.storage.config.delivery.secret_path_patterns, allPaths);
148
+ const limits = {
149
+ commits: { count: evidence.commit_count, limit: DELIVERY_DIAGNOSTIC_LIMITS.commits, truncated: evidence.commits_truncated },
150
+ paths: { count: evidence.path_count, limit: DELIVERY_DIAGNOSTIC_LIMITS.paths, truncated: evidence.paths_truncated },
151
+ provenance: { limit_per_path: DELIVERY_DIAGNOSTIC_LIMITS.provenance_commits_per_path, truncated: evidence.paths.some((item) => item.provenance_truncated) },
152
+ candidate_traceability: {
153
+ candidates_limit: diagnosticCandidateLimit,
154
+ paths_limit: diagnosticCandidatePathLimit,
155
+ candidates_truncated: traceability.candidates_truncated || evidence.commits_truncated || false,
156
+ paths_truncated: traceability.paths_truncated || false,
157
+ },
158
+ git_output: { bytes: evidence.git_output_bytes, limit: DELIVERY_DIAGNOSTIC_LIMITS.git_output_bytes, truncated: false },
159
+ };
160
+ const complete = deliveryDiagnosticComplete(limits);
161
+ const normalizedFindings = findings.map((finding) => {
162
+ const matchedPaths = finding.affected_paths.filter((file) => finalPathSet.has(file));
163
+ const unmatchedPaths = finding.affected_paths.filter((file) => !finalPathSet.has(file));
164
+ const normalized = {
165
+ ...finding,
166
+ summary: redactor.text(finding.summary),
167
+ affected_paths: finding.affected_paths.map(redactor.path),
168
+ ...(evidence.paths_truncated ? {} : {
169
+ matched_paths: matchedPaths.map(redactor.path),
170
+ unmatched_paths: unmatchedPaths.map(redactor.path),
171
+ }),
172
+ ...(finding.recommendation === undefined || !complete ? {} : { recommendation: redactor.text(finding.recommendation) }),
173
+ };
174
+ if (!complete) delete normalized.recommendation;
175
+ return normalized;
176
+ });
177
+ const candidates = traceability.candidates.map((candidate) => ({ ...candidate, paths: candidate.paths.map(redactor.path) }));
178
+ const redactedPaths = evidence.paths.map((item) => ({ ...item, path: redactor.path(item.path) }));
179
+ const candidateTraceability = { ...traceability, candidates };
180
+ const candidateSlice = complete ? recommendDeliverySlices({
181
+ findings: normalizedFindings,
182
+ paths: redactedPaths,
183
+ candidate_traceability: candidateTraceability,
184
+ }) : [];
185
+ const severity = { info: 0, warning: 0, error: 0 };
186
+ for (const finding of normalizedFindings) severity[finding.severity] += 1;
187
+ return validateDeliveryExplainEnvelope({
188
+ contract_version: DELIVERY_EXPLAIN_CONTRACT_VERSION,
189
+ operation: DELIVERY_EXPLAIN_OPERATION,
190
+ immutable_range: evidence.immutable_range,
191
+ limits,
192
+ summary: {
193
+ commits: evidence.commit_count,
194
+ paths: evidence.path_count,
195
+ findings: normalizedFindings.length,
196
+ severity,
197
+ candidate_attributed_commits: traceability.capability === "available" ? new Set(candidates.flatMap((candidate) => candidate.commits)).size : null,
198
+ direct_commits: traceability.capability === "available" ? traceability.direct_commits.length : null,
199
+ },
200
+ paths: redactedPaths,
201
+ lineage: evidence.lineage.map((item) => ({ ...item, from_path: redactor.path(item.from_path), to_path: redactor.path(item.to_path) })),
202
+ findings: normalizedFindings,
203
+ candidate_traceability: candidateTraceability,
204
+ candidate_slice: candidateSlice,
205
+ redactions: redactor.summary,
206
+ complete,
207
+ });
208
+ }
209
+
210
+ candidateTraceability(workspace, commitSet) {
211
+ const records = this.context.candidates().projectionRecords(workspace)
212
+ .filter((candidate) => candidate.status === "committed" && commitSet.has(candidate.commit_hash))
213
+ .sort((left, right) => left.candidate.localeCompare(right.candidate));
214
+ const included = records.slice(0, diagnosticCandidateLimit);
215
+ let remainingPaths = diagnosticCandidatePathLimit;
216
+ let pathsTruncated = false;
217
+ const candidates = included.map((candidate) => {
218
+ const selectedPaths = [...candidate.selected_paths].sort(compareText);
219
+ const paths = selectedPaths.slice(0, remainingPaths);
220
+ remainingPaths -= paths.length;
221
+ if (paths.length < selectedPaths.length) pathsTruncated = true;
222
+ return {
223
+ candidate: candidate.candidate,
224
+ strategy: candidate.strategy || "exact",
225
+ related_stages: candidate.related_stages || [],
226
+ commits: [candidate.commit_hash],
227
+ paths,
228
+ };
229
+ });
230
+ const attributed = new Set(records.map((candidate) => candidate.commit_hash));
231
+ return {
232
+ capability: "available",
233
+ candidates,
234
+ direct_commits: [...commitSet].filter((commit) => !attributed.has(commit)),
235
+ candidates_truncated: records.length > included.length,
236
+ paths_truncated: pathsTruncated,
237
+ };
238
+ }
239
+
114
240
  mark(workspace, environment, commit, confirmation) {
115
241
  workspace = this.assertWorkspace(workspace);
116
242
  environment = normalizeEnvironment(environment);
package/src/errors.js CHANGED
@@ -11,6 +11,8 @@ export const ERROR_CODES = Object.freeze({
11
11
  CANDIDATE_REF_RACE: "CANDIDATE_REF_RACE", CANDIDATE_COMMIT_FAILED: "CANDIDATE_COMMIT_FAILED",
12
12
  EXECUTION_REVISION_CONFLICT: "EXECUTION_REVISION_CONFLICT", EXECUTION_LIMIT_EXCEEDED: "EXECUTION_LIMIT_EXCEEDED",
13
13
  DELIVERY_INVALID_RANGE: "DELIVERY_INVALID_RANGE", DELIVERY_RANGE_TOO_LARGE: "DELIVERY_RANGE_TOO_LARGE",
14
+ DELIVERY_INVALID_FINDINGS: "DELIVERY_INVALID_FINDINGS", DELIVERY_DIAGNOSTIC_TOO_LARGE: "DELIVERY_DIAGNOSTIC_TOO_LARGE",
15
+ DELIVERY_COMMAND_PROTOCOL_MISMATCH: "DELIVERY_COMMAND_PROTOCOL_MISMATCH",
14
16
  });
15
17
 
16
18
  export class WorkContextError extends Error {
package/src/index.js CHANGED
@@ -14,4 +14,9 @@ export * from "./work-context-snapshot.js";
14
14
  export * from "./git-candidates.js";
15
15
  export * from "./candidates.js";
16
16
  export * from "./delivery.js";
17
+ export * from "./delivery-contracts.js";
18
+ export * from "./delivery-git.js";
19
+ export * from "./delivery-redaction.js";
20
+ export * from "./delivery-doctor.js";
21
+ export * from "./protocol.js";
17
22
  export * from "./capability-profiles.js";
@@ -1,6 +1,8 @@
1
+ import fs from "node:fs";
1
2
  import path from "node:path";
2
3
  import { fileURLToPath } from "node:url";
3
4
  import { WorkContext } from "./core.js";
5
+ import { WORK_CONTEXT_PROTOCOL, WORK_CONTEXT_PROTOCOL_DESCRIPTOR_HASH } from "./protocol.js";
4
6
  import { renderTitle } from "./title.js";
5
7
  export { readStagesSnapshot } from "./stages-snapshot.js";
6
8
 
@@ -20,3 +22,26 @@ export function titleFor(context, workspace, stage, sessionId, knownSession = nu
20
22
  return renderTitle({ workspace, stageTitle: stageMeta.title, stage, ordinal: current.ordinal, state: current.state, trackerLinks: primaryTrackerLinks, stageTrackerLinks, issuePrefix: context.storage.config.title?.issue_prefix || "short" });
21
23
  }
22
24
  export const packageRoot = () => path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
25
+
26
+ export function runtimeSelfReport(projectRoot) {
27
+ const root = packageRoot();
28
+ let manifest = {};
29
+ try { manifest = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")); } catch {}
30
+ const project = path.resolve(projectRoot);
31
+ const localRoots = [path.join(project, "node_modules"), path.join(project, ".opencode", "node_modules")];
32
+ const moduleOrigin = localRoots.some((candidate) => root === candidate || root.startsWith(`${candidate}${path.sep}`))
33
+ ? "project_local"
34
+ : root.endsWith(`${path.sep}opencode-work-context`) && root.includes(`${path.sep}.cache${path.sep}`)
35
+ ? "managed_cache"
36
+ : "package_source";
37
+ return {
38
+ evidence_kind: "self_reported",
39
+ package_name: manifest.name,
40
+ package_version: manifest.version,
41
+ module_origin: moduleOrigin,
42
+ protocol: {
43
+ ...WORK_CONTEXT_PROTOCOL,
44
+ descriptor_hash: WORK_CONTEXT_PROTOCOL_DESCRIPTOR_HASH,
45
+ },
46
+ };
47
+ }
@@ -0,0 +1,47 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ export const WORK_CONTEXT_PROTOCOL = Object.freeze({
4
+ schema: 1,
5
+ major: 1,
6
+ minor: 0,
7
+ });
8
+
9
+ export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR = Object.freeze({
10
+ schema: WORK_CONTEXT_PROTOCOL.schema,
11
+ name: "opencode-work-context/wc",
12
+ protocol: Object.freeze({
13
+ major: WORK_CONTEXT_PROTOCOL.major,
14
+ minor: WORK_CONTEXT_PROTOCOL.minor,
15
+ }),
16
+ operations: Object.freeze(["delivery.doctor"]),
17
+ });
18
+
19
+ export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR_BYTES = JSON.stringify(WORK_CONTEXT_PROTOCOL_DESCRIPTOR);
20
+ export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR_HASH = createHash("sha256")
21
+ .update(WORK_CONTEXT_PROTOCOL_DESCRIPTOR_BYTES)
22
+ .digest("hex");
23
+
24
+ export const WORK_CONTEXT_PROTOCOL_MARKER = `<!-- opencode-work-context-protocol: ${JSON.stringify({
25
+ schema: WORK_CONTEXT_PROTOCOL.schema,
26
+ major: WORK_CONTEXT_PROTOCOL.major,
27
+ minor: WORK_CONTEXT_PROTOCOL.minor,
28
+ descriptor_hash: `sha256:${WORK_CONTEXT_PROTOCOL_DESCRIPTOR_HASH}`,
29
+ })} -->`;
30
+
31
+ export function parseWorkContextProtocolMarker(content) {
32
+ if (typeof content !== "string") return null;
33
+ const matches = [...content.matchAll(/<!-- opencode-work-context-protocol: (\{[^\r\n]*\}) -->/g)];
34
+ if (matches.length !== 1) return null;
35
+ try {
36
+ const marker = JSON.parse(matches[0][1]);
37
+ if (!marker || typeof marker !== "object" || Array.isArray(marker)
38
+ || !Number.isInteger(marker.schema) || marker.schema < 1
39
+ || !Number.isInteger(marker.major) || marker.major < 0
40
+ || !Number.isInteger(marker.minor) || marker.minor < 0
41
+ || typeof marker.descriptor_hash !== "string"
42
+ || !/^sha256:[a-f0-9]{64}$/.test(marker.descriptor_hash)) return null;
43
+ return marker;
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
package/src/storage.js CHANGED
@@ -5,6 +5,7 @@ import { WorkContextError, ERROR_CODES, fail } from "./errors.js";
5
5
  import { parseFrontmatter, renderMarkdown } from "./markdown.js";
6
6
  import { validateExecutionRecord } from "./stage-execution.js";
7
7
  import { CAPABILITY_CLASSIFICATIONS, CAPABILITY_DEPTHS, CAPABILITY_PROFILES } from "./capability-profiles.js";
8
+ import { validateSecretPathPatterns } from "./delivery-redaction.js";
8
9
 
9
10
  const now = () => new Date().toISOString();
10
11
  const ensure = (dir) => fs.mkdirSync(dir, { recursive: true });
@@ -142,7 +143,8 @@ export class FileStorage {
142
143
  constructor(projectRoot, config = {}) {
143
144
  this.projectRoot = projectRoot;
144
145
  const storage = config.storage || {};
145
- this.config = { mode: "hybrid", root: ".work-context", personal_root: ".work-context/local", title: { issue_prefix: "short" }, tracker: { provider: null }, capability_profiles: { mode: "advisory" }, ...config, ...storage, title: { issue_prefix: "short", ...(config.title || {}) }, tracker: { provider: null, ...(config.tracker || {}) }, capability_profiles: { mode: "advisory", ...(config.capability_profiles || {}) } };
146
+ this.config = { mode: "hybrid", root: ".work-context", personal_root: ".work-context/local", title: { issue_prefix: "short" }, tracker: { provider: null }, capability_profiles: { mode: "advisory" }, delivery: { secret_path_patterns: [] }, ...config, ...storage, title: { issue_prefix: "short", ...(config.title || {}) }, tracker: { provider: null, ...(config.tracker || {}) }, capability_profiles: { mode: "advisory", ...(config.capability_profiles || {}) }, delivery: { secret_path_patterns: [], ...(config.delivery || {}) } };
147
+ this.config.delivery.secret_path_patterns = validateSecretPathPatterns(this.config.delivery.secret_path_patterns);
146
148
  this.root = path.resolve(projectRoot, this.config.root);
147
149
  this.personalRoot = path.resolve(projectRoot, this.config.personal_root);
148
150
  const project = path.resolve(projectRoot);
@@ -310,7 +312,7 @@ export class FileStorage {
310
312
 
311
313
  export function loadConfig(projectRoot, configFile = path.resolve(projectRoot, ".work-context", "config.yaml")) {
312
314
  if (!fs.existsSync(configFile)) return {};
313
- const data = Object.assign(Object.create(null), { storage: Object.create(null), title: Object.create(null), tracker: Object.create(null), notifications: Object.create(null), capability_profiles: Object.create(null) });
315
+ const data = Object.assign(Object.create(null), { storage: Object.create(null), title: Object.create(null), tracker: Object.create(null), notifications: Object.create(null), capability_profiles: Object.create(null), delivery: Object.create(null) });
314
316
  let section = null;
315
317
  for (const line of fs.readFileSync(configFile, "utf8").split("\n")) {
316
318
  if (!line.trim() || line.trim().startsWith("#")) continue;
@@ -318,9 +320,20 @@ export function loadConfig(projectRoot, configFile = path.resolve(projectRoot, "
318
320
  if (!match[1]) { section = match[3] ? null : match[2]; if (match[3]) data[match[2]] = scalarConfig(match[3]); else if (!data[match[2]] || typeof data[match[2]] !== "object") data[match[2]] = Object.create(null); continue; }
319
321
  if (section && data[section] && typeof data[section] === "object") data[section][match[2]] = scalarConfig(match[3]);
320
322
  }
321
- if (Object.keys(data).some((key) => !["schema", "storage", "title", "tracker", "notifications", "capability_profiles"].includes(key)) || Object.keys(data.storage).some((key) => !["mode", "root", "personal_root"].includes(key)) || Object.keys(data.title).some((key) => key !== "issue_prefix") || Object.keys(data.tracker).some((key) => key !== "provider") || !data.notifications || typeof data.notifications !== "object" || Array.isArray(data.notifications) || Object.keys(data.notifications).some((key) => key !== "desktop") || !data.capability_profiles || typeof data.capability_profiles !== "object" || Array.isArray(data.capability_profiles) || Object.keys(data.capability_profiles).some((key) => key !== "mode") || (data.capability_profiles.mode !== undefined && !["advisory", "off"].includes(data.capability_profiles.mode)) || data.schema !== 1 || !data.storage || !["personal", "shared-git", "hybrid"].includes(data.storage.mode) || typeof data.storage.root !== "string" || typeof data.storage.personal_root !== "string" || !data.title || !["none", "short", "full"].includes(data.title.issue_prefix) || !data.tracker || (data.tracker.provider !== null && typeof data.tracker.provider !== "string") || (data.notifications.desktop !== undefined && typeof data.notifications.desktop !== "boolean")) fail(ERROR_CODES.STORAGE_ERROR, "Invalid work-context config");
323
+ if (Object.keys(data).some((key) => !["schema", "storage", "title", "tracker", "notifications", "capability_profiles", "delivery"].includes(key)) || Object.keys(data.storage).some((key) => !["mode", "root", "personal_root"].includes(key)) || Object.keys(data.title).some((key) => key !== "issue_prefix") || Object.keys(data.tracker).some((key) => key !== "provider") || !data.notifications || typeof data.notifications !== "object" || Array.isArray(data.notifications) || Object.keys(data.notifications).some((key) => key !== "desktop") || !data.capability_profiles || typeof data.capability_profiles !== "object" || Array.isArray(data.capability_profiles) || Object.keys(data.capability_profiles).some((key) => key !== "mode") || (data.capability_profiles.mode !== undefined && !["advisory", "off"].includes(data.capability_profiles.mode)) || !data.delivery || typeof data.delivery !== "object" || Array.isArray(data.delivery) || Object.keys(data.delivery).some((key) => key !== "secret_path_patterns") || data.schema !== 1 || !data.storage || !["personal", "shared-git", "hybrid"].includes(data.storage.mode) || typeof data.storage.root !== "string" || typeof data.storage.personal_root !== "string" || !data.title || !["none", "short", "full"].includes(data.title.issue_prefix) || !data.tracker || (data.tracker.provider !== null && typeof data.tracker.provider !== "string") || (data.notifications.desktop !== undefined && typeof data.notifications.desktop !== "boolean")) fail(ERROR_CODES.STORAGE_ERROR, "Invalid work-context config");
322
324
  data.capability_profiles.mode ||= "advisory";
325
+ data.delivery.secret_path_patterns = validateSecretPathPatterns(data.delivery.secret_path_patterns || []);
323
326
  return data;
324
327
  }
325
- const scalarConfig = (value) => value === "null" ? null : value === "[]" ? [] : value === "{}" ? {} : /^(true|false)$/.test(value) ? value === "true" : /^-?\d+(\.\d+)?$/.test(value) ? Number(value) : value;
326
- export const defaultConfig = () => `schema: 1\nstorage:\n mode: hybrid\n root: .work-context\n personal_root: .work-context/local\ntitle:\n issue_prefix: short\ntracker:\n provider: null\nnotifications:\n desktop: true\n`;
328
+ const scalarConfig = (value) => {
329
+ if (value === "null") return null;
330
+ if (value === "[]") return [];
331
+ if (value === "{}") return {};
332
+ if (/^(true|false)$/.test(value)) return value === "true";
333
+ if (/^-?\d+(\.\d+)?$/.test(value)) return Number(value);
334
+ if (value.startsWith("[") && value.endsWith("]")) {
335
+ try { return JSON.parse(value); } catch { return value; }
336
+ }
337
+ return value;
338
+ };
339
+ export const defaultConfig = () => `schema: 1\nstorage:\n mode: hybrid\n root: .work-context\n personal_root: .work-context/local\ntitle:\n issue_prefix: short\ntracker:\n provider: null\nnotifications:\n desktop: true\ndelivery:\n secret_path_patterns: []\n`;
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { z } from "zod";
3
- import { contextFor, titleFor } from "../src/opencode-adapter.js";
3
+ import { contextFor, runtimeSelfReport, titleFor } from "../src/opencode-adapter.js";
4
+ import { WorkContext } from "../src/core.js";
4
5
  import { fail, ERROR_CODES } from "../src/errors.js";
5
6
  import { normalizeStageId, normalizeWorkspaceId } from "../src/identifiers.js";
6
7
 
@@ -17,10 +18,34 @@ const run = (fn) => async (args, context) => {
17
18
  return { output: JSON.stringify({ ok: false, error: { code: error.code || "STORAGE_ERROR", message: error.message, details: error.details || {} } }), metadata: { code: error.code || "STORAGE_ERROR" } };
18
19
  }
19
20
  };
21
+ const runProject = (fn, { metadata = true, redactErrors = false } = {}) => async (args, context) => {
22
+ try {
23
+ const projectRoot = context.worktree === "/" ? context.directory : (context.worktree || context.directory);
24
+ const result = await fn(projectRoot, args, context);
25
+ if (metadata) try { await context.metadata({ title: "work-context", metadata: { result } }); } catch {}
26
+ return { output: JSON.stringify(result), metadata: result };
27
+ } catch (error) {
28
+ const stable = Object.values(ERROR_CODES).includes(error.code) ? error.code : ERROR_CODES.STORAGE_ERROR;
29
+ const result = { ok: false, error: {
30
+ code: stable,
31
+ message: redactErrors && stable !== ERROR_CODES.DELIVERY_COMMAND_PROTOCOL_MISMATCH ? "Delivery doctor could not complete safely" : error.message,
32
+ details: redactErrors && stable !== ERROR_CODES.DELIVERY_COMMAND_PROTOCOL_MISMATCH ? {} : (error.details || {}),
33
+ } };
34
+ return { output: JSON.stringify(result), metadata: { code: result.error.code } };
35
+ }
36
+ };
20
37
  const common = { workspace: tool.schema.string(), stage: tool.schema.string() };
21
38
  const contextualStage = { workspace: tool.schema.string().optional(), stage: tool.schema.string().optional() };
22
39
  const capabilityProfile = tool.schema.enum(["routine", "implementation", "architecture", "security", "review"]);
23
40
  const capabilityDepth = tool.schema.enum(["light", "standard", "deep"]);
41
+ const deliveryFinding = tool.schema.object({
42
+ id: tool.schema.string(),
43
+ severity: tool.schema.enum(["info", "warning", "error"]),
44
+ summary: tool.schema.string(),
45
+ affected_paths: tool.schema.array(tool.schema.string()).optional(),
46
+ remediation_ids: tool.schema.array(tool.schema.string()).optional(),
47
+ recommendation: tool.schema.string().optional(),
48
+ }).strict();
24
49
  const executionSections = {
25
50
  scope: tool.schema.array(tool.schema.string()).optional(),
26
51
  completed: tool.schema.array(tool.schema.string()).optional(),
@@ -76,6 +101,15 @@ export const work_context_ready_candidate = tool({ description: "Mark a captured
76
101
  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)) });
77
102
  export const work_context_discard_candidate = tool({ description: "Discard a local commit candidate without changing Git state.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string() }, execute: run((ctx, a) => ctx.discardCandidate(a.workspace, a.candidateId)) });
78
103
  export const work_context_read_delivery = tool({ description: "Read workspace-level delivery context. Exact Git inspection runs only when both immutable from and to commit hashes are provided.", args: { workspace: tool.schema.string(), environment: tool.schema.string().optional(), from: tool.schema.string().optional(), to: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.readDelivery(a.workspace, { environment: a.environment, from: a.from, to: a.to })) });
104
+ export const work_context_explain_delivery = tool({ description: "Explain a bounded immutable delivery range with read-only Git evidence, findings, and traceability.", args: { workspace: tool.schema.string(), from: tool.schema.string(), to: tool.schema.string(), findings: tool.schema.array(deliveryFinding).optional() }, execute: run((ctx, a) => ctx.explainDelivery(a.workspace, a.from, a.to, a.findings) ) });
105
+ const createDoctorDeliveryTool = ({ runtimeEvidence = runtimeSelfReport } = {}) => tool({
106
+ description: "Diagnose project delivery command, installation, and loaded-plugin protocol evidence without making changes.",
107
+ args: {},
108
+ execute: runProject((projectRoot) => WorkContext.doctorDelivery(projectRoot, {
109
+ loadedPlugin: typeof runtimeEvidence === "function" ? runtimeEvidence(projectRoot) : runtimeEvidence,
110
+ }), { metadata: false, redactErrors: true }),
111
+ });
112
+ export const work_context_doctor_delivery = createDoctorDeliveryTool();
79
113
  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)) });
80
114
  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)) });
81
115
  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)) });
@@ -114,4 +148,10 @@ export const work_context_add_knowledge = tool({ description: "Add a durable kno
114
148
  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)) });
115
149
  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) ) });
116
150
 
117
- export default { work_context_list_workspaces, work_context_workspace_list, work_context_rename_workspace, work_context_set_workspace_mode, work_context_create_candidate, work_context_capture_candidate, work_context_preview_candidate, work_context_show_candidate, work_context_list_candidates, work_context_ready_candidate, work_context_commit_candidate, work_context_discard_candidate, work_context_read_delivery, work_context_mark_delivery, work_context_workspace_finish, work_context_reopen_workspace, work_context_create_workspace, work_context_start_session, work_context_add_stage, work_context_set_stage_profiles, work_context_refresh_stage_profiles, work_context_show_capability_profiles, work_context_configure_capability_profiles, work_context_reset_capability_profiles, work_context_rename_stage, work_context_update_stage, work_context_update_stage_prompt, work_context_update_stage_result, work_context_read_stage_execution, work_context_replace_stage_execution, work_context_update_stage_execution, work_context_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 };
151
+ const defaultTools = { work_context_list_workspaces, work_context_workspace_list, work_context_rename_workspace, work_context_set_workspace_mode, work_context_create_candidate, work_context_capture_candidate, work_context_preview_candidate, work_context_show_candidate, work_context_list_candidates, work_context_ready_candidate, work_context_commit_candidate, work_context_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_add_stage, work_context_set_stage_profiles, work_context_refresh_stage_profiles, work_context_show_capability_profiles, work_context_configure_capability_profiles, work_context_reset_capability_profiles, work_context_rename_stage, work_context_update_stage, work_context_update_stage_prompt, work_context_update_stage_result, work_context_read_stage_execution, work_context_replace_stage_execution, work_context_update_stage_execution, work_context_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 };
152
+
153
+ export function createToolDefinitions(options = {}) {
154
+ return { ...defaultTools, work_context_doctor_delivery: createDoctorDeliveryTool(options) };
155
+ }
156
+
157
+ export default defaultTools;
@@ -0,0 +1,3 @@
1
+ import { work_context_doctor_delivery } from "../src/tool-definitions.js";
2
+
3
+ export default work_context_doctor_delivery;
@@ -0,0 +1,3 @@
1
+ import { work_context_explain_delivery } from "../src/tool-definitions.js";
2
+
3
+ export default work_context_explain_delivery;