@planu/cli 5.7.11 → 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 (37) hide show
  1. package/CHANGELOG.md +27 -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 +7 -4
  16. package/dist/engine/spec-format/technical-md-populator.js +114 -3
  17. package/dist/engine/spec-format/unified-spec-builder.js +33 -6
  18. package/dist/engine/validator/blast-radius-gate.d.ts +3 -0
  19. package/dist/engine/validator/blast-radius-gate.js +139 -0
  20. package/dist/engine/validator/spec-compliance-runner.d.ts +1 -0
  21. package/dist/engine/validator/spec-compliance-runner.js +3 -0
  22. package/dist/engine/validator/validation-report-writer.d.ts +2 -0
  23. package/dist/engine/validator/validation-report-writer.js +68 -30
  24. package/dist/storage/runtime-db.js +7 -3
  25. package/dist/storage/spec-store.js +6 -2
  26. package/dist/tools/challenge-spec/scenarios-data.js +2 -2
  27. package/dist/tools/challenge-spec/scenarios-utils.d.ts +2 -0
  28. package/dist/tools/challenge-spec/scenarios-utils.js +36 -3
  29. package/dist/tools/validate-lint.js +19 -0
  30. package/dist/tools/validate.js +46 -4
  31. package/dist/types/abortable-process.d.ts +1 -0
  32. package/dist/types/handoff-artifacts.d.ts +10 -0
  33. package/dist/types/runtime-policy.d.ts +1 -0
  34. package/dist/types/spec-format.d.ts +9 -0
  35. package/dist/types/validation-evidence.d.ts +21 -0
  36. package/package.json +2 -2
  37. package/planu-plugin.json +1 -1
