opencode-work-context 0.10.0 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -686,6 +686,76 @@ If the host `opencode.json` restricts `experimental.primary_tools`, add the
686
686
  registered `work_context_*` tool names to that allowlist; the installer does not
687
687
  rewrite project-specific agent policy.
688
688
 
689
+ ### Delivery diagnostics
690
+
691
+ `delivery explain` and `delivery doctor` are versioned, read-only diagnostic
692
+ contracts. They never deploy, run remediation, change candidates or checkpoints,
693
+ rewrite configuration or generated command files, or persist diagnostic data.
694
+
695
+ Use `delivery explain` only with explicit immutable full commit hashes. An
696
+ external repository planner supplies structurally validated findings; Work Context
697
+ does not invent release policy or interpret remediation meaning:
698
+
699
+ ```text
700
+ /wc delivery explain 000123 <from-commit> <to-commit> '[{"id":"release.tests","severity":"warning","summary":"Review coverage","affected_paths":["src/report.js"],"remediation_ids":["tests.report"],"recommendation":"Add regression coverage"}]'
701
+ ```
702
+
703
+ The v1 response includes normalized Git path and provenance evidence, findings,
704
+ redaction status, and candidate traceability. It is bounded to 500 commits, 500
705
+ final paths, 50 provenance commits per path, 200 findings, and 4 MiB of Git and
706
+ diagnostic output. If a count limit truncates evidence, `complete` is false and
707
+ recommendations are omitted. A byte limit fails safely instead of returning an
708
+ unbounded response. In a startup workspace, committed candidates in the range are
709
+ traceability only and commits without them are reported as direct commits. In a
710
+ standard workspace, Git evidence remains available but candidate metadata is
711
+ explicitly unavailable.
712
+
713
+ Configure repository-relative secret-path redaction in the project-owned config:
714
+
715
+ ```yaml
716
+ delivery:
717
+ secret_path_patterns:
718
+ - secret/**
719
+ - '*.env'
720
+ ```
721
+
722
+ Only a constrained slash-separated glob grammar is accepted. Matching paths are
723
+ replaced everywhere in the response with response-local opaque tokens. Responses
724
+ never include raw patches, file contents, host commands, environment values,
725
+ credentials, tokens, secret values, or unsafe Git stderr.
726
+
727
+ Use `delivery doctor` to inspect the generated command, declared installation,
728
+ safely discoverable package manifests, loaded-plugin self-report, and host
729
+ attestation when the host provides it:
730
+
731
+ ```text
732
+ /wc delivery doctor
733
+ ```
734
+
735
+ Evidence is labeled `self_reported`, `host_attested`, or `unavailable`. A command
736
+ and loaded plugin with different protocol majors fail fast. Minor protocol,
737
+ descriptor hash, version, and module-origin drift produce findings with repair
738
+ guidance. The current OpenCode host may report authoritative attestation as
739
+ unavailable; doctor does not guess or repair automatically.
740
+
741
+ For a pinned local installation, repair with:
742
+
743
+ ```sh
744
+ npx --yes opencode-work-context@<version> init --force
745
+ ```
746
+
747
+ For managed activation, update the shared managed cache and then refresh the
748
+ project command contract when instructed:
749
+
750
+ ```sh
751
+ opencode plugin opencode-work-context@<version> --force
752
+ npx --yes opencode-work-context@<version> activate --force
753
+ ```
754
+
755
+ Restart OpenCode after either repair. The generated `.opencode/commands/wc.md`
756
+ remains package-managed; redaction configuration remains project-owned and is
757
+ preserved by installer updates.
758
+
689
759
  ## Release
690
760
 
691
761
  Maintainers publish this package only through
package/commands/wc.md CHANGED
@@ -3,6 +3,8 @@ description: Explicit work-context lifecycle commands backed by structured tools
3
3
  subtask: false
4
4
  ---
5
5
 
6
+ <!-- opencode-work-context-protocol: {"schema":1,"major":1,"minor":0,"descriptor_hash":"sha256:5cedc90065e0b36a1fd6e6a2cae519ccb51b1b6883c5dd9d9ea75efe776f8b50"} -->
7
+
6
8
  Interpret `/wc $ARGUMENTS` as an explicit work-context operation. Use the matching
7
9
  `work_context_*` custom tool registered by the installed package plugin with structured arguments. Never edit work-context
8
10
  Markdown, JSONL, INDEX, or SESSIONS projections directly. For mutating operations
@@ -38,6 +40,8 @@ Use these exact tool mappings; do not invent shortened tool names:
38
40
  - `candidate commit <workspace> <candidateId> ["message"]` -> `work_context_commit_candidate`
39
41
  - `candidate discard <workspace> <candidateId>` -> `work_context_discard_candidate`
40
42
  - `delivery read <workspace> [<environment>] [range <from> <to>]` -> `work_context_read_delivery`
43
+ - `delivery explain <workspace> <from> <to> [findings JSON]` -> `work_context_explain_delivery`
44
+ - `delivery doctor` -> `work_context_doctor_delivery`
41
45
  - `delivery mark <workspace> <environment> <commit> DELIVERY_CONFIRMED` -> `work_context_mark_delivery`
42
46
  - `workspace finish <workspace>` -> `work_context_workspace_finish`
43
47
  - `workspace reopen <workspace> "reason"` -> `work_context_reopen_workspace`
@@ -82,6 +86,8 @@ Supported syntax:
82
86
  - `candidate commit <workspace> <candidateId> ["message"]`
83
87
  - `candidate discard <workspace> <candidateId>`
84
88
  - `delivery read <workspace> [<environment>] [range <from> <to>]`
