@planu/cli 5.7.11 → 5.7.13

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 (63) hide show
  1. package/CHANGELOG.md +43 -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/cli/commands/package-handoff.js +10 -3
  7. package/dist/config/registries/strict-audit-scripts.json +4 -0
  8. package/dist/config/runtime-policy.json +2 -1
  9. package/dist/engine/abortable-process-runner.js +1 -0
  10. package/dist/engine/bump-carrier-binding.d.ts +10 -0
  11. package/dist/engine/bump-carrier-binding.js +276 -0
  12. package/dist/engine/doctor/npm-cache-check.d.ts +10 -0
  13. package/dist/engine/doctor/npm-cache-check.js +109 -0
  14. package/dist/engine/ears-gate.d.ts +1 -0
  15. package/dist/engine/ears-gate.js +64 -2
  16. package/dist/engine/framework-detector.d.ts +1 -0
  17. package/dist/engine/framework-detector.js +1 -1
  18. package/dist/engine/handoff-artifacts/schemas.d.ts +22 -0
  19. package/dist/engine/handoff-artifacts/schemas.js +13 -1
  20. package/dist/engine/runtime-policy.js +4 -0
  21. package/dist/engine/source-quality-binding.d.ts +26 -0
  22. package/dist/engine/source-quality-binding.js +162 -0
  23. package/dist/engine/source-quality-receipt-reader.d.ts +3 -0
  24. package/dist/engine/source-quality-receipt-reader.js +51 -0
  25. package/dist/engine/spec-format/bdd-parser.js +7 -4
  26. package/dist/engine/spec-format/technical-md-populator.js +114 -3
  27. package/dist/engine/spec-format/unified-spec-builder.js +33 -6
  28. package/dist/engine/spec-grounding/contract.js +3 -1
  29. package/dist/engine/spec-grounding/grounding-entry-parser.js +1 -0
  30. package/dist/engine/validator/blast-radius-gate.d.ts +3 -0
  31. package/dist/engine/validator/blast-radius-gate.js +225 -0
  32. package/dist/engine/validator/spec-compliance-runner.d.ts +2 -0
  33. package/dist/engine/validator/spec-compliance-runner.js +78 -25
  34. package/dist/engine/validator/strict-audits-gate.d.ts +3 -0
  35. package/dist/engine/validator/strict-audits-gate.js +74 -0
  36. package/dist/engine/validator/validation-report-writer.d.ts +2 -0
  37. package/dist/engine/validator/validation-report-writer.js +72 -32
  38. package/dist/storage/runtime-db.js +7 -3
  39. package/dist/storage/spec-store.js +6 -2
  40. package/dist/tools/challenge-spec/scenarios-data.js +4 -3
  41. package/dist/tools/challenge-spec/scenarios-utils.d.ts +1 -0
  42. package/dist/tools/challenge-spec/scenarios-utils.js +47 -3
  43. package/dist/tools/register-spec-tools/core-spec-tools.js +5 -0
  44. package/dist/tools/update-status/batch.js +1 -0
  45. package/dist/tools/update-status/file-sync.d.ts +1 -1
  46. package/dist/tools/update-status/file-sync.js +4 -2
  47. package/dist/tools/update-status/index.js +4 -1
  48. package/dist/tools/update-status/transition-guard.d.ts +0 -1
  49. package/dist/tools/update-status/transition-guard.js +9 -5
  50. package/dist/tools/validate-lint.js +19 -0
  51. package/dist/tools/validate.js +111 -4
  52. package/dist/types/abortable-process.d.ts +1 -0
  53. package/dist/types/handoff-artifacts.d.ts +11 -1
  54. package/dist/types/installation.d.ts +10 -0
  55. package/dist/types/runtime-policy.d.ts +1 -0
  56. package/dist/types/spec-format.d.ts +10 -0
  57. package/dist/types/spec-grounding.d.ts +1 -1
  58. package/dist/types/validation-evidence.d.ts +51 -1
  59. package/package.json +2 -2
  60. package/planu-plugin.json +1 -1
  61. package/src/i18n/messages/en.json +1 -1
  62. package/src/i18n/messages/es.json +1 -1
  63. package/src/i18n/messages/pt.json +1 -1
@@ -10,8 +10,9 @@ export async function writeImplementationReviewReport(input) {
10
10
  conventionRegression: input.conventionRegression ?? false,
11
11
  specCompliance,
12
12
  minimalityReport: input.minimalityReport,
13
+ blastRadius: input.blastRadius,
13
14
  });
