@planu/cli 6.0.0 → 6.0.1

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 (74) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/.planu-build.json +1 -1
  3. package/dist/cli/commands/job.js +7 -1
  4. package/dist/cli/router.js +24 -5
  5. package/dist/config/official-sdd-tools.d.ts +0 -1
  6. package/dist/config/official-sdd-tools.js +0 -3
  7. package/dist/core/spec-validator.js +1 -1
  8. package/dist/engine/coach/i18n.d.ts +1 -1
  9. package/dist/engine/coach/i18n.js +2 -2
  10. package/dist/engine/convention-scanner/codebase-scanner.js +140 -8
  11. package/dist/engine/conventions-ttl.d.ts +0 -2
  12. package/dist/engine/conventions-ttl.js +1 -1
  13. package/dist/engine/evidence-gates/artifact-reader.d.ts +0 -2
  14. package/dist/engine/evidence-gates/artifact-reader.js +0 -2
  15. package/dist/engine/execution/package-handoff-job-executor.d.ts +1 -1
  16. package/dist/engine/execution/package-handoff-job-executor.js +42 -13
  17. package/dist/engine/execution/startup-recovery.d.ts +3 -0
  18. package/dist/engine/execution/startup-recovery.js +15 -0
  19. package/dist/engine/execution/validate-job-executor.d.ts +1 -1
  20. package/dist/engine/execution/validate-job-executor.js +23 -3
  21. package/dist/engine/handoff-packager.d.ts +2 -0
  22. package/dist/engine/handoff-packager.js +25 -9
  23. package/dist/engine/network-policy.js +31 -0
  24. package/dist/engine/test-selection/policy.js +1 -1
  25. package/dist/engine/validation-evidence-ledger.js +8 -37
  26. package/dist/engine/validation-impact-planner.d.ts +1 -3
  27. package/dist/engine/validation-impact-planner.js +2 -18
  28. package/dist/engine/validator/analyzer.js +0 -1
  29. package/dist/engine/validator/reliability-gate.js +6 -1
  30. package/dist/index.js +3 -11
  31. package/dist/security/adapters/local-file.js +8 -1
  32. package/dist/security/secret-provider.js +0 -2
  33. package/dist/storage/migrations/sdd-core-v6.js +101 -23
  34. package/dist/storage/project-identity.js +18 -2
  35. package/dist/tools/check-readiness.js +45 -35
  36. package/dist/tools/create-spec.js +14 -16
  37. package/dist/tools/init-project/agents-md-writer.js +0 -3
  38. package/dist/tools/package-handoff.js +19 -16
  39. package/dist/tools/update-status/approval-gates.d.ts +1 -1
  40. package/dist/tools/update-status/approval-gates.js +28 -5
  41. package/dist/tools/update-status/evidence-payload.d.ts +0 -2
  42. package/dist/tools/update-status/index.js +18 -8
  43. package/dist/tools/update-status/transition-guard.d.ts +1 -1
  44. package/dist/tools/update-status/transition-guard.js +18 -2
  45. package/dist/tools/validate.js +29 -7
  46. package/dist/types/common/learning.d.ts +0 -17
  47. package/dist/types/durable-job.d.ts +15 -1
  48. package/dist/types/index.d.ts +0 -3
  49. package/dist/types/index.js +0 -3
  50. package/dist/types/living-spec/annotations.d.ts +0 -30
  51. package/dist/types/living-spec/annotations.js +14 -0
  52. package/dist/types/living-spec.d.ts +0 -1
  53. package/dist/types/living-spec.js +0 -1
  54. package/dist/types/project/core.d.ts +0 -2
  55. package/dist/types/project/planu-config.d.ts +0 -1
  56. package/dist/types/readiness.d.ts +2 -0
  57. package/dist/types/security.d.ts +1 -1
  58. package/dist/types/spec-quality.d.ts +0 -20
  59. package/dist/types/timing.d.ts +0 -6
  60. package/dist/types/validation-evidence.d.ts +2 -2
  61. package/dist/types/validation.d.ts +2 -0
  62. package/package.json +4 -4
  63. package/scripts/check-reliability-policies.mjs +504 -0
  64. package/dist/engine/timing/structured-log.d.ts +0 -10
  65. package/dist/engine/timing/structured-log.js +0 -36
  66. package/dist/types/analysis-detection.d.ts +0 -14
  67. package/dist/types/analysis-detection.js +0 -5
  68. package/dist/types/lessons.d.ts +0 -28
  69. package/dist/types/lessons.js +0 -3
  70. package/dist/types/living-spec/dashboard-and-sync.d.ts +0 -82
  71. package/dist/types/living-spec/dashboard-and-sync.js +0 -3
  72. package/dist/types/vector-store.d.ts +0 -46
  73. package/dist/types/vector-store.js +0 -21
  74. package/planu-plugin.json +0 -35
@@ -4,6 +4,7 @@ import { isAbsolute } from 'node:path';
4
4
  import { specStore } from '../storage/index.js';
5
5
  import { resolveVerifiedSpecPath } from '../storage/project-identity.js';