89
+ - `delivery explain <workspace> <from> <to> [findings JSON]`
90
+ - `delivery doctor`
85
91
  - `delivery mark <workspace> <environment> <commit> DELIVERY_CONFIRMED`
86
92
  - `workspace finish <workspace>`
87
93
  - `workspace reopen <workspace> "reason"`
@@ -158,6 +164,8 @@ Supported syntax:
158
164
  - `workspace reopen <workspace> "reason"` applies only to a completed workspace, changes it to `in_progress`, and records durable recovery history. Cancelled workspaces cannot be reopened.
159
165
  - candidate operations require `startup` workflow mode and store metadata and patch payloads only under `.work-context/local/`; create accepts an optional strategy and related stages, which are normalized references for traceability only and never ownership or lifecycle; active candidates explicitly related to the resumed stage appear as bounded metadata in `resume.context.pending_candidates` and in expanded sidebar details; capture requires exactly one explicit list of complete paths or one Git unified patch and never infers stage ownership; commit requires a ready candidate, uses its stored message unless a non-empty override is supplied, serializes Git publication, bypasses hooks and signing, and never uses the ordinary Git index
160
166
  - delivery operations are mode-neutral local operational state and never execute deployment; `delivery read` without a range returns metadata only, exact Git inspection requires both immutable `from` and `to` hashes, and `delivery mark` requires the exact `DELIVERY_CONFIRMED` token only after the user confirms successful delivery to that environment
167
+ - `delivery explain` is strictly read-only, accepts findings as structured JSON data, inspects only the explicit immutable range, and preserves stable errors, contract version, completeness, and omission of recommendations when incomplete
168
+ - `delivery doctor` is strictly read-only, compares generated-command, declared, installed, self-reported, and host-attested or unavailable runtime evidence, and fails fast only when command and loaded-plugin protocol majors differ
161
169
  - `knowledge list|add|update|supersede <workspace> ...`
162
170
 
163
171
  Arguments: $ARGUMENTS
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "opencode-work-context",
3
3
  "type": "module",
4
- "version": "0.10.0",
4
+ "version": "0.10.2",
5
5
  "description": "Filesystem work-context core and OpenCode adapter",
6
6
  "license": "MIT",
7
7
  "author": {
@@ -58,6 +58,15 @@ const stageCandidateText = (stage) => {
58
58
  return `Pending: ${candidate.status} · ${candidate.strategy}${others.length ? ` · also ${others.join(", ")}` : ""}`;
59
59
  };
60
60
  const capitalize = (value) => value ? `${value[0].toUpperCase()}${value.slice(1)}` : value;
61
+ const visibleAttentionSnapshot = (attention, workspace, stages) => {
62
+ const byStage = new Map(stages.map((stage) => [stage.id, attention?.attentionForStage?.(workspace, stage.id) || null]));
63
+ const bySession = new Map();
64
+ for (const unread of byStage.values()) {
65
+ for (const item of unread?.items || []) bySession.set(item.sessionId, item);
66
+ }
67
+ const items = [...bySession.values()];
68
+ return { byStage, workspace: items.length ? { count: items.length, items } : null };
69
+ };
61
70
 
62
71
  export { readStagesSnapshot, renderStagesPanel };
63
72
 
@@ -67,7 +76,8 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention,
67
76
  runtime.jsx("text", { children: runtime.jsx("b", { children: "Stages" }) }),
68
77
  ...renderStagesPanel(result).split("\n").slice(1).map((line) => runtime.jsx("text", { children: line })),
69
78
  ];
70
- const workspaceAttention = attentionSummaryText(attention?.attentionForWorkspace?.(result.data.workspace.id), { alwaysCount: true });
79
+ const attentionSnapshot = visibleAttentionSnapshot(attention, result.data.workspace.id, result.data.stages);
80
+ const workspaceAttention = attentionSummaryText(attentionSnapshot.workspace, { alwaysCount: true });
71
81
  return [
72
82
  runtime.jsx("box", {
73
83
  marginBottom: 1,
@@ -88,7 +98,7 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention,
88
98
  ],
89
99
  }),
