peaks-loop 4.1.5 → 4.1.6

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 (86) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +36 -0
  3. package/README-en.md +47 -183
  4. package/README.md +24 -188
  5. package/dist/cli/commands/best-practice-scan-command.d.ts +11 -6
  6. package/dist/cli/commands/best-practice-scan-command.js +35 -20
  7. package/dist/cli/commands/best-practice-scan-helpers.d.ts +47 -0
  8. package/dist/cli/commands/best-practice-scan-helpers.js +88 -5
  9. package/dist/cli/commands/best-practice-scan-lookup-results.d.ts +13 -0
  10. package/dist/cli/commands/best-practice-scan-lookup-results.js +237 -0
  11. package/dist/cli/commands/dispatch-command-spec.js +1 -1
  12. package/dist/cli/commands/dispatch-isolation-lease.d.ts +1 -1
  13. package/dist/cli/commands/dispatch-isolation-lease.js +6 -53
  14. package/dist/cli/commands/dispatch-prompt-blocks.d.ts +1 -1
  15. package/dist/cli/commands/dispatch-prompt-composition.d.ts +1 -1
  16. package/dist/cli/commands/dispatch-record-write.d.ts +1 -1
  17. package/dist/cli/commands/dispatch-tool-call.d.ts +1 -1
  18. package/dist/cli/commands/openspec-command-shared.js +2 -2
  19. package/dist/cli/commands/request-transition-failures.js +31 -4
  20. package/dist/cli/commands/request-transition-preflight.js +1 -1
  21. package/dist/cli/commands/slice-decompose-artifacts.js +2 -1
  22. package/dist/cli/commands/verdict-aggregate-command.js +2 -1
  23. package/dist/cli/commands/workflow-gate-commands.js +4 -4
  24. package/dist/cli/program.js +0 -2
  25. package/dist/services/artifacts/artifact-contract-block.js +21 -2
  26. package/dist/services/artifacts/artifact-prerequisites.js +7 -7
  27. package/dist/services/artifacts/rd-transition-gates.d.ts +33 -0
  28. package/dist/services/artifacts/rd-transition-gates.js +71 -0
  29. package/dist/services/artifacts/request-artifact-service.js +22 -20
  30. package/dist/services/artifacts/request-artifact-state-helpers.d.ts +9 -1
  31. package/dist/services/artifacts/request-artifact-state-helpers.js +6 -4
  32. package/dist/services/audit-independent/judged-declaration-check.d.ts +1 -0
  33. package/dist/services/audit-independent/judged-declaration-check.js +62 -1
  34. package/dist/services/context/build-dispatch-system-prompt.d.ts +5 -9
  35. package/dist/services/context/build-dispatch-system-prompt.js +11 -11
  36. package/dist/services/context/post-compact-reinjection.js +1 -1
  37. package/dist/services/dispatch/test-tool-detection.d.ts +17 -1
  38. package/dist/services/dispatch/test-tool-detection.js +12 -1
  39. package/dist/services/evidence/evidence-generator.js +8 -4
  40. package/dist/services/openspec/coverage-evidence-reader.d.ts +9 -9
  41. package/dist/services/openspec/coverage-evidence-reader.js +8 -8
  42. package/dist/services/openspec/openspec-archive-service.d.ts +1 -1
  43. package/dist/services/openspec/openspec-archive-service.js +6 -6
  44. package/dist/services/scan/file-size-baseline.d.ts +13 -6
  45. package/dist/services/scan/file-size-baseline.js +54 -31
  46. package/dist/services/scan/file-size-scan.d.ts +7 -14
  47. package/dist/services/scan/file-size-scan.js +6 -1
  48. package/dist/services/scan/type-corroboration.d.ts +32 -0
  49. package/dist/services/scan/type-corroboration.js +51 -0
  50. package/dist/services/scan/type-sanity-service.d.ts +14 -0
  51. package/dist/services/scan/type-sanity-service.js +10 -19
  52. package/dist/services/security/safe-settings-path.d.ts +5 -0
  53. package/dist/services/security/safe-settings-path.js +64 -8
  54. package/dist/services/skill/resume-detector.js +8 -8
  55. package/dist/services/workflow/pipeline-verify-gate-support.d.ts +24 -8
  56. package/dist/services/workflow/pipeline-verify-gate-support.js +32 -38
  57. package/dist/services/workflow/pipeline-verify-qa-phase.d.ts +102 -0
  58. package/dist/services/workflow/pipeline-verify-qa-phase.js +176 -0
  59. package/dist/services/workflow/pipeline-verify-service.js +26 -27
  60. package/dist/services/workflow/request-type-resolution.d.ts +99 -0
  61. package/dist/services/workflow/request-type-resolution.js +130 -0
  62. package/dist/services/workflow/workflow-skip-service.d.ts +1 -0
  63. package/dist/services/workflow/workflow-skip-service.js +19 -21
  64. package/dist/services/workflow/workflow-state-store.d.ts +9 -0
  65. package/dist/services/workflow/workflow-state-store.js +26 -1
  66. package/dist/shared/incrementing-number.d.ts +23 -2
  67. package/dist/shared/incrementing-number.js +57 -15
  68. package/package.json +5 -7
  69. package/skills/bee/peaks-prd/SKILL.md +3 -2
  70. package/skills/peaks-code/SKILL.md +32 -15
  71. package/dist/cli/commands/vm-command-shared.d.ts +0 -23
  72. package/dist/cli/commands/vm-command-shared.js +0 -23
  73. package/dist/cli/commands/vm-commands.d.ts +0 -3
  74. package/dist/cli/commands/vm-commands.js +0 -45
  75. package/dist/cli/commands/vm-hypervisor-probe.d.ts +0 -27
  76. package/dist/cli/commands/vm-hypervisor-probe.js +0 -78
  77. package/dist/cli/commands/vm-hypervisor-runtime.d.ts +0 -15
  78. package/dist/cli/commands/vm-hypervisor-runtime.js +0 -64
  79. package/dist/cli/commands/vm-release-command.d.ts +0 -5
  80. package/dist/cli/commands/vm-release-command.js +0 -101
  81. package/dist/cli/commands/vm-spawn-command.d.ts +0 -5
  82. package/dist/cli/commands/vm-spawn-command.js +0 -177
  83. package/dist/cli/commands/vm-status-command.d.ts +0 -3
  84. package/dist/cli/commands/vm-status-command.js +0 -50
  85. package/dist/services/vm/vm-lease.d.ts +0 -40
  86. package/dist/services/vm/vm-lease.js +0 -160
