@haposoft/cafekit 0.16.0-rc.3 → 0.16.0-rc.4

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 (91) hide show
  1. package/bin/__tests__/codex-hooks.test.js +444 -14
  2. package/bin/__tests__/codex-native.test.js +228 -7
  3. package/bin/__tests__/develop-contract.test.js +615 -185
  4. package/bin/__tests__/installer-safety.test.js +39 -0
  5. package/bin/__tests__/opencode-spec-gate.test.js +24 -16
  6. package/bin/__tests__/package-inventory.test.js +687 -13
  7. package/bin/__tests__/specs-v2-execution-closeout.test.js +421 -0
  8. package/bin/__tests__/specs-v2-policy-and-scaffold.test.js +601 -0
  9. package/bin/__tests__/specs-v2-validator-grounder-contract.test.js +952 -0
  10. package/bin/__tests__/test-runtime-dependency-closure.cjs +182 -0
  11. package/bin/__tests__/validator-grounding.test.js +1914 -221
  12. package/bin/lib/managed-writer.js +12 -3
  13. package/bin/phases/codex-runtime.js +17 -1
  14. package/package.json +1 -1
  15. package/src/claude/CLAUDE.md +6 -0
  16. package/src/claude/agents/code-auditor.md +20 -0
  17. package/src/claude/agents/spec-maker.md +143 -99
  18. package/src/claude/hooks/__tests__/completion-authority.test.js +291 -58
  19. package/src/claude/hooks/__tests__/privacy-block.test.js +172 -0
  20. package/src/claude/hooks/__tests__/semantic-review-authority.test.js +257 -0
  21. package/src/claude/hooks/__tests__/spec-gate.test.js +115 -40
  22. package/src/claude/hooks/completion-authority-check.cjs +37 -288
  23. package/src/claude/hooks/completion-authority-state.cjs +10 -8
  24. package/src/claude/hooks/completion-authority.cjs +13 -7
  25. package/src/claude/hooks/docs-sync.cjs +5 -2
  26. package/src/claude/hooks/lib/privacy-command-analysis.cjs +393 -0
  27. package/src/claude/hooks/lib/runtime-path-safety.cjs +119 -0
  28. package/src/claude/hooks/privacy-block.cjs +77 -30
  29. package/src/claude/hooks/semantic-review-authority.cjs +152 -0
  30. package/src/claude/hooks/spec-gate.cjs +47 -117
  31. package/src/claude/hooks/spec-state.cjs +8 -2
  32. package/src/claude/migration-manifest.json +9 -1
  33. package/src/claude/rules/state-sync.md +52 -21
  34. package/src/claude/rules/workflow.md +17 -9
  35. package/src/claude/scripts/spec-final-state.cjs +244 -0
  36. package/src/claude/scripts/spec-ground.cjs +535 -173
  37. package/src/claude/scripts/spec-readiness.cjs +118 -0
  38. package/src/claude/scripts/spec-receipt.cjs +162 -0
  39. package/src/claude/scripts/spec-resolver.cjs +67 -16
  40. package/src/claude/scripts/spec-scaffold.cjs +1354 -139
  41. package/src/claude/scripts/spec-semantic-model.cjs +396 -0
  42. package/src/claude/scripts/validate-spec-output.cjs +2782 -142
  43. package/src/claude/scripts/workflow-policy.cjs +501 -183
  44. package/src/claude/settings/settings.json +4 -0
  45. package/src/claude/skills/code-review/SKILL.md +12 -3
  46. package/src/claude/skills/code-review/references/spec-compliance-review.md +10 -2
  47. package/src/claude/skills/code-review/references/verification-gate.md +13 -0
  48. package/src/claude/skills/develop/SKILL.md +47 -60
  49. package/src/claude/skills/develop/references/parallel-waves.md +9 -6
  50. package/src/claude/skills/develop/references/quality-gate.md +19 -12
  51. package/src/claude/skills/specs/SKILL.md +183 -177
  52. package/src/claude/skills/specs/references/ask-user-question-gates.md +27 -18
  53. package/src/claude/skills/specs/references/cross-spec-dependency.md +8 -4
  54. package/src/claude/skills/specs/references/research-strategy.md +4 -1
  55. package/src/claude/skills/specs/references/review.md +200 -260
  56. package/src/claude/skills/specs/references/scope-inquiry.md +18 -5
  57. package/src/claude/skills/specs/rules/design-discovery-full.md +33 -81
  58. package/src/claude/skills/specs/rules/design-discovery-light.md +21 -42
  59. package/src/claude/skills/specs/rules/design-principles.md +136 -180
  60. package/src/claude/skills/specs/rules/design-review.md +42 -97
  61. package/src/claude/skills/specs/rules/ears-format.md +42 -50
  62. package/src/claude/skills/specs/rules/phase-decision-matrix.md +42 -41
  63. package/src/claude/skills/specs/rules/task-scoring-rubric.md +2 -1
  64. package/src/claude/skills/specs/rules/tasks-generation.md +189 -300
  65. package/src/claude/skills/specs/templates/design.md +49 -263
  66. package/src/claude/skills/specs/templates/requirements.md +26 -36
  67. package/src/claude/skills/specs/templates/research.md +9 -98
  68. package/src/claude/skills/specs/templates/spec-state.json +23 -85
  69. package/src/claude/skills/specs/templates/task.md +30 -102
  70. package/src/claude/skills/sync/SKILL.md +33 -10
  71. package/src/claude/skills/sync/references/sync-protocols.md +31 -13
  72. package/src/claude/skills/test/SKILL.md +17 -7
  73. package/src/codex/AGENTS.md +6 -0
  74. package/src/codex/hooks/completion-authority-check.cjs +43 -240
  75. package/src/codex/hooks/completion-authority-state.cjs +10 -8
  76. package/src/codex/hooks/completion-authority.cjs +13 -7
  77. package/src/codex/hooks/lib/hook-context.cjs +16 -2
  78. package/src/codex/hooks/lib/privacy-command-analysis.cjs +3 -0
  79. package/src/codex/hooks/lib/privacy-state.cjs +38 -16
  80. package/src/codex/hooks/lib/runtime-path-safety.cjs +3 -0
  81. package/src/codex/hooks/lib/spec-receipt.cjs +72 -134
  82. package/src/codex/hooks/lib/spec-utils.cjs +56 -5
  83. package/src/codex/hooks/privacy-approval.cjs +1 -1
  84. package/src/codex/hooks/privacy-block.cjs +67 -11
  85. package/src/codex/hooks/semantic-review-authority.cjs +130 -0
  86. package/src/codex/hooks/spec-gate.cjs +49 -34
  87. package/src/codex/hooks/spec-state.cjs +10 -3
  88. package/src/codex/hooks/state.cjs +2 -0
  89. package/src/codex/hooks.json +6 -1
  90. package/src/codex/rules/state-sync.md +47 -27
  91. package/src/common/AGENTS.md +1 -1
@@ -6,11 +6,20 @@
6
6
  * the hard backstop before a spec is marked ready for implementation.
7
7
  */
8
8
 
9
+ const crypto = require('crypto');
9
10
  const fs = require('fs');
10
11
  const path = require('path');
11
12
  const POLICY = require('./workflow-policy.cjs');
13
+ const SEMANTIC = require('./spec-semantic-model.cjs');
14
+ const {
15
+ canonicalProjectRoot,
16
+ groundSpec,
17
+ parseCanonicalAnchors,
18
+ parseVerificationDefinitions,
19
+ } = require('./spec-ground.cjs');
12
20
 
13
21
  const TASK_PATH_RE = /^tasks\/task-R\d+-\d{2}-[a-z0-9]+(?:-[a-z0-9]+)*\.md$/;