6
6
  import { buildCheckReadinessSummary } from '../engine/human-summary.js';
7
+ import { validateHandoffOwnership } from '../engine/handoff-packager.js';
7
8
  // eslint-disable-next-line no-restricted-imports -- grandfathered layer violation, remediation SPEC-1661 SPEC-1662 SPEC-1663
8
9
  import { validateSpecFormat } from '../core/spec-validator.js';
9
10
  import { parseFrontmatter } from '../engine/frontmatter-parser.js';
@@ -49,35 +50,22 @@ async function synthesizeSpecFromDiscoveredPath(specId, discoveredPath) {
49
50
  const raw = await readFile(discoveredPath, 'utf-8');
50
51
  const { metadata } = parseFrontmatter(raw);
51
52
  return {
52
- id: specId,
53
- specPath: discoveredPath,
54
- difficulty: asDifficulty(metadata.difficulty) ?? 3,
55
- tags: asStringTags(metadata.tags),
56
- dependencies: [],
57
- scope: asSpecScope(metadata.scope) ?? 'feature',
58
- target: asSpecTarget(metadata.target) ?? 'backend',
59
- type: asSpecType(metadata.type) ?? 'feature',
60
- title: typeof metadata.title === 'string' && metadata.title.trim().length > 0
61
- ? metadata.title
62
- : specId,
53
+ raw,
54
+ spec: {
55
+ id: specId,
56
+ specPath: discoveredPath,
57
+ difficulty: asDifficulty(metadata.difficulty) ?? 3,
58
+ tags: asStringTags(metadata.tags),
59
+ dependencies: [],
60
+ scope: asSpecScope(metadata.scope) ?? 'feature',
61
+ target: asSpecTarget(metadata.target) ?? 'backend',
62
+ type: asSpecType(metadata.type) ?? 'feature',
63
+ title: typeof metadata.title === 'string' && metadata.title.trim().length > 0
64
+ ? metadata.title
65
+ : specId,
66
+ },
63
67
  };
64
68
  }
