@planu/cli 5.7.10 → 5.7.12

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 (40) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/dist/.planu-build.json +1 -1
  3. package/dist/cli/commands/package-handoff.js +10 -3
  4. package/dist/config/runtime-policy.json +2 -1
  5. package/dist/engine/abortable-process-runner.js +1 -0
  6. package/dist/engine/bump-carrier-binding.d.ts +10 -0
  7. package/dist/engine/bump-carrier-binding.js +276 -0
  8. package/dist/engine/handoff-artifacts/schemas.d.ts +20 -0
  9. package/dist/engine/handoff-artifacts/schemas.js +12 -0
  10. package/dist/engine/runtime-policy.js +4 -0
  11. package/dist/engine/source-quality-binding.d.ts +26 -0
  12. package/dist/engine/source-quality-binding.js +162 -0
  13. package/dist/engine/source-quality-receipt-reader.d.ts +3 -0
  14. package/dist/engine/source-quality-receipt-reader.js +51 -0
  15. package/dist/engine/spec-format/bdd-parser.js +13 -7
  16. package/dist/engine/spec-format/technical-md-populator.js +114 -3
  17. package/dist/engine/spec-format/unified-spec-builder.js +41 -7
  18. package/dist/engine/validation/validation-freshness.js +3 -2
  19. package/dist/engine/validator/blast-radius-gate.d.ts +3 -0
  20. package/dist/engine/validator/blast-radius-gate.js +139 -0
  21. package/dist/engine/validator/spec-compliance-runner.d.ts +1 -0
  22. package/dist/engine/validator/spec-compliance-runner.js +3 -0
  23. package/dist/engine/validator/validation-report-writer.d.ts +2 -0
  24. package/dist/engine/validator/validation-report-writer.js +68 -30
  25. package/dist/storage/runtime-db.js +7 -3
  26. package/dist/storage/spec-store.js +17 -6
  27. package/dist/tools/challenge-spec/scenarios-data.js +2 -2
  28. package/dist/tools/challenge-spec/scenarios-utils.d.ts +2 -0
  29. package/dist/tools/challenge-spec/scenarios-utils.js +36 -3
  30. package/dist/tools/update-status/side-effects.js +3 -1
  31. package/dist/tools/validate-lint.js +19 -0
  32. package/dist/tools/validate.js +46 -4
  33. package/dist/transports/transport-factory.js +15 -6
  34. package/dist/types/abortable-process.d.ts +1 -0
  35. package/dist/types/handoff-artifacts.d.ts +10 -0
  36. package/dist/types/runtime-policy.d.ts +1 -0
  37. package/dist/types/spec-format.d.ts +9 -0
  38. package/dist/types/validation-evidence.d.ts +21 -0
  39. package/package.json +3 -2
  40. package/planu-plugin.json +1 -1
@@ -10,8 +10,9 @@ export async function writeImplementationReviewReport(input) {
10
10
  conventionRegression: input.conventionRegression ?? false,
11
11
  specCompliance,
12
12
  minimalityReport: input.minimalityReport,
13
+ blastRadius: input.blastRadius,
13
14
  });
14
- const mergedGates = await preserveUnobservedGates(input, gates);
15
+ const { gates: mergedGates, preservedBlastRadius } = await preserveUnobservedGates(input, gates);
15
16
  const passed = mergedGates.every((gate) => gate.passed);
16
17
  const reviewer = {
17
18
  kind: 'automation',
@@ -19,45 +20,50 @@ export async function writeImplementationReviewReport(input) {
19
20
  verdict: passed ? 'approved' : 'changes-requested',
20
21
  };
21
22
  const reportCompliance = toValidationReportCompliance(specCompliance);
22
- const payload = {
23
- schema_version: '1.0.0',
23
+ const payload = buildValidationReportPayload({
24
24
  specId: input.specId,
25
25
  passed,
26
26
  gates: mergedGates,
27
27
  reviewer,
28
- specCompliance: reportCompliance,
28
+ reportCompliance,
29
29
  minimalityReport: input.minimalityReport,
30
- score: reportScore ?? undefined,
31
- completedAt: new Date().toISOString(),
32
- };
30
+ reportScore,
31
+ blastRadius: input.blastRadius,
32
+ preservedBlastRadius,
33
+ });
34
+ const persisted = await persistValidationReport(input.projectId, input.specId, payload);
35
+ return { ...persisted, reviewer, passed, gates: mergedGates, specCompliance: reportCompliance };
36
+ }
37
+ async function persistValidationReport(projectId, specId, payload) {
33
38
  try {
34
39
  const artifact = await appendArtifact({
35
- projectId: input.projectId,
36
- specId: input.specId,
40
+ projectId,
41
+ specId,
37
42
  kind: 'validation-report',
38
43
  payload,
39
44
  });
40
- return {
41
- written: true,
42
- path: artifact.path,
43
- sha: `sha256:${artifact.sha}`,
44
- reviewer,
45
- passed,
46
- gates: mergedGates,
47
- specCompliance: reportCompliance,
48
- };
45
+ return { written: true, path: artifact.path, sha: `sha256:${artifact.sha}` };
49
46
  }
50
47
  catch (err) {
51
- return {
52
- written: false,
53
- error: err instanceof Error ? err.message : String(err),
54
- reviewer,
55
- passed,
56
- gates: mergedGates,
57
- specCompliance: reportCompliance,
58
- };
48
+ return { written: false, error: err instanceof Error ? err.message : String(err) };
59
49
  }
60
50
  }