@@ -1,9 +1,9 @@
1
1
  /**
2
- * Coverage Evidence reader for c8 `coverage-summary.json` (Fix-6B).
2
+ * Coverage Evidence reader for the istanbul `coverage-summary.json` shape (Fix-6B).
3
3
  *
4
4
  * - pure helper module, no side effects beyond FS reads
5
- * - reads the istanbul-reporter JSON shape emitted by `c8 --reporter=json-summary`
6
- * (the project's coverage tool — see scripts/coverage-c8.mjs)
5
+ * - reads the istanbul-reporter JSON shape a `--reporter=json-summary` run emits
6
+ * (the project's instrument is `.husky/coverage-ratchet.mjs`, which emits it)
7
7
  * - resolves a `coverage-summary.json` from a fixed discovery order
8
8
  * - validates per-capability coverage against a `## Capability Mapping` block
9
9
  *
@@ -14,7 +14,7 @@
14
14
  *
15
15
  * Conventions:
16
16
  * - All paths are POSIX-normalized for JSON safety.
17
- * - The c8 summary's per-file keys are project-root-relative POSIX paths
17
+ * - The summary's per-file keys are project-root-relative POSIX paths
18
18
  * (e.g. `src/services/openspec/openspec-archive-service.ts`).
19
19
  * - Capability mapping `source` field is also project-root-relative, may be
20
20
  * a file (`foo.ts`) or a directory (`src/services/openspec/`).
@@ -36,7 +36,7 @@ const DEFAULT_DISCOVERY = [
36
36
  *
37
37
  * Discovery order (per Fix-6B AC1):
38
38
  * 1. `explicitPath` (passed via `--coverage-summary`)
39
- * 2. `<projectRoot>/coverage/coverage-summary.json` (c8 wrapper default)
39
+ * 2. `<projectRoot>/coverage/coverage-summary.json` (the coverage run's default)
40
40
  * 3. `<projectRoot>/openspec/coverage-summary.json` (per-project override)
41
41
  *
42
42
  * Returns:
@@ -238,7 +238,7 @@ function parseCapabilityRow(line) {
238
238
  * - File path: returns `[file]`.
239
239
  * - Directory path: returns every `*.ts` file recursively under it (relative
240
240
  * to `projectRoot`, POSIX separators). Non-TS files are excluded because
241
- * c8 only collects coverage on TS source modules.
241
+ * the summary only carries TS source modules.
242
242
  */
243
243
  export async function resolveCapabilityFiles(input) {
244
244
  const abs = resolve(input.projectRoot, input.row.source);
@@ -280,7 +280,7 @@ async function walkTsFiles(absRoot, projectRoot) {
280
280
  // ---------------------------------------------------------------------------
281
281
  /**
282
282
  * Validate per-capability coverage. Each capability row's `source` is resolved
283
- * to one or more files; each file must appear in the c8 summary with all four
283
+ * to one or more files; each file must appear in the summary with all four
284
284
  * metrics at exactly 100%.
285
285
  *
286
286
  * Returns `{ ok: true }` when every capability passes; `{ ok: false, mismatches }`
@@ -336,7 +336,7 @@ export async function validateCapabilityCoverage(input) {
336
336
  // ---------------------------------------------------------------------------
337
337
  /**
338
338
  * Compare the mtime of every spec/proposal/tasks file under the change against
339
- * the mtime of the c8 summary. If any change file is newer than the summary,
339
+ * the mtime of the summary. If any change file is newer than the summary,
340
340
  * the captured V8 counters no longer match the source on disk and the summary
341
341
  * is stale.
342
342
  *
@@ -38,7 +38,7 @@ export type CoverageEvidence = {
38
38
  capabilityRows: ReadonlyArray<CapabilityMappingRow>;
39
39
  /** Resolved coverage-summary.json absolute path (Fix-6B). */
40
40
  summaryPath?: string;
41
- /** Freshness status of the c8 summary relative to change files. */
41
+ /** Freshness status of the summary relative to change files. */
42
42
  summaryStatus: 'missing' | 'stale' | 'fresh' | 'unavailable';
43
43
  /** Per-capability validation outcome. */
44
44
  capabilityValidation: 'ok' | 'mismatch' | 'no-mapping' | 'not-enforced';
@@ -218,7 +218,7 @@ export async function archiveOpenSpecChange(changeId, options = {}) {
218
218
  });
219
219
  }
