@planu/cli 5.7.12 → 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.
Files changed (62) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/.planu-build.json +1 -1
  3. package/dist/cli/commands/doctor.d.ts +2 -1
  4. package/dist/cli/commands/doctor.js +51 -1
  5. package/dist/cli/commands/install.js +14 -0
  6. package/dist/config/negative-predicate-phrases.json +33 -0
  7. package/dist/config/registries/strict-audit-scripts.json +4 -0
  8. package/dist/engine/doctor/npm-cache-check.d.ts +10 -0
  9. package/dist/engine/doctor/npm-cache-check.js +109 -0
  10. package/dist/engine/ears-gate.d.ts +1 -0
  11. package/dist/engine/ears-gate.js +64 -2
  12. package/dist/engine/framework-detector.d.ts +1 -0
  13. package/dist/engine/framework-detector.js +1 -1
  14. package/dist/engine/handoff-artifacts/schemas.d.ts +2 -0
  15. package/dist/engine/handoff-artifacts/schemas.js +1 -1
  16. package/dist/engine/spec-format/bdd-parser.d.ts +2 -0
  17. package/dist/engine/spec-format/bdd-parser.js +70 -4
  18. package/dist/engine/spec-grounding/contract.js +3 -1
  19. package/dist/engine/spec-grounding/grounding-entry-parser.js +1 -0
  20. package/dist/engine/validator/analyzer.d.ts +0 -9
  21. package/dist/engine/validator/analyzer.js +33 -9
  22. package/dist/engine/validator/blast-radius-gate.js +181 -10
  23. package/dist/engine/validator/deep-code-checker.js +2 -5
  24. package/dist/engine/validator/negative-predicate.d.ts +18 -0
  25. package/dist/engine/validator/negative-predicate.js +240 -0
  26. package/dist/engine/validator/spec-compliance-runner.d.ts +1 -0
  27. package/dist/engine/validator/spec-compliance-runner.js +91 -26
  28. package/dist/engine/validator/strict-audits-gate.d.ts +3 -0
  29. package/dist/engine/validator/strict-audits-gate.js +74 -0
  30. package/dist/engine/validator/validation-report-writer.js +4 -2
  31. package/dist/storage/runtime-db.d.ts +1 -1
  32. package/dist/storage/runtime-db.js +15 -2
  33. package/dist/tools/challenge-spec/scenarios-data.js +4 -3
  34. package/dist/tools/challenge-spec/scenarios-utils.d.ts +1 -2
  35. package/dist/tools/challenge-spec/scenarios-utils.js +13 -2
  36. package/dist/tools/create-spec.js +10 -0
  37. package/dist/tools/jobs/handlers.d.ts +2 -1
  38. package/dist/tools/jobs/handlers.js +17 -3
  39. package/dist/tools/register-spec-tools/core-spec-tools.js +5 -0
  40. package/dist/tools/tool-registry/core-tools.js +28 -2
  41. package/dist/tools/update-status/batch.js +1 -0
  42. package/dist/tools/update-status/evidence-gate.js +13 -1
  43. package/dist/tools/update-status/file-sync.d.ts +1 -1
  44. package/dist/tools/update-status/file-sync.js +4 -2
  45. package/dist/tools/update-status/index.js +4 -1
  46. package/dist/tools/update-status/transition-guard.d.ts +0 -1
  47. package/dist/tools/update-status/transition-guard.js +42 -14
  48. package/dist/tools/validate.js +79 -2
  49. package/dist/types/analysis.d.ts +20 -0
  50. package/dist/types/errors/structured-error.d.ts +1 -1
  51. package/dist/types/handoff-artifacts.d.ts +1 -1
  52. package/dist/types/installation.d.ts +10 -0
  53. package/dist/types/plugin-configs.d.ts +4 -0
  54. package/dist/types/spec/inputs.d.ts +14 -0
  55. package/dist/types/spec-format.d.ts +1 -0
  56. package/dist/types/spec-grounding.d.ts +1 -1
  57. package/dist/types/validation-evidence.d.ts +32 -1
  58. package/package.json +2 -1
  59. package/planu-plugin.json +1 -1
  60. package/src/i18n/messages/en.json +1 -1
  61. package/src/i18n/messages/es.json +1 -1
  62. package/src/i18n/messages/pt.json +1 -1