22
+ const TASK_IDENTITY_RE = /^tasks\/task-(R\d+-\d{2})-[a-z0-9]+(?:-[a-z0-9]+)*\.md$/;
14
23
  const REQUIRED_REGISTRY_KEYS = [
15
24
  'id',
16
25
  'title',
@@ -23,11 +32,50 @@ const REQUIRED_REGISTRY_KEYS = [
23
32
  ];
24
33
  const APPROVAL_SCHEMA_VERSION = '2.0';
25
34
  const LEGACY_APPROVAL_ERROR =
26
- `Legacy approval field "approved" detected. Migration required: replace "approved" with "agent_validated" and "user_approved" per schema v${APPROVAL_SCHEMA_VERSION} (schema_version: "${APPROVAL_SCHEMA_VERSION}"). See spec-state.json template. Refusing to infer user approval.`;
35
+ `Legacy approval field "approved" detected. Migration required: replace "approved" with "agent_validated" per schema v${APPROVAL_SCHEMA_VERSION} (schema_version: "${APPROVAL_SCHEMA_VERSION}"). See spec-state.json template.`;
27
36
  const FEATURE_RECEIPT_FILE = 'feature-receipt.md';
37
+ const SPEC_STATUS_VALUES = new Set(['in_progress', 'in-progress', 'paused', 'blocked', 'done']);
38
+ const TASK_STATUS_VALUES = new Set(['pending', 'in_progress', 'blocked', 'done']);
39
+ const VALIDATION_STATUS_VALUES = new Set(['not-run', 'in_progress', 'completed']);
40
+ const ANCHOR_TYPES = new Set([
41
+ 'file', 'symbol', 'command', 'route', 'schema', 'contract', 'artifact', 'external',
42
+ ]);
43
+ const PHASE_FIELDS = ['id', 'task_ids', 'entry_condition', 'exit_condition', 'owner_boundary'];
44
+ const TASK_TRIGGER_VALUES = new Set([
45
+ 'distinct_ownership',
46
+ 'real_dependency',
47
+ 'durable_transition',
48
+ 'separate_proof',
49
+ 'parallel_coordination',
50
+ ]);
51
+ const SEMANTIC_REVIEW_FIELDS = [
52
+ 'status',
53
+ 'reviewed_artifact_digest',
54
+ 'reviewed_criteria',
55
+ 'counterexamples',
56
+ ];
57
+ const SEMANTIC_REVIEW_STATUSES = new Set(['not-run', 'completed']);
58
+ const SHA256_RE = /^sha256:[a-f0-9]{64}$/;
59
+ const SCHEMA_21 = '2.1';
60
+ const TASK_21_SECTIONS = [
61
+ 'Outcome', 'Scope', 'Anchors and Ownership', 'Changes', 'Acceptance', 'Dependencies', 'Verification Plan',
62
+ ];
63
+ const BOUNDARY_21_FIELDS = Object.freeze({
64
+ ownership: ['id', 'type', 'tasks', 'write_sets'],
65
+ dependency: ['id', 'type', 'producer', 'consumer', 'deliverable'],
66
+ transition: ['id', 'type', 'design_ref', 'owner', 'consumers', 'precondition', 'postcondition', 'failure', 'recovery'],
67
+ proof: ['id', 'type', 'subject', 'verifier', 'verification_ref', 'artifact_anchor'],
68
+ parallel: ['id', 'type', 'tasks', 'resources'],
69
+ });
70
+ const SPEC_21_REQUIRED_FIELDS = Object.freeze([
71
+ 'schema_version', 'feature_name', 'created_at', 'updated_at', 'language', 'status',
72
+ 'scope_lock', 'authoring', 'coordination', 'validation', 'semantic_model',
73
+ 'ready_for_implementation', 'workflow_policy',
74
+ ]);
75
+ const SPEC_21_OPTIONAL_FIELDS = Object.freeze(['research', 'task_files', 'task_registry', 'decisions']);
28
76
 
29
77
  function usage() {
30
- console.error('Usage: node .claude/scripts/validate-spec-output.cjs specs/<feature>');
78
+ console.error('Usage: node .claude/scripts/validate-spec-output.cjs specs/<feature> [--semantic-digest]');
31
79
  }
32
80
 
33
81
  function resolveSpecDir(input) {
@@ -52,6 +100,10 @@ function readJson(filePath, errors) {
52
100
  }
53
101
  }
54
102
 
103
+ function isPlainObject(value) {
104
+ return Boolean(value && typeof value === 'object' && !Array.isArray(value));
105
+ }
106
+
55
107
  function isPathInside(parent, child) {
56
108
  const relative = path.relative(path.resolve(parent), path.resolve(child));
57
109
  return relative !== '' && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
@@ -174,6 +226,20 @@ function hasHeading(content, heading) {
174
226
  return new RegExp(`^##\\s+${escaped}\\s*$`, 'm').test(content);
175
227
  }
176
228
 
229
+ function headingCount(content, heading) {
230
+ const escaped = heading.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
231
+ return [...content.matchAll(new RegExp(`^##\\s+${escaped}\\s*$`, 'gim'))].length;
232
+ }
233
+
234
+ function validateUniqueSectionGroups(label, content, groups, errors) {
235
+ for (const group of groups) {
236
+ const count = group.reduce((total, heading) => total + headingCount(content, heading), 0);
237
+ if (count > 1) {
238
+ errors.push(`${label}: machine-read section ${group.join('/')} must appear at most once`);
239
+ }
240
+ }
241
+ }
242
+
177
243
  function extractSection(content, heading) {
178
244
  const escaped = heading.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
179
245
  const re = new RegExp(`^##\\s+${escaped}\\s*$`, 'im');
@@ -185,46 +251,336 @@ function extractSection(content, heading) {
185
251
  return next ? after.slice(0, next.index) : after;
186
252
  }
187
253
 
188
- function extractRequirementIds(requirementsText) {
189
- const ids = new Set();
190
- const headingRe = /^#{2,4}\s+(?:(?:Requirement)\s+)?((?:REQ-\d+)|(?:R\d+))\b/gim;
254
+ function semanticMarkdown(content) {
255
+ const withoutComments = String(content).replace(/<!--[\s\S]*?-->/g, '');
256
+ let fence = null;
257
+ return withoutComments.split('\n').map((line) => {
258
+ const marker = line.match(/^\s{0,3}(`{3,}|~{3,})/);
259
+ if (marker) {
260
+ const character = marker[1][0];
261
+ const length = marker[1].length;
262
+ if (fence === null) fence = { character, length };
263
+ else if (character === fence.character && length >= fence.length) fence = null;
264
+ return '';
265
+ }
266
+ return fence === null ? line : '';
267
+ }).join('\n');
268
+ }
269
+
270
+ function requirementHeadingDeclarations(requirementsText) {
271
+ const semanticText = semanticMarkdown(requirementsText);
272
+ const declarations = [];
273
+ const invalid = [];
274
+ const headingRe = /^#{2,4}\s+(.+?)\s*$/gm;
191
275
  let match;
276
+ while ((match = headingRe.exec(semanticText)) !== null) {
277
+ const heading = match[1].trim();
278
+ const explicit = heading.match(/^Requirement\s+([^\s:.-]+)(?=[:.\s-]|$)/i);
279
+ const prefixed = heading.match(/^((?:R|REQ|NFR|SEC|PERF)[A-Za-z0-9_.-]*\d[A-Za-z0-9_.-]*)(?=[:\s]|$)/i);
280
+ const numeric = heading.match(/^(\d+)(?=[:.\s-]|$)/);
281
+ const bracketed = heading.match(/^\[(R\d+)\](?=[:.\s-]|$)/i);
282
+ let token = null;
283
+ let canonical = null;
284
+ if (explicit) {
285
+ token = explicit[1];
286
+ canonical = /^\d+$/.test(token)
287
+ ? `R${token}`
288
+ : (/^R\d+$/i.test(token) ? token.toUpperCase() : null);
289
+ } else if (prefixed) {
290
+ token = prefixed[1];
291
+ canonical = /^R\d+$/i.test(token) ? token.toUpperCase() : null;
292
+ } else if (numeric) {
293
+ token = numeric[1];
294
+ } else if (bracketed) {
295
+ token = bracketed[1];
296
+ }
297
+ if (canonical) declarations.push({ id: canonical, heading });
298
+ else if (token !== null) invalid.push({ token, heading });
299
+ }
300
+ return { declarations, invalid };
301
+ }
192
302
 
193
- while ((match = headingRe.exec(requirementsText)) !== null) {
194
- ids.add(match[1].toUpperCase());
303
+ function acceptanceCriterionDeclarations(requirementsText) {
304
+ const semanticText = semanticMarkdown(requirementsText);
305
+ const canonical = [];
306
+ const invalid = [];
307
+ const re = /^\s*(?:[-*+]\s+)?\*{0,2}([^\s*]+)\*{0,2}(?:\s*[:—-])?\s+(.+?)\s*$/gm;
308
+ let match;
309
+ while ((match = re.exec(semanticText)) !== null) {
310
+ const token = match[1];
311
+ const looksStructured = /^(?:R|REQ|NFR|SEC|PERF|AC)[A-Za-z0-9_.-]*\d[A-Za-z0-9_.-]*$/i.test(token)
312
+ || /^R\d+[.-][A-Za-z0-9]+$/i.test(token);
313
+ if (!looksStructured) continue;
314
+ if (/^R\d+\.\d+$/i.test(token)) {
315
+ canonical.push({ id: token.toUpperCase(), text: match[2].trim() });
316
+ } else {
317
+ invalid.push({ token, text: match[2].trim() });
318
+ }
195
319
  }
320
+ return { canonical, invalid };
321
+ }
196
322
 
197
- const numericRequirementRe = /^#{2,4}\s+(?:Requirement\s+)?(\d+)(?=[:.\s-])/gim;
198
- while ((match = numericRequirementRe.exec(requirementsText)) !== null) {
199
- ids.add(`R${match[1]}`);
323
+ function validateRequirementInventory(requirementsText, errors) {
324
+ const headings = requirementHeadingDeclarations(requirementsText);
325
+ const criteria = acceptanceCriterionDeclarations(requirementsText);
326
+ for (const declaration of headings.invalid) {
327
+ if (hasSpecPlaceholders(declaration.token)) continue;
328
+ errors.push(
329
+ `requirements.md: unsupported requirement id ${declaration.token} in requirement heading; ` +
330
+ 'use Requirement N or RN',
331
+ );
332
+ }
333
+ for (const declaration of criteria.invalid) {
334
+ if (hasSpecPlaceholders(declaration.token)) continue;
335
+ errors.push(
336
+ `requirements.md: unsupported acceptance criterion id ${declaration.token}; use RN.M`,
337
+ );
200
338
  }
201
339
 
202
- const bracketRe = /\[((?:REQ-\d+)|(?:R\d+))\]/gi;
203
- while ((match = bracketRe.exec(requirementsText)) !== null) {
204
- ids.add(match[1].toUpperCase());
340
+ const seenRequirements = new Set();
341
+ for (const declaration of headings.declarations) {
342
+ if (seenRequirements.has(declaration.id)) {
343
+ errors.push(`requirements.md: duplicate canonical requirement id ${declaration.id}`);
344
+ }
345
+ seenRequirements.add(declaration.id);
346
+ }
347
+ const seenCriteria = new Set();
348
+ for (const criterion of criteria.canonical) {
349
+ if (seenCriteria.has(criterion.id)) {
350
+ errors.push(`requirements.md: duplicate canonical acceptance criterion id ${criterion.id}`);
351
+ }
352
+ seenCriteria.add(criterion.id);
353
+ const requirementId = criterion.id.split('.')[0];
354
+ if (seenRequirements.size > 0 && !seenRequirements.has(requirementId)) {
355
+ errors.push(`requirements.md: acceptance criterion ${criterion.id} has no matching ${requirementId} heading`);
356
+ }
205
357
  }
358
+ }
359
+
360
+ function extractRequirementIds(requirementsText) {
361
+ return [...new Set(requirementHeadingDeclarations(requirementsText).declarations
362
+ .map(({ id }) => id)
363
+ .filter((id) => id !== 'R0'))].sort();
364
+ }
365
+
366
+ function extractAcceptanceCriteria(requirementsText) {
367
+ return acceptanceCriterionDeclarations(requirementsText).canonical;
368
+ }
369
+
370
+ function hasTestableAcceptanceCriterion(requirementsText) {
371
+ const assertion = /\b(?:shall|must|returns?|rejects?|emits?|writes?|persists?|creates?|deletes?|renders?|displays?|records?|exits?|fails?|equals?|contains?|remains?|transitions?)\b/i;
372
+ const observable = /`[^`]+`|\b(?:exit code|http|status|file|path|record|event|response|result|state|field|value|message|artifact|directory|request|output|error)\b|\d/i;
373
+ return extractAcceptanceCriteria(requirementsText).some(({ text }) => (
374
+ text.length >= 24
375
+ && !hasSpecPlaceholders(text)
376
+ && assertion.test(text)
377
+ && observable.test(text)
378
+ ));
379
+ }
380
+
381
+ function hasConcreteDesignBoundary(designText) {
382
+ const sections = [
383
+ 'Boundary',
384
+ 'Architecture',
385
+ 'Components and Interfaces',
386
+ 'Canonical Contracts & Invariants',
387
+ 'Implementation Boundary',
388
+ ].map((heading) => extractSection(designText, heading)).filter(Boolean);
389
+ const boundary = sections.join('\n');
390
+ if (boundary.length < 24 || hasSpecPlaceholders(boundary)) return false;
391
+ const genericIdentifiers = new Set([
392
+ 'module', 'service', 'component', 'entrypoint', 'interface', 'function',
393
+ 'class', 'route', 'command', 'database', 'table', 'process', 'boundary', 'owner',
394
+ ]);
395
+ const fencedReferences = [...boundary.matchAll(/`([^`]+)`/g)]
396
+ .map((match) => match[1].trim())
397
+ .filter((reference) => (
398
+ reference.length >= 3
399
+ && !genericIdentifiers.has(reference.toLowerCase())
400
+ && (/[/\\.]/.test(reference) || /^[A-Za-z_$][A-Za-z0-9_$.:-]*$/.test(reference))
401
+ ));
402
+ const pathReference = /(?:^|\s)(?:src|packages|apps|lib|cmd|internal|tests?|\.claude|\.codex)\/[A-Za-z0-9_.\/-]+/im.test(boundary);
403
+ const ownedBehavior = /\b(?:owns?|reads?|writes?|calls?|invokes?|imports?|registers?|routes?|persists?|updates?|creates?|deletes?|validates?|returns?|emits?|handles?|maps?|touches?|modifies?|implements?|consumes?|produces?)\b/i.test(boundary);
404
+ return ownedBehavior && (fencedReferences.length > 0 || pathReference);
405
+ }
406
+
407
+ function taskFormat(content) {
408
+ const conciseHeadings = [
409
+ 'Outcome', 'Scope and Typed Anchors', 'Changes', 'Acceptance', 'Dependencies',
410
+ 'Verification Plan',
411
+ ];
412
+ return conciseHeadings.some((heading) => hasHeading(content, heading)) ? 'v2' : 'legacy';
413
+ }
414
+
415
+ function sectionFieldValues(section, labels) {
416
+ return evidenceFieldValues(section || '', labels);
417
+ }
206
418
 
207
- return [...ids].filter((id) => id !== 'R0').sort();
419
+ function validateVerificationPlan(taskPath, content, errors) {
420
+ const section = extractSection(content, 'Verification Plan') || '';
421
+ const commands = sectionFieldValues(section, ['Command', 'Commands', 'Command(s)']);
422
+ if (!commands.some((value) => isExecutableCommand(value) || isJustifiedNotApplicable(value))) {
423
+ errors.push(`${taskPath}: Verification Plan requires a command-shaped invocation or justified N/A`);
424
+ }
425
+ if (!sectionFieldValues(section, ['Expected', 'Expected result', 'Expected proof']).some(hasObservableProof)) {
426
+ errors.push(`${taskPath}: Verification Plan requires an observable Expected result`);
427
+ }
428
+ const negative = sectionFieldValues(section, ['Negative path', 'Negative-path']);
429
+ if (!negative.some((value) => meaningfulMarkdownLines(value).length > 0 || isJustifiedNotApplicable(value))) {
430
+ errors.push(`${taskPath}: Verification Plan requires a negative-path disposition`);
431
+ }
432
+ const reachability = sectionFieldValues(section, ['Reachability']);
433
+ if (!reachability.some((value) => isConcreteReachabilityAnchor(value) || isJustifiedNotApplicable(value))) {
434
+ errors.push(`${taskPath}: Verification Plan requires a concrete reachability target or justified N/A`);
435
+ }
436
+ if (/^\s*(?:[-*+]\s*)?(?:\*\*)?(?:Observed|Actual|Verdict|Verification)(?:\*\*)?\s*:/im.test(section)
437
+ || /^\s*(?:Base|Head)\s*:/im.test(section)
438
+ || /\b(?:PASS|PASS_WITH_WARNINGS|FAIL|BLOCKED)\b/.test(section)) {
439
+ errors.push(`${taskPath}: Verification Plan is planned proof only and must not contain execution receipt fields or verdicts`);
440
+ }
208
441
  }
209
442
 
210
443
  /**
211
- * Extract sub-criteria IDs (e.g. R3.4) ONLY when requirements.md declares them
212
- * as explicit literals — bold `**R3.4**` or a line-leading `R3.4`. Specs that
213
- * write acceptance criteria as a plain numbered list declare no such literals.
214
- * Every declared literal must have an explicit numeric task mapping.
444
+ * Extract sub-criteria IDs (e.g. R3.4) only from canonical criterion declaration
445
+ * positions. Incidental prose such as "see R7.2" is not an inventory entry.
215
446
  */
216
447
  function extractSubCriteriaIds(requirementsText) {
217
- const ids = new Set();
218
- const re = /(?:^|\s)\**(R\d+\.\d+)\**/gim;
219
- let match;
220
- while ((match = re.exec(requirementsText)) !== null) {
221
- const id = match[1].toUpperCase();
222
- if (!id.startsWith('R0.')) ids.add(id);
223
- }
224
- return [...ids].sort();
448
+ return [...new Set(extractAcceptanceCriteria(requirementsText)
449
+ .map(({ id }) => id)
450
+ .filter((id) => !id.startsWith('R0.')))].sort();
451
+ }
452
+
453
+ function meaningfulMarkdownLines(section) {
454
+ if (typeof section !== 'string') return [];
455
+ return section.split('\n').map((rawLine) => rawLine
456
+ .trim()
457
+ .replace(/^[-*+]\s*/, '')
458
+ .replace(/^\[[ xX]\]\s*/, '')
459
+ .replace(/\*\*/g, '')
460
+ .trim())
461
+ .filter((line) => (
462
+ line.length >= 8
463
+ && !/^\|?\s*:?-{3,}/.test(line)
464
+ && !hasSpecPlaceholders(line)
465
+ ));
466
+ }
467
+
468
+ function hasSubstantiveSection(content, headings) {
469
+ const section = headings.map((heading) => extractSection(content, heading)).find((value) => value !== null);
470
+ return meaningfulMarkdownLines(section).length > 0;
471
+ }
472
+
473
+ function hasActionableTaskStep(section) {
474
+ if (typeof section !== 'string') return false;
475
+ return section.split('\n').some((line) => {
476
+ const match = line.match(/^\s*[-*+]\s+\[[ xX]\]\s+(?:\d+(?:\.\d+)?\s+)?(?:\(P\)\s+)?(.+?)\s*$/i);
477
+ if (!match) return false;
478
+ const action = match[1].replace(/\*\*/g, '').trim();
479
+ return action.length >= 4
480
+ && !hasSpecPlaceholders(action)
481
+ && !/^_?Requirements?\s*:/i.test(action);
482
+ });
483
+ }
484
+
485
+ function hasSubstantiveTaskRequirement(section) {
486
+ return meaningfulMarkdownLines(section).some((line) => {
487
+ if (/^_?Requirements?\s*:/i.test(line)) return false;
488
+ const match = line.match(/^(?:R)?\d+(?:\.\d+)?\s*(?:[-—:]\s*)?(.+)$/i);
489
+ return Boolean(match && match[1].trim().length >= 4 && !hasSpecPlaceholders(match[1]));
490
+ });
491
+ }
492
+
493
+ function evidenceFieldValues(section, labels) {
494
+ const alternation = labels
495
+ .map((label) => label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
496
+ .join('|');
497
+ const re = new RegExp(
498
+ `^\\s*(?:[-*+]\\s*)?(?:\\*\\*)?(?:${alternation})(?:\\*\\*)?\\s*:\\s*(.*?)\\s*$`,
499
+ 'gim',
500
+ );
501
+ return [...section.matchAll(re)].map((match) => match[1].trim());
502
+ }
503
+
504
+ function isJustifiedNotApplicable(value) {
505
+ const match = typeof value === 'string' && value.match(/^N\/A\s*(?:[-—:]\s*)(.+)$/i);
506
+ return Boolean(match && match[1].trim().length >= 12 && !hasSpecPlaceholders(match[1]));
507
+ }
508
+
509
+ function isExecutableCommand(value) {
510
+ // Static validation can prove command shape only. Project command/script
511
+ // existence is runtime evidence owned by the execution receipt; resolving it
512
+ // here would require forbidden project inspection or command execution.
513
+ if (typeof value !== 'string' || hasSpecPlaceholders(value)) return false;
514
+ const fenced = [...value.matchAll(/`([^`]+)`/g)].map((match) => match[1].trim());
515
+ const candidates = fenced.length > 0 ? fenced : [value.trim()];
516
+ return candidates.some((command) => {
517
+ if (command.length < 4 || /^(?:run|execute|verify|check)\s+(?:tests?|checks?|build)$/i.test(command)) return false;
518
+ const first = command.split(/\s+/)[0];
519
+ if (!/^(?:[A-Za-z0-9_@.-]+|\.\.?\/[A-Za-z0-9_./-]+)$/.test(first)) return false;
520
+ return command.includes(' ')
521
+ || /[/.]/.test(first)
522
+ || /^(?:make|pytest|jest|vitest)$/i.test(first);
523
+ });
524
+ }
525
+
526
+ function hasObservableProof(value) {
527
+ if (typeof value !== 'string') return false;
528
+ const text = value.trim();
529
+ return text.length >= 12
530
+ && !hasSpecPlaceholders(text)
531
+ && /`[^`]+`|(?:^|\s)(?:src|packages|apps|lib|cmd|internal|tests?)\/|\b(?:exit(?:\s+code)?|status|error|output|result|artifact|route|record|state|field|value|response|file|path|persisted|rendered|registered|imported|mounted|invoked)\b|\d/i.test(text);
532
+ }
533
+
534
+ function hasObservableCompletionCriterion(section) {
535
+ return meaningfulMarkdownLines(section).some((line) => (
536
+ line.length >= 16
537
+ && /\b(?:returns?|rejects?|writes?|persists?|creates?|deletes?|renders?|displays?|records?|exits?|fails?|equals?|contains?|remains?|transitions?|is imported|is mounted|is registered|is invoked)\b/i.test(line)
538
+ && /`[^`]+`|(?:^|\s)(?:src|packages|apps|lib|cmd|internal|tests?)\/|\b(?:exit(?:\s+code)?|status|error|output|result|artifact|route|record|state|field|value|response|file|path|caller|component|service|command)\b|\d/i.test(line)
539
+ ));
540
+ }
541
+
542
+ function isConcreteReachabilityAnchor(value) {
543
+ if (typeof value !== 'string') return false;
544
+ const anchor = value.replace(/`/g, '').trim();
545
+ return anchor.length >= 3
546
+ && !hasSpecPlaceholders(anchor)
547
+ && !/^(?:N\/A|none|unknown|pending)$/i.test(anchor)
548
+ && (/[/\\.]/.test(anchor) || /^[A-Za-z_$][A-Za-z0-9_$:-]*(?:\s+[A-Za-z0-9_./:-]+)*$/.test(anchor));
225
549
  }
226
550
 
227
551
  function validateTaskSections(taskPath, content, errors) {
552
+ if (taskFormat(content) === 'v2') {
553
+ const headings = [
554
+ 'Outcome', 'Scope and Typed Anchors', 'Changes', 'Acceptance', 'Dependencies',
555
+ 'Verification Plan',
556
+ ];
557
+ validateUniqueSectionGroups(taskPath, content, headings.map((heading) => [heading]), errors);
558
+ for (const heading of headings) {
559
+ if (!hasHeading(content, heading)) errors.push(`${taskPath}: missing ${heading}`);
560
+ else if (heading !== 'Dependencies' && !hasSubstantiveSection(content, [heading])) errors.push(`${taskPath}: ${heading} must be substantive`);
561
+ }
562
+ const changes = extractSection(content, 'Changes') || '';
563
+ if (!hasActionableTaskStep(changes)) {
564
+ errors.push(`${taskPath}: Changes must contain at least one substantive actionable checkbox`);
565
+ }
566
+ const acceptance = extractSection(content, 'Acceptance') || '';
567
+ if (!/\bR?\d+\.\d+\b/.test(acceptance)) {
568
+ errors.push(`${taskPath}: Acceptance must map at least one canonical RN.M criterion`);
569
+ }
570
+ validateVerificationPlan(taskPath, content, errors);
571
+ return;
572
+ }
573
+ validateUniqueSectionGroups(taskPath, content, [
574
+ ['Context'],
575
+ ['Constraints'],
576
+ ['Steps', 'Implementation Steps'],
577
+ ['Requirements'],
578
+ ['Related Files'],
579
+ ['Completion Criteria'],
580
+ ['Evidence', 'Task Test Plan & Verification Evidence', 'Verification & Evidence'],
581
+ ['Risk Assessment'],
582
+ ['Execution Closure'],
583
+ ], errors);
228
584
  const hasContext = hasHeading(content, 'Context');
229
585
  const hasConstraints = hasHeading(content, 'Constraints');
230
586
  const hasSteps =
@@ -239,14 +595,28 @@ function validateTaskSections(taskPath, content, errors) {
239
595
  hasHeading(content, 'Task Test Plan & Verification Evidence') ||
240
596
  hasHeading(content, 'Verification & Evidence');
241
597
  const hasRiskAssessment = hasHeading(content, 'Risk Assessment');
598
+ const stepsSection = extractSection(content, 'Steps')
599
+ || extractSection(content, 'Implementation Steps')
600
+ || '';
601
+ const requirementsSection = extractSection(content, 'Requirements') || '';
242
602
 
243
603
  if (!hasContext) errors.push(`${taskPath}: missing Context`);
604
+ else if (!hasSubstantiveSection(content, ['Context'])) errors.push(`${taskPath}: Context section must contain substantive task context`);
244
605
  if (!hasConstraints) errors.push(`${taskPath}: missing Constraints`);
606
+ else if (!hasSubstantiveSection(content, ['Constraints'])) errors.push(`${taskPath}: Constraints section must contain substantive scope or implementation constraints`);
245
607
  if (!hasSteps) errors.push(`${taskPath}: missing Steps/Implementation Steps`);
608
+ else if (!hasActionableTaskStep(stepsSection)) errors.push(`${taskPath}: Steps must contain at least one substantive actionable checkbox`);
246
609
  if (!hasRequirements) errors.push(`${taskPath}: missing Requirements mapping`);
610
+ else if (!hasSubstantiveTaskRequirement(requirementsSection)) errors.push(`${taskPath}: Requirements section must contain a substantive mapped requirement description`);
247
611
  if (!hasRelatedFiles) errors.push(`${taskPath}: missing Related Files`);
248
612
  else if (relatedFilesSection(content).rows.length === 0) errors.push(`${taskPath}: Related Files section must not be empty`);
249
613
  if (!hasCompletionCriteria) errors.push(`${taskPath}: missing Completion Criteria`);
614
+ else {
615
+ const completion = extractSection(content, 'Completion Criteria') || '';
616
+ if (!hasObservableCompletionCriterion(completion)) {
617
+ errors.push(`${taskPath}: Completion Criteria must contain at least one observable, testable outcome`);
618
+ }
619
+ }
250
620
  if (!hasEvidence) errors.push(`${taskPath}: missing Evidence or task test plan`);
251
621
  if (!hasRiskAssessment) errors.push(`${taskPath}: missing Risk Assessment`);
252
622
  if (hasEvidence) {
@@ -254,25 +624,38 @@ function validateTaskSections(taskPath, content, errors) {
254
624
  || extractSection(content, 'Task Test Plan & Verification Evidence')
255
625
  || extractSection(content, 'Verification & Evidence')
256
626
  || '';
627
+ const commandValues = evidenceFieldValues(evidenceSection, ['Command', 'Commands', 'Command(s)']);
628
+ if (!commandValues.some((value) => isExecutableCommand(value) || isJustifiedNotApplicable(value))) {
629
+ errors.push(`${taskPath}: Evidence requires an executable Command(s) value or explicit justified N/A`);
630
+ }
631
+ const expectedValues = evidenceFieldValues(evidenceSection, ['Expected proof', 'Expected result', 'Expected', 'Expect']);
632
+ if (!expectedValues.some(hasObservableProof)) {
633
+ errors.push(`${taskPath}: Evidence requires an observable expected result`);
634
+ }
635
+ const artifactValues = evidenceFieldValues(
636
+ evidenceSection,
637
+ ['Inspect', 'Artifact/runtime proof', 'Artifact / runtime proof', 'Artifact proof', 'Runtime proof'],
638
+ );
639
+ if (!artifactValues.some((value) => isConcreteReachabilityAnchor(value) || hasObservableProof(value))) {
640
+ errors.push(`${taskPath}: Evidence requires concrete artifact or runtime proof`);
641
+ }
257
642
  if (!/Runtime reachability verification/i.test(evidenceSection)) {
258
643
  errors.push(`${taskPath}: missing Runtime reachability verification`);
259
644
  } else {
260
- // Reachability must prove a concrete path/anchor, not just the phrase.
261
- // Require at least one of: backtick file path, Entrypoint/caller line, or anchor.
262
- const hasConcreteAnchor =
263
- /`[^`]*\.[a-z]{1,4}`/i.test(evidenceSection) ||
264
- /Entrypoint\/caller\s*:/i.test(evidenceSection) ||
265
- /Route is registered|import.*from|anchor:\s*`/i.test(evidenceSection);
266
- if (!hasConcreteAnchor) {
645
+ const anchorValues = evidenceFieldValues(evidenceSection, ['Entrypoint/caller', 'Anchor']);
646
+ const concreteAnchors = anchorValues.filter(isConcreteReachabilityAnchor);
647
+ if (concreteAnchors.length === 0) {
267
648
  errors.push(`${taskPath}: Runtime reachability verification must reference a concrete file path or anchor (e.g. \`src/...\` or Entrypoint/caller)`);
268
649
  } else {
269
650
  // Cross-check against declared Related Files paths
270
651
  const relatedPaths = new Set(relatedFilesSection(content).rows.map((r) => r.path));
271
- const referencedPaths = [...evidenceSection.matchAll(/`([^`]*\.[a-z0-9]{1,4})`/gi)].map((m) => m[1].replace(/^\.\//, ''));
652
+ const referencedPaths = concreteAnchors
653
+ .map((anchor) => anchor.replace(/`/g, '').replace(/^\.\//, ''))
654
+ .filter((anchor) => /[/\\.]|^[A-Za-z0-9_-]+\.[A-Za-z0-9]+$/.test(anchor));
272
655
  // At least one referenced path should correspond to a declared Related Files entry (or be clearly external)
273
656
  if (referencedPaths.length > 0 && relatedPaths.size > 0) {
274
657
  const overlaps = referencedPaths.some((p) => [...relatedPaths].some((rp) => p === rp || p.endsWith(rp) || rp.endsWith(p) || p.includes(rp.split('/').pop())));
275
- if (!overlaps && !/Entrypoint\/caller/i.test(evidenceSection)) {
658
+ if (!overlaps && !/\b(?:external|later integration task)\b/i.test(evidenceSection)) {
276
659
  errors.push(`${taskPath}: Runtime reachability verification references no Related Files path — must anchor to a declared file`);
277
660
  }
278
661
  }
@@ -281,6 +664,29 @@ function validateTaskSections(taskPath, content, errors) {
281
664
  }
282
665
  }
283
666
 
667
+ function taskDeclaresParallel(content, taskPath, errors) {
668
+ const steps = extractSection(content, 'Changes')
669
+ || extractSection(content, 'Steps')
670
+ || extractSection(content, 'Implementation Steps')
671
+ || '';
672
+ const actionable = steps.split('\n').filter((line) => /^\s*[-*+]\s+\[[ xX]\]\s+/i.test(line));
673
+ const markedIndexes = [];
674
+ actionable.forEach((line, index) => {
675
+ if (/\(P\)/i.test(line)) markedIndexes.push(index);
676
+ });
677
+ if (markedIndexes.length > 1) {
678
+ errors.push(`${taskPath}: task-level (P) marker must appear exactly once`);
679
+ }
680
+ if (markedIndexes.some((index) => index !== 0)) {
681
+ errors.push(`${taskPath}: task-level (P) marker must be on the first actionable Steps checkbox`);
682
+ }
683
+ if (markedIndexes.length > 0
684
+ && !/^\s*[-*+]\s+\[[ xX]\]\s+(?:\d+(?:\.\d+)?\s+)?\(P\)\s+\S/i.test(actionable[markedIndexes[0]])) {
685
+ errors.push(`${taskPath}: (P) must follow the optional step number on an actionable checkbox`);
686
+ }
687
+ return markedIndexes.length > 0;
688
+ }
689
+
284
690
  /**
285
691
  * Task files are created from the scaffold template (the scaffold-guard hook
286
692
  * forces creation through it), so every task starts as a stub full of `{{...}}`
@@ -298,11 +704,168 @@ function validateTaskPlaceholders(taskPath, content, errors, warnings) {
298
704
  if (stub) {
299
705
  errors.push(`${taskPath}: unfilled scaffold placeholder ${stub[0]} — task stub was not completed`);
300
706
  }
707
+ const bracket = content.match(SPEC_BRACKET_PLACEHOLDER_RE);
708
+ if (bracket) {
709
+ errors.push(`${taskPath}: unresolved square-bracket placeholder ${bracket[0]}`);
710
+ }
301
711
  if (/\.\.\.\//.test(content)) {
302
712
  warnings.push(`${taskPath}: contains a '.../' path placeholder — replace with a concrete path`);
303
713
  }
304
714
  }
305
715
 
716
+ function markdownHeaders(content, name) {
717
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
718
+ return [...content.matchAll(new RegExp(`^\\*\\*${escaped}:\\*\\*\\s*(.*?)\\s*$`, 'gim'))]
719
+ .map((match) => match[1].trim());
720
+ }
721
+
722
+ function expectedTaskId(taskPath) {
723
+ return taskPath.match(TASK_IDENTITY_RE)?.[1] || null;
724
+ }
725
+
726
+ function validateTaskIdentity(taskPath, content, entry, errors) {
727
+ const expected = expectedTaskId(taskPath);
728
+ if (!expected) return;
729
+ if (entry?.id !== expected) {
730
+ errors.push(`${taskPath}: task_registry id must match path-derived id ${expected} (got ${String(entry?.id)})`);
731
+ }
732
+ const headings = [...content.matchAll(/^#\s+Task\s+(R\d+-\d{2})\s*:/gim)].map((match) => match[1].toUpperCase());
733
+ if (headings.length !== 1) {
734
+ errors.push(`${taskPath}: canonical task heading must appear exactly once`);
735
+ } else if (headings[0] !== expected) {
736
+ errors.push(`${taskPath}: Markdown heading id ${headings[0]} must match path-derived id ${expected}`);
737
+ }
738
+ }
739
+
740
+ function isIsoTimestamp(value) {
741
+ return typeof value === 'string'
742
+ && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(value)
743
+ && Number.isFinite(Date.parse(value));
744
+ }
745
+
746
+ function validateTaskLifecycle(taskPath, entry, errors) {
747
+ if (!isPlainObject(entry) || !TASK_STATUS_VALUES.has(entry.status)) return;
748
+ const label = `spec.json.task_registry.${taskPath}`;
749
+ const blocker = entry.blocker;
750
+ if (blocker !== null && (typeof blocker !== 'string' || blocker.trim() === '')) {
751
+ errors.push(`${label}.blocker: must be null or a non-empty string`);
752
+ }
753
+ for (const field of ['started_at', 'completed_at', 'last_updated_at']) {
754
+ if (entry[field] !== null && !isIsoTimestamp(entry[field])) {
755
+ errors.push(`${label}.${field}: must be null or an ISO 8601 timestamp`);
756
+ }
757
+ }
758
+
759
+ if (entry.status === 'pending') {
760
+ if (blocker !== null) errors.push(`${label}: pending status requires blocker null`);
761
+ if (entry.started_at !== null || entry.completed_at !== null) {
762
+ errors.push(`${label}: pending status requires started_at and completed_at null`);
763
+ }
764
+ } else if (entry.status === 'in_progress') {
765
+ if (blocker !== null) errors.push(`${label}: in_progress status requires blocker null`);
766
+ if (!isIsoTimestamp(entry.started_at) || !isIsoTimestamp(entry.last_updated_at)) {
767
+ errors.push(`${label}: in_progress status requires started_at and last_updated_at timestamps`);
768
+ } else if (Date.parse(entry.last_updated_at) < Date.parse(entry.started_at)) {
769
+ errors.push(`${label}: in_progress timestamps must satisfy started_at <= last_updated_at`);
770
+ }
771
+ if (entry.completed_at !== null) errors.push(`${label}: in_progress status requires completed_at null`);
772
+ } else if (entry.status === 'blocked') {
773
+ if (typeof blocker !== 'string' || blocker.trim() === '') {
774
+ errors.push(`${label}: blocked status requires a non-empty blocker`);
775
+ }
776
+ if (!isIsoTimestamp(entry.last_updated_at)) {
777
+ errors.push(`${label}: blocked status requires last_updated_at timestamp`);
778
+ } else if (isIsoTimestamp(entry.started_at)
779
+ && Date.parse(entry.last_updated_at) < Date.parse(entry.started_at)) {
780
+ errors.push(`${label}: started blocked timestamps must satisfy started_at <= last_updated_at`);
781
+ }
782
+ if (entry.completed_at !== null) errors.push(`${label}: blocked status requires completed_at null`);
783
+ } else if (entry.status === 'done') {
784
+ if (blocker !== null) errors.push(`${label}: done status requires blocker null`);
785
+ if (![entry.started_at, entry.completed_at, entry.last_updated_at].every(isIsoTimestamp)) {
786
+ errors.push(`${label}: done status requires started_at, completed_at, and last_updated_at timestamps`);
787
+ } else if (
788
+ Date.parse(entry.completed_at) < Date.parse(entry.started_at)
789
+ || Date.parse(entry.last_updated_at) < Date.parse(entry.completed_at)
790
+ ) {
791
+ errors.push(`${label}: done timestamps must satisfy started_at <= completed_at <= last_updated_at`);
792
+ }
793
+ }
794
+ }
795
+
796
+ function validateTaskDependencyHeader(taskPath, content, entry, specReady, errors) {
797
+ const registryDependencies = Array.isArray(entry?.dependencies) ? entry.dependencies : [];
798
+ const headers = markdownHeaders(content, 'Dependencies');
799
+ if (headers.length > 1) {
800
+ errors.push(`${taskPath}: Dependencies header must appear exactly once`);
801
+ }
802
+ let raw = headers[0];
803
+ if (taskFormat(content) === 'v2') {
804
+ const section = extractSection(content, 'Dependencies') || '';
805
+ const values = section.split('\n')
806
+ .map((line) => line.trim().replace(/^[-*+]\s*/, '').replace(/^`|`$/g, '').trim())
807
+ .filter(Boolean);
808
+ raw = values.length === 1 && /^(?:none|n\/a)$/i.test(values[0])
809
+ ? values[0]
810
+ : values.join(',');
811
+ }
812
+ if (raw === undefined) {
813
+ if (registryDependencies.length > 0 || specReady) {
814
+ errors.push(`${taskPath}: missing Dependencies header; required for dependency parity before readiness`);
815
+ }
816
+ return;
817
+ }
818
+
819
+ let markdownDependencies = [];
820
+ if (!/^(?:none|n\/a)$/i.test(raw)) {
821
+ markdownDependencies = raw.split(',').map((dependency) => dependency.trim().replace(/^`|`$/g, ''));
822
+ const seen = new Set();
823
+ for (const dependency of markdownDependencies) {
824
+ if (!TASK_PATH_RE.test(dependency)) {
825
+ errors.push(`${taskPath}: Dependencies header contains invalid task path ${dependency || '(empty)'}`);
826
+ } else if (dependency === taskPath) {
827
+ errors.push(`${taskPath}: Dependencies header cannot contain itself`);
828
+ } else if (seen.has(dependency)) {
829
+ errors.push(`${taskPath}: Dependencies header contains duplicate dependency ${dependency}`);
830
+ }
831
+ seen.add(dependency);
832
+ }
833
+ }
834
+
835
+ const registrySorted = [...registryDependencies].sort();
836
+ const markdownSorted = [...markdownDependencies].sort();
837
+ if (JSON.stringify(registrySorted) !== JSON.stringify(markdownSorted)) {
838
+ errors.push(
839
+ `${taskPath}: dependency drift between spec.json task_registry ${JSON.stringify(registrySorted)} ` +
840
+ `and Markdown Dependencies header ${JSON.stringify(markdownSorted)}`,
841
+ );
842
+ }
843
+ }
844
+
845
+ function validateTaskStatusHeader(taskPath, content, entry, specReady, errors) {
846
+ const headers = markdownHeaders(content, 'Status');
847
+ if (headers.length > 1) {
848
+ errors.push(`${taskPath}: Status header must appear exactly once`);
849
+ }
850
+ const status = headers[0];
851
+ if (status === undefined) {
852
+ errors.push(`${taskPath}: missing Status header required for registry parity`);
853
+ return;
854
+ }
855
+ if (!TASK_STATUS_VALUES.has(status)) {
856
+ errors.push(`${taskPath}: Status must be one of ${[...TASK_STATUS_VALUES].join(', ')} (got ${status})`);
857
+ }
858
+ if (specReady && status === 'blocked') {
859
+ errors.push(`${taskPath}: Status cannot be blocked while ready_for_implementation is true`);
860
+ }
861
+ if (typeof entry?.status === 'string' && status !== entry.status) {
862
+ errors.push(
863
+ `${taskPath}: status drift between spec.json task_registry ${entry.status} ` +
864
+ `and Markdown Status header ${status}`,
865
+ );
866
+ }
867
+ }
868
+
306
869
  /**
307
870
  * Each phase completion must carry its own timestamp. Reusing `timestamps.init`
308
871
  * for a later phase is forbidden (SKILL.md spec.json Update Rules). This used to
@@ -310,9 +873,23 @@ function validateTaskPlaceholders(taskPath, content, errors, warnings) {
310
873
  */
311
874
  function validateTimestamps(spec, errors) {
312
875
  const ts = spec.timestamps;
313
- if (!ts || typeof ts !== 'object') return;
876
+ for (const field of ['created_at', 'updated_at']) {
877
+ if (Object.prototype.hasOwnProperty.call(spec, field) && !isIsoTimestamp(spec[field])) {
878
+ errors.push(`spec.json.${field}: must be an ISO 8601 timestamp`);
879
+ }
880
+ }
881
+ if (ts === undefined) return;
882
+ if (!isPlainObject(ts)) {
883
+ errors.push('spec.json.timestamps: must be an object when present');
884
+ return;
885
+ }
886
+ for (const [field, value] of Object.entries(ts)) {
887
+ if (value !== null && !isIsoTimestamp(value)) {
888
+ errors.push(`spec.json.timestamps.${field}: must be null or an ISO 8601 timestamp`);
889
+ }
890
+ }
314
891
  const init = ts.init;
315
- if (!init) return;
892
+ if (!isIsoTimestamp(init)) return;
316
893
 
317
894
  for (const phase of ['requirements_done', 'design_done', 'tasks_done']) {
318
895
  if (ts[phase] && ts[phase] === init) {
@@ -324,6 +901,55 @@ function validateTimestamps(spec, errors) {
324
901
  }
325
902
  }
326
903
 
904
+ function validateFinalLifecycleTimestamps(spec, taskFiles, context, errors) {
905
+ if (spec.ready_for_implementation !== true) return;
906
+ const ts = isPlainObject(spec.timestamps) ? spec.timestamps : {};
907
+ const required = ['init', 'requirements_done', 'design_done', 'validation_done'];
908
+ if (taskFiles.length > 0) required.push('tasks_done');
909
+ if (explicitResearchPath(spec) === 'research.md') required.push('research_done');
910
+ for (const field of required) {
911
+ if (!isIsoTimestamp(ts[field])) {
912
+ errors.push(`spec.json.timestamps.${field}: ready handoff requires an ISO 8601 timestamp`);
913
+ }
914
+ }
915
+ for (const field of ['created_at', 'updated_at']) {
916
+ if (!isIsoTimestamp(spec[field])) {
917
+ errors.push(`spec.json.${field}: ready handoff requires an ISO 8601 timestamp`);
918
+ }
919
+ }
920
+
921
+ if (![spec.created_at, ts.init, ts.requirements_done, ts.design_done, ts.validation_done, spec.updated_at]
922
+ .every(isIsoTimestamp)) return;
923
+ const ordered = [
924
+ ['created_at', spec.created_at],
925
+ ['timestamps.init', ts.init],
926
+ ['timestamps.requirements_done', ts.requirements_done],
927
+ ...(isIsoTimestamp(ts.research_done) ? [['timestamps.research_done', ts.research_done]] : []),
928
+ ['timestamps.design_done', ts.design_done],
929
+ ...(isIsoTimestamp(ts.tasks_done) ? [['timestamps.tasks_done', ts.tasks_done]] : []),
930
+ ...(isIsoTimestamp(ts.review_done) ? [['timestamps.review_done', ts.review_done]] : []),
931
+ ['timestamps.validation_done', ts.validation_done],
932
+ ];
933
+ for (let index = 1; index < ordered.length; index += 1) {
934
+ if (Date.parse(ordered[index][1]) < Date.parse(ordered[index - 1][1])) {
935
+ errors.push(
936
+ `spec.json final lifecycle timestamps must be ordered; ${ordered[index][0]} precedes ${ordered[index - 1][0]}`,
937
+ );
938
+ }
939
+ }
940
+ if (Date.parse(spec.updated_at) !== Date.parse(ts.validation_done)) {
941
+ errors.push('spec.json.updated_at must describe the same final state as timestamps.validation_done');
942
+ }
943
+ const lastValidatedAt = spec.validation?.last_validated_at;
944
+ if (lastValidatedAt !== undefined && lastValidatedAt !== null) {
945
+ if (!isIsoTimestamp(lastValidatedAt)) {
946
+ errors.push('spec.json.validation.last_validated_at: must be null or an ISO 8601 timestamp');
947
+ } else if (Date.parse(lastValidatedAt) !== Date.parse(ts.validation_done)) {
948
+ errors.push('spec.json.validation.last_validated_at must describe the same final state as timestamps.validation_done');
949
+ }
950
+ }
951
+ }
952
+
327
953
  /** Normalize a fenced code block body for byte-comparison: trim + collapse
328
954
  * trailing whitespace per line + drop blank edges. Keeps inner structure so a
329
955
  * real field rename (user_name vs userName) still differs. */
@@ -341,11 +967,15 @@ function normalizeBlock(body) {
341
967
  * Returns a Map<name, normalizedBody>. Empty when the spec uses no markers —
342
968
  * which makes the whole cross-layer check opt-in (no effect on legacy specs).
343
969
  */
344
- function extractContractDefs(designText) {
970
+ function extractContractDefs(designText, label, errors) {
345
971
  const defs = new Map();
346
972
  const re = /<!--\s*contract:([A-Za-z0-9_.-]+)\s*-->\s*\n```[^\n]*\n([\s\S]*?)\n```/g;
347
973
  let match;
348
974
  while ((match = re.exec(designText)) !== null) {
975
+ if (defs.has(match[1])) {
976
+ errors.push(`${label}: duplicate canonical contract definition "${match[1]}"`);
977
+ continue;
978
+ }
349
979
  defs.set(match[1], normalizeBlock(match[2]));
350
980
  }
351
981
  return defs;
@@ -360,21 +990,80 @@ function extractContractDefs(designText) {
360
990
  * `firstBlock` keeps the legacy fallback for single-contract tasks that copy
361
991
  * the block without repeating the marker.
362
992
  */
363
- function extractTaskContracts(taskText) {
993
+ function extractTaskContracts(taskText, taskPath, errors) {
364
994
  const names = [];
365
- const nameLine = taskText.match(/^\s*Contracts:\s*([^\n]+)$/im);
366
- if (nameLine) {
995
+ const nameLines = [...taskText.matchAll(/^\s*Contracts:\s*([^\n]+)$/gim)];
996
+ if (nameLines.length > 1) {
997
+ errors.push(`${taskPath}: Contracts declaration must appear at most once`);
998
+ }
999
+ const seenNames = new Set();
1000
+ for (const nameLine of nameLines) {
367
1001
  for (const token of nameLine[1].split(',')) {
368
1002
  const name = token.trim();
369
- if (name) names.push(name);
1003
+ if (!name) continue;
1004
+ if (seenNames.has(name)) {
1005
+ errors.push(`${taskPath}: Contracts declaration contains duplicate name "${name}"`);
1006
+ continue;
1007
+ }
1008
+ seenNames.add(name);
1009
+ names.push(name);
370
1010
  }
371
1011
  }
372
- const blocks = extractContractDefs(taskText); // same marker+fence grammar as design.md
1012
+ const blocks = extractContractDefs(taskText, taskPath, errors); // same marker+fence grammar as design.md
373
1013
  const blockMatch = taskText.match(/```[^\n]*\n([\s\S]*?)\n```/);
374
1014
  const firstBlock = blockMatch ? normalizeBlock(blockMatch[1]) : null;
375
1015
  return { names, blocks, firstBlock };
376
1016
  }
377
1017
 
1018
+ function implementationObligationClosure(content, label, errors) {
1019
+ const allIds = [];
1020
+ const re = /<!--\s*implementation-obligation:([a-z0-9]+(?:[._-][a-z0-9]+)*)\s*-->/gi;
1021
+ let match;
1022
+ while ((match = re.exec(content)) !== null) {
1023
+ allIds.push(match[1].toLowerCase());
1024
+ }
1025
+ const counts = new Map();
1026
+ for (const id of allIds) counts.set(id, (counts.get(id) || 0) + 1);
1027
+ for (const [id, count] of counts) {
1028
+ if (count > 1) errors.push(`${label}: duplicate implementation obligation marker ${id}`);
1029
+ }
1030
+
1031
+ const closureCount = headingCount(content, 'Execution Closure');
1032
+ const section = closureCount === 1 ? (extractSection(content, 'Execution Closure') || '') : '';
1033
+ const closureIds = [];
1034
+ const blocks = new Map();
1035
+ const closureRe = /<!--\s*implementation-obligation:([a-z0-9]+(?:[._-][a-z0-9]+)*)\s*-->/gi;
1036
+ const markers = [...section.matchAll(closureRe)];
1037
+ for (const [index, marker] of markers.entries()) {
1038
+ const id = marker[1].toLowerCase();
1039
+ closureIds.push(id);
1040
+ const blockStart = marker.index + marker[0].length;
1041
+ const blockEnd = markers[index + 1]?.index ?? section.length;
1042
+ if (!blocks.has(id)) blocks.set(id, section.slice(blockStart, blockEnd).trim());
1043
+ }
1044
+ if (allIds.length > 0 && closureCount !== 1) {
1045
+ errors.push(`${label}: implementation obligation markers require exactly one Execution Closure section`);
1046
+ } else if (allIds.length > closureIds.length) {
1047
+ const closureCounts = new Map();
1048
+ for (const id of closureIds) closureCounts.set(id, (closureCounts.get(id) || 0) + 1);
1049
+ for (const [id, count] of counts) {
1050
+ if ((closureCounts.get(id) || 0) < count) {
1051
+ errors.push(`${label}: implementation obligation marker ${id} must be inside Execution Closure`);
1052
+ }
1053
+ }
1054
+ }
1055
+ const notApplicable = closureCount === 1
1056
+ && closureIds.length === 0
1057
+ && isJustifiedNotApplicable(section.trim());
1058
+ return {
1059
+ ids: [...new Set(closureIds)],
1060
+ section,
1061
+ headingCount: closureCount,
1062
+ blocks,
1063
+ notApplicable,
1064
+ };
1065
+ }
1066
+
378
1067
  const RELATED_FILE_ACTIONS = new Set(['create', 'modify', 'delete', 'read']);
379
1068
 
380
1069
  function relatedFilesSection(content) {
@@ -414,6 +1103,86 @@ function validateRelatedFiles(taskPath, content, errors) {
414
1103
  }
415
1104
  }
416
1105
 
1106
+ function parseMarkdownTable(section, expectedHeaders) {
1107
+ if (typeof section !== 'string') return [];
1108
+ const lines = section.split('\n');
1109
+ for (let index = 0; index + 1 < lines.length; index += 1) {
1110
+ if (!/^\s*\|/.test(lines[index]) || !/^\s*\|(?:\s*:?-{3,}:?\s*\|)+\s*$/.test(lines[index + 1])) continue;
1111
+ const headers = lines[index].split('|').slice(1, -1).map((cell) => cell.trim().toLowerCase());
1112
+ if (JSON.stringify(headers) !== JSON.stringify(expectedHeaders.map((header) => header.toLowerCase()))) continue;
1113
+ const rows = [];
1114
+ for (let rowIndex = index + 2; rowIndex < lines.length && /^\s*\|/.test(lines[rowIndex]); rowIndex += 1) {
1115
+ const cells = lines[rowIndex].split('|').slice(1, -1)
1116
+ .map((cell) => cell.trim().replace(/^`|`$/g, '').trim());
1117
+ if (cells.some(Boolean)) rows.push(cells);
1118
+ }
1119
+ return rows;
1120
+ }
1121
+ return [];
1122
+ }
1123
+
1124
+ function typedAnchors(content, label, namespace, errors) {
1125
+ const section = extractSection(content, namespace === 'design' ? 'Typed Anchors' : 'Scope and Typed Anchors') || '';
1126
+ const rows = parseMarkdownTable(section, ['ID', 'Type', 'Target', 'Role']);
1127
+ if (rows.length === 0) {
1128
+ const consumesDesign = namespace === 'task'
1129
+ && sectionFieldValues(section, ['Canonical design anchors consumed']).join(' ').match(/\bA-D-\d{2}\b/);
1130
+ if (!consumesDesign) errors.push(`${label}: typed anchor table ID/Type/Target/Role is required unless the task only consumes canonical design anchors`);
1131
+ return [];
1132
+ }
1133
+ const taskId = namespace === 'task' ? expectedTaskId(label) : null;
1134
+ const namespacePattern = namespace === 'design'
1135
+ ? /^A-D-\d{2}$/
1136
+ : new RegExp(`^A-${taskId || 'INVALID'}-\\d{2}$`);
1137
+ return rows.map(([id = '', rawType = '', target = '', role = '']) => {
1138
+ const type = rawType.toLowerCase();
1139
+ if (!ANCHOR_TYPES.has(type)) {
1140
+ errors.push(`${label}: typed anchor ${id || '(missing id)'} has unknown Type ${rawType || '(empty)'}`);
1141
+ }
1142
+ if (!namespacePattern.test(id)) {
1143
+ errors.push(`${label}: typed anchor ${id || '(missing id)'} has invalid ${namespace} namespace`);
1144
+ }
1145
+ if (!target || hasSpecPlaceholders(target)) {
1146
+ errors.push(`${label}: typed anchor ${id || '(missing id)'} requires a concrete Target`);
1147
+ }
1148
+ if (!role || hasSpecPlaceholders(role)) {
1149
+ errors.push(`${label}: typed anchor ${id || '(missing id)'} requires a concrete Role`);
1150
+ }
1151
+ return { id, type, target, role, label, namespace };
1152
+ });
1153
+ }
1154
+
1155
+ function validateTypedAnchorInventory(designText, taskContents, errors) {
1156
+ const designAnchors = typedAnchors(designText, 'design.md', 'design', errors);
1157
+ const allAnchors = [...designAnchors];
1158
+ for (const [taskPath, content] of taskContents) {
1159
+ if (taskFormat(content) === 'v2') allAnchors.push(...typedAnchors(content, taskPath, 'task', errors));
1160
+ }
1161
+ const byId = new Map();
1162
+ const designByTarget = new Map(designAnchors.map((anchor) => [`${anchor.type}\0${anchor.target}`, anchor]));
1163
+ for (const anchor of allAnchors) {
1164
+ if (byId.has(anchor.id)) {
1165
+ errors.push(`${anchor.label}: duplicate typed anchor ID ${anchor.id}; first declared in ${byId.get(anchor.id).label}`);
1166
+ } else byId.set(anchor.id, anchor);
1167
+ if (anchor.namespace === 'task') {
1168
+ const canonical = designByTarget.get(`${anchor.type}\0${anchor.target}`);
1169
+ if (canonical) {
1170
+ errors.push(`${anchor.label}: typed anchor ${anchor.id} duplicates canonical design target ${canonical.id}; reference the design anchor ID instead`);
1171
+ }
1172
+ }
1173
+ }
1174
+ for (const [taskPath, content] of taskContents) {
1175
+ if (taskFormat(content) !== 'v2') continue;
1176
+ for (const reference of content.match(/\bA-D-\d{2}\b/g) || []) {
1177
+ if (!byId.has(reference)) errors.push(`${taskPath}: dangling canonical design anchor reference ${reference}`);
1178
+ }
1179
+ }
1180
+ for (const reference of designText.match(/\bA-D-\d{2}\b/g) || []) {
1181
+ if (!byId.has(reference)) errors.push(`design.md: dangling canonical design anchor reference ${reference}`);
1182
+ }
1183
+ return { anchors: allAnchors, designAnchors, byId };
1184
+ }
1185
+
417
1186
  function validateArtifactDeclaration(taskPath, entry, errors) {
418
1187
  if (!Object.prototype.hasOwnProperty.call(entry || {}, 'artifacts')) return;
419
1188
  const artifacts = entry.artifacts;
@@ -445,13 +1214,21 @@ function workflowPolicyContext(spec, errors) {
445
1214
  const result = POLICY.validateWorkflowPolicySnapshot(spec.workflow_policy);
446
1215
  if (!result.valid) {
447
1216
  for (const error of result.errors) errors.push(error);
448
- return { explicit: true, policy: null, bounded: false, strict: false };
1217
+ return { explicit: true, policy: null, legacy: false, taskRequired: false, strict: false };
1218
+ }
1219
+ let policy;
1220
+ try {
1221
+ policy = POLICY.readWorkflowPolicySnapshot(spec);
1222
+ } catch (error) {
1223
+ errors.push(`spec.json.workflow_policy: shared policy adapter failed (${error.message})`);
1224
+ return { explicit: true, policy: null, legacy: false, taskRequired: false, strict: false };
449
1225
  }
450
1226
  return {
451
1227
  explicit: true,
452
- policy: spec.workflow_policy,
453
- bounded: spec.workflow_policy.artifact_profile === 'bounded',
454
- strict: spec.workflow_policy.artifact_profile === 'strict',
1228
+ policy,
1229
+ legacy: spec.workflow_policy.version === '1',
1230
+ taskRequired: spec.coordination?.tasks_required === true,
1231
+ strict: policy.assurance_level === 'Strict',
455
1232
  };
456
1233
  }
457
1234
 
@@ -461,15 +1238,11 @@ function workflowPolicyContext(spec, errors) {
461
1238
  ? 'spec.json.workflow_policy: missing persisted snapshot; design_context.execution_tier is a read-only legacy adapter and cannot establish workflow authority or readiness'
462
1239
  : 'spec.json.workflow_policy: missing persisted snapshot; the current spec boundary requires an explicit workflow_policy',
463
1240
  );
464
- return { explicit: false, policy: null, bounded: false, strict: false };
1241
+ return { explicit: false, policy: null, legacy: false, taskRequired: false, strict: false };
465
1242
  }
466
1243
 
467
- function validateFeatureReceipt(spec, context, errors, receiptArtifact) {
468
- if (!context.explicit || !context.bounded) return;
469
- if (!receiptArtifact) {
470
- errors.push(`${FEATURE_RECEIPT_FILE}: required by bounded Standard workflow policy`);
471
- return;
472
- }
1244
+ function validateFeatureReceipt(spec, context, errors, warnings, receiptArtifact) {
1245
+ if (!receiptArtifact) return;
473
1246
  let body;
474
1247
  try {
475
1248
  body = fs.readFileSync(receiptArtifact.path, 'utf8');
@@ -477,32 +1250,108 @@ function validateFeatureReceipt(spec, context, errors, receiptArtifact) {
477
1250
  errors.push(`${FEATURE_RECEIPT_FILE}: cannot be read (${error.message})`);
478
1251
  return;
479
1252
  }
480
- // A spec-ready artifact is a design boundary, not execution closeout. Keep a
481
- // pending receipt explicit. Feature receipts are informational and never own
482
- // completion authority; task Evidence receipts are the only closeout source.
483
- if (/^\s*Verification:\s*PENDING\s*$/im.test(body)) return;
484
- errors.push(`${FEATURE_RECEIPT_FILE}: informational only; keep Verification: PENDING and use task Evidence for completion authority`);
1253
+ if (/^\s*Verification:\s*PENDING\s*$/im.test(body)) {
1254
+ if (context.legacy) {
1255
+ warnings.push(`${FEATURE_RECEIPT_FILE}: legacy v1 PENDING receipt is read-compatible only and is not readiness proof`);
1256
+ return;
1257
+ }
1258
+ errors.push(`${FEATURE_RECEIPT_FILE}: premature execution receipt is forbidden in a Specs v2 pre-implementation artifact`);
1259
+ return;
1260
+ }
1261
+ if (spec.status !== 'done') {
1262
+ errors.push(`${FEATURE_RECEIPT_FILE}: completed execution receipt is valid only on terminal status done, never for readiness`);
1263
+ return;
1264
+ }
1265
+ if (!/^\s*Verification:\s*PASS\s*$/im.test(body)) {
1266
+ errors.push(`${FEATURE_RECEIPT_FILE}: completed taskless proof requires literal Verification: PASS`);
1267
+ }
1268
+ if (!/^\s*Status:\s*done\s*$/im.test(body)) {
1269
+ errors.push(`${FEATURE_RECEIPT_FILE}: completed proof and spec.json must both use status done`);
1270
+ }
1271
+ const commands = evidenceFieldValues(body, ['Command', 'Commands', 'Command(s)']);
1272
+ if (!commands.some(isExecutableCommand)) {
1273
+ errors.push(`${FEATURE_RECEIPT_FILE}: completed proof requires an executable Command`);
1274
+ }
1275
+ const expected = evidenceFieldValues(body, ['Expected result', 'Expected proof', 'Expected']);
1276
+ if (!expected.some(hasObservableProof)) {
1277
+ errors.push(`${FEATURE_RECEIPT_FILE}: completed proof requires an observable expected result`);
1278
+ }
1279
+ const observed = evidenceFieldValues(body, ['Observed result', 'Result', 'Observed proof']);
1280
+ if (!observed.some(hasObservableProof)) {
1281
+ errors.push(`${FEATURE_RECEIPT_FILE}: completed proof requires an observable result`);
1282
+ }
1283
+ const artifacts = evidenceFieldValues(
1284
+ body,
1285
+ ['Artifact/runtime proof', 'Artifact / runtime proof', 'Artifact proof', 'Runtime proof', 'Inspect'],
1286
+ );
1287
+ if (!artifacts.some((value) => isConcreteReachabilityAnchor(value) || hasObservableProof(value))) {
1288
+ errors.push(`${FEATURE_RECEIPT_FILE}: completed proof requires concrete artifact or runtime proof`);
1289
+ }
1290
+ const bindingPattern = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i;
1291
+ const base = evidenceFieldValues(body, ['Base'])[0];
1292
+ const head = evidenceFieldValues(body, ['Head'])[0];
1293
+ if (!bindingPattern.test(base || '') || !bindingPattern.test(head || '') || base === head) {
1294
+ errors.push(`${FEATURE_RECEIPT_FILE}: completed proof requires distinct 40- or 64-hex Base and Head bindings`);
1295
+ }
485
1296
  }
486
1297
 
487
- const SPEC_PLACEHOLDER_RE = /\{\{[^}\n]+\}\}|<[^>\n]+>|\b(?:TBD|TODO|N\/A|NA|NONE|UNKNOWN|PENDING|PLACEHOLDER|REPLACE_ME)\b|\.{3,}/i;
1298
+ const SPEC_PLACEHOLDER_RE = /\{\{[^}\n]+\}\}|<[^>\n]+>|(?<![A-Za-z0-9_./-])(?:TBD|TODO|N\/A|NA|NONE|UNKNOWN|PENDING|PLACEHOLDER|REPLACE_ME)(?![A-Za-z0-9_./-])|\.{3,}/i;
1299
+ const SPEC_BRACKET_PLACEHOLDER_RE = /\[(?:specific(?:\s+[a-z][a-z0-9 /_-]{0,60})?|target\s+users?|component\s+name)\](?!\s*\()/i;
488
1300
  const SPEC_TEMPLATE_GUIDANCE_RE = /\b(?:to be filled|filled by (?:the )?(?:feature owner|user)|fill (?:this|in)|replace (?:this|with)|add (?:the )?real)\b/i;
489
1301
 
490
1302
  function hasSpecPlaceholders(content) {
491
- return SPEC_PLACEHOLDER_RE.test(content) || SPEC_TEMPLATE_GUIDANCE_RE.test(content);
1303
+ return SPEC_PLACEHOLDER_RE.test(content)
1304
+ || SPEC_BRACKET_PLACEHOLDER_RE.test(content)
1305
+ || SPEC_TEMPLATE_GUIDANCE_RE.test(content);
492
1306
  }
493
1307
 
494
- function validateBoundedReadiness(spec, requirementsText, designText, errors) {
495
- if (spec.ready_for_implementation !== true) return;
1308
+ function validateRequirementDialect(requirementsText, errors) {
1309
+ const legacy = requirementsText.match(/\bREQ-\d+\b/i);
1310
+ if (legacy) {
1311
+ errors.push(
1312
+ `requirements.md: ${legacy[0].toUpperCase()} is not a canonical requirement id; ` +
1313
+ 'use Requirement N/RN with acceptance criteria RN.M (task mappings use N.M)',
1314
+ );
1315
+ }
1316
+ }
1317
+
1318
+ function validateSemanticReadiness(spec, requirementsText, designText, context, errors) {
1319
+ if (
1320
+ spec.ready_for_implementation !== true
1321
+ || !context.explicit
1322
+ || context.policy?.lane === 'Direct'
1323
+ ) return;
1324
+ const profile = context.policy?.lane || 'non-Direct';
496
1325
 
497
1326
  const source = spec.scope_lock?.source;
498
1327
  if (typeof source !== 'string' || source.trim() === '' || hasSpecPlaceholders(source)) {
499
- errors.push('spec.json.scope_lock.source: Standard bounded readiness requires a concrete scope source');
1328
+ errors.push(`spec.json.scope_lock.source: ${profile} readiness requires a concrete scope source`);
500
1329
  }
501
1330
  if (hasSpecPlaceholders(requirementsText)) {
502
- errors.push('requirements.md: Standard bounded readiness rejects placeholders');
1331
+ errors.push(`requirements.md: ${profile} readiness rejects placeholders`);
1332
+ }
1333
+ let placeholderDesignText = designText;
1334
+ if (context.policy?.lane === 'Critical') {
1335
+ const closure = extractSection(designText, 'Execution Closure');
1336
+ if (closure !== null && isJustifiedNotApplicable(closure.trim())) {
1337
+ placeholderDesignText = designText.replace(closure, '');
1338
+ }
1339
+ }
1340
+ if (hasSpecPlaceholders(placeholderDesignText)) {
1341
+ errors.push(`design.md: ${profile} readiness rejects placeholders`);
503
1342
  }
504
- if (hasSpecPlaceholders(designText)) {
505
- errors.push('design.md: Standard bounded readiness rejects placeholders');
1343
+ if (extractRequirementIds(requirementsText).length === 0) {
1344
+ errors.push(`requirements.md: ${profile} readiness requires at least one canonical numeric requirement id (Requirement N or RN)`);
1345
+ }
1346
+ if (extractSubCriteriaIds(requirementsText).length === 0 || !hasTestableAcceptanceCriterion(requirementsText)) {
1347
+ errors.push(
1348
+ `requirements.md: ${profile} readiness requires at least one testable acceptance criterion using RN.M`,
1349
+ );
1350
+ }
1351
+ if (!hasConcreteDesignBoundary(designText)) {
1352
+ errors.push(
1353
+ `design.md: ${profile} readiness requires a grounded path/code identifier plus owned or touched behavior in Architecture, Components and Interfaces, Canonical Contracts & Invariants, or Implementation Boundary`,
1354
+ );
506
1355
  }
507
1356
  }
508
1357
 
@@ -549,6 +1398,7 @@ function validateResearchArtifact(researchArtifact, errors, requireConcrete = tr
549
1398
  return;
550
1399
  }
551
1400
  const research = fs.readFileSync(researchArtifact.path, 'utf8');
1401
+ validateUniqueSectionGroups('research.md', research, [['Evidence Summary']], errors);
552
1402
  const evidence = extractSection(research, 'Evidence Summary');
553
1403
  if (evidence === null) {
554
1404
  errors.push('research.md: missing ## Evidence Summary');
@@ -557,8 +1407,55 @@ function validateResearchArtifact(researchArtifact, errors, requireConcrete = tr
557
1407
  }
558
1408
  }
559
1409
 
1410
+ function groundedResearchEvidence(section, canonicalSpecDir) {
1411
+ if (/https:\/\/[^\s)>]+/i.test(section)) return true;
1412
+ const projectRoot = path.dirname(path.dirname(canonicalSpecDir));
1413
+ for (const match of section.matchAll(/`([^`]+)`/g)) {
1414
+ let target = match[1].trim();
1415
+ if (!target || /\s/.test(target) || path.isAbsolute(target) || /^[A-Za-z]:[\\/]/.test(target)) continue;
1416
+ target = target.split('#')[0].replace(/:\d+(?::\d+)?$/, '');
1417
+ if (unsafeRelatedPath(target)) continue;
1418
+ const resolved = path.resolve(projectRoot, target);
1419
+ if (isPathInside(projectRoot, resolved) && fs.existsSync(resolved)) return true;
1420
+ }
1421
+ return false;
1422
+ }
1423
+
1424
+ function validateResearchArtifact21(researchArtifact, canonicalSpecDir, errors) {
1425
+ const research = fs.readFileSync(researchArtifact.path, 'utf8');
1426
+ const headings = ['Uncertainty', 'Evidence Summary', 'Decision', 'Remaining Gaps'];
1427
+ for (const heading of headings) {
1428
+ const count = headingCount(research, heading);
1429
+ if (count !== 1) errors.push(`research.md: requires exactly one ## ${heading} section`);
1430
+ }
1431
+ const sections = Object.fromEntries(headings.map((heading) => [heading, extractSection(research, heading)]));
1432
+ for (const heading of ['Uncertainty', 'Evidence Summary', 'Decision']) {
1433
+ if (sections[heading] !== null && !hasConcreteResearchEvidence(sections[heading])) {
1434
+ errors.push(`research.md: ${heading} must contain concrete non-placeholder content`);
1435
+ }
1436
+ }
1437
+ if (sections['Evidence Summary'] !== null
1438
+ && hasConcreteResearchEvidence(sections['Evidence Summary'])
1439
+ && !groundedResearchEvidence(sections['Evidence Summary'], canonicalSpecDir)) {
1440
+ errors.push('research.md: Evidence Summary must ground at least one existing repository target or https primary source');
1441
+ }
1442
+ const gaps = sections['Remaining Gaps'];
1443
+ if (gaps !== null) {
1444
+ const semantic = semanticMarkdown(gaps).replace(/^\s*[-*+]\s*/gm, '').trim();
1445
+ const none = /^none\b/i.test(semantic);
1446
+ if (none) {
1447
+ const rationale = semantic.replace(/^none\b\s*(?:[-—:]\s*)?/i, '').trim();
1448
+ if (rationale.length < 12 || !hasConcreteResearchEvidence(rationale)) {
1449
+ errors.push('research.md: Remaining Gaps None requires concrete rationale or evidence');
1450
+ }
1451
+ } else if (!hasConcreteResearchEvidence(gaps)) {
1452
+ errors.push('research.md: Remaining Gaps must contain a concrete gap or None with rationale or evidence');
1453
+ }
1454
+ }
1455
+ }
1456
+
560
1457
  function validateStateTransitions(spec, errors, context = {}) {
561
- // Approval schema v2: generated, agent_validated, user_approved independent.
1458
+ // Canonical approval authority is technical only. rc.3 user_approved is readable but inert.
562
1459
  // Legacy "approved" field is rejected fail-closed with migration guidance.
563
1460
  const approvals = spec.approvals || {};
564
1461
  let hasLegacy = false;
@@ -571,6 +1468,15 @@ function validateStateTransitions(spec, errors, context = {}) {
571
1468
  errors.push(`spec.json.approvals.${stage}: ${LEGACY_APPROVAL_ERROR}`);
572
1469
  hasLegacy = true;
573
1470
  }
1471
+ const keys = Object.keys(approval).sort();
1472
+ const canonical = ['agent_validated', 'generated'];
1473
+ const rc3 = ['agent_validated', 'generated', 'user_approved'];
1474
+ if (JSON.stringify(keys) !== JSON.stringify(canonical) && JSON.stringify(keys) !== JSON.stringify(rc3)) {
1475
+ errors.push(`spec.json.approvals.${stage}: fields must be generated and agent_validated; legacy user_approved is readable but has zero authority`);
1476
+ }
1477
+ for (const key of keys) {
1478
+ if (typeof approval[key] !== 'boolean') errors.push(`spec.json.approvals.${stage}.${key}: must be boolean`);
1479
+ }
574
1480
  // Unsupported/ambiguous: if schema_version missing when approvals use v2 shape, warn but not fail? B2 says fail closed.
575
1481
  // We fail closed when version is unsupported or ambiguous and ready_for_implementation is true.
576
1482
  }
@@ -583,12 +1489,12 @@ function validateStateTransitions(spec, errors, context = {}) {
583
1489
  errors.push(`spec.json.approval_schema_version: unsupported "${spec.approval_schema_version}", expected "${APPROVAL_SCHEMA_VERSION}"`);
584
1490
  }
585
1491
  // If approvals use v2 fields but no schema_version, treat as ambiguous — fail closed when ready flag is set
586
- const usesV2 = Object.values(approvals).some((a) => a && typeof a === 'object' && ('agent_validated' in a || 'user_approved' in a));
1492
+ const usesV2 = Object.values(approvals).some((a) => a && typeof a === 'object' && 'agent_validated' in a);
587
1493
  if (usesV2 && spec.schema_version === undefined && spec.approval_schema_version === undefined) {
588
1494
  // Only warn now; will be error if ready_for_implementation is true (checked below)
589
1495
  // Provide guidance
590
1496
  if (spec.ready_for_implementation === true) {
591
- errors.push(`spec.json.schema_version: missing — spec uses v2 approvals (agent_validated/user_approved) but has no schema_version "${APPROVAL_SCHEMA_VERSION}"`);
1497
+ errors.push(`spec.json.schema_version: missing — spec uses v2 approvals but has no schema_version "${APPROVAL_SCHEMA_VERSION}"`);
592
1498
  }
593
1499
  }
594
1500
 
@@ -598,15 +1504,15 @@ function validateStateTransitions(spec, errors, context = {}) {
598
1504
 
599
1505
  if (spec.ready_for_implementation === true) {
600
1506
  if (hasLegacy) {
601
- errors.push(`spec.json.ready_for_implementation: cannot be true with legacy approval fields — migrate to agent_validated/user_approved`);
1507
+ errors.push('spec.json.ready_for_implementation: cannot be true with legacy approved fields');
602
1508
  }
603
- const stages = context.bounded && !(Array.isArray(spec.task_files) && spec.task_files.length > 0)
604
- ? ['requirements', 'design']
605
- : ['requirements', 'design', 'tasks'];
1509
+ const stages = context.taskRequired
1510
+ ? ['requirements', 'design', 'tasks']
1511
+ : ['requirements', 'design'];
606
1512
  for (const stage of stages) {
607
1513
  const approval = spec.approvals?.[stage];
608
- if (!approval || approval?.generated !== true || approval?.agent_validated !== true || approval?.user_approved !== true) {
609
- errors.push(`spec.json.ready_for_implementation: requires generated and agent_validated and user_approved ${stage} evidence (v2)`);
1514
+ if (!approval || approval?.generated !== true || approval?.agent_validated !== true) {
1515
+ errors.push(`spec.json.ready_for_implementation: requires generated and agent_validated ${stage} evidence (v2)`);
610
1516
  }
611
1517
  }
612
1518
  if (spec.validation?.status === 'in_progress' || spec.validation?.status === 'not-run') {
@@ -615,12 +1521,432 @@ function validateStateTransitions(spec, errors, context = {}) {
615
1521
  }
616
1522
  }
617
1523
 
618
- function validateDependencyTopology(spec, taskFiles, registry, taskRecords, errors) {
619
- const dependencies = new Map(taskFiles.map((taskFile) => [taskFile, new Set(registry?.[taskFile]?.dependencies || [])]));
620
- if (dependencies.size === 0) return;
1524
+ function validateReadinessStatusValues(spec, errors) {
1525
+ if (typeof spec.ready_for_implementation !== 'boolean') {
1526
+ errors.push('spec.json.ready_for_implementation: must be a boolean');
1527
+ }
1528
+ if (typeof spec.status !== 'string' || !SPEC_STATUS_VALUES.has(spec.status)) {
1529
+ errors.push(`spec.json.status: must be one of ${[...SPEC_STATUS_VALUES].join(', ')}`);
1530
+ }
1531
+ if (spec.validation !== undefined && !isPlainObject(spec.validation)) {
1532
+ errors.push('spec.json.validation: must be an object when present');
1533
+ }
1534
+ const validationStatus = isPlainObject(spec.validation) ? spec.validation.status : undefined;
1535
+ if (validationStatus !== undefined && !VALIDATION_STATUS_VALUES.has(validationStatus)) {
1536
+ errors.push(`spec.json.validation.status: must be one of ${[...VALIDATION_STATUS_VALUES].join(', ')}`);
1537
+ }
1538
+ if (spec.ready_for_implementation !== true) return;
1539
+ if (spec.status === 'blocked' || spec.status === 'paused') {
1540
+ errors.push(`spec.json.status: cannot be ${spec.status} while ready_for_implementation is true`);
1541
+ }
1542
+ if (typeof spec.blocker === 'string' && spec.blocker.trim() !== '') {
1543
+ errors.push('spec.json.blocker: must be empty while ready_for_implementation is true');
1544
+ }
1545
+ if (validationStatus !== 'completed') {
1546
+ errors.push('spec.json.ready_for_implementation: requires validation.status completed');
1547
+ }
1548
+ }
621
1549
 
622
- const visiting = new Set();
623
- const visited = new Set();
1550
+ function validateCoreMachineState(spec, taskFiles, errors, { schema21 = false } = {}) {
1551
+ if (!isPlainObject(spec.scope_lock)) {
1552
+ errors.push('spec.json.scope_lock: must be an object, not a boolean or array');
1553
+ }
1554
+ validateTimestamps(spec, errors);
1555
+ validateReadinessStatusValues(spec, errors);
1556
+ if (isIsoTimestamp(spec.created_at) && isIsoTimestamp(spec.updated_at)
1557
+ && Date.parse(spec.updated_at) < Date.parse(spec.created_at)) {
1558
+ errors.push('spec.json lifecycle timestamps must satisfy created_at <= updated_at');
1559
+ }
1560
+ if (schema21 || spec.schema_version === APPROVAL_SCHEMA_VERSION) {
1561
+ const required = [
1562
+ 'schema_version', 'feature_name', 'created_at', 'updated_at', 'status',
1563
+ 'scope_lock', 'authoring', 'coordination', 'validation', 'ready_for_implementation', 'workflow_policy',
1564
+ ];
1565
+ if (!schema21) required.splice(required.indexOf('authoring'), 1);
1566
+ else required.push('language');
1567
+ for (const field of required) if (!Object.prototype.hasOwnProperty.call(spec, field)) {
1568
+ errors.push(`spec.json.${field}: required by schema ${spec.schema_version} machine state`);
1569
+ }
1570
+ if (!isPlainObject(spec.validation)
1571
+ || !Object.prototype.hasOwnProperty.call(spec.validation, 'status')
1572
+ || !Object.prototype.hasOwnProperty.call(spec.validation, 'semantic_review')) {
1573
+ errors.push(`spec.json.validation: schema ${spec.schema_version} requires status and semantic_review`);
1574
+ }
1575
+ }
1576
+
1577
+ if (taskFiles.length === 0) return;
1578
+ const taskFileSet = new Set(taskFiles);
1579
+ if (!Array.isArray(spec.task_files)) errors.push('spec.json.task_files: physical tasks require an array');
1580
+ if (!isPlainObject(spec.task_registry)) {
1581
+ errors.push('spec.json.task_registry: physical tasks require an object keyed by task file path');
1582
+ return;
1583
+ }
1584
+ for (const taskPath of taskFiles) {
1585
+ const entry = spec.task_registry[taskPath];
1586
+ const label = `spec.json.task_registry.${taskPath}`;
1587
+ if (!isPlainObject(entry)) {
1588
+ errors.push(`${label}: must be an object`);
1589
+ continue;
1590
+ }
1591
+ for (const key of REQUIRED_REGISTRY_KEYS) if (!Object.prototype.hasOwnProperty.call(entry, key)) {
1592
+ errors.push(`${label}: missing ${key}`);
1593
+ }
1594
+ if (entry.id !== expectedTaskId(taskPath)) {
1595
+ errors.push(`${label}: id must match path-derived id ${expectedTaskId(taskPath)} (got ${String(entry.id)})`);
1596
+ }
1597
+ if (typeof entry.title !== 'string' || entry.title.trim() === '' || hasSpecPlaceholders(entry.title)) {
1598
+ errors.push(`${label}.title: must be a concrete non-empty string`);
1599
+ }
1600
+ if (!TASK_STATUS_VALUES.has(entry.status)) {
1601
+ errors.push(`${label}.status: must be one of ${[...TASK_STATUS_VALUES].join(', ')}`);
1602
+ }
1603
+ validateTaskLifecycle(taskPath, entry, errors);
1604
+ if (spec.ready_for_implementation === true && entry.status === 'blocked') {
1605
+ errors.push(`${label}.status: cannot be blocked while ready_for_implementation is true`);
1606
+ }
1607
+ if (!Array.isArray(entry.dependencies)) {
1608
+ errors.push(`${label}.dependencies: must be an array`);
1609
+ continue;
1610
+ }
1611
+ const seen = new Set();
1612
+ for (const dependency of entry.dependencies) {
1613
+ if (!taskFileSet.has(dependency)) errors.push(`${label}.dependencies: unknown dependency ${dependency}`);
1614
+ if (dependency === taskPath) errors.push(`${label}.dependencies: cannot contain itself`);
1615
+ if (seen.has(dependency)) errors.push(`${label}.dependencies: duplicate dependency ${dependency}`);
1616
+ seen.add(dependency);
1617
+ }
1618
+ }
1619
+ }
1620
+
1621
+ function meaningfulObligationValue(value) {
1622
+ if (typeof value !== 'string') return false;
1623
+ const text = value.trim();
1624
+ return text.length >= 8
1625
+ && !hasSpecPlaceholders(text)
1626
+ && !/^(?:works?|done|check|verify|test|proof|evidence|state|authority|recovery)$/i.test(text);
1627
+ }
1628
+
1629
+ function normalizeClosureText(value) {
1630
+ return String(value)
1631
+ .toLowerCase()
1632
+ .replace(/[|`*_[\]{}()]/g, ' ')
1633
+ .replace(/\s+/g, ' ')
1634
+ .trim();
1635
+ }
1636
+
1637
+ function closureFieldName(value) {
1638
+ const name = normalizeClosureText(value).replace(/\s*\/\s*/g, ' / ');
1639
+ if (/^(?:obligation ids? \/ )?requirements?$/.test(name)
1640
+ || /^obligation id \/ requirements$/.test(name)) return ['requirements'];
1641
+ if (/^canonical state$/.test(name)) return ['canonical_state'];
1642
+ if (/^authority$/.test(name)) return ['authority'];
1643
+ if (/^(?:crash \/ retry )?recovery$/.test(name)) return ['recovery'];
1644
+ if (/^owner task$/.test(name)) return ['owner_task'];
1645
+ if (/^(?:consumer tasks?|consumers?)(?: \/ dependency order)?$/.test(name)) return ['consumer_tasks'];
1646
+ if (/^verification$/.test(name)) return ['verification'];
1647
+ if (/^evidence$/.test(name)) return ['evidence'];
1648
+ if (/^verification \/ evidence$/.test(name)) return ['verification', 'evidence'];
1649
+ return [];
1650
+ }
1651
+
1652
+ function appendClosureField(fields, label, value) {
1653
+ for (const key of closureFieldName(label)) {
1654
+ if (!fields.has(key)) fields.set(key, []);
1655
+ fields.get(key).push(String(value).trim());
1656
+ }
1657
+ }
1658
+
1659
+ function parseClosureFields(block) {
1660
+ const fields = new Map();
1661
+ const lines = String(block).split('\n');
1662
+ for (const line of lines) {
1663
+ const candidate = line
1664
+ .trim()
1665
+ .replace(/^[-*+]\s*/, '')
1666
+ .replace(/^\*\*/, '');
1667
+ const field = candidate.match(/^([^:]+?)(?:\*\*)?\s*:\s*(.*?)\s*$/);
1668
+ if (field) appendClosureField(fields, field[1], field[2]);
1669
+ }
1670
+
1671
+ for (let index = 0; index + 2 < lines.length; index += 1) {
1672
+ if (!/^\s*\|/.test(lines[index]) || !/^\s*\|(?:\s*:?-{3,}:?\s*\|)+\s*$/.test(lines[index + 1])) {
1673
+ continue;
1674
+ }
1675
+ const headers = lines[index].split('|').slice(1, -1).map((cell) => cell.trim());
1676
+ for (let rowIndex = index + 2; rowIndex < lines.length && /^\s*\|/.test(lines[rowIndex]); rowIndex += 1) {
1677
+ const cells = lines[rowIndex].split('|').slice(1, -1).map((cell) => cell.trim());
1678
+ headers.forEach((header, cellIndex) => appendClosureField(fields, header, cells[cellIndex] || ''));
1679
+ }
1680
+ break;
1681
+ }
1682
+ return fields;
1683
+ }
1684
+
1685
+ function closureField(fields, key) {
1686
+ return (fields.get(key) || []).join(' ');
1687
+ }
1688
+
1689
+ function normalizedStringSet(values) {
1690
+ return [...new Set(values.map((value) => String(value).toUpperCase()))].sort();
1691
+ }
1692
+
1693
+ function validateClosureCorrespondence(label, closure, obligationId, obligation, errors) {
1694
+ const block = closure.blocks?.get(obligationId);
1695
+ if (typeof block !== 'string' || block.trim() === '') {
1696
+ errors.push(`${label}: Execution Closure marker ${obligationId} requires a marker-local field block`);
1697
+ return;
1698
+ }
1699
+ const parsed = parseClosureFields(block);
1700
+ const fields = [
1701
+ ['canonical_state', obligation.canonical_state],
1702
+ ['authority', obligation.authority],
1703
+ ['recovery', obligation.recovery],
1704
+ ['owner_task', obligation.owner_task],
1705
+ ['verification', obligation.verification],
1706
+ ['evidence', obligation.evidence],
1707
+ ];
1708
+ for (const [field, value] of fields) {
1709
+ if (typeof value !== 'string' || value.trim() === '') continue;
1710
+ const localValue = closureField(parsed, field);
1711
+ if (!localValue || !normalizeClosureText(localValue).includes(normalizeClosureText(value))) {
1712
+ errors.push(
1713
+ `${label}: Execution Closure for ${obligationId} must mirror spec.json ${field} in its marker-local field`,
1714
+ );
1715
+ }
1716
+ }
1717
+
1718
+ const expectedRequirements = normalizedStringSet(
1719
+ Array.isArray(obligation.requirements) ? obligation.requirements : [],
1720
+ );
1721
+ const actualRequirements = normalizedStringSet(
1722
+ closureField(parsed, 'requirements').match(/\bR\d+(?:\.\d+)?\b/gi) || [],
1723
+ );
1724
+ if (JSON.stringify(actualRequirements) !== JSON.stringify(expectedRequirements)) {
1725
+ errors.push(
1726
+ `${label}: Execution Closure for ${obligationId} must mirror spec.json requirements in its marker-local field`,
1727
+ );
1728
+ }
1729
+
1730
+ const consumers = Array.isArray(obligation.consumer_tasks) ? obligation.consumer_tasks : [];
1731
+ const consumerValue = closureField(parsed, 'consumer_tasks');
1732
+ if (consumers.length === 0) {
1733
+ if (!/^\s*(?:none|n\/a)\b/i.test(consumerValue)) {
1734
+ errors.push(`${label}: Execution Closure for ${obligationId} must state that consumer_tasks are none`);
1735
+ }
1736
+ } else {
1737
+ const actualConsumers = [...new Set(
1738
+ consumerValue.match(/tasks\/task-R\d+-\d{2}-[a-z0-9]+(?:-[a-z0-9]+)*\.md/gi) || [],
1739
+ )].sort();
1740
+ const expectedConsumers = [...new Set(consumers)].sort();
1741
+ if (JSON.stringify(actualConsumers) !== JSON.stringify(expectedConsumers)) {
1742
+ errors.push(
1743
+ `${label}: Execution Closure for ${obligationId} must mirror spec.json consumer_tasks in its marker-local field`,
1744
+ );
1745
+ }
1746
+ }
1747
+ }
1748
+
1749
+ function validateImplementationObligations(
1750
+ spec,
1751
+ context,
1752
+ requirementIds,
1753
+ subCriteriaIds,
1754
+ taskFiles,
1755
+ registry,
1756
+ designClosure,
1757
+ taskClosures,
1758
+ errors,
1759
+ ) {
1760
+ if (!Object.prototype.hasOwnProperty.call(spec, 'implementation_obligations')) {
1761
+ const taskClosurePresent = [...taskClosures.values()].some((closure) => closure.headingCount > 0);
1762
+ if (designClosure.ids.length > 0 || [...taskClosures.values()].some((closure) => closure.ids.length > 0)) {
1763
+ errors.push(
1764
+ 'implementation obligation markers require a declared spec.json.implementation_obligations array',
1765
+ );
1766
+ }
1767
+ if (context.policy?.lane === 'Critical') {
1768
+ if (designClosure.headingCount !== 1 || !designClosure.notApplicable) {
1769
+ errors.push(
1770
+ 'design.md: Critical scope must declare non-empty spec.json.implementation_obligations or one justified N/A in Execution Closure',
1771
+ );
1772
+ }
1773
+ } else if (designClosure.headingCount > 0) {
1774
+ errors.push('design.md: Execution Closure is allowed only for a declared Critical obligation decision');
1775
+ }
1776
+ if (taskClosurePresent) {
1777
+ errors.push('tasks/: Execution Closure is allowed only for tasks assigned to declared implementation obligations');
1778
+ }
1779
+ return;
1780
+ }
1781
+ const obligations = spec.implementation_obligations;
1782
+ if (context.policy?.lane !== 'Critical') {
1783
+ errors.push('spec.json.implementation_obligations: allowed only for Critical workflow policy');
1784
+ }
1785
+ if (!Array.isArray(obligations) || obligations.length === 0) {
1786
+ errors.push('spec.json.implementation_obligations: must be a non-empty array when present');
1787
+ return;
1788
+ }
1789
+ if (designClosure.notApplicable) {
1790
+ errors.push('design.md: justified N/A cannot coexist with declared implementation obligations');
1791
+ }
1792
+
1793
+ const knownRequirements = new Set([...requirementIds, ...subCriteriaIds]);
1794
+ const knownTasks = new Set(taskFiles);
1795
+ const dependencies = new Map(taskFiles.map((taskFile) => [
1796
+ taskFile,
1797
+ new Set(Array.isArray(registry?.[taskFile]?.dependencies) ? registry[taskFile].dependencies : []),
1798
+ ]));
1799
+ function dependsOn(taskFile, ownerTask, seen = new Set()) {
1800
+ if (taskFile === ownerTask) return true;
1801
+ if (seen.has(taskFile)) return false;
1802
+ seen.add(taskFile);
1803
+ return [...(dependencies.get(taskFile) || [])].some((dependency) => (
1804
+ dependsOn(dependency, ownerTask, seen)
1805
+ ));
1806
+ }
1807
+
1808
+ const ids = new Set();
1809
+ const obligationsById = new Map();
1810
+ for (const [index, obligation] of obligations.entries()) {
1811
+ const label = `spec.json.implementation_obligations[${index}]`;
1812
+ if (!isPlainObject(obligation)) {
1813
+ errors.push(`${label}: must be an object`);
1814
+ continue;
1815
+ }
1816
+ const obligationId = typeof obligation.id === 'string' ? obligation.id.trim().toLowerCase() : '';
1817
+ if (!/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/.test(obligationId)) {
1818
+ errors.push(`${label}.id: must be a stable lowercase marker id`);
1819
+ } else if (obligation.id !== obligationId) {
1820
+ errors.push(`${label}.id: must be lowercase without surrounding whitespace`);
1821
+ } else if (ids.has(obligationId)) {
1822
+ errors.push(`${label}.id: duplicate obligation id ${obligationId}`);
1823
+ } else {
1824
+ ids.add(obligationId);
1825
+ obligationsById.set(obligationId, obligation);
1826
+ }
1827
+
1828
+ if (!Array.isArray(obligation.requirements) || obligation.requirements.length === 0) {
1829
+ errors.push(`${label}.requirements: must be a non-empty array of requirement references`);
1830
+ } else {
1831
+ const seenRequirements = new Set();
1832
+ for (const reference of obligation.requirements) {
1833
+ if (typeof reference !== 'string' || !/^R\d+(?:\.\d+)?$/i.test(reference)) {
1834
+ errors.push(`${label}.requirements: invalid requirement reference ${String(reference)}`);
1835
+ continue;
1836
+ }
1837
+ const normalized = reference.toUpperCase();
1838
+ if (seenRequirements.has(normalized)) {
1839
+ errors.push(`${label}.requirements: duplicate requirement reference ${normalized}`);
1840
+ } else if (!knownRequirements.has(normalized)) {
1841
+ errors.push(`${label}.requirements: unknown requirement reference ${normalized}`);
1842
+ }
1843
+ seenRequirements.add(normalized);
1844
+ }
1845
+ }
1846
+
1847
+ const ownerTask = obligation.owner_task;
1848
+ const ownerValid = typeof ownerTask === 'string' && knownTasks.has(ownerTask);
1849
+ if (!ownerValid) {
1850
+ errors.push(`${label}.owner_task: must name exactly one registered task`);
1851
+ }
1852
+
1853
+ if (!Array.isArray(obligation.consumer_tasks)) {
1854
+ errors.push(`${label}.consumer_tasks: must be an array of registered tasks`);
1855
+ } else {
1856
+ const seenConsumers = new Set();
1857
+ for (const consumerTask of obligation.consumer_tasks) {
1858
+ if (typeof consumerTask !== 'string' || !knownTasks.has(consumerTask)) {
1859
+ errors.push(`${label}.consumer_tasks: unknown task reference ${String(consumerTask)}`);
1860
+ continue;
1861
+ }
1862
+ if (consumerTask === ownerTask) {
1863
+ errors.push(`${label}.consumer_tasks: owner task cannot also be a consumer`);
1864
+ } else if (seenConsumers.has(consumerTask)) {
1865
+ errors.push(`${label}.consumer_tasks: duplicate task reference ${consumerTask}`);
1866
+ } else if (ownerValid && !dependsOn(consumerTask, ownerTask)) {
1867
+ errors.push(`${label}.consumer_tasks: ${consumerTask} must depend on owner ${ownerTask}`);
1868
+ }
1869
+ seenConsumers.add(consumerTask);
1870
+ }
1871
+ }
1872
+
1873
+ for (const field of ['canonical_state', 'authority', 'recovery']) {
1874
+ if (!meaningfulObligationValue(obligation[field])) {
1875
+ errors.push(`${label}.${field}: must be concrete, non-placeholder implementation semantics`);
1876
+ }
1877
+ }
1878
+ if (!isExecutableCommand(obligation.verification)) {
1879
+ errors.push(`${label}.verification: must be an executable command`);
1880
+ }
1881
+ if (!hasObservableProof(obligation.evidence)) {
1882
+ errors.push(`${label}.evidence: must name an observable result, state, artifact, or exit outcome`);
1883
+ }
1884
+ }
1885
+
1886
+ if (ids.size > 0 && designClosure.headingCount !== 1) {
1887
+ errors.push('design.md: declared implementation obligations require exactly one Execution Closure section');
1888
+ }
1889
+ const designSet = new Set(designClosure.ids);
1890
+ for (const designId of designSet) {
1891
+ if (!ids.has(designId)) {
1892
+ errors.push(`design.md: implementation obligation marker ${designId} is not declared in spec.json`);
1893
+ }
1894
+ }
1895
+ for (const obligationId of ids) {
1896
+ if (!designSet.has(obligationId)) {
1897
+ errors.push(`design.md: missing implementation obligation marker ${obligationId}`);
1898
+ }
1899
+ }
1900
+
1901
+ for (const [taskFile, closure] of taskClosures) {
1902
+ if (closure.headingCount > 0 && closure.ids.length === 0) {
1903
+ errors.push(`${taskFile}: Execution Closure requires at least one assigned implementation obligation marker`);
1904
+ }
1905
+ for (const marker of closure.ids) {
1906
+ const obligation = obligationsById.get(marker);
1907
+ if (!obligation) {
1908
+ errors.push(`${taskFile}: implementation obligation marker ${marker} is not declared in spec.json`);
1909
+ continue;
1910
+ }
1911
+ const participants = new Set([
1912
+ obligation.owner_task,
1913
+ ...(Array.isArray(obligation.consumer_tasks) ? obligation.consumer_tasks : []),
1914
+ ]);
1915
+ if (!participants.has(taskFile)) {
1916
+ errors.push(`${taskFile}: marker ${marker} is not assigned to this owner/consumer task`);
1917
+ }
1918
+ }
1919
+ }
1920
+
1921
+ for (const [obligationId, obligation] of obligationsById) {
1922
+ if (designSet.has(obligationId)) {
1923
+ validateClosureCorrespondence('design.md', designClosure, obligationId, obligation, errors);
1924
+ }
1925
+ const participants = [
1926
+ obligation.owner_task,
1927
+ ...(Array.isArray(obligation.consumer_tasks) ? obligation.consumer_tasks : []),
1928
+ ].filter((taskFile) => typeof taskFile === 'string' && knownTasks.has(taskFile));
1929
+ for (const taskFile of participants) {
1930
+ const closure = taskClosures.get(taskFile)
1931
+ || { ids: [], section: '', headingCount: 0, blocks: new Map(), notApplicable: false };
1932
+ if (!closure.ids.includes(obligationId)) {
1933
+ errors.push(`${taskFile}: missing implementation obligation marker ${obligationId}`);
1934
+ } else {
1935
+ if (closure.headingCount !== 1) {
1936
+ errors.push(`${taskFile}: declared implementation obligations require exactly one Execution Closure section`);
1937
+ }
1938
+ validateClosureCorrespondence(taskFile, closure, obligationId, obligation, errors);
1939
+ }
1940
+ }
1941
+ }
1942
+ }
1943
+
1944
+ function validateDependencyTopology(spec, taskFiles, registry, taskRecords, errors) {
1945
+ const dependencies = new Map(taskFiles.map((taskFile) => [taskFile, new Set(registry?.[taskFile]?.dependencies || [])]));
1946
+ if (dependencies.size === 0) return;
1947
+
1948
+ const visiting = new Set();
1949
+ const visited = new Set();
624
1950
  function visit(taskFile, stack = []) {
625
1951
  if (visiting.has(taskFile)) {
626
1952
  const cycleStart = stack.indexOf(taskFile);
@@ -737,7 +2063,1203 @@ function validateDependencyTopology(spec, taskFiles, registry, taskRecords, erro
737
2063
  }
738
2064
  }
739
2065
 
740
- function validateSpec(specDir) {
2066
+ function validateParallelEligibility(taskFiles, registry, taskRecords, errors) {
2067
+ const parallelTasks = taskFiles.filter((taskFile) => taskRecords.get(taskFile)?.parallel === true);
2068
+ for (const taskFile of parallelTasks) {
2069
+ const dependencies = Array.isArray(registry?.[taskFile]?.dependencies)
2070
+ ? registry[taskFile].dependencies
2071
+ : [];
2072
+ if (dependencies.length > 0) {
2073
+ errors.push(`${taskFile}: task-level (P) cannot declare sibling dependencies`);
2074
+ }
2075
+
2076
+ const ownRows = taskRecords.get(taskFile)?.rows || [];
2077
+ for (const sibling of taskFiles) {
2078
+ if (sibling === taskFile) continue;
2079
+ const siblingRows = taskRecords.get(sibling)?.rows || [];
2080
+ const conflicts = new Set();
2081
+ for (const ownRow of ownRows) {
2082
+ for (const siblingRow of siblingRows) {
2083
+ if (ownRow.path === siblingRow.path) {
2084
+ conflicts.add(ownRow.path);
2085
+ }
2086
+ }
2087
+ }
2088
+ for (const conflict of conflicts) {
2089
+ errors.push(
2090
+ `${taskFile}: task-level (P) has Related Files contention on ${conflict} with ${sibling}`,
2091
+ );
2092
+ }
2093
+ }
2094
+ }
2095
+ }
2096
+
2097
+ function explicitResearchPath(spec) {
2098
+ if (!Object.prototype.hasOwnProperty.call(spec, 'research') || spec.research === null) return null;
2099
+ return isPlainObject(spec.research) ? spec.research.path : spec.research;
2100
+ }
2101
+
2102
+ function validateCoordinationTopology(spec, context, taskFiles, specDir, errors) {
2103
+ const depth = context.policy?.planning_depth;
2104
+ if (depth === 'None') {
2105
+ errors.push('spec.json.workflow_policy.planning_depth: None cannot have a durable spec artifact');
2106
+ }
2107
+ const coordination = spec.coordination;
2108
+ if (!isPlainObject(coordination)) {
2109
+ if (!context.legacy) errors.push('spec.json.coordination: Specs v2 requires an object');
2110
+ return { tasksRequired: context.legacy && taskFiles.length > 0, phases: [] };
2111
+ }
2112
+ if (typeof coordination.tasks_required !== 'boolean') {
2113
+ errors.push('spec.json.coordination.tasks_required: must be a boolean');
2114
+ }
2115
+ if (typeof coordination.phases_required !== 'boolean') {
2116
+ errors.push('spec.json.coordination.phases_required: must be a boolean');
2117
+ }
2118
+ const tasksRequired = coordination.tasks_required === true;
2119
+ if (tasksRequired && taskFiles.length === 0) {
2120
+ errors.push('spec.json.coordination.tasks_required: true requires physical task files and matching registry');
2121
+ }
2122
+ if (!tasksRequired && taskFiles.length > 0) {
2123
+ errors.push('tasks/: physical task files exist while coordination.tasks_required is false');
2124
+ }
2125
+ let taskTriggers = [];
2126
+ if (!context.legacy && tasksRequired) {
2127
+ if (coordination.reason !== 'task_topology') {
2128
+ errors.push('spec.json.coordination.reason: Specs v2 task bundles require canonical task_topology reason');
2129
+ }
2130
+ if (!Array.isArray(coordination.task_triggers) || coordination.task_triggers.length === 0) {
2131
+ errors.push('spec.json.coordination.task_triggers: Specs v2 task bundles require a non-empty auditable trigger list');
2132
+ } else {
2133
+ taskTriggers = coordination.task_triggers;
2134
+ const seen = new Set();
2135
+ for (const trigger of taskTriggers) {
2136
+ if (!TASK_TRIGGER_VALUES.has(trigger)) {
2137
+ errors.push(`spec.json.coordination.task_triggers: unknown trigger ${String(trigger)}`);
2138
+ } else if (seen.has(trigger)) {
2139
+ errors.push(`spec.json.coordination.task_triggers: duplicate trigger ${trigger}`);
2140
+ }
2141
+ seen.add(trigger);
2142
+ }
2143
+ }
2144
+ } else if (!context.legacy && Object.prototype.hasOwnProperty.call(coordination, 'task_triggers')) {
2145
+ errors.push('spec.json.coordination.task_triggers: taskless Specs v2 must omit task triggers');
2146
+ }
2147
+ const phases = coordination.phases;
2148
+ if (phases !== undefined && !Array.isArray(phases)) {
2149
+ errors.push('spec.json.coordination.phases: must be an array when present');
2150
+ return { tasksRequired, phases: [] };
2151
+ }
2152
+ const phaseList = Array.isArray(phases) ? phases : [];
2153
+ if (coordination.phases_required !== (phaseList.length > 0)) {
2154
+ errors.push('spec.json.coordination.phases_required: must match whether structured phases are present');
2155
+ }
2156
+ if (phaseList.length > 0 && (depth !== 'Full' || !tasksRequired)) {
2157
+ errors.push('spec.json.coordination.phases: structured phases are allowed only for a Full task graph');
2158
+ }
2159
+ const taskIds = new Set(taskFiles.map(expectedTaskId));
2160
+ const covered = new Set();
2161
+ const phaseIds = new Set();
2162
+ for (const [index, phase] of phaseList.entries()) {
2163
+ const label = `spec.json.coordination.phases[${index}]`;
2164
+ if (!isPlainObject(phase)
2165
+ || JSON.stringify(Object.keys(phase).sort()) !== JSON.stringify([...PHASE_FIELDS].sort())) {
2166
+ errors.push(`${label}: must contain exactly ${PHASE_FIELDS.join(', ')}`);
2167
+ continue;
2168
+ }
2169
+ if (typeof phase.id !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(phase.id)) {
2170
+ errors.push(`${label}.id: must be a stable kebab-case id`);
2171
+ } else if (phaseIds.has(phase.id)) errors.push(`${label}.id: duplicate phase id ${phase.id}`);
2172
+ phaseIds.add(phase.id);
2173
+ if (!Array.isArray(phase.task_ids) || phase.task_ids.length === 0) {
2174
+ errors.push(`${label}.task_ids: must be a non-empty array`);
2175
+ } else {
2176
+ for (const taskId of phase.task_ids) {
2177
+ if (!taskIds.has(taskId)) errors.push(`${label}.task_ids: unknown task id ${String(taskId)}`);
2178
+ else if (covered.has(taskId)) errors.push(`${label}.task_ids: task ${taskId} is grouped more than once`);
2179
+ covered.add(taskId);
2180
+ }
2181
+ }
2182
+ for (const field of ['entry_condition', 'exit_condition', 'owner_boundary']) {
2183
+ if (typeof phase[field] !== 'string' || phase[field].trim().length < 8 || hasSpecPlaceholders(phase[field])) {
2184
+ errors.push(`${label}.${field}: must be concrete and non-placeholder`);
2185
+ }
2186
+ }
2187
+ }
2188
+ if (phaseList.length > 0) {
2189
+ for (const taskId of taskIds) {
2190
+ if (!covered.has(taskId)) errors.push(`spec.json.coordination.phases: task ${taskId} is not grouped exactly once`);
2191
+ }
2192
+ }
2193
+ try {
2194
+ for (const entry of fs.readdirSync(specDir, { withFileTypes: true })) {
2195
+ if (entry.isFile() && /^phase(?:-|_).*\.md$/i.test(entry.name)) {
2196
+ errors.push(`${entry.name}: phase files are forbidden; use compact spec.json.coordination.phases metadata`);
2197
+ }
2198
+ }
2199
+ } catch (_) {}
2200
+ return { tasksRequired, phases: phaseList, taskTriggers };
2201
+ }
2202
+
2203
+ function validateTaskTriggerEvidence(spec, topology, taskFiles, taskRecords, errors) {
2204
+ if (!Array.isArray(topology.taskTriggers) || topology.taskTriggers.length === 0) return;
2205
+ const triggers = new Set(topology.taskTriggers);
2206
+ const dependencyCount = Object.values(spec.task_registry || {}).reduce((count, entry) => (
2207
+ count + (Array.isArray(entry?.dependencies) ? entry.dependencies.length : 0)
2208
+ ), 0);
2209
+ const artifactTaskCount = Object.values(spec.task_registry || {}).filter((entry) => (
2210
+ Array.isArray(entry?.artifacts) && entry.artifacts.length > 0
2211
+ )).length;
2212
+ const parallelTaskCount = taskFiles.filter((taskFile) => taskRecords.get(taskFile)?.parallel === true).length;
2213
+ const writeOwners = new Map();
2214
+ let tasksWithWriteOwnership = 0;
2215
+ for (const taskFile of taskFiles) {
2216
+ const writePaths = new Set((taskRecords.get(taskFile)?.rows || [])
2217
+ .filter((row) => ['create', 'modify', 'delete'].includes(row.action))
2218
+ .map((row) => path.normalize(row.path).split(path.sep).join('/')));
2219
+ if (writePaths.size > 0) tasksWithWriteOwnership += 1;
2220
+ for (const filePath of writePaths) {
2221
+ if (!writeOwners.has(filePath)) writeOwners.set(filePath, []);
2222
+ writeOwners.get(filePath).push(taskFile);
2223
+ }
2224
+ }
2225
+ const overlappingWrite = [...writeOwners.entries()]
2226
+ .find(([, owners]) => owners.length > 1);
2227
+ const hasDistinctOwnership = taskFiles.length >= 2
2228
+ && tasksWithWriteOwnership >= 2
2229
+ && overlappingWrite === undefined;
2230
+ const evidence = {
2231
+ distinct_ownership: hasDistinctOwnership,
2232
+ real_dependency: dependencyCount > 0,
2233
+ durable_transition: topology.phases.length > 0,
2234
+ separate_proof: artifactTaskCount > 0,
2235
+ parallel_coordination: parallelTaskCount > 0,
2236
+ };
2237
+ for (const trigger of triggers) {
2238
+ if (TASK_TRIGGER_VALUES.has(trigger) && evidence[trigger] !== true) {
2239
+ if (trigger === 'distinct_ownership') {
2240
+ const overlap = overlappingWrite
2241
+ ? `; shared write path ${overlappingWrite[0]} is declared by ${overlappingWrite[1].join(', ')}`
2242
+ : '';
2243
+ errors.push(
2244
+ 'spec.json.coordination.task_triggers: distinct_ownership requires at least 2 tasks with distinct, ' +
2245
+ `non-overlapping Related Files Create/Modify/Delete boundaries${overlap}`,
2246
+ );
2247
+ } else {
2248
+ errors.push(`spec.json.coordination.task_triggers: ${trigger} has no matching physical task inventory or graph evidence`);
2249
+ }
2250
+ }
2251
+ }
2252
+ for (const [trigger, present] of Object.entries(evidence)) {
2253
+ if (present && trigger !== 'distinct_ownership' && !triggers.has(trigger)) {
2254
+ errors.push(`spec.json.coordination.task_triggers: physical task inventory or graph requires ${trigger}`);
2255
+ }
2256
+ }
2257
+ }
2258
+
2259
+ function criterionReferences(content) {
2260
+ const ids = new Set();
2261
+ for (const match of semanticMarkdown(content).matchAll(/\bR?(\d+\.\d+)\b/gi)) ids.add(`R${match[1]}`);
2262
+ return ids;
2263
+ }
2264
+
2265
+ function namedContractDefinitions(designText, errors) {
2266
+ const ids = new Set();
2267
+ for (const match of semanticMarkdown(designText).matchAll(/^#{3,6}\s+(C\d+)\s+(?:—|-)\s+.+$/gim)) {
2268
+ const id = match[1].toUpperCase();
2269
+ if (ids.has(id)) errors.push(`design.md: duplicate named contract ID ${id}`);
2270
+ ids.add(id);
2271
+ }
2272
+ return ids;
2273
+ }
2274
+
2275
+ function validateNamedContractReferences(designText, taskContents, errors) {
2276
+ const definitions = namedContractDefinitions(designText, errors);
2277
+ for (const [taskPath, content] of taskContents) {
2278
+ if (taskFormat(content) !== 'v2') continue;
2279
+ const scope = extractSection(content, 'Scope and Typed Anchors') || '';
2280
+ const declared = sectionFieldValues(scope, ['Contracts/Invariants', 'Contracts', 'Invariants']).join(' ');
2281
+ for (const id of declared.match(/\bC\d+\b/gi) || []) {
2282
+ if (!definitions.has(id.toUpperCase())) errors.push(`${taskPath}: references unknown named contract ${id.toUpperCase()}`);
2283
+ }
2284
+ if (/<!--\s*contract:[A-Za-z0-9_.-]+\s*-->/.test(content)) {
2285
+ errors.push(`${taskPath}: Specs v2 tasks reference named contract IDs and must not copy canonical contract blocks`);
2286
+ }
2287
+ }
2288
+ }
2289
+
2290
+ function stableJson(value) {
2291
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;
2292
+ if (isPlainObject(value)) {
2293
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(',')}}`;
2294
+ }
2295
+ return JSON.stringify(value);
2296
+ }
2297
+
2298
+ function semanticDigestState(spec) {
2299
+ const taskRegistry = isPlainObject(spec.task_registry)
2300
+ ? Object.fromEntries(Object.entries(spec.task_registry).map(([taskPath, entry]) => [taskPath, {
2301
+ id: entry?.id ?? null,
2302
+ dependencies: entry?.dependencies ?? null,
2303
+ ...(Object.prototype.hasOwnProperty.call(entry || {}, 'artifacts') ? { artifacts: entry.artifacts } : {}),
2304
+ }]))
2305
+ : spec.task_registry ?? null;
2306
+ return {
2307
+ scope_lock: spec.scope_lock ?? null,
2308
+ task_files: spec.task_files ?? null,
2309
+ task_registry: taskRegistry,
2310
+ coordination: spec.coordination ?? null,
2311
+ semantic_model: spec.semantic_model ?? null,
2312
+ decisions: spec.decisions ?? null,
2313
+ workflow_policy: spec.workflow_policy ?? null,
2314
+ };
2315
+ }
2316
+
2317
+ function semanticTaskMarkdown(content) {
2318
+ let fence = null;
2319
+ let inComment = false;
2320
+ return String(content).split(/(\r?\n)/).map((line) => {
2321
+ if (/^\r?\n$/.test(line)) return line;
2322
+ if (inComment) {
2323
+ if (line.includes('-->')) inComment = false;
2324
+ return line;
2325
+ }
2326
+ const commentStart = line.indexOf('<!--');
2327
+ if (commentStart >= 0) {
2328
+ if (line.indexOf('-->', commentStart + 4) < 0) inComment = true;
2329
+ return line;
2330
+ }
2331
+ const marker = line.match(/^\s{0,3}(`{3,}|~{3,})/);
2332
+ if (marker) {
2333
+ const character = marker[1][0];
2334
+ const length = marker[1].length;
2335
+ if (fence === null) fence = { character, length };
2336
+ else if (character === fence.character && length >= fence.length) fence = null;
2337
+ return line;
2338
+ }
2339
+ if (fence !== null) return line;
2340
+ return line
2341
+ .replace(/^(\*\*Status:\*\*[ \t]*)(?:pending|in_progress|blocked|done)([ \t]*)$/, '$1<lifecycle-status>$2')
2342
+ .replace(/^(\s*[-*+]\s+\[)[ xX](\])/, '$1 $2');
2343
+ }).join('');
2344
+ }
2345
+
2346
+ function computeSemanticDigest(specDir) {
2347
+ const errors = [];
2348
+ const canonicalSpecDir = validateSpecRoot(specDir, errors);
2349
+ if (!canonicalSpecDir) return { errors, digest: null };
2350
+ const specArtifact = inspectSpecArtifact(
2351
+ specDir, canonicalSpecDir, 'spec.json', 'spec.json', errors, { required: true },
2352
+ );
2353
+ const spec = specArtifact ? readJson(specArtifact.path, errors) : null;
2354
+ const artifacts = [];
2355
+ for (const relativePath of ['requirements.md', 'design.md']) {
2356
+ const artifact = inspectSpecArtifact(
2357
+ specDir, canonicalSpecDir, relativePath, relativePath, errors, { required: true },
2358
+ );
2359
+ if (artifact) artifacts.push([relativePath, fs.readFileSync(artifact.path)]);
2360
+ }
2361
+ const research = inspectSpecArtifact(specDir, canonicalSpecDir, 'research.md', 'research.md', errors);
2362
+ if (research) artifacts.push(['research.md', fs.readFileSync(research.path)]);
2363
+ for (const taskFile of listTaskFiles(specDir, canonicalSpecDir, errors)) {
2364
+ const artifact = inspectSpecArtifact(specDir, canonicalSpecDir, taskFile, taskFile, errors, { required: true });
2365
+ if (artifact) artifacts.push([taskFile, Buffer.from(semanticTaskMarkdown(fs.readFileSync(artifact.path, 'utf8')), 'utf8')]);
2366
+ }
2367
+ if (!isPlainObject(spec) || errors.length > 0) return { errors, digest: null };
2368
+ const hash = crypto.createHash('sha256');
2369
+ for (const [relativePath, bytes] of artifacts) {
2370
+ hash.update(relativePath, 'utf8');
2371
+ hash.update('\0');
2372
+ hash.update(String(bytes.length), 'utf8');
2373
+ hash.update('\0');
2374
+ hash.update(bytes);
2375
+ hash.update('\0');
2376
+ }
2377
+ const state = Buffer.from(stableJson(semanticDigestState(spec)), 'utf8');
2378
+ hash.update('spec.json#semantic-state\0', 'utf8');
2379
+ hash.update(String(state.length), 'utf8');
2380
+ hash.update('\0');
2381
+ hash.update(state);
2382
+ return { errors, digest: `sha256:${hash.digest('hex')}` };
2383
+ }
2384
+
2385
+ function designSemanticReviewIds(designText) {
2386
+ return new Set([...semanticMarkdown(designText).matchAll(/^#{3,6}\s+([DIC]\d+)\s+(?:—|-)\s+.+$/gim)]
2387
+ .map((match) => match[1].toUpperCase()));
2388
+ }
2389
+
2390
+ function concreteSemanticReviewText(value) {
2391
+ return typeof value === 'string'
2392
+ && value.trim() === value
2393
+ && meaningfulObligationValue(value)
2394
+ && !hasSpecPlaceholders(value);
2395
+ }
2396
+
2397
+ function validateSemanticReview(specDir, spec, context, subCriteriaIds, designText, errors) {
2398
+ const review = spec.validation?.semantic_review;
2399
+ if (!isPlainObject(review)) {
2400
+ if (!context.legacy) errors.push('spec.json.validation.semantic_review: Specs v2 requires the canonical object');
2401
+ return;
2402
+ }
2403
+ const fields = Object.keys(review).sort();
2404
+ if (JSON.stringify(fields) !== JSON.stringify([...SEMANTIC_REVIEW_FIELDS].sort())) {
2405
+ errors.push(`spec.json.validation.semantic_review: fields must be exactly ${SEMANTIC_REVIEW_FIELDS.join(', ')}`);
2406
+ }
2407
+ if (!SEMANTIC_REVIEW_STATUSES.has(review.status)) {
2408
+ errors.push('spec.json.validation.semantic_review.status: must be not-run or completed');
2409
+ return;
2410
+ }
2411
+ if (!Array.isArray(review.reviewed_criteria)) {
2412
+ errors.push('spec.json.validation.semantic_review.reviewed_criteria: must be an array');
2413
+ }
2414
+ if (!Array.isArray(review.counterexamples)) {
2415
+ errors.push('spec.json.validation.semantic_review.counterexamples: must be an array');
2416
+ }
2417
+ if (review.status === 'not-run') {
2418
+ if (spec.ready_for_implementation === true) {
2419
+ errors.push('spec.json.ready_for_implementation: requires validation.semantic_review.status completed');
2420
+ }
2421
+ if (review.reviewed_artifact_digest !== null || review.reviewed_criteria?.length > 0
2422
+ || review.counterexamples?.length > 0) {
2423
+ errors.push('spec.json.validation.semantic_review: not-run state must keep receipt fields null or empty');
2424
+ }
2425
+ return;
2426
+ }
2427
+
2428
+ if (!SHA256_RE.test(review.reviewed_artifact_digest || '')) {
2429
+ errors.push('spec.json.validation.semantic_review.reviewed_artifact_digest: must be sha256:<64 lowercase hex>');
2430
+ } else {
2431
+ const computed = computeSemanticDigest(specDir);
2432
+ if (computed.errors.length > 0) {
2433
+ errors.push(`spec.json.validation.semantic_review.reviewed_artifact_digest: cannot recompute (${computed.errors.join('; ')})`);
2434
+ } else if (review.reviewed_artifact_digest !== computed.digest) {
2435
+ errors.push('spec.json.validation.semantic_review.reviewed_artifact_digest: stale or does not match final artifacts and canonical state');
2436
+ }
2437
+ }
2438
+ if (context.policy?.assurance_level === 'Strict' && SHA256_RE.test(review.reviewed_artifact_digest || '')) {
2439
+ try {
2440
+ const authority = require('../hooks/semantic-review-authority.cjs');
2441
+ const canonicalSpecDir = fs.realpathSync(specDir);
2442
+ let root = fs.realpathSync(process.cwd());
2443
+ if (!isPathInside(root, canonicalSpecDir)) root = path.dirname(path.dirname(canonicalSpecDir));
2444
+ const attestation = authority.verifyAttestation(
2445
+ root,
2446
+ path.join(canonicalSpecDir, 'spec.json'),
2447
+ spec.feature_name,
2448
+ review.reviewed_artifact_digest,
2449
+ );
2450
+ if (!attestation.ok) errors.push(`spec.json.validation.semantic_review: Strict assurance requires matching host-observed reviewer PASS attestation (${attestation.reason})`);
2451
+ } catch (error) {
2452
+ errors.push(`spec.json.validation.semantic_review: Strict assurance attestation is unavailable (${error.message})`);
2453
+ }
2454
+ }
2455
+
2456
+ const criteria = Array.isArray(review.reviewed_criteria) ? review.reviewed_criteria : [];
2457
+ const criterionSet = new Set(criteria);
2458
+ if (criterionSet.size !== criteria.length) {
2459
+ errors.push('spec.json.validation.semantic_review.reviewed_criteria: must not contain duplicates');
2460
+ }
2461
+ for (const criterion of criteria) {
2462
+ if (!subCriteriaIds.includes(criterion)) {
2463
+ errors.push(`spec.json.validation.semantic_review.reviewed_criteria: unknown criterion ${String(criterion)}`);
2464
+ }
2465
+ }
2466
+ for (const criterion of subCriteriaIds) {
2467
+ if (!criterionSet.has(criterion)) {
2468
+ errors.push(`spec.json.validation.semantic_review.reviewed_criteria: missing criterion ${criterion}`);
2469
+ }
2470
+ }
2471
+
2472
+ const designIds = designSemanticReviewIds(designText);
2473
+ const coveredCriteria = new Set();
2474
+ for (const [index, counterexample] of (Array.isArray(review.counterexamples) ? review.counterexamples : []).entries()) {
2475
+ const label = `spec.json.validation.semantic_review.counterexamples[${index}]`;
2476
+ const expectedFields = ['criterion', 'scenario', 'expected', 'design_reference'];
2477
+ if (!isPlainObject(counterexample)
2478
+ || JSON.stringify(Object.keys(counterexample).sort()) !== JSON.stringify(expectedFields.sort())) {
2479
+ errors.push(`${label}: must contain exactly criterion, scenario, expected, design_reference`);
2480
+ continue;
2481
+ }
2482
+ if (!subCriteriaIds.includes(counterexample.criterion)) {
2483
+ errors.push(`${label}.criterion: unknown criterion ${String(counterexample.criterion)}`);
2484
+ } else if (coveredCriteria.has(counterexample.criterion)) {
2485
+ errors.push(`${label}.criterion: duplicate counterexample for ${counterexample.criterion}`);
2486
+ } else {
2487
+ coveredCriteria.add(counterexample.criterion);
2488
+ }
2489
+ for (const field of ['scenario', 'expected']) {
2490
+ if (!concreteSemanticReviewText(counterexample[field])) {
2491
+ errors.push(`${label}.${field}: must be concrete and non-placeholder`);
2492
+ }
2493
+ }
2494
+ if (typeof counterexample.design_reference !== 'string'
2495
+ || !designIds.has(counterexample.design_reference.toUpperCase())) {
2496
+ errors.push(`${label}.design_reference: must reference a real D/I/C ID in design.md`);
2497
+ }
2498
+ }
2499
+ for (const criterionId of subCriteriaIds) {
2500
+ if (!coveredCriteria.has(criterionId)) {
2501
+ errors.push(`spec.json.validation.semantic_review.counterexamples: missing concrete counterexample for ${criterionId}`);
2502
+ }
2503
+ }
2504
+ }
2505
+
2506
+ function exactTaskTarget(value) {
2507
+ return typeof value === 'string' && value.trim() === value && value !== ''
2508
+ && !unsafeRelatedPath(value) && !/[*?{}[\]]/.test(value) && !/[\\/]$/.test(value);
2509
+ }
2510
+
2511
+ function targetsContend(left, right) {
2512
+ const a = left.replace(/\\/g, '/').replace(/\/+$/, '');
2513
+ const b = right.replace(/\\/g, '/').replace(/\/+$/, '');
2514
+ return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
2515
+ }
2516
+
2517
+ function task21Anchors(taskPath, content, errors) {
2518
+ const section = extractSection(content, 'Anchors and Ownership') || '';
2519
+ const tableCount = (section.match(/^\s*\|\s*ID\s*\|\s*Type\s*\|\s*Target\s*\|\s*Role\s*\|\s*Access\s*\|\s*Action\s*\|\s*$/gim) || []).length;
2520
+ if (tableCount !== 1) {
2521
+ errors.push(`${taskPath}: Anchors and Ownership requires one table ID | Type | Target | Role | Access | Action`);
2522
+ return [];
2523
+ }
2524
+ if (hasHeading(content, 'Related Files')) {
2525
+ errors.push(`${taskPath}: Related Files is not canonical in schema 2.1; use Anchors and Ownership only`);
2526
+ }
2527
+ return parseCanonicalAnchors(content, { label: taskPath, design: false }, errors);
2528
+ }
2529
+
2530
+ function canonicalTaskCriterionIds(section) {
2531
+ return [...new Set([...String(section || '').matchAll(/^\s*[-*+]\s+(?:\*\*)?(R\d+\.\d+)(?:\*\*)?\s*:/gim)]
2532
+ .map((match) => match[1].toUpperCase()))].sort();
2533
+ }
2534
+
2535
+ function canonicalTaskChangeIds(section) {
2536
+ const ids = [];
2537
+ for (const match of String(section || '').matchAll(/_Requirements:\s*([^_\n]+)_/gi)) {
2538
+ for (const token of match[1].split(',')) {
2539
+ const id = token.trim().match(/^(?:R)?(\d+\.\d+)$/i);
2540
+ if (id) ids.push(`R${id[1]}`);
2541
+ }
2542
+ }
2543
+ return [...new Set(ids)].sort();
2544
+ }
2545
+
2546
+ function hasConcreteTaskProse(section) {
2547
+ return meaningfulMarkdownLines(section).some((line) => (
2548
+ line.length >= 16
2549
+ && !/^(?:implement|update|handle|verify|deliver|support|works?|done|task outcome|in scope|out of scope)\.?$/i.test(line)
2550
+ && !/\b(?:as needed|appropriate behavior|expected behavior|the feature|this task|relevant files?)\b/i.test(line)
2551
+ ));
2552
+ }
2553
+
2554
+ function validateTask21(taskPath, content, entry, errors) {
2555
+ for (const section of TASK_21_SECTIONS) {
2556
+ if (headingCount(content, section) !== 1) errors.push(`${taskPath}: requires exactly one ## ${section} section`);
2557
+ }
2558
+ const h2 = [...content.matchAll(/^##\s+(.+?)\s*$/gm)].map((match) => match[1]);
2559
+ for (const heading of h2) if (!TASK_21_SECTIONS.includes(heading)) {
2560
+ errors.push(`${taskPath}: schema 2.1 task has non-canonical section ## ${heading}`);
2561
+ }
2562
+ validateTaskIdentity(taskPath, content, entry, errors);
2563
+ validateTaskDependencyHeader(taskPath, content, entry, true, errors);
2564
+ validateTaskStatusHeader(taskPath, content, entry, true, errors);
2565
+ validateVerificationPlan(taskPath, content, errors);
2566
+ validateTaskPlaceholders(taskPath, content, errors, []);
2567
+ const outcome = extractSection(content, 'Outcome') || '';
2568
+ const scope = extractSection(content, 'Scope') || '';
2569
+ const changes = extractSection(content, 'Changes') || '';
2570
+ const acceptance = extractSection(content, 'Acceptance') || '';
2571
+ if (!hasConcreteTaskProse(outcome)) errors.push(`${taskPath}: Outcome must be concrete and non-generic`);
2572
+ if (!hasConcreteTaskProse(scope)
2573
+ || !/^\s*[-*+]\s+(?:\*\*)?In scope(?:\*\*)?\s*:/im.test(scope)
2574
+ || !/^\s*[-*+]\s+(?:\*\*)?Out of scope(?:\*\*)?\s*:/im.test(scope)) {
2575
+ errors.push(`${taskPath}: Scope requires concrete In scope and Out of scope boundaries`);
2576
+ }
2577
+ if (!hasActionableTaskStep(changes)) errors.push(`${taskPath}: Changes requires an actionable checkbox`);
2578
+ const changeCriteria = canonicalTaskChangeIds(changes);
2579
+ const acceptanceCriteria = canonicalTaskCriterionIds(acceptance);
2580
+ const rawChangeCriteria = [...changes.matchAll(/_Requirements:\s*([^_\n]+)_/gi)]
2581
+ .flatMap((match) => match[1].split(','))
2582
+ .map((token) => token.trim().replace(/^R/i, ''))
2583
+ .filter((token) => /^\d+\.\d+$/.test(token));
2584
+ const rawAcceptanceCriteria = [...acceptance.matchAll(/^\s*[-*+]\s+(?:\*\*)?(R\d+\.\d+)(?:\*\*)?\s*:/gim)]
2585
+ .map((match) => match[1].toUpperCase());
2586
+ if (new Set(rawChangeCriteria).size !== rawChangeCriteria.length) errors.push(`${taskPath}: Changes contains duplicate RN.M authority`);
2587
+ if (new Set(rawAcceptanceCriteria).size !== rawAcceptanceCriteria.length) errors.push(`${taskPath}: Acceptance contains duplicate RN.M authority`);
2588
+ if (!hasConcreteTaskProse(acceptance)) errors.push(`${taskPath}: Acceptance must declare a concrete implementation or verification outcome`);
2589
+ if (JSON.stringify(changeCriteria) !== JSON.stringify(acceptanceCriteria)) {
2590
+ errors.push(`${taskPath}: Changes and Acceptance must trace the same exact RN.M criteria`);
2591
+ }
2592
+ const verificationRefs = sectionFieldValues(extractSection(content, 'Verification Plan') || '', ['Verification ref'])
2593
+ .map((value) => String(value).toUpperCase().match(/\bV\d+(?:\.\d+)?\b/)?.[0])
2594
+ .filter(Boolean);
2595
+ if (verificationRefs.length !== 1 || !/^V\d+(?:\.\d+)?$/.test(verificationRefs[0])) {
2596
+ errors.push(`${taskPath}: Verification Plan requires exactly one canonical V reference`);
2597
+ }
2598
+ const taskRoles = sectionFieldValues(extractSection(content, 'Verification Plan') || '', ['Task role'])
2599
+ .map((value) => String(value).toLowerCase().match(/\b(subject|verifier)\b/)?.[1])
2600
+ .filter(Boolean);
2601
+ if (taskRoles.length !== 1) errors.push(`${taskPath}: Verification Plan requires exactly one Task role: subject or verifier`);
2602
+ return {
2603
+ anchors: task21Anchors(taskPath, content, errors),
2604
+ criteria: acceptanceCriteria,
2605
+ verificationRefs,
2606
+ taskRole: taskRoles[0] || null,
2607
+ };
2608
+ }
2609
+
2610
+ function semanticDigest21(specDir, spec, taskFiles) {
2611
+ const policy = spec.workflow_policy;
2612
+ const semanticState = {
2613
+ schema_version: spec.schema_version,
2614
+ feature_name: spec.feature_name,
2615
+ scope_lock: spec.scope_lock,
2616
+ authoring: spec.authoring,
2617
+ research: spec.research ?? null,
2618
+ workflow_policy: policy,
2619
+ coordination: spec.coordination,
2620
+ semantic_model: spec.semantic_model,
2621
+ task_files: spec.task_files,
2622
+ task_registry: Object.fromEntries(taskFiles.map((taskPath) => {
2623
+ const entry = spec.task_registry?.[taskPath] || {};
2624
+ return [taskPath, { id: entry.id, title: entry.title, dependencies: entry.dependencies, artifacts: entry.artifacts }];
2625
+ })),
2626
+ };
2627
+ const artifacts = {
2628
+ state: semanticState,
2629
+ requirements: fs.readFileSync(path.join(specDir, 'requirements.md'), 'utf8'),
2630
+ design: fs.readFileSync(path.join(specDir, 'design.md'), 'utf8'),
2631
+ research: spec.research === 'research.md' && fs.existsSync(path.join(specDir, 'research.md'))
2632
+ ? fs.readFileSync(path.join(specDir, 'research.md'), 'utf8') : null,
2633
+ tasks: taskFiles.map((taskPath) => [taskPath, semanticTaskMarkdown(fs.readFileSync(path.join(specDir, taskPath), 'utf8'))]),
2634
+ };
2635
+ return `sha256:${crypto.createHash('sha256').update(stableJson(artifacts)).digest('hex')}`;
2636
+ }
2637
+
2638
+ function computeSemanticDigest21(specDir, spec) {
2639
+ const errors = [];
2640
+ const canonicalSpecDir = validateSpecRoot(specDir, errors);
2641
+ if (!canonicalSpecDir) return { errors, digest: null };
2642
+ if (spec === undefined) {
2643
+ const specArtifact = inspectSpecArtifact(specDir, canonicalSpecDir, 'spec.json', 'spec.json', errors, { required: true });
2644
+ if (specArtifact) spec = readJson(specArtifact.path, errors);
2645
+ }
2646
+ if (!isPlainObject(spec)) {
2647
+ if (errors.length === 0) errors.push('spec.json: must contain a JSON object');
2648
+ return { errors, digest: null };
2649
+ }
2650
+ const requiredArtifacts = ['requirements.md', 'design.md'];
2651
+ const contents = new Map();
2652
+ for (const relativePath of requiredArtifacts) {
2653
+ const artifact = inspectSpecArtifact(specDir, canonicalSpecDir, relativePath, relativePath, errors, { required: true });
2654
+ if (artifact) contents.set(relativePath, fs.readFileSync(artifact.path, 'utf8'));
2655
+ }
2656
+ const taskFiles = listTaskFiles(specDir, canonicalSpecDir, errors);
2657
+ const projection = SEMANTIC.modelFromMarkdown(canonicalSpecDir, spec);
2658
+ errors.push(...projection.errors.map((error) => `semantic projection: ${error}`));
2659
+ let digestSpec = spec;
2660
+ if (!isPlainObject(spec.semantic_model)) {
2661
+ digestSpec = { ...spec, semantic_model: projection.model };
2662
+ } else {
2663
+ errors.push(...SEMANTIC.validateSemanticModel(spec.semantic_model, spec));
2664
+ if (SEMANTIC.stableJson(spec.semantic_model) !== SEMANTIC.stableJson(projection.model)) {
2665
+ errors.push('spec.json.semantic_model: digest refuses Markdown projection drift');
2666
+ }
2667
+ }
2668
+ const verificationDefinitions = new Map(((spec.semantic_model || projection.model).verification_definitions || [])
2669
+ .map((definition) => [definition.id, definition]));
2670
+ const declared = Array.isArray(spec.task_files) ? [...spec.task_files].sort() : [];
2671
+ if (taskFiles.length === 0) {
2672
+ if (Object.prototype.hasOwnProperty.call(spec, 'task_files') || Object.prototype.hasOwnProperty.call(spec, 'task_registry')) {
2673
+ errors.push('schema 2.1 digest refuses task inventory without physical tasks');
2674
+ }
2675
+ } else {
2676
+ if (JSON.stringify(declared) !== JSON.stringify(taskFiles)) errors.push('schema 2.1 digest requires task_files to match physical tasks exactly');
2677
+ if (!isPlainObject(spec.task_registry) || Object.keys(spec.task_registry).sort().join(',') !== taskFiles.join(',')) {
2678
+ errors.push('schema 2.1 digest requires task_registry to match physical tasks exactly');
2679
+ }
2680
+ }
2681
+ validateResearchLifecycle21(specDir, canonicalSpecDir, spec, errors);
2682
+ const anchorsByTask = new Map();
2683
+ const criteriaByTask = new Map();
2684
+ for (const taskPath of taskFiles) {
2685
+ const artifact = inspectSpecArtifact(specDir, canonicalSpecDir, taskPath, taskPath, errors, { required: true });
2686
+ if (!artifact) continue;
2687
+ const content = fs.readFileSync(artifact.path, 'utf8');
2688
+ for (const section of TASK_21_SECTIONS) if (headingCount(content, section) !== 1) {
2689
+ errors.push(`${taskPath}: digest requires exactly one ## ${section} section`);
2690
+ }
2691
+ validateTaskIdentity(taskPath, content, spec.task_registry?.[taskPath], errors);
2692
+ anchorsByTask.set(taskPath, task21Anchors(taskPath, content, errors));
2693
+ criteriaByTask.set(taskPath, canonicalTaskCriterionIds(extractSection(content, 'Acceptance') || ''));
2694
+ }
2695
+ if (contents.has('design.md')) {
2696
+ validateBoundaries21(
2697
+ spec, taskFiles, spec.task_registry || {}, anchorsByTask, criteriaByTask,
2698
+ contents.get('design.md'), verificationDefinitions, errors,
2699
+ );
2700
+ }
2701
+ if (errors.length > 0) return { errors, digest: null };
2702
+ return { errors, digest: semanticDigest21(specDir, digestSpec, taskFiles) };
2703
+ }
2704
+
2705
+ function validateSemanticReview21(specDir, spec, criteria, designIds, verificationDefs, errors) {
2706
+ const review = spec.validation?.semantic_review;
2707
+ const fields = ['status', 'semantic_digest', 'reviewed_criteria', 'counterexamples'];
2708
+ if (!isPlainObject(review) || Object.keys(review).sort().join(',') !== fields.sort().join(',')) {
2709
+ errors.push(`spec.json.validation.semantic_review: schema 2.1 fields must be exactly ${fields.join(', ')}`);
2710
+ return;
2711
+ }
2712
+ if (!['not-run', 'completed'].includes(review.status)) errors.push('spec.json.validation.semantic_review.status: must be not-run or completed');
2713
+ if (review.status === 'not-run') {
2714
+ if (review.semantic_digest !== null || review.reviewed_criteria?.length || review.counterexamples?.length) {
2715
+ errors.push('spec.json.validation.semantic_review: not-run receipt must be empty');
2716
+ }
2717
+ if (spec.ready_for_implementation === true) errors.push('spec.json.ready_for_implementation: requires completed semantic review');
2718
+ return;
2719
+ }
2720
+ const computed = computeSemanticDigest21(specDir, spec);
2721
+ if (computed.errors.length > 0) {
2722
+ errors.push(`spec.json.validation.semantic_review.semantic_digest: cannot recompute malformed physical topology (${computed.errors.join('; ')})`);
2723
+ } else if (review.semantic_digest !== computed.digest) {
2724
+ errors.push('spec.json.validation.semantic_review.semantic_digest: stale for current authoring, policy, topology, or research');
2725
+ }
2726
+ if (!Array.isArray(review.reviewed_criteria) || new Set(review.reviewed_criteria).size !== review.reviewed_criteria.length) {
2727
+ errors.push('spec.json.validation.semantic_review.reviewed_criteria: must be a unique array');
2728
+ } else {
2729
+ for (const criterion of criteria) if (!review.reviewed_criteria.includes(criterion)) errors.push(`semantic review missing criterion ${criterion}`);
2730
+ for (const criterion of review.reviewed_criteria) if (!criteria.includes(criterion)) errors.push(`semantic review has unknown criterion ${criterion}`);
2731
+ }
2732
+ if (!Array.isArray(review.counterexamples)) {
2733
+ errors.push('spec.json.validation.semantic_review.counterexamples: must be an array');
2734
+ return;
2735
+ }
2736
+ const fingerprints = new Map();
2737
+ const covered = new Set();
2738
+ for (const [index, counterexample] of review.counterexamples.entries()) {
2739
+ const label = `semantic_review.counterexamples[${index}]`;
2740
+ const expected = ['criterion', 'case_kind', 'scenario', 'expected', 'decision_refs', 'verification_ref'];
2741
+ if (!isPlainObject(counterexample) || Object.keys(counterexample).sort().join(',') !== expected.sort().join(',')) {
2742
+ errors.push(`${label}: fields must be exactly ${expected.join(', ')}`);
2743
+ continue;
2744
+ }
2745
+ if (!criteria.includes(counterexample.criterion)) errors.push(`${label}.criterion: unknown criterion ${counterexample.criterion}`);
2746
+ if (covered.has(counterexample.criterion)) errors.push(`${label}.criterion: duplicate counterexample for ${counterexample.criterion}`);
2747
+ covered.add(counterexample.criterion);
2748
+ if (!['negative', 'boundary', 'failure', 'recovery', 'adversarial'].includes(counterexample.case_kind)) {
2749
+ errors.push(`${label}.case_kind: must name a concrete semantic case kind`);
2750
+ }
2751
+ for (const field of ['scenario', 'expected']) {
2752
+ const value = counterexample[field];
2753
+ if (!concreteSemanticReviewText(value) || /^(?:works?|fails?|handles? (?:it|error)|correct behavior|expected behavior)$/i.test(String(value).trim())) {
2754
+ errors.push(`${label}.${field}: obvious placeholder or generic boilerplate; structural checks do not replace semantic judgment`);
2755
+ }
2756
+ }
2757
+ const fingerprint = [counterexample.case_kind, counterexample.scenario, counterexample.expected]
2758
+ .map((value) => String(value).toLowerCase().replace(/\bR\d+(?:\.\d+)?\b/gi, '').replace(/[^a-z0-9]+/g, ' ').trim()).join('|');
2759
+ if (fingerprints.has(fingerprint)) {
2760
+ errors.push(`${label}: normalized duplicate counterexample fingerprint also used by ${fingerprints.get(fingerprint)}; structural checks do not replace semantic judgment`);
2761
+ } else fingerprints.set(fingerprint, counterexample.criterion);
2762
+ if (!Array.isArray(counterexample.decision_refs) || counterexample.decision_refs.length === 0) {
2763
+ errors.push(`${label}.decision_refs: requires at least one D/I/C ref`);
2764
+ } else for (const ref of counterexample.decision_refs) {
2765
+ if (!/^[DIC]\d+(?:\.\d+)?$/i.test(ref) || !designIds.has(ref.toUpperCase())) errors.push(`${label}.decision_refs: ${ref} does not exist in design.md`);
2766
+ }
2767
+ const verificationRef = String(counterexample.verification_ref || '').toUpperCase();
2768
+ const definition = verificationDefs.get(verificationRef);
2769
+ if (!definition) errors.push(`${label}.verification_ref: ${verificationRef || '(empty)'} has no V definition in design.md`);
2770
+ else {
2771
+ const definitionCriteria = [...definition.subject_criteria, ...definition.proof_criteria];
2772
+ if (!definitionCriteria.includes(counterexample.criterion)) errors.push(`${label}.verification_ref: ${verificationRef} does not trace criterion ${counterexample.criterion}`);
2773
+ for (const ref of counterexample.decision_refs || []) {
2774
+ if (!definition.decision_refs.includes(ref.toUpperCase())) errors.push(`${label}.verification_ref: ${verificationRef} does not trace decision ${ref}`);
2775
+ }
2776
+ }
2777
+ }
2778
+ for (const criterion of criteria) if (!covered.has(criterion)) errors.push(`semantic review counterexamples missing criterion ${criterion}`);
2779
+ if (spec.workflow_policy?.assurance_level === 'Strict' && SHA256_RE.test(review.semantic_digest || '')) {
2780
+ try {
2781
+ const authority = require('../hooks/semantic-review-authority.cjs');
2782
+ const root = canonicalProjectRoot(specDir);
2783
+ const attestation = authority.verifyAttestation(root, path.join(specDir, 'spec.json'), spec.feature_name, review.semantic_digest);
2784
+ if (!attestation.ok) errors.push(`spec.json.validation.semantic_review: Strict readiness requires matching allowlisted host-observed reviewer PASS attestation (${attestation.reason})`);
2785
+ } catch (error) {
2786
+ errors.push(`spec.json.validation.semantic_review: Strict readiness attestation is unavailable (${error.message})`);
2787
+ }
2788
+ }
2789
+ }
2790
+
2791
+ function validateDecisionState21(spec, errors) {
2792
+ if (!Object.prototype.hasOwnProperty.call(spec, 'decisions')) return;
2793
+ if (!Array.isArray(spec.decisions) || spec.decisions.length === 0) {
2794
+ errors.push('spec.json.decisions: omit when no decisions exist; otherwise use a non-empty array');
2795
+ return;
2796
+ }
2797
+ const ids = new Set();
2798
+ for (const [index, decision] of spec.decisions.entries()) {
2799
+ const label = `spec.json.decisions[${index}]`;
2800
+ const fields = ['id', 'classification', 'statement', 'status', 'evidence'];
2801
+ if (!isPlainObject(decision) || Object.keys(decision).sort().join(',') !== fields.sort().join(',')) {
2802
+ errors.push(`${label}: fields must be exactly ${fields.join(', ')}`); continue;
2803
+ }
2804
+ if (!/^Q\d+$/.test(decision.id) || ids.has(decision.id)) errors.push(`${label}.id: must be a unique Qn id`);
2805
+ ids.add(decision.id);
2806
+ if (!concreteSemanticReviewText(decision.statement)) errors.push(`${label}.statement: must be concrete`);
2807
+ if (decision.classification === 'repository_fact') {
2808
+ if (decision.status !== 'grounded' || !concreteSemanticReviewText(decision.evidence)) errors.push(`${label}: repository_fact requires grounded status and repository evidence`);
2809
+ } else if (decision.classification === 'reversible_assumption') {
2810
+ if (decision.status !== 'recorded' || !concreteSemanticReviewText(decision.evidence)) errors.push(`${label}: reversible_assumption requires recorded status and a bounded reversal boundary`);
2811
+ } else if (decision.classification === 'user_owned') {
2812
+ if (!['unresolved', 'resolved'].includes(decision.status)) errors.push(`${label}.status: user_owned must be unresolved or resolved`);
2813
+ if (decision.status === 'unresolved' && decision.evidence !== null) errors.push(`${label}.evidence: unresolved user_owned decision must be null`);
2814
+ if (decision.status === 'resolved' && !concreteSemanticReviewText(decision.evidence)) errors.push(`${label}.evidence: resolved user_owned decision requires the user resolution`);
2815
+ if (decision.status === 'unresolved' && spec.ready_for_implementation === true) errors.push(`${label}: unresolved material user-owned decision blocks readiness`);
2816
+ } else errors.push(`${label}.classification: must be repository_fact, reversible_assumption, or user_owned`);
2817
+ }
2818
+ }
2819
+
2820
+ function canonicalDesignDefinitions(designText, kind, errors) {
2821
+ const definitions = new Map();
2822
+ const semantic = semanticMarkdown(designText);
2823
+ const heading = new RegExp(`^#{3,6}\\s+(${kind}\\d+(?:\\.\\d+)?)\\s+(?:—|-)\\s+(.+)$`, 'gim');
2824
+ const matches = [...semantic.matchAll(heading)];
2825
+ for (const [index, match] of matches.entries()) {
2826
+ const nextHeading = semantic.slice(match.index + match[0].length).search(/^#{1,6}\s+/m);
2827
+ const end = nextHeading < 0 ? semantic.length : match.index + match[0].length + nextHeading;
2828
+ const definition = semantic.slice(match.index + match[0].length, end).trim();
2829
+ const id = match[1].toUpperCase();
2830
+ if (definitions.has(id)) errors.push(`design.md: duplicate canonical ${kind} definition ${id}`);
2831
+ else definitions.set(id, definition);
2832
+ }
2833
+ const bullet = new RegExp(`^\\s*(?:[-*]\\s*)?\\*\\*(${kind}\\d+(?:\\.\\d+)?)\\*\\*\\s*[:—-]\\s*(.+)$`, 'gim');
2834
+ for (const match of semantic.matchAll(bullet)) {
2835
+ const id = match[1].toUpperCase();
2836
+ if (definitions.has(id)) errors.push(`design.md: duplicate canonical ${kind} definition ${id}`);
2837
+ else definitions.set(id, match[2].trim());
2838
+ }
2839
+ return definitions;
2840
+ }
2841
+
2842
+ function boundaryParticipants(boundary) {
2843
+ if (boundary.type === 'ownership' || boundary.type === 'parallel') return boundary.tasks || [];
2844
+ if (boundary.type === 'dependency') return [boundary.producer, boundary.consumer];
2845
+ if (boundary.type === 'transition') return [boundary.owner, ...(boundary.consumers || [])];
2846
+ if (boundary.type === 'proof') return [boundary.subject, boundary.verifier];
2847
+ return [];
2848
+ }
2849
+
2850
+ function validateTaskCriterionGraph(
2851
+ taskFiles, registry, criteriaByTask, verificationRefsByTask, taskRolesByTask,
2852
+ knownCriteria, boundaries, verificationDefinitions, errors,
2853
+ ) {
2854
+ if (taskFiles.length === 0) return;
2855
+ const owners = new Map(knownCriteria.map((criterion) => [criterion, []]));
2856
+ for (const taskPath of taskFiles) {
2857
+ for (const criterion of criteriaByTask.get(taskPath) || []) {
2858
+ if (!owners.has(criterion)) errors.push(`${taskPath}: Acceptance references unknown criterion ${criterion}`);
2859
+ else owners.get(criterion).push(registry[taskPath]?.id);
2860
+ }
2861
+ }
2862
+ for (const [criterion, taskIds] of owners) {
2863
+ if (taskIds.length === 0) errors.push(`requirements.md:${criterion}: acceptance criterion not covered by any task`);
2864
+ if (taskIds.length > 1) errors.push(`requirements.md:${criterion}: requires exactly one implementation owner; claimed by ${taskIds.join(', ')}`);
2865
+ }
2866
+ for (const taskPath of taskFiles) {
2867
+ for (const verificationRef of verificationRefsByTask.get(taskPath) || []) {
2868
+ const definition = verificationDefinitions.get(verificationRef);
2869
+ if (!definition) {
2870
+ errors.push(`${taskPath}: Verification ref ${verificationRef} has no concrete canonical V definition`);
2871
+ continue;
2872
+ }
2873
+ const definitionCriteria = [...definition.subject_criteria, ...definition.proof_criteria];
2874
+ for (const criterion of criteriaByTask.get(taskPath) || []) if (!definitionCriteria.includes(criterion)) {
2875
+ errors.push(`${taskPath}: Verification ref ${verificationRef} does not trace owned criterion ${criterion}`);
2876
+ }
2877
+ }
2878
+ }
2879
+ for (const boundary of (boundaries || []).filter((item) => item?.type === 'proof')) {
2880
+ const subjectPath = taskFiles.find((candidate) => registry[candidate]?.id === boundary.subject);
2881
+ const verifierPath = taskFiles.find((candidate) => registry[candidate]?.id === boundary.verifier);
2882
+ const subjectCriteria = criteriaByTask.get(subjectPath) || [];
2883
+ const verifierCriteria = criteriaByTask.get(verifierPath) || [];
2884
+ if (taskRolesByTask.get(subjectPath) !== 'subject') errors.push(`${subjectPath || boundary.subject}: proof subject must declare Task role subject`);
2885
+ if (taskRolesByTask.get(verifierPath) !== 'verifier') errors.push(`${verifierPath || boundary.verifier}: proof verifier must declare Task role verifier`);
2886
+ if (subjectCriteria.length === 0) errors.push(`${subjectPath || boundary.subject}: proof subject requires at least one implementation criterion`);
2887
+ if (verifierCriteria.length === 0) errors.push(`${verifierPath || boundary.verifier}: proof verifier requires a separately owned proof criterion`);
2888
+ for (const criterion of verifierCriteria) if (subjectCriteria.includes(criterion)) {
2889
+ errors.push(`${verifierPath || boundary.verifier}: proof verifier criterion ${criterion} duplicates subject implementation ownership`);
2890
+ }
2891
+ const definition = verificationDefinitions.get(String(boundary.verification_ref).toUpperCase());
2892
+ const definitionCriteria = definition ? [...definition.subject_criteria, ...definition.proof_criteria] : [];
2893
+ for (const criterion of [...subjectCriteria, ...verifierCriteria]) if (definition && !definitionCriteria.includes(criterion)) {
2894
+ errors.push(`${boundary.id}: shared V definition must trace subject and verifier criterion ${criterion}`);
2895
+ }
2896
+ for (const taskId of [boundary.subject, boundary.verifier]) {
2897
+ const taskPath = taskFiles.find((candidate) => registry[candidate]?.id === taskId);
2898
+ if (taskPath && !(verificationRefsByTask.get(taskPath) || []).includes(String(boundary.verification_ref).toUpperCase())) {
2899
+ errors.push(`${taskPath}: proof boundary ${boundary.id} must match task Verification ref ${boundary.verification_ref}`);
2900
+ }
2901
+ }
2902
+ }
2903
+ }
2904
+
2905
+ function validateBoundaries21(spec, taskFiles, registry, anchorsByTask, criteriaByTask, designText, verificationDefinitions, errors) {
2906
+ if (!isPlainObject(spec.coordination) || !Array.isArray(spec.coordination.boundaries)) {
2907
+ errors.push('spec.json.coordination.boundaries: must be an array');
2908
+ return;
2909
+ }
2910
+ const allowedCoordination = new Set(['boundaries', 'phases']);
2911
+ for (const key of Object.keys(spec.coordination)) if (!allowedCoordination.has(key)) {
2912
+ errors.push(`spec.json.coordination.${key}: marker/task trigger authority is not canonical in schema 2.1`);
2913
+ }
2914
+ if (taskFiles.length > 0 && spec.coordination.boundaries.length === 0) {
2915
+ errors.push('physical task bundle requires at least one typed coordination boundary with semantic evidence');
2916
+ }
2917
+ const pathById = new Map(taskFiles.map((taskPath) => [registry[taskPath]?.id, taskPath]));
2918
+ const taskIds = new Set(pathById.keys());
2919
+ const boundaryIds = new Set();
2920
+ const boundaryById = new Map();
2921
+ const dependencyEdges = [];
2922
+ const authorityByTask = new Map(taskFiles.map((taskPath) => [registry[taskPath]?.id, new Set()]));
2923
+ const transitionDefinitions = canonicalDesignDefinitions(designText, 'T', errors);
2924
+ const taskList = (value, label, minimum = 1) => {
2925
+ if (!Array.isArray(value) || value.length < minimum || new Set(value).size !== value.length) {
2926
+ errors.push(`${label}: must contain at least ${minimum} unique task id(s)`);
2927
+ return [];
2928
+ }
2929
+ for (const taskId of value) if (!taskIds.has(taskId)) errors.push(`${label}: unknown task ${taskId}`);
2930
+ return value;
2931
+ };
2932
+ const validateTargetMap = (value, tasks, label) => {
2933
+ if (!isPlainObject(value) || Object.keys(value).sort().join(',') !== [...tasks].sort().join(',')) {
2934
+ errors.push(`${label}: must be keyed exactly by boundary tasks`); return;
2935
+ }
2936
+ for (const taskId of tasks) {
2937
+ if (!Array.isArray(value[taskId]) || value[taskId].length === 0 || new Set(value[taskId]).size !== value[taskId].length) {
2938
+ errors.push(`${label}.${taskId}: must be a non-empty array of unique exact targets`);
2939
+ continue;
2940
+ }
2941
+ for (const target of value[taskId]) if (!exactTaskTarget(target)) errors.push(`${label}.${taskId}: ${target} is not an exact target`);
2942
+ }
2943
+ for (let left = 0; left < tasks.length; left += 1) for (let right = left + 1; right < tasks.length; right += 1) {
2944
+ for (const a of value[tasks[left]] || []) for (const b of value[tasks[right]] || []) {
2945
+ if (targetsContend(a, b)) errors.push(`${label}: parent/child or exact resource contention ${a} vs ${b}`);
2946
+ }
2947
+ }
2948
+ };
2949
+ for (const [index, boundary] of spec.coordination.boundaries.entries()) {
2950
+ const label = `spec.json.coordination.boundaries[${index}]`;
2951
+ const fields = BOUNDARY_21_FIELDS[boundary?.type];
2952
+ if (!fields || !isPlainObject(boundary) || Object.keys(boundary).sort().join(',') !== [...(fields || [])].sort().join(',')) {
2953
+ errors.push(`${label}: malformed typed boundary`); continue;
2954
+ }
2955
+ if (boundaryIds.has(boundary.id)) errors.push(`${label}: duplicate boundary ID ${boundary.id}`);
2956
+ boundaryIds.add(boundary.id);
2957
+ boundaryById.set(boundary.id, boundary);
2958
+ if (boundary.type === 'ownership') {
2959
+ const tasks = taskList(boundary.tasks, `${label}.tasks`, 2);
2960
+ validateTargetMap(boundary.write_sets, tasks, `${label}.write_sets`);
2961
+ for (const taskId of tasks) {
2962
+ const taskWrites = new Set((anchorsByTask.get(pathById.get(taskId)) || []).filter((anchor) => anchor.access === 'write').map((anchor) => anchor.target));
2963
+ const declaredWrites = new Set(boundary.write_sets?.[taskId] || []);
2964
+ for (const target of boundary.write_sets?.[taskId] || []) if (!taskWrites.has(target)) errors.push(`${label}.write_sets.${taskId}: ${target} lacks exact task write anchor`);
2965
+ for (const target of taskWrites) if (!declaredWrites.has(target)) errors.push(`${label}.write_sets.${taskId}: missing exact task write target ${target}`);
2966
+ }
2967
+ } else if (boundary.type === 'dependency') {
2968
+ taskList([boundary.producer, boundary.consumer], label, 2);
2969
+ if (boundary.producer === boundary.consumer) errors.push(`${label}: producer and consumer must differ`);
2970
+ if (!exactTaskTarget(boundary.deliverable)) errors.push(`${label}.deliverable: missing exact deliverable`);
2971
+ dependencyEdges.push([boundary.producer, boundary.consumer, boundary.deliverable]);
2972
+ const producerPath = pathById.get(boundary.producer);
2973
+ const consumerPath = pathById.get(boundary.consumer);
2974
+ const producerAnchors = anchorsByTask.get(producerPath) || [];
2975
+ const consumerAnchors = anchorsByTask.get(consumerPath) || [];
2976
+ if (!producerAnchors.some((anchor) => anchor.target === boundary.deliverable && anchor.access === 'write')) {
2977
+ errors.push(`${label}.deliverable: producer ${boundary.producer} must own an exact write anchor for ${boundary.deliverable}`);
2978
+ }
2979
+ if (!consumerAnchors.some((anchor) => anchor.target === boundary.deliverable && anchor.access === 'read')) {
2980
+ errors.push(`${label}.deliverable: consumer ${boundary.consumer} must own an exact read anchor for ${boundary.deliverable}`);
2981
+ }
2982
+ if (!registry[consumerPath]?.dependencies?.includes(producerPath)) errors.push(`${label}: dependency boundary must bind the registry DAG edge`);
2983
+ } else if (boundary.type === 'transition') {
2984
+ taskList([boundary.owner], `${label}.owner`);
2985
+ taskList(boundary.consumers, `${label}.consumers`);
2986
+ if (boundary.consumers.includes(boundary.owner)) errors.push(`${label}.consumers: transition owner cannot also be its consumer`);
2987
+ const transitionDefinition = transitionDefinitions.get(String(boundary.design_ref).toUpperCase());
2988
+ if (!transitionDefinition || !concreteSemanticReviewText(transitionDefinition)) errors.push(`${label}.design_ref: missing canonical design T definition`);
2989
+ for (const field of ['precondition', 'postcondition', 'failure', 'recovery']) if (!concreteSemanticReviewText(boundary[field])) errors.push(`${label}.${field}: missing concrete transition definition`);
2990
+ for (const taskId of [boundary.owner, ...boundary.consumers]) authorityByTask.get(taskId)?.add(boundary.id);
2991
+ } else if (boundary.type === 'proof') {
2992
+ taskList([boundary.subject, boundary.verifier], label, 2);
2993
+ if (boundary.subject === boundary.verifier) errors.push(`${label}: proof subject must differ from verifier`);
2994
+ const verificationDefinition = verificationDefinitions.get(String(boundary.verification_ref).toUpperCase());
2995
+ if (!verificationDefinition) errors.push(`${label}.verification_ref: missing canonical V definition`);
2996
+ else {
2997
+ if (verificationDefinition.subject_owner !== boundary.subject) errors.push(`${label}.subject: must match semantic V subject_owner`);
2998
+ if (verificationDefinition.proof_owner !== boundary.verifier) errors.push(`${label}.verifier: must match semantic V proof_owner`);
2999
+ if (verificationDefinition.evidence_anchor !== boundary.artifact_anchor) errors.push(`${label}.artifact_anchor: must match semantic V evidence_anchor`);
3000
+ }
3001
+ const verifierPath = pathById.get(boundary.verifier);
3002
+ const proofAnchor = (anchorsByTask.get(verifierPath) || []).find((anchor) => anchor.id === boundary.artifact_anchor);
3003
+ const observableProofAnchor = proofAnchor?.role === 'verifier' && (
3004
+ (proofAnchor.type === 'command' && proofAnchor.access === 'read' && proofAnchor.action === 'read')
3005
+ || (proofAnchor.type === 'artifact' && proofAnchor.access === 'write' && ['create', 'modify'].includes(proofAnchor.action))
3006
+ );
3007
+ if (!observableProofAnchor) errors.push(`${label}.artifact_anchor: must be owned by verifier ${boundary.verifier} as an observable command or output artifact anchor; a source write is not proof`);
3008
+ const subjectPath = pathById.get(boundary.subject);
3009
+ const subjectCriteria = criteriaByTask.get(subjectPath) || [];
3010
+ const definitionCriteria = verificationDefinition
3011
+ ? [...verificationDefinition.subject_criteria, ...verificationDefinition.proof_criteria] : [];
3012
+ if (verificationDefinition && !subjectCriteria.some((criterion) => definitionCriteria.includes(criterion))) {
3013
+ errors.push(`${label}.verification_ref: canonical V definition must trace a criterion owned by proof subject ${boundary.subject}`);
3014
+ }
3015
+ authorityByTask.get(boundary.subject)?.add(boundary.id);
3016
+ authorityByTask.get(boundary.verifier)?.add(boundary.id);
3017
+ } else if (boundary.type === 'parallel') {
3018
+ const tasks = taskList(boundary.tasks, `${label}.tasks`, 2);
3019
+ validateTargetMap(boundary.resources, tasks, `${label}.resources`);
3020
+ for (const taskId of tasks) {
3021
+ const taskWrites = (anchorsByTask.get(pathById.get(taskId)) || []).filter((anchor) => anchor.access === 'write').map((anchor) => anchor.target);
3022
+ const resources = [...(boundary.resources?.[taskId] || [])].sort();
3023
+ if (JSON.stringify([...new Set(taskWrites)].sort()) !== JSON.stringify(resources)) {
3024
+ errors.push(`${label}.resources.${taskId}: must exactly equal task write resources`);
3025
+ }
3026
+ }
3027
+ }
3028
+ }
3029
+ const participation = new Map([...taskIds].map((taskId) => [taskId, 0]));
3030
+ for (const boundary of spec.coordination.boundaries) {
3031
+ for (const taskId of new Set(boundaryParticipants(boundary))) if (participation.has(taskId)) {
3032
+ participation.set(taskId, participation.get(taskId) + 1);
3033
+ }
3034
+ }
3035
+ for (const [taskId, count] of participation) if (count === 0) {
3036
+ errors.push(`spec.json.coordination.boundaries: task ${taskId} must participate in at least one justified typed boundary`);
3037
+ }
3038
+ for (const taskPath of taskFiles) {
3039
+ const expected = dependencyEdges.filter(([, consumer]) => consumer === registry[taskPath]?.id).map(([producer]) => pathById.get(producer)).sort();
3040
+ if (JSON.stringify([...(registry[taskPath]?.dependencies || [])].sort()) !== JSON.stringify(expected)) errors.push(`${taskPath}: registry dependencies must be an exact projection of dependency boundaries`);
3041
+ }
3042
+ if (Object.prototype.hasOwnProperty.call(spec.coordination, 'phases')) {
3043
+ if (!Array.isArray(spec.coordination.phases) || spec.coordination.phases.length === 0) {
3044
+ errors.push('spec.json.coordination.phases: must be a non-empty compact metadata array');
3045
+ } else {
3046
+ const phaseIds = new Set();
3047
+ for (const [index, phase] of spec.coordination.phases.entries()) {
3048
+ const label = `spec.json.coordination.phases[${index}]`;
3049
+ const fields = ['id', 'task_ids', 'entry_condition', 'exit_condition', 'owner_boundary'];
3050
+ if (!isPlainObject(phase) || Object.keys(phase).sort().join(',') !== fields.sort().join(',')) {
3051
+ errors.push(`${label}: fields must be exactly ${fields.join(', ')}`); continue;
3052
+ }
3053
+ if (phaseIds.has(phase.id)) errors.push(`${label}: duplicate phase id ${phase.id}`);
3054
+ phaseIds.add(phase.id);
3055
+ taskList(phase.task_ids, `${label}.task_ids`);
3056
+ const ownerBoundary = boundaryById.get(phase.owner_boundary);
3057
+ if (!ownerBoundary) errors.push(`${label}.owner_boundary: unknown boundary ${phase.owner_boundary}`);
3058
+ else {
3059
+ const participants = [...new Set(boundaryParticipants(ownerBoundary))].sort();
3060
+ const phaseTasks = [...new Set(phase.task_ids || [])].sort();
3061
+ if (!['dependency', 'transition', 'proof'].includes(ownerBoundary.type)) {
3062
+ errors.push(`${label}.owner_boundary: ${ownerBoundary.type} cannot own phase progression`);
3063
+ }
3064
+ if (JSON.stringify(participants) !== JSON.stringify(phaseTasks)) {
3065
+ errors.push(`${label}.owner_boundary: participants must match phase task_ids exactly`);
3066
+ }
3067
+ }
3068
+ for (const field of ['entry_condition', 'exit_condition']) if (!concreteSemanticReviewText(phase[field])) errors.push(`${label}.${field}: must be concrete`);
3069
+ }
3070
+ const phaseTasks = spec.coordination.phases.flatMap((phase) => Array.isArray(phase?.task_ids) ? phase.task_ids : []);
3071
+ const counts = new Map([...taskIds].map((taskId) => [taskId, phaseTasks.filter((candidate) => candidate === taskId).length]));
3072
+ for (const [taskId, count] of counts) if (count !== 1) {
3073
+ errors.push(`spec.json.coordination.phases: task ${taskId} must appear in exactly one phase (found ${count})`);
3074
+ }
3075
+ }
3076
+ }
3077
+ const graph = new Map([...taskIds].map((taskId) => [taskId, []]));
3078
+ for (const [producer, consumer] of dependencyEdges) graph.get(producer)?.push(consumer);
3079
+ const visiting = new Set();
3080
+ const visited = new Set();
3081
+ const visit = (taskId, stack = []) => {
3082
+ if (visiting.has(taskId)) {
3083
+ const start = stack.indexOf(taskId);
3084
+ errors.push(`spec.json.coordination.boundaries: dependency cycle ${stack.slice(start).concat(taskId).join(' -> ')}`);
3085
+ return;
3086
+ }
3087
+ if (visited.has(taskId)) return;
3088
+ visiting.add(taskId);
3089
+ for (const next of graph.get(taskId) || []) visit(next, [...stack, taskId]);
3090
+ visiting.delete(taskId);
3091
+ visited.add(taskId);
3092
+ };
3093
+ for (const taskId of taskIds) visit(taskId);
3094
+ const pathExists = (from, to, seen = new Set()) => {
3095
+ if (from === to) return true;
3096
+ if (seen.has(from)) return false;
3097
+ seen.add(from);
3098
+ return (graph.get(from) || []).some((next) => pathExists(next, to, seen));
3099
+ };
3100
+ for (const boundary of spec.coordination.boundaries.filter((item) => item.type === 'parallel')) {
3101
+ for (let left = 0; left < boundary.tasks.length; left += 1) for (let right = left + 1; right < boundary.tasks.length; right += 1) {
3102
+ const a = boundary.tasks[left]; const b = boundary.tasks[right];
3103
+ if (pathExists(a, b) || pathExists(b, a)) errors.push(`${boundary.id}: parallel tasks have a dependency path`);
3104
+ for (const authority of authorityByTask.get(a) || []) if (authorityByTask.get(b)?.has(authority)) errors.push(`${boundary.id}: parallel tasks share transition/proof authority ${authority}`);
3105
+ }
3106
+ }
3107
+ }
3108
+
3109
+ function validateResearchLifecycle21(specDir, canonicalSpecDir, spec, errors) {
3110
+ const state = spec.authoring?.research;
3111
+ const hasPointer = Object.prototype.hasOwnProperty.call(spec, 'research');
3112
+ const artifact = inspectSpecArtifact(specDir, canonicalSpecDir, 'research.md', 'research.md', errors);
3113
+ if (state === 'absent') {
3114
+ if (hasPointer) errors.push('spec.json.research: authoring.research absent requires no pointer');
3115
+ if (artifact) errors.push('research.md: authoring.research absent requires no physical artifact');
3116
+ return null;
3117
+ }
3118
+ if (state === 'draft' || state === 'validated') {
3119
+ if (spec.research !== 'research.md') errors.push(`spec.json.research: authoring.research ${state} requires canonical pointer research.md`);
3120
+ if (!artifact) errors.push(`research.md: authoring.research ${state} requires a physical regular file`);
3121
+ else validateResearchArtifact21(artifact, canonicalSpecDir, errors);
3122
+ return artifact;
3123
+ }
3124
+ return artifact;
3125
+ }
3126
+
3127
+ function validateSpec21(specDir, canonicalSpecDir, spec, errors, warnings) {
3128
+ const allowedFields = new Set([...SPEC_21_REQUIRED_FIELDS, ...SPEC_21_OPTIONAL_FIELDS]);
3129
+ for (const field of SPEC_21_REQUIRED_FIELDS) if (!Object.prototype.hasOwnProperty.call(spec, field)) {
3130
+ errors.push(`spec.json.${field}: required by closed schema 2.1 machine state`);
3131
+ }
3132
+ for (const field of Object.keys(spec)) if (!allowedFields.has(field)) {
3133
+ errors.push(`spec.json.${field}: unknown or legacy field is not canonical in closed schema 2.1`);
3134
+ }
3135
+ const policy = POLICY.validateWorkflowPolicySnapshot(spec.workflow_policy);
3136
+ if (!policy.valid || spec.workflow_policy?.version !== SCHEMA_21) {
3137
+ errors.push(...policy.errors.map((error) => `spec.json.${error}`));
3138
+ if (spec.workflow_policy?.version !== SCHEMA_21) errors.push('spec.json.workflow_policy.version: schema 2.1 mutation requires policy 2.1');
3139
+ }
3140
+ const authoringFields = ['requirements', 'design', 'research', 'tasks'];
3141
+ if (!isPlainObject(spec.authoring) || Object.keys(spec.authoring).sort().join(',') !== authoringFields.sort().join(',')) {
3142
+ errors.push(`spec.json.authoring: fields must be exactly ${authoringFields.join(', ')}`);
3143
+ } else for (const [artifact, state] of Object.entries(spec.authoring)) {
3144
+ if (!['draft', 'validated', 'absent'].includes(state)) errors.push(`spec.json.authoring.${artifact}: must be draft, validated, or absent`);
3145
+ }
3146
+ if (Object.prototype.hasOwnProperty.call(spec, 'approvals')) errors.push('spec.json.approvals: legacy approval semantics are inert and not canonical in schema 2.1');
3147
+ const scopeFields = ['source', 'in_scope', 'out_of_scope', 'expansion_policy'];
3148
+ if (isPlainObject(spec.scope_lock)
3149
+ && Object.keys(spec.scope_lock).sort().join(',') !== [...scopeFields].sort().join(',')) {
3150
+ errors.push(`spec.json.scope_lock: fields must be exactly ${scopeFields.join(', ')}`);
3151
+ }
3152
+ if (isPlainObject(spec.scope_lock)) {
3153
+ if (typeof spec.scope_lock.source !== 'string' || spec.scope_lock.source.trim() === '') errors.push('spec.json.scope_lock.source: must be a non-empty string');
3154
+ for (const field of ['in_scope', 'out_of_scope']) {
3155
+ const values = spec.scope_lock[field];
3156
+ if (!Array.isArray(values) || values.some((value) => typeof value !== 'string' || value.trim() !== value || value === '')
3157
+ || new Set(values || []).size !== (values || []).length) {
3158
+ errors.push(`spec.json.scope_lock.${field}: must be an array of unique non-empty trimmed strings`);
3159
+ }
3160
+ }
3161
+ if (spec.scope_lock.expansion_policy !== 'requires-user-approval') errors.push('spec.json.scope_lock.expansion_policy: must be requires-user-approval');
3162
+ }
3163
+ if (isPlainObject(spec.validation)
3164
+ && Object.keys(spec.validation).sort().join(',') !== 'semantic_review,status') {
3165
+ errors.push('spec.json.validation: fields must be exactly status, semantic_review');
3166
+ }
3167
+ const taskFiles = listTaskFiles(specDir, canonicalSpecDir, errors);
3168
+ validateCoreMachineState(spec, taskFiles, errors, { schema21: true });
3169
+ validateDecisionState21(spec, errors);
3170
+ validateResearchLifecycle21(specDir, canonicalSpecDir, spec, errors);
3171
+ if (taskFiles.length === 0) {
3172
+ if (Object.prototype.hasOwnProperty.call(spec, 'task_files') || Object.prototype.hasOwnProperty.call(spec, 'task_registry')) errors.push('taskless schema 2.1 must omit task_files and task_registry');
3173
+ if (spec.authoring?.tasks !== 'absent') errors.push('spec.json.authoring.tasks: taskless spec must be absent');
3174
+ } else {
3175
+ if (JSON.stringify([...(spec.task_files || [])].sort()) !== JSON.stringify(taskFiles)) errors.push('spec.json.task_files: must exactly match physical tasks');
3176
+ if (!isPlainObject(spec.task_registry) || Object.keys(spec.task_registry).sort().join(',') !== taskFiles.join(',')) errors.push('spec.json.task_registry: must exactly match physical tasks');
3177
+ if (!['draft', 'validated'].includes(spec.authoring?.tasks)) errors.push('spec.json.authoring.tasks: physical tasks require draft or validated');
3178
+ }
3179
+ const requirementsText = fs.readFileSync(path.join(specDir, 'requirements.md'), 'utf8');
3180
+ const designText = fs.readFileSync(path.join(specDir, 'design.md'), 'utf8');
3181
+ const projection = SEMANTIC.modelFromMarkdown(canonicalSpecDir, spec);
3182
+ errors.push(...projection.errors.map((error) => `semantic projection: ${error}`));
3183
+ if (!isPlainObject(spec.semantic_model)) {
3184
+ errors.push('spec.json.semantic_model: schema 2.1 requires explicit promoted machine semantic authority');
3185
+ } else {
3186
+ errors.push(...SEMANTIC.validateSemanticModel(spec.semantic_model, spec));
3187
+ if (SEMANTIC.stableJson(spec.semantic_model) !== SEMANTIC.stableJson(projection.model)) {
3188
+ errors.push('spec.json.semantic_model: differs from Markdown projection; rerun spec-readiness with the current semantic review result');
3189
+ }
3190
+ }
3191
+ const authorityModel = isPlainObject(spec.semantic_model) ? spec.semantic_model : projection.model;
3192
+ const verificationDefinitions = new Map((authorityModel.verification_definitions || []).map((definition) => [definition.id, definition]));
3193
+ const designIds = new Set(designSemanticReviewIds(designText));
3194
+ for (const definition of verificationDefinitions.values()) for (const decisionRef of definition.decision_refs) {
3195
+ if (!designIds.has(decisionRef)) errors.push(`spec.json.semantic_model.${definition.id}: decision ref ${decisionRef} does not exist in design.md`);
3196
+ }
3197
+ const designAnchors = (authorityModel.anchors || []).filter((anchor) => /^A-D-/.test(anchor.id)).map((anchor) => ({
3198
+ ...anchor, label: 'design.md', design: true, schema21: true,
3199
+ }));
3200
+ validateRequirementInventory(requirementsText, errors);
3201
+ const criteria = (authorityModel.criteria || []).map((criterion) => criterion.id);
3202
+ const anchorsByTask = new Map();
3203
+ const criteriaByTask = new Map();
3204
+ const verificationRefsByTask = new Map();
3205
+ const taskRolesByTask = new Map();
3206
+ const taskContents = new Map();
3207
+ for (const taskPath of taskFiles) {
3208
+ const content = fs.readFileSync(path.join(specDir, taskPath), 'utf8');
3209
+ const task = validateTask21(taskPath, content, spec.task_registry?.[taskPath], errors);
3210
+ taskContents.set(taskPath, content);
3211
+ anchorsByTask.set(taskPath, task.anchors);
3212
+ criteriaByTask.set(taskPath, task.criteria);
3213
+ verificationRefsByTask.set(taskPath, task.verificationRefs);
3214
+ taskRolesByTask.set(taskPath, task.taskRole);
3215
+ }
3216
+ const anchorsById = new Map();
3217
+ const designTargets = new Map(designAnchors.map((anchor) => [`${anchor.type}\0${anchor.target}`, anchor]));
3218
+ for (const anchor of [...designAnchors, ...[...anchorsByTask.values()].flat()]) {
3219
+ if (anchorsById.has(anchor.id)) errors.push(`${anchor.label}: duplicate anchor ID ${anchor.id}; first declared in ${anchorsById.get(anchor.id).label}`);
3220
+ else anchorsById.set(anchor.id, anchor);
3221
+ if (!anchor.design && designTargets.has(`${anchor.type}\0${anchor.target}`)) {
3222
+ errors.push(`${anchor.label}: anchor ${anchor.id} duplicates canonical design target ${designTargets.get(`${anchor.type}\0${anchor.target}`).id}`);
3223
+ }
3224
+ }
3225
+ for (const [taskPath, content] of taskContents) for (const reference of content.match(/\bA-D-\d{2}\b/g) || []) {
3226
+ if (!anchorsById.has(reference)) errors.push(`${taskPath}: dangling canonical design anchor reference ${reference}`);
3227
+ }
3228
+ validateTaskCriterionGraph(
3229
+ taskFiles,
3230
+ spec.task_registry || {},
3231
+ criteriaByTask,
3232
+ verificationRefsByTask,
3233
+ taskRolesByTask,
3234
+ criteria,
3235
+ spec.coordination?.boundaries,
3236
+ verificationDefinitions,
3237
+ errors,
3238
+ );
3239
+ validateBoundaries21(
3240
+ spec, taskFiles, spec.task_registry || {}, anchorsByTask, criteriaByTask,
3241
+ designText, verificationDefinitions, errors,
3242
+ );
3243
+ validateSemanticReview21(specDir, spec, criteria, designIds, verificationDefinitions, errors);
3244
+ if (spec.ready_for_implementation === true) {
3245
+ for (const artifact of ['requirements', 'design']) if (spec.authoring?.[artifact] !== 'validated') errors.push(`spec.json.authoring.${artifact}: readiness requires validated`);
3246
+ if (taskFiles.length > 0 && spec.authoring?.tasks !== 'validated') errors.push('spec.json.authoring.tasks: readiness requires validated task projection');
3247
+ if (spec.research === 'research.md' && spec.authoring?.research !== 'validated') errors.push('spec.json.authoring.research: explicit research readiness requires validated');
3248
+ let projectRoot = null;
3249
+ try { projectRoot = canonicalProjectRoot(canonicalSpecDir); } catch (error) {
3250
+ errors.push(`spec.json.ready_for_implementation: canonical project root cannot be resolved (${error.message})`);
3251
+ }
3252
+ if (projectRoot) {
3253
+ const grounding = groundSpec({ specDir: canonicalSpecDir, root: projectRoot, spec });
3254
+ for (const error of grounding.errors) errors.push(`grounding: ${error}`);
3255
+ for (const warning of grounding.warnings) warnings.push(`grounding: ${warning}`);
3256
+ }
3257
+ if (errors.length > 0) errors.push('spec.json.ready_for_implementation: cannot be true while schema 2.1 semantic errors exist');
3258
+ }
3259
+ warnings.push('schema 2.1 structural checks do not replace semantic judgment');
3260
+ }
3261
+
3262
+ function validateSpec(specDir, overrideSpec) {
741
3263
  const errors = [];
742
3264
  const warnings = [];
743
3265
  const canonicalSpecDir = validateSpecRoot(specDir, errors);
@@ -753,30 +3275,39 @@ function validateSpec(specDir) {
753
3275
  const specJsonArtifact = inspectSpecArtifact(specDir, canonicalSpecDir, 'spec.json', 'spec.json', errors, { required: true });
754
3276
  if (!specJsonArtifact) return { errors, warnings };
755
3277
 
756
- const spec = readJson(specJsonArtifact.path, errors);
3278
+ const spec = overrideSpec === undefined ? readJson(specJsonArtifact.path, errors) : overrideSpec;
757
3279
  if (!spec || typeof spec !== 'object' || Array.isArray(spec)) {
758
3280
  if (errors.length === 0) errors.push('spec.json: must contain a JSON object');
759
3281
  return { errors, warnings };
760
3282
  }
761
3283
 
762
- const policyContext = workflowPolicyContext(spec, errors);
763
- if (policyContext.explicit && Object.prototype.hasOwnProperty.call(spec, 'override_receipt')) {
764
- errors.push('spec.json.override_receipt: duplicate legacy field; persist only workflow_policy.override_receipt');
3284
+ if (spec.schema_version === SCHEMA_21 && Object.prototype.hasOwnProperty.call(spec, 'override_receipt')) {
3285
+ errors.push('spec.json.override_receipt: legacy override receipt is inert read compatibility and must be omitted from canonical state');
765
3286
  }
766
3287
 
767
- if (!spec.scope_lock || typeof spec.scope_lock !== 'object' || Array.isArray(spec.scope_lock)) {
768
- errors.push('spec.json.scope_lock: must be an object, not a boolean or array');
3288
+ if (spec.schema_version === SCHEMA_21) {
3289
+ const requirements = inspectSpecArtifact(specDir, canonicalSpecDir, 'requirements.md', 'requirements.md', errors, { required: true });
3290
+ const design = inspectSpecArtifact(specDir, canonicalSpecDir, 'design.md', 'design.md', errors, { required: true });
3291
+ if (requirements && design) validateSpec21(specDir, canonicalSpecDir, spec, errors, warnings);
3292
+ return { errors, warnings };
769
3293
  }
770
3294
 
771
- validateTimestamps(spec, errors);
772
- validateStateTransitions(spec, errors, policyContext);
773
-
3295
+ const policyContext = workflowPolicyContext(spec, errors);
774
3296
  const taskFiles = listTaskFiles(specDir, canonicalSpecDir, errors);
775
3297
  const taskFileSet = new Set(taskFiles);
776
- const declaredTaskBundle = Array.isArray(spec.task_files) && spec.task_files.length > 0;
777
- const requiresTaskBundle = taskFiles.length > 0 || declaredTaskBundle || policyContext.strict;
778
- if (policyContext.strict && taskFiles.length === 0) {
779
- errors.push('strict workflow policy requires at least one task file and task registry entry');
3298
+ validateCoreMachineState(spec, taskFiles, errors);
3299
+ const topology = validateCoordinationTopology(spec, policyContext, taskFiles, specDir, errors);
3300
+ policyContext.taskRequired = topology.tasksRequired;
3301
+ const requiresTaskBundle = topology.tasksRequired;
3302
+ validateStateTransitions(spec, errors, policyContext);
3303
+ validateFinalLifecycleTimestamps(spec, taskFiles, policyContext, errors);
3304
+ if (!requiresTaskBundle && !policyContext.legacy) {
3305
+ if (Object.prototype.hasOwnProperty.call(spec, 'task_files')) {
3306
+ errors.push('spec.json.task_files: taskless Specs v2 must omit task inventory');
3307
+ }
3308
+ if (Object.prototype.hasOwnProperty.call(spec, 'task_registry')) {
3309
+ errors.push('spec.json.task_registry: taskless Specs v2 must omit task registry');
3310
+ }
780
3311
  }
781
3312
 
782
3313
  if (!Array.isArray(spec.task_files)) {
@@ -804,20 +3335,7 @@ function validateSpec(specDir) {
804
3335
  if (!taskFileSet.has(registryPath)) {
805
3336
  errors.push(`spec.json.task_registry.${registryPath}: no matching task file`);
806
3337
  }
807
- for (const key of REQUIRED_REGISTRY_KEYS) {
808
- if (!(key in (entry || {}))) {
809
- errors.push(`spec.json.task_registry.${registryPath}: missing ${key}`);
810
- }
811
- }
812
3338
  validateArtifactDeclaration(registryPath, entry, errors);
813
- if (entry && !Array.isArray(entry.dependencies)) {
814
- errors.push(`spec.json.task_registry.${registryPath}.dependencies: must be an array`);
815
- }
816
- for (const dep of entry?.dependencies || []) {
817
- if (!taskFileSet.has(dep)) {
818
- errors.push(`spec.json.task_registry.${registryPath}.dependencies: unknown dependency ${dep}`);
819
- }
820
- }
821
3339
  }
822
3340
  }
823
3341
 
@@ -849,7 +3367,7 @@ function validateSpec(specDir) {
849
3367
  errors.push('spec.json.timestamps.validation_done: required when validation.status is completed');
850
3368
  }
851
3369
  if (taskFiles.length >= 5 && !spec.timestamps?.review_done) {
852
- errors.push('spec.json.timestamps.review_done: required for 5+ task specs after validation');
3370
+ errors.push('spec.json.timestamps.review_done: required after validation for a large task graph');
853
3371
  }
854
3372
  }
855
3373
 
@@ -873,13 +3391,21 @@ function validateSpec(specDir) {
873
3391
  const receiptArtifact = inspectSpecArtifact(specDir, canonicalSpecDir, FEATURE_RECEIPT_FILE, FEATURE_RECEIPT_FILE, errors);
874
3392
  validateResearchPointer(specDir, canonicalSpecDir, spec, errors);
875
3393
 
876
- const requiresResearchArtifact = policyContext.explicit
877
- && Boolean(policyContext.policy?.proof_obligations?.includes('needsResearchGrounding'));
878
- if (requiresResearchArtifact) {
879
- validateResearchArtifact(researchArtifact, errors, policyContext.explicit);
3394
+ const researchPointer = explicitResearchPath(spec);
3395
+ if (researchPointer !== null && researchPointer !== 'research.md') {
3396
+ errors.push('spec.research: explicit research must use the canonical research.md path');
3397
+ }
3398
+ const legacyResearchRequired = policyContext.legacy
3399
+ && spec.workflow_policy?.proof_obligations?.includes('needsResearchGrounding');
3400
+ if (researchPointer === 'research.md' || (policyContext.legacy && researchArtifact)) {
3401
+ validateResearchArtifact(researchArtifact, errors, true);
3402
+ } else if (legacyResearchRequired) {
3403
+ validateResearchArtifact(null, errors, true);
3404
+ } else if (researchArtifact) {
3405
+ errors.push('research.md: physical research artifact requires explicit spec.research="research.md"');
880
3406
  }
881
3407
 
882
- validateFeatureReceipt(spec, policyContext, errors, receiptArtifact);
3408
+ validateFeatureReceipt(spec, policyContext, errors, warnings, receiptArtifact);
883
3409
 
884
3410
  let requirementIds = [];
885
3411
  let subCriteriaIds = [];
@@ -887,38 +3413,85 @@ function validateSpec(specDir) {
887
3413
  let designText = '';
888
3414
  if (requirementsArtifact) {
889
3415
  requirementsText = fs.readFileSync(requirementsArtifact.path, 'utf8');
3416
+ validateUniqueSectionGroups('requirements.md', requirementsText, [['Requirements']], errors);
3417
+ validateRequirementDialect(requirementsText, errors);
3418
+ validateRequirementInventory(requirementsText, errors);
890
3419
  requirementIds = extractRequirementIds(requirementsText);
891
3420
  subCriteriaIds = extractSubCriteriaIds(requirementsText);
892
3421
  }
893
- if (designArtifact) designText = fs.readFileSync(designArtifact.path, 'utf8');
894
- validateBoundedReadiness(spec, requirementsText, designText, errors);
3422
+ if (designArtifact) {
3423
+ designText = fs.readFileSync(designArtifact.path, 'utf8');
3424
+ validateUniqueSectionGroups('design.md', designText, [
3425
+ ['Architecture'],
3426
+ ['Canonical Contracts & Invariants'],
3427
+ ['Execution Closure'],
3428
+ ['Requirements Traceability'],
3429
+ ['Components and Interfaces'],
3430
+ ], errors);
3431
+ }
3432
+ if (!policyContext.legacy) {
3433
+ validateSemanticReview(
3434
+ specDir,
3435
+ spec,
3436
+ policyContext,
3437
+ subCriteriaIds,
3438
+ designText,
3439
+ errors,
3440
+ );
3441
+ }
3442
+ validateSemanticReadiness(spec, requirementsText, designText, policyContext, errors);
895
3443
 
896
3444
  const coveredRequirementIds = new Set();
897
3445
  const coveredSubCriteriaIds = new Set();
898
3446
  const mappedRequirementReferences = [];
899
3447
  const taskRecords = new Map();
3448
+ const taskClosures = new Map();
3449
+ const taskContents = new Map();
900
3450
  // Cross-layer contract defs (opt-in): empty unless design.md uses
901
3451
  // <!-- contract:NAME --> markers, so legacy specs are unaffected.
902
- const contractDefs = designArtifact ? extractContractDefs(designText) : new Map();
903
- if (taskFiles.length >= 5 && contractDefs.size === 0) {
904
- errors.push(
905
- 'design.md: 5+ task spec requires contract blocks for BE/FE shared shapes (<!-- contract:NAME -->) — fail closed, not warning',
906
- );
907
- }
3452
+ const contractDefs = designArtifact ? extractContractDefs(designText, 'design.md', errors) : new Map();
3453
+ const designClosure = designArtifact
3454
+ ? implementationObligationClosure(designText, 'design.md', errors)
3455
+ : { ids: [], section: '', headingCount: 0, blocks: new Map(), notApplicable: false };
908
3456
  for (const taskFile of taskFiles) {
909
3457
  const taskArtifact = inspectSpecArtifact(specDir, canonicalSpecDir, taskFile, taskFile, errors);
910
3458
  if (!taskArtifact) continue;
911
3459
  const content = fs.readFileSync(taskArtifact.path, 'utf8');
3460
+ taskContents.set(taskFile, content);
3461
+ const registryEntry = spec.task_registry?.[taskFile];
3462
+ validateTaskIdentity(taskFile, content, registryEntry, errors);
912
3463
  validateTaskSections(taskFile, content, errors);
913
3464
  validateTaskPlaceholders(taskFile, content, errors, warnings);
914
3465
  validateRelatedFiles(taskFile, content, errors);
915
- taskRecords.set(taskFile, { rows: relatedFilesSection(content).rows });
3466
+ validateTaskDependencyHeader(
3467
+ taskFile,
3468
+ content,
3469
+ registryEntry,
3470
+ spec.ready_for_implementation === true,
3471
+ errors,
3472
+ );
3473
+ validateTaskStatusHeader(
3474
+ taskFile,
3475
+ content,
3476
+ registryEntry,
3477
+ spec.ready_for_implementation === true,
3478
+ errors,
3479
+ );
3480
+ taskClosures.set(
3481
+ taskFile,
3482
+ implementationObligationClosure(content, taskFile, errors),
3483
+ );
3484
+ taskRecords.set(taskFile, {
3485
+ rows: relatedFilesSection(content).rows,
3486
+ parallel: taskDeclaresParallel(content, taskFile, errors),
3487
+ });
916
3488
 
917
3489
  // Requirement traceability: only structured _Requirements: ..._ mappings inside Steps/Requirements sections count.
918
3490
  // Incidental mentions elsewhere (prose Context, Constraints) must not be counted.
919
- const stepsSection = extractSection(content, 'Steps') || extractSection(content, 'Implementation Steps') || '';
3491
+ const stepsSection = extractSection(content, 'Changes') || extractSection(content, 'Steps') || extractSection(content, 'Implementation Steps') || '';
920
3492
  const reqSectionInTask = extractSection(content, 'Requirements') || '';
921
- const mappingSource = `${stepsSection}\n${reqSectionInTask}`;
3493
+ const acceptanceSection = extractSection(content, 'Acceptance') || '';
3494
+ const mappingSource = `${stepsSection}\n${reqSectionInTask}\n${acceptanceSection}`;
922
3495
  // Also consider inline _Requirements: inside Steps bullet lines that may be outside section extraction edge cases,
923
3496
  // so fallback to whole content scanning only if sections are null (e.g., malformed heading). But prefer scoped.
924
3497
  const effectiveMappingSource = mappingSource.trim() ? mappingSource : content;
@@ -933,8 +3506,8 @@ function validateSpec(specDir) {
933
3506
  const sub = trimmed.match(/^(\d+\.\d+)$/);
934
3507
  const subId = sub ? `R${sub[1]}` : null;
935
3508
  coveredRequirementIds.add(requirementId);
936
- if (policyContext.strict) mappedRequirementReferences.push({ taskFile, token: trimmed, requirementId, subId });
937
- } else if (policyContext.strict && trimmed !== '') {
3509
+ mappedRequirementReferences.push({ taskFile, token: trimmed, requirementId, subId });
3510
+ } else if (trimmed !== '') {
938
3511
  errors.push(`${taskFile}: requirement mapping "${trimmed}" must use numeric IDs such as 1 or 1.1`);
939
3512
  }
940
3513
  // Record the full sub-criterion (e.g. 3.4 -> R3.4) for per-criterion coverage.
@@ -943,13 +3516,34 @@ function validateSpec(specDir) {
943
3516
  }
944
3517
  }
945
3518
 
3519
+ if (taskFormat(content) === 'v2') {
3520
+ for (const subId of criterionReferences(`${stepsSection}\n${acceptanceSection}`)) {
3521
+ coveredSubCriteriaIds.add(subId);
3522
+ coveredRequirementIds.add(subId.split('.')[0]);
3523
+ mappedRequirementReferences.push({
3524
+ taskFile,
3525
+ token: subId.slice(1),
3526
+ requirementId: subId.split('.')[0],
3527
+ subId,
3528
+ });
3529
+ }
3530
+ }
3531
+
946
3532
  // Cross-layer contract check (opt-in via design.md markers). When a task
947
3533
  // claims `Contracts: NAME`, design.md must define the name and the task's
948
3534
  // local copy must match the canonical definition byte-for-byte (after
949
3535
  // whitespace normalization). This catches BE/FE drift like user_name vs
950
3536
  // userName before integration, and rejects declarations with no canonical
951
3537
  // source instead of silently accepting an orphan contract.
952
- const { names, blocks, firstBlock } = extractTaskContracts(content);
3538
+ if (taskFormat(content) === 'v2') continue;
3539
+ const { names, blocks, firstBlock } = extractTaskContracts(content, taskFile, errors);
3540
+ for (const taggedName of blocks.keys()) {
3541
+ if (!names.includes(taggedName)) {
3542
+ errors.push(
3543
+ `${taskFile}: carries <!-- contract:${taggedName} --> block but must declare it on one Contracts: line`,
3544
+ );
3545
+ }
3546
+ }
953
3547
  if (names.length > 0 && contractDefs.size === 0) {
954
3548
  errors.push(`${taskFile}: declares contract(s) but design.md defines no canonical contract blocks`);
955
3549
  }
@@ -972,21 +3566,38 @@ function validateSpec(specDir) {
972
3566
  errors.push(`${taskFile}: contract "${name}" body diverges from the canonical definition in design.md`);
973
3567
  }
974
3568
  }
975
- // Marker-tagged blocks not declared on the Contracts: line are drift risks.
976
- for (const taggedName of blocks.keys()) {
977
- if (!names.includes(taggedName)) {
978
- warnings.push(`${taskFile}: carries <!-- contract:${taggedName} --> block but does not declare it on the Contracts: line`);
979
- }
980
- }
981
3569
  }
982
3570
  }
983
3571
 
3572
+
3573
+ if (!policyContext.legacy) validateTypedAnchorInventory(designText, taskContents, errors);
3574
+ validateNamedContractReferences(designText, taskContents, errors);
3575
+
984
3576
  validateDependencyTopology(spec, taskFiles, spec.task_registry, taskRecords, errors);
3577
+ validateParallelEligibility(taskFiles, spec.task_registry, taskRecords, errors);
3578
+ if (!policyContext.legacy) {
3579
+ validateTaskTriggerEvidence(spec, topology, taskFiles, taskRecords, errors);
3580
+ }
3581
+ if (policyContext.legacy) {
3582
+ validateImplementationObligations(
3583
+ spec,
3584
+ policyContext,
3585
+ requirementIds,
3586
+ subCriteriaIds,
3587
+ taskFiles,
3588
+ spec.task_registry,
3589
+ designClosure,
3590
+ taskClosures,
3591
+ errors,
3592
+ );
3593
+ } else if (Object.prototype.hasOwnProperty.call(spec, 'implementation_obligations')) {
3594
+ errors.push('spec.json.implementation_obligations: legacy copied-closure contract is not part of Specs v2; use named design contracts and task references');
3595
+ }
985
3596
 
986
- if (policyContext.strict) {
987
- if (requirementIds.length === 0) {
988
- errors.push('requirements.md: strict workflow requires numeric requirement IDs (for example Requirement 1 or R1)');
989
- }
3597
+ if (policyContext.strict && requirementIds.length === 0) {
3598
+ errors.push('requirements.md: strict workflow requires numeric requirement IDs (for example Requirement 1 or R1)');
3599
+ }
3600
+ if (requiresTaskBundle) {
990
3601
  const knownRequirements = new Set(requirementIds);
991
3602
  const knownSubCriteria = new Set(subCriteriaIds);
992
3603
  for (const reference of mappedRequirementReferences) {
@@ -1016,6 +3627,15 @@ function validateSpec(specDir) {
1016
3627
  }
1017
3628
  }
1018
3629
 
3630
+
3631
+ const designVerification = extractSection(designText, 'Verification') || '';
3632
+ const designVerificationCoverage = criterionReferences(designVerification);
3633
+ for (const subId of subCriteriaIds) {
3634
+ if (!designVerificationCoverage.has(subId)) {
3635
+ errors.push(`requirements.md:${subId}: missing deterministic design Verification coverage`);
3636
+ }
3637
+ }
3638
+
1019
3639
  if (spec.ready_for_implementation === true && errors.length > 0) {
1020
3640
  errors.push('spec.json.ready_for_implementation: cannot be true while validator errors exist');
1021
3641
  }
@@ -1024,26 +3644,46 @@ function validateSpec(specDir) {
1024
3644
  }
1025
3645
 
1026
3646
  function main() {
1027
- const specDir = resolveSpecDir(process.argv[2]);
3647
+ const args = process.argv.slice(2);
3648
+ const semanticDigestMode = args.includes('--semantic-digest');
3649
+ const positional = args.filter((arg) => arg !== '--semantic-digest');
3650
+ const specDir = positional.length === 1 ? resolveSpecDir(positional[0]) : null;
1028
3651
  if (!specDir) {
1029
3652
  usage();
1030
3653
  process.exit(2);
1031
3654
  }
1032
3655
 
3656
+ if (semanticDigestMode) {
3657
+ let spec = null;
3658
+ try { spec = JSON.parse(fs.readFileSync(path.join(specDir, 'spec.json'), 'utf8')); } catch {}
3659
+ const result = spec?.schema_version === SCHEMA_21
3660
+ ? computeSemanticDigest21(specDir, spec)
3661
+ : computeSemanticDigest(specDir);
3662
+ if (result.errors.length > 0) {
3663
+ console.error(`SEMANTIC_DIGEST_FAIL ${path.relative(process.cwd(), specDir) || specDir}`);
3664
+ for (const error of result.errors) console.error(`- ${error}`);
3665
+ process.exit(1);
3666
+ }
3667
+ console.log(result.digest);
3668
+ return;
3669
+ }
3670
+
1033
3671
  const { errors, warnings } = validateSpec(specDir);
1034
3672
  for (const warning of warnings) {
1035
3673
  console.warn(`[WARN] ${warning}`);
1036
3674
  }
1037
3675
 
1038
3676
  if (errors.length > 0) {
1039
- console.error(`FAIL ${path.relative(process.cwd(), specDir) || specDir}`);
3677
+ console.error(`STRUCTURAL_FAIL ${path.relative(process.cwd(), specDir) || specDir}`);
1040
3678
  for (const error of errors) {
1041
3679
  console.error(`- ${error}`);
1042
3680
  }
1043
3681
  process.exit(1);
1044
3682
  }
1045
3683
 
1046
- console.log(`PASS ${path.relative(process.cwd(), specDir) || specDir}`);
3684
+ console.log(`STRUCTURALLY_VALID ${path.relative(process.cwd(), specDir) || specDir} (semantic review and execution proof are not claimed)`);
1047
3685
  }
1048
3686
 
1049
- main();
3687
+ module.exports = { validateSpec, computeSemanticDigest21 };
3688
+
3689
+ if (require.main === module) main();