@planu/cli 5.7.13 → 5.7.14

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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,20 @@
1
+ ## [5.7.14] - 2026-09-03
2
+
3
+ ### Features
4
+ - feat(validator): credit negative and deletion criteria via fail-closed absence scan (SPEC-1579)
5
+ - feat(gates): carry executable next actions and external blockage state (SPEC-1691)
6
+ - feat(jobs): accept projectPath in get_job and restart_job (SPEC-1392)
7
+
8
+ ### Bug Fixes
9
+ - fix(types): import ToolResult from primitives to break the structured-error barrel cycle (SPEC-1691)
10
+ - fix(validate): rebuild stale dist once before the blast-radius importer run (SPEC-1781)
11
+ - fix(gates): prefer projectPath by undefined check and drop comments (SPEC-1691)
12
+ - fix(bdd-parser): tolerate list markers and split single-line GWT criteria (SPEC-1720)
13
+
14
+ ### Refactoring
15
+ - refactor(gates): move GateUnavailableIdentity to types and compact blocked text (SPEC-1691)
16
+
17
+
1
18
  ## [5.7.13] - 2026-09-03
2
19
 
3
20
  ### Features
@@ -1 +1 @@
1
- {"schemaVersion":1,"commit":"ee3c4024cb57c413795f82e3c5049899d22e2b3f"}
1
+ {"schemaVersion":1,"commit":"d670004fb49b403f699139c7c2781e651ed0d04a"}
@@ -0,0 +1,33 @@
1
+ [
2
+ {
3
+ "id": "deletion",
4
+ "phrases": [
5
+ "no longer exist",
6
+ "does not exist",
7
+ "do not exist",
8
+ "must not exist",
9
+ "is removed",
10
+ "are removed",
11
+ "has been removed",
12
+ "have been removed",
13
+ "is deleted",
14
+ "are deleted"
15
+ ]
16
+ },
17
+ {
18
+ "id": "import-absence",
19
+ "phrases": [
20
+ "nothing imports",
21
+ "no longer imports",
22
+ "must not import",
23
+ "does not import",
24
+ "no references to",
25
+ "no remaining references",
26
+ "with no"
27
+ ]
28
+ },
29
+ {
30
+ "id": "literal-absence",
31
+ "phrases": ["no hardcoded", "no literal", "no magic", "no raw", "remove all"]
32
+ }
33
+ ]
@@ -20,5 +20,7 @@ export declare function renderBddScenariosYaml(scenarios: BddScenario[]): string
20
20
  * Plain text criteria get a generic GIVEN (system context) and WHEN (action trigger)
21
21
  * so scenarios are always structurally valid BDD.
22
22
  */
23
+ export declare const PLACEHOLDER_GIVEN_STEP_TEXT = "the system is in its default state";
24
+ export declare const PLACEHOLDER_WHEN_STEP_TEXT = "the described behavior is triggered";
23
25
  export declare function convertCheckboxToBdd(criteria: LeanCriterion[]): BddScenario[];
24
26
  //# sourceMappingURL=bdd-parser.d.ts.map
@@ -1,12 +1,17 @@
1
1
  // engine/spec-format/bdd-parser.ts — BDD/Gherkin parser and emitter (SPEC-481)
2
2
  import { consumePathRunPreservingCase } from './technical-md-populator.js';
3
3
  const TEST_MARKER_RE = /\bTESTS?\s*:/gi;