90
100
  ...result.data.stages.flatMap((stage) => {
91
- const unread = attention?.attentionForStage?.(result.data.workspace.id, stage.id);
101
+ const unread = attentionSnapshot.byStage.get(stage.id);
92
102
  const working = attention?.activityForStage?.(result.data.workspace.id, stage.id);
93
103
  const recommendation = stage.execution_profile && stage.execution_depth && stage.recommended_model
94
104
  ? `${capitalize(stage.execution_profile)} · ${capitalize(stage.execution_depth)} · ${capitalize(stage.recommended_model)}`
@@ -1,11 +1,11 @@
1
- import tools from "../src/tool-definitions.js";
2
- import { contextFor, titleFor } from "../src/opencode-adapter.js";
1
+ import { createToolDefinitions } from "../src/tool-definitions.js";
2
+ import { contextFor, runtimeSelfReport, titleFor } from "../src/opencode-adapter.js";
3
3
  import { readTuiState } from "./tui-state.js";
4
4
 
5
5
  export default async ({ client, directory, worktree }) => ({
6
- tool: tools,
6
+ tool: createToolDefinitions({ runtimeEvidence: runtimeSelfReport(worktree === "/" ? directory : (worktree || directory)) }),
7
7
  "tool.execute.after": async ({ tool, sessionID }) => {
8
- if (!tool?.startsWith("work_context_") || !sessionID) return;
8
+ if (!tool?.startsWith("work_context_") || tool === "work_context_doctor_delivery" || !sessionID) return;
9
9
  await updateSessionTitle(client, worktree || directory, directory, sessionID);
10
10
  },
11
11
  event: async ({ event }) => {
package/src/core.js CHANGED
@@ -10,6 +10,7 @@ import { normalizeStageId, normalizeWorkspaceId } from "./identifiers.js";
10
10
  import { isDependencySatisfied } from "./stage-status.js";
11
11
  import { CandidateStore } from "./candidates.js";
12
12
  import { DeliveryStore } from "./delivery.js";
13
+ import { doctorDelivery as runDeliveryDoctor } from "./delivery-doctor.js";
13
14
  import { applyExecutionPatch, assertExecutionSize, executionState, normalizeExecutionState } from "./stage-execution.js";
14
15
  import { CAPABILITY_CLASSIFICATIONS, CAPABILITY_DEPTHS, CAPABILITY_MAPPINGS_FILE, CAPABILITY_PROFILES, capabilityProfileMode, capabilityRecommendations, readCapabilityMappings, validateCapabilityMappings } from "./capability-profiles.js";
15
16
 
@@ -108,6 +109,10 @@ export class WorkContext {
108
109
  return new WorkContext(new FileStorage(root, { ...loadConfig(root), ...(options.config || {}) }), { ...options, initialize: false });
109
110
  }
110
111
 
112
+ static doctorDelivery(projectRoot, options = {}) {
113
+ return { ok: true, data: runDeliveryDoctor(projectRoot, options) };
114
+ }
115
+
111
116
  writeEvents(events) {
112
117
  this.storage.appendEvents(events);
113
118
  atomicWrite(path.join(this.storage.personalRoot, "SESSIONS.md"), renderSessions(reduceSessions(this.storage.readEvents())));
@@ -337,6 +342,14 @@ export class WorkContext {
337
342
 
338
343
  readDelivery(workspace, options = {}) { return { ok: true, data: this.deliveries().readContext(workspace, options) }; }
339
344
 
345
+ explainDelivery(workspace, from, to, findings = []) {
346
+ return { ok: true, data: this.deliveries().explain(workspace, { from, to, findings }) };
347
+ }
348
+
349
+ doctorDelivery(options = {}) {
350
+ return { ok: true, data: runDeliveryDoctor(this.storage.projectRoot, options) };
351
+ }
352
+
340
353
  markDelivery(workspace, environment, commit, confirmation) {
341
354
  this.storage.assertSafeRoots();
342
355
  return withLock(this.storage.lockPath("candidate-git"), () => this.transact("delivery-mark", () =>
@@ -971,7 +984,7 @@ export class WorkContext {
971
984
  help(command = "") {
972
985
  return this.result({
973
986
  command,
974
- syntax: "/wc [create|list|workspace list|workspace rename|workspace mode|candidate create|candidate capture|candidate preview|candidate show|candidate list|candidate ready|candidate commit|candidate discard|delivery read|delivery mark|profiles show|profiles setup|profiles reset|workspace finish|workspace reopen|resume|stage add|stage profiles|stage profiles refresh|stage reopen|stage restore|stage rename|stage update|stage update-prompt|stage update-result|stage execution read|stage execution replace|stage execution update|stage force-close|stage archive|stage handoff|stage abandon|stage finish|link-issue|unlink-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]",
987
+ syntax: "/wc [create|list|workspace list|workspace rename|workspace mode|candidate create|candidate capture|candidate preview|candidate show|candidate list|candidate ready|candidate commit|candidate discard|delivery read|delivery explain|delivery doctor|delivery mark|profiles show|profiles setup|profiles reset|workspace finish|workspace reopen|resume|stage add|stage profiles|stage profiles refresh|stage reopen|stage restore|stage rename|stage update|stage update-prompt|stage update-result|stage execution read|stage execution replace|stage execution update|stage force-close|stage archive|stage handoff|stage abandon|stage finish|link-issue|unlink-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]",
975
988
  note: "execution recommendations combine a vendor-neutral capability with light, standard, or deep depth; Planning agents infer missing values before stage creation, ordinary refresh updates missing/inferred classifications while preserving explicit assignments, and local depth mappings resolve only an advisory model label; profiles setup gathers mode and mappings through questions, off mode suppresses presentation and resolution, and no profile operation changes a model, agent, reviewer, or session; delivery context is workspace-level local operational state; exact Git range inspection runs only for explicit immutable hashes; stage execution state is a bounded stage-local operational checkpoint; associated startup sessions receive the shared-worktree candidate policy; stage finish requires an explicit user lifecycle request unless Planning contains AUTO_STAGE_FINISH: allowed; recovery operations preserve lifecycle history.",
976
989
  }, []);
977
990
  }
@@ -0,0 +1,108 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { ERROR_CODES, fail } from "./errors.js";
3
+ import { validateDeliverySlices } from "./delivery-slices.js";
4
+
5
+ export const DELIVERY_EXPLAIN_CONTRACT_VERSION = "1.0";
6
+ export const DELIVERY_EXPLAIN_OPERATION = "delivery.explain";
7
+ export const DELIVERY_STABLE_ID_PATTERN = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/;
8
+
9
+ export const DELIVERY_DIAGNOSTIC_LIMITS = Object.freeze({
10
+ findings: 200,
11
+ affected_paths_per_finding: 100,
12
+ remediation_ids_per_finding: 20,
13
+ stable_id_characters: 128,
14
+ input_path_bytes: 4096,
15
+ commit_subject_bytes: 200,
16
+ secret_path_patterns: 100,
17
+ secret_path_pattern_characters: 256,
18
+ findings_bytes: 1024 * 1024,
19
+ diagnostic_bytes: 4 * 1024 * 1024,
20
+ commits: 500,
21
+ paths: 500,
22
+ provenance_commits_per_path: 50,
23
+ git_output_bytes: 4 * 1024 * 1024,
24
+ });
25
+
26
+ const findingKeys = ["id", "severity", "summary", "affected_paths", "remediation_ids", "recommendation"];
27
+ const severities = new Set(["info", "warning", "error"]);
28
+ const plainObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
29
+
30
+ export function validateDeliveryStableId(value, label = "Stable ID") {
31
+ if (typeof value !== "string" || value.length > DELIVERY_DIAGNOSTIC_LIMITS.stable_id_characters || !DELIVERY_STABLE_ID_PATTERN.test(value)) {
32
+ fail(ERROR_CODES.DELIVERY_INVALID_FINDINGS, `${label} is invalid`);
33
+ }
34
+ return value;
35
+ }
36
+
37
+ const validatePath = (value) => {
38
+ if (typeof value !== "string" || !value || value.includes("\0") || Buffer.byteLength(value, "utf8") > DELIVERY_DIAGNOSTIC_LIMITS.input_path_bytes) {
39
+ fail(ERROR_CODES.DELIVERY_INVALID_FINDINGS, "Finding paths must be non-empty bounded strings");
40
+ }
41
+ return value;
42
+ };
43
+
44
+ const validateUniqueList = (value, limit, itemValidator, label) => {
45
+ if (!Array.isArray(value) || value.length > limit) fail(ERROR_CODES.DELIVERY_INVALID_FINDINGS, `${label} exceeds its supported limit`);
46
+ const normalized = value.map(itemValidator);
47
+ if (new Set(normalized).size !== normalized.length) fail(ERROR_CODES.DELIVERY_INVALID_FINDINGS, `${label} must not contain duplicates`);
48
+ return normalized;
49
+ };
50
+
51
+ export function validateDeliveryFindings(findings = []) {
52
+ let bytes;
53
+ try { bytes = Buffer.byteLength(JSON.stringify(findings), "utf8"); }
54
+ catch { fail(ERROR_CODES.DELIVERY_INVALID_FINDINGS, "Findings must be JSON-serializable"); }
55
+ if (bytes > DELIVERY_DIAGNOSTIC_LIMITS.findings_bytes) fail(ERROR_CODES.DELIVERY_INVALID_FINDINGS, "Findings exceed the supported 1 MiB limit");
56
+ if (!Array.isArray(findings) || findings.length > DELIVERY_DIAGNOSTIC_LIMITS.findings) fail(ERROR_CODES.DELIVERY_INVALID_FINDINGS, "Findings must be a bounded array");
57
+ const ids = new Set();
58
+ const normalized = findings.map((finding) => {
59
+ if (!plainObject(finding) || !Object.keys(finding).every((key) => findingKeys.includes(key))) fail(ERROR_CODES.DELIVERY_INVALID_FINDINGS, "Finding contains unsupported fields");
60
+ const id = validateDeliveryStableId(finding.id, "Finding ID");
61
+ if (ids.has(id)) fail(ERROR_CODES.DELIVERY_INVALID_FINDINGS, "Finding IDs must be unique", { id });
62
+ ids.add(id);
63
+ if (!severities.has(finding.severity)) fail(ERROR_CODES.DELIVERY_INVALID_FINDINGS, "Finding severity must be info, warning, or error", { id });
64
+ if (typeof finding.summary !== "string" || !finding.summary.trim()) fail(ERROR_CODES.DELIVERY_INVALID_FINDINGS, "Finding summary must be a non-empty string", { id });
65
+ if (finding.recommendation !== undefined && (typeof finding.recommendation !== "string" || !finding.recommendation.trim())) {
66
+ fail(ERROR_CODES.DELIVERY_INVALID_FINDINGS, "Finding recommendation must be a non-empty string", { id });
67
+ }
68
+ return {
69
+ id,
70
+ severity: finding.severity,
71
+ summary: finding.summary.trim(),
72
+ affected_paths: validateUniqueList(finding.affected_paths ?? [], DELIVERY_DIAGNOSTIC_LIMITS.affected_paths_per_finding, validatePath, "Affected paths"),
73
+ remediation_ids: validateUniqueList(finding.remediation_ids ?? [], DELIVERY_DIAGNOSTIC_LIMITS.remediation_ids_per_finding, (value) => validateDeliveryStableId(value, "Remediation ID"), "Remediation IDs"),
74
+ ...(finding.recommendation === undefined ? {} : { recommendation: finding.recommendation.trim() }),
75
+ };
76
+ });
77
+ return normalized;
78
+ }
79
+
80
+ export function deliveryDiagnosticComplete(limits) {
81
+ if (!plainObject(limits)) return false;
82
+ const truncated = (value, key = "") => {
83
+ if ((key === "truncated" || key.endsWith("_truncated")) && value === true) return true;
84
+ return plainObject(value) && Object.entries(value).some(([childKey, child]) => truncated(child, childKey));
85
+ };
86
+ return !Object.entries(limits).some(([key, value]) => truncated(value, key));
87
+ }
88
+
89
+ export function validateDeliveryExplainEnvelope(envelope) {
90
+ const required = ["contract_version", "operation", "immutable_range", "limits", "summary", "paths", "findings", "candidate_traceability", "candidate_slice", "redactions", "complete"];
91
+ if (!plainObject(envelope) || required.some((key) => !(key in envelope))
92
+ || envelope.contract_version !== DELIVERY_EXPLAIN_CONTRACT_VERSION || envelope.operation !== DELIVERY_EXPLAIN_OPERATION
93
+ || typeof envelope.complete !== "boolean" || !plainObject(envelope.immutable_range) || !plainObject(envelope.limits)
94
+ || !plainObject(envelope.summary) || !Array.isArray(envelope.paths) || !Array.isArray(envelope.findings)
95
+ || !plainObject(envelope.candidate_traceability) || !Array.isArray(envelope.candidate_slice) || !plainObject(envelope.redactions)) {
96
+ fail(ERROR_CODES.INVALID_ARGUMENT, "Invalid delivery diagnostic output envelope");
97
+ }
98
+ if (!envelope.complete && envelope.findings.some((finding) => plainObject(finding) && "recommendation" in finding)) {
99
+ fail(ERROR_CODES.INVALID_ARGUMENT, "Incomplete diagnostics cannot contain recommendations");
100
+ }
101
+ if (!envelope.complete && envelope.candidate_slice.length) fail(ERROR_CODES.INVALID_ARGUMENT, "Incomplete diagnostics cannot contain candidate-slice recommendations");
102
+ validateDeliverySlices(envelope.candidate_slice);
103
+ let bytes;
104
+ try { bytes = Buffer.byteLength(JSON.stringify(envelope), "utf8"); }
105
+ catch { fail(ERROR_CODES.INVALID_ARGUMENT, "Delivery diagnostic output must be JSON-serializable"); }
106
+ if (bytes > DELIVERY_DIAGNOSTIC_LIMITS.diagnostic_bytes) fail(ERROR_CODES.DELIVERY_DIAGNOSTIC_TOO_LARGE, "Delivery diagnostic output exceeds the supported 4 MiB limit");
107
+ return envelope;
108
+ }
@@ -0,0 +1,304 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { Buffer } from "node:buffer";
4
+ import { ERROR_CODES, fail } from "./errors.js";
5
+ import {
6
+ WORK_CONTEXT_PROTOCOL,
7
+ WORK_CONTEXT_PROTOCOL_DESCRIPTOR_HASH,
8
+ parseWorkContextProtocolMarker,
9
+ } from "./protocol.js";
10
+
11
+ export const DELIVERY_DOCTOR_CONTRACT_VERSION = "1.0";
12
+ export const DELIVERY_DOCTOR_OPERATION = "delivery.doctor";
13
+ export const DELIVERY_DOCTOR_EVIDENCE_KINDS = Object.freeze(["self_reported", "host_attested", "unavailable"]);
14
+
15
+ const PACKAGE_NAME = "opencode-work-context";
16
+ const MAX_FILE_BYTES = 1024 * 1024;
17
+ const MAX_VALUE_CHARACTERS = 256;
18
+ const SAFE_VERSION_PATTERN = /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
19
+ const relativeFiles = Object.freeze({
20
+ command: ".opencode/commands/wc.md",
21
+ opencode: ".opencode/opencode.json",
22
+ tui: ".opencode/tui.json",
23
+ rootManifest: "package.json",
24
+ opencodeManifest: ".opencode/package.json",
25
+ rootInstalled: `node_modules/${PACKAGE_NAME}/package.json`,
26
+ opencodeInstalled: `.opencode/node_modules/${PACKAGE_NAME}/package.json`,
27
+ localLoader: ".opencode/plugins/work-context.js",
28
+ });
29
+
30
+ const cleanValue = (value) => typeof value === "string"
31
+ && value.length > 0
32
+ && value.length <= MAX_VALUE_CHARACTERS
33
+ && /^[A-Za-z0-9._+-]+$/.test(value)
34
+ ? value
35
+ : null;
36
+ const cleanVersion = (value) => typeof value === "string" && value.length <= 128 && SAFE_VERSION_PATTERN.test(value) ? value : null;
37
+
38
+ const safeFile = (projectRoot, relative, parseJson = false) => {
39
+ const file = path.join(projectRoot, ...relative.split("/"));
40
+ let current = projectRoot;
41
+ try {
42
+ for (const part of relative.split("/")) {
43
+ current = path.join(current, part);
44
+ const stat = fs.lstatSync(current);
45
+ if (stat.isSymbolicLink()) return { status: "unsafe", path: relative };
46
+ if (current !== file && !stat.isDirectory()) return { status: "unsafe", path: relative };
47
+ if (current === file && !stat.isFile()) return { status: "unsafe", path: relative };
48
+ }
49
+ const descriptor = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
50
+ let content;
51
+ try {
52
+ const opened = fs.fstatSync(descriptor);
53
+ if (!opened.isFile()) return { status: "unsafe", path: relative };
54
+ if (opened.size > MAX_FILE_BYTES) return { status: "oversized", path: relative };
55
+ content = fs.readFileSync(descriptor, "utf8");
56
+ const after = fs.lstatSync(file);
57
+ if (after.isSymbolicLink() || !after.isFile() || after.dev !== opened.dev || after.ino !== opened.ino) return { status: "unsafe", path: relative };
58
+ } finally {
59
+ fs.closeSync(descriptor);
60
+ }
61
+ if (!parseJson) return { status: "available", path: relative, content };
62
+ try {
63
+ const value = JSON.parse(content);
64
+ if (!value || typeof value !== "object" || Array.isArray(value)) return { status: "malformed", path: relative };
65
+ return { status: "available", path: relative, value };
66
+ } catch {
67
+ return { status: "malformed", path: relative };
68
+ }
69
+ } catch (error) {
70
+ if (error.code === "ENOENT") return { status: "missing", path: relative };
71
+ return { status: "unavailable", path: relative };
72
+ }
73
+ };
74
+
75
+ const packageSpec = (value) => {
76
+ if (typeof value !== "string") return null;
77
+ if (value === PACKAGE_NAME) return { package: PACKAGE_NAME, version: null };
78
+ if (!value.startsWith(`${PACKAGE_NAME}@`)) return null;
79
+ const version = cleanVersion(value.slice(PACKAGE_NAME.length + 1));
80
+ return version ? { package: PACKAGE_NAME, version } : null;
81
+ };
82
+
83
+ const dependencySpec = (value) => {
84
+ if (typeof value !== "string") return null;
85
+ const version = value.startsWith("=") ? value.slice(1) : value;
86
+ const normalized = cleanVersion(version);
87
+ return normalized ? { package: PACKAGE_NAME, version: normalized } : null;
88
+ };
89
+
90
+ const collectDeclarations = (projectRoot) => {
91
+ const observations = [];
92
+ for (const [source, relative] of [["opencode", relativeFiles.opencode], ["tui", relativeFiles.tui]]) {
93
+ const file = safeFile(projectRoot, relative, true);
94
+ if (file.status !== "available") {
95
+ observations.push({ source, path: relative, status: file.status });
96
+ continue;
97
+ }
98
+ const fields = source === "opencode" ? ["plugin", "plugins"] : ["plugin"];
99
+ let supported = true;
100
+ for (const field of fields) {
101
+ if (file.value[field] !== undefined && !Array.isArray(file.value[field])) supported = false;
102
+ for (const value of Array.isArray(file.value[field]) ? file.value[field] : []) {
103
+ const parsed = packageSpec(value);
104
+ if (parsed) observations.push({ source, path: relative, field, status: "declared", ...parsed, model: "managed" });
105
+ else if (typeof value === "string" && value.startsWith(PACKAGE_NAME)) observations.push({ source, path: relative, field, status: "malformed" });
106
+ }
107
+ }
108
+ if (!supported) observations.push({ source, path: relative, status: "unsupported" });
109
+ }
110
+ for (const [source, relative] of [["root_manifest", relativeFiles.rootManifest], ["opencode_manifest", relativeFiles.opencodeManifest]]) {
111
+ const file = safeFile(projectRoot, relative, true);
112
+ if (file.status !== "available") {
113
+ observations.push({ source, path: relative, status: file.status });
114
+ continue;
115
+ }
116
+ for (const field of ["dependencies", "devDependencies"]) {
117
+ const container = file.value[field];
118
+ if (container !== undefined && (!container || typeof container !== "object" || Array.isArray(container))) {
119
+ observations.push({ source, path: relative, status: "unsupported" });
120
+ continue;
121
+ }
122
+ if (!Object.hasOwn(container || {}, PACKAGE_NAME)) continue;
123
+ const parsed = dependencySpec(container[PACKAGE_NAME]);
124
+ observations.push(parsed
125
+ ? { source, path: relative, field, status: "declared", ...parsed, model: "pinned_local" }
126
+ : { source, path: relative, field, status: "malformed" });
127
+ }
128
+ }
129
+ return observations;
130
+ };
131
+
132
+ const collectInstallations = (projectRoot) => [["root", relativeFiles.rootInstalled], ["opencode", relativeFiles.opencodeInstalled]].map(([source, relative]) => {
133
+ const file = safeFile(projectRoot, relative, true);
134
+ if (file.status !== "available") return { source, path: relative, status: file.status };
135
+ const name = file.value.name === PACKAGE_NAME ? PACKAGE_NAME : null;
136
+ const version = cleanVersion(file.value.version);
137
+ if (name !== PACKAGE_NAME || !version) return { source, path: relative, status: "malformed" };
138
+ return { source, path: relative, status: "installed", package: name, version };
139
+ });
140
+
141
+ const normalizeRuntimeEvidence = (evidence, kind) => {
142
+ if (!evidence || evidence.evidence_kind === "unavailable") return {
143
+ evidence_kind: "unavailable",
144
+ reason: kind === "host_attested" ? "authoritative runtime evidence is not provided by the host" : "loaded-plugin self-report is unavailable",
145
+ };
146
+ const packageName = evidence.package_name === PACKAGE_NAME ? PACKAGE_NAME : null;
147
+ const packageVersion = cleanVersion(evidence.package_version);
148
+ const origin = ["project_local", "managed_cache", "package_source", "unknown"].includes(evidence.module_origin) ? evidence.module_origin : "unknown";
149
+ const protocol = evidence.protocol;
150
+ if (packageName !== PACKAGE_NAME || !packageVersion || !protocol
151
+ || !Number.isInteger(protocol.schema) || !Number.isInteger(protocol.major) || !Number.isInteger(protocol.minor)
152
+ || typeof protocol.descriptor_hash !== "string" || !/^[a-f0-9]{64}$/.test(protocol.descriptor_hash)) {
153
+ return { evidence_kind: "unavailable", reason: `${kind} runtime evidence is malformed` };
154
+ }
155
+ return {
156
+ evidence_kind: kind,
157
+ package_name: packageName,
158
+ package_version: packageVersion,
159
+ module_origin: origin,
160
+ protocol: {
161
+ schema: protocol.schema,
162
+ major: protocol.major,
163
+ minor: protocol.minor,
164
+ descriptor_hash: protocol.descriptor_hash,
165
+ },
166
+ };
167
+ };
168
+
169
+ const repairFor = (model, version, commandChanged) => {
170
+ const target = cleanVersion(version);
171
+ if (!target || !["managed", "pinned_local"].includes(model)) return {
172
+ model: "unknown",
173
+ steps: ["Resolve the installation model and exact loaded package version, then rerun delivery doctor."],
174
+ restart_required: false,
175
+ };
176
+ if (model === "managed") return {
177
+ model: "managed",
178
+ steps: [
179
+ `opencode plugin ${PACKAGE_NAME}@${target} --force`,
180
+ ...(commandChanged ? [`npx --yes ${PACKAGE_NAME}@${target} activate --force`] : []),
181
+ "Restart OpenCode.",
182
+ ],
183
+ restart_required: true,
184
+ };
185
+ return {
186
+ model: "pinned_local",
187
+ steps: [`npx --yes ${PACKAGE_NAME}@${target} init --force`, "Restart OpenCode."],
188
+ restart_required: true,
189
+ };
190
+ };
191
+
192
+ const addFinding = (findings, id, severity, summary, repair) => {
193
+ if (!findings.some((finding) => finding.id === id)) findings.push({ id, severity, summary, ...(repair ? { repair } : {}) });
194
+ };
195
+
196
+ export function validateDeliveryDoctorEnvelope(envelope) {
197
+ if (!envelope || typeof envelope !== "object" || Array.isArray(envelope)
198
+ || envelope.contract_version !== DELIVERY_DOCTOR_CONTRACT_VERSION
199
+ || envelope.operation !== DELIVERY_DOCTOR_OPERATION
200
+ || !envelope.protocol || typeof envelope.protocol !== "object" || Array.isArray(envelope.protocol)
201
+ || !envelope.evidence || typeof envelope.evidence !== "object" || Array.isArray(envelope.evidence)
202
+ || !DELIVERY_DOCTOR_EVIDENCE_KINDS.includes(envelope.evidence.loaded_plugin?.evidence_kind)
203
+ || !DELIVERY_DOCTOR_EVIDENCE_KINDS.includes(envelope.evidence.host_attestation?.evidence_kind)
204
+ || !Array.isArray(envelope.evidence.declarations) || !Array.isArray(envelope.evidence.installations)
205
+ || !Array.isArray(envelope.findings)
206
+ || envelope.findings.length > 100) fail(ERROR_CODES.INVALID_ARGUMENT, "Invalid delivery doctor output envelope");
207
+ for (const finding of envelope.findings) {
208
+ if (!finding || typeof finding !== "object" || Array.isArray(finding)
209
+ || typeof finding.id !== "string" || !/^[a-z][a-z0-9_.-]*$/.test(finding.id)
210
+ || !["info", "warning", "error"].includes(finding.severity)
211
+ || typeof finding.summary !== "string" || !finding.summary) fail(ERROR_CODES.INVALID_ARGUMENT, "Invalid delivery doctor finding");
212
+ }
213
+ const serialized = JSON.stringify(envelope);
214
+ if (Buffer.byteLength(serialized, "utf8") > MAX_FILE_BYTES) fail(ERROR_CODES.DELIVERY_DIAGNOSTIC_TOO_LARGE, "Delivery doctor output exceeds the supported 1 MiB limit");
215
+ return envelope;
216
+ }
217
+
218
+ export function doctorDelivery(projectRoot, options = {}) {
219
+ projectRoot = fs.realpathSync(path.resolve(projectRoot));
220
+ const loaded = normalizeRuntimeEvidence(options.loadedPlugin, "self_reported");
221
+ const host = normalizeRuntimeEvidence(options.hostAttestation, "host_attested");
222
+ const commandFile = safeFile(projectRoot, relativeFiles.command);
223
+ const marker = commandFile.status === "available" ? parseWorkContextProtocolMarker(commandFile.content) : null;
224
+ const command = {
225
+ path: relativeFiles.command,
226
+ status: commandFile.status === "available" ? (marker ? "available" : "malformed") : commandFile.status,
227
+ ...(marker ? { marker } : {}),
228
+ };
229
+ const declarations = collectDeclarations(projectRoot);
230
+ const installations = collectInstallations(projectRoot);
231
+ const declared = declarations.filter((item) => item.status === "declared");
232
+ const installed = installations.filter((item) => item.status === "installed");
233
+ const models = [...new Set(declared.map((item) => item.model))];
234
+ const model = models.length > 1 ? "conflict" : models[0] || (loaded.module_origin === "managed_cache" ? "managed" : "pinned_local");
235
+ const version = loaded.package_version;
236
+ const findings = [];
237
+
238
+ if (marker && loaded.evidence_kind === "self_reported" && marker.major !== loaded.protocol.major) {
239
+ fail(ERROR_CODES.DELIVERY_COMMAND_PROTOCOL_MISMATCH, "Generated command and loaded plugin use incompatible protocol majors", {
240
+ command_major: marker.major,
241
+ loaded_major: loaded.protocol.major,
242
+ });
243
+ }
244
+ if (command.status !== "available") addFinding(findings, `command.${command.status}`, "error", `Generated command protocol marker is ${command.status}.`, repairFor(model, version, true));
245
+ if (marker && loaded.evidence_kind === "self_reported") {
246
+ if (marker.minor !== loaded.protocol.minor) {
247
+ const direction = marker.minor < loaded.protocol.minor ? "generated command is older" : "loaded plugin is older";
248
+ addFinding(findings, "command.protocol_minor_drift", "warning", `Protocol minors differ: ${direction}.`, repairFor(model, version, true));
249
+ }
250
+ if (marker.schema !== loaded.protocol.schema) addFinding(findings, "command.schema_mismatch", "warning", "Generated command protocol schema differs from the loaded plugin.", repairFor(model, version, true));
251
+ if (marker.descriptor_hash !== `sha256:${loaded.protocol.descriptor_hash}`) addFinding(findings, "command.descriptor_hash_mismatch", "warning", "Generated command descriptor hash differs from the loaded plugin.", repairFor(model, version, true));
252
+ }
253
+ if (loaded.evidence_kind === "unavailable") {
254
+ addFinding(findings, "runtime.protocol_major_unknown", "error", "Loaded-plugin protocol major is unknown, so compatibility cannot be established.", repairFor(model, version, false));
255
+ addFinding(findings, "runtime.self_report_unavailable", "warning", "Loaded-plugin self-report is unavailable.", repairFor(model, version, false));
256
+ } else {
257
+ if (loaded.protocol.schema !== WORK_CONTEXT_PROTOCOL.schema) addFinding(findings, "runtime.self_report_schema_mismatch", "warning", "Loaded-plugin self-reported protocol schema differs from this package contract.", repairFor(model, version, false));
258
+ if (loaded.protocol.descriptor_hash !== WORK_CONTEXT_PROTOCOL_DESCRIPTOR_HASH) addFinding(findings, "runtime.self_report_hash_mismatch", "warning", "Loaded-plugin self-reported descriptor hash differs from this package contract.", repairFor(model, version, false));
259
+ }
260
+ if (host.evidence_kind === "unavailable") addFinding(findings, "runtime.host_attestation_unavailable", "info", "The host does not provide authoritative loaded-plugin attestation.");
261
+ if (host.evidence_kind === "host_attested" && loaded.evidence_kind === "self_reported") {
262
+ if (host.protocol.major !== loaded.protocol.major) addFinding(findings, "runtime.host_protocol_mismatch", "error", "Host-attested and self-reported protocol majors differ.", repairFor(model, version, false));
263
+ if (host.protocol.minor !== loaded.protocol.minor) addFinding(findings, "runtime.host_protocol_minor_mismatch", "warning", "Host-attested and self-reported protocol minors differ.", repairFor(model, version, false));
264
+ if (host.protocol.schema !== loaded.protocol.schema) addFinding(findings, "runtime.host_schema_mismatch", "warning", "Host-attested and self-reported protocol schemas differ.", repairFor(model, version, false));
265
+ if (host.protocol.descriptor_hash !== loaded.protocol.descriptor_hash) addFinding(findings, "runtime.host_hash_mismatch", "warning", "Host-attested and self-reported descriptor hashes differ.", repairFor(model, version, false));
266
+ if (host.package_version !== loaded.package_version) addFinding(findings, "runtime.host_version_mismatch", "warning", "Host-attested and self-reported package versions differ.", repairFor(model, version, false));
267
+ if (host.module_origin !== "unknown" && host.module_origin !== loaded.module_origin) addFinding(findings, "runtime.host_origin_mismatch", "warning", "Host-attested and self-reported module origins differ.", repairFor(model, version, false));
268
+ }
269
+ for (const observation of declarations) {
270
+ if (!["missing", "available", "declared"].includes(observation.status)) addFinding(findings, `declaration.${observation.source}.${observation.status}`, "warning", `${observation.path} declaration evidence is ${observation.status}.`, repairFor(model, version, false));
271
+ }
272
+ for (const observation of installations) {
273
+ if (!["missing", "installed"].includes(observation.status)) addFinding(findings, `installation.${observation.source}.${observation.status}`, "warning", `${observation.path} installation evidence is ${observation.status}.`, repairFor(model, version, false));
274
+ }
275
+ if (!declared.length) addFinding(findings, "declaration.missing", "warning", "No supported project declaration for opencode-work-context was found.", repairFor(model, version, false));
276
+ if (declared.some((item) => item.version === null)) addFinding(findings, "declaration.version_unpinned", "warning", "A managed package declaration does not identify an exact version.", repairFor(model, version, false));
277
+ const declarationKeys = declared.map((item) => `${item.path}:${item.field}:${item.version || "unversioned"}`);
278
+ if (new Set(declarationKeys).size !== declarationKeys.length) addFinding(findings, "declaration.duplicate", "warning", "A project configuration contains duplicate opencode-work-context declarations.", repairFor(model, version, false));
279
+ if (models.length > 1) addFinding(findings, "declaration.installation_model_conflict", "error", "Managed and pinned-local declarations are both present.", repairFor(model, version, false));
280
+ if (version && declared.some((item) => item.version && item.version !== version)) addFinding(findings, "declaration.version_mismatch", "warning", "A declared package version differs from the loaded package version.", repairFor(model, version, false));
281
+ if (model === "pinned_local" && !installed.length) addFinding(findings, "installation.missing", "warning", "No safely discoverable pinned-local package manifest was found.", repairFor(model, version, false));
282
+ if (version && installed.some((item) => item.version !== version)) addFinding(findings, "installation.version_mismatch", "warning", "An installed package version differs from the loaded package version.", repairFor(model, version, false));
283
+ const localLoader = safeFile(projectRoot, relativeFiles.localLoader);
284
+ if (model === "pinned_local" && localLoader.status !== "available") addFinding(findings, "origin.local_loader_missing", "warning", "Pinned-local declaration exists without a regular package-managed loader.", repairFor(model, version, false));
285
+ if (loaded.evidence_kind === "self_reported"
286
+ && ((model === "managed" && loaded.module_origin === "project_local") || (model === "pinned_local" && loaded.module_origin === "managed_cache"))) {
287
+ addFinding(findings, "origin.installation_model_mismatch", "warning", "Loaded-plugin origin differs from the declared installation model.", repairFor(model, version, false));
288
+ }
289
+
290
+ findings.sort((left, right) => left.id < right.id ? -1 : left.id > right.id ? 1 : 0);
291
+ return validateDeliveryDoctorEnvelope({
292
+ contract_version: DELIVERY_DOCTOR_CONTRACT_VERSION,
293
+ operation: DELIVERY_DOCTOR_OPERATION,
294
+ protocol: {
295
+ schema: WORK_CONTEXT_PROTOCOL.schema,
296
+ major: WORK_CONTEXT_PROTOCOL.major,
297
+ minor: WORK_CONTEXT_PROTOCOL.minor,
298
+ descriptor_hash: WORK_CONTEXT_PROTOCOL_DESCRIPTOR_HASH,
299
+ },
300
+ evidence: { command, declarations, installations, loaded_plugin: loaded, host_attestation: host },
301
+ findings,
302
+ complete: true,
303
+ });
304
+ }