@planu/cli 6.0.1 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,14 @@
1
+ ## [6.0.2] - 2026-09-10
2
+
3
+ ### Reliability
4
+ - prove lifecycle persistence, registered-worktree isolation, and implementation-change attribution end to end
5
+ - enforce current stable direct dependencies through a deterministic read-only preflight and pre-push guard
6
+ - distinguish actionable dependency drift from registry, timeout, empty-output, and malformed-output failures
7
+
8
+ ### Maintenance
9
+ - refresh direct dependencies to their current stable compatible releases
10
+ - consolidate overlapping lifecycle specs and discard obsolete work
11
+
1
12
  ## [6.0.1] - 2026-09-10
2
13
 
3
14
  ### Cleanup
@@ -1 +1 @@
1
- {"schemaVersion":1,"commit":"af76d38310eb4ab7b625442c738f40230a8e0b0a"}
1
+ {"schemaVersion":1,"commit":"50315919adc1c8fd80b058334e0c970a57daa578"}
@@ -13,7 +13,9 @@ type AttributableOwnedPaths = {
13
13
  * committed baseline. Failure is deliberately quiet: callers must not turn
14
14
  * baseline tokens into implementation evidence when attribution is unavailable.
15
15
  */
16
- export declare function resolveAttributableOwnedPaths(projectPath: string, ownedPaths: string[]): Promise<AttributableOwnedPaths>;
16
+ export declare function resolveAttributableOwnedPaths(projectPath: string, ownedPaths: string[], baselineSha?: string | null): Promise<AttributableOwnedPaths>;
17
+ /** Capture the selected checkout commit once so a lifecycle call has one stable diff baseline. */
18
+ export declare function captureAttributionBaseline(projectPath: string): Promise<string | null>;
17
19
  /**
18
20
  * Scan the spec's owned paths for evidence of implementation across 4 layers.
19
21
  * Empty ownership yields an empty result — never a repository-wide scan.
@@ -6,13 +6,14 @@ import { execFile } from 'node:child_process';
6
6
  import { promisify } from 'node:util';
7
7
  import { fastReadFiles } from '../core-bridge.js';
8
8
  const CODE_FILE_RE = /\.(ts|js|tsx|jsx)$/;
9
+ const GIT_COMMIT_RE = /^[a-f0-9]{40,64}$/u;
9
10
  const execFileAsync = promisify(execFile);
10
11
  /**
11
12
  * Reduce the already-bounded ownership list to files changed from the current
12
13
  * committed baseline. Failure is deliberately quiet: callers must not turn
13
14
  * baseline tokens into implementation evidence when attribution is unavailable.
14
15
  */
15
- export async function resolveAttributableOwnedPaths(projectPath, ownedPaths) {
16
+ export async function resolveAttributableOwnedPaths(projectPath, ownedPaths, baselineSha) {
16
17
  const bounded = [
17
18
  ...new Set(ownedPaths
18
19
  .map((path) => normalize(path))
@@ -22,9 +23,13 @@ export async function resolveAttributableOwnedPaths(projectPath, ownedPaths) {
22
23
  return { available: true, paths: [] };
23
24
  }
24
25
  try {
26
+ const baseline = baselineSha === undefined ? await captureAttributionBaseline(projectPath) : baselineSha;
27
+ if (baseline === null) {
28
+ return { available: false, paths: [], diagnostic: 'git-baseline-unavailable' };
29
+ }
25
30
  const commands = [
26
- ['diff', '--name-only', '--diff-filter=ACMRTUXB', 'HEAD', '--', ...bounded],
27
- ['diff', '--cached', '--name-only', '--diff-filter=ACMRTUXB', 'HEAD', '--', ...bounded],
31
+ ['diff', '--name-only', '--diff-filter=ACMRTUXB', baseline, '--', ...bounded],
32
+ ['diff', '--cached', '--name-only', '--diff-filter=ACMRTUXB', baseline, '--', ...bounded],
28
33
  ['ls-files', '--others', '--exclude-standard', '--', ...bounded],
29
34
  ];
30
35
  const outputs = await Promise.all(commands.map((args) => execFileAsync('git', ['-C', projectPath, ...args], {
@@ -44,6 +49,17 @@ export async function resolveAttributableOwnedPaths(projectPath, ownedPaths) {
44
49
  return { available: false, paths: [], diagnostic: 'git-baseline-unavailable' };
45
50
  }
46
51
  }
52
+ /** Capture the selected checkout commit once so a lifecycle call has one stable diff baseline. */
53
+ export async function captureAttributionBaseline(projectPath) {
54
+ try {
55
+ const { stdout } = await execFileAsync('git', ['-C', projectPath, 'rev-parse', '--verify', 'HEAD'], { encoding: 'utf8', maxBuffer: 1024 * 1024 });
56
+ const baseline = stdout.trim();
57
+ return GIT_COMMIT_RE.test(baseline) ? baseline : null;
58
+ }
59
+ catch {
60
+ return null;
61
+ }
62
+ }
47
63
  /**
48
64
  * Scan the spec's owned paths for evidence of implementation across 4 layers.
49
65
  * Empty ownership yields an empty result — never a repository-wide scan.
@@ -5,7 +5,7 @@ export declare function executionMkdir(path: string, options: MakeDirectoryOptio
5
5
  recursive: true;
6
6
  }): Promise<string | undefined>;
7
7
  /** Exclusive-create helper for idempotency claims; never overwrites an owner. */
8
- export declare function executionWriteFileExclusive(path: string, content: string, options?: Omit<WriteFileOptions, 'flag'>): Promise<void>;
8
+ export declare function executionWriteFileExclusive(path: string, content: string, options?: Exclude<WriteFileOptions, BufferEncoding>): Promise<void>;
9
9
  export declare function executionRename(source: string, target: string): Promise<void>;
10
10
  export declare function executionLink(source: string, target: string): Promise<void>;
11
11
  export declare function executionRemove(path: string, options?: {
@@ -7,9 +7,9 @@ export async function executionMkdir(path, options) {
7
7
  return mkdir(path, options);
8
8
  }
9
9
  /** Exclusive-create helper for idempotency claims; never overwrites an owner. */
10
- export async function executionWriteFileExclusive(path, content, options = {}) {
10
+ export async function executionWriteFileExclusive(path, content, options) {
11
11
  assertExecutionCanCommit();
12
- await writeFile(path, content, { ...options, flag: 'wx' });
12
+ await writeFile(path, content, { ...(options ?? {}), flag: 'wx' });
13
13
  }
14
14
  export async function executionRename(source, target) {
15
15
  assertExecutionCanCommit();
@@ -30,6 +30,7 @@ function countNonOverlappingOccurrences(haystack, needle) {
30
30
  }
31
31
  return count;
32
32
  }
33
+ // eslint-disable-next-line max-lines-per-function -- validation and replay share the atomic write boundary
33
34
  export async function applyChangesToSpec(specPath, changes) {
34
35
  const approvedTextChanges = changes.filter((c) => c.approved && !SECTIONS_WITHOUT_LITERAL_BODY_TEXT.has(c.section));
35
36
  if (approvedTextChanges.length === 0) {
@@ -70,6 +71,13 @@ export async function applyChangesToSpec(specPath, changes) {
70
71
  const sectionBody = modified.slice(bounds.start, bounds.end);
71
72
  const occurrences = countNonOverlappingOccurrences(sectionBody, change.originalValue);
72
73
  if (occurrences === 0) {
74
+ const replacementOccurrences = countNonOverlappingOccurrences(sectionBody, change.newValue);
75
+ if (replacementOccurrences === 1) {
76
+ // Idempotent replay: the canonical body stage committed in a prior attempt.
77
+ applied++;
78
+ appliedSections.add(change.section);
79
+ continue;
80
+ }
73
81
  skipped.push({
74
82
  section: change.section,
75
83
  originalValue: change.originalValue,
@@ -100,7 +108,10 @@ export async function applyChangesToSpec(specPath, changes) {
100
108
  return { applied: 0, skipped, fileWritten: false };
101
109
  }
102
110
  modified = propagateMirrors(modified, appliedSections);
103
- await atomicWriteFile(specPath, modified);
104
- return { applied, skipped, fileWritten: true };
111
+ const fileWritten = modified !== content;
112
+ if (fileWritten) {
113
+ await atomicWriteFile(specPath, modified);
114
+ }
115
+ return { applied, skipped, fileWritten };
105
116
  }
106
117
  //# sourceMappingURL=apply-changes.js.map
@@ -1,6 +1,7 @@
1
1
  import { escapeRegex } from '../../core/shared/strings.js';
2
2
  import { normalizeCriterionText } from '../criterion-identity.js';
3
3
  import { parseBddScenarios, renderBddScenariosYaml } from '../spec-format/bdd-parser.js';
4
+ import { parseFrontmatterScenarios } from '../validator/spec-compliance-runner.js';
4
5
  import { extractSectionCriteria } from '../spec-format/acceptance-criteria.js';
5
6
  import { extractListItems, findMarkdownSectionRange } from '../spec-format/markdown-sections.js';
6
7
  import { parseCriterionGroundingRecords, parseTechnicalReferenceGroundingRecords, renderGroundingFrontmatter, renderTechnicalReferenceGroundingFrontmatter, } from '../spec-grounding/contract.js';
@@ -14,7 +15,18 @@ const VERIFICATION_COMMANDS_HEADING = 'Verification Commands';
14
15
  const VERIFICATION_STARTS_WITH_RE = /Verification starts with:\s*`([^`]+)`/i;
15
16
  export function propagateMirrors(content, appliedSections) {
16
17
  let result = content;
17
- if (appliedSections.has(ACCEPTANCE_CRITERIA_HEADING)) {
18
+ const propagatedSections = new Set(appliedSections);
19
+ if (appliedSections.has('Problem')) {
20
+ const criteria = extractProblemAcceptanceCriteria(result);
21
+ if (criteria !== null) {
22
+ if (criteria.length === 0 || !criteria.every(isCompleteBddCriterion)) {
23
+ throw new Error('INVALID_RECONCILED_ACCEPTANCE_CRITERIA: Problem declares Acceptance criteria but no complete BDD criteria could be parsed');
24
+ }
25
+ result = replaceNamedSection(result, ACCEPTANCE_CRITERIA_HEADING, criteria.map((criterion) => `- ${criterion}`));
26
+ propagatedSections.add(ACCEPTANCE_CRITERIA_HEADING);
27
+ }
28
+ }
29
+ if (propagatedSections.has(ACCEPTANCE_CRITERIA_HEADING)) {
18
30
  result = propagateAcceptanceCriteria(result);
19
31
  }
20
32
  if (appliedSections.has(FILES_HEADING)) {
@@ -25,6 +37,27 @@ export function propagateMirrors(content, appliedSections) {
25
37
  }
26
38
  return result;
27
39
  }
40
+ function isCompleteBddCriterion(text) {
41
+ const criterion = text.replace(/^(?:AC|AB)\d+:\s*/i, '');
42
+ const [scenario] = parseBddScenarios(criterion);
43
+ if (!scenario) {
44
+ return false;
45
+ }
46
+ const keywords = new Set(scenario.steps.map((step) => step.keyword));
47
+ return keywords.has('given') && keywords.has('when') && keywords.has('then');
48
+ }
49
+ function extractProblemAcceptanceCriteria(content) {
50
+ const problem = findMarkdownSectionRange(content, 'Problem');
51
+ if (!problem) {
52
+ return null;
53
+ }
54
+ const body = content.slice(problem.contentStart, problem.end);
55
+ const marker = /^\s*Acceptance criteria:\s*$/im.exec(body);
56
+ if (!marker) {
57
+ return null;
58
+ }
59
+ return extractSectionCriteria(body.slice(marker.index + marker[0].length));
60
+ }
28
61
  function propagateAcceptanceCriteria(content) {
29
62
  const section = findMarkdownSectionRange(content, ACCEPTANCE_CRITERIA_HEADING);
30
63
  if (!section) {
@@ -32,16 +65,44 @@ function propagateAcceptanceCriteria(content) {
32
65
  }
33
66
  const sectionBody = content.slice(section.contentStart, section.end);
34
67
  const criteriaTexts = extractSectionCriteria(sectionBody);
35
- const scenarios = criteriaTexts.map(criterionToScenario);
68
+ const oldScenarios = mapWithFrontmatter(content, (fm) => parseFrontmatterScenarios(`---\n${fm}\n---\n`).map((scenario) => ({
69
+ title: scenario.title,
70
+ done: scenario.done,
71
+ tests: scenario.tests,
72
+ steps: (scenario.steps ?? []).map((step) => ({
73
+ keyword: step.keyword,
74
+ text: step.text,
75
+ })),
76
+ })));
77
+ const oldScenarioByCriterion = new Map();
78
+ const oldCriteria = mapWithFrontmatter(content, (fm) => parseCriterionGroundingRecords(fm).records);
79
+ oldCriteria.forEach((record, index) => {
80
+ const scenario = oldScenarios[index];
81
+ if (scenario) {
82
+ oldScenarioByCriterion.set(normalizeCriterionText(record.text), scenario);
83
+ }
84
+ });
85
+ const scenarios = criteriaTexts.map((text) => {
86
+ const parsed = criterionToScenario(text);
87
+ const previous = oldScenarioByCriterion.get(normalizeCriterionText(text));
88
+ return previous
89
+ ? { ...parsed, done: previous.done, tests: previous.tests ?? parsed.tests }
90
+ : parsed;
91
+ });
36
92
  const oldRecords = mapWithFrontmatter(content, (fm) => indexCriterionRecords(parseCriterionGroundingRecords(fm).records));
37
93
  const oldTestPaths = mapWithFrontmatter(content, (fm) => parseTechnicalReferenceGroundingRecords(fm)
38
94
  .records.filter((record) => record.section === 'test')
39
95
  .map((record) => record.path));
40
- const criteriaRecords = criteriaTexts.map((text) => oldRecords.get(normalizeCriterionText(text)) ?? {
41
- text,
42
- source: 'user_input',
43
- evidence: ['reconcile_spec.changes'],
44
- confidence: 'high',
96
+ const criteriaRecords = criteriaTexts.map((text) => {
97
+ const previous = oldRecords.get(normalizeCriterionText(text));
98
+ return previous
99
+ ? { ...previous, text }
100
+ : {
101
+ text,
102
+ source: 'user_input',
103
+ evidence: ['reconcile_spec.changes'],
104
+ confidence: 'high',
105
+ };
45
106
  });
46
107
  let result = transformFrontmatter(content, (fm) => {
47
108
  let updated = replaceFrontmatterKeyBlock(fm, 'scenarios', renderBddScenariosYaml(scenarios));
@@ -91,6 +152,10 @@ function propagateTechnicalVerificationCommand(content) {
91
152
  return replaceNamedSection(content, VERIFICATION_COMMANDS_HEADING, [`- \`${newCommand}\``]);
92
153
  }
93
154
  function criterionToScenario(text) {
155
+ const [directScenario] = parseBddScenarios(text);
156
+ if (directScenario?.steps.some((step) => step.keyword === 'then')) {
157
+ return directScenario;
158
+ }
94
159
  const gwtLines = text
95
160
  .split(/\b(GIVEN|WHEN|THEN|AND)\b/)
96
161
  .reduce((lines, part, index, parts) => {
@@ -9,6 +9,12 @@ export declare class SpecFrozenError extends Error {
9
9
  readonly code: 'SPEC_FROZEN';
10
10
  constructor(specId: string, fixHint: string);
11
11
  }
12
+ export declare class AtomicWriteError extends Error {
13
+ readonly stage: 'prepare' | 'write' | 'file-fsync' | 'rename' | 'parent-fsync';
14
+ readonly targetCommitted: boolean;
15
+ readonly code: 'ATOMIC_WRITE_FAILED';
16
+ constructor(stage: 'prepare' | 'write' | 'file-fsync' | 'rename' | 'parent-fsync', targetCommitted: boolean, cause: unknown);
17
+ }
12
18
  /** Remove one optional lifecycle artifact without touching Git state. */
13
19
  export declare function removeLifecycleArtifact(path: string): Promise<void>;
14
20
  /**
@@ -28,7 +34,9 @@ export declare function removeLifecycleArtifact(path: string): Promise<void>;
28
34
  * EXDEV: Cross-device rename is rejected with an explicit error. Callers must
29
35
  * keep tmp on the same filesystem as target.
30
36
  */
31
- export declare function atomicWriteFile(targetPath: string, content: string | Buffer, opts?: AtomicWriteOptions): Promise<void>;
37
+ export declare function atomicWriteFile(targetPath: string, content: string | Buffer, opts?: AtomicWriteOptions & {
38
+ _faultInjectionStage?: 'prepare' | 'write' | 'file-fsync' | 'rename' | 'parent-fsync';
39
+ }): Promise<void>;
32
40
  /**
33
41
  * Remove orphaned `.tmp.<pid>.<nonce>` files left by interrupted writes.
34
42
  * Called by `init_project`'s cleanup pass on startup.
@@ -30,6 +30,17 @@ export class SpecFrozenError extends Error {
30
30
  this.name = 'SpecFrozenError';
31
31
  }
32
32
  }
33
+ export class AtomicWriteError extends Error {
34
+ stage;
35
+ targetCommitted;
36
+ code = 'ATOMIC_WRITE_FAILED';
37
+ constructor(stage, targetCommitted, cause) {
38
+ super(`Atomic write failed at ${stage}; targetCommitted=${String(targetCommitted)}: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
39
+ this.stage = stage;
40
+ this.targetCommitted = targetCommitted;
41
+ this.name = 'AtomicWriteError';
42
+ }
43
+ }
33
44
  /** Remove one optional lifecycle artifact without touching Git state. */
34
45
  export async function removeLifecycleArtifact(path) {
35
46
  await unlink(path).catch((error) => {
@@ -95,21 +106,38 @@ export async function atomicWriteFile(targetPath, content, opts) {
95
106
  const fsyncParent = opts?.fsyncParent ?? IS_POSIX;
96
107
  const nonce = opts?.tmpSuffix ?? `.tmp.${process.pid.toString()}.${randomBytes(4).toString('hex')}`;
97
108
  const tmpPath = `${targetPath}${nonce}`;
98
- await mkdir(dirname(targetPath), { recursive: true });
99
109
  let tmpFd = null;
110
+ let stage = 'prepare';
111
+ let targetCommitted = false;
112
+ const inject = (candidate) => {
113
+ if (opts?._faultInjectionStage === candidate) {
114
+ throw new Error(`Injected atomic write failure at ${candidate}`);
115
+ }
116
+ };
100
117
  try {
118
+ inject('prepare');
119
+ await mkdir(dirname(targetPath), { recursive: true });
101
120
  // Exclusive create — prevents name collision if two calls race with same nonce
121
+ stage = 'write';
102
122
  tmpFd = await open(tmpPath, 'wx', mode);
103
123
  const buf = Buffer.isBuffer(content) ? content : Buffer.from(content, encoding);
124
+ inject('write');
104
125
  await tmpFd.write(buf);
126
+ stage = 'file-fsync';
127
+ inject('file-fsync');
105
128
  await tmpFd.datasync();
106
129
  await tmpFd.close();
107
130
  tmpFd = null;
108
131
  // The temporary file is not externally visible. Cross the request commit
109
132
  // fence immediately before the only externally visible mutation.
110
133
  assertExecutionCanCommit();
134
+ stage = 'rename';
135
+ inject('rename');
111
136
  await rename(tmpPath, targetPath);
137
+ targetCommitted = true;
112
138
  if (fsyncParent) {
139
+ stage = 'parent-fsync';
140
+ inject('parent-fsync');
113
141
  await fsyncDirectory(dirname(targetPath));
114
142
  }
115
143
  }
@@ -126,13 +154,21 @@ export async function atomicWriteFile(targetPath, content, opts) {
126
154
  }
127
155
  // Best-effort cleanup of tmp file
128
156
  try {
129
- await unlink(tmpPath);
157
+ if (!targetCommitted) {
158
+ await unlink(tmpPath);
159
+ }
130
160
  }
131
161
  catch (cleanupError) {
132
162
  // reliability-cleanup: ATOMIC_TEMP_UNLINK — startup scavenger removes orphan
133
163
  reportClassifiedDegradation('ATOMIC_TEMP_UNLINK', cleanupError);
134
164
  }
135
- throw err;
165
+ if (err.code === 'EXECUTION_CANCELLED') {
166
+ throw err;
167
+ }
168
+ if (err instanceof AtomicWriteError) {
169
+ throw err;
170
+ }
171
+ throw new AtomicWriteError(stage, targetCommitted, err);
136
172
  }
137
173
  }
138
174
  /**
@@ -151,9 +187,9 @@ async function fsyncDirectory(dirPath) {
151
187
  dirFd = null;
152
188
  }
153
189
  catch (error) {
154
- // reliability-optional: DIRECTORY_FSYNC — target bytes are already durable
190
+ // The rename already committed the new bytes. Surface the durability failure
191
+ // so callers never claim that the prior destination was restored.
155
192
  reportClassifiedDegradation('DIRECTORY_FSYNC', error);
156
- // Non-fatal — target file is already durable, only dir metadata may need recovery
157
193
  if (dirFd !== null) {
158
194
  try {
159
195
  await dirFd.close();
@@ -163,6 +199,7 @@ async function fsyncDirectory(dirPath) {
163
199
  reportClassifiedDegradation('DIRECTORY_FD_CLOSE', closeError);
164
200
  }
165
201
  }
202
+ throw error;
166
203
  }
167
204
  }
168
205
  /**
@@ -50,6 +50,7 @@ async function buildBroadCache(projectPath) {
50
50
  }
51
51
  import { deepCheckCriterion } from './deep-code-checker.js';
52
52
  import { classifyNegativePredicate, checkTokensAbsent } from './negative-predicate.js';
53
+ import { resolvePackageJsonEvidence } from './package-json-evidence.js';
53
54
  import { ConfigLoader } from '../config-loader.js';
54
55
  import { filterValidatedTestPaths, groundNumericLiteral, createProbeCache, groundAgainstDeclaredTests, findBacktickIdentifierEvidence, } from './test-evidence-grounding.js';
55
56
  // ---------------------------------------------------------------------------
@@ -252,6 +253,10 @@ export async function checkCriterionEvidence(criterion, projectPath, codeState,
252
253
  if (fileExistenceResult) {
253
254
  return fileExistenceResult;
254
255
  }
256
+ const packageJsonResult = await resolvePackageJsonEvidence(criterion, projectPath);
257
+ if (packageJsonResult) {
258
+ return packageJsonResult;
259
+ }
255
260
  // Check for component/function existence in code (legacy + SPEC-1367 backtick forms)
256
261
  const componentResult = await checkComponentMatch(criterion, projectPath, codeState, sharedFileContents, safeTestPaths);
257
262
  if (componentResult) {
@@ -0,0 +1,3 @@
1
+ import type { CriterionEvidenceResult } from '../../types/index.js';
2
+ export declare function resolvePackageJsonEvidence(criterion: string, projectPath: string): Promise<CriterionEvidenceResult | null>;
3
+ //# sourceMappingURL=package-json-evidence.d.ts.map
@@ -0,0 +1,97 @@
1
+ import { open } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ const MAX_PACKAGE_JSON_BYTES = 1_000_000;
4
+ function extractPackageJsonAssertions(criterion) {
5
+ if (!/\bpackage\.json\b/i.test(criterion)) {
6
+ return null;
7
+ }
8
+ const exposesMatch = /\bpackage\.json\b\s+exposes\s+([\s\S]+)/i.exec(criterion);
9
+ if (!exposesMatch?.[1]) {
10
+ return null;
11
+ }
12
+ const assertions = [];
13
+ const objectPattern = /\b([A-Za-z_][\w-]*)\s*\{([^{}]*)\}/g;
14
+ let scalarText = exposesMatch[1];
15
+ let objectMatch;
16
+ while ((objectMatch = objectPattern.exec(exposesMatch[1])) !== null) {
17
+ const parent = objectMatch[1];
18
+ const body = objectMatch[2];
19
+ if (!parent || !body) {
20
+ continue;
21
+ }
22
+ const propertyPattern = /\b([A-Za-z_][\w-]*)\s*:\s*["']([^"']+)["']/g;
23
+ let propertyMatch;
24
+ while ((propertyMatch = propertyPattern.exec(body)) !== null) {
25
+ const property = propertyMatch[1];
26
+ const expected = propertyMatch[2];
27
+ if (property && expected !== undefined) {
28
+ assertions.push([[parent, property], expected]);
29
+ }
30
+ }
31
+ scalarText = scalarText.replace(objectMatch[0], ' ');
32
+ }
33
+ const scalarPattern = /\b([A-Za-z_][\w-]*)\s+["']([^"']+)["']/g;
34
+ let scalarMatch;
35
+ while ((scalarMatch = scalarPattern.exec(scalarText)) !== null) {
36
+ const property = scalarMatch[1];
37
+ const expected = scalarMatch[2];
38
+ if (property && expected !== undefined) {
39
+ assertions.push([[property], expected]);
40
+ }
41
+ }
42
+ return assertions.length > 0 ? assertions : null;
43
+ }
44
+ function valueAtJsonPath(value, path) {
45
+ let current = value;
46
+ for (const segment of path) {
47
+ if (typeof current !== 'object' || current === null || Array.isArray(current)) {
48
+ return undefined;
49
+ }
50
+ current = current[segment];
51
+ }
52
+ return current;
53
+ }
54
+ export async function resolvePackageJsonEvidence(criterion, projectPath) {
55
+ const assertions = extractPackageJsonAssertions(criterion);
56
+ if (!assertions) {
57
+ return null;
58
+ }
59
+ let manifest;
60
+ try {
61
+ const handle = await open(join(projectPath, 'package.json'), 'r');
62
+ try {
63
+ const buffer = Buffer.alloc(MAX_PACKAGE_JSON_BYTES + 1);
64
+ let totalBytesRead = 0;
65
+ while (totalBytesRead < buffer.length) {
66
+ const { bytesRead } = await handle.read(buffer, totalBytesRead, buffer.length - totalBytesRead, totalBytesRead);
67
+ if (bytesRead === 0) {
68
+ break;
69
+ }
70
+ totalBytesRead += bytesRead;
71
+ }
72
+ if (totalBytesRead > MAX_PACKAGE_JSON_BYTES) {
73
+ return { status: 'missing', evidence: 'package.json exceeds the validation size limit' };
74
+ }
75
+ manifest = JSON.parse(buffer.subarray(0, totalBytesRead).toString('utf-8'));
76
+ }
77
+ finally {
78
+ await handle.close();
79
+ }
80
+ }
81
+ catch {
82
+ return { status: 'missing', evidence: 'package.json is missing or malformed' };
83
+ }
84
+ for (const [path, expected] of assertions) {
85
+ if (valueAtJsonPath(manifest, path) !== expected) {
86
+ return {
87
+ status: 'missing',
88
+ evidence: `package.json:${path.join('.')} does not match the required value`,
89
+ };
90
+ }
91
+ }
92
+ return {
93
+ status: 'proven',
94
+ evidence: `package.json:${assertions.map(([path]) => path.join('.')).join(',')}`,
95
+ };
96
+ }
97
+ //# sourceMappingURL=package-json-evidence.js.map
@@ -13,6 +13,7 @@ import { normalizeCriterionText } from '../criterion-identity.js';
13
13
  import { isExecutableTestPath } from '../spec-format/executable-test-path.js';
14
14
  import { normalizeExecutableEvidence } from './executable-evidence.js';
15
15
  import { classifyNegativePredicate, checkTokensAbsent } from './negative-predicate.js';
16
+ import { resolvePackageJsonEvidence } from './package-json-evidence.js';
16
17
  /** A sanitized terminal adapter failure that cannot be mistaken for a failed test verdict. */
17
18
  class ComplianceCommandTerminalError extends Error {
18
19
  code;
@@ -361,7 +362,8 @@ async function runVitestAdapter(links, projectPath, signal) {
361
362
  continue;
362
363
  }
363
364
  const assertions = testResult.assertionResults;
364
- statuses.set(relativePath, assertions.length > 0 && assertions.every((item) => item.status === 'passed')
365
+ statuses.set(relativePath, assertions.some((item) => item.status === 'passed') &&
366
+ !assertions.some((item) => item.status === 'failed')
365
367
  ? 'pass'
366
368
  : 'fail');
367
369
  }
@@ -506,6 +508,41 @@ function canonicalScenarioCriterion(scenario) {
506
508
  ? steps.map((step) => `${step.keyword.toUpperCase()} ${step.text}`).join(' ')
507
509
  : undefined;
508
510
  }
511
+ async function resolveStructuredScenarioEvidence(scenario, projectPath) {
512
+ const criterion = canonicalScenarioCriterion(scenario);
513
+ const evidence = criterion ? await resolvePackageJsonEvidence(criterion, projectPath) : null;
514
+ if (!evidence) {
515
+ return null;
516
+ }
517
+ return {
518
+ title: scenario.title,
519
+ verdict: evidence.status === 'proven' ? 'pass' : 'missing',
520
+ evidence: evidence.evidence ? [evidence.evidence] : [],
521
+ linkVerdicts: [],
522
+ };
523
+ }
524
+ async function resolveUnlinkedScenarioEvidence(scenario, projectPath, signal) {
525
+ const criterion = canonicalScenarioCriterion(scenario);
526
+ const negative = criterion
527
+ ? classifyNegativePredicate(criterion)
528
+ : { isNegative: false, tokens: [] };
529
+ if (negative.isNegative) {
530
+ const absence = await checkTokensAbsent(negative.tokens, projectPath, { signal });
531
+ return {
532
+ title: scenario.title,
533
+ verdict: absence.met ? 'pass' : 'missing',
534
+ evidence: absence.evidence,
535
+ linkVerdicts: [],
536
+ ...(absence.unverifiable ? { unverifiable: true } : {}),
537
+ };
538
+ }
539
+ return {
540
+ title: scenario.title,
541
+ verdict: 'missing',
542
+ evidence: ['No test links — scenario has no tests array'],
543
+ linkVerdicts: [],
544
+ };
545
+ }
509
546
  function resolveExactCommandRow(exactRows, scenario) {
510
547
  const identities = new Set([scenario.title, canonicalScenarioCriterion(scenario)]
511
548
  .filter((value) => typeof value === 'string')
@@ -586,7 +623,8 @@ export async function runSpecCompliance(spec, projectPath, signal, canonicalProj
586
623
  doneDriftFindings,
587
624
  };
588
625
  }
589
- const allLinks = scenarios.flatMap((scenario) => scenario.tests ?? []);
626
+ const structuredEvidenceByScenario = new Map(await Promise.all(scenarios.map(async (scenario) => [scenario, await resolveStructuredScenarioEvidence(scenario, projectPath)])));
627
+ const allLinks = scenarios.flatMap((scenario) => structuredEvidenceByScenario.get(scenario)?.verdict === 'missing' ? [] : (scenario.tests ?? []));
590
628
  const executableLinks = allLinks.filter(isExecutableTestLink);
591
629
  const commandLinks = allLinks.filter((link) => !isExecutableTestLink(link));
592
630
  const resolvedLinks = await Promise.all(executableLinks.map((link) => resolveLink(link, projectPath)));
@@ -651,29 +689,15 @@ export async function runSpecCompliance(spec, projectPath, signal, canonicalProj
651
689
  return `${technologyValue('technology-vitest-a9127f')} --reporter=json --run ${links.map((link) => link.path).join(' ')}`;
652
690
  });
653
691
  const scenarioResults = await Promise.all(scenarios.map(async (scenario) => {
692
+ const structuredEvidence = structuredEvidenceByScenario.get(scenario) ?? null;
693
+ if (structuredEvidence?.verdict === 'missing' ||
694
+ (structuredEvidence && !scenario.tests?.length)) {
695
+ return structuredEvidence;
696
+ }
654
697
  if (!scenario.tests?.length) {
655
- const criterion = canonicalScenarioCriterion(scenario);
656
- const negative = criterion
657
- ? classifyNegativePredicate(criterion)
658
- : { isNegative: false, tokens: [] };
659
- if (negative.isNegative) {
660
- const absence = await checkTokensAbsent(negative.tokens, projectPath, { signal });
661
- return {
662
- title: scenario.title,
663
- verdict: absence.met ? 'pass' : 'missing',
664
- evidence: absence.evidence,
665
- linkVerdicts: [],
666
- ...(absence.unverifiable ? { unverifiable: true } : {}),
667
- };
668
- }
669
- return {
670
- title: scenario.title,
671
- verdict: 'missing',
672
- evidence: ['No test links — scenario has no tests array'],
673
- linkVerdicts: [],
674
- };
698
+ return resolveUnlinkedScenarioEvidence(scenario, projectPath, signal);
675
699
  }
676
- const evidence = [];
700
+ const evidence = [...(structuredEvidence?.evidence ?? [])];
677
701
  const commandRow = resolveExactCommandRow(exactCommandRows, scenario);
678
702
  const linkResults = scenario.tests.map((source) => {
679
703
  if (!isExecutableTestLink(source)) {
@@ -746,9 +746,8 @@ async function findByIdempotencyKey(projectPath, key, projectId, windowMs = IDEM
746
746
  return evidenceMatch;
747
747
  }
748
748
  try {
749
- const { glob } = await import('glob');
750
- const { join: joinPath } = await import('node:path');
751
- const specFiles = await glob(joinPath(projectPath, 'planu/specs/*/spec.md'));
749
+ const globModule = await import('glob');
750
+ const specFiles = await globModule.glob(pathJoin(projectPath, 'planu/specs/*/spec.md'));
752
751
  for (const specFile of specFiles) {
753
752
  const fileStat = await fsStat(specFile).catch(() => null);
754
753
  if (fileStat === null || fileStat.mtimeMs < cutoff) {
@@ -776,10 +775,9 @@ async function findByIdempotencyKey(projectPath, key, projectId, windowMs = IDEM
776
775
  /** SPEC-770: Scan for recently written spec.md files (for possibleDuplicates in timeout response). */
777
776
  async function findRecentlyWrittenSpecs(projectPath, windowMs, requestedTitle) {
778
777
  try {
779
- const { glob } = await import('glob');
780
- const { join: joinPath } = await import('node:path');
778
+ const globModule = await import('glob');
781
779
  const cutoff = Date.now() - windowMs;
782
- const specFiles = await glob(joinPath(projectPath, 'planu/specs/*/spec.md'));
780
+ const specFiles = await globModule.glob(pathJoin(projectPath, 'planu/specs/*/spec.md'));
783
781
  const results = [];
784
782
  for (const specFile of specFiles) {
785
783
  const fileStat = await fsStat(specFile).catch(() => null);
@@ -201,6 +201,7 @@ export function buildInitProjectResult(input) {
201
201
  const narrative = ti('tools.init_project.success', { projectPath: result.projectPath }) +
202
202
  `\n\nDetected: **${result.language}** / ${framework} — project ${action}. ` +
203
203
  `Run \`create_spec\` to start planning your first feature.` +
204
+ (!isUpdate ? `\n\nLearn the workflow: https://planu.dev/?src=init` : '') +
204
205
  ((input.criticalMigrationFailures?.length ?? 0) > 0
205
206
  ? `\n\n⚠️ Critical spec migration warnings: ${String(input.criticalMigrationFailures?.length ?? 0)} issue(s). ` +
206
207
  `See migrationReportPath in structuredContent${input.migrationReportPath ? ` (${input.migrationReportPath})` : ''}.`
@@ -108,7 +108,7 @@ function insertReconciliationLogEntry(existingTechnical, reconcileSection) {
108
108
  ? `${existingTechnical}\n\n### Reconciliation Log\n\n${reconcileSection}`
109
109
  : `### Reconciliation Log\n\n${reconcileSection}`;
110
110
  }
111
- async function writeAuditLogForAppliedChanges(spec, changes) {
111
+ async function writeAuditLogForAppliedChanges(spec, changes, replayKey) {
112
112
  const appliedChanges = changes.filter((c) => c.approved);
113
113
  if (appliedChanges.length === 0) {
114
114
  return { auditWritten: false };
@@ -123,16 +123,15 @@ async function writeAuditLogForAppliedChanges(spec, changes) {
123
123
  ].join('\n');
124
124
  let auditWritten = false;
125
125
  if (spec.specPath) {
126
- try {
127
- const specContent = await readFile(spec.specPath, 'utf-8');
128
- const existingTechnical = extractSectionBody(specContent, 'Technical');
129
- const updatedTechnical = insertReconciliationLogEntry(existingTechnical, reconcileSection);
130
- await replaceSectionInSpec(spec.specPath, 'Technical', updatedTechnical);
131
- auditWritten = true;
132
- }
133
- catch {
134
- /* best-effort */
126
+ const specContent = await readFile(spec.specPath, 'utf-8');
127
+ const marker = `<!-- reconcile:${replayKey}:audit -->`;
128
+ if (specContent.includes(marker)) {
129
+ return { auditWritten: true };
135
130
  }
131
+ const existingTechnical = extractSectionBody(specContent, 'Technical');
132
+ const updatedTechnical = insertReconciliationLogEntry(existingTechnical, `${marker}\n${reconcileSection}`);
133
+ await replaceSectionInSpec(spec.specPath, 'Technical', updatedTechnical);
134
+ auditWritten = true;
136
135
  }
137
136
  return { auditWritten };
138
137
  }
@@ -208,25 +207,35 @@ async function verifyWriteOrBuildFailureResult(specPath, appliedTextChanges, app
208
207
  },
209
208
  };
210
209
  }
211
- async function appendPlanReconcileNote(planPath, changes) {
212
- try {
213
- const existing = await readFile(planPath, 'utf-8');
214
- const note = [
215
- '',
216
- '---',
217
- '',
218
- `## Reconciliation Note — ${new Date().toISOString()}`,
219
- '',
220
- `> ${changes.length} change(s) applied during reconciliation:`,
221
- '',
222
- ...changes.map((c) => `- **${c.section}**: ${c.reason}`),
223
- '',
224
- ].join('\n');
225
- await atomicWriteFile(planPath, existing + note);
226
- }
227
- catch {
228
- /* best-effort */
210
+ async function appendPlanReconcileNote(planPath, changes, replayKey) {
211
+ const existing = await readFile(planPath, 'utf-8');
212
+ const marker = `<!-- reconcile:${replayKey}:plan-note -->`;
213
+ if (existing.includes(marker)) {
214
+ return;
229
215
  }
216
+ const note = [
217
+ '',
218
+ marker,
219
+ '---',
220
+ '',
221
+ `## Reconciliation Note — ${new Date().toISOString()}`,
222
+ '',
223
+ `> ${changes.length} change(s) applied during reconciliation:`,
224
+ '',
225
+ ...changes.map((c) => `- **${c.section}**: ${c.reason}`),
226
+ '',
227
+ ].join('\n');
228
+ await atomicWriteFile(planPath, existing + note);
229
+ }
230
+ function reconciliationReplayKey(changes) {
231
+ return createHash('sha256')
232
+ .update(JSON.stringify(changes.map(({ section, originalValue, newValue }) => ({
233
+ section,
234
+ originalValue,
235
+ newValue,
236
+ }))))
237
+ .digest('hex')
238
+ .slice(0, 16);
230
239
  }
231
240
  function buildConflictResolutionQuestion(pendingChanges) {
232
241
  const { field, property } = buildEnumSchema('resolution', ['keep-mine', 'use-spec', 'merge-interactive', 'cancel'], [
@@ -284,7 +293,17 @@ async function routeDeclaredArchitecturalDrift(spec, projectId, projectPath, dec
284
293
  syncSpecFiles,
285
294
  });
286
295
  }
296
+ // eslint-disable-next-line complexity -- stage accounting is explicit for deterministic recovery
287
297
  export async function handleReconcileSpec(params, server) {
298
+ const committedStages = [];
299
+ let failedStage = null;
300
+ const injectedFailureStage = params
301
+ ._faultInjectionStage;
302
+ const injectStageFailure = (stage) => {
303
+ if (injectedFailureStage === stage) {
304
+ throw new Error(`Injected reconcile failure at ${stage}`);
305
+ }
306
+ };
288
307
  const { specId, projectId, autoDetect = true, livingSpec = false, changes: manualChanges, declaredDrift, projectPath, } = params;
289
308
  try {
290
309
  const knowledge = await knowledgeStore.getKnowledge(projectId);
@@ -380,11 +399,16 @@ export async function handleReconcileSpec(params, server) {
380
399
  };
381
400
  }
382
401
  }
402
+ failedStage = 'spec.md';
403
+ injectStageFailure('spec.md');
383
404
  const applyResult = await applyChangesToSpec(spec.specPath, approvedChanges);
384
405
  specBodyWritten = applyResult.fileWritten;
385
406
  bodySkippedChanges = applyResult.skipped;
386
407
  appliedTextChanges = partitionAppliedTextChanges(approvedTextChanges, applyResult.skipped);
387
- if (applyResult.fileWritten) {
408
+ if (appliedTextChanges.length > 0) {
409
+ committedStages.push('spec.md');
410
+ }
411
+ if (appliedTextChanges.length > 0) {
388
412
  const verificationFailure = await verifyWriteOrBuildFailureResult(spec.specPath, appliedTextChanges, approvedChanges, preWriteSpecContent, preWriteVersion);
389
413
  if (verificationFailure) {
390
414
  return verificationFailure;
@@ -401,27 +425,65 @@ export async function handleReconcileSpec(params, server) {
401
425
  }
402
426
  const appliedChanges = [...metadataChanges, ...appliedTextChanges];
403
427
  const anyApplied = appliedChanges.length > 0;
428
+ const replayKey = reconciliationReplayKey(appliedChanges);
404
429
  let auditWriteResult = { auditWritten: false };
405
430
  if (anyApplied) {
406
- auditWriteResult = await writeAuditLogForAppliedChanges(spec, appliedChanges);
431
+ failedStage = 'audit';
432
+ injectStageFailure('audit');
433
+ auditWriteResult = await writeAuditLogForAppliedChanges(spec, appliedChanges, replayKey);
434
+ if (auditWriteResult.auditWritten) {
435
+ committedStages.push('audit');
436
+ }
407
437
  }
408
438
  const hasStatusChange = metadataChanges.find((c) => c.section === 'status');
409
439
  if (hasStatusChange) {
410
- await specStore.__internalSetStatus(projectId, specId, hasStatusChange.newValue);
440
+ failedStage = 'status';
441
+ injectStageFailure('status');
442
+ if (spec.status !== hasStatusChange.newValue) {
443
+ await specStore.__internalSetStatus(projectId, specId, hasStatusChange.newValue);
444
+ }
445
+ committedStages.push('status');
446
+ }
447
+ else if (anyApplied) {
448
+ committedStages.push('status');
411
449
  }
412
450
  if (spec.planPath && anyApplied) {
413
- await appendPlanReconcileNote(spec.planPath, appliedChanges);
451
+ failedStage = 'plan-note';
452
+ injectStageFailure('plan-note');
453
+ await appendPlanReconcileNote(spec.planPath, appliedChanges, replayKey);
454
+ committedStages.push('plan-note');
455
+ }
456
+ else if (anyApplied) {
457
+ committedStages.push('plan-note');
414
458
  }
415
459
  let createdVersion = null;
416
460
  if (anyApplied) {
417
- const currentVersion = await specStore.getLatestVersion(projectId, specId);
418
- const version = createVersion(specId, currentVersion, appliedChanges, `Reconcile: ${appliedChanges.length} change(s) applied`);
419
- await specStore.saveVersion(projectId, specId, version);
420
- createdVersion = version.version;
461
+ failedStage = 'version';
462
+ injectStageFailure('version');
463
+ const loadVersions = specStore
464
+ .loadVersions;
465
+ const versions = loadVersions ? await loadVersions(projectId, specId) : [];
466
+ const existingVersion = versions.find((version) => version.reason.includes(`[${replayKey}]`));
467
+ if (existingVersion) {
468
+ createdVersion = existingVersion.version;
469
+ }
470
+ else {
471
+ const currentVersion = await specStore.getLatestVersion(projectId, specId);
472
+ const version = createVersion(specId, currentVersion, appliedChanges, `Reconcile [${replayKey}]: ${appliedChanges.length} change(s) applied`);
473
+ await specStore.saveVersion(projectId, specId, version);
474
+ createdVersion = version.version;
475
+ }
476
+ committedStages.push('version');
421
477
  }
478
+ failedStage = 'store-update';
479
+ injectStageFailure('store-update');
422
480
  await specStore.updateSpec(projectId, specId, {
423
481
  updatedAt: new Date().toISOString(),
424
482
  });
483
+ if (anyApplied) {
484
+ committedStages.push('store-update');
485
+ }
486
+ failedStage = null;
425
487
  const report = {
426
488
  specId,
427
489
  changes: allChanges,
@@ -453,6 +515,8 @@ export async function handleReconcileSpec(params, server) {
453
515
  versionCreated: createdVersion,
454
516
  specBodyWritten,
455
517
  auditWritten: auditWriteResult.auditWritten,
518
+ committedStages,
519
+ failedStage,
456
520
  appliedChanges: appliedChangesReport,
457
521
  skippedChanges: skippedChangesReport,
458
522
  ...(bodySkippedChanges.length > 0 ? { skippedTextChanges: bodySkippedChanges } : {}),
@@ -492,10 +556,16 @@ export async function handleReconcileSpec(params, server) {
492
556
  };
493
557
  }
494
558
  catch (error) {
559
+ if (failedStage === 'spec.md' &&
560
+ error.targetCommitted === true &&
561
+ !committedStages.includes('spec.md')) {
562
+ committedStages.push('spec.md');
563
+ }
495
564
  const message = error instanceof Error ? error.message : String(error);
496
565
  return {
497
566
  content: [{ type: 'text', text: ti('errors.internalError', { message }) }],
498
567
  isError: true,
568
+ structuredContent: { committedStages, failedStage },
499
569
  };
500
570
  }
501
571
  }
@@ -11,7 +11,7 @@ type LifecycleAuthorityRoute = {
11
11
  result: ToolResult;
12
12
  };
13
13
  /** Select the lifecycle path before any transition, artifact, receipt, or log mutation. */
14
- export declare function runOwnershipBoundedCodeReality(spec: Spec, projectPath: string): Promise<GapScore>;
14
+ export declare function runOwnershipBoundedCodeReality(spec: Spec, projectPath: string, baselineSha?: string | null): Promise<GapScore>;
15
15
  export declare function classifyLifecycleAuthority(input: UpdateStatusInput, context: ReconciliationInvocationContext, options?: {
16
16
  requireDoneDigest?: boolean;
17
17
  }): LifecycleAuthorityRoute;
@@ -27,7 +27,7 @@ import { readFile } from 'node:fs/promises';
27
27
  import { queuePostCommitTasks } from './side-effects.js';
28
28
  import { formatKeyValue } from '../output-formatter.js';
29
29
  import { checkCodeReality } from '../../engine/code-scanner/index.js';
30
- import { resolveAttributableOwnedPaths } from '../../engine/code-scanner/layer-scanner.js';
30
+ import { captureAttributionBaseline, resolveAttributableOwnedPaths, } from '../../engine/code-scanner/layer-scanner.js';
31
31
  import { scoreUnavailableAttribution } from '../../engine/code-scanner/gap-scorer.js';
32
32
  import { extractFilesFromSpecBody } from '../../engine/spec-format/technical-md-populator.js';
33
33
  import { isAbsolute, join, resolve } from 'node:path';
@@ -53,7 +53,7 @@ function lifecycleAuthorityError(code, message, fixHint) {
53
53
  };
54
54
  }
55
55
  /** Select the lifecycle path before any transition, artifact, receipt, or log mutation. */
56
- export async function runOwnershipBoundedCodeReality(spec, projectPath) {
56
+ export async function runOwnershipBoundedCodeReality(spec, projectPath, baselineSha) {
57
57
  const specPath = isAbsolute(spec.specPath) ? spec.specPath : join(projectPath, spec.specPath);
58
58
  const specBody = await readSpecContent(specPath);
59
59
  const ownership = specBody === null ? null : await extractFilesFromSpecBody(specBody, projectPath);
@@ -65,7 +65,7 @@ export async function runOwnershipBoundedCodeReality(spec, projectPath) {
65
65
  if (ownedPaths.length === 0) {
66
66
  reportClassifiedDegradation('CODE_REALITY_OWNERSHIP_MISSING', new Error(`spec ${spec.id} declares no canonical owned paths`));
67
67
  }
68
- const attributable = await resolveAttributableOwnedPaths(projectPath, ownedPaths);
68
+ const attributable = await resolveAttributableOwnedPaths(projectPath, ownedPaths, baselineSha);
69
69
  if (!attributable.available) {
70
70
  reportClassifiedDegradation('CODE_REALITY_ATTRIBUTION_UNAVAILABLE', new Error(attributable.diagnostic));
71
71
  return scoreUnavailableAttribution();
@@ -700,6 +700,9 @@ export async function handleUpdateStatus(params, server) {
700
700
  const transitionProjectPath = (params.projectPath?.trim()
701
701
  ? effectiveProjectPath
702
702
  : (knowledge?.projectPath ?? effectiveProjectPath)) || undefined;
703
+ const implementationBaselineSha = newStatus === 'implementing' && transitionProjectPath
704
+ ? await captureAttributionBaseline(transitionProjectPath)
705
+ : undefined;
703
706
  if (authorityRoute.route === 'reconcile') {
704
707
  if (params.evidence !== undefined) {
705
708
  return {
@@ -1041,7 +1044,7 @@ export async function handleUpdateStatus(params, server) {
1041
1044
  const [codeRealityResult, doneGatesResult] = await Promise.all([
1042
1045
  // Code reality: only relevant for 'implementing'
1043
1046
  newStatus === 'implementing' && !reverseTransition && effectiveGatePath
1044
- ? runOwnershipBoundedCodeReality(spec, effectiveGatePath).catch((error) => {
1047
+ ? runOwnershipBoundedCodeReality(spec, effectiveGatePath, implementationBaselineSha).catch((error) => {
1045
1048
  // reliability-optional: CODE_REALITY_ENRICHMENT — downstream evidence gates remain binding
1046
1049
  reportClassifiedDegradation('CODE_REALITY_ENRICHMENT', error);
1047
1050
  return null;
@@ -1005,6 +1005,7 @@ function buildCompactValidateText(args) {
1005
1005
  if (failedCount === 0 && qualityFailures.length === 0) {
1006
1006
  // All passing — single line
1007
1007
  return (`✅ Validate: ${String(score)}/100 — ${String(passedCount)}/${String(totalCriteria)} criteria passing` +
1008
+ ` — See what to do next: https://planu.dev/?src=validation` +
1008
1009
  commitReminder +
1009
1010
  planuReminder);
1010
1011
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@planu/cli",
3
- "version": "6.0.1",
3
+ "version": "6.1.0",
4
4
  "description": "Planu — MCP Server for Spec Driven Development. Cross-platform (Linux/macOS/Windows, x64/arm64).",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -49,8 +49,12 @@
49
49
  "check:sdd-core": "node scripts/check-sdd-core-closure.mjs",
50
50
  "measure:sdd-core": "node scripts/measure-sdd-core.mjs --baseline tests/fixtures/sdd-core-baseline.json --measure-current",
51
51
  "check:destructive-ops": "bash scripts/check-no-automatic-destructive-ops.sh",
52
+ "check:deps:fresh": "node scripts/check-dependency-freshness.mjs",
53
+ "check:website-facts": "node scripts/check-website-facts.mjs",
54
+ "generate:donation-qr": "node website/scripts/generate-donation-qr.mjs",
55
+ "check:donation-qr": "node website/scripts/generate-donation-qr.mjs --check",
52
56
  "check:strict": "pnpm check && pnpm generate:host-tool-registry -- --check && node scripts/prune-dead-exports.mjs --check && pnpm audit:deadcode && pnpm audit:circular && pnpm audit:types",
53
- "check:preflight": "pnpm check && pnpm test:contracts && pnpm measure:sdd-core && pnpm build",
57
+ "check:preflight": "pnpm check:deps:fresh && pnpm check && pnpm check:website-facts && pnpm test:contracts && pnpm measure:sdd-core && pnpm build",
54
58
  "test:contracts": "node scripts/test-contracts.mjs",
55
59
  "test:migrations": "vitest run tests/storage/corruption-contract.test.ts tests/integration/runtime-storage.test.ts tests/integration/canonical-storage-migration.test.ts tests/storage/sdd-core-migration.test.ts",
56
60
  "test:fault-injection": "vitest run tests/integration/durable-job-runtime.test.ts tests/integration/idempotent-operations.test.ts tests/storage/sdd-core-migration.test.ts",
@@ -80,6 +84,17 @@
80
84
  "access": "public"
81
85
  },
82
86
  "homepage": "https://planu.dev",
87
+ "repository": {
88
+ "type": "git",
89
+ "url": "git+https://github.com/planu-dev/planu.git"
90
+ },
91
+ "bugs": {
92
+ "url": "https://github.com/planu-dev/planu/issues"
93
+ },
94
+ "funding": {
95
+ "type": "individual",
96
+ "url": "https://planu.dev/#support"
97
+ },
83
98
  "keywords": [
84
99
  "mcp",
85
100
  "mcp-server",
@@ -101,8 +116,8 @@
101
116
  "dependencies": {
102
117
  "@modelcontextprotocol/sdk": "^1.30.0",
103
118
  "glob": "^13.0.6",
104
- "yaml": "^2.9.0",
105
- "zod": "^4.5.4"
119
+ "yaml": "2.9.1",
120
+ "zod": "^4.6.2"
106
121
  },
107
122
  "devDependencies": {
108
123
  "@commitlint/cli": "^21.2.2",
@@ -110,7 +125,7 @@
110
125
  "@eslint/js": "^10.0.1",
111
126
  "@secretlint/secretlint-rule-no-homedir": "^13.0.5",
112
127
  "@secretlint/secretlint-rule-preset-recommend": "^13.0.5",
113
- "@types/node": "^26.4.1",
128
+ "@types/node": "^22.20.2",
114
129
  "@typescript/native": "npm:typescript@^7.0.2",
115
130
  "@vitest/coverage-v8": "^5.0.0",
116
131
  "eslint": "10.10.0",
@@ -119,16 +134,17 @@
119
134
  "eslint-plugin-import": "^2.32.0",
120
135
  "husky": "^9.1.7",
121
136
  "jiti": "2.7.0",
122
- "knip": "^6.34.0",
123
- "lint-staged": "^17.5.0",
137
+ "knip": "^6.35.1",
138
+ "lint-staged": "^17.5.1",
124
139
  "madge": "^8.0.0",
125
140
  "prettier": "^3.9.6",
141
+ "qrcode": "1.5.4",
126
142
  "secretlint": "^13.0.5",
127
- "tsc-alias": "^1.9.4",
143
+ "tsc-alias": "^1.9.5",
128
144
  "type-coverage": "^2.30.1",
129
145
  "typescript": "npm:@typescript/typescript6@^6.0.2",
130
- "typescript-eslint": "^8.69.0",
131
- "vite": "^8.2.2",
146
+ "typescript-eslint": "^8.70.0",
147
+ "vite": "^8.3.0",
132
148
  "vitest": "^5.0.0"
133
149
  }
134
150
  }