4
+ const MARKER_BOUNDARY_RE = /\b(?:FILES?|FUNCTIONS?|OWNER|TESTS?)\s*:/i;
5
+ const PATH_SHAPED_TOKEN_RE = /(?:[\w.@-]+\/)+[\w.-]+\.[a-zA-Z0-9]+/g;
4
6
  export function extractInlineTestPaths(text) {
5
7
  const paths = [];
6
8
  const seen = new Set();
7
9
  for (const marker of text.matchAll(TEST_MARKER_RE)) {
8
10
  const start = marker.index + marker[0].length;
9
- for (const path of consumePathRunPreservingCase(text.slice(start))) {
11
+ const segment = text.slice(start).split(MARKER_BOUNDARY_RE)[0] ?? '';
12
+ const run = consumePathRunPreservingCase(segment);
13
+ const found = run.length > 0 ? run : (segment.match(PATH_SHAPED_TOKEN_RE) ?? []);
14
+ for (const path of found) {
10
15
  if (!seen.has(path)) {
11
16
  seen.add(path);
12
17
  paths.push(path);
@@ -50,6 +55,58 @@ function opensHeaderlessScenario(rawKeyword, text, rawLine) {
50
55
  function suffixedTitle(thenText, steps) {
51
56
  return `${thenText} (given ${steps.find((step) => step.keyword === 'given')?.text ?? ''})`;
52
57
  }
58
+ const LIST_MARKER_RE = /^(?:[-*+>]\s+|\d+[.)]\s+)/;
59
+ const MARKER_TAIL_RE = /\s*\b(?:FILES?|FUNCTIONS?|TESTS?|OWNER)\s*:[\s\S]*$/i;
60
+ const CODE_SPAN_RE = /`[^`]*`/g;
61
+ function stripMarkerTail(text) {
62
+ return text.replace(MARKER_TAIL_RE, '').trim();
63
+ }
64
+ function maskCodeSpans(text) {
65
+ return text.replace(CODE_SPAN_RE, (span) => ' '.repeat(span.length));
66
+ }
67
+ function splitSingleLineGwt(line) {
68
+ const masked = maskCodeSpans(line);
69
+ const given = /^GIVEN\b/.exec(masked);
70
+ if (given === null) {
71
+ return null;
72
+ }
73
+ const when = /\bWHEN\b/.exec(masked.slice(given.index));
74
+ if (when === null) {
75
+ return null;
76
+ }
77
+ const whenIndex = given.index + when.index;
78
+ const then = /\bTHEN\b/.exec(masked.slice(whenIndex));
79
+ if (then === null) {
80
+ return null;
81
+ }
82
+ const thenIndex = whenIndex + then.index;
83
+ const givenText = line.slice(given.index + 'GIVEN'.length, whenIndex).trim();
84
+ const whenText = line.slice(whenIndex + 'WHEN'.length, thenIndex).trim();
85
+ const thenText = line.slice(thenIndex + 'THEN'.length).trim();
86
+ if (givenText === '' || whenText === '' || thenText === '') {
87
+ return null;
88
+ }
89
+ return [
90
+ { keyword: 'given', text: givenText },
91
+ { keyword: 'when', text: whenText },
92
+ { keyword: 'then', text: stripMarkerTail(thenText) },
93
+ ];
94
+ }
95
+ function buildSingleLineScenario(line, closedTitles) {
96
+ const singleLineSteps = splitSingleLineGwt(line);
97
+ if (singleLineSteps === null) {
98
+ return null;
99
+ }
100
+ const thenText = singleLineSteps[singleLineSteps.length - 1]?.text ?? '';
101
+ const title = closedTitles.has(thenText) ? suffixedTitle(thenText, singleLineSteps) : thenText;
102
+ const tests = extractInlineTestPaths(line).map((path) => ({ path }));
103
+ return {
104
+ title,
105
+ steps: singleLineSteps,
106
+ done: false,
107
+ ...(tests.length > 0 ? { tests } : {}),
108
+ };
109
+ }
53
110
  export function parseBddScenarios(markdown) {
54
111
  const scenarios = [];
55
112
  const lines = markdown.split('\n');
@@ -65,7 +122,7 @@ export function parseBddScenarios(markdown) {
65
122
  currentIsHeaderless = false;
66
123
  };
67
124
  for (const raw of lines) {
68
- const line = raw.trim();
125
+ const line = raw.trim().replace(LIST_MARKER_RE, '');
69
126
  // Detect scenario header
70
127
  const scenarioMatch = /^(?:#{1,6}\s*)?scenario(?:\s+\d+)?:\s*(.+)$/i.exec(line);
71
128
  if (scenarioMatch) {
@@ -73,6 +130,13 @@ export function parseBddScenarios(markdown) {
73
130
  current = { title: (scenarioMatch[1] ?? '').trim(), steps: [], done: false };
74
131
  continue;
75
132
  }
133
+ const singleLineScenario = buildSingleLineScenario(line, closedTitles);
134
+ if (singleLineScenario !== null) {
135
+ closeCurrent();
136
+ current = singleLineScenario;
137
+ closeCurrent();
138
+ continue;
139
+ }
76
140
  // Detect step keywords
77
141
  const stepMatch = /^(given|when|then|and|but)\s+(.+)$/i.exec(line);
78
142
  if (!stepMatch) {
@@ -141,12 +205,14 @@ export function renderBddScenariosYaml(scenarios) {
141
205
  * Plain text criteria get a generic GIVEN (system context) and WHEN (action trigger)
142
206
  * so scenarios are always structurally valid BDD.
143
207
  */
208
+ export const PLACEHOLDER_GIVEN_STEP_TEXT = 'the system is in its default state';
209
+ export const PLACEHOLDER_WHEN_STEP_TEXT = 'the described behavior is triggered';
144
210
  export function convertCheckboxToBdd(criteria) {
145
211
  return criteria.map((criterion) => ({
146
212
  title: criterion.text,
147
213
  steps: [
148
- { keyword: 'given', text: 'the system is in its default state' },
149
- { keyword: 'when', text: 'the described behavior is triggered' },
214
+ { keyword: 'given', text: PLACEHOLDER_GIVEN_STEP_TEXT },
215
+ { keyword: 'when', text: PLACEHOLDER_WHEN_STEP_TEXT },
150
216
  { keyword: 'then', text: criterion.text },
151
217
  ],
152
218
  done: criterion.done,
@@ -3,15 +3,6 @@ import type { Spec, AuditFinding, CodeState, VerifyBlock, CriterionEvidenceResul
3
3
  * Scan the project directory to build a CodeState for the given spec.
4
4
  */
5
5
  export declare function scanCodeForSpec(spec: Spec, projectPath: string): Promise<CodeState>;
6
- /**
7
- * Check whether a single criterion is satisfied in the given code state.
8
- * When `verifyBlock` is provided it is forwarded to deepCheckCriterion,
9
- * bypassing keyword-based classification (explicit beats inferred).
10
- *
11
- * Pass `sharedFileContents` (pre-built via buildBroadCache or
12
- * buildFileContentsCache from criterion-matcher) to avoid a redundant
13
- * glob+readFile pass when checking multiple criteria in the same call.
14
- */
15
6
  export declare function checkCriterionEvidence(criterion: string, projectPath: string, codeState: CodeState, verifyBlock?: VerifyBlock, sharedFileContents?: Map<string, string>, declaredTestPaths?: string[], probeCache?: Map<string, {
16
7
  passed: boolean;
17
8
  evidence: string;
@@ -49,6 +49,7 @@ async function buildBroadCache(projectPath) {
49
49
  return cache;
50
50
  }
51
51
  import { deepCheckCriterion } from './deep-code-checker.js';
52
+ import { classifyNegativePredicate, checkTokensAbsent } from './negative-predicate.js';
52
53
  import { ConfigLoader } from '../config-loader.js';
53
54
  import { filterValidatedTestPaths, groundNumericLiteral, createProbeCache, groundAgainstDeclaredTests, findBacktickIdentifierEvidence, } from './test-evidence-grounding.js';
54
55
  // ---------------------------------------------------------------------------
@@ -209,6 +210,30 @@ async function checkComponentMatch(criterion, projectPath, codeState, sharedFile
209
210
  * buildFileContentsCache from criterion-matcher) to avoid a redundant
210
211
  * glob+readFile pass when checking multiple criteria in the same call.
211
212
  */
213
+ async function resolveNegativePredicateEvidence(criterion, projectPath) {
214
+ const negative = classifyNegativePredicate(criterion);
215
+ if (!negative.isNegative) {
216
+ return null;
217
+ }
218
+ const absence = await checkTokensAbsent(negative.tokens, projectPath);
219
+ if (absence.unverifiable) {
220
+ return { status: 'indeterminate', evidence: absence.evidence[0] };
221
+ }
222
+ return { status: absence.met ? 'proven' : 'missing', evidence: absence.evidence[0] };
223
+ }
224
+ async function resolveFileExistenceEvidence(criterion, projectPath) {
225
+ const fileMatch = /(?:create|add|implement)\s+(?:file\s+)?["']?([^\s"']+\.\w+)["']?/i.exec(criterion);
226
+ if (!fileMatch?.[1]) {
227
+ return null;
228
+ }
229
+ try {
230
+ await stat(join(projectPath, fileMatch[1]));
231
+ return { status: 'proven' };
232
+ }
233
+ catch {
234
+ return { status: 'missing' };
235
+ }
236
+ }
212
237
  export async function checkCriterionEvidence(criterion, projectPath, codeState, verifyBlock, sharedFileContents, declaredTestPaths, probeCache) {
213
238
  // SPEC-1367 review finding 1: validate declared test paths ONCE, up front —
214
239
  // they reach both a readFile call and a spawnSync argv further down. Every
@@ -218,17 +243,16 @@ export async function checkCriterionEvidence(criterion, projectPath, codeState,
218
243
  const safeTestPaths = declaredTestPaths && declaredTestPaths.length > 0
219
244
  ? await filterValidatedTestPaths(projectPath, declaredTestPaths)
220
245
  : [];
221
- // Check for file existence criteria
222
- const fileMatch = /(?:create|add|implement)\s+(?:file\s+)?["']?([^\s"']+\.\w+)["']?/i.exec(criterion);
223
- if (fileMatch?.[1]) {
224
- try {
225
- await stat(join(projectPath, fileMatch[1]));
226
- return { status: 'proven' };
227
- }
228
- catch {
229
- return { status: 'missing' };
246
+ if (!verifyBlock) {
247
+ const negativeResult = await resolveNegativePredicateEvidence(criterion, projectPath);
248
+ if (negativeResult) {
249
+ return negativeResult;
230
250
  }
231
251
  }
252
+ const fileExistenceResult = await resolveFileExistenceEvidence(criterion, projectPath);
253
+ if (fileExistenceResult) {
254
+ return fileExistenceResult;
255
+ }
232
256
  // Check for component/function existence in code (legacy + SPEC-1367 backtick forms)
233
257
  const componentResult = await checkComponentMatch(criterion, projectPath, codeState, sharedFileContents, safeTestPaths);
234
258
  if (componentResult) {
@@ -2,10 +2,15 @@ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
2
2
  import { tmpdir } from 'node:os';
3
3
  import { isAbsolute, join, relative } from 'node:path';
4
4
  import { runAbortableProcess } from '../abortable-process-runner.js';
5
+ import { assertLocalBuildFreshness } from '../build-freshness.js';
6
+ import { pmRunner } from '../framework-detector.js';
7
+ import { resolveProjectCommandPlan } from '../project-command-runtime.js';
5
8
  import { technologyValue } from '../technology-registry.js';
6
9
  const IMPORTABLE_SOURCE_PATTERN = /\.(?:ts|tsx|js|jsx|mjs|cjs)$/u;
7
10
  const INTEGRATION_ONLY_ENV = 'PLANU_INTEGRATION_TESTS_ONLY';
8
11
  const EXCLUDE_INTEGRATION_ENV = 'PLANU_EXCLUDE_INTEGRATION_TESTS';
12
+ const DIST_ROOT = 'dist';
13
+ const BUILD_SCRIPT_CANDIDATES = ['build:ts', 'build'];
9
14
  function skippedResult(skipped) {
10
15
  return {
11
16
  skipped,
@@ -17,6 +22,82 @@ function skippedResult(skipped) {
17
22
  warningReason: null,
18
23
  };
19
24
  }
25
+ function resolveBuildPlan(projectPath) {
26
+ let pkg;
27
+ try {
28
+ const raw = readFileSync(join(projectPath, 'package.json'), 'utf-8');
29
+ pkg = JSON.parse(raw);
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ const scripts = pkg.scripts ?? {};
35
+ const script = BUILD_SCRIPT_CANDIDATES.find((candidate) => typeof scripts[candidate] === 'string');
36
+ if (script === undefined) {
37
+ return null;
38
+ }
39
+ const packageManagerName = typeof pkg.packageManager === 'string' ? (pkg.packageManager.split('@')[0] ?? null) : null;
40
+ const runner = pmRunner(packageManagerName);
41
+ const plan = resolveProjectCommandPlan(projectPath, `${runner} run ${script}`);
42
+ return { executable: plan.executable, args: plan.args, script };
43
+ }
44
+ function staleDistFailure(selectedFiles, reason, detail) {
45
+ return {
46
+ skipped: null,
47
+ selectedFiles,
48
+ passed: false,
49
+ timedOut: false,
50
+ failures: [
51
+ { file: 'dist', message: `stale-dist: ${reason}; ${detail}; run pnpm build:ts and retry` },
52
+ ],
53
+ integrationImporters: [],
54
+ warningReason: 'stale-dist',
55
+ };
56
+ }
57
+ async function ensureFreshDist(projectPath, selectedFiles, runProcess, options) {
58
+ const check = options.checkBuildFreshness ?? assertLocalBuildFreshness;
59
+ const distRoot = join(projectPath, DIST_ROOT);
60
+ const first = check(distRoot);
61
+ if (first.status !== 'stale') {
62
+ return { failure: null, remainingTimeoutMs: options.timeoutMs };
63
+ }
64
+ const plan = resolveBuildPlan(projectPath);
65
+ if (plan === null) {
66
+ return {
67
+ failure: staleDistFailure(selectedFiles, first.reason ?? 'stale build output', 'no build script found in package.json'),
68
+ remainingTimeoutMs: options.timeoutMs,
69
+ };
70
+ }
71
+ const startedAt = Date.now();
72
+ const build = await runProcess(plan.executable, plan.args, {
73
+ cwd: projectPath,
74
+ timeoutMs: options.timeoutMs,
75
+ maxBufferBytes: 16 * 1024 * 1024,
76
+ signal: options.signal,
77
+ env: process.env,
78
+ });
79
+ if (build.timedOut) {
80
+ return {
81
+ failure: staleDistFailure(selectedFiles, first.reason ?? 'stale build output', `${plan.script} timed out after ${options.timeoutMs} ms`),
82
+ remainingTimeoutMs: 0,
83
+ };
84
+ }
85
+ const second = check(distRoot);
86
+ const remainingTimeoutMs = Math.max(0, options.timeoutMs - (Date.now() - startedAt));
87
+ if (second.status === 'stale') {
88
+ return {
89
+ failure: staleDistFailure(selectedFiles, second.reason ?? 'stale build output', `${plan.script} did not refresh the build stamp`),
90
+ remainingTimeoutMs,
91
+ };
92
+ }
93
+ if (remainingTimeoutMs === 0) {
94
+ return {
95
+ failure: staleDistFailure(selectedFiles, first.reason ?? 'stale build output', `${plan.script} consumed the ${options.timeoutMs} ms blast-radius budget`),
96
+ remainingTimeoutMs: 0,
97
+ };
98
+ }
99
+ return { failure: null, remainingTimeoutMs };
100
+ }
20
101
  function normalizeCandidate(projectPath, file) {
21
102
  const absolute = isAbsolute(file) ? file : join(projectPath, file);
22
103
  const relativePath = relative(projectPath, absolute);
@@ -169,6 +250,10 @@ export async function runBlastRadiusGate(projectPath, candidateFiles, options) {
169
250
  return skippedResult('vitest-not-installed');
170
251
  }
171
252
  const runProcess = options.runProcess ?? runAbortableProcess;
253
+ const preflight = await ensureFreshDist(projectPath, selectedFiles, runProcess, options);
254
+ if (preflight.failure !== null) {
255
+ return preflight.failure;
256
+ }
172
257
  const reportDir = mkdtempSync(join(tmpdir(), 'planu-blast-radius-'));
173
258
  const reportPath = join(reportDir, 'blast-radius.json');
174
259
  try {
@@ -181,7 +266,7 @@ export async function runBlastRadiusGate(projectPath, candidateFiles, options) {
181
266
  ...selectedFiles,
182
267
  ], {
183
268
  cwd: projectPath,
184
- timeoutMs: options.timeoutMs,
269
+ timeoutMs: preflight.remainingTimeoutMs,
185
270
  maxBufferBytes: 64 * 1024 * 1024,
186
271
  signal: options.signal,
187
272
  env: { ...process.env, [EXCLUDE_INTEGRATION_ENV]: '1' },
@@ -4,6 +4,7 @@ import { readFile, stat } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
5
5
  import { glob } from 'glob';
6
6
  import { escapeRegex } from '../../core/shared/strings.js';
7
+ import { matchesLegacyAbsentPhrase } from './negative-predicate.js';
7
8
  const DEFAULT_IGNORE = ['node_modules/**', 'dist/**', 'build/**', '.git/**', 'coverage/**'];
8
9
  // ─── Numeric literal normalization (SPEC-1367) ───────────────────────────────
9
10
  // Grounds criteria whose THEN names an explicit numeric timeout (e.g. "45_000")
@@ -39,11 +40,7 @@ export function extractNumericLiterals(text) {
39
40
  export function classifyCriterion(text) {
40
41
  const lower = text.toLowerCase();
41
42
  // grep_absent: look for patterns that MUST NOT exist
42
- if (lower.includes('no hardcoded') ||
43
- lower.includes('no literal') ||
44
- lower.includes('no magic') ||
45
- lower.includes('no raw') ||
46
- lower.includes('remove all')) {
43
+ if (matchesLegacyAbsentPhrase(lower)) {
47
44
  return { type: 'grep_absent', config: buildAbsentConfig(text) };
48
45
  }
49
46
  // SPEC-1367 review: a global numeric_timeout bucket used to live here,
@@ -0,0 +1,18 @@
1
+ import type { TokenAbsenceResult } from '../../types/index.js';
2
+ export declare function loadNegativePredicatePhrases(): readonly string[];
3
+ export declare function matchesNegativePhrase(text: string): boolean;
4
+ export declare function matchesLegacyAbsentPhrase(text: string): boolean;
5
+ export declare function extractNegativeTokens(text: string): string[];
6
+ export declare function isPathShaped(token: string): boolean;
7
+ export declare function classifyNegativePredicate(text: string): {
8
+ isNegative: boolean;
9
+ tokens: string[];
10
+ };
11
+ export declare const NEGATIVE_TOKEN_SCOPE: readonly string[];
12
+ export declare const NEGATIVE_SCAN_IGNORE: readonly string[];
13
+ export declare const NEGATIVE_SCAN_FILE_LIMIT = 5000;
14
+ export declare function checkTokensAbsent(tokens: readonly string[], projectPath: string, options?: {
15
+ fileLimit?: number;
16
+ signal?: AbortSignal;
17
+ }): Promise<TokenAbsenceResult>;
18
+ //# sourceMappingURL=negative-predicate.d.ts.map
@@ -0,0 +1,240 @@
1
+ import { readFile, lstat, realpath } from 'node:fs/promises';
2
+ import { dirname, isAbsolute, join, relative, sep } from 'node:path';
3
+ import { glob } from 'glob';
4
+ import { z } from 'zod';
5
+ import { ConfigLoader } from '../config-loader.js';
6
+ const NegativePredicatePhraseGroupSchema = z.object({
7
+ id: z.string().describe('Phrase group identifier (e.g. "deletion", "import-absence")'),
8
+ phrases: z
9
+ .array(z.string())
10
+ .describe('Lowercase phrases that mark a criterion as asserting absence'),
11
+ });
12
+ const NegativePredicatePhraseGroupArraySchema = z.array(NegativePredicatePhraseGroupSchema);
13
+ const loader = new ConfigLoader('negative-predicate-phrases', NegativePredicatePhraseGroupArraySchema);
14
+ export function loadNegativePredicatePhrases() {
15
+ return loader.load().flatMap((group) => group.phrases.map((phrase) => phrase.toLowerCase()));
16
+ }
17
+ export function matchesNegativePhrase(text) {
18
+ const lower = text.toLowerCase();
19
+ return loadNegativePredicatePhrases().some((phrase) => lower.includes(phrase));
20
+ }
21
+ const LEGACY_ABSENT_GROUP_ID = 'literal-absence';
22
+ export function matchesLegacyAbsentPhrase(text) {
23
+ const lower = text.toLowerCase();
24
+ return loader
25
+ .load()
26
+ .filter((group) => group.id === LEGACY_ABSENT_GROUP_ID)
27
+ .flatMap((group) => group.phrases.map((phrase) => phrase.toLowerCase()))
28
+ .some((phrase) => lower.includes(phrase));
29
+ }
30
+ const SLASH_JOINED_IDENTIFIER_PAIR = /^[A-Za-z_$][\w$]*(?:\/[A-Za-z_$][\w$]*)+$/;
31
+ const BARE_TOKEN_PATTERN = /(?:^|[\s(,])((?:@[\w.-]+\/)?[\w.@-]+(?:\/[\w.@*-]+)+)/g;
32
+ function normalizeToken(rawToken) {
33
+ return rawToken
34
+ .trim()
35
+ .replace(/[.,;:)]+$/, '')
36
+ .replace(/\*$/u, '');
37
+ }
38
+ function splitSlashJoinedIdentifiers(token) {
39
+ return SLASH_JOINED_IDENTIFIER_PAIR.test(token) ? token.split('/') : [token];
40
+ }
41
+ export function extractNegativeTokens(text) {
42
+ const rawTokens = [];
43
+ for (const match of text.matchAll(/`([^`]+)`/g)) {
44
+ rawTokens.push(match[1] ?? '');
45
+ }
46
+ for (const match of text.matchAll(/"([^"]+)"/g)) {
47
+ rawTokens.push(match[1] ?? '');
48
+ }
49
+ for (const match of text.matchAll(/'([^']+)'/g)) {
50
+ rawTokens.push(match[1] ?? '');
51
+ }
52
+ for (const match of text.matchAll(BARE_TOKEN_PATTERN)) {
53
+ rawTokens.push(match[1] ?? '');
54
+ }
55
+ const tokens = [];
56
+ const seen = new Set();
57
+ for (const raw of rawTokens) {
58
+ const normalized = normalizeToken(raw);
59
+ for (const token of splitSlashJoinedIdentifiers(normalized)) {
60
+ if (token.length < 3 || seen.has(token)) {
61
+ continue;
62
+ }
63
+ seen.add(token);
64
+ tokens.push(token);
65
+ }
66
+ }
67
+ return tokens;
68
+ }
69
+ export function isPathShaped(token) {
70
+ return (token.includes('/') &&
71
+ !token.includes('*') &&
72
+ !/\s/.test(token) &&
73
+ !token.includes('\\') &&
74
+ !token.startsWith('/') &&
75
+ !token.startsWith('@') &&
76
+ !token.split('/').includes('..'));
77
+ }
78
+ export function classifyNegativePredicate(text) {
79
+ const tokens = extractNegativeTokens(text);
80
+ return { isNegative: matchesNegativePhrase(text) && tokens.length > 0, tokens };
81
+ }
82
+ export const NEGATIVE_TOKEN_SCOPE = [
83
+ 'src/**/*.{ts,tsx,mts,cts,js,mjs,cjs,jsx,json}',
84
+ 'scripts/**/*.{ts,mts,cts,js,mjs,cjs,sh,json}',
85
+ '**/package.json',
86
+ 'pnpm-workspace.yaml',
87
+ 'tsconfig*.json',
88
+ ];
89
+ export const NEGATIVE_SCAN_IGNORE = [
90
+ '**/node_modules/**',
91
+ '**/dist/**',
92
+ '**/build/**',
93
+ '**/coverage/**',
94
+ '**/.vitepress/cache/**',
95
+ '.git/**',
96
+ 'planu/**',
97
+ '.planu/**',
98
+ '.worktrees/**',
99
+ ];
100
+ export const NEGATIVE_SCAN_FILE_LIMIT = 5000;
101
+ function isOutside(root, candidate) {
102
+ const pathFromRoot = relative(root, candidate);
103
+ return pathFromRoot === '..' || pathFromRoot.startsWith(`..${sep}`) || isAbsolute(pathFromRoot);
104
+ }
105
+ async function projectEntryExists(projectPath, token) {
106
+ const candidate = join(projectPath, token);
107
+ try {
108
+ await lstat(candidate);
109
+ }
110
+ catch (err) {
111
+ const code = err.code;
112
+ if (code === 'ENOENT' || code === 'ENOTDIR') {
113
+ return { status: 'absent' };
114
+ }
115
+ return {
116
+ status: 'unverifiable',
117
+ evidence: `scan-unreadable: ${token} could not be stat'd — absence cannot be verified`,
118
+ };
119
+ }
120
+ try {
121
+ const [rootReal, parentReal] = await Promise.all([
122
+ realpath(projectPath),
123
+ realpath(dirname(candidate)),
124
+ ]);
125
+ if (isOutside(rootReal, parentReal)) {
126
+ return {
127
+ status: 'unverifiable',
128
+ evidence: `scan-escaped: ${token} resolves outside the project — absence cannot be verified`,
129
+ };
130
+ }
131
+ return { status: 'present' };
132
+ }
133
+ catch {
134
+ return {
135
+ status: 'unverifiable',
136
+ evidence: `scan-unreadable: ${token} could not be resolved — absence cannot be verified`,
137
+ };
138
+ }
139
+ }
140
+ async function scanContentHits(files, tokens, projectPath, signal) {
141
+ const contentHits = [];
142
+ for (const relPath of files) {
143
+ signal?.throwIfAborted();
144
+ let content;
145
+ try {
146
+ content = await readFile(join(projectPath, relPath), 'utf-8');
147
+ }
148
+ catch {
149
+ return {
150
+ ok: false,
151
+ result: {
152
+ met: false,
153
+ unverifiable: true,
154
+ evidence: [`scan-unreadable: ${relPath} could not be read — absence cannot be verified`],
155
+ },
156
+ };
157
+ }
158
+ for (const token of tokens) {
159
+ const index = content.indexOf(token);
160
+ if (index !== -1) {
161
+ const line = content.slice(0, index).split('\n').length;
162
+ contentHits.push(`\`${token}\`: still present at ${relPath}:${line}`);
163
+ }
164
+ }
165
+ }
166
+ return { ok: true, hits: contentHits };
167
+ }
168
+ async function scanPathHits(tokens, projectPath) {
169
+ const pathHits = [];
170
+ for (const token of tokens) {
171
+ if (!isPathShaped(token)) {
172
+ continue;
173
+ }
174
+ const entry = await projectEntryExists(projectPath, token);
175
+ if (entry.status === 'unverifiable') {
176
+ return {
177
+ ok: false,
178
+ result: { met: false, unverifiable: true, evidence: [entry.evidence] },
179
+ };
180
+ }
181
+ if (entry.status === 'present') {
182
+ pathHits.push(`\`${token}\`: still present as project entry ${token}`);
183
+ }
184
+ }
185
+ return { ok: true, hits: pathHits };
186
+ }
187
+ export async function checkTokensAbsent(tokens, projectPath, options) {
188
+ if (tokens.length === 0) {
189
+ return {
190
+ met: false,
191
+ unverifiable: true,
192
+ evidence: ['no tokens extracted — absence cannot be verified'],
193
+ };
194
+ }
195
+ const fileLimit = options?.fileLimit ?? NEGATIVE_SCAN_FILE_LIMIT;
196
+ let files;
197
+ try {
198
+ files = await glob([...NEGATIVE_TOKEN_SCOPE], {
199
+ cwd: projectPath,
200
+ nodir: true,
201
+ ignore: [...NEGATIVE_SCAN_IGNORE],
202
+ signal: options?.signal,
203
+ });
204
+ }
205
+ catch {
206
+ return {
207
+ met: false,
208
+ unverifiable: true,
209
+ evidence: [
210
+ 'scan-error: glob failed over the negative-token scope — absence cannot be verified',
211
+ ],
212
+ };
213
+ }
214
+ if (files.length > fileLimit) {
215
+ return {
216
+ met: false,
217
+ unverifiable: true,
218
+ evidence: [
219
+ `scan-truncated: ${files.length} files exceed the ${fileLimit}-file scan limit — absence cannot be verified`,
220
+ ],
221
+ };
222
+ }
223
+ const contentScan = await scanContentHits(files, tokens, projectPath, options?.signal);
224
+ if (!contentScan.ok) {
225
+ return contentScan.result;
226
+ }
227
+ const pathScan = await scanPathHits(tokens, projectPath);
228
+ if (!pathScan.ok) {
229
+ return pathScan.result;
230
+ }
231
+ const hits = [...contentScan.hits, ...pathScan.hits];
232
+ const met = hits.length === 0;
233
+ const evidence = met
234
+ ? tokens.map((token) => isPathShaped(token)
235
+ ? `\`${token}\`: absent — 0 matches in ${files.length} scanned files, and no project entry`
236
+ : `\`${token}\`: absent — 0 matches in ${files.length} scanned files`)
237
+ : hits;
238
+ return { met, unverifiable: false, evidence };
239
+ }
240
+ //# sourceMappingURL=negative-predicate.js.map
@@ -10,6 +10,7 @@ import { readEvidenceArtifacts, traceabilityRowHasCurrentCommandEvidence, } from
10
10
  import { normalizeCriterionText } from '../criterion-identity.js';
11
11
  import { isExecutableTestPath } from '../spec-format/executable-test-path.js';
12
12
  import { normalizeExecutableEvidence } from './executable-evidence.js';
13
+ import { classifyNegativePredicate, checkTokensAbsent } from './negative-predicate.js';
13
14
  /** A sanitized terminal adapter failure that cannot be mistaken for a failed test verdict. */
14
15
  export class ComplianceCommandTerminalError extends Error {
15
16
  code;
@@ -612,8 +613,22 @@ export async function runSpecCompliance(spec, projectPath, signal, canonicalProj
612
613
  }
613
614
  return `${technologyValue('technology-vitest-a9127f')} --reporter=json --run ${links.map((link) => link.path).join(' ')}`;
614
615
  });