@@ -41,8 +41,11 @@ function hasThenSignal(scenario) {
41
41
  function isSingleLineGivenWhenThenText(text) {
42
42
  return WHEN_WORD_RE.test(text) && THEN_WORD_RE.test(text);
43
43
  }
44
- function opensHeaderlessScenario(rawKeyword, text) {
45
- return rawKeyword === 'given' || isSingleLineGivenWhenThenText(text);
44
+ const UPPERCASE_WHEN_LINE_RE = /^WHEN\s/;
45
+ function opensHeaderlessScenario(rawKeyword, text, rawLine) {
46
+ return (rawKeyword === 'given' ||
47
+ isSingleLineGivenWhenThenText(text) ||
48
+ UPPERCASE_WHEN_LINE_RE.test(rawLine));
46
49
  }
47
50
  function suffixedTitle(thenText, steps) {
48
51
  return `${thenText} (given ${steps.find((step) => step.keyword === 'given')?.text ?? ''})`;
@@ -64,7 +67,7 @@ export function parseBddScenarios(markdown) {
64
67
  for (const raw of lines) {
65
68
  const line = raw.trim();
66
69
  // Detect scenario header
67
- const scenarioMatch = /^scenario:\s*(.+)$/i.exec(line);
70
+ const scenarioMatch = /^(?:#{1,6}\s*)?scenario(?:\s+\d+)?:\s*(.+)$/i.exec(line);
68
71
  if (scenarioMatch) {
69
72
  closeCurrent();
70
73
  current = { title: (scenarioMatch[1] ?? '').trim(), steps: [], done: false };
@@ -85,7 +88,7 @@ export function parseBddScenarios(markdown) {
85
88
  closeCurrent();
86
89
  }
87
90
  if (!current) {
88
- if (!opensHeaderlessScenario(rawKeyword, text)) {
91
+ if (!opensHeaderlessScenario(rawKeyword, text, line)) {
89
92
  continue;
90
93
  }
91
94
  current = { title: text, steps: [], done: false };
@@ -37,6 +37,115 @@ function extractPathsFromSection(sectionText) {
37
37
  }
38
38
  return paths;
39
39
  }
40
+ const LABELED_LIST_LINE_RE = /^\s*-?\s*(?:Files to (create|modify)|(Create|Modify|Test))\s*:\s*(.*)$/i;
41
+ const NONE_TOKEN_RE = /^none\.?$/i;
42
+ const TRAILING_LIST_PUNCTUATION_RE = /[.,;:]+$/;
43
+ function labeledBucketKind(labelMatch) {
44
+ const kind = (labelMatch[1] ?? labelMatch[2])?.toLowerCase();
45
+ return kind === 'create' || kind === 'modify' || kind === 'test' ? kind : null;
46
+ }
47
+ function stripLabeledListToken(token) {
48
+ return token
49
+ .replace(/\([^)]*\)/g, '')
50
+ .trim()
51
+ .replace(/^`|`$/g, '')
52
+ .trim()
53
+ .replace(TRAILING_LIST_PUNCTUATION_RE, '');
54
+ }
55
+ const LABELED_PATH_SHAPE_RE = /^[\w./-]+$/;
56
+ function isPathShapedLabelToken(token) {
57
+ return (LABELED_PATH_SHAPE_RE.test(token) && (token.includes('/') || /\.[a-zA-Z0-9]+$/.test(token)));
58
+ }
59
+ function splitLabeledList(text) {
60
+ return text
61
+ .split(',')
62
+ .map(stripLabeledListToken)
63
+ .filter((token) => token.length > 0 && !NONE_TOKEN_RE.test(token) && isPathShapedLabelToken(token));
64
+ }
65
+ function consumeLabeledBulletLines(lines, start) {
66
+ const paths = [];
67
+ let i = start;
68
+ while (i < lines.length && (lines[i] ?? '').trim().length > 0) {
69
+ const line = lines[i] ?? '';
70
+ if (LABELED_LIST_LINE_RE.test(line)) {
71
+ break;
72
+ }
73
+ const bulletMatch = /^\s*-\s*(.+)$/.exec(line);
74
+ if (!bulletMatch?.[1]) {
75
+ break;
76
+ }
77
+ paths.push(...splitLabeledList(bulletMatch[1]));
78
+ i += 1;
79
+ }
80
+ return { paths, next: i };
81
+ }
82
+ function parseLabeledFileLists(body) {
83
+ const lines = body.split('\n');
84
+ const lists = { create: [], modify: [], test: [] };
85
+ let found = false;
86
+ for (let i = 0; i < lines.length; i += 1) {
87
+ const labelMatch = LABELED_LIST_LINE_RE.exec(lines[i] ?? '');
88
+ if (!labelMatch) {
89
+ continue;
90
+ }
91
+ const kind = labeledBucketKind(labelMatch);
92
+ if (!kind || labelMatch[3] === undefined) {
93
+ continue;
94
+ }
95
+ found = true;
96
+ const inline = labelMatch[3].trim();
97
+ if (inline.length > 0) {
98
+ lists[kind].push(...splitLabeledList(inline));
99
+ continue;
100
+ }
101
+ const { paths, next } = consumeLabeledBulletLines(lines, i + 1);
102
+ lists[kind].push(...paths);
103
+ i = next - 1;
104
+ }
105
+ return found ? lists : null;
106
+ }
107
+ function buildEntriesFromLabeledLists(labeled) {
108
+ const create = [];
109
+ const modify = [];
110
+ const test = labeled.test.map((p) => ({ path: p, status: 'pending' }));
111
+ for (const p of labeled.create) {
112
+ create.push({ path: p, status: 'pending' });
113
+ if (isExecutableTestPath(p)) {
114
+ test.push({ path: p, status: 'pending' });
115
+ }
116
+ }
117
+ for (const p of labeled.modify) {
118
+ modify.push({ path: p, status: 'pending' });
119
+ if (isExecutableTestPath(p)) {
120
+ test.push({ path: p, status: 'pending' });
121
+ }
122
+ }
123
+ return { create, modify, test };
124
+ }
125
+ function dedupeByPath(entries) {
126
+ const seen = new Set();
127
+ const result = [];
128
+ for (const entry of entries) {
129
+ if (!seen.has(entry.path)) {
130
+ seen.add(entry.path);
131
+ result.push(entry);
132
+ }
133
+ }
134
+ return result;
135
+ }
136
+ function mergeStructuredAndLabeled(structured, labeled) {
137
+ if (structured === null && labeled === null) {
138
+ return null;
139
+ }
140
+ const fromLabels = labeled === null ? null : buildEntriesFromLabeledLists(labeled);
141
+ const base = structured ?? { create: [], modify: [], test: [] };
142
+ const extra = fromLabels ?? { create: [], modify: [], test: [] };
143
+ return {
144
+ create: dedupeByPath([...base.create, ...extra.create]),
145
+ modify: dedupeByPath([...base.modify, ...extra.modify]),
146
+ test: dedupeByPath([...base.test, ...extra.test]),
147
+ };
148
+ }
40
149
  function parseSectionedFileLists(body) {
41
150
  const filesRange = findMarkdownSectionRange(body, 'Files') ??
42
151
  findMarkdownSectionRange(body, 'Files likely to change');
@@ -189,9 +298,11 @@ export function extractMarkerDeclaredPaths(description) {
189
298
  */
190
299
  export async function extractFilesFromSpecBody(specBody, projectPath) {
191
300
  const structured = parseSectionedFileLists(specBody);
192
- if (structured !== null &&
193
- (structured.create.length > 0 || structured.modify.length > 0 || structured.test.length > 0)) {
194
- return structured;
301
+ const labeled = parseLabeledFileLists(specBody);
302
+ const merged = mergeStructuredAndLabeled(structured, labeled);
303
+ if (merged !== null &&
304
+ (merged.create.length > 0 || merged.modify.length > 0 || merged.test.length > 0)) {
305
+ return merged;
195
306
  }
196
307
  const candidates = [
197
308
  ...new Set(Array.from(stripFencedBlocks(specBody).matchAll(FILE_PATH_RE), (m) => m[0])),
@@ -20,7 +20,8 @@ export function buildCanonicalUnifiedSpecContent(input) {
20
20
  const source = input.sourceDescription.replace(/\r\n/g, '\n').trim();
21
21
  const explicitProblem = extractTopLevelSectionBody(source, 'Problem');
22
22
  const proseBeforeHeading = source.split(/^##[ \t]+\S.*$/m, 1)[0]?.trim() ?? '';
23
- const problem = firstNonEmpty(explicitProblem, proseBeforeHeading, source);
23
+ const fallbackSection = explicitProblem === null && proseBeforeHeading.length === 0 ? firstAuthorSection(source) : null;
24
+ const problem = firstNonEmpty(explicitProblem, proseBeforeHeading, fallbackSection?.body, source);
24
25
  const explicitGoal = extractTopLevelSectionBody(source, 'Goal');
25
26
  const goal = firstNonEmpty(explicitGoal, firstSentence(problem), 'Needs decision: define the goal this spec must achieve.');
26
27
  const explicitTechnical = extractTopLevelSectionBody(source, 'Technical');
@@ -39,7 +40,7 @@ export function buildCanonicalUnifiedSpecContent(input) {
39
40
  renderSection('Acceptance Criteria', acceptance),
40
41
  renderSection('Files', renderOwnedFiles(input.files)),
41
42
  renderSection('Out of scope', outOfScope),
42
- ...extractAuthorSections(source),
43
+ ...extractAuthorSections(source, fallbackSection?.name),
43
44
  ];
44
45
  return `${frontmatter ? `${frontmatter}\n\n` : ''}${sections.join('\n\n')}\n`;
45
46
  }
@@ -52,7 +53,7 @@ const CANONICAL_SECTION_NAMES = new Set([
52
53
  'Files',
53
54
  'Out of scope',
54
55
  ].map((name) => name.toLowerCase()));
55
- function extractAuthorSections(source) {
56
+ function extractAuthorSections(source, skipName) {
56
57
  const scannable = stripFencedCodeBlocks(source);
57
58
  const headingRe = /^##[ \t]+(\S.*?)[ \t]*$/gm;
58
59
  const preserved = [];
@@ -62,6 +63,9 @@ function extractAuthorSections(source) {
62
63
  if (CANONICAL_SECTION_NAMES.has(name.toLowerCase())) {
63
64
  continue;
64
65
  }
66
+ if (skipName?.toLowerCase() === name.toLowerCase()) {
67
+ continue;
68
+ }
65
69
  const body = extractTopLevelSectionBody(source, name);
66
70
  if (body !== null && body.length > 0) {
67
71
  preserved.push(renderSection(name, body));
@@ -69,6 +73,27 @@ function extractAuthorSections(source) {
69
73
  }
70
74
  return preserved;
71
75
  }
76
+ /**
77
+ * The first non-canonical `##` section with a non-empty body, used as the
78
+ * problem fallback when the description opens directly with a heading
79
+ * (SPEC-1753). Returns null when no such section exists.
80
+ */
81
+ function firstAuthorSection(source) {
82
+ const scannable = stripFencedCodeBlocks(source);
83
+ const headingRe = /^##[ \t]+(\S.*?)[ \t]*$/gm;
84
+ let match;
85
+ while ((match = headingRe.exec(scannable)) !== null) {
86
+ const name = match[1] ?? '';
87
+ if (CANONICAL_SECTION_NAMES.has(name.toLowerCase())) {
88
+ continue;
89
+ }
90
+ const body = extractTopLevelSectionBody(source, name);
91
+ if (body !== null && body.length > 0) {
92
+ return { name, body };
93
+ }
94
+ }
95
+ return null;
96
+ }
72
97
  /**
73
98
  * Combine a generated lean spec.md body and a generated lean technical.md body
74
99
  * into a single unified spec.md content. The technical body's YAML frontmatter
@@ -294,14 +319,16 @@ function findEmbeddedRequiredSections(body) {
294
319
  return [...embedded];
295
320
  }
296
321
  function extractTopLevelSectionBody(body, section) {
297
- const heading = new RegExp(`^##[ \\t]+${escapeRegex(section)}[ \\t]*$`, 'mi').exec(body);
322
+ const scannable = maskFencedAndQuotedText(body);
323
+ const heading = new RegExp(`^##[ \\t]+${escapeRegex(section)}[ \\t]*$`, 'mi').exec(scannable);
298
324
  if (!heading) {
299
325
  return null;
300
326
  }
301
327
  const start = heading.index + heading[0].length;
302
- const rest = body.slice(start);
328
+ const rest = scannable.slice(start);
303
329
  const next = /^##[ \t]+\S.*$/m.exec(rest);
304
- return rest.slice(0, next?.index ?? rest.length).trim();
330
+ const end = start + (next?.index ?? rest.length);
331
+ return body.slice(start, end).trim();
305
332
  }
306
333
  function renderSection(title, body) {
307
334
  return `## ${title}\n\n${body.trim()}`;
@@ -0,0 +1,3 @@
1
+ import type { BlastRadiusGateResult, RunBlastRadiusGateOptions } from '../../types/validation-evidence.js';
2
+ export declare function runBlastRadiusGate(projectPath: string, candidateFiles: string[], options: RunBlastRadiusGateOptions): Promise<BlastRadiusGateResult>;
3
+ //# sourceMappingURL=blast-radius-gate.d.ts.map
@@ -0,0 +1,139 @@
1
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { isAbsolute, join, relative } from 'node:path';
4
+ import { runAbortableProcess } from '../abortable-process-runner.js';
5
+ import { technologyValue } from '../technology-registry.js';
6
+ const IMPORTABLE_SOURCE_PATTERN = /\.(?:ts|tsx|js|jsx|mjs|cjs)$/u;
7
+ function skippedResult(skipped) {
8
+ return { skipped, selectedFiles: [], passed: true, timedOut: false, failures: [] };
9
+ }
10
+ function normalizeCandidate(projectPath, file) {
11
+ const absolute = isAbsolute(file) ? file : join(projectPath, file);
12
+ const relativePath = relative(projectPath, absolute);
13
+ return relativePath.startsWith('..') ? null : relativePath;
14
+ }
15
+ function selectCandidateFiles(projectPath, candidateFiles) {
16
+ const normalized = candidateFiles
17
+ .map((file) => normalizeCandidate(projectPath, file))
18
+ .filter((file) => file !== null);
19
+ return [...new Set(normalized)].filter((file) => IMPORTABLE_SOURCE_PATTERN.test(file) && existsSync(join(projectPath, file)));
20
+ }
21
+ function firstFailureLine(assertion) {
22
+ const message = assertion.failureMessages?.[0] ?? 'test failed';
23
+ return message.split('\n')[0] ?? message;
24
+ }
25
+ function relativeReportPath(projectPath, reportedPath) {
26
+ return isAbsolute(reportedPath) ? relative(projectPath, reportedPath) : reportedPath;
27
+ }
28
+ function parseVitestReport(projectPath, reportPath) {
29
+ const raw = readFileSync(reportPath, 'utf-8');
30
+ const parsed = JSON.parse(raw);
31
+ if (!Array.isArray(parsed.testResults)) {
32
+ throw new Error('vitest report has no testResults array');
33
+ }
34
+ const failures = [];
35
+ for (const testResult of parsed.testResults) {
36
+ const reportedPath = testResult.testFilePath ?? testResult.name;
37
+ if (!reportedPath) {
38
+ continue;
39
+ }
40
+ const file = relativeReportPath(projectPath, reportedPath);
41
+ for (const assertion of testResult.assertionResults ?? []) {
42
+ if (assertion.status === 'failed') {
43
+ failures.push({ file, message: firstFailureLine(assertion) });
44
+ }
45
+ }
46
+ }
47
+ return failures;
48
+ }
49
+ function abortFailure(reportPath, signal, selectedFiles) {
50
+ const message = signal !== null ? `vitest related aborted (signal ${signal})` : 'vitest related aborted';
51
+ return {
52
+ skipped: null,
53
+ selectedFiles,
54
+ passed: false,
55
+ timedOut: false,
56
+ failures: [{ file: reportPath, message }],
57
+ };
58
+ }
59
+ function exitStatusFailure(reportPath, status, selectedFiles) {
60
+ return {
61
+ skipped: null,
62
+ selectedFiles,
63
+ passed: false,
64
+ timedOut: false,
65
+ failures: [
66
+ {
67
+ file: reportPath,
68
+ message: `vitest related exited with status ${status} without parseable failures`,
69
+ },
70
+ ],
71
+ };
72
+ }
73
+ function reportFailure(reportPath, selectedFiles, error) {
74
+ const detail = error instanceof Error ? error.message : String(error);
75
+ return {
76
+ skipped: null,
77
+ selectedFiles,
78
+ passed: false,
79
+ timedOut: false,
80
+ failures: [
81
+ { file: reportPath, message: `blast radius report missing or unreadable: ${detail}` },
82
+ ],
83
+ };
84
+ }
85
+ export async function runBlastRadiusGate(projectPath, candidateFiles, options) {
86
+ const selectedFiles = selectCandidateFiles(projectPath, candidateFiles);
87
+ if (selectedFiles.length === 0) {
88
+ return skippedResult('no-importable-files');
89
+ }
90
+ const vitestBin = join(projectPath, 'node_modules', '.bin', technologyValue('technology-vitest-a9127f'));
91
+ if (!existsSync(vitestBin)) {
92
+ return skippedResult('vitest-not-installed');
93
+ }
94
+ const runProcess = options.runProcess ?? runAbortableProcess;
95
+ const reportDir = mkdtempSync(join(tmpdir(), 'planu-blast-radius-'));
96
+ const reportPath = join(reportDir, 'blast-radius.json');
97
+ try {
98
+ const result = await runProcess(vitestBin, [
99
+ 'related',
100
+ '--run',
101
+ '--maxWorkers=6',
102
+ '--reporter=json',
103
+ `--outputFile.json=${reportPath}`,
104
+ ...selectedFiles,
105
+ ], {
106
+ cwd: projectPath,
107
+ timeoutMs: options.timeoutMs,
108
+ maxBufferBytes: 64 * 1024 * 1024,
109
+ signal: options.signal,
110
+ env: { ...process.env, PLANU_EXCLUDE_INTEGRATION_TESTS: '1' },
111
+ });
112
+ if (result.timedOut) {
113
+ return { skipped: null, selectedFiles, passed: false, timedOut: true, failures: [] };
114
+ }
115
+ if (result.aborted || result.signal !== null) {
116
+ return abortFailure(reportPath, result.signal, selectedFiles);
117
+ }
118
+ try {
119
+ const failures = parseVitestReport(projectPath, reportPath);
120
+ if (failures.length === 0 && result.status !== null && result.status !== 0) {
121
+ return exitStatusFailure(reportPath, result.status, selectedFiles);
122
+ }
123
+ return {
124
+ skipped: null,
125
+ selectedFiles,
126
+ passed: failures.length === 0,
127
+ timedOut: false,
128
+ failures,
129
+ };
130
+ }
131
+ catch (error) {
132
+ return reportFailure(reportPath, selectedFiles, error);
133
+ }
134
+ }
135
+ finally {
136
+ rmSync(reportDir, { recursive: true, force: true });
137
+ }
138
+ }
139
+ //# sourceMappingURL=blast-radius-gate.js.map
@@ -8,5 +8,6 @@ export declare class ComplianceCommandTerminalError extends Error {
8
8
  export declare function parseFrontmatterScenarios(raw: string): FrontmatterScenario[];
9
9
  export declare function runSpecCompliance(spec: Spec, projectPath: string, signal?: AbortSignal, canonicalProjectId?: string): Promise<SpecComplianceResult>;
10
10
  export declare function findScenariosWithoutTests(raw: string): string[];
11
+ export declare function collectDeclaredSpecFiles(raw: string): string[];
11
12
  export declare function findDoneDriftMissingFiles(spec: Spec, raw: string, projectPath: string, fileExists: (path: string) => boolean): DoneDriftMissingFileFinding[];
12
13
  //# sourceMappingURL=spec-compliance-runner.d.ts.map
@@ -701,6 +701,9 @@ function extractFilesSectionPaths(raw) {
701
701
  }
702
702
  return paths;
703
703
  }
704
+ export function collectDeclaredSpecFiles(raw) {
705
+ return [...new Set([...extractFilesMarkerPaths(raw), ...extractFilesSectionPaths(raw)])];
706
+ }
704
707
  export function findDoneDriftMissingFiles(spec, raw, projectPath, fileExists) {
705
708
  if (spec.status !== 'done') {
706
709
  return [];
@@ -1,5 +1,6 @@
1
1
  import type { Spec } from '../../types/index.js';
2
2
  import type { ValidationReportV1 } from '../../types/handoff-artifacts.js';
3
+ import type { BlastRadiusGateResult } from '../../types/validation-evidence.js';
3
4
  import type { MinimalImplementationReport } from '../../types/minimal-implementation-gate.js';
4
5
  export declare const AUTOMATED_VALIDATOR_AGENT = "planu-automated-validator";
5
6
  export declare function writeImplementationReviewReport(input: {
@@ -12,6 +13,7 @@ export declare function writeImplementationReviewReport(input: {
12
13
  conventionRegression?: boolean;
13
14
  minimalityReport?: MinimalImplementationReport;
14
15
  signal?: AbortSignal;
16
+ blastRadius?: BlastRadiusGateResult;
15
17
  }): Promise<{
16
18
  written: boolean;
17
19
  path?: string;
@@ -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() {
@@ -252,6 +252,10 @@ async function persistDigestRefresh(projectId, specId, title, specVersion, conte
252
252
  * spec.md; callers that omit it get the specs.json record unchecked (matching
253
253
  * the existing canonicalRoot-gated legacy-migration behavior on this same path).
254
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
+ }
255
259
  async function refreshSpecFromDisk(projectId, spec, canonicalRoot) {
256
260
  let specMdPath;
257
261
  try {
@@ -279,10 +283,10 @@ async function refreshSpecFromDisk(projectId, spec, canonicalRoot) {
279
283
  return null;
280
284
  }
281
285
  const digest = digestOf(content);
282
- if (digest === spec.contentDigest) {
286
+ const fields = readFrontmatterScalars(content);
287
+ if (digest === spec.contentDigest && !frontmatterScalarsDrifted(fields, spec)) {
283
288
  return spec;
284
289
  }
285
- const fields = readFrontmatterScalars(content);
286
290
  const refreshed = {
287
291
  ...spec,
288
292
  title: fields.title ?? spec.title,
@@ -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;