220
220
  }
221
- // --- Fix-6B: parse Capability Mapping block + validate against c8 summary ---
221
+ // --- Fix-6B: parse Capability Mapping block + validate against the summary ---
222
222
  const mapping = await parseCapabilityMapping(proposalPath);
223
223
  coverage = {
224
224
  ...coverage,
@@ -245,7 +245,7 @@ export async function archiveOpenSpecChange(changeId, options = {}) {
245
245
  ? summaryPathResult.error.triedPaths
246
246
  : [summaryPathResult.error.path];
247
247
  throw new OpenSpecArchiveError('OPENSPEC_COVERAGE_EVIDENCE_MISSING', `Refusing to archive "${changeId}": no coverage-summary.json found at any of: ${triedPaths.join(', ')}. ` +
248
- 'Run `pnpm test:coverage` (which invokes scripts/coverage-c8.mjs) to generate one, ' +
248
+ 'Generate coverage/coverage-summary.json with the project coverage run (`.husky/coverage-ratchet.mjs` here), ' +
249
249
  'or pass --coverage-summary <path> to point at an existing summary, ' +
250
250
  'or re-run with --force to bypass.', {
251
251
  changeId,
@@ -260,7 +260,7 @@ export async function archiveOpenSpecChange(changeId, options = {}) {
260
260
  }
261
261
  catch (error) {
262
262
  throw new OpenSpecArchiveError('OPENSPEC_COVERAGE_EVIDENCE_MISSING', `Refusing to archive "${changeId}": coverage-summary.json at ${summaryPathResult.value} is malformed (${error.message}). ` +
263
- 'Re-run `pnpm test:coverage` to regenerate, or pass --coverage-summary <path> to point at a valid summary.', { changeId, path: summaryPathResult.value, coverage });
263
+ 'Re-generate coverage/coverage-summary.json, or pass --coverage-summary <path> to point at a valid summary.', { changeId, path: summaryPathResult.value, coverage });
264
264
  }
265
265
  coverage = {
266
266
  ...coverage,
@@ -279,7 +279,7 @@ export async function archiveOpenSpecChange(changeId, options = {}) {
279
279
  staleFiles
280
280
  };
281
281
  throw new OpenSpecArchiveError('OPENSPEC_COVERAGE_EVIDENCE_STALE', `Refusing to archive "${changeId}": coverage-summary.json is older than ${staleFiles.length} change file(s). ` +
282
- 'Re-run `pnpm test:coverage` to refresh, or re-run with --force to bypass.', { changeId, staleFiles, summaryPath: summary.path, coverage });
282
+ 'Re-generate coverage/coverage-summary.json to refresh, or re-run with --force to bypass.', { changeId, staleFiles, summaryPath: summary.path, coverage });
283
283
  }
284
284
  coverage = {
285
285
  ...coverage,
@@ -301,8 +301,8 @@ export async function archiveOpenSpecChange(changeId, options = {}) {
301
301
  coverageMismatchBypassed = true;
302
302
  }
303
303
  else {
304
- throw new OpenSpecArchiveError('OPENSPEC_COVERAGE_EVIDENCE_MISMATCH', `Refusing to archive "${changeId}": ${validation.mismatches.length} capability row(s) claim "covered" in proposal.md but c8 reports < 100% coverage. ` +
305
- 'Re-run `pnpm test:coverage` after closing the gap, or re-run with --force to bypass.', {
304
+ throw new OpenSpecArchiveError('OPENSPEC_COVERAGE_EVIDENCE_MISMATCH', `Refusing to archive "${changeId}": ${validation.mismatches.length} capability row(s) claim "covered" in proposal.md but the coverage summary reports < 100% coverage. ` +
305
+ 'Re-generate coverage/coverage-summary.json after closing the gap, or re-run with --force to bypass.', {
306
306
  changeId,
307
307
  mismatches: validation.mismatches,
308
308
  coverage
@@ -13,12 +13,19 @@ export type ChangedFiles = {
13
13
  baselinePathFor(file: string): string;
14
14
  };
15
15
  /**
16
- * The changed-file population the scan measures, as `git diff --name-status`
17
- * reports it. `A`/`M` keep their path; `R`/`C` keep the TARGET path and record
18
- * the source, so the rename is judged against the size the file had before it
19
- * moved; `D` is dropped. A git failure here THROWS rather than returning `[]`.
20
- *
21
- * `only` is the caller's own list, when it has one — see `restrictedTo`.
16
+ * One git enumeration for both readers that need the change set: the declared-
17
+ * type rule judges `changedPaths` (deletions included), and the size scan
18
+ * measures `changedFiles` (the A/M/R/untracked subset). Two spawns total,
19
+ * `git diff` + `git ls-files`, never one pair per reader.
20
+ */
21
+ export type GitChangeSet = {
22
+ changedPaths: string[];
23
+ changedFiles: ChangedFiles;
24
+ };
25
+ export declare function readGitChangeSet(projectRoot: string, baseRef: string, only?: readonly string[]): GitChangeSet;
26
+ /**
27
+ * The measurable subset alone. Kept as the size scan's entry point; the
28
+ * transition gate calls `readGitChangeSet` so the type rule shares the read.
22
29
  */
23
30
  export declare function readChangedFiles(projectRoot: string, baseRef: string, only?: readonly string[]): ChangedFiles;
24
31
  /** The file's raw-line count AT `baseRef`, or `null` when the ref has no such
@@ -57,11 +57,10 @@ export class GitReadFailedError extends Error {
57
57
  this.name = 'GitReadFailedError';
58
58
  }
59
59
  }
60
- function gitLines(projectRoot, args) {
60
+ function gitNul(projectRoot, args) {
61
61
  let raw;
62
62
  try {
63
63
  raw = execFileSync('git', ['-C', projectRoot, ...args], {
64
- encoding: 'utf8',
65
64
  windowsHide: true
66
65
  });
67
66
  }
@@ -69,10 +68,12 @@ function gitLines(projectRoot, args) {
69
68
  const detail = error instanceof Error ? (error.message.split('\n')[0] ?? '') : String(error);
70
69
  throw new GitReadFailedError(`\`git ${args.join(' ')}\``, projectRoot, detail);
71
70
  }
71
+ // `-z` suppresses C-quoting (core.quotePath), so a non-ASCII name arrives as
72
+ // the real path rather than `"src/\303\251.ts"`; NUL is the only separator.
72
73
  return raw
73
- .split(/\r?\n/)
74
- .map((line) => line.trim())
75
- .filter(Boolean);
74
+ .toString('utf8')
75
+ .split('\0')
76
+ .filter((entry) => entry.length > 0);
76
77
  }
77
78
  /**
78
79
  * The caller's list, intersected with what git reports — or the whole change set when
@@ -91,36 +92,58 @@ function restrictedTo(all, only) {
91
92
  const wanted = new Set(only.map(normalizePolicyPath));
92
93
  return all.filter((file) => wanted.has(normalizePolicyPath(file)));
93
94
  }
94
- /**
95
- * The changed-file population the scan measures, as `git diff --name-status`
96
- * reports it. `A`/`M` keep their path; `R`/`C` keep the TARGET path and record
97
- * the source, so the rename is judged against the size the file had before it
98
- * moved; `D` is dropped. A git failure here THROWS rather than returning `[]`.
99
- *
100
- * `only` is the caller's own list, when it has one — see `restrictedTo`.
101
- */
102
- export function readChangedFiles(projectRoot, baseRef, only) {
103
- const paths = [];
104
- const renameSources = new Map();
105
- for (const line of gitLines(projectRoot, ['diff', '--name-status', baseRef])) {
106
- const [status, first, second] = line.split('\t');
107
- if (status === undefined || first === undefined)
108
- continue;
109
- if ((status.startsWith('R') || status.startsWith('C')) && second !== undefined) {
110
- paths.push(second);
111
- renameSources.set(second, first);
112
- }
113
- else if (status.startsWith('A') || status.startsWith('M')) {
114
- paths.push(first);
115
- }
95
+ /** One `--name-status -z` entry into the accumulator. Extracted because the
96
+ * inline form pushed `readGitChangeSet` past the complexity cap. */
97
+ function appendEntry(status, fields, acc) {
98
+ if (status.startsWith('R') || status.startsWith('C')) {
99
+ const from = fields[0];
100
+ const to = fields[1];
101
+ if (from === undefined || to === undefined)
102
+ return;
103
+ acc.changedPaths.push(...(status.startsWith('R') ? [from] : []), to);
104
+ acc.measurable.push(to);
105
+ acc.renameSources.set(to, from);
106
+ return;
116
107
  }
117
- const untracked = gitLines(projectRoot, ['ls-files', '--others', '--exclude-standard']);
118
- const allPaths = Array.from(new Set([...paths, ...untracked]));
108
+ const path = fields[0];
109
+ if (path === undefined)
110
+ return;
111
+ acc.changedPaths.push(path);
112
+ if (status.startsWith('A') || status.startsWith('M'))
113
+ acc.measurable.push(path);
114
+ }
115
+ export function readGitChangeSet(projectRoot, baseRef, only) {
116
+ const acc = { changedPaths: [], measurable: [], renameSources: new Map() };
117
+ const tokens = gitNul(projectRoot, [
118
+ 'diff',
119
+ '--name-status',
120
+ '--relative',
121
+ '-z',
122
+ '--end-of-options',
123
+ baseRef
124
+ ]);
125
+ for (let i = 0; i < tokens.length;) {
126
+ const status = tokens[i++] ?? '';
127
+ const count = status.startsWith('R') || status.startsWith('C') ? 2 : 1;
128
+ appendEntry(status, tokens.slice(i, i + count), acc);
129
+ i += count;
130
+ }
131
+ const untracked = gitNul(projectRoot, ['ls-files', '--others', '--exclude-standard', '-z']);
119
132
  return {
120
- paths: restrictedTo(allPaths, only),
121
- baselinePathFor: (file) => renameSources.get(file) ?? file
133
+ changedPaths: Array.from(new Set([...acc.changedPaths, ...untracked])),
134
+ changedFiles: {
135
+ paths: restrictedTo(Array.from(new Set([...acc.measurable, ...untracked])), only),
136
+ baselinePathFor: (file) => acc.renameSources.get(file) ?? file
137
+ }
122
138
  };
123
139
  }
140
+ /**
141
+ * The measurable subset alone. Kept as the size scan's entry point; the
142
+ * transition gate calls `readGitChangeSet` so the type rule shares the read.
143
+ */
144
+ export function readChangedFiles(projectRoot, baseRef, only) {
145
+ return readGitChangeSet(projectRoot, baseRef, only).changedFiles;
146
+ }
124
147
  /**
125
148
  * Whether `git cat-file -e` could resolve `<baseRef>:<file>`, i.e. whether the
126
149
  * probe EXITED ZERO. What a non-zero exit actually measures is wider than "the
@@ -1,3 +1,4 @@
1
+ import { type ChangedFiles } from './file-size-baseline.js';
1
2
  /**
2
3
  * Paths exempt from the file-size cap. The cap is Karpathy's "Simplicity
3
4
  * First": it exists to make a human *simplify* an over-long file. A path is
@@ -99,19 +100,11 @@ export type FileSizeScanOptions = {
99
100
  * git alone decides the population.
100
101
  */
101
102
  files?: readonly string[];
103
+ /**
104
+ * A change set the caller already read (the transition gate shares one read
105
+ * with the declared-type rule). When present, NO git enumeration runs here;
106
+ * `files` restriction is the caller's responsibility.
107
+ */
108
+ changedFiles?: ChangedFiles;
102
109
  };
103
- /**
104
- * The diff-scoped scan, judged as a RATCHET: a changed file is a violation only
105
- * when THIS change enlarged it — it grew past its cap, or was created over it.
106
- * A file that is over its cap but no larger than its own state at `baseRef`
107
- * passes, because the baseline already carries it as an accepted over-cap
108
- * quantity (`ceilings.fileSizeOverCap`) and `request transition rd →
109
- * implemented` refusing to touch any of those files is the contradiction that
110
- * blocked two consecutive slices. A rename is judged against the size the file
111
- * had before it moved, so moving a file is not itself growth.
112
- *
113
- * THROWS `GitReadFailedError` when git cannot enumerate the changed files (an
114
- * unresolvable `baseRef`, a non-repo path) — an empty list must mean "nothing
115
- * changed", never "the read failed". `readChangedFiles` owns that refusal.
116
- */
117
110
  export declare function scanFileSize(options: FileSizeScanOptions): FileSizeScanResult;
@@ -125,12 +125,17 @@ function policyCapFor(file, override) {
125
125
  * unresolvable `baseRef`, a non-repo path) — an empty list must mean "nothing
126
126
  * changed", never "the read failed". `readChangedFiles` owns that refusal.
127
127
  */
128
+ /** The change set: the caller's already-read one, or one enumeration. Kept out
129
+ * of `scanFileSize` so the `??` does not push the scan past its complexity cap. */
130
+ function changesFor(options, baseRef) {
131
+ return options.changedFiles ?? readChangedFiles(options.projectRoot, baseRef, options.files);
132
+ }
128
133
  export function scanFileSize(options) {
129
134
  const baseRef = options.baseRef ?? 'HEAD';
130
135
  // `null` here means "the policy decides, per file" — the cap is a property of
131
136
  // the path (300 raw lines; 500 under root `tests/`), not of the run.
132
137
  const override = options.threshold ?? null;
133
- const changed = readChangedFiles(options.projectRoot, baseRef, options.files);
138
+ const changed = changesFor(options, baseRef);
134
139
  const violations = [];
135
140
  const deletedFiles = [];
136
141
  const exemptFiles = [];
@@ -0,0 +1,32 @@
1
+ /**
2
+ * `corroborateDeclaredType` — the declared request type judged against what the
3
+ * change actually touches. A `docs | chore | config` rid selects a reduced
4
+ * prerequisite table, so it may not carry product source.
5
+ *
6
+ * Split out of `type-sanity-service.ts` when that file reached its 300-line cap.
7
+ * It reuses `tryGitDiffFiles` (the SAME enumeration `checkTypeSanity` reads), so
8
+ * the two rules cannot drift; unlike `checkTypeSanity`, it FAILS CLOSED when git
9
+ * cannot enumerate.
10
+ */
11
+ import type { RequestType } from '../artifacts/artifact-prerequisites.js';
12
+ import { type TypeSanityOptions } from './type-sanity-service.js';
13
+ /** True when the path is product source by the repository's own boundary. */
14
+ export declare function isProductSourcePath(filePath: string): boolean;
15
+ /** True for the three types this rule judges (and bypasses are recorded for). */
16
+ export declare function isToolingOnlyDeclaredType(declaredType: RequestType): boolean;
17
+ export type TypeCorroboration = {
18
+ ok: true;
19
+ } | {
20
+ ok: false;
21
+ kind: 'source-touched' | 'diff-unavailable';
22
+ message: string;
23
+ };
24
+ export type TypeCorroborationOptions = TypeSanityOptions & {
25
+ /** A change set the caller already enumerated; skips the git read. */
26
+ changedPaths?: readonly string[];
27
+ };
28
+ /** The fail-closed verdict, shared with the transition gate's own read. */
29
+ export declare function diffUnavailableVerdict(declaredType: RequestType, baseRef?: string): Extract<TypeCorroboration, {
30
+ ok: false;
31
+ }>;
32
+ export declare function corroborateDeclaredType(options: TypeCorroborationOptions): TypeCorroboration;
@@ -0,0 +1,51 @@
1
+ import { normalizePath } from '../../shared/path-utils.js';
2
+ import { isArtifactWorkspaceFile, tryGitDiffFiles } from './type-sanity-service.js';
3
+ const TOOLING_ONLY_DECLARED_TYPES = new Set(['docs', 'chore', 'config']);
4
+ /** `src/**` + `packages/<name>/src/**` — the rule `.husky/lint-scope.mjs` owns.
5
+ * `tests/unit/lint/lint-scope-rule.test.ts` binds this copy to that module. */
6
+ const PACKAGE_SOURCE_RE = /^packages\/[^/]+\/src\//;
7
+ /** True when the path is product source by the repository's own boundary. */
8
+ export function isProductSourcePath(filePath) {
9
+ const normalized = normalizePath(filePath);
10
+ return normalized.startsWith('src/') || PACKAGE_SOURCE_RE.test(normalized);
11
+ }
12
+ /** True for the three types this rule judges (and bypasses are recorded for). */
13
+ export function isToolingOnlyDeclaredType(declaredType) {
14
+ return TOOLING_ONLY_DECLARED_TYPES.has(declaredType);
15
+ }
16
+ /** The fail-closed verdict, shared with the transition gate's own read. */
17
+ export function diffUnavailableVerdict(declaredType, baseRef = 'HEAD') {
18
+ return {
19
+ ok: false,
20
+ kind: 'diff-unavailable',
21
+ message: `Declared type '${declaredType}' could not be corroborated: git could not enumerate ` +
22
+ `the changed files against '${baseRef}' (not a repo, or the ref is unreadable). ` +
23
+ 'This gate fails closed — an unreadable diff is not an empty diff.'
24
+ };
25
+ }
26
+ export function corroborateDeclaredType(options) {
27
+ if (!isToolingOnlyDeclaredType(options.declaredType))
28
+ return { ok: true };
29
+ const baseRef = options.baseRef ?? 'HEAD';
30
+ let files;
31
+ if (options.changedPaths !== undefined) {
32
+ files = options.changedPaths.filter((file) => !isArtifactWorkspaceFile(file));
33
+ }
34
+ else {
35
+ const read = tryGitDiffFiles(options.projectRoot, baseRef);
36
+ if (!read.ok)
37
+ return diffUnavailableVerdict(options.declaredType, baseRef);
38
+ files = read.files;
39
+ }
40
+ const offendingPaths = files.filter(isProductSourcePath);
41
+ if (offendingPaths.length === 0)
42
+ return { ok: true };
43
+ return {
44
+ ok: false,
45
+ kind: 'source-touched',
46
+ message: `Declared type '${options.declaredType}' cannot change product source: ${offendingPaths.join(', ')}. ` +
47
+ 'A docs/chore/config request selects a reduced prerequisite table, so it may not carry ' +
48
+ 'src/** or packages/<name>/src/** changes. Declare feature, bugfix or refactor (which carry ' +
49
+ 'the full QA evidence), or move the change out of product source.'
50
+ };
51
+ }
@@ -20,4 +20,18 @@ export type TypeSanityOptions = {
20
20
  /** Compare working tree against this ref. Default 'HEAD' (covers staged + unstaged). */
21
21
  baseRef?: string;
22
22
  };
23
+ /**
24
+ * Peaks' own artifact workspace. Changes here (PRD/RD/QA markdown, session
25
+ * state) are never the "code change" a request type describes, so they must be
26
+ * excluded from the diff — otherwise a PRD-planning-phase handoff that only
27
+ * wrote `.peaks/**` markdown would be misclassified as a docs change.
28
+ */
29
+ export declare function isArtifactWorkspaceFile(filePath: string): boolean;
30
+ /** The ONE git enumeration: tracked changes vs `baseRef` plus untracked files.
31
+ * `readGitChangeSet` is NUL-safe and `--relative`, so non-ASCII names and a
32
+ * nested project root are both read correctly. */
33
+ export declare function tryGitDiffFiles(projectRoot: string, baseRef: string): {
34
+ ok: boolean;
35
+ files: string[];
36
+ };
23
37
  export declare function checkTypeSanity(options: TypeSanityOptions): TypeSanityReport;
@@ -1,6 +1,6 @@
1
- import { execFileSync } from 'node:child_process';
2
1
  import { extname, basename } from 'node:path';
3
2
  import { normalizePath } from '../../shared/path-utils.js';
3
+ import { readGitChangeSet } from './file-size-baseline.js';
4
4
  const SOURCE_EXTENSIONS = new Set([
5
5
  '.ts',
6
6
  '.tsx',
@@ -116,28 +116,19 @@ function classifyFile(filePath) {
116
116
  * excluded from the diff — otherwise a PRD-planning-phase handoff that only
117
117
  * wrote `.peaks/**` markdown would be misclassified as a docs change.
118
118
  */
119
- function isArtifactWorkspaceFile(filePath) {
119
+ export function isArtifactWorkspaceFile(filePath) {
120
120
  const normalized = normalizePath(filePath);
121
121
  return normalized === '.peaks' || normalized.startsWith('.peaks/');
122
122
  }
123
- function tryGitDiffFiles(projectRoot, baseRef) {
123
+ /** The ONE git enumeration: tracked changes vs `baseRef` plus untracked files.
124
+ * `readGitChangeSet` is NUL-safe and `--relative`, so non-ASCII names and a
125
+ * nested project root are both read correctly. */
126
+ export function tryGitDiffFiles(projectRoot, baseRef) {
124
127
  try {
125
- // Combine: tracked changes vs baseRef + untracked files. Use porcelain status for untracked too.
126
- const trackedRaw = execFileSync('git', ['-C', projectRoot, 'diff', '--name-only', baseRef], {
127
- encoding: 'utf8',
128
- windowsHide: true
129
- });
130
- const tracked = trackedRaw
131
- .split(/\r?\n/)
132
- .map((line) => line.trim())
133
- .filter(Boolean);
134
- const untrackedRaw = execFileSync('git', ['-C', projectRoot, 'ls-files', '--others', '--exclude-standard'], { encoding: 'utf8', windowsHide: true });
135
- const untracked = untrackedRaw
136
- .split(/\r?\n/)
137
- .map((line) => line.trim())
138
- .filter(Boolean);
139
- const merged = Array.from(new Set([...tracked, ...untracked])).filter((file) => !isArtifactWorkspaceFile(file));
140
- return { ok: true, files: merged };
128
+ return {
129
+ ok: true,
130
+ files: readGitChangeSet(projectRoot, baseRef).changedPaths.filter((file) => !isArtifactWorkspaceFile(file))
131
+ };
141
132
  }
142
133
  catch {
143
134
  return { ok: false, files: [] };
@@ -6,6 +6,11 @@ export declare function dispatchRecordsDir(projectRoot: string, sid: string): st
6
6
  * Assert that `recordPath` lives under `projectRoot/.peaks/_sub_agents/<sid>/`.
7
7
  * Rejects symlink/junction escapes and `..` segments.
8
8
  *
9
+ * `projectRoot` and `recordPath` may be two spellings of the same directory —
10
+ * macOS resolves `/var` (and `/tmp`) into `/private`, so `os.tmpdir()` and the
11
+ * kernel disagree — and that is accepted, not refused. See the comparison
12
+ * below.
13
+ *
9
14
  * Throws an Error with `.code = 'INVALID_RECORD_PATH'` on rejection so
10
15
  * the CLI can map to `{ok: false, code: "INVALID_RECORD_PATH"}`.
11
16
  */
@@ -16,6 +16,7 @@
16
16
  */
17
17
  import { realpathSync } from 'node:fs';
18
18
  import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
19
+ import { stablePath } from '../../shared/path-utils.js';
19
20
  const SUB_AGENTS_DIR = '_sub_agents';
20
21
  /** Build the canonical record path for a given session/rid/timestamp. */
21
22
  export function dispatchRecordPath(projectRoot, sid, rid, ts = new Date()) {
@@ -33,6 +34,11 @@ export function dispatchRecordsDir(projectRoot, sid) {
33
34
  * Assert that `recordPath` lives under `projectRoot/.peaks/_sub_agents/<sid>/`.
34
35
  * Rejects symlink/junction escapes and `..` segments.
35
36
  *
37
+ * `projectRoot` and `recordPath` may be two spellings of the same directory —
38
+ * macOS resolves `/var` (and `/tmp`) into `/private`, so `os.tmpdir()` and the
39
+ * kernel disagree — and that is accepted, not refused. See the comparison
40
+ * below.
41
+ *
36
42
  * Throws an Error with `.code = 'INVALID_RECORD_PATH'` on rejection so
37
43
  * the CLI can map to `{ok: false, code: "INVALID_RECORD_PATH"}`.
38
44
  */
@@ -48,8 +54,22 @@ export function assertSafeDispatchRecordPath(recordPath, projectRoot) {
48
54
  if (rawSegments.includes('..')) {
49
55
  throw invalidPathError(recordPath, 'must not contain .. segments');
50
56
  }
51
- const expected = resolve(projectRoot, '.peaks', SUB_AGENTS_DIR);
52
- const rel = relative(expected, recordPath);
57
+ // Compare the two on their CANONICAL spellings, not on the caller's, because
58
+ // they are routinely two spellings of ONE directory: macOS resolves `/var`
59
+ // into `/private/var` while `os.tmpdir()` hands out the unresolved form, and
60
+ // any caller can reach its project through a junction. Compared raw, the two
61
+ // share no leading segment, `relative()` walks to the project root and a
62
+ // legitimate record is refused as though it had escaped the ledger.
63
+ // `stablePath` is preferred here because it resolves the deepest EXISTING
64
+ // ancestor and re-appends the missing tail — the common case, since the
65
+ // record usually does not exist yet. It is NOT the primitive
66
+ // `projectRootCompareKey` is built from; that key uses `stableRealPath`,
67
+ // which does not walk up and adds separator and Windows-only case folding.
68
+ // They are siblings with different behaviour. Nor swap it for a bare
69
+ // `realpathSync`, whose `.native` variant also rewrites Windows 8.3 short
70
+ // names (see `projectRootCompareKey`'s doc-comment) and is not a drop-in.
71
+ const expected = resolve(canonicalSpelling(projectRoot), '.peaks', SUB_AGENTS_DIR);
72
+ const rel = relative(expected, canonicalSpelling(recordPath));
53
73
  if (rel.startsWith('..') || isAbsolute(rel)) {
54
74
  throw invalidPathError(recordPath, 'must be under .peaks/_sub_agents/');
55
75
  }
@@ -71,12 +91,15 @@ export function assertSafeDispatchRecordPath(recordPath, projectRoot) {
71
91
  // canonical projectRoot — the write will then create the file,
72
92
  // and any symlink in the parent will be caught on the next read.
73
93
  //
74
- // macOS note: the project's own realpath may still resolve the
75
- // `/var -> /private/var` symlink even when the sub-agent dir does
76
- // not exist yet, so the caller can compare on a stable prefix
77
- // instead of having one side of the comparison on `/var/...` and
78
- // the other on `/private/var/...`. We still validate that the
79
- // canonical record path lives under the canonical projectRoot.
94
+ // What this branch returns is the record path rebuilt under the CANONICAL
95
+ // projectRoot, so the caller writes, indexes and hands back a stable
96
+ // spelling. The alias tolerance that GETS here belongs to the canonical
97
+ // comparison above; this branch does NOT inherit it. `fallback` is built
98
+ // from the caller's `projectRoot`, and `recordPath` is compared here as the
99
+ // caller spelled it, so an aliased root beside a canonical record and a
100
+ // not-yet-created parent is still REFUSED by the comparison below — the
101
+ // same alias defect this change repairs, surviving in this one branch. It
102
+ // is fail-closed: it refuses a legitimate record; it never admits an escape.
80
103
  const fallback = resolve(projectRoot, '.peaks', SUB_AGENTS_DIR);
81
104
  const rel2 = relative(fallback, recordPath);
82
105
  if (rel2.startsWith('..') || isAbsolute(rel2)) {
@@ -101,6 +124,39 @@ export function assertSafeDispatchRecordPath(recordPath, projectRoot) {
101
124
  }
102
125
  return realRecord;
103
126
  }
127
+ /**
128
+ * `path` with its existing prefix symlink-resolved, or the raw spelling when
129
+ * the filesystem will not resolve it (a locked or vanishing ancestor).
130
+ *
131
+ * The fallback is what keeps this guard's contract intact: it promises to
132
+ * REJECT with `INVALID_RECORD_PATH`, and a raw `realpathSync` that threw here
133
+ * would surface as a crash on the dispatch write path instead. Its cost is
134
+ * stronger than a different refusal shape, though: the throw reverts the
135
+ * comparison to the pre-fix one, so on an aliased root the bug returns for that
136
+ * call — a legitimate record refused, not merely refused differently.
137
+ *
138
+ * The swallow is NOT fail-closed, which an earlier draft of this comment
139
+ * claimed. Measured in scratch copies of this guard: reverting the recordPath
140
+ * side of the comparison above to its raw spelling, ALONE, re-admits all three
141
+ * escape shapes that comparison closes — a `_sub_agents` junction pointing
142
+ * outside with the session dir missing, the in-repo sibling junction, and an
143
+ * existing leaf file-symlink pointing outside. Reverting both sides reproduces
144
+ * the pre-fix guard. A throw here therefore GROWS the admitted set rather than
145
+ * shrinking it. Nothing known makes `stablePath` throw on this input — a
146
+ * self-referential or deep junction, and every dangling link, make `existsSync`
147
+ * false so the peel loop runs instead — so the path is unverified, not cleared.
148
+ * The swallow stays anyway: refusing it trades this guard's refusal contract
149
+ * for a crash on the dispatch write path, and `stablePath` does not throw for a
150
+ * `projectRoot` that does not exist (verified by reading it).
151
+ */
152
+ function canonicalSpelling(path) {
153
+ try {
154
+ return stablePath(path);
155
+ }
156
+ catch {
157
+ return path;
158
+ }
159
+ }
104
160
  function sanitizeSegment(segment, label) {
105
161
  if (typeof segment !== 'string' || segment.length === 0) {
106
162
  throw new Error(`Invalid ${label}: empty`);
@@ -31,6 +31,7 @@
31
31
  */
32
32
  import { existsSync, readdirSync, readFileSync } from 'node:fs';
33
33
  import { join } from 'node:path';
34
+ import { requestIdFromFileName } from '../../shared/incrementing-number.js';
34
35
  import { readArtifactState } from '../artifacts/request-artifact-state-helpers.js';
35
36
  const MID_IMPL_RD_STATES = new Set([
36
37
  'spec-locked',
@@ -330,16 +331,15 @@ function extractState(content) {
330
331
  return readArtifactState(content) ?? '';
331
332
  }
332
333
  /**
333
- * The `<rid>` embedded in a request filename: drop the `.md` suffix and the
334
- * zero-padded `NNN-` prefix `request init` writes.
335
- *
336
- * Uses the same `^0\d{2}-` rule as the request loader
337
- * (`request-artifact-service.ts`: "Only strip 3-digit zero-padded prefixes").
338
- * A looser `^\d+-` would eat the leading year of every real rid, which is
339
- * itself date-shaped (`2026-09-14-<slug>`).
334
+ * The `<rid>` a request filename carries: the `.md` suffix and the `<NNN>-` prefix
335
+ * `request init` writes, both dropped by the reader that owns them — so this
336
+ * module cannot be left behind by a writer that moves the family. It used to spell
337
+ * its own `^0\d{2}-` here, which agreed with that reader only until the family was
338
+ * widened, and then reported a different id for the same file. A looser `^\d+-`
339
+ * would instead eat the leading year of every real rid, which is date-shaped.
340
340
  */
341
341
  function ridOf(filename) {
342
- return filename.replace(/^0\d{2}-/, '').replace(/\.md$/, '');
342
+ return requestIdFromFileName(filename) ?? filename.replace(/\.md$/, '');
343
343
  }
344
344
  function hasAbandonedTransitionNote(content) {
345
345
  return /user-requested-abandon/.test(content);