615
- const scenarioResults = scenarios.map((scenario) => {
616
+ const scenarioResults = await Promise.all(scenarios.map(async (scenario) => {
616
617
  if (!scenario.tests?.length) {
618
+ const criterion = canonicalScenarioCriterion(scenario);
619
+ const negative = criterion
620
+ ? classifyNegativePredicate(criterion)
621
+ : { isNegative: false, tokens: [] };
622
+ if (negative.isNegative) {
623
+ const absence = await checkTokensAbsent(negative.tokens, projectPath, { signal });
624
+ return {
625
+ title: scenario.title,
626
+ verdict: absence.met ? 'pass' : 'missing',
627
+ evidence: absence.evidence,
628
+ linkVerdicts: [],
629
+ ...(absence.unverifiable ? { unverifiable: true } : {}),
630
+ };
631
+ }
617
632
  return {
618
633
  title: scenario.title,
619
634
  verdict: 'missing',
@@ -668,7 +683,7 @@ export async function runSpecCompliance(spec, projectPath, signal, canonicalProj
668
683
  linkVerdicts: verdicts,
669
684
  ...(unverifiable ? { unverifiable: true } : {}),
670
685
  };
671
- });
686
+ }));
672
687
  const perScenario = scenarioResults.map(({ linkVerdicts: _linkVerdicts, ...scenario }) => scenario);
673
688
  const passCount = perScenario.filter((scenario) => scenario.verdict === 'pass').length;
674
689
  const indeterminateCount = perScenario.filter((scenario) => scenario.verdict === 'indeterminate').length;
@@ -84,7 +84,6 @@ export declare class RuntimeSchemaAheadError extends Error {
84
84
  readonly code: 'RUNTIME_SCHEMA_AHEAD';
85
85
  constructor(storeSchema: number, supportedSchema: number);
86
86
  }
87
- /** A bounded (one connection), transactional SQLite runtime store. */
88
87
  export declare class RuntimeDatabase implements Disposable {
89
88
  readonly path: string;
90
89
  readonly schemaVersion = 5;
@@ -139,6 +138,7 @@ export declare class RuntimeDatabase implements Disposable {
139
138
  restartReceiptPublication(projectId: string, workspaceId: string, id: string, limits: ValidationReceiptCheckpointLimits): DurableJobRecord;
140
139
  restartJobWithPayload(projectId: string, workspaceId: string, id: string, payload: unknown): DurableJobRecord;
141
140
  cancelJob(projectId: string, workspaceId: string, id: string): DurableJobRecord;
141
+ private notRestartableError;
142
142
  private assertRestartCeiling;
143
143
  private freshRestartDeadline;
144
144
  private archiveCheckpointBeforeRestart;
@@ -109,6 +109,16 @@ function withFreshValidateDeadline(payload, deadlineAt) {
109
109
  return { ...payload, deadlineAt };
110
110
  }
111
111
  /** A bounded (one connection), transactional SQLite runtime store. */
112
+ const RESTART_NEXT_ACTION = {
113
+ absent: 'no job exists under this operation id; submit the work again with validate or package_handoff',
114
+ running: 'wait for the current attempt to finish, poll get_job with the same operationId, then restart_job once it leaves running',
115
+ accepted: 'the job is already queued; poll get_job with the same operationId instead of restarting',
116
+ checkpointed: 'the job is already queued from its checkpoint; poll get_job with the same operationId',
117
+ cancelled: 'the run was cancelled; resubmit it with validate or package_handoff',
118
+ failed: 'restart_job is the correct verb here; re-read the row with get_job and retry',
119
+ 'dead-letter': 'restart_job is the correct verb here; re-read the row with get_job and retry',
120
+ completed: 'the job already produced a result; read it with get_job, and only re-run validate if its inputs changed',
121
+ };
112
122
  export class RuntimeDatabase {
113
123
  path;
114
124
  schemaVersion = CURRENT_SCHEMA_VERSION;
@@ -609,7 +619,7 @@ export class RuntimeDatabase {
609
619
  const current = this.getJob(projectId, workspaceId, id);
610
620
  if (!current ||
611
621
  !['accepted', 'checkpointed', 'failed', 'dead-letter', 'cancelled', 'completed'].includes(current.state)) {
612
- throw new Error('[Planu] Job is not restartable');
622
+ throw this.notRestartableError('Job', id, current?.state ?? 'absent');
613
623
  }
614
624
  this.assertRestartCeiling(current, id);
615
625
  const { now, deadlineAt } = this.freshRestartDeadline();
@@ -639,7 +649,7 @@ export class RuntimeDatabase {
639
649
  !['failed', 'dead-letter'].includes(current.state) ||
640
650
  current.cancelRequested ||
641
651
  !parseValidationReceiptPendingCheckpoint(current.checkpoint, limits)) {
642
- throw new Error('[Planu] Job receipt publication is not restartable');
652
+ throw this.notRestartableError('Job receipt publication', id, current?.state ?? 'absent');
643
653
  }
644
654
  this.assertRestartCeiling(current, id);
645
655
  const { now, deadlineAt } = this.freshRestartDeadline();
@@ -710,6 +720,9 @@ export class RuntimeDatabase {
710
720
  .run(now, projectId, workspaceId, id);
711
721
  return requireJobRecord(this.getJob(projectId, workspaceId, id), id);
712
722
  }
723
+ notRestartableError(subject, id, state) {
724
+ return new Error(`[Planu] ${subject} ${id}: ${subject === 'Job' ? 'not restartable' : 'receipt publication is not restartable'} in state ${state}: ${RESTART_NEXT_ACTION[state]}`);
725
+ }
713
726
  assertRestartCeiling(current, id) {
714
727
  if (current.restarts >= current.maxAttempts) {
715
728
  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`);
@@ -21,6 +21,7 @@ import { extractFilesFromSpecBody, extractMarkerDeclaredPaths, } from '../engine
21
21
  import { buildCanonicalUnifiedSpecContent, containsUnresolvedContractPlaceholder, validateUnifiedSpecCandidate, } from '../engine/spec-format/unified-spec-builder.js';
22
22
  import { buildImplementationContractSection } from '../engine/implementation-contract/index.js';
23
23
  import { updateFrontmatterField } from '../engine/frontmatter-parser.js';
24
+ import { parseBddScenarios, PLACEHOLDER_WHEN_STEP_TEXT } from '../engine/spec-format/bdd-parser.js';
24
25
  import { resolveEnglishOnlySpecGate } from '../engine/spec-language/english-only.js';
25
26
  import { FallbackGenerator } from '../engine/spec-generator/index.js';
26
27
  import { analyzeProjectForSpec, getEmptyAutopilotResult, } from './create-spec/autopilot-analyzer.js';
@@ -1309,6 +1310,15 @@ async function prepareCreateSpecCandidate(initialParams, server) {
1309
1310
  // candidate.
1310
1311
  unifiedSpec = updateFrontmatterField(unifiedSpec, 'qualityWarnings', JSON.stringify(spec.qualityWarnings));
1311
1312
  }
1313
+ if (params.acFormat === 'bdd' && leanSpec.includes(PLACEHOLDER_WHEN_STEP_TEXT)) {
1314
+ const unparsedCriterion = criteria.find((criterion) => parseBddScenarios(criterion.text).length === 0)?.text ?? '';
1315
+ const placeholderFallbackWarning = `BDD parse fell back to placeholder steps — restate as a single GIVEN … WHEN … THEN … line: ` +
1316
+ `"${unparsedCriterion.slice(0, 120)}"`;
1317
+ spec.qualityWarnings = [
1318
+ ...new Set([...(spec.qualityWarnings ?? []), placeholderFallbackWarning]),
1319
+ ];
1320
+ unifiedSpec = updateFrontmatterField(unifiedSpec, 'qualityWarnings', JSON.stringify(spec.qualityWarnings));
1321
+ }
1312
1322
  const genericOutputGate = checkGenericSpecOutput(unifiedSpec);
1313
1323
  if (!genericOutputGate.passed) {
1314
1324
  return earlyPreparation({
@@ -1,7 +1,8 @@
1
1
  import type { ToolResult } from '../../types/index.js';
2
2
  export interface JobToolIdentityInput {
3
3
  operationId: string;
4
- projectId: string;
4
+ projectId?: string;
5
+ projectPath?: string;
5
6
  workspaceId?: string;
6
7
  }
7
8
  export declare function handleGetJob(input: JobToolIdentityInput): Promise<ToolResult>;
@@ -56,6 +56,19 @@ import { schedulePackageHandoffJobExecution } from '../../engine/execution/packa
56
56
  import { isValidationReceiptPendingIntent, parseValidationReceiptPendingCheckpoint, } from '../../types/durable-validation.js';
57
57
  import { redactText } from '../../security/redactor.js';
58
58
  import { getRuntimePolicy } from '../../engine/runtime-policy.js';
59
+ import { resolveProjectId } from '../resolve-project-id.js';
60
+ function jobIdentity(input) {
61
+ const derived = resolveProjectId({ projectPath: input.projectPath });
62
+ const passed = input.projectId?.trim();
63
+ if (derived && passed && derived !== passed) {
64
+ throw new Error(`[Planu] projectPath resolves to projectId ${derived} but projectId ${passed} was passed; pass only one.`);
65
+ }
66
+ const projectId = derived ?? passed;
67
+ if (!projectId) {
68
+ throw new Error('[Planu] Provide projectPath or projectId to identify the project.');
69
+ }
70
+ return { operationId: input.operationId, projectId, workspaceId: input.workspaceId };
71
+ }
59
72
  function result(payload) {
60
73
  return {
61
74
  content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],
@@ -101,7 +114,7 @@ export function handleGetJob(input) {
101
114
  const env_1 = { stack: [], error: void 0, hasError: false };
102
115
  try {
103
116
  const runtime = __addDisposableResource(env_1, new DurableJobRuntime(), false);
104
- const job = runtime.get(input);
117
+ const job = runtime.get(jobIdentity(input));
105
118
  const observation = publicJob(runtime, job);
106
119
  return Promise.resolve(result({ schemaVersion: 1, job: observation, cursor: publicJobCursor(observation) }));
107
120
  }
@@ -117,12 +130,13 @@ export function handleRestartJob(input) {
117
130
  const env_2 = { stack: [], error: void 0, hasError: false };
118
131
  try {
119
132
  const runtime = __addDisposableResource(env_2, new DurableJobRuntime(), false);
120
- const current = runtime.get(input);
133
+ const identity = jobIdentity(input);
134
+ const current = runtime.get(identity);
121
135
  const pending = parseValidationReceiptPendingCheckpoint(current.checkpoint, checkpointLimits());
122
136
  if (!pending && isValidationReceiptPendingIntent(current.checkpoint)) {
123
137
  throw new Error('[Planu] Invalid validation receipt checkpoint');
124
138
  }
125
- const job = pending ? runtime.restartReceiptPublication(input) : runtime.restart(input);
139
+ const job = pending ? runtime.restartReceiptPublication(identity) : runtime.restart(identity);
126
140
  rescheduleStalledJob(job);
127
141
  const observation = publicJob(runtime, job);
128
142
  return Promise.resolve(result({ schemaVersion: 1, job: observation, cursor: publicJobCursor(observation) }));
@@ -77,7 +77,20 @@ const coreToolsRegistry = [
77
77
  .min(1)
78
78
  .max(128)
79
79
  .describe('Job operation ID. Max 128 characters.'),
80
- projectId: z.string().trim().min(1).max(128).describe('Project ID hash. Max 128 characters.'),
80
+ projectId: z
81
+ .string()
82
+ .trim()
83
+ .min(1)
84
+ .max(128)
85
+ .optional()
86
+ .describe('Project ID hash. Optional when projectPath is given. Max 128 characters.'),
87
+ projectPath: z
88
+ .string()
89
+ .trim()
90
+ .min(1)
91
+ .max(4096)
92
+ .optional()
93
+ .describe('Absolute path to the project root; projectId is derived from it. Max 4096 characters.'),
81
94
  workspaceId: z
82
95
  .string()
83
96
  .trim()
@@ -106,7 +119,20 @@ const coreToolsRegistry = [
106
119
  .min(1)
107
120
  .max(128)
108
121
  .describe('Job operation ID. Max 128 characters.'),
109
- projectId: z.string().trim().min(1).max(128).describe('Project ID hash. Max 128 characters.'),
122
+ projectId: z
123
+ .string()
124
+ .trim()
125
+ .min(1)
126
+ .max(128)
127
+ .optional()
128
+ .describe('Project ID hash. Optional when projectPath is given. Max 128 characters.'),
129
+ projectPath: z
130
+ .string()
131
+ .trim()
132
+ .min(1)
133
+ .max(4096)
134
+ .optional()
135
+ .describe('Absolute path to the project root; projectId is derived from it. Max 4096 characters.'),
110
136
  workspaceId: z
111
137
  .string()
112
138
  .trim()
@@ -128,13 +128,20 @@ export async function checkLifecycleEvidenceTransitionGate(args) {
128
128
  : null;
129
129
  if (receiptResult && !receiptResult.ok) {
130
130
  const message = receiptResult.reason === 'stale-bindings'
131
- ? 'stale-bindings: validation inputs changed after the receipt was issued. Re-run validate, then retry done.'
131
+ ? staleBindingsIssueMessage(args.specId)
132
132
  : receiptResult.reason;
133
133
  return evidenceGateError({
134
134
  specId: args.specId,
135
135
  transition: args.transition,
136
136
  issues: [{ code: 'evidence_provenance_invalid', message }],
137
137
  requiredContractKinds: [],
138
+ nextAction: receiptResult.reason === 'stale-bindings'
139
+ ? {
140
+ tool: 'validate',
141
+ args: { specId: args.specId },
142
+ rationale: 'Re-run validate for a fresh sourceDigest, then package_handoff for a fresh contextHash, then retry done.',
143
+ }
144
+ : undefined,
138
145
  });
139
146
  }
140
147
  const result = await checkLifecycleEvidenceGate({
@@ -314,6 +321,9 @@ async function extractLifecycleGateCriteriaAndBody(spec, projectPath) {
314
321
  }
315
322
  return { criteria: await extractCriteria(spec), body: null };
316
323
  }
324
+ function staleBindingsIssueMessage(specId) {
325
+ return `stale-bindings: validation inputs changed after the receipt was issued, so the receipt's bound sourceDigest no longer matches the working tree. Re-run validate(specId=${specId}) for a fresh sourceDigest, then package_handoff(specId=${specId}) for a fresh contextHash, then retry done.`;
326
+ }
317
327
  function evidenceGateError(args) {
318
328
  return {
319
329
  content: [
@@ -327,6 +337,7 @@ function evidenceGateError(args) {
327
337
  issues: args.issues.length,
328
338
  firstIssue: args.issues[0]?.message,
329
339
  requiredContractKinds: args.requiredContractKinds.length,
340
+ nextActionTool: args.nextAction?.tool,
330
341
  fixHint: 'Add the missing evidence artifact to the external Planu project data handoff store, then retry the transition. Do not create JSON files under planu/specs/<spec>/.',
331
342
  }),
332
343
  },
@@ -341,6 +352,7 @@ function evidenceGateError(args) {
341
352
  transition: args.transition,
342
353
  issues: args.issues,
343
354
  requiredContractKinds: args.requiredContractKinds,
355
+ nextAction: args.nextAction,
344
356
  },
345
357
  fixHint: 'Add discovery.json, task-plan.json, traceability-matrix.json, and contract-validation-*.json to the external Planu handoff store as required for this transition. Spec folders remain spec.md-only.',
346
358
  },
@@ -209,7 +209,7 @@ export async function checkAmbiguityGate(spec, newStatus) {
209
209
  }
210
210
  const report = await scoreAmbiguityFromPath(spec.specPath);
211
211
  if (!report) {
212
- return gateUnavailableResult('AMBIGUITY_GATE_UNAVAILABLE', 'Ambiguity scoring failed.');
212
+ return gateUnavailableResult('AMBIGUITY_GATE_UNAVAILABLE', 'Ambiguity scoring failed.', readinessGateIdentity(spec));
213
213
  }
214
214
  if (report.score >= 70) {
215
215
  return null;
@@ -342,11 +342,11 @@ export async function checkReadinessGate(spec, newStatus, forceApprove, projectP
342
342
  ? `spec.md is missing at ${spec.specPath}. Recreate the spec via create_spec or restore spec.md from git/backup before retrying this transition.`
343
343
  : error instanceof Error
344
344
  ? error.message
345
- : 'spec.md could not be read');
345
+ : 'spec.md could not be read', readinessGateIdentity(spec, projectPath));
346
346
  }
347
347
  // Guard: mock environments return undefined; unreadable files return non-string
348
348
  if (typeof body !== 'string') {
349
- return readinessUnavailable('READINESS_SPEC_INVALID', 'spec.md did not return text content');
349
+ return readinessUnavailable('READINESS_SPEC_INVALID', 'spec.md did not return text content', readinessGateIdentity(spec, projectPath));
350
350
  }
351
351
  const languageValidation = validateEnglishOnlySpecText(body);
352
352
  if (!languageValidation.ok) {
@@ -440,7 +440,7 @@ export async function checkReadinessGate(spec, newStatus, forceApprove, projectP
440
440
  catch (error) {
441
441
  /* reliability-optional: READINESS_EVALUATION_FAILED — transition fails closed below */
442
442
  reportClassifiedDegradation('READINESS_EVALUATION_FAILED', error);
443
- return readinessUnavailable('READINESS_EVALUATION_FAILED', error instanceof Error ? error.message : 'readiness evaluation failed', structuralInterpolationWarnings);
443
+ return readinessUnavailable('READINESS_EVALUATION_FAILED', error instanceof Error ? error.message : 'readiness evaluation failed', readinessGateIdentity(spec, projectPath), structuralInterpolationWarnings);
444
444
  }
445
445
  const { score } = readiness;
446
446
  const blockers = [...readiness.issues.blockers];
@@ -579,15 +579,39 @@ export async function checkReadinessGate(spec, newStatus, forceApprove, projectP
579
579
  qualityWarnings: structuralInterpolationWarnings,
580
580
  };
581
581
  }
582
- function gateUnavailableResult(code, message) {
582
+ function gateBlockedText(message) {
583
+ return `${message} Transition blocked until the gate succeeds. Do not retry the spec-level transition until the originating condition is cleared.`;
584
+ }
585
+ function readinessGateIdentity(spec, projectPath) {
586
+ const identity = { specId: spec.id, projectId: spec.projectId };
587
+ return projectPath === undefined ? identity : { ...identity, projectPath };
588
+ }
589
+ function gateUnavailableResult(code, message, identity) {
590
+ const structuredContent = {
591
+ error: code,
592
+ message,
593
+ retryable: false,
594
+ externalGateBlocked: true,
595
+ originatingCondition: code,
596
+ nextAction: {
597
+ tool: 'check_readiness',
598
+ args: {
599
+ specId: identity.specId,
600
+ ...(identity.projectPath === undefined
601
+ ? { projectId: identity.projectId }
602
+ : { projectPath: identity.projectPath }),
603
+ },
604
+ rationale: `${message} Fix the originating condition outside the spec contract, then re-run check_readiness to confirm it cleared. Retrying update_status on the same spec will not clear it.`,
605
+ },
606
+ };
583
607
  return {
584
- content: [{ type: 'text', text: `${message} Transition blocked until the gate succeeds.` }],
608
+ content: [{ type: 'text', text: gateBlockedText(message) }],
585
609
  isError: true,
586
- structuredContent: { error: code, message, retryable: true },
610
+ structuredContent: structuredContent,
587
611
  };
588
612
  }
589
- function readinessUnavailable(code, message, qualityWarnings = []) {
590
- return { blockResult: gateUnavailableResult(code, message), qualityWarnings };
613
+ function readinessUnavailable(code, message, identity, qualityWarnings = []) {
614
+ return { blockResult: gateUnavailableResult(code, message, identity), qualityWarnings };
591
615
  }
592
616
  const CHALLENGE_RESOLUTION_INSTRUCTIONS = 'Add a "### Challenge Resolution" subsection to the spec\'s spec.md with one "- " bullet per unresolved finding, each bullet containing that finding\'s exact scenario text plus your mitigation, then re-run challenge_spec to re-derive the report.';
593
617
  /**
@@ -120,7 +120,19 @@ function computeIntegrationTimeoutMs() {
120
120
  function isBlastRadiusPassed(blastRadiusGate) {
121
121
  return blastRadiusGate.passed && blastRadiusGate.warningReason === null;
122
122
  }
123
- function blastRadiusIntegrationWarnings(blastRadiusGate) {
123
+ function blastRadiusWarnings(blastRadiusGate) {
124
+ if (blastRadiusGate.warningReason === 'stale-dist') {
125
+ return [
126
+ {
127
+ file: 'blast-radius',
128
+ line: 0,
129
+ severity: 'warning',
130
+ rule: 'stale-dist',
131
+ message: 'Blast radius gate could not run: dist/ build provenance is stale',
132
+ suggestion: 'Run pnpm build:ts and re-run validate.',
133
+ },
134
+ ];
135
+ }
124
136
  return blastRadiusGate.warningReason === null
125
137
  ? []
126
138
  : [
@@ -622,7 +634,7 @@ export async function executeValidate(args, server, onProgress) {
622
634
  suggestion: 'No importer regression coverage ran for this validate call.',
623
635
  });
624
636
  }
625
- output.qualityIssues.push(...blastRadiusIntegrationWarnings(blastRadiusGate));
637
+ output.qualityIssues.push(...blastRadiusWarnings(blastRadiusGate));
626
638
  output.qualityIssues.push(...strictAuditsQualityIssues(strictAuditsGate));
627
639
  // Auto-suggest corrective actions based on validation results
628
640
  // score is null when no criteria can be extracted — treat as 0 for comparisons.
@@ -327,6 +327,26 @@ export interface DeepCheckResult {
327
327
  expected: number;
328
328
  description: string;
329
329
  }
330
+ export interface TokenAbsenceResult {
331
+ met: boolean;
332
+ unverifiable: boolean;
333
+ evidence: string[];
334
+ }
335
+ export type ProjectEntryStatus = {
336
+ status: 'absent';
337
+ } | {
338
+ status: 'present';
339
+ } | {
340
+ status: 'unverifiable';
341
+ evidence: string;
342
+ };
343
+ export type TokenHitScan = {
344
+ ok: true;
345
+ hits: string[];
346
+ } | {
347
+ ok: false;
348
+ result: TokenAbsenceResult;
349
+ };
330
350
  export interface DeepCheckConfig {
331
351
  pattern: string;
332
352
  scope: string;
@@ -1,4 +1,4 @@
1
- import type { ToolResult } from '../index.js';
1
+ import type { ToolResult } from '../common/primitives.js';
2
2
  export type ToolHandler = (args: Record<string, unknown>, extra?: unknown) => Promise<ToolResult>;
3
3
  export interface StructuredErrorNextAction {
4
4
  tool: string;
@@ -5,6 +5,10 @@ export interface AcGapKeywordGroup {
5
5
  language: string;
6
6
  keywords: string[];
7
7
  }
8
+ export interface NegativePredicatePhraseGroup {
9
+ id: string;
10
+ phrases: string[];
11
+ }
8
12
  export interface CodeQualityThreshold {
9
13
  id: string;
10
14
  language: string;
@@ -2,6 +2,7 @@ import type { ModelTierUsed, SpecStatus, SpecType, SpecScope, SpecTarget, ToolRe
2
2
  import type { Actuals } from '../estimation.js';
3
3
  import type { GlobalConfig } from '../project/config-metrics.js';
4
4
  import type { ProjectKnowledge } from '../project.js';
5
+ import type { StructuredErrorNextAction } from '../errors/structured-error.js';
5
6
  import type { Spec, ChecklistCategory, SpecDiagram, SpecSplitSuggestion, ReconcileChange } from './core.js';
6
7
  export interface ReconciliationInvocationContext {
7
8
  surface: 'local-mcp' | 'http' | 'dashboard' | 'direct' | 'unknown';
@@ -121,6 +122,19 @@ export interface ReadinessGateOutput {
121
122
  /** Warnings collected when force-approved with score < 70. Empty otherwise. */
122
123
  qualityWarnings: string[];
123
124
  }
125
+ export interface GateUnavailableIdentity {
126
+ specId: string;
127
+ projectId: string;
128
+ projectPath?: string;
129
+ }
130
+ export interface ExternalGateBlockedContext {
131
+ error: string;
132
+ message: string;
133
+ retryable: false;
134
+ externalGateBlocked: true;
135
+ originatingCondition: string;
136
+ nextAction: StructuredErrorNextAction;
137
+ }
124
138
  /**
125
139
  * SPEC-780: Output from the format gate check in update_status(approved).
126
140
  * Mirrors ReadinessGateOutput so callers can merge qualityWarnings from both gates.
@@ -1,4 +1,5 @@
1
1
  import type { AbortableProcessOptions, AbortableProcessResult } from './abortable-process.js';
2
+ import type { BuildFreshnessResult } from './build-freshness.js';
2
3
  export declare const VALIDATION_EVIDENCE_SCHEMA_VERSION: '1.0.0';
3
4
  export type ValidationGateCapability = 'typecheck' | 'lint' | 'test-related' | 'test-full' | 'contract' | 'coverage' | 'migration' | 'fault-injection' | 'security' | 'native' | 'website' | 'reproducibility';
4
5
  export type ValidationEvidenceStatus = 'passed' | 'failed' | 'cancelled' | 'invalidated';
@@ -144,13 +145,14 @@ export interface BlastRadiusGateResult {
144
145
  timedOut: boolean;
145
146
  failures: BlastRadiusGateFailure[];
146
147
  integrationImporters: string[];
147
- warningReason: 'integration-importers-skipped' | null;
148
+ warningReason: 'integration-importers-skipped' | 'stale-dist' | null;
148
149
  }
149
150
  export interface RunBlastRadiusGateOptions {
150
151
  timeoutMs: number;
151
152
  integrationTimeoutMs?: number;
152
153
  signal?: AbortSignal;
153
154
  runProcess?: (command: string, args: string[], options: AbortableProcessOptions) => Promise<AbortableProcessResult>;
155
+ checkBuildFreshness?: (distRoot: string) => BuildFreshnessResult;
154
156
  }
155
157
  export type StrictAuditsSkipReason = 'no-strict-scripts' | 'deadline-exceeded';
156
158
  export interface StrictAuditsGateFinding {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@planu/cli",
3
- "version": "5.7.13",
3
+ "version": "5.7.14",
4
4
  "description": "Planu — MCP Server for Spec Driven Development. Cross-platform (Linux/macOS/Windows, x64/arm64).",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -83,6 +83,7 @@
83
83
  "audit:i18n": "bash scripts/audit-i18n.sh",
84
84
  "audit:hardcodes": "node scripts/check-hardcodes.mjs",
85
85
  "audit:mutation": "stryker run",
86
+ "audit:test-suite": "bash scripts/test-suite-audit.sh",
86
87
  "setup:protection": "bash scripts/setup-branch-protection.sh",
87
88
  "prepare": "husky || true",
88
89
  "prepublishOnly": "bash scripts/prepublish-guard.sh",
package/planu-plugin.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "dev.planu.cli",
3
3
  "displayName": "Planu — Spec Driven Development",
4
4
  "description": "Manage software specs, estimations, and autonomous SDD workflows. Language-agnostic MCP server for Claude Code.",
5
- "version": "5.7.13",
5
+ "version": "5.7.14",
6
6
  "icon": "assets/plugin/icon.svg",
7
7
  "command": ["npx", "@planu/cli@latest"],
8
8
  "packageName": "@planu/cli",