14
- const mergedGates = await preserveUnobservedGates(input, gates);
15
+ const { gates: mergedGates, preservedBlastRadius } = await preserveUnobservedGates(input, gates);
15
16
  const passed = mergedGates.every((gate) => gate.passed);
16
17
  const reviewer = {
17
18
  kind: 'automation',
@@ -19,45 +20,50 @@ export async function writeImplementationReviewReport(input) {
19
20
  verdict: passed ? 'approved' : 'changes-requested',
20
21
  };
21
22
  const reportCompliance = toValidationReportCompliance(specCompliance);
22
- const payload = {
23
- schema_version: '1.0.0',
23
+ const payload = buildValidationReportPayload({
24
24
  specId: input.specId,
25
25
  passed,
26
26
  gates: mergedGates,
27
27
  reviewer,
28
- specCompliance: reportCompliance,
28
+ reportCompliance,
29
29
  minimalityReport: input.minimalityReport,
30
- score: reportScore ?? undefined,
31
- completedAt: new Date().toISOString(),
32
- };
30
+ reportScore,
31
+ blastRadius: input.blastRadius,
32
+ preservedBlastRadius,
33
+ });
34
+ const persisted = await persistValidationReport(input.projectId, input.specId, payload);
35
+ return { ...persisted, reviewer, passed, gates: mergedGates, specCompliance: reportCompliance };
36
+ }
37
+ async function persistValidationReport(projectId, specId, payload) {
33
38
  try {
34
39
  const artifact = await appendArtifact({
35
- projectId: input.projectId,
36
- specId: input.specId,
40
+ projectId,
41
+ specId,
37
42
  kind: 'validation-report',
38
43
  payload,
39
44
  });
40
- return {
41
- written: true,
42
- path: artifact.path,
43
- sha: `sha256:${artifact.sha}`,
44
- reviewer,
45
- passed,
46
- gates: mergedGates,
47
- specCompliance: reportCompliance,
48
- };
45
+ return { written: true, path: artifact.path, sha: `sha256:${artifact.sha}` };
49
46
  }
50
47
  catch (err) {
51
- return {
52
- written: false,
53
- error: err instanceof Error ? err.message : String(err),
54
- reviewer,
55
- passed,
56
- gates: mergedGates,
57
- specCompliance: reportCompliance,
58
- };
48
+ return { written: false, error: err instanceof Error ? err.message : String(err) };
59
49
  }
60
50
  }
51
+ function buildValidationReportPayload(args) {
52
+ return {
53
+ schema_version: '1.0.0',
54
+ specId: args.specId,
55
+ passed: args.passed,
56
+ gates: args.gates,
57
+ reviewer: args.reviewer,
58
+ specCompliance: args.reportCompliance,
59
+ minimalityReport: args.minimalityReport,
60
+ score: args.reportScore ?? undefined,
61
+ completedAt: new Date().toISOString(),
62
+ blastRadius: args.blastRadius !== undefined
63
+ ? toValidationReportBlastRadius(args.blastRadius)
64
+ : args.preservedBlastRadius,
65
+ };
66
+ }
61
67
  function resolveExecutableValidationScore(score, specCompliance) {
62
68
  return specCompliance.perScenario.length > 0 ? specCompliance.dimensionScore : score;
63
69
  }
@@ -67,6 +73,7 @@ async function preserveUnobservedGates(input, nextGates) {
67
73
  ...(input.lintPassed !== undefined ? ['lint'] : []),
68
74
  ...(input.conventionRegression !== undefined ? ['convention-regression'] : []),
69
75
  ...(input.minimalityReport !== undefined ? ['minimal-implementation'] : []),
76
+ ...(input.blastRadius !== undefined ? ['blast-radius'] : []),
70
77
  ]);
71
78
  const existing = await readArtifact({
72
79
  projectId: input.projectId,
@@ -74,18 +81,23 @@ async function preserveUnobservedGates(input, nextGates) {
74
81
  kind: 'validation-report',
75
82
  }).catch(() => null);
76
83
  if (!existing?.ok) {
77
- return nextGates;
84
+ return { gates: nextGates };
78
85
  }
86
+ const preservedBlastRadius = input.blastRadius === undefined ? existing.payload.blastRadius : undefined;
79
87
  const preserved = existing.payload.gates.filter((gate) => currentGateNames.has(gate.name) &&
80
88
  !explicitlyObserved.has(gate.name) &&
81
89
  (gate.name === 'lint' ||
82
90
  gate.name === 'convention-regression' ||
83
- gate.name === 'minimal-implementation'));
91
+ gate.name === 'minimal-implementation' ||
92
+ gate.name === 'blast-radius'));
84
93
  if (preserved.length === 0) {
85
- return nextGates;
94
+ return { gates: nextGates, preservedBlastRadius };
86
95
  }