65
- async function readFreshDifficultyAndScope(specId, specPath, projectPath) {
66
- try {
67
- const resolvedPath = projectPath
68
- ? await resolveVerifiedSpecPath(specId, specPath, projectPath)
69
- : specPath;
70
- const raw = await readFile(resolvedPath, 'utf-8');
71
- const { metadata } = parseFrontmatter(raw);
72
- return {
73
- difficulty: asDifficulty(metadata.difficulty),
74
- scope: asSpecScope(metadata.scope),
75
- };
76
- }
77
- catch {
78
- return {};
79
- }
80
- }
81
69
  async function resolveEffectiveSpecPath(specId, specPath, projectPath) {
82
70
  if (!projectPath || isAbsolute(specPath)) {
83
71
  return specPath;
@@ -214,10 +202,8 @@ export async function handleCheckReadiness(args) {
214
202
  specStore.getSpecFresh;
215
203
  const spec = await lifecycleRead(projectId, specId, args.projectPath);
216
204
  let effectiveSpec;
205
+ let rawSpec = null;
217
206
  if (spec) {
218
- const fresh = spec.specPath
219
- ? await readFreshDifficultyAndScope(spec.id, spec.specPath, args.projectPath)
220
- : {};
221
207
  let resolvedSpecPath = spec.specPath;
222
208
  if (spec.specPath) {
223
209
  try {
@@ -236,11 +222,20 @@ export async function handleCheckReadiness(args) {
236
222
  };
237
223
  }
238
224
  }
225
+ if (resolvedSpecPath) {
226
+ try {
227
+ rawSpec = await readFile(resolvedSpecPath, 'utf-8');
228
+ }
229
+ catch {
230
+ rawSpec = null;
231
+ }
232
+ }
233
+ const freshMetadata = rawSpec === null ? {} : parseFrontmatter(rawSpec).metadata;
239
234
  effectiveSpec = {
240
235
  id: spec.id,
241
236
  specPath: resolvedSpecPath,
242
- difficulty: fresh.difficulty ?? spec.difficulty,
243
- scope: fresh.scope ?? spec.scope,
237
+ difficulty: asDifficulty(freshMetadata.difficulty) ?? spec.difficulty,
238
+ scope: asSpecScope(freshMetadata.scope) ?? spec.scope,
244
239
  target: spec.target,
245
240
  type: spec.type,
246
241
  title: spec.title,
@@ -263,11 +258,21 @@ export async function handleCheckReadiness(args) {
263
258
  isError: true,
264
259
  };
265
260
  }
266
- effectiveSpec = await synthesizeSpecFromDiscoveredPath(specId, discoveredPath);
261
+ const discovered = await synthesizeSpecFromDiscoveredPath(specId, discoveredPath);
262
+ effectiveSpec = discovered.spec;
263
+ rawSpec = discovered.raw;
267
264
  }
268
265
  // validateSpecFormat owns the readiness and quality evaluation so the response
269
266
  // cannot combine separately computed evidence from different reads of spec.md.
270
- const validationResult = await validateSpecFormat(effectiveSpec, { readinessMode: mode });
267
+ const validationResult = await validateSpecFormat(effectiveSpec, {
268
+ readinessMode: mode,
269
+ rawSpec,
270
+ });
271
+ const ownershipBlockers = effectiveSpec.specPath
272
+ ? rawSpec === null
273
+ ? ['handoff_ownership_invalid path=<spec> classifications=SpecRead:Failed']
274
+ : validateHandoffOwnership(rawSpec)
275
+ : [];
271
276
  // SPEC-716: Ground ready flag in unified SpecValidationResult.
272
277
  // Only non-file-access errors from validateSpecFormat are surfaced in the
273
278
  // report — MISSING_FRONTMATTER due to file-not-found is best-effort since
@@ -285,6 +290,11 @@ export async function handleCheckReadiness(args) {
285
290
  report.issues.blockers.push(msg);
286
291
  }
287
292
  }
293
+ for (const blocker of ownershipBlockers) {
294
+ if (!report.issues.blockers.includes(blocker)) {
295
+ report.issues.blockers.push(blocker);
296
+ }
297
+ }
288
298
  for (const msg of formatWarnings) {
289
299
  if (!report.issues.warnings.includes(msg)) {
290
300
  report.issues.warnings.push(msg);
@@ -292,7 +302,7 @@ export async function handleCheckReadiness(args) {
292
302
  }
293
303
  // Ground ready: only false if BOTH readiness report and format gate agree
294
304
  // (or format has hard non-file errors)
295
- report.ready = report.ready && hardFormatErrors.length === 0;
305
+ report.ready = report.ready && hardFormatErrors.length === 0 && ownershipBlockers.length === 0;
296
306
  const canonicalFailure = canonicalReadinessFailure(vr);
297
307
  if (canonicalFailure !== null) {
298
308
  const target = mode === 'strict' ? report.issues.blockers : report.issues.warnings;
@@ -25,7 +25,6 @@ import { resolveEnglishOnlySpecGate } from '../engine/spec-language/english-only
25
25
  import { FallbackGenerator } from '../engine/spec-generator/index.js';
26
26
  import { analyzeProjectForSpec, getEmptyAutopilotResult, } from './create-spec/autopilot-analyzer.js';
27
27
  import { withBudget, unwrapBudget, withTotalBudget } from '../engine/timing/budget.js';
28
- import { measureStep } from '../engine/timing/structured-log.js';
29
28
  import { resolveProjectIdOrAutoDetect } from './resolve-project-id.js';
30
29
  import { hashProjectPath, projectDataDir } from '../storage/base-store.js';
31
30
  import { issuePlannerToken } from '../engine/reviewer-tokens/issuer.js';
@@ -967,7 +966,7 @@ export async function resolveGroundedVerificationCommands(projectPath, testPaths
967
966
  }
968
967
  async function prepareCreateSpecCandidate(initialParams) {
969
968
  let params = { ...initialParams };
970
- const buildResult = await measureStep('buildSpecContext', () => buildSpecContext(params));
969
+ const buildResult = await buildSpecContext(params);
971
970
  if (!buildResult.ok) {
972
971
  return earlyPreparation({
973
972
  content: [{ type: 'text', text: buildResult.errorMessage }],
@@ -976,11 +975,11 @@ async function prepareCreateSpecCandidate(initialParams) {
976
975
  }
977
976
  const context = buildResult.context;
978
977
  const { spec, projectId } = context;
979
- const knowledge = await measureStep('loadKnowledge', () => knowledgeStore.getKnowledge(projectId));
978
+ const knowledge = await knowledgeStore.getKnowledge(projectId);
980
979
  const clarificationSession = params.clarificationSessionId
981
980
  ? await knowledgeStore.getClarification(projectId, params.clarificationSessionId)
982
981
  : null;
983
- const constitutionCheck = await measureStep('validateConstitution', () => validateConstitution(projectId, spec.title, spec.tags));
982
+ const constitutionCheck = await validateConstitution(projectId, spec.title, spec.tags);
984
983
  if (constitutionCheck.blocked && constitutionCheck.errorResult) {
985
984
  return earlyPreparation(constitutionCheck.errorResult);
986
985
  }
@@ -1021,7 +1020,7 @@ async function prepareCreateSpecCandidate(initialParams) {
1021
1020
  .filter(Boolean)
1022
1021
  .join('\n')
1023
1022
  : '';
1024
- const generatedSpec = await measureStep('generateSpecBody', () => new FallbackGenerator().generate({
1023
+ const generatedSpec = await new FallbackGenerator().generate({
1025
1024
  title: spec.title,
1026
1025
  description: `${params.description}${contractNote}`,
1027
1026
  type: spec.type,
@@ -1033,7 +1032,7 @@ async function prepareCreateSpecCandidate(initialParams) {
1033
1032
  framework: technologyContract?.framework ?? knowledge?.framework ?? undefined,
1034
1033
  architecture: knowledge?.architecture.primary ?? undefined,
1035
1034
  },
1036
- }));
1035
+ });
1037
1036
  spec.generation = generatedSpec.generation;
1038
1037
  // SPEC-1406 (DEFECT 4, round 2): FallbackGenerator no longer emits an unconditional
1039
1038
  // warning, so qualityWarnings only needs the non-empty guard now — the redundant
@@ -1091,17 +1090,17 @@ async function prepareCreateSpecCandidate(initialParams) {
1091
1090
  },
1092
1091
  });
1093
1092
  }
1094
- const technicalFiles = await measureStep('resolveTechnicalFiles', () => resolveTechnicalFiles({
1093
+ const technicalFiles = await resolveTechnicalFiles({
1095
1094
  generatedSpecBody: generatedSpec.specBody,
1096
1095
  generatedTechnicalSection: generatedSpec.technicalSection,
1097
1096
  projectPath: params.projectPath ?? '',
1098
- }));
1099
- const groundedTechnical = await measureStep('groundTechnicalFiles', () => groundTechnicalFiles({
1097
+ });
1098
+ const groundedTechnical = await groundTechnicalFiles({
1100
1099
  files: technicalFiles,
1101
1100
  projectPath: params.projectPath ?? '',
1102
1101
  userInput: params.description,
1103
1102
  autopilot,
1104
- }));
1103
+ });
1105
1104
  const outOfScope = resolveOutOfScope(params.outOfScope, params.description);
1106
1105
  const scenarioTestPaths = groundedTechnical.files.test.map((file) => file.path);
1107
1106
  const criteria = contractCriteria.map((record) => ({ text: record.text, done: false }));
@@ -1559,10 +1558,9 @@ export async function handleCreateSpec(inputParams) {
1559
1558
  result: committedResult,
1560
1559
  });
1561
1560
  operationJournal.prepared('create_spec', operationKey);
1562
- await measureStep('mkdir-specDir', () => executionMkdir(specDir, { recursive: true }));
1563
- // SPEC-713: measure file write — this is the critical persistence step.
1561
+ await executionMkdir(specDir, { recursive: true });
1564
1562
  assertExecutionCanCommit(criticalSignal);
1565
- await measureStep('writeFile-specPath', () => atomicWriteFile(specPath, unifiedSpec, { encoding: 'utf-8' }));
1563
+ await atomicWriteFile(specPath, unifiedSpec, { encoding: 'utf-8' });
1566
1564
  assertExecutionCanCommit(criticalSignal);
1567
1565
  // SPEC-1351 (AC2): verify the write actually landed on disk
1568
1566
  // before any commit path is allowed to report persisted:true.
@@ -1575,11 +1573,11 @@ export async function handleCreateSpec(inputParams) {
1575
1573
  throw new Error(`create_spec failed to persist ${specPath}: file is missing or empty after write. ` +
1576
1574
  'No spec was registered — retry create_spec.');
1577
1575
  }
1578
- await measureStep('specStore-createSpec', () => specStore.createSpec(projectId, spec));
1576
+ await specStore.createSpec(projectId, spec);
1579
1577
  storeCreated = true;
1580
1578
  const lifecycleRead = specStore.getLifecycleSpec;
1581
1579
  if (lifecycleRead) {
1582
- const visibleSpec = await measureStep('specStore-visibility-barrier', () => lifecycleRead(projectId, spec.id, resolvedPath));
1580
+ const visibleSpec = await lifecycleRead(projectId, spec.id, resolvedPath);
1583
1581
  if (visibleSpec?.id !== spec.id) {
1584
1582
  throw new Error(`create_spec persisted ${spec.id} but the lifecycle visibility barrier could not read it`);
1585
1583
  }
@@ -1592,7 +1590,7 @@ export async function handleCreateSpec(inputParams) {
1592
1590
  /* best-effort */
1593
1591
  });
1594
1592
  assertExecutionCanCommit(criticalSignal);
1595
- await measureStep('commit-idempotency-evidence', () => commitIdempotencyEvidence(resolvedPath, idempotencyKey, idempotencyClaim, spec, specPath));
1593
+ await commitIdempotencyEvidence(resolvedPath, idempotencyKey, idempotencyClaim, spec, specPath);
1596
1594
  operationJournal.committed('create_spec', operationKey, committedResult);
1597
1595
  claimLifecycle.committed = true;
1598
1596
  // SPEC-709/SPEC-461: unified spec.md; no progress or HTML artifacts.
@@ -64,9 +64,6 @@ ${toolsTable}
64
64
  - NEVER treat a \`validate\` acknowledgement as a passing result
65
65
  - Specs stay \`spec.md\`-only; the injected rules block below lists the forbidden and allowed files.
66
66
 
67
- ## Skill Discovery
68
-
69
- Use find-skills to discover available workflows.
70
67
  `;
71
68
  }
72
69
  const CURSORRULES_CONTENT = `# Planu SDD — Cursor Rules
@@ -53,12 +53,12 @@ var __disposeResources = (this && this.__disposeResources) || (function (Suppres
53
53
  });
54
54
  import { createHash } from 'node:crypto';
55
55
  import { readFile } from 'node:fs/promises';
56
- import { isAbsolute, resolve as resolvePath } from 'node:path';
57
56
  import { specStore, knowledgeStore } from '../storage/index.js';
58
57
  import { DurableJobRuntime, DurableJobNotFoundError, publicJobCursor, } from '../engine/execution/job-runtime.js';
59
58
  import { schedulePackageHandoffJobExecution } from '../engine/execution/package-handoff-job-executor.js';
60
59
  import { acquireLock, releaseLock } from '../engine/safety/cross-process-lock.js';
61
60
  import { resolveProjectId, missingProjectIdError } from './resolve-project-id.js';
61
+ import { resolveVerifiedSpecPath } from '../storage/project-identity.js';
62
62
  const SUBMISSION_LOCK_WAIT_MS = 5_000;
63
63
  const SUBMISSION_LOCK_POLL_MS = 100;
64
64
  const TERMINAL_RECOVERABLE_STATES = new Set(['failed', 'cancelled', 'dead-letter']);
@@ -78,19 +78,8 @@ async function resolveProjectRoot(projectId, projectPath) {
78
78
  }
79
79
  return undefined;
80
80
  }
81
- async function digestSpecFile(projectId, projectPath, specPath) {
82
- if (!specPath) {
83
- return '';
84
- }
85
- if (isAbsolute(specPath)) {
86
- return readFile(specPath).then((bytes) => createHash('sha256').update(bytes).digest('hex'), () => '');
87
- }
88
- const projectRoot = await resolveProjectRoot(projectId, projectPath);
89
- if (!projectRoot) {
90
- return '';
91
- }
92
- const absoluteSpecPath = resolvePath(projectRoot, specPath);
93
- return readFile(absoluteSpecPath).then((bytes) => createHash('sha256').update(bytes).digest('hex'), () => '');
81
+ async function digestSpecFile(verifiedSpecPath) {
82
+ return readFile(verifiedSpecPath).then((bytes) => createHash('sha256').update(bytes).digest('hex'), () => '');
94
83
  }
95
84
  async function acquireSubmissionLock(projectId, operationId) {
96
85
  const deadlineAt = Date.now() + SUBMISSION_LOCK_WAIT_MS;
@@ -127,7 +116,19 @@ export async function handlePackageHandoff(args) {
127
116
  };
128
117
  }
129
118
  const specVersion = spec.spec_version ?? '0.0.0';
130
- const specContentDigest = await digestSpecFile(projectId, projectRoot, spec.specPath);
119
+ if (!projectRoot || !spec.specPath) {
120
+ return {
121
+ content: [{ type: 'text', text: `Spec '${specId}' has no verified project path` }],
122
+ isError: true,
123
+ structuredContent: {
124
+ error: 'spec_path_unavailable',
125
+ code: 422,
126
+ context: { specId, projectId },
127
+ },
128
+ };
129
+ }
130
+ const verifiedSpecPath = await resolveVerifiedSpecPath(specId, spec.specPath, projectRoot);
131
+ const specContentDigest = await digestSpecFile(verifiedSpecPath);
131
132
  const operationId = deriveOperationId(projectId, specId, specVersion, specContentDigest);
132
133
  const submissionLock = await acquireSubmissionLock(projectId, operationId);
133
134
  try {
@@ -160,10 +161,12 @@ export async function handlePackageHandoff(args) {
160
161
  operationId,
161
162
  payload: {
162
163
  kind: 'package-handoff',
163
- schemaVersion: 1,
164
+ schemaVersion: 2,
164
165
  projectId,
165
166
  specId,
166
167
  specVersion,
168
+ selectedProjectPath: projectRoot,
169
+ selectedSpecPath: spec.specPath,
167
170
  },
168
171
  });
169
172
  schedulePackageHandoffJobExecution(projectId, job.workspaceId);
@@ -9,5 +9,5 @@ export interface ApprovalComplianceGateResult {
9
9
  /** Run the optional compliance check for a transition into review. */
10
10
  export declare function checkComplianceGate(specId: string, projectId: string, projectPath: string | undefined): Promise<ApprovalComplianceGateResult>;
11
11
  /** Validate canonical spec format before approval, preserving audited bypass warnings. */
12
- export declare function checkApprovedFormatGate(spec: Spec, newStatus: string, forceApprove?: boolean | undefined): Promise<FormatGateOutput>;
12
+ export declare function checkApprovedFormatGate(spec: Spec, newStatus: string, forceApprove?: boolean | undefined, projectPath?: string): Promise<FormatGateOutput>;
13
13
  //# sourceMappingURL=approval-gates.d.ts.map
@@ -3,6 +3,7 @@ import { validateSpecFormat } from '../../core/spec-validator.js';
3
3
  import { getComplianceGateConfig } from '../../storage/compliance-gate-config-store.js';
4
4
  import { formatKeyValue } from '../output-formatter.js';
5
5
  import { reportClassifiedDegradation } from '../../errors/classified-degradation.js';
6
+ import { PortablePathError, resolveVerifiedSpecPath } from '../../storage/project-identity.js';
6
7
  /** Run the optional compliance check for a transition into review. */
7
8
  export async function checkComplianceGate(specId, projectId, projectPath) {
8
9
  if (!projectPath) {
@@ -30,21 +31,43 @@ export async function checkComplianceGate(specId, projectId, projectPath) {
30
31
  }
31
32
  }
32
33
  /** Validate canonical spec format before approval, preserving audited bypass warnings. */
33
- export async function checkApprovedFormatGate(spec, newStatus, forceApprove = false) {
34
+ export async function checkApprovedFormatGate(spec, newStatus, forceApprove = false, projectPath) {
34
35
  if (newStatus !== 'approved') {
35
36
  return { blockResult: null, qualityWarnings: [] };
36
37
  }
37
38
  let result;
38
39
  try {
39
- result = await validateSpecFormat(spec, {
40
+ const validatedSpec = projectPath && spec.specPath
41
+ ? {
42
+ ...spec,
43
+ specPath: await resolveVerifiedSpecPath(spec.id, spec.specPath, projectPath),
44
+ }
45
+ : spec;
46
+ result = await validateSpecFormat(validatedSpec, {
40
47
  readinessMode: 'strict',
41
48
  bypassReason: forceApprove ? 'forceApprove' : undefined,
42
49
  });
43
50
  }
44
51
  catch (error) {
45
- /* reliability-optional: FORMAT_GATE_UNAVAILABLE — caller receives explicit degraded result */
46
- reportClassifiedDegradation('FORMAT_GATE_UNAVAILABLE', error);
47
- return { blockResult: null, qualityWarnings: [] };
52
+ if (error instanceof PortablePathError) {
53
+ result = {
54
+ valid: false,
55
+ errors: [
56
+ {
57
+ code: 'SPEC_PATH_INVALID',
58
+ message: error.message,
59
+ path: 'specPath',
60
+ source: 'registry',
61
+ },
62
+ ],
63
+ warnings: [],
64
+ };
65
+ }
66
+ else {
67
+ /* reliability-optional: FORMAT_GATE_UNAVAILABLE — caller receives explicit degraded result */
68
+ reportClassifiedDegradation('FORMAT_GATE_UNAVAILABLE', error);
69
+ return { blockResult: null, qualityWarnings: [] };
70
+ }
48
71
  }
49
72
  if (result.valid) {
50
73
  const qualityWarnings = result.warnings
@@ -74,13 +74,11 @@ export declare const UpdateStatusEvidencePayloadSchema: z.ZodObject<{
74
74
  "fault-injection": "fault-injection";
75
75
  lint: "lint";
76
76
  migration: "migration";
77
- native: "native";
78
77
  reproducibility: "reproducibility";
79
78
  security: "security";
80
79
  "test-full": "test-full";
81
80
  "test-related": "test-related";
82
81
  typecheck: "typecheck";
83
- website: "website";
84
82
  }>;
85
83
  command: z.ZodString;
86
84
  scope: z.ZodArray<z.ZodString>;
@@ -472,11 +472,21 @@ async function commitTransitionWithNarrowLock(args) {
472
472
  : join(args.projectPath, args.expectedSpec.specPath)
473
473
  : '';
474
474
  const priorSpecFile = args.changeRequest
475
- ? await readFile(specFilePath, 'utf8').catch(() => null)
475
+ ? await readFile(specFilePath, 'utf8').catch((error) => {
476
+ if (error.code === 'ENOENT') {
477
+ return null;
478
+ }
479
+ throw error;
480
+ })
476
481
  : null;
477
482
  const evidencePaths = ['review_feedback.md', 'spec.lock.json'].map((name) => join(projectDataDir(args.projectId), 'handoffs', args.specId, name));
478
483
  const priorEvidence = args.changeRequest
479
- ? await Promise.all(evidencePaths.map((path) => readFile(path).catch(() => null)))
484
+ ? await Promise.all(evidencePaths.map((path) => readFile(path).catch((error) => {
485
+ if (error.code === 'ENOENT') {
486
+ return null;
487
+ }
488
+ throw error;
489
+ })))
480
490
  : [];
481
491
  assertExecutionCanCommit();
482
492
  const transitionRecord = await transitionSpec(args.projectId, args.specId, args.newStatus, {
@@ -546,8 +556,8 @@ async function commitTransitionWithNarrowLock(args) {
546
556
  }));
547
557
  approvalRecordsRestored = true;
548
558
  }
549
- catch {
550
- // Report the incomplete compensation below.
559
+ catch (compensationError) {
560
+ reportClassifiedDegradation('STATUS_APPROVAL_COMPENSATION_FAILURE', compensationError);
551
561
  }
552
562
  try {
553
563
  await rollbackTransitionSpec(transitionRecord);
@@ -556,8 +566,8 @@ async function commitTransitionWithNarrowLock(args) {
556
566
  }
557
567
  lifecycleRestored = true;
558
568
  }
559
- catch {
560
- // Report the incomplete compensation below.
569
+ catch (compensationError) {
570
+ reportClassifiedDegradation('STATUS_LIFECYCLE_COMPENSATION_FAILURE', compensationError);
561
571
  }
562
572
  return {
563
573
  ok: false,
@@ -886,12 +896,12 @@ export async function handleUpdateStatus(params, server) {
886
896
  return dorError;
887
897
  }
888
898
  // SPEC-716/SPEC-780: Format gate — block 'approved' unless forceApprove bypasses with warnings
889
- const formatGate = await checkApprovedFormatGate(spec, approvalGateStatus, params.forceApprove);
899
+ const formatGate = await checkApprovedFormatGate(spec, approvalGateStatus, params.forceApprove, transitionProjectPath);
890
900
  if (formatGate.blockResult) {
891
901
  return formatGate.blockResult;
892
902
  }
893
903
  // SPEC-632: Ambiguity gate — block 'approved' if score < 70
894
- const ambiguityError = await checkAmbiguityGate(spec, approvalGateStatus);
904
+ const ambiguityError = await checkAmbiguityGate(spec, approvalGateStatus, transitionProjectPath);
895
905
  if (ambiguityError) {
896
906
  return ambiguityError;
897
907
  }
@@ -58,7 +58,7 @@ export declare function checkImplementationDependencyGate(spec: Spec, allSpecs:
58
58
  * SPEC-632: Block transition to 'approved' if ambiguity score < 70.
59
59
  * Fails closed when the spec cannot be scored.
60
60
  */
61
- export declare function checkAmbiguityGate(spec: Spec, newStatus: SpecStatus): Promise<ToolResult | null>;
61
+ export declare function checkAmbiguityGate(spec: Spec, newStatus: SpecStatus, projectPath?: string): Promise<ToolResult | null>;
62
62
  export declare function checkSpecArtifactCommittedGate(spec: Spec, newStatus: SpecStatus, projectPath: string | undefined): Promise<ToolResult | null>;
63
63
  /**
64
64
  * SPEC-769/SPEC-492: Readiness gate — block 'review'/'approved' when spec
@@ -191,11 +191,27 @@ export function checkImplementationDependencyGate(spec, allSpecs, newStatus) {
191
191
  * SPEC-632: Block transition to 'approved' if ambiguity score < 70.
192
192
  * Fails closed when the spec cannot be scored.
193
193
  */
194
- export async function checkAmbiguityGate(spec, newStatus) {
194
+ export async function checkAmbiguityGate(spec, newStatus, projectPath) {
195
195
  if (newStatus !== 'approved' || !spec.specPath) {
196
196
  return null;
197
197
  }
198
- const report = await scoreAmbiguityFromPath(spec.specPath);
198
+ let resolvedSpecPath;
199
+ try {
200
+ if (!isAbsolute(spec.specPath)) {
201
+ if (!projectPath) {
202
+ throw new PortablePathError('ROOT_NOT_FOUND', '[Planu] project root is required for a portable spec path');
203
+ }
204
+ resolvedSpecPath = await resolveVerifiedSpecPath(spec.id, spec.specPath, projectPath);
205
+ }
206
+ else {
207
+ resolvedSpecPath = spec.specPath;
208
+ }
209
+ }
210
+ catch (error) {
211
+ reportClassifiedDegradation('AMBIGUITY_SPEC_UNRESOLVABLE', error);
212
+ return gateUnavailableResult('AMBIGUITY_GATE_UNAVAILABLE', 'Ambiguity scoring failed.', readinessGateIdentity(spec));
213
+ }
214
+ const report = await scoreAmbiguityFromPath(resolvedSpecPath);
199
215
  if (!report) {
200
216
  return gateUnavailableResult('AMBIGUITY_GATE_UNAVAILABLE', 'Ambiguity scoring failed.', readinessGateIdentity(spec));
201
217
  }
@@ -177,7 +177,13 @@ export function createValidationStageRunner(onProgress) {
177
177
  }
178
178
  /** Public MCP boundary: persist and acknowledge validation work without running it inline. */
179
179
  export async function handleValidate(args) {
180
- const projectId = resolveProjectId(args);
180
+ let projectId;
181
+ try {
182
+ projectId = resolveProjectId(args);
183
+ }
184
+ catch (error) {
185
+ return validationWorktreeErrorResult(error, args.specId);
186
+ }
181
187
  if (!projectId) {
182
188
  return missingProjectIdError;
183
189
  }
@@ -209,8 +215,8 @@ export async function handleValidate(args) {
209
215
  structuredContent: { error: 'project_not_found', code: 404, context: { projectId } },
210
216
  };
211
217
  }
212
- const spec = await specStore.getSpec(projectId, args.specId, knowledge.projectPath);
213
- if (!spec) {
218
+ const storedSpec = await specStore.getSpec(projectId, args.specId, args.projectPath === undefined ? knowledge.projectPath : undefined);
219
+ if (!storedSpec?.specPath) {
214
220
  return {
215
221
  content: [{ type: 'text', text: ti('spec.notFound', { id: args.specId }) }],
216
222
  isError: true,
@@ -223,16 +229,32 @@ export async function handleValidate(args) {
223
229
  }
224
230
  let validationWorktree;
225
231
  try {
232
+ const requestedProjectPath = args.projectPath ?? knowledge.projectPath;
233
+ const selectedSpecPath = isAbsolute(storedSpec.specPath)
234
+ ? storedSpec.specPath
235
+ : join(requestedProjectPath, storedSpec.specPath);
226
236
  validationWorktree = await resolveValidationWorktree({
227
- requestedProjectPath: args.projectPath ?? knowledge.projectPath,
237
+ requestedProjectPath,
228
238
  canonicalProjectPath: knowledge.projectPath,
229
- canonicalSpecPath: spec.specPath,
239
+ canonicalSpecPath: selectedSpecPath,
230
240
  specId: args.specId,
231
241
  });
232
242
  }
233
243
  catch (error) {
234
244
  return validationWorktreeErrorResult(error, args.specId);
235
245
  }
246
+ const spec = await specStore.getSpec(projectId, args.specId, validationWorktree.projectPath);
247
+ if (!spec) {
248
+ return {
249
+ content: [{ type: 'text', text: ti('spec.notFound', { id: args.specId }) }],
250
+ isError: true,
251
+ structuredContent: {
252
+ error: 'spec_not_found',
253
+ code: 404,
254
+ context: { specId: args.specId, projectId },
255
+ },
256
+ };
257
+ }
236
258
  const submissionLock = await acquireValidationSubmissionLock(projectId, args.specId);
237
259
  try {
238
260
  const env_1 = { stack: [], error: void 0, hasError: false };
@@ -371,7 +393,8 @@ export async function executeValidate(args, server, onProgress) {
371
393
  },
372
394
  };
373
395
  }
374
- const spec = await specStore.getSpec(projectId, specId, knowledge.projectPath);
396
+ const projectPath = args.projectPath ?? knowledge.projectPath;
397
+ const spec = await specStore.getSpec(projectId, specId, projectPath);
375
398
  if (!spec) {
376
399
  return {
377
400
  content: [{ type: 'text', text: ti('spec.notFound', { id: specId }) }],
@@ -384,7 +407,6 @@ export async function executeValidate(args, server, onProgress) {
384
407
  },
385
408
  };
386
409
  }
387
- const projectPath = args.projectPath ?? knowledge.projectPath;
388
410
  const executionSpec = args.specPath ? { ...spec, specPath: args.specPath } : spec;
389
411
  const runStage = createValidationStageRunner(onProgress);
390
412
  // SPEC-1017: fail closed when planu/ contains non-canonical artifacts.
@@ -1,21 +1,4 @@
1
1
  import type { ExecutionMode } from './primitives.js';
2
- export interface CalibrationMetrics {
3
- specId: string;
4
- estimatedHours: number;
5
- actualHours: number;
6
- estimatedComplexity: number;
7
- actualComplexity: number;
8
- specCompleteness: number;
9
- driftCount: number;
10
- completedAt: string;
11
- }
12
- export interface CalibrationState {
13
- totalSpecs: number;
14
- avgAccuracy: number;
15
- coefficients: Record<string, number>;
16
- history: CalibrationMetrics[];
17
- lastCalibrated: string;
18
- }
19
2
  export interface LearnedRegistryEntry {
20
3
  id: string;
21
4
  registry: string;
@@ -36,13 +36,23 @@ export interface ValidateDurableJobPayload {
36
36
  readonly freshnessLease?: ValidationFreshnessLease;
37
37
  readonly specPath: string;
38
38
  }
39
- export interface PackageHandoffDurableJobPayload {
39
+ interface PackageHandoffDurableJobPayloadV1 {
40
40
  readonly kind: 'package-handoff';
41
41
  readonly schemaVersion: 1;
42
42
  readonly projectId: string;
43
43
  readonly specId: string;
44
44
  readonly specVersion: string;
45
45
  }
46
+ interface PackageHandoffDurableJobPayloadV2 {
47
+ readonly kind: 'package-handoff';
48
+ readonly schemaVersion: 2;
49
+ readonly projectId: string;
50
+ readonly specId: string;
51
+ readonly specVersion: string;
52
+ readonly selectedProjectPath: string;
53
+ readonly selectedSpecPath: string;
54
+ }
55
+ export type PackageHandoffDurableJobPayload = PackageHandoffDurableJobPayloadV1 | PackageHandoffDurableJobPayloadV2;
46
56
  /** Outcome of one deadline-bounded package-handoff stage execution. */
47
57
  interface PackageHandoffStageOutcome<T> {
48
58
  readonly ok: boolean;
@@ -101,5 +111,9 @@ export interface DurableJobRecord {
101
111
  readonly createdAt: string;
102
112
  readonly updatedAt: string;
103
113
  }
114
+ export interface DurableJobRecoveryActions {
115
+ recoverValidate(): Promise<void>;
116
+ recoverPackageHandoff(): Promise<void>;
117
+ }
104
118
  export {};
105
119
  //# sourceMappingURL=durable-job.d.ts.map