@ran-sh/dsh-crew 0.3.6 → 0.3.8

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.
Files changed (85) hide show
  1. package/.claude-plugin/plugin.json +8 -8
  2. package/.mcp.json +8 -8
  3. package/LICENSE +21 -21
  4. package/README.de.md +359 -359
  5. package/README.es.md +359 -359
  6. package/README.fr.md +359 -359
  7. package/README.hi.md +359 -359
  8. package/README.id.md +359 -359
  9. package/README.ja.md +359 -359
  10. package/README.ko.md +359 -359
  11. package/README.md +94 -180
  12. package/README.pt.md +359 -359
  13. package/README.ru.md +359 -359
  14. package/README.th.md +359 -359
  15. package/README.tr.md +359 -359
  16. package/README.vi.md +359 -359
  17. package/README.zh-TW.md +359 -359
  18. package/README.zh.md +94 -180
  19. package/agents/ds-flash.md +26 -26
  20. package/agents/ds-pro.md +32 -32
  21. package/agents/ds-reviewer.md +23 -23
  22. package/agents/ds-worker.md +22 -22
  23. package/codex/agents/ds-flash.toml +30 -30
  24. package/codex/agents/ds-pro.toml +31 -31
  25. package/codex/agents/ds-reviewer.toml +28 -28
  26. package/codex/agents/ds-worker.toml +28 -28
  27. package/codex/prompts/dsh-config.md +3 -3
  28. package/codex/prompts/dsh-status.md +1 -1
  29. package/commands/config.md +11 -11
  30. package/commands/off.md +5 -5
  31. package/commands/on.md +5 -5
  32. package/commands/status.md +5 -5
  33. package/cordis.patch.yml +4 -4
  34. package/lib/client.js +1655 -974
  35. package/official-web-bridge/cordis.patch.yml +4 -0
  36. package/official-web-bridge/entry.mjs +1 -0
  37. package/official-web-bridge/lib/client.js +3446 -0
  38. package/official-web-bridge/package.json +26 -0
  39. package/package.json +133 -131
  40. package/scripts/build-client.mjs +32 -28
  41. package/scripts/live-crew-smoke.mjs +39 -39
  42. package/scripts/live-policy-matrix.mjs +177 -177
  43. package/scripts/policy-probe.mjs +101 -101
  44. package/scripts/setup.mjs +284 -284
  45. package/scripts/smoke-real.mjs +110 -110
  46. package/scripts/smoke.mjs +78 -78
  47. package/scripts/verify-installer-fix.mjs +26 -26
  48. package/scripts/verify-official-bridge-e2e.mjs +159 -0
  49. package/src/adaptive-routing.mjs +260 -260
  50. package/src/client/activation-summary.tsx +64 -64
  51. package/src/client/collapsible-sections.mjs +55 -0
  52. package/src/client/entry.tsx +236 -236
  53. package/src/client/index.tsx +1213 -1120
  54. package/src/config-readiness.mjs +59 -59
  55. package/src/delivery.mjs +205 -205
  56. package/src/dsh-cli-runtime.mjs +458 -447
  57. package/src/failure-classification.mjs +172 -172
  58. package/src/hub/entry.mjs +98 -98
  59. package/src/hub-client.mjs +132 -132
  60. package/src/hub-compatibility.mjs +49 -49
  61. package/src/i18n.mjs +19 -19
  62. package/src/install/cli.mjs +28 -28
  63. package/src/install/install-legacy.mjs +462 -462
  64. package/src/install/install.mjs +451 -451
  65. package/src/install/npx-lifecycle.mjs +1119 -1055
  66. package/src/install/official-web.mjs +132 -0
  67. package/src/mcp-runtime.mjs +257 -257
  68. package/src/model-catalog.mjs +173 -173
  69. package/src/model-routing.mjs +391 -391
  70. package/src/official-web-bridge.mjs +196 -0
  71. package/src/policy.mjs +197 -197
  72. package/src/readiness-matrix.mjs +169 -169
  73. package/src/runtime-controls.mjs +90 -90
  74. package/src/runtime-identity.mjs +108 -108
  75. package/src/server.mjs +477 -477
  76. package/src/status-shard.mjs +52 -52
  77. package/src/structured-error-code.mjs +38 -38
  78. package/src/vision-route.mjs +138 -138
  79. package/src/workflow-runtime.mjs +573 -573
  80. package/src/workflow.mjs +160 -160
  81. package/src/workspace-audit.mjs +231 -231
  82. package/src/workspace-isolation.mjs +365 -365
  83. package/statusline/statusline.sh +14 -14
  84. package/statusline/worker-segment.sh +35 -35
  85. package/worker.cordis.yml +77 -77