87
96
  const preservedByName = new Map(preserved.map((gate) => [gate.name, gate]));
88
- return nextGates.map((gate) => preservedByName.get(gate.name) ?? gate);
97
+ return {
98
+ gates: nextGates.map((gate) => preservedByName.get(gate.name) ?? gate),
99
+ preservedBlastRadius,
100
+ };
89
101
  }
90
102
  function buildGates(args) {
91
103
  return [
@@ -112,8 +124,34 @@ function buildGates(args) {
112
124
  },
113
125
  buildSpecComplianceGate(args.specCompliance),
114
126
  buildMinimalityGate(args.minimalityReport),
127
+ buildBlastRadiusGate(args.blastRadius),
115
128
  ];
116
129
  }
130
+ function buildBlastRadiusGate(result) {
131
+ if (result === undefined) {
132
+ return {
133
+ name: 'blast-radius',
134
+ passed: true,
135
+ reason: 'Blast radius result unavailable.',
136
+ };
137
+ }
138
+ return {
139
+ name: 'blast-radius',
140
+ passed: result.passed,
141
+ reason: result.passed
142
+ ? undefined
143
+ : `Blast radius gate failed: ${String(result.failures.length)} importer test failure(s).`,
144
+ };
145
+ }
146
+ function toValidationReportBlastRadius(result) {
147
+ return {
148
+ selectedFiles: result.selectedFiles.length,
149
+ passed: result.passed,
150
+ timedOut: result.timedOut,
151
+ ...(result.skipped !== null ? { skipped: result.skipped } : {}),
152
+ failures: result.failures,
153
+ };
154
+ }
117
155
  function buildMinimalityGate(report) {
118
156
  if (report?.enabled !== true) {
119
157
  return {
@@ -144,13 +182,15 @@ function buildSpecComplianceGate(result) {
144
182
  reason: `No executable scenarios declared (evidence source: ${result.evidenceSource ?? 'none'}) — add BDD criteria TEST: markers or frontmatter scenarios before done.${ignoredNote}`,
145
183
  };
146
184
  }
147
- const passed = result.dimensionScore === 100;
185
+ const passed = result.dimensionScore === 100 && result.runnerFailure === undefined;
148
186
  return {
149
187
  name: 'spec-compliance',
150
188
  passed,
151
189
  reason: passed
152
190
  ? ignoredNote.trim() || undefined
153
- : `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}`,
154
194
  };
155
195
  }
156
196
  function toValidationReportCompliance(result) {
@@ -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 { 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 = [/\b(cache|cached|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,6 +28,7 @@ export interface ChallengeCapabilities {
28
28
  numericInput: boolean;
29
29
  rollout: boolean;
30
30
  }
31
+ export declare function hasApplicationCacheEvidence(text: string): boolean;
31
32
  /** Boundary-aware, affirmative replacement for advisory substring checks. */
32
33
  export declare function contentMentions(content: string, keywords: string[]): boolean;
33
34
  export declare function detectChallengeCapabilities(spec: Spec, specContent: string): ChallengeCapabilities;
@@ -7,9 +7,7 @@ const CAPABILITY_SIGNALS = {
7
7
  /\bfetch(?:es|ing)?\s+(?:from\s+)?(?:an?\s+)?(?:endpoint|service|url)\b/i,
8
8
  ],
9
9
  database: [
10
- /\b(?:database|postgres(?:ql)?|mysql|sqlite|mongodb|dynamodb|supabase)\b/i,
11
10
  /\b(?:sql|nosql)\s+(?:query|statement|table|database)\b/i,
12
- /\b(?:database|persistence)\s+(?:query|schema|table|migration|transaction)\b/i,
13
11
  /\b(?:orm|prisma|drizzle|typeorm|sequelize)\b/i,
14
12
  ],
15
13
  authentication: [/\b(?:login|sign[ -]?in|password|jwt|oauth2?|session\s+auth)\b/i],
@@ -42,7 +40,12 @@ const CAPABILITY_SIGNALS = {
42
40
  /\b(?:state-changing|data\s+mutation|atomic\s+database\s+writes?)\b/i,
43
41
  /\b(?:transaction|atomic\s+writes?|update\s+(?:record|state)|modify\s+(?:record|state))\b/i,
44
42
  ],
45
- cache: [/\b(?:cache|caching|cached\s+(?:data|response)|redis)\b/i],
43
+ cache: [
44
+ /\bcach(?:e|es|ed|ing)\s+(?:the|responses|results|entries|data)\b/i,
45
+ /\bcache\s+invalidat(?:e|es|ed|ing|ion)\b/i,
46
+ /\b(?:responses|results|entries|data)\s+(?:are|is|were)\s+cached\b/i,
47
+ /\bredis\b/i,
48
+ ],
46
49
  duplicateOperation: [
47
50
  /\b(?:double[ -]?click|duplicate\s+(?:request|submission|operation|record)|idempoten)/i,
48
51
  ],
@@ -118,6 +121,45 @@ function hasProductAuthenticationEvidence(contract) {
118
121
  return (hasAffirmedMatch(contract, AUTHENTICATION_BARE_TOKEN_RE) &&
119
122
  !REGISTRY_AUTH_CONTEXT_RE.test(contract));
120
123
  }
124
+ const DATABASE_PRODUCT_TOKEN_RE = '(?:database|postgres(?:ql)?|mysql|sqlite|mongodb|dynamodb|supabase)';
125
+ const DATABASE_PERSISTENCE_VERB_RE = '(?:stor(?:e|es|ed|ing)|persist(?:s|ed|ing)?|writ(?:e|es|ing|ten)|read(?:s|ing)?|quer(?:y|ies|ying)|insert(?:s|ing|ed)?|updat(?:e|es|ing|ed)|delet(?:e|es|ing|ed)|migrat(?:e|es|ing|ed|ion|ions))';
126
+ const DATABASE_TEST_GUARD_RE = '(?:test|fixture|mock(?:s|ed|ing)?|stub(?:s|bed|bing)?)';
127
+ const DATABASE_PRODUCT_RE = new RegExp(`\\b${DATABASE_PRODUCT_TOKEN_RE}\\b`, 'i');
128
+ const DATABASE_DDL_VERB_RE = /\b(?:add|adds|added|adding)\b/i;
129
+ const DATABASE_DDL_CONTEXT_RE = /\b(?:migration|schema|column|table)\b/i;
130
+ const DATABASE_PERSISTENCE_ACTION_RE = new RegExp(`\\b${DATABASE_PERSISTENCE_VERB_RE}\\b(?:\\W+\\w+){0,4}?\\W+\\b${DATABASE_PRODUCT_TOKEN_RE}\\b|` +
131
+ `\\b${DATABASE_PRODUCT_TOKEN_RE}\\b(?:\\W+\\w+){0,4}?\\W+\\b${DATABASE_PERSISTENCE_VERB_RE}\\b`, 'i');
132
+ const DATABASE_TEST_CONTEXT_RE = new RegExp(`\\b${DATABASE_TEST_GUARD_RE}\\b(?:\\W+\\w+){0,6}?\\W+\\b(?:${DATABASE_PRODUCT_TOKEN_RE}|${DATABASE_PERSISTENCE_VERB_RE})\\b|` +
133
+ `\\b(?:${DATABASE_PRODUCT_TOKEN_RE}|${DATABASE_PERSISTENCE_VERB_RE})\\b(?:\\W+\\w+){0,6}?\\W+\\b${DATABASE_TEST_GUARD_RE}\\b`, 'i');
134
+ function hasDatabasePersistenceEvidenceInClause(clause) {
135
+ if (DATABASE_TEST_CONTEXT_RE.test(clause)) {
136
+ return false;
137
+ }
138
+ if (hasAffirmedMatch(clause, DATABASE_PERSISTENCE_ACTION_RE)) {
139
+ return true;
140
+ }
141
+ return (DATABASE_PRODUCT_RE.test(clause) &&
142
+ DATABASE_DDL_CONTEXT_RE.test(clause) &&
143
+ DATABASE_DDL_VERB_RE.test(clause));
144
+ }
145
+ function hasProductDatabaseEvidence(contract) {
146
+ if (hasAnyAffirmedMatch(contract, CAPABILITY_SIGNALS.database)) {
147
+ return true;
148
+ }
149
+ return contract.split(/[.;\n]/).some(hasDatabasePersistenceEvidenceInClause);
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
+ }
121
163
  const NETWORK_API_BARE_TOKEN_RE = /(?<!compiler\s)\bapi\b(?!\s+(?:compatibility|surface|package|type))/i;
122
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;
123
165
  function hasProductNetworkEvidence(contract) {
@@ -162,6 +204,8 @@ export function detectChallengeCapabilities(spec, specContent) {
162
204
  ]));
163
205
  capabilities.authentication = hasProductAuthenticationEvidence(contract);
164
206
  capabilities.networkApi = hasProductNetworkEvidence(contract);
207
+ capabilities.database = hasProductDatabaseEvidence(contract);
208
+ capabilities.cache = hasApplicationCacheEvidence(contract);
165
209
  return capabilities;
166
210
  }
167
211
  export function hasAnyChallengeCapability(capabilities, names) {
@@ -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
@@ -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) {
@@ -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;
@@ -132,7 +132,7 @@ function assertSpecBodyIntegrity(args) {
132
132
  }
133
133
  }
134
134
  const FROZEN_TERMINAL_STATUSES = ['done', 'discarded'];
135
- export async function syncSpecFiles(updatedSpec, _currentStatus, newStatus, projectPath, qualityWarnings = []) {
135
+ export async function syncSpecFiles(updatedSpec, _currentStatus, newStatus, projectPath, qualityWarnings = [], frozenTransitionReason) {
136
136
  let warning;
137
137
  let refreshedTitle;
138
138
  let transitionSpecPath;
@@ -171,7 +171,9 @@ export async function syncSpecFiles(updatedSpec, _currentStatus, newStatus, proj
171
171
  newStatus,
172
172
  specId: updatedSpec.id,
173
173
  });
174
- await atomicWriteFile(transitionSpecPath, updatedContent);
174
+ await atomicWriteFile(transitionSpecPath, updatedContent, ...(frozenTransitionReason !== undefined && frozenTransitionReason.trim().length >= 30
175
+ ? [{ forceEdit: { reason: frozenTransitionReason } }]
176
+ : []));
175
177
  // SPEC-544: Auto-stage spec.md after writing so it's included in the user's next commit
176
178
  // SPEC-575: Auto-commit staged planu/ docs (idempotent, safe-fail)
177
179
  // Commit message must reflect the actual transition — 'mark-done' is only
@@ -653,7 +653,10 @@ async function commitTransitionWithNarrowLock(args) {
653
653
  expectedSpec: freshSpec,
654
654
  });
655
655
  const updatedSpec = transitionRecord.spec;
656
- const syncResult = await syncSpecFiles(updatedSpec, args.originalStatus, args.newStatus, args.projectPath, args.qualityWarnings);
656
+ const frozenReasonArgs = isReverseTransition(args.originalStatus, args.newStatus)
657
+ ? [args.options.reason]
658
+ : [];
659
+ const syncResult = await syncSpecFiles(updatedSpec, args.originalStatus, args.newStatus, args.projectPath, args.qualityWarnings, ...frozenReasonArgs);
657
660
  if (!syncResult.warning) {
658
661
  if (syncResult.title) {
659
662
  updatedSpec.title = syncResult.title;
@@ -12,7 +12,6 @@ import type { Spec } from '../../types/spec/core.js';
12
12
  export declare const VALID_TRANSITIONS: Record<SpecStatus, SpecStatus[]>;
13
13
  /**
14
14
  * Allowed reverse transition pairs (from terminal state back to active).
15
- * Only these two pairs are supported. Any other reverse pair is rejected.
16
15
  */
17
16
  export declare const REVERSE_TRANSITIONS: (readonly [SpecStatus, SpecStatus])[];
18
17
  /**
@@ -27,7 +27,7 @@ export const VALID_TRANSITIONS = {
27
27
  review: ['draft', 'approved', 'discarded'],
28
28
  approved: ['draft', 'review', 'implementing', 'discarded'],
29
29
  implementing: ['approved', 'done', 'discarded'],
30
- done: ['implementing'], // SPEC-733: reverse transition with mandatory reason
30
+ done: ['implementing', 'discarded'], // SPEC-733: reverse transition with mandatory reason
31
31
  discarded: ['draft'], // SPEC-733: reverse transition with mandatory reason
32
32
  };
33
33
  // ---------------------------------------------------------------------------
@@ -35,12 +35,15 @@ export const VALID_TRANSITIONS = {
35
35
  // ---------------------------------------------------------------------------
36
36
  /**
37
37
  * Allowed reverse transition pairs (from terminal state back to active).
38
- * Only these two pairs are supported. Any other reverse pair is rejected.
39
38
  */
40
39
  export const REVERSE_TRANSITIONS = [
41
40
  ['done', 'implementing'],
41
+ ['done', 'discarded'],
42
42
  ['discarded', 'draft'],
43
43
  ];
44
+ function allowedReversePairs() {
45
+ return REVERSE_TRANSITIONS.map(([from, to]) => `${from}→${to}`).join(', ');
46
+ }
44
47
  /**
45
48
  * Returns true if the (from, to) pair is a whitelisted reverse transition.
46
49
  */
@@ -57,15 +60,15 @@ export function validateReverseTransition(input) {
57
60
  if (!isReverseTransition(from, to)) {
58
61
  return {
59
62
  ok: false,
60
- error: `Reverse transition ${from} → ${to} is not supported. Allowed: done→implementing, discarded→draft.`,
61
- fixHint: 'Only done→implementing and discarded→draft are supported reverse transitions.',
63
+ error: `Reverse transition ${from} → ${to} is not supported. Allowed: ${allowedReversePairs()}.`,
64
+ fixHint: `Only ${allowedReversePairs()} are supported reverse transitions.`,
62
65
  };
63
66
  }
64
67
  if (!reason || reason.trim().length < 30) {
65
68
  return {
66
69
  ok: false,
67
70
  error: `Reverse transition ${from} → ${to} requires reason (≥ 30 chars). Received: "${reason ?? ''}" (${String(reason?.trim().length ?? 0)} chars).`,
68
- fixHint: 'Reverse transitions require reason (>= 30 chars). Example: "Regression found in prod traced to AC#3 — reopening to fix."',
71
+ fixHint: `Reverse transitions (${allowedReversePairs()}) require reason (>= 30 chars). Example: "Regression found in prod traced to AC#3 — reopening to fix."`,
69
72
  };
70
73
  }
71
74
  return { ok: true };
@@ -107,6 +110,7 @@ export function checkTransition(currentStatus, newStatus) {
107
110
  text: ti('spec.invalidTransition', {
108
111
  from: currentStatus,
109
112
  to: newStatus,
113
+ valid: validNextStates.join(', '),
110
114
  }),
111
115
  },
112
116
  ],
@@ -4,6 +4,7 @@ import { formatLintFailureDiagnostics, resolveProjectCommandPlan, runProjectComm
4
4
  import { getToolExecutionSignal } from './safe-handler.js';
5
5
  import { VALIDATION_COMMANDS } from '../engine/validation-impact-planner.js';
6
6
  import { boundedEnvironmentDuration, getRuntimePolicy } from '../engine/runtime-policy.js';
7
+ import { readMatchingSourceQualityReceipt } from '../engine/source-quality-receipt-reader.js';
7
8
  /** Allowlist: alphanumerics, spaces, and safe shell chars. Rejects ; | $ ` & < > */
8
9
  const SAFE_COMMAND_RE = /^[\w\s./:@~=-]+$/;
9
10
  function isSafeCommand(cmd) {
@@ -80,6 +81,24 @@ export async function runLintCheck(projectPath, lintCommand, context = {}) {
80
81
  };
81
82
  }
82
83
  }
84
+ const sourceQualityMatch = readMatchingSourceQualityReceipt(projectPath, command);
85
+ if (sourceQualityMatch) {
86
+ const output = `(reused source-quality receipt ${sourceQualityMatch.key})`;
87
+ if (context.projectId) {
88
+ recordSuccessfulValidationEvidence({
89
+ projectId: context.projectId,
90
+ input: evidenceInput,
91
+ expectedKey,
92
+ producer: 'planu-validate',
93
+ durationMs: 0,
94
+ output,
95
+ reason: context.specId
96
+ ? `Lint reused the source-quality receipt while validating ${context.specId}.`
97
+ : 'Lint reused the source-quality receipt during canonical validation.',
98
+ });
99
+ }
100
+ return { passed: true, command, issueCount: 0, output };
101
+ }
83
102
  const timeoutMs = Math.min(lintCheckTimeoutMs(), context.maximumTimeoutMs ?? Number.MAX_SAFE_INTEGER);
84
103
  try {
85
104
  const startedAt = Date.now();