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

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