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/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.1",
4
+ "version": "0.10.3",
5
5
  "description": "Filesystem work-context core and OpenCode adapter",
6
6
  "license": "MIT",
7
7
  "author": {
@@ -49,6 +49,11 @@ const deliverySummaryText = (workspace) => {
49
49
  const pending = delivery.environments.reduce((total, environment) => total + environment.pending, 0);
50
50
  return `Delivery · ${delivery.environments.length} environments · ${pending} tracked pending`;
51
51
  };
52
+ const workspaceSummaryText = (workspace, attention) => [
53
+ attention && `Attention · ${attention}`,
54
+ candidateSummaryText(workspace),
55
+ deliverySummaryText(workspace),
56
+ ].filter(Boolean).join(" · ");
52
57
  const stageCandidateText = (stage) => {
53
58
  const projection = stage.candidates;
54
59
  if (!projection || !(projection.draft || projection.ready)) return null;
@@ -78,17 +83,16 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention,
78
83
  ];
79
84
  const attentionSnapshot = visibleAttentionSnapshot(attention, result.data.workspace.id, result.data.stages);
80
85
  const workspaceAttention = attentionSummaryText(attentionSnapshot.workspace, { alwaysCount: true });
86
+ const workspaceSummary = workspaceSummaryText(result.data.workspace, workspaceAttention);
81
87
  return [
82
88
  runtime.jsx("box", {
83
89
  marginBottom: 1,
84
90
  flexDirection: "column",
85
- children: [
86
- runtime.jsx("text", { wrapMode: "word", children: runtime.jsx("b", { children: result.data.workspace.title }) }),
87
- runtime.jsx("text", { fg: theme?.current?.textMuted, children: `Workflow · ${result.data.workspace.mode || "standard"}` }),
88
- workspaceAttention && runtime.jsx("text", { children: ["Attention · ", runtime.jsx("b", { children: workspaceAttention })] }),
89
- candidateSummaryText(result.data.workspace) && runtime.jsx("text", { fg: theme?.current?.textMuted, children: candidateSummaryText(result.data.workspace) }),
90
- deliverySummaryText(result.data.workspace) && runtime.jsx("text", { fg: theme?.current?.textMuted, children: deliverySummaryText(result.data.workspace) }),
91
- ].filter(Boolean),
91
+ children: [
92
+ runtime.jsx("text", { wrapMode: "word", children: runtime.jsx("b", { children: result.data.workspace.title }) }),
93
+ runtime.jsx("text", { fg: theme?.current?.textMuted, children: `Workflow · ${result.data.workspace.mode || "standard"}` }),
94
+ workspaceSummary && runtime.jsx("text", { wrapMode: "word", fg: theme?.current?.textMuted, children: workspaceSummary }),
95
+ ].filter(Boolean),
92
96
  }),
93
97
  runtime.jsx("box", {
94
98
  flexDirection: "row",
@@ -114,7 +118,7 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention,
114
118
  if (event?.button != null && event.button !== 0) return;
115
119
  return onStageSelect?.(stage);
116
120
  };
117
- const titleRow = runtime.jsx("box", {
121
+ const stageRow = runtime.jsx("box", {
118
122
  flexDirection: "row",
119
123
  onMouseDown,
120
124
  children: [
@@ -125,19 +129,18 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention,
125
129
  children: working ? activityFrame() : attentionSignal ? runtime.jsx("b", { children: attentionSignal }) : " ",
126
130
  }),
127
131
  runtime.jsx("text", { flexShrink: 0, marginRight: 1, fg: current ? theme?.current?.warning : theme?.current?.textMuted, children: statusMarker(stage.status) }),
128
- runtime.jsx("text", { flexGrow: 1, flexShrink: 1, wrapMode: "word", fg: current ? theme?.current?.warning : theme?.current?.text, children: `${stage.id}. ${stage.title}` }),
129
- ],
130
- });
131
- const metadataRow = metadata && runtime.jsx("box", {
132
- flexDirection: "row",
133
- onMouseDown,
134
- children: [
135
- runtime.jsx("text", { flexShrink: 0, marginRight: 1, children: " " }),
136
- runtime.jsx("text", { flexShrink: 0, marginRight: 1, children: " " }),
137
- runtime.jsx("text", { flexGrow: 1, flexShrink: 1, wrapMode: "word", fg: theme?.current?.textMuted, children: metadata }),
132
+ runtime.jsx("box", {
133
+ flexGrow: 1,
134
+ flexShrink: 1,
135
+ flexDirection: "column",
136
+ children: [
137
+ runtime.jsx("text", { wrapMode: "word", fg: current ? theme?.current?.warning : theme?.current?.text, children: `${stage.id}. ${stage.title}` }),
138
+ metadata && runtime.jsx("text", { wrapMode: "word", fg: theme?.current?.textMuted, children: metadata }),
139
+ ].filter(Boolean),
140
+ }),
138
141
  ],
139
142
  });
140
- return [titleRow, metadataRow].filter(Boolean);
143
+ return stageRow;
141
144
  }),
142
145
  ];
143
146
  };
@@ -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
+ }