51
+ function buildValidationReportPayload(args) {
52
+ return {
53
+ schema_version: '1.0.0',
54
+ specId: args.specId,
55
+ passed: args.passed,
56
+ gates: args.gates,
57
+ reviewer: args.reviewer,
58
+ specCompliance: args.reportCompliance,
59
+ minimalityReport: args.minimalityReport,
60
+ score: args.reportScore ?? undefined,
61
+ completedAt: new Date().toISOString(),
62
+ blastRadius: args.blastRadius !== undefined
63
+ ? toValidationReportBlastRadius(args.blastRadius)
64
+ : args.preservedBlastRadius,
65
+ };
66
+ }
61
67
  function resolveExecutableValidationScore(score, specCompliance) {
62
68
  return specCompliance.perScenario.length > 0 ? specCompliance.dimensionScore : score;
63
69
  }
@@ -67,6 +73,7 @@ async function preserveUnobservedGates(input, nextGates) {
67
73
  ...(input.lintPassed !== undefined ? ['lint'] : []),
68
74
  ...(input.conventionRegression !== undefined ? ['convention-regression'] : []),
69
75
  ...(input.minimalityReport !== undefined ? ['minimal-implementation'] : []),
76
+ ...(input.blastRadius !== undefined ? ['blast-radius'] : []),
70
77
  ]);
71
78
  const existing = await readArtifact({
72
79
  projectId: input.projectId,
@@ -74,18 +81,23 @@ async function preserveUnobservedGates(input, nextGates) {
74
81
  kind: 'validation-report',
75
82
  }).catch(() => null);
76
83
  if (!existing?.ok) {
77
- return nextGates;
84
+ return { gates: nextGates };
78
85
  }
86
+ const preservedBlastRadius = input.blastRadius === undefined ? existing.payload.blastRadius : undefined;
79
87
  const preserved = existing.payload.gates.filter((gate) => currentGateNames.has(gate.name) &&
80
88
  !explicitlyObserved.has(gate.name) &&
81
89
  (gate.name === 'lint' ||
82
90
  gate.name === 'convention-regression' ||
83
- gate.name === 'minimal-implementation'));
91
+ gate.name === 'minimal-implementation' ||
92
+ gate.name === 'blast-radius'));
84
93
  if (preserved.length === 0) {
85
- return nextGates;
94
+ return { gates: nextGates, preservedBlastRadius };
86
95
  }
87
96
  const preservedByName = new Map(preserved.map((gate) => [gate.name, gate]));
88
- return nextGates.map((gate) => preservedByName.get(gate.name) ?? gate);
97
+ return {
98
+ gates: nextGates.map((gate) => preservedByName.get(gate.name) ?? gate),
99
+ preservedBlastRadius,
100
+ };
89
101
  }
90
102
  function buildGates(args) {
91
103
  return [
@@ -112,8 +124,34 @@ function buildGates(args) {
112
124
  },
113
125
  buildSpecComplianceGate(args.specCompliance),
114
126
  buildMinimalityGate(args.minimalityReport),
127
+ buildBlastRadiusGate(args.blastRadius),
115
128
  ];
116
129
  }