@@ -1,59 +1,59 @@
1
- import { buildReadinessMatrix, READINESS_REASON_CODES } from './readiness-matrix.mjs';
2
-
3
- function warningCodes(catalogBody) {
4
- const hints = Array.isArray(catalogBody?.health?.hints) ? catalogBody.health.hints : [];
5
- return [...new Set(hints
6
- .filter((hint) => hint?.level === 'warning' && typeof hint?.code === 'string' && hint.code.trim())
7
- .map((hint) => hint.code.trim()))];
8
- }
9
-
10
- /**
11
- * Enrich the conservative runtime matrix with evidence the config report has
12
- * already collected. This function performs no I/O and never reads provider
13
- * configuration, credentials, quotas, pricing, or hidden catalog expectations.
14
- */
15
- export function buildConfigReadinessMatrix({
16
- platform = process.platform,
17
- hubCompatibility = null,
18
- workerProviderMode = null,
19
- providerCatalogChecked = false,
20
- providerCatalogBody = null,
21
- } = {}) {
22
- const warnings = warningCodes(providerCatalogBody);
23
- const catalogResponseOk = !!providerCatalogBody
24
- && typeof providerCatalogBody === 'object'
25
- && providerCatalogBody.ok !== false;
26
- const catalogOk = providerCatalogChecked && catalogResponseOk && warnings.length === 0;
27
-
28
- const evidence = {};
29
- if (
30
- workerProviderMode !== 'deepseek-official'
31
- && hubCompatibility?.compatible === true
32
- && providerCatalogChecked
33
- && catalogResponseOk
34
- && warnings.length > 0
35
- ) {
36
- evidence.provider_catalog = {
37
- status: 'FAIL',
38
- reason_code: READINESS_REASON_CODES.PROVIDER_CATALOG_HEALTH_WARNING,
39
- evidence_source: 'harness-catalog',
40
- };
41
- }
42
-
43
- const matrix = buildReadinessMatrix({
44
- platform,
45
- hubCompatibility,
46
- workerProviderMode,
47
- providerCatalogChecked,
48
- providerCatalogOk: catalogOk,
49
- evidence,
50
- });
51
-
52
- if (warnings.length === 0) return matrix;
53
- return {
54
- ...matrix,
55
- rows: matrix.rows.map((row) => row.id === 'provider_catalog'
56
- ? { ...row, detail_codes: warnings }
57
- : row),
58
- };
59
- }
1
+ import { buildReadinessMatrix, READINESS_REASON_CODES } from './readiness-matrix.mjs';
2
+
3
+ function warningCodes(catalogBody) {
4
+ const hints = Array.isArray(catalogBody?.health?.hints) ? catalogBody.health.hints : [];
5
+ return [...new Set(hints
6
+ .filter((hint) => hint?.level === 'warning' && typeof hint?.code === 'string' && hint.code.trim())
7
+ .map((hint) => hint.code.trim()))];
8
+ }
9
+
10
+ /**
11
+ * Enrich the conservative runtime matrix with evidence the config report has
12
+ * already collected. This function performs no I/O and never reads provider
13
+ * configuration, credentials, quotas, pricing, or hidden catalog expectations.
14
+ */
15
+ export function buildConfigReadinessMatrix({
16
+ platform = process.platform,
17
+ hubCompatibility = null,
18
+ workerProviderMode = null,
19
+ providerCatalogChecked = false,
20
+ providerCatalogBody = null,
21
+ } = {}) {
22
+ const warnings = warningCodes(providerCatalogBody);
23
+ const catalogResponseOk = !!providerCatalogBody
24
+ && typeof providerCatalogBody === 'object'
25
+ && providerCatalogBody.ok !== false;
26
+ const catalogOk = providerCatalogChecked && catalogResponseOk && warnings.length === 0;
27
+
28
+ const evidence = {};
29
+ if (
30
+ workerProviderMode !== 'deepseek-official'
31
+ && hubCompatibility?.compatible === true
32
+ && providerCatalogChecked
33
+ && catalogResponseOk
34
+ && warnings.length > 0
35
+ ) {
36
+ evidence.provider_catalog = {
37
+ status: 'FAIL',
38
+ reason_code: READINESS_REASON_CODES.PROVIDER_CATALOG_HEALTH_WARNING,
39
+ evidence_source: 'harness-catalog',
40
+ };
41
+ }
42
+
43
+ const matrix = buildReadinessMatrix({
44
+ platform,
45
+ hubCompatibility,
46
+ workerProviderMode,
47
+ providerCatalogChecked,
48
+ providerCatalogOk: catalogOk,
49
+ evidence,
50
+ });
51
+
52
+ if (warnings.length === 0) return matrix;
53
+ return {
54
+ ...matrix,
55
+ rows: matrix.rows.map((row) => row.id === 'provider_catalog'
56
+ ? { ...row, detail_codes: warnings }
57
+ : row),
58
+ };
59
+ }
package/src/delivery.mjs CHANGED
@@ -1,205 +1,205 @@
1
- // Auditable worker delivery: one shared Delivery Contract that every coding
2
- // worker (and the automatic Pro review) must fill out before its result is
3
- // accepted, plus pure helpers to prompt for, parse, validate and format it.
4
- //
5
- // Everything here is a pure function (no I/O, no worker runtime), so tests can
6
- // exercise the contract without starting DSH. Keeping the contract in one
7
- // shared builder guarantees the prompt-construction points (jobs.mjs, the hub,
8
- // the MCP shim) emit byte-identical instructions, and parse / validate let the
9
- // orchestrator separate *execution* status (running/done/failed) from
10
- // *delivery* completeness (did the worker actually report Diff/Tests/Risks?).
11
-
12
- export const DELIVERY_SECTIONS = ['Diff', 'Tests', 'Risks'];
13
- export const OPTIONAL_DELIVERY_SECTIONS = ['Unverified'];
14
- export const ALL_DELIVERY_SECTIONS = [...DELIVERY_SECTIONS, ...OPTIONAL_DELIVERY_SECTIONS];
15
-
16
- export const REVIEW_SECTIONS = ['Review Findings', 'Evidence', 'Risks', 'Verdict'];
17
-
18
- /** Any worker prompt that already carries a delivery report (added once). */
19
- export const DELIVERY_MARKER = '# Delivery report';
20
-
21
- const METADATA_KEYS = {
22
- Diff: 'diff',
23
- Tests: 'tests',
24
- Risks: 'risks',
25
- Unverified: 'unverified',
26
- 'Review Findings': 'findings',
27
- Evidence: 'evidence',
28
- Verdict: 'verdict',
29
- };
30
-
31
- /**
32
- * Prompts a coding worker (or, with isReview, an automatic Pro review) to end
33
- * its final message with the auditable delivery contract. This is the single
34
- * source of the contract text for every worker prompt.
35
- */
36
- export function buildDeliveryInstructions({ tier = 'pro', isReview = false } = {}) {
37
- if (isReview) {
38
- return `# Delivery report — automatic review (worker tier: pro)
39
- You are reviewing an implementation, and your review must be auditable. End your final message with these four sections — each on its own line as a '##' heading — followed by concise content:
40
-
41
- ## Review Findings
42
- One-line overall assessment of whether the implementation satisfies the task.
43
-
44
- ## Evidence
45
- What you inspected: file paths, diffs, commands you ran, and their results.
46
-
47
- ## Risks
48
- Concrete issues found: bugs, style problems, missing edge cases, security or secret-handling concerns.
49
-
50
- ## Verdict
51
- One line: approved / needs changes / rejected, plus the single most important reason.
52
-
53
- Do not edit files unless the user explicitly asks for fixes.`;
54
- }
55
- return `# Delivery report requirements (worker tier: ${String(tier).toUpperCase()})
56
- You are a coding worker, and your result must be auditable. End your final message with these three mandatory sections — each on its own line as a '##' heading — followed by concise, factual content:
57
-
58
- ## Diff
59
- Every file you changed or created (paths), with a one-line summary per file. If you changed nothing, write "no files changed".
60
-
61
- ## Tests
62
- Every entry must use exactly one of these auditable states:
63
- PASS — <command/check> — <result>
64
- FAIL — <command/check> — <reason>
65
- NOT RUN — <check> — <reason>
66
- "none" is not a valid Tests result.
67
-
68
- ## Risks
69
- Known risks and side effects: files touched outside the requested scope, assumptions you made, anything that could break, and any credentials or sensitive data you opened.
70
-
71
- ## Unverified
72
- (Optional — omit entirely if you verified everything.) Anything you could not verify: skipped builds, untested platforms, known gaps.
73
-
74
- The Diff, Tests and Risks sections are mandatory — do not skip them. Keep each section tight (a few lines is enough).
75
-
76
- ${tier === 'flash' ? `Implement only the delegated coding scope.
77
- Run direct validation needed for your change.
78
- Return the Delivery Report.
79
- Then stop and return control to the Main Agent.
80
-
81
- Do not autonomously start a new task or delegate further work.` : ''}`;
82
- }
83
-
84
- /**
85
- * Append the delivery instructions to a worker task prompt. Idempotent: a task
86
- * that already carries the delivery report (e.g. a review prompt, or a
87
- * re-dispatch) is returned untouched so instructions are never doubled.
88
- */
89
- export function appendDeliveryInstructions(task, { tier, isReview } = {}) {
90
- if (typeof task !== 'string') return task;
91
- if (task.includes(DELIVERY_MARKER)) return task;
92
- return `${task}\n\n${buildDeliveryInstructions({ tier, isReview })}`;
93
- }
94
-
95
- function parseTestsSection(value) {
96
- if (typeof value !== 'string' || value.trim() === '') return { valid: false, status: undefined };
97
- const statuses = [];
98
- for (const line of value.split(/\r?\n/).map((item) => item.trim()).filter(Boolean)) {
99
- const match = line.match(/^(?:[-*+]\s+)?(PASS|FAIL|NOT RUN)\s+—\s+\S.*?\s+—\s+\S.*$/);
100
- if (!match) return { valid: false, status: undefined };
101
- statuses.push(match[1]);
102
- }
103
- const status = statuses.includes('FAIL') ? 'FAIL' : statuses.includes('NOT RUN') ? 'NOT RUN' : statuses.includes('PASS') ? 'PASS' : undefined;
104
- return { valid: status !== undefined, status };
105
- }
106
-
107
- /**
108
- * Parse a worker's final message into the delivery report. Detects the report
109
- * format from the headings present: coding workers use Diff/Tests/Risks
110
- * (+ optional Unverified), automatic reviews use Review Findings/Evidence/
111
- * Risks/Verdict. `complete` means every *mandatory* section of the detected
112
- * format is present and non-empty.
113
- *
114
- * Returns { format, present, complete, missing, sections }.
115
- */
116
- export function parseDeliveryReport(text = '') {
117
- const normalized = typeof text === 'string' ? text : String(text ?? '');
118
- if (normalized.trim() === '') {
119
- return { format: null, present: [], complete: false, missing: [...DELIVERY_SECTIONS], sections: {} };
120
- }
121
- const canonical = new Map(ALL_DELIVERY_SECTIONS.concat(REVIEW_SECTIONS).map((name) => [name.toLowerCase(), name]));
122
- const heading = /^##\s+(Diff|Tests|Risks|Unverified|Review Findings|Evidence|Verdict)\s*$/gim;
123
- const marks = [];
124
- let m;
125
- while ((m = heading.exec(normalized)) !== null) marks.push({ index: m.index, name: canonical.get(m[1].toLowerCase()), len: m[0].length });
126
- if (marks.length === 0) {
127
- return { format: null, present: [], complete: false, missing: [...DELIVERY_SECTIONS], sections: {} };
128
- }
129
- const sections = {};
130
- for (let i = 0; i < marks.length; i++) {
131
- const start = marks[i].index + marks[i].len;
132
- const end = i + 1 < marks.length ? marks[i + 1].index : normalized.length;
133
- const body = normalized.slice(start, end).trim();
134
- const name = marks[i].name;
135
- sections[name] = sections[name] === undefined ? body : `${sections[name]}\n\n${body}`;
136
- }
137
- const isReview = REVIEW_SECTIONS.some((s) => s !== 'Risks' && sections[s] !== undefined);
138
- const mandatory = isReview ? REVIEW_SECTIONS : DELIVERY_SECTIONS;
139
- const parsedTests = isReview ? null : parseTestsSection(sections.Tests);
140
- const missing = mandatory.filter((s) => {
141
- const v = sections[s];
142
- if (v === undefined || v === '') return true;
143
- return !isReview && s === 'Tests' && !parsedTests.valid;
144
- });
145
- const testsStatus = parsedTests?.status;
146
- return {
147
- format: isReview ? 'review' : 'coding',
148
- present: [...new Set(marks.map((x) => x.name))],
149
- complete: missing.length === 0,
150
- missing,
151
- sections,
152
- ...(testsStatus ? { tests_status: testsStatus } : {}),
153
- };
154
- }
155
-
156
- /**
157
- * Re-check a parsed report (or raw text) against the contract. Pure and
158
- * forgiving: returns { ok, complete, missing, present } and never throws.
159
- */
160
- export function validateDeliveryReport(parsedOrText) {
161
- const parsed = typeof parsedOrText === 'string'
162
- ? parseDeliveryReport(parsedOrText)
163
- : (parsedOrText ?? parseDeliveryReport(''));
164
- const sections = parsed.sections ?? {};
165
- const isReview = parsed.format === 'review';
166
- const mandatory = isReview ? REVIEW_SECTIONS : DELIVERY_SECTIONS;
167
- const parsedTests = isReview ? null : parseTestsSection(sections.Tests);
168
- const missing = mandatory.filter((s) => {
169
- const v = sections[s];
170
- if (v === undefined || v === '') return true;
171
- return !isReview && s === 'Tests' && !parsedTests.valid;
172
- });
173
- return { ok: missing.length === 0, complete: missing.length === 0, missing: [...missing], present: [...(parsed.present ?? [])] };
174
- }
175
-
176
- function clip(text, limit) {
177
- if (typeof text !== 'string') return undefined;
178
- const t = text.trim();
179
- if (t === '') return undefined;
180
- return t.length > limit ? `${t.slice(0, limit)}…` : t;
181
- }
182
-
183
- /**
184
- * Compact metadata form of a parsed report for MCP responses / job views:
185
- * complete + missing plus a bounded snippet per present section. Keeps the
186
- * worker's full message out of status payloads.
187
- */
188
- export function formatDeliveryMetadata(parsed, { limit = 400 } = {}) {
189
- const sections = parsed?.sections ?? {};
190
- const out = {
191
- complete: parsed?.complete === true,
192
- missing: Array.isArray(parsed?.missing) ? [...parsed.missing] : [],
193
- };
194
- for (const s of ALL_DELIVERY_SECTIONS) {
195
- const clipped = clip(sections[s], limit);
196
- if (clipped !== undefined) out[METADATA_KEYS[s]] = clipped;
197
- }
198
- for (const s of REVIEW_SECTIONS) {
199
- const clipped = clip(sections[s], limit);
200
- if (clipped !== undefined) out[METADATA_KEYS[s]] = clipped;
201
- }
202
- if (parsed?.tests_status) out.tests_status = parsed.tests_status;
203
- if (out.missing.length === 0) delete out.missing;
204
- return out;
205
- }
1
+ // Auditable worker delivery: one shared Delivery Contract that every coding
2
+ // worker (and the automatic Pro review) must fill out before its result is
3
+ // accepted, plus pure helpers to prompt for, parse, validate and format it.
4
+ //
5
+ // Everything here is a pure function (no I/O, no worker runtime), so tests can
6
+ // exercise the contract without starting DSH. Keeping the contract in one
7
+ // shared builder guarantees the prompt-construction points (jobs.mjs, the hub,
8
+ // the MCP shim) emit byte-identical instructions, and parse / validate let the
9
+ // orchestrator separate *execution* status (running/done/failed) from
10
+ // *delivery* completeness (did the worker actually report Diff/Tests/Risks?).
11
+
12
+ export const DELIVERY_SECTIONS = ['Diff', 'Tests', 'Risks'];
13
+ export const OPTIONAL_DELIVERY_SECTIONS = ['Unverified'];
14
+ export const ALL_DELIVERY_SECTIONS = [...DELIVERY_SECTIONS, ...OPTIONAL_DELIVERY_SECTIONS];
15
+
16
+ export const REVIEW_SECTIONS = ['Review Findings', 'Evidence', 'Risks', 'Verdict'];
17
+
18
+ /** Any worker prompt that already carries a delivery report (added once). */
19
+ export const DELIVERY_MARKER = '# Delivery report';
20
+
21
+ const METADATA_KEYS = {
22
+ Diff: 'diff',
23
+ Tests: 'tests',
24
+ Risks: 'risks',
25
+ Unverified: 'unverified',
26
+ 'Review Findings': 'findings',
27
+ Evidence: 'evidence',
28
+ Verdict: 'verdict',
29
+ };
30
+
31
+ /**
32
+ * Prompts a coding worker (or, with isReview, an automatic Pro review) to end
33
+ * its final message with the auditable delivery contract. This is the single
34
+ * source of the contract text for every worker prompt.
35
+ */
36
+ export function buildDeliveryInstructions({ tier = 'pro', isReview = false } = {}) {
37
+ if (isReview) {
38
+ return `# Delivery report — automatic review (worker tier: pro)
39
+ You are reviewing an implementation, and your review must be auditable. End your final message with these four sections — each on its own line as a '##' heading — followed by concise content:
40
+
41
+ ## Review Findings
42
+ One-line overall assessment of whether the implementation satisfies the task.
43
+
44
+ ## Evidence
45
+ What you inspected: file paths, diffs, commands you ran, and their results.
46
+
47
+ ## Risks
48
+ Concrete issues found: bugs, style problems, missing edge cases, security or secret-handling concerns.
49
+
50
+ ## Verdict
51
+ One line: approved / needs changes / rejected, plus the single most important reason.
52
+
53
+ Do not edit files unless the user explicitly asks for fixes.`;
54
+ }
55
+ return `# Delivery report requirements (worker tier: ${String(tier).toUpperCase()})
56
+ You are a coding worker, and your result must be auditable. End your final message with these three mandatory sections — each on its own line as a '##' heading — followed by concise, factual content:
57
+
58
+ ## Diff
59
+ Every file you changed or created (paths), with a one-line summary per file. If you changed nothing, write "no files changed".
60
+
61
+ ## Tests
62
+ Every entry must use exactly one of these auditable states:
63
+ PASS — <command/check> — <result>
64
+ FAIL — <command/check> — <reason>
65
+ NOT RUN — <check> — <reason>
66
+ "none" is not a valid Tests result.
67
+
68
+ ## Risks
69
+ Known risks and side effects: files touched outside the requested scope, assumptions you made, anything that could break, and any credentials or sensitive data you opened.
70
+
71
+ ## Unverified
72
+ (Optional — omit entirely if you verified everything.) Anything you could not verify: skipped builds, untested platforms, known gaps.
73
+
74
+ The Diff, Tests and Risks sections are mandatory — do not skip them. Keep each section tight (a few lines is enough).
75
+
76
+ ${tier === 'flash' ? `Implement only the delegated coding scope.
77
+ Run direct validation needed for your change.
78
+ Return the Delivery Report.
79
+ Then stop and return control to the Main Agent.
80
+
81
+ Do not autonomously start a new task or delegate further work.` : ''}`;
82
+ }
83
+
84
+ /**
85
+ * Append the delivery instructions to a worker task prompt. Idempotent: a task
86
+ * that already carries the delivery report (e.g. a review prompt, or a
87
+ * re-dispatch) is returned untouched so instructions are never doubled.
88
+ */
89
+ export function appendDeliveryInstructions(task, { tier, isReview } = {}) {
90
+ if (typeof task !== 'string') return task;
91
+ if (task.includes(DELIVERY_MARKER)) return task;
92
+ return `${task}\n\n${buildDeliveryInstructions({ tier, isReview })}`;
93
+ }
94
+
95
+ function parseTestsSection(value) {
96
+ if (typeof value !== 'string' || value.trim() === '') return { valid: false, status: undefined };
97
+ const statuses = [];
98
+ for (const line of value.split(/\r?\n/).map((item) => item.trim()).filter(Boolean)) {
99
+ const match = line.match(/^(?:[-*+]\s+)?(PASS|FAIL|NOT RUN)\s+—\s+\S.*?\s+—\s+\S.*$/);
100
+ if (!match) return { valid: false, status: undefined };
101
+ statuses.push(match[1]);
102
+ }
103
+ const status = statuses.includes('FAIL') ? 'FAIL' : statuses.includes('NOT RUN') ? 'NOT RUN' : statuses.includes('PASS') ? 'PASS' : undefined;
104
+ return { valid: status !== undefined, status };
105
+ }
106
+
107
+ /**
108
+ * Parse a worker's final message into the delivery report. Detects the report
109
+ * format from the headings present: coding workers use Diff/Tests/Risks
110
+ * (+ optional Unverified), automatic reviews use Review Findings/Evidence/
111
+ * Risks/Verdict. `complete` means every *mandatory* section of the detected
112
+ * format is present and non-empty.
113
+ *
114
+ * Returns { format, present, complete, missing, sections }.
115
+ */
116
+ export function parseDeliveryReport(text = '') {
117
+ const normalized = typeof text === 'string' ? text : String(text ?? '');
118
+ if (normalized.trim() === '') {
119
+ return { format: null, present: [], complete: false, missing: [...DELIVERY_SECTIONS], sections: {} };
120
+ }
121
+ const canonical = new Map(ALL_DELIVERY_SECTIONS.concat(REVIEW_SECTIONS).map((name) => [name.toLowerCase(), name]));
122
+ const heading = /^##\s+(Diff|Tests|Risks|Unverified|Review Findings|Evidence|Verdict)\s*$/gim;
123
+ const marks = [];
124
+ let m;
125
+ while ((m = heading.exec(normalized)) !== null) marks.push({ index: m.index, name: canonical.get(m[1].toLowerCase()), len: m[0].length });
126
+ if (marks.length === 0) {
127
+ return { format: null, present: [], complete: false, missing: [...DELIVERY_SECTIONS], sections: {} };
128
+ }
129
+ const sections = {};
130
+ for (let i = 0; i < marks.length; i++) {
131
+ const start = marks[i].index + marks[i].len;
132
+ const end = i + 1 < marks.length ? marks[i + 1].index : normalized.length;
133
+ const body = normalized.slice(start, end).trim();
134
+ const name = marks[i].name;
135
+ sections[name] = sections[name] === undefined ? body : `${sections[name]}\n\n${body}`;
136
+ }
137
+ const isReview = REVIEW_SECTIONS.some((s) => s !== 'Risks' && sections[s] !== undefined);
138
+ const mandatory = isReview ? REVIEW_SECTIONS : DELIVERY_SECTIONS;
139
+ const parsedTests = isReview ? null : parseTestsSection(sections.Tests);
140
+ const missing = mandatory.filter((s) => {
141
+ const v = sections[s];
142
+ if (v === undefined || v === '') return true;
143
+ return !isReview && s === 'Tests' && !parsedTests.valid;
144
+ });
145
+ const testsStatus = parsedTests?.status;
146
+ return {
147
+ format: isReview ? 'review' : 'coding',
148
+ present: [...new Set(marks.map((x) => x.name))],
149
+ complete: missing.length === 0,
150
+ missing,
151
+ sections,
152
+ ...(testsStatus ? { tests_status: testsStatus } : {}),
153
+ };
154
+ }
155
+
156
+ /**
157
+ * Re-check a parsed report (or raw text) against the contract. Pure and
158
+ * forgiving: returns { ok, complete, missing, present } and never throws.
159
+ */
160
+ export function validateDeliveryReport(parsedOrText) {
161
+ const parsed = typeof parsedOrText === 'string'
162
+ ? parseDeliveryReport(parsedOrText)
163
+ : (parsedOrText ?? parseDeliveryReport(''));
164
+ const sections = parsed.sections ?? {};
165
+ const isReview = parsed.format === 'review';
166
+ const mandatory = isReview ? REVIEW_SECTIONS : DELIVERY_SECTIONS;
167
+ const parsedTests = isReview ? null : parseTestsSection(sections.Tests);
168
+ const missing = mandatory.filter((s) => {
169
+ const v = sections[s];
170
+ if (v === undefined || v === '') return true;
171
+ return !isReview && s === 'Tests' && !parsedTests.valid;
172
+ });
173
+ return { ok: missing.length === 0, complete: missing.length === 0, missing: [...missing], present: [...(parsed.present ?? [])] };
174
+ }
175
+
176
+ function clip(text, limit) {
177
+ if (typeof text !== 'string') return undefined;
178
+ const t = text.trim();
179
+ if (t === '') return undefined;
180
+ return t.length > limit ? `${t.slice(0, limit)}…` : t;
181
+ }
182
+
183
+ /**
184
+ * Compact metadata form of a parsed report for MCP responses / job views:
185
+ * complete + missing plus a bounded snippet per present section. Keeps the
186
+ * worker's full message out of status payloads.
187
+ */
188
+ export function formatDeliveryMetadata(parsed, { limit = 400 } = {}) {
189
+ const sections = parsed?.sections ?? {};
190
+ const out = {
191
+ complete: parsed?.complete === true,
192
+ missing: Array.isArray(parsed?.missing) ? [...parsed.missing] : [],
193
+ };
194
+ for (const s of ALL_DELIVERY_SECTIONS) {
195
+ const clipped = clip(sections[s], limit);
196
+ if (clipped !== undefined) out[METADATA_KEYS[s]] = clipped;
197
+ }
198
+ for (const s of REVIEW_SECTIONS) {
199
+ const clipped = clip(sections[s], limit);
200
+ if (clipped !== undefined) out[METADATA_KEYS[s]] = clipped;
201
+ }
202
+ if (parsed?.tests_status) out.tests_status = parsed.tests_status;
203
+ if (out.missing.length === 0) delete out.missing;
204
+ return out;
205
+ }