@@ -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;
@@ -210,6 +211,11 @@ export function parseFrontmatterScenarios(raw) {
210
211
  }
211
212
  return scenarios;
212
213
  }
214
+ function isAdapterFailure(adapter) {
215
+ return (adapter?.statuses.size === 0 &&
216
+ (adapter.detail.startsWith('runner failed') ||
217
+ adapter.detail.startsWith('unparseable runner output')));
218
+ }
213
219
  function validRelativePath(candidate) {
214
220
  if (candidate.trim() !== candidate ||
215
221
  candidate.length === 0 ||
@@ -254,17 +260,20 @@ async function matchPlaywrightLink(reportedPath, links, projectPath) {
254
260
  const candidates = links.filter((link) => link.path === reportedPath || link.path.endsWith(`/${reportedPath}`));
255
261
  return candidates.length === 1 ? (candidates[0] ?? null) : null;
256
262
  }
257
- function parseJsonOutput(stdout) {
258
- const jsonStart = stdout.indexOf('{');
259
- if (jsonStart === -1) {
260
- return null;
261
- }
262
- try {
263
- return JSON.parse(stdout.slice(jsonStart));
264
- }
265
- catch {
266
- return null;
263
+ const VITEST_REPORT_ANCHOR = '{"numTotalTestSuites';
264
+ export function parseJsonOutput(stdout) {
265
+ for (const start of [stdout.lastIndexOf(VITEST_REPORT_ANCHOR), stdout.indexOf('{')]) {
266
+ if (start === -1) {
267
+ continue;
268
+ }
269
+ try {
270
+ return JSON.parse(stdout.slice(start));
271
+ }
272
+ catch {
273
+ continue;
274
+ }
267
275
  }
276
+ return null;
268
277
  }
269
278
  function vitestFilePath(result) {
270
279
  for (const candidate of [result.testFilePath, result.name, result.filepath, result.filePath]) {
@@ -290,9 +299,14 @@ function throwForTerminalProcessFailure(result) {
290
299
  throw new ComplianceCommandTerminalError('COMPLIANCE_COMMAND_TIMED_OUT');
291
300
  }
292
301
  }
302
+ function isVitestReport(report) {
303
+ return (typeof report === 'object' &&
304
+ report !== null &&
305
+ Array.isArray(report.testResults));
306
+ }
293
307
  async function runVitestAdapter(links, projectPath, signal) {
294
308
  const statuses = new Map();
295
- const result = await runAbortableProcess('pnpm', [
309
+ const runVitestOnce = () => runAbortableProcess('pnpm', [
296
310
  'exec',
297
311
  technologyValue('technology-vitest-a9127f'),
298
312
  '--reporter=json',
@@ -304,15 +318,26 @@ async function runVitestAdapter(links, projectPath, signal) {
304
318
  maxBufferBytes: 64 * 1024 * 1024,
305
319
  signal,
306
320
  });
307
- throwForTerminalProcessFailure(result);
308
- if (result.error) {
309
- return { statuses, detail: 'runner failed' };
310
- }
311
- const report = parseJsonOutput(result.stdout);
312
- if (!report || !Array.isArray(report.testResults)) {
313
- return { statuses, detail: 'unparseable runner output' };
321
+ const first = await runVitestOnce();
322
+ throwForTerminalProcessFailure(first);
323
+ const firstReport = first.error ? null : parseJsonOutput(first.stdout);
324
+ const attempt = isVitestReport(firstReport)
325
+ ? { result: first, report: firstReport }
326
+ : await (async () => {
327
+ const second = await runVitestOnce();
328
+ throwForTerminalProcessFailure(second);
329
+ const secondReport = second.error ? null : parseJsonOutput(second.stdout);
330
+ return { result: second, report: isVitestReport(secondReport) ? secondReport : null };
331
+ })();
332
+ if (attempt.report === null) {
333
+ return {
334
+ statuses,
335
+ detail: attempt.result.error
336
+ ? 'runner failed (retried once)'
337
+ : 'unparseable runner output (retried once)',
338
+ };
314
339
  }
315
- for (const testResult of report.testResults) {
340
+ for (const testResult of attempt.report.testResults) {
316
341
  const reportedPath = vitestFilePath(testResult);
317
342
  if (!reportedPath || !Array.isArray(testResult.assertionResults)) {
318
343
  continue;
@@ -588,12 +613,27 @@ export async function runSpecCompliance(spec, projectPath, signal, canonicalProj
588
613
  }
589
614
  return `${technologyValue('technology-vitest-a9127f')} --reporter=json --run ${links.map((link) => link.path).join(' ')}`;
590
615
  });
591
- const perScenario = scenarios.map((scenario) => {
616
+ const scenarioResults = await Promise.all(scenarios.map(async (scenario) => {
592
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
+ }
593
632
  return {
594
633
  title: scenario.title,
595
634
  verdict: 'missing',
596
635
  evidence: ['No test links — scenario has no tests array'],
636
+ linkVerdicts: [],
597
637
  };
598
638
  }
599
639
  const evidence = [];
@@ -614,34 +654,59 @@ export async function runSpecCompliance(spec, projectPath, signal, canonicalProj
614
654
  evidence.push(`${source.path || '(missing path)'}: ${link?.error ?? 'malformed test link'}`);
615
655
  return { verdict: 'missing', unverifiable: true };
616
656
  }
657
+ const groupResult = statusByGroup.get(groupKey(link));
658
+ if (isAdapterFailure(groupResult)) {
659
+ evidence.push(`${link.path}: runner reported ${groupResult.detail}`);
660
+ return { verdict: 'indeterminate', unverifiable: true };
661
+ }
617
662
  const adapter = statusByGroup.get(groupKey(link));
618
663
  const verdict = adapter?.statuses.get(link.path) ?? 'missing';
619
664
  evidence.push(`${link.path}: ${verdict === 'pass' ? 'passed' : verdict === 'fail' ? 'failed' : `not found in ${adapter?.detail ?? 'runner output'}`}`);
620
665
  return { verdict, unverifiable: false };
621
666
  });
622
667
  const verdicts = linkResults.map((entry) => entry.verdict);
623
- const unverifiable = linkResults.some((entry) => entry.unverifiable);
668
+ const hasFail = verdicts.some((item) => item === 'fail');
669
+ const hasMissing = verdicts.some((item) => item === 'missing');
624
670
  const verdict = verdicts.every((item) => item === 'pass')
625
671
  ? 'pass'
626
- : verdicts.some((item) => item === 'missing')
627
- ? 'missing'
628
- : 'fail';
672
+ : !hasFail && !hasMissing
673
+ ? 'indeterminate'
674
+ : hasMissing
675
+ ? 'missing'
676
+ : 'fail';
677
+ const unverifiable = verdict === 'indeterminate' ||
678
+ linkResults.some((entry) => entry.verdict === 'missing' && entry.unverifiable);
629
679
  return {
630
680
  title: scenario.title,
631
681
  verdict,
632
682
  evidence,
683
+ linkVerdicts: verdicts,
633
684
  ...(unverifiable ? { unverifiable: true } : {}),
634
685
  };
635
- });
686
+ }));
687
+ const perScenario = scenarioResults.map(({ linkVerdicts: _linkVerdicts, ...scenario }) => scenario);
636
688
  const passCount = perScenario.filter((scenario) => scenario.verdict === 'pass').length;
689
+ const indeterminateCount = perScenario.filter((scenario) => scenario.verdict === 'indeterminate').length;
690
+ const scoredCount = scenarios.length - indeterminateCount;
691
+ const failedAdapters = [...statusByGroup.values()].filter(isAdapterFailure);
692
+ const affectedScenarios = scenarioResults.filter((scenario) => scenario.linkVerdicts.some((verdict) => verdict === 'indeterminate')).length;
637
693
  return {
638
- dimensionScore: Math.round((passCount / scenarios.length) * 100),
694
+ dimensionScore: scoredCount > 0 ? Math.round((passCount / scoredCount) * 100) : 0,
639
695
  perScenario,
640
696
  command: commands.join(' && ') ||
641
697
  `${technologyValue('technology-vitest-a9127f')} --reporter=json --run (no test files linked)`,
642
698
  evidenceSource: executableEvidence.source,
643
699
  ignoredCriteriaTitles: executableEvidence.ignoredCriteriaTitles,
644
700
  doneDriftFindings,
701
+ ...(failedAdapters.length > 0
702
+ ? {
703
+ runnerFailure: {
704
+ kind: 'runner-output-unparseable',
705
+ detail: failedAdapters[0]?.detail ?? 'unparseable runner output',
706
+ indeterminateScenarios: affectedScenarios,
707
+ },
708
+ }
709
+ : {}),
645
710
  };
646
711
  }
647
712
  export function findScenariosWithoutTests(raw) {
@@ -0,0 +1,3 @@
1
+ import type { RunStrictAuditsGateOptions, StrictAuditsGateResult } from '../../types/validation-evidence.js';
2
+ export declare function runStrictAuditsGate(projectPath: string, options: RunStrictAuditsGateOptions): Promise<StrictAuditsGateResult>;
3
+ //# sourceMappingURL=strict-audits-gate.d.ts.map
@@ -0,0 +1,74 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { runAbortableProcess } from '../abortable-process-runner.js';
4
+ import { pmRunner } from '../framework-detector.js';
5
+ import { resolveProjectCommandPlan } from '../project-command-runtime.js';
6
+ import { remainingExecutionMs } from '../execution/context.js';
7
+ import strictAuditScripts from '../../config/registries/strict-audit-scripts.json' with { type: 'json' };
8
+ const REGISTRY = strictAuditScripts;
9
+ const MAX_FINDING_LINES = 20;
10
+ function fallbackFindingLine(script, result) {
11
+ const signal = result.signal !== null ? ` (signal ${result.signal})` : '';
12
+ const error = result.error !== undefined ? `: ${result.error.message}` : '';
13
+ return `${script} exited with status ${String(result.status)}${signal}${error}`;
14
+ }
15
+ function findingsForFailure(script, result) {
16
+ const lines = `${result.stdout}\n${result.stderr}`
17
+ .split('\n')
18
+ .map((line) => line.trim())
19
+ .filter((line) => line.length > 0)
20
+ .slice(0, MAX_FINDING_LINES);
21
+ if (lines.length === 0) {
22
+ return [{ script, line: fallbackFindingLine(script, result) }];
23
+ }
24
+ return lines.map((line) => ({ script, line }));
25
+ }
26
+ function noStrictScriptsResult() {
27
+ return { skipped: 'no-strict-scripts', executedScripts: [], passed: true, findings: [] };
28
+ }
29
+ function deadlineExceededResult(executedScripts, findings) {
30
+ return { skipped: 'deadline-exceeded', executedScripts, passed: false, findings };
31
+ }
32
+ export async function runStrictAuditsGate(projectPath, options) {
33
+ let pkg;
34
+ try {
35
+ const raw = readFileSync(join(projectPath, 'package.json'), 'utf-8');
36
+ pkg = JSON.parse(raw);
37
+ }
38
+ catch {
39
+ return noStrictScriptsResult();
40
+ }
41
+ const scripts = pkg.scripts ?? {};
42
+ const declared = REGISTRY.scripts.filter((script) => typeof scripts[script] === 'string');
43
+ if (declared.length === 0) {
44
+ return noStrictScriptsResult();
45
+ }
46
+ const packageManagerName = typeof pkg.packageManager === 'string' ? (pkg.packageManager.split('@')[0] ?? null) : null;
47
+ const runner = pmRunner(packageManagerName);
48
+ const runProcess = options.runProcess ?? runAbortableProcess;
49
+ const deadlineAt = Date.now() + options.timeoutMs;
50
+ const executedScripts = [];
51
+ const findings = [];
52
+ for (const script of declared) {
53
+ const budgetMs = Math.min(deadlineAt - Date.now(), remainingExecutionMs());
54
+ if (budgetMs <= 0) {
55
+ return deadlineExceededResult(executedScripts, findings);
56
+ }
57
+ const plan = resolveProjectCommandPlan(projectPath, `${runner} run ${script}`);
58
+ const result = await runProcess(plan.executable, plan.args, {
59
+ cwd: projectPath,
60
+ timeoutMs: budgetMs,
61
+ maxBufferBytes: 8 * 1024 * 1024,
62
+ signal: options.signal,
63
+ });
64
+ executedScripts.push(script);
65
+ if (result.timedOut || result.aborted) {
66
+ return deadlineExceededResult(executedScripts, findings);
67
+ }
68
+ if (result.error !== undefined || result.status !== 0) {
69
+ findings.push(...findingsForFailure(script, result));
70
+ }
71
+ }
72
+ return { skipped: null, executedScripts, passed: findings.length === 0, findings };
73
+ }
74
+ //# sourceMappingURL=strict-audits-gate.js.map
@@ -182,13 +182,15 @@ function buildSpecComplianceGate(result) {
182
182
  reason: `No executable scenarios declared (evidence source: ${result.evidenceSource ?? 'none'}) — add BDD criteria TEST: markers or frontmatter scenarios before done.${ignoredNote}`,
183
183
  };
184
184
  }
185
- const passed = result.dimensionScore === 100;
185
+ const passed = result.dimensionScore === 100 && result.runnerFailure === undefined;
186
186
  return {
187
187
  name: 'spec-compliance',
188
188
  passed,
189
189
  reason: passed
190
190
  ? ignoredNote.trim() || undefined
191
- : `Expected all executable scenarios to pass, got ${String(result.dimensionScore)}.${ignoredNote}`,
191
+ : result.runnerFailure
192
+ ? `Test runner output was unusable (${result.runnerFailure.detail}); ${String(result.runnerFailure.indeterminateScenarios)} scenario(s) are indeterminate — re-run validate.${ignoredNote}`
193
+ : `Expected all executable scenarios to pass, got ${String(result.dimensionScore)}.${ignoredNote}`,
192
194
  };
193
195
  }
194
196
  function toValidationReportCompliance(result) {
@@ -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`);
@@ -1,5 +1,5 @@
1
1
  // tools/challenge-spec/scenarios-data.ts — Data consistency and partial write scenarios
2
- import { CACHE_ACTION_SIGNALS, contentMentions, hasAnyAffirmedMatch } from './scenarios-utils.js';
2
+ import { contentMentions, hasAnyAffirmedMatch, hasApplicationCacheEvidence, } 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 = [...CACHE_ACTION_SIGNALS, /\b(?:real-time|realtime|websocket|stale data)\b/i];
12
+ const CACHE_FRESHNESS_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,
@@ -40,7 +40,8 @@ export function generateDataConsistencyScenarios(_spec, content, _knowledge) {
40
40
  });
41
41
  }
42
42
  // Stale data
43
- if (hasAnyAffirmedMatch(content, CACHE_SIGNALS)) {
43
+ if (hasApplicationCacheEvidence(content) ||
44
+ hasAnyAffirmedMatch(content, CACHE_FRESHNESS_SIGNALS)) {
44
45
  scenarios.push({
45
46
  scenario: 'Stale data served from cache after underlying data changes',
46
47
  probability: 'high',
@@ -28,8 +28,7 @@ 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
+ export declare function hasApplicationCacheEvidence(text: string): boolean;
33
32
  /** Boundary-aware, affirmative replacement for advisory substring checks. */
34
33
  export declare function contentMentions(content: string, keywords: string[]): boolean;
35
34
  export declare function detectChallengeCapabilities(spec: Spec, specContent: string): ChallengeCapabilities;
@@ -107,8 +107,6 @@ const CAPABILITY_SIGNALS = {
107
107
  /\bdeployment\s+strategy\b/i,
108
108
  ],
109
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;
112
110
  const AUTHENTICATION_BARE_TOKEN_RE = /\bauth(?:entication|enticate)?\b/i;
113
111
  // A bare "auth" token next to registry/package-manager vocabulary describes a
114
112
  // dependency-registry failure, not a product authentication contract, in either
@@ -150,6 +148,18 @@ function hasProductDatabaseEvidence(contract) {
150
148
  }
151
149
  return contract.split(/[.;\n]/).some(hasDatabasePersistenceEvidenceInClause);
152
150
  }
151
+ const CLAUSE_BOUNDARY_RE = /[;\n]|\.(?=\s|$)/;
152
+ const PACKAGE_MANAGER_CACHE_TOKEN_RE = /\b(?:npm|npx|pnpm|yarn|bun|pip|cargo|composer|brew|homebrew|gradle|maven)\b|_cacache|node_modules\/\.cache/i;
153
+ const APPLICATION_CACHE_CONTRACT_RE = /\b(?:invalidat(?:e|es|ed|ing|ion)|stale|ttl|expir(?:e|es|ed|ing|ation|y)|evict(?:s|ed|ing|ion)?|memoi[sz]\w*|redis|memcached|freshness)\b/i;
154
+ function isPackageManagerCacheClause(clause) {
155
+ return PACKAGE_MANAGER_CACHE_TOKEN_RE.test(clause) && !APPLICATION_CACHE_CONTRACT_RE.test(clause);
156
+ }
157
+ export function hasApplicationCacheEvidence(text) {
158
+ return text
159
+ .split(CLAUSE_BOUNDARY_RE)
160
+ .some((clause) => !isPackageManagerCacheClause(clause) &&
161
+ hasAnyAffirmedMatch(clause, CAPABILITY_SIGNALS.cache));
162
+ }
153
163
  const NETWORK_API_BARE_TOKEN_RE = /(?<!compiler\s)\bapi\b(?!\s+(?:compatibility|surface|package|type))/i;
154
164
  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;
155
165
  function hasProductNetworkEvidence(contract) {
@@ -195,6 +205,7 @@ export function detectChallengeCapabilities(spec, specContent) {
195
205
  capabilities.authentication = hasProductAuthenticationEvidence(contract);
196
206
  capabilities.networkApi = hasProductNetworkEvidence(contract);
197
207
  capabilities.database = hasProductDatabaseEvidence(contract);
208
+ capabilities.cache = hasApplicationCacheEvidence(contract);
198
209
  return capabilities;
199
210
  }
200
211
  export function hasAnyChallengeCapability(capabilities, names) {
@@ -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) }));
@@ -459,6 +459,11 @@ export function registerCoreSpecTools(server) {
459
459
  .max(10_000)
460
460
  .optional()
461
461
  .describe('Optional notes for each transition. Max 10000 characters.'),
462
+ reason: z
463
+ .string()
464
+ .max(2000)
465
+ .optional()
466
+ .describe('Must be ≥30 and <=2000 chars. Forwarded verbatim to every per-spec transition; required by reverse transitions (discarded→draft, done→implementing).'),
462
467
  evidence: z
463
468
  .record(z.string(), z.object({
464
469
  modelTierUsed: z
@@ -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()
@@ -120,6 +120,7 @@ export async function handleUpdateStatusBatch(input) {
120
120
  projectId: resolved.projectId,
121
121
  projectPath: resolved.projectPath,
122
122
  reviewNotes: input.reviewNotes,
123
+ reason: input.reason,
123
124
  });
124
125
  const message = firstText(result);
125
126
  if (result.isError === true) {
@@ -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
  },
@@ -10,7 +10,7 @@ export interface FrontmatterSyncWarning {
10
10
  specPath: string | null;
11
11
  reason: string;
12
12
  }
13
- export declare function syncSpecFiles(updatedSpec: Spec, _currentStatus: SpecStatus, newStatus: SpecStatus, projectPath?: string, qualityWarnings?: readonly string[]): Promise<{
13
+ export declare function syncSpecFiles(updatedSpec: Spec, _currentStatus: SpecStatus, newStatus: SpecStatus, projectPath?: string, qualityWarnings?: readonly string[], frozenTransitionReason?: string): Promise<{
14
14
  warning?: FrontmatterSyncWarning;
15
15
  title?: string;
16
16
  driftReconciled?: boolean;