130
+ function buildBlastRadiusGate(result) {
131
+ if (result === undefined) {
132
+ return {
133
+ name: 'blast-radius',
134
+ passed: true,
135
+ reason: 'Blast radius result unavailable.',
136
+ };
137
+ }
138
+ return {
139
+ name: 'blast-radius',
140
+ passed: result.passed,
141
+ reason: result.passed
142
+ ? undefined
143
+ : `Blast radius gate failed: ${String(result.failures.length)} importer test failure(s).`,
144
+ };
145
+ }
146
+ function toValidationReportBlastRadius(result) {
147
+ return {
148
+ selectedFiles: result.selectedFiles.length,
149
+ passed: result.passed,
150
+ timedOut: result.timedOut,
151
+ ...(result.skipped !== null ? { skipped: result.skipped } : {}),
152
+ failures: result.failures,
153
+ };
154
+ }
117
155
  function buildMinimalityGate(report) {
118
156
  if (report?.enabled !== true) {
119
157
  return {
@@ -668,11 +668,15 @@ export class RuntimeDatabase {
668
668
  !['failed', 'dead-letter', 'cancelled', 'completed'].includes(current.state)) {
669
669
  throw new Error('[Planu] Job payload is not replaceable while work is active');
670
670
  }
671
- this.assertRestartCeiling(current, id);
671
+ const isFreshRun = current.state === 'completed';
672
+ if (!isFreshRun) {
673
+ this.assertRestartCeiling(current, id);
674
+ }
672
675
  const { now, deadlineAt } = this.freshRestartDeadline();
673
676
  this.archiveCheckpointBeforeRestart(projectId, workspaceId, id, now);
674
677
  const result = this.database
675
- .prepare(`UPDATE jobs SET state = 'accepted', attempts = 0, restarts = restarts + 1, cancel_requested = 0,
678
+ .prepare(`UPDATE jobs SET state = 'accepted', attempts = 0,
679
+ restarts = CASE WHEN state = 'completed' THEN 0 ELSE restarts + 1 END, cancel_requested = 0,
676
680
  payload_json = ?, checkpoint_json = NULL, result_json = NULL, error_message = NULL,
677
681
  lease_owner = NULL, lease_expires_at = NULL, updated_at = ?
678
682
  WHERE project_id = ? AND workspace_id = ? AND id = ?
@@ -708,7 +712,7 @@ export class RuntimeDatabase {
708
712
  }
709
713
  assertRestartCeiling(current, id) {
710
714
  if (current.restarts >= current.maxAttempts) {
711
- throw new Error(`[Planu] Job ${id} was restarted ${String(current.restarts)} times (ceiling ${String(current.maxAttempts)}); call cancel_job and submit a fresh operation`);
715
+ throw new Error(`[Planu] Job ${id} was restarted ${String(current.restarts)} times (ceiling ${String(current.maxAttempts)}); the operation id is deterministic, so fix the failing run before submitting it again`);
712
716
  }
713
717
  }
714
718
  freshRestartDeadline() {
@@ -230,14 +230,16 @@ export async function discoverCanonicalSpecPath(specId, canonicalRoot) {
230
230
  * getSpec/listSpecs is otherwise doing. Best-effort: failure to persist never
231
231
  * blocks the caller — the freshly parsed value is already what gets returned.
232
232
  */
233
- async function persistDigestRefresh(projectId, specId, title, contentDigest) {
233
+ async function persistDigestRefresh(projectId, specId, title, specVersion, contentDigest) {
234
234
  await withSpecMutationLock(projectId, async () => {
235
235
  const specs = await loadAll(projectId);
236
236
  const idx = specs.findIndex((s) => s.id === specId);
237
237
  if (idx === -1) {
238
238
  return;
239
239
  }
240
- const nextSpecs = specs.map((current, currentIdx) => currentIdx === idx ? { ...current, title, contentDigest } : current);
240
+ const nextSpecs = specs.map((current, currentIdx) => currentIdx === idx
241
+ ? { ...current, title, spec_version: specVersion, contentDigest }
242
+ : current);
241
243
  await saveAll(projectId, nextSpecs);
242
244
  });
243
245
  }
@@ -250,6 +252,10 @@ async function persistDigestRefresh(projectId, specId, title, contentDigest) {
250
252
  * spec.md; callers that omit it get the specs.json record unchecked (matching
251
253
  * the existing canonicalRoot-gated legacy-migration behavior on this same path).
252
254
  */
255
+ function frontmatterScalarsDrifted(fields, spec) {
256
+ return ((fields.spec_version !== undefined && fields.spec_version !== spec.spec_version) ||
257
+ (fields.title !== undefined && fields.title !== spec.title));
258
+ }
253
259
  async function refreshSpecFromDisk(projectId, spec, canonicalRoot) {
254
260
  let specMdPath;
255
261
  try {
@@ -277,12 +283,17 @@ async function refreshSpecFromDisk(projectId, spec, canonicalRoot) {
277
283
  return null;
278
284
  }
279
285
  const digest = digestOf(content);
280
- if (digest === spec.contentDigest) {
286
+ const fields = readFrontmatterScalars(content);
287
+ if (digest === spec.contentDigest && !frontmatterScalarsDrifted(fields, spec)) {
281
288
  return spec;
282
289
  }
283
- const fields = readFrontmatterScalars(content);
284
- const refreshed = { ...spec, title: fields.title ?? spec.title, contentDigest: digest };
285
- await persistDigestRefresh(projectId, spec.id, refreshed.title, digest).catch((error) => {
290
+ const refreshed = {
291
+ ...spec,
292
+ title: fields.title ?? spec.title,
293
+ spec_version: fields.spec_version ?? spec.spec_version,
294
+ contentDigest: digest,
295
+ };
296
+ await persistDigestRefresh(projectId, spec.id, refreshed.title, refreshed.spec_version, digest).catch((error) => {
286
297
  reportClassifiedDegradation('SPEC_CONTENT_DIGEST_REFRESH_PERSIST', error);
287
298
  });
288
299
  return refreshed;
@@ -1,5 +1,5 @@
1
1
  // tools/challenge-spec/scenarios-data.ts — Data consistency and partial write scenarios
2
- import { contentMentions, hasAnyAffirmedMatch } from './scenarios-utils.js';
2
+ import { CACHE_ACTION_SIGNALS, contentMentions, hasAnyAffirmedMatch } from './scenarios-utils.js';
3
3
  const GIT_CHECKOUT_PREFIX = '(?<!\\b(?:git|branch|worktree|main)\\s)';
4
4
  const WRITE_SIGNALS = [
5
5
  /\b(transaction|persist|database write|save record|create record|update record|delete record)\b/i,
@@ -9,7 +9,7 @@ const WRITE_SIGNALS = [
9
9
  /\bplaces?\s+an\s+order\b/i,
10
10
  new RegExp(`${GIT_CHECKOUT_PREFIX}\\bcheckout\\s+(?:flow|process|order|endpoint)\\b`, 'i'),
11
11
  ];
12
- const CACHE_SIGNALS = [/\b(cache|cached|real-time|realtime|websocket|stale data)\b/i];
12
+ const CACHE_SIGNALS = [...CACHE_ACTION_SIGNALS, /\b(?:real-time|realtime|websocket|stale data)\b/i];
13
13
  const DUPLICATE_OPERATION_SIGNALS = [
14
14
  /\bsubmit(?:s|ted|ting)?\s+(?:a\s+|the\s+)?form\b/i,
15
15
  /\bform\s+submission\b/i,
@@ -28,6 +28,8 @@ export interface ChallengeCapabilities {
28
28
  numericInput: boolean;
29
29
  rollout: boolean;
30
30
  }
31
+ /** Shared with scenarios-data.ts so the stale-cache scenario uses the same caching-action anchor. */
32
+ export declare const CACHE_ACTION_SIGNALS: RegExp[];
31
33
  /** Boundary-aware, affirmative replacement for advisory substring checks. */
32
34
  export declare function contentMentions(content: string, keywords: string[]): boolean;
33
35
  export declare function detectChallengeCapabilities(spec: Spec, specContent: string): ChallengeCapabilities;
@@ -7,9 +7,7 @@ const CAPABILITY_SIGNALS = {
7
7
  /\bfetch(?:es|ing)?\s+(?:from\s+)?(?:an?\s+)?(?:endpoint|service|url)\b/i,
8
8
  ],
9
9
  database: [
10
- /\b(?:database|postgres(?:ql)?|mysql|sqlite|mongodb|dynamodb|supabase)\b/i,
11
10
  /\b(?:sql|nosql)\s+(?:query|statement|table|database)\b/i,
12
- /\b(?:database|persistence)\s+(?:query|schema|table|migration|transaction)\b/i,
13
11
  /\b(?:orm|prisma|drizzle|typeorm|sequelize)\b/i,
14
12
  ],
15
13
  authentication: [/\b(?:login|sign[ -]?in|password|jwt|oauth2?|session\s+auth)\b/i],
@@ -42,7 +40,12 @@ const CAPABILITY_SIGNALS = {
42
40
  /\b(?:state-changing|data\s+mutation|atomic\s+database\s+writes?)\b/i,
43
41
  /\b(?:transaction|atomic\s+writes?|update\s+(?:record|state)|modify\s+(?:record|state))\b/i,
44
42
  ],
45
- cache: [/\b(?:cache|caching|cached\s+(?:data|response)|redis)\b/i],
43
+ cache: [
44
+ /\bcach(?:e|es|ed|ing)\s+(?:the|responses|results|entries|data)\b/i,
45
+ /\bcache\s+invalidat(?:e|es|ed|ing|ion)\b/i,
46
+ /\b(?:responses|results|entries|data)\s+(?:are|is|were)\s+cached\b/i,
47
+ /\bredis\b/i,
48
+ ],
46
49
  duplicateOperation: [
47
50
  /\b(?:double[ -]?click|duplicate\s+(?:request|submission|operation|record)|idempoten)/i,
48
51
  ],
@@ -104,6 +107,8 @@ const CAPABILITY_SIGNALS = {
104
107
  /\bdeployment\s+strategy\b/i,
105
108
  ],
106
109
  };
110
+ /** Shared with scenarios-data.ts so the stale-cache scenario uses the same caching-action anchor. */
111
+ export const CACHE_ACTION_SIGNALS = CAPABILITY_SIGNALS.cache;
107
112
  const AUTHENTICATION_BARE_TOKEN_RE = /\bauth(?:entication|enticate)?\b/i;
108
113
  // A bare "auth" token next to registry/package-manager vocabulary describes a
109
114
  // dependency-registry failure, not a product authentication contract, in either
@@ -118,6 +123,33 @@ function hasProductAuthenticationEvidence(contract) {
118
123
  return (hasAffirmedMatch(contract, AUTHENTICATION_BARE_TOKEN_RE) &&
119
124
  !REGISTRY_AUTH_CONTEXT_RE.test(contract));
120
125
  }
126
+ const DATABASE_PRODUCT_TOKEN_RE = '(?:database|postgres(?:ql)?|mysql|sqlite|mongodb|dynamodb|supabase)';
127
+ const DATABASE_PERSISTENCE_VERB_RE = '(?:stor(?:e|es|ed|ing)|persist(?:s|ed|ing)?|writ(?:e|es|ing|ten)|read(?:s|ing)?|quer(?:y|ies|ying)|insert(?:s|ing|ed)?|updat(?:e|es|ing|ed)|delet(?:e|es|ing|ed)|migrat(?:e|es|ing|ed|ion|ions))';
128
+ const DATABASE_TEST_GUARD_RE = '(?:test|fixture|mock(?:s|ed|ing)?|stub(?:s|bed|bing)?)';
129
+ const DATABASE_PRODUCT_RE = new RegExp(`\\b${DATABASE_PRODUCT_TOKEN_RE}\\b`, 'i');
130
+ const DATABASE_DDL_VERB_RE = /\b(?:add|adds|added|adding)\b/i;
131
+ const DATABASE_DDL_CONTEXT_RE = /\b(?:migration|schema|column|table)\b/i;
132
+ const DATABASE_PERSISTENCE_ACTION_RE = new RegExp(`\\b${DATABASE_PERSISTENCE_VERB_RE}\\b(?:\\W+\\w+){0,4}?\\W+\\b${DATABASE_PRODUCT_TOKEN_RE}\\b|` +
133
+ `\\b${DATABASE_PRODUCT_TOKEN_RE}\\b(?:\\W+\\w+){0,4}?\\W+\\b${DATABASE_PERSISTENCE_VERB_RE}\\b`, 'i');
134
+ const DATABASE_TEST_CONTEXT_RE = new RegExp(`\\b${DATABASE_TEST_GUARD_RE}\\b(?:\\W+\\w+){0,6}?\\W+\\b(?:${DATABASE_PRODUCT_TOKEN_RE}|${DATABASE_PERSISTENCE_VERB_RE})\\b|` +
135
+ `\\b(?:${DATABASE_PRODUCT_TOKEN_RE}|${DATABASE_PERSISTENCE_VERB_RE})\\b(?:\\W+\\w+){0,6}?\\W+\\b${DATABASE_TEST_GUARD_RE}\\b`, 'i');
136
+ function hasDatabasePersistenceEvidenceInClause(clause) {
137
+ if (DATABASE_TEST_CONTEXT_RE.test(clause)) {
138
+ return false;
139
+ }
140
+ if (hasAffirmedMatch(clause, DATABASE_PERSISTENCE_ACTION_RE)) {
141
+ return true;
142
+ }
143
+ return (DATABASE_PRODUCT_RE.test(clause) &&
144
+ DATABASE_DDL_CONTEXT_RE.test(clause) &&
145
+ DATABASE_DDL_VERB_RE.test(clause));
146
+ }
147
+ function hasProductDatabaseEvidence(contract) {
148
+ if (hasAnyAffirmedMatch(contract, CAPABILITY_SIGNALS.database)) {
149
+ return true;
150
+ }
151
+ return contract.split(/[.;\n]/).some(hasDatabasePersistenceEvidenceInClause);
152
+ }
121
153
  const NETWORK_API_BARE_TOKEN_RE = /(?<!compiler\s)\bapi\b(?!\s+(?:compatibility|surface|package|type))/i;
122
154
  const NETWORK_API_CONTEXT_RE = /\b(?:endpoint|route|http|https|rest|fetch|url|socket|request|response|timeout|retry|webhook|payload|keys?)\b(?:\W+\w+){0,6}?\W+api\b|\bapi\b(?:\W+\w+){0,6}?\W+\b(?:endpoint|route|http|https|rest|fetch|url|socket|request|response|timeout|retry|webhook|payload|keys?)\b/i;
123
155
  function hasProductNetworkEvidence(contract) {
@@ -162,6 +194,7 @@ export function detectChallengeCapabilities(spec, specContent) {
162
194
  ]));
163
195
  capabilities.authentication = hasProductAuthenticationEvidence(contract);
164
196
  capabilities.networkApi = hasProductNetworkEvidence(contract);
197
+ capabilities.database = hasProductDatabaseEvidence(contract);
165
198
  return capabilities;
166
199
  }
167
200
  export function hasAnyChallengeCapability(capabilities, names) {
@@ -219,7 +219,9 @@ async function readDisabledByConfig(projectPath) {
219
219
  return Array.isArray(disabled) ? new Set(disabled) : new Set();
220
220
  }
221
221
  catch (error) {
222
- /* reliability-optional: CASCADE_CONFIG_UNAVAILABLE — default empty disable set is explicit */
222
+ if (error.code === 'ENOENT') {
223
+ return new Set();
224
+ }
223
225
  reportClassifiedDegradation('CASCADE_CONFIG_UNAVAILABLE', error);
224
226
  return new Set();
225
227
  }
@@ -4,6 +4,7 @@ import { formatLintFailureDiagnostics, resolveProjectCommandPlan, runProjectComm
4
4
  import { getToolExecutionSignal } from './safe-handler.js';
5
5
  import { VALIDATION_COMMANDS } from '../engine/validation-impact-planner.js';
6
6
  import { boundedEnvironmentDuration, getRuntimePolicy } from '../engine/runtime-policy.js';
7
+ import { readMatchingSourceQualityReceipt } from '../engine/source-quality-receipt-reader.js';
7
8
  /** Allowlist: alphanumerics, spaces, and safe shell chars. Rejects ; | $ ` & < > */
8
9
  const SAFE_COMMAND_RE = /^[\w\s./:@~=-]+$/;
9
10
  function isSafeCommand(cmd) {
@@ -80,6 +81,24 @@ export async function runLintCheck(projectPath, lintCommand, context = {}) {
80
81
  };
81
82
  }
82
83
  }
84
+ const sourceQualityMatch = readMatchingSourceQualityReceipt(projectPath, command);
85
+ if (sourceQualityMatch) {
86
+ const output = `(reused source-quality receipt ${sourceQualityMatch.key})`;
87
+ if (context.projectId) {
88
+ recordSuccessfulValidationEvidence({
89
+ projectId: context.projectId,
90
+ input: evidenceInput,
91
+ expectedKey,
92
+ producer: 'planu-validate',
93
+ durationMs: 0,
94
+ output,
95
+ reason: context.specId
96
+ ? `Lint reused the source-quality receipt while validating ${context.specId}.`
97
+ : 'Lint reused the source-quality receipt during canonical validation.',
98
+ });
99
+ }
100
+ return { passed: true, command, issueCount: 0, output };
101
+ }
83
102
  const timeoutMs = Math.min(lintCheckTimeoutMs(), context.maximumTimeoutMs ?? Number.MAX_SAFE_INTEGER);
84
103
  try {
85
104
  const startedAt = Date.now();
@@ -69,8 +69,12 @@ import { validateContractCompliance } from '../engine/test-scaffold-generator.js
69
69
  import { parseConventions, scanConventions } from '../engine/convention-scanner/index.js';
70
70
  import { validateScopeCompliance } from '../engine/scope-boundaries/index.js';
71
71
  import { compareWithBaseline } from '../storage/convention-baseline.js';
72
+ import { readFile } from 'node:fs/promises';
73
+ import { isAbsolute, join } from 'node:path';
72
74
  import { writeImplementationReviewReport } from '../engine/validator/validation-report-writer.js';
73
75
  import { runReliabilityGate } from '../engine/validator/reliability-gate.js';
76
+ import { runBlastRadiusGate } from '../engine/validator/blast-radius-gate.js';
77
+ import { collectDeclaredSpecFiles } from '../engine/validator/spec-compliance-runner.js';
74
78
  import { buildGraphCoverageReport, formatGraphCoverageText } from './validate-graph-coverage.js';
75
79
  import { buildMinimalityReport } from './validate-minimality.js';
76
80
  import { buildValidateFailureFallback, validateStrictLayoutOrError } from './validate-helpers.js';
@@ -87,7 +91,7 @@ import { getRuntimePolicy } from '../engine/runtime-policy.js';
87
91
  import { resolveValidationWorktree, ValidationWorktreeError, } from '../engine/validation/validation-worktree.js';
88
92
  // Re-export for external use (SPEC-018)
89
93
  export { validateContractCompliance };
90
- const VALIDATION_GATE_TOTAL = 9;
94
+ const VALIDATION_GATE_TOTAL = 10;
91
95
  const GATE_DEADLINE_EXEMPT_PHASES = new Set(['lint', 'compliance']);
92
96
  async function runWithGateDeadline(phase, command, work) {
93
97
  if (GATE_DEADLINE_EXEMPT_PHASES.has(phase)) {
@@ -368,9 +372,20 @@ export async function executeValidate(args, server, onProgress) {
368
372
  });
369
373
  const implementationQualityScore = calcQualityScore(result.qualityIssues);
370
374
  const auditedFiles = [...new Set(result.qualityIssues.map((i) => i.file))];
371
- const reliabilityGate = await runStage('reliability', 'scripts/check-reliability-policies.mjs --json', async () => {
372
- const codeState = await scanCodeForSpec(executionSpec, projectPath);
373
- return runReliabilityGate(projectPath, codeState.affectedFiles);
375
+ const codeState = await scanCodeForSpec(executionSpec, projectPath);
376
+ const reliabilityGate = await runStage('reliability', 'scripts/check-reliability-policies.mjs --json', () => runReliabilityGate(projectPath, codeState.affectedFiles));
377
+ const blastRadiusGate = await runStage('blast-radius', "vitest related over the spec's affected source files", async () => {
378
+ const absoluteSpecPath = isAbsolute(executionSpec.specPath)
379
+ ? executionSpec.specPath
380
+ : join(projectPath, executionSpec.specPath);
381
+ const raw = await readFile(absoluteSpecPath, 'utf-8');
382
+ const candidateFiles = [
383
+ ...new Set([...collectDeclaredSpecFiles(raw), ...codeState.affectedFiles]),
384
+ ];
385
+ return runBlastRadiusGate(projectPath, candidateFiles, {
386
+ timeoutMs: getRuntimePolicy().validation.blastRadiusTimeoutMs,
387
+ signal: getToolExecutionSignal(),
388
+ });
374
389
  });
375
390
  const { conventionViolations, regressionDetected } = await runStage('conventions', 'validate project conventions', () => scanProjectConventions(projectId, projectPath));
376
391
  const lintCheck = await runStage('lint', knowledge.lintCommand ?? 'pnpm lint', () => runLintCheck(projectPath, knowledge.lintCommand ?? null, {
@@ -401,6 +416,7 @@ export async function executeValidate(args, server, onProgress) {
401
416
  conventionRegression: regressionDetected,
402
417
  minimalityReport: minimalityReport ?? undefined,
403
418
  signal: getToolExecutionSignal(),
419
+ blastRadius: blastRadiusGate,
404
420
  }));
405
421
  const effectiveResult = buildEffectiveValidationResult(result, validationReport.specCompliance);
406
422
  const qualityGateSummary = buildQualityGateSummary({
@@ -410,6 +426,7 @@ export async function executeValidate(args, server, onProgress) {
410
426
  assurancePassed: assuranceGates.newCode.passed,
411
427
  minimalityBlocked: minimalityReport?.blocked === true,
412
428
  reliabilityPassed: reliabilityGate.passed,
429
+ blastRadiusPassed: blastRadiusGate.passed,
413
430
  score: effectiveResult.score,
414
431
  });
415
432
  const output = {
@@ -525,6 +542,26 @@ export async function executeValidate(args, server, onProgress) {
525
542
  suggestion: 'Not blocking this spec — file is outside the spec Files section.',
526
543
  });
527
544
  }
545
+ for (const failure of blastRadiusGate.failures) {
546
+ output.qualityIssues.push({
547
+ file: failure.file,
548
+ line: 0,
549
+ severity: 'critical',
550
+ rule: 'blast-radius',
551
+ message: `Blast radius test failure: ${failure.message}`,
552
+ suggestion: 'Fix the failing importer tests (or raise validation.blastRadiusTimeoutMs) before marking this spec done.',
553
+ });
554
+ }
555
+ if (blastRadiusGate.skipped !== null) {
556
+ output.qualityIssues.push({
557
+ file: 'blast-radius',
558
+ line: 0,
559
+ severity: 'warning',
560
+ rule: 'blast-radius-skipped',
561
+ message: `Blast radius gate skipped: ${blastRadiusGate.skipped}`,
562
+ suggestion: 'No importer regression coverage ran for this validate call.',
563
+ });
564
+ }
528
565
  // Auto-suggest corrective actions based on validation results
529
566
  // score is null when no criteria can be extracted — treat as 0 for comparisons.
530
567
  const scoreValue = effectiveResult.score ?? 0;
@@ -562,6 +599,9 @@ export async function executeValidate(args, server, onProgress) {
562
599
  else if (!reliabilityGate.passed) {
563
600
  suggestions.push(`Reliability gate failed: ${String(reliabilityGate.failures.length)} violation(s) in this spec's files. Fix before marking as done.`);
564
601
  }
602
+ if (blastRadiusGate.skipped === null && !blastRadiusGate.passed) {
603
+ suggestions.push('Fix the failing importer tests (or raise validation.blastRadiusTimeoutMs) before marking this spec done.');
604
+ }
565
605
  if (!assuranceGates.newCode.passed) {
566
606
  suggestions.push(`Assurance gate failed: ${String(assuranceGates.newCode.findings.length)} new-code domain inference issue(s) found.`);
567
607
  }
@@ -713,6 +753,7 @@ function buildQualityGateSummary(input) {
713
753
  ...(!input.assurancePassed ? ['assurance'] : []),
714
754
  ...(input.minimalityBlocked ? ['minimality'] : []),
715
755
  ...(!input.reliabilityPassed ? ['reliability'] : []),
756
+ ...(!input.blastRadiusPassed ? ['blast-radius'] : []),
716
757
  ];
717
758
  return {
718
759
  passed: failures.length === 0,
@@ -724,6 +765,7 @@ function buildQualityGateSummary(input) {
724
765
  assurancePassed: input.assurancePassed,
725
766
  minimalityPassed: !input.minimalityBlocked,
726
767
  reliabilityPassed: input.reliabilityPassed,
768
+ blastRadiusPassed: input.blastRadiusPassed,
727
769
  };
728
770
  }
729
771
  function buildExecutableCoverage(specCompliance) {
@@ -142,6 +142,17 @@ async function drainPostCommitWorkOnShutdown() {
142
142
  reportClassifiedDegradation('POST_COMMIT_DRAIN_TIMEOUT', new Error(`Shutdown drain exceeded ${String(POST_COMMIT_DRAIN_MS)}ms with ${String(drainResult.pendingCount)} pending`));
143
143
  }
144
144
  }
145
+ function createExitOnce() {
146
+ let exited = false;
147
+ return () => {
148
+ if (exited) {
149
+ return;
150
+ }
151
+ exited = true;
152
+ signalDescendants('SIGKILL');
153
+ process.exit(0);
154
+ };
155
+ }
145
156
  function installStdioShutdownHandlers(server) {
146
157
  let shuttingDown = false;
147
158
  const handlers = new Map();
@@ -170,10 +181,9 @@ function installStdioShutdownHandlers(server) {
170
181
  shuttingDown = true;
171
182
  removeHandlers();
172
183
  console.error(`[Planu] MCP stdio ${reason}; shutting down.`);
173
- const hardStop = setTimeout(() => {
174
- signalDescendants('SIGKILL');
175
- process.exit(0);
176
- }, 1_500);
184
+ const exitOnce = createExitOnce();
185
+ const hardStop = setTimeout(exitOnce, 1_500);
186
+ hardStop.unref();
177
187
  void import('../tools/safe-handler.js')
178
188
  .then(({ abortActiveToolExecutions }) => {
179
189
  abortActiveToolExecutions(`MCP stdio ${reason}`);
@@ -195,8 +205,7 @@ function installStdioShutdownHandlers(server) {
195
205
  })
196
206
  .finally(() => {
197
207
  clearTimeout(hardStop);
198
- signalDescendants('SIGKILL');
199
- process.exit(0);
208
+ exitOnce();
200
209
  });
201
210
  };
202
211
  const end = () => {
@@ -12,6 +12,7 @@ export interface AbortableProcessOptions {
12
12
  timeoutMs: number;
13
13
  maxBufferBytes: number;
14
14
  signal?: AbortSignal;
15
+ env?: NodeJS.ProcessEnv;
15
16
  /** Called synchronously after process-group termination has been requested. */
16
17
  onCancellationAcknowledged?: () => void;
17
18
  }
@@ -95,6 +95,16 @@ export interface ValidationReportV1 {
95
95
  completedAt: string;
96
96
  receiptId?: string;
97
97
  receiptKey?: string;
98
+ blastRadius?: {
99
+ selectedFiles: number;
100
+ passed: boolean;
101
+ timedOut: boolean;
102
+ skipped?: string;
103
+ failures: {
104
+ file: string;
105
+ message: string;
106
+ }[];
107
+ };
98
108
  }
99
109
  export type ReconciliationReceiptState = 'prepared' | 'committed' | 'aborted';
100
110
  /** Mutable, atomically replaced recovery record for a reconciliation transaction. */
@@ -40,6 +40,7 @@ export interface RuntimePolicy {
40
40
  receiptPublicationDeadlineMs: number;
41
41
  receiptCheckpointLogMaxBytes: number;
42
42
  receiptCheckpointResultMaxBytes: number;
43
+ blastRadiusTimeoutMs: number;
43
44
  };
44
45
  postCommit: {
45
46
  defaultTaskTimeoutMs: number;
@@ -59,6 +59,10 @@ export interface LeanFileEntry {
59
59
  path: string;
60
60
  status: 'pending' | 'done';
61
61
  }
62
+ /** Bucket a labelled "Files to create/modify" or "Create:/Modify:/Test:" entry belongs to. */
63
+ export type LabeledFileBucketKind = 'create' | 'modify' | 'test';
64
+ /** Paths parsed from labelled Files lists, grouped by bucket. */
65
+ export type LabeledFileLists = Record<LabeledFileBucketKind, string[]>;
62
66
  /** Result of a planu/ cleanup operation (SPEC-466). */
63
67
  export interface CleanupResult {
64
68
  deletedRootFiles: string[];
@@ -195,6 +199,11 @@ export interface UnifiedSpecCandidateValidation {
195
199
  valid: boolean;
196
200
  issues: UnifiedSpecCandidateIssue[];
197
201
  }
202
+ /** The first non-canonical author section found in a source description (SPEC-1753). */
203
+ export interface AuthorSection {
204
+ name: string;
205
+ body: string;
206
+ }
198
207
  export interface CanonicalUnifiedSpecInput {
199
208
  leanSpecBody: string;
200
209
  sourceDescription: string;
@@ -1,3 +1,4 @@
1
+ import type { AbortableProcessOptions, AbortableProcessResult } from './abortable-process.js';
1
2
  export declare const VALIDATION_EVIDENCE_SCHEMA_VERSION: '1.0.0';
2
3
  export type ValidationGateCapability = 'typecheck' | 'lint' | 'test-related' | 'test-full' | 'contract' | 'coverage' | 'migration' | 'fault-injection' | 'security' | 'native' | 'website' | 'reproducibility';
3
4
  export type ValidationEvidenceStatus = 'passed' | 'failed' | 'cancelled' | 'invalidated';
@@ -110,6 +111,10 @@ export interface ExecutableEvidence {
110
111
  unmappedCriteria: string[];
111
112
  ignoredCriteriaTitles: string[];
112
113
  }
114
+ export interface SourceQualityReceiptMatch {
115
+ key: string;
116
+ path: string;
117
+ }
113
118
  export interface ReliabilityGateViolation {
114
119
  file: string;
115
120
  line: number;
@@ -122,4 +127,20 @@ export interface ReliabilityGateResult {
122
127
  warnings: ReliabilityGateViolation[];
123
128
  executionError?: string;
124
129
  }
130
+ export interface BlastRadiusGateFailure {
131
+ file: string;
132
+ message: string;
133
+ }
134
+ export interface BlastRadiusGateResult {
135
+ skipped: 'no-importable-files' | 'vitest-not-installed' | null;
136
+ selectedFiles: string[];
137
+ passed: boolean;
138
+ timedOut: boolean;
139
+ failures: BlastRadiusGateFailure[];
140
+ }
141
+ export interface RunBlastRadiusGateOptions {
142
+ timeoutMs: number;
143
+ signal?: AbortSignal;
144
+ runProcess?: (command: string, args: string[], options: AbortableProcessOptions) => Promise<AbortableProcessResult>;
145
+ }
125
146
  //# sourceMappingURL=validation-evidence.d.ts.map