peaks-loop 4.1.23 → 4.1.25

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 (66) hide show
  1. package/.claude-plugin/marketplace.json +12 -2
  2. package/CHANGELOG.md +188 -0
  3. package/dist/cli/commands/code-auto-compact-command.js +19 -1
  4. package/dist/cli/commands/code-gate-step-08-command.js +103 -105
  5. package/dist/cli/commands/code-gate-step-08-remedy.d.ts +10 -2
  6. package/dist/cli/commands/code-gate-step-08-remedy.js +11 -3
  7. package/dist/cli/commands/gate-commands-enforce.d.ts +14 -8
  8. package/dist/cli/commands/gate-commands-enforce.js +31 -24
  9. package/dist/cli/commands/observability-commands-session-row.d.ts +48 -0
  10. package/dist/cli/commands/observability-commands-session-row.js +201 -0
  11. package/dist/cli/commands/observability-commands.js +2 -0
  12. package/dist/services/artifacts/prerequisite-path-census.d.ts +8 -3
  13. package/dist/services/artifacts/prerequisite-path-census.js +30 -9
  14. package/dist/services/artifacts/prerequisite-path-resolver.js +32 -2
  15. package/dist/services/hooks/output.d.ts +35 -1
  16. package/dist/services/hooks/output.js +39 -1
  17. package/dist/services/observability/aggregation.js +2 -1
  18. package/dist/services/observability/hotspot-shared.d.ts +7 -12
  19. package/dist/services/observability/hotspot-shared.js +18 -13
  20. package/dist/services/observability/near-miss-difference.js +4 -1
  21. package/dist/services/observability/near-miss.js +9 -2
  22. package/dist/services/observability/owner-skill-map.js +23 -3
  23. package/dist/services/observability/repair-cycle-metric.js +6 -3
  24. package/dist/services/skills/presence-role.js +9 -2
  25. package/dist/services/standards/loop-engineering-readiness-lint.d.ts +15 -1
  26. package/dist/services/standards/loop-engineering-readiness-lint.js +27 -9
  27. package/dist/shared/incrementing-number.d.ts +57 -0
  28. package/dist/shared/incrementing-number.js +13 -0
  29. package/dist/skills/peaks-maker/index.js +43 -30
  30. package/output-styles/peaks-skill-swarm.md +2 -2
  31. package/package.json +7 -6
  32. package/scripts/install-skills-bundles.mjs +6 -1
  33. package/scripts/install-skills.mjs +10 -1
  34. package/skills/bee/peaks-perf-audit/SKILL.md +1 -1
  35. package/skills/bee/peaks-prd/SKILL.md +1 -1
  36. package/skills/bee/peaks-qa/SKILL.md +1 -1
  37. package/skills/bee/peaks-rd/SKILL.md +1 -1
  38. package/skills/bee/peaks-reviewer/SKILL.md +1 -1
  39. package/skills/bee/peaks-sc/SKILL.md +1 -1
  40. package/skills/bee/peaks-security-audit/SKILL.md +1 -1
  41. package/skills/bee/peaks-txt/SKILL.md +1 -1
  42. package/skills/bee/peaks-ui/SKILL.md +1 -1
  43. package/skills/peaks-audit/SKILL.md +1 -1
  44. package/skills/peaks-code/SKILL.md +1 -1
  45. package/skills/peaks-content/SKILL.md +1 -1
  46. package/skills/peaks-doctor/SKILL.md +1 -1
  47. package/skills/peaks-final-review/SKILL.md +1 -1
  48. package/skills/peaks-ide/SKILL.md +1 -1
  49. package/skills/peaks-issue-fix-orchestrator/SKILL.md +1 -1
  50. package/skills/peaks-maker/SKILL.md +125 -0
  51. package/skills/peaks-mut/SKILL.md +297 -0
  52. package/skills/peaks-race-code/SKILL.md +1 -1
  53. package/skills/peaks-resume/SKILL.md +1 -1
  54. package/skills/peaks-slice-decompose/SKILL.md +1 -1
  55. package/skills/peaks-solo/SKILL.md +1 -1
  56. package/skills/peaks-sop/SKILL.md +1 -1
  57. package/skills/peaks-status/SKILL.md +1 -1
  58. package/skills/peaks-test/SKILL.md +1 -1
  59. package/skills/bee/peaks-prd/test-prompts.json +0 -12
  60. package/skills/bee/peaks-qa/test-prompts.json +0 -12
  61. package/skills/bee/peaks-rd/test-prompts.json +0 -12
  62. package/skills/bee/peaks-txt/test-prompts.json +0 -12
  63. package/skills/bee/peaks-ui/test-prompts.json +0 -12
  64. package/skills/peaks-code/test-prompts.json +0 -12
  65. package/skills/peaks-doctor/test_prompts.json +0 -17
  66. package/skills/peaks-sop/test-prompts.json +0 -17
@@ -135,18 +135,32 @@ export function handleWorktreeGate(io, options, toolKind, payload) {
135
135
  return false;
136
136
  }
137
137
  /**
138
- * Not a guarded surface — allow. Emit minimal JSON on stdout so Claude Code's PreToolUse hook
139
- * validator accepts the response. Empty stdout is rejected with "Hook JSON output validation
140
- * failed — Invalid input" in Claude Code 2.x; `{}` is the canonical no-op marker.
138
+ * Emit an allow path: the plain CLI envelope on stdout, and nothing else.
139
+ *
140
+ * The gate's own decision stays under `data`, a key the host does not own, so the
141
+ * host reads no root `decision` at all. The document carries NO `hookSpecificOutput`:
142
+ * an allow is a real permission GRANT — it approves the call and skips the user's own
143
+ * permission prompt — and a gate that passes a call through has no opinion to give.
144
+ * Exit 0 is the pass-through signal, and the call proceeds to the user's normal
145
+ * permission flow.
141
146
  */
142
- export function emitAllowSkipped(io, options) {
147
+ function emitAllowEnvelope(io, options, data) {
143
148
  if (options.json === true) {
144
- printResult(io, ok('gate.enforce', { decision: 'allow', skipped: true }), true);
149
+ printResult(io, ok('gate.enforce', data), true);
145
150
  }
146
151
  else {
147
152
  emitDecision(io, {});
148
153
  }
149
154
  }
155
+ /**
156
+ * Not a guarded surface — allow.
157
+ *
158
+ * The stdout document is the CLI envelope a downstream consumer reads
159
+ * (`JSON.parse(stdout).data.decision`), carrying no permission grant.
160
+ */
161
+ export function emitAllowSkipped(io, options) {
162
+ emitAllowEnvelope(io, options, { decision: 'allow', skipped: true });
163
+ }
150
164
  /**
151
165
  * Hard block: a worktree-mutating tool call without a current-task user grant. emitBlock writes
152
166
  * the Claude Code permissionDecision:"deny" envelope and exits 2. The reason carries the
@@ -159,14 +173,13 @@ function emitWorktreeDeny(io, options, wtDecision) {
159
173
  emitHint(io, JSON.stringify(ok('gate.enforce', { decision: 'deny', layer: 'worktree-auth', ...wtDecision })));
160
174
  }
161
175
  }
162
- /** Worktree gate allowed and this is not a Bash surface — allow without running the SOP gate. */
176
+ /**
177
+ * Worktree gate allowed and this is not a Bash surface — allow without running
178
+ * the SOP gate. Same plain-envelope shape as the skipped path (see
179
+ * {@link emitAllowSkipped}).
180
+ */
163
181
  export function emitAllowWorktree(io, options) {
164
- if (options.json === true) {
165
- printResult(io, ok('gate.enforce', { decision: 'allow', layer: 'worktree-auth' }), true);
166
- }
167
- else {
168
- emitDecision(io, {});
169
- }
182
+ emitAllowEnvelope(io, options, { decision: 'allow', layer: 'worktree-auth' });
170
183
  }
171
184
  /**
172
185
  * writes the Claude Code permissionDecision:"deny" JSON to stdout (the hook's decision signal),
@@ -189,18 +202,12 @@ export function emitSopWarnings(io, decision) {
189
202
  }
190
203
  }
191
204
  /**
192
- * SOP gate allowed the command. --json mode emits the canonical envelope on stdout (the documented
193
- * contract for downstream tooling). The hook decision (allow/deny) is still signalled via
194
- * emitHint here was wrong — emitHint writes to stderr, but the AC5 contract expects the JSON
195
- * envelope on stdout. Switch to printResult(asJson=true).
205
+ * SOP gate allowed the command.
206
+ *
207
+ * `--json` mode emits the canonical envelope on stdout (the documented contract
208
+ * for downstream tooling): ONE JSON document, the gate's decision under `data`, and
209
+ * no permission grant — see {@link emitAllowSkipped} for the shape and the reason.
196
210
  */
197
211
  export function emitSopAllow(io, options, decision) {
198
- if (options.json === true) {
199
- printResult(io, ok('gate.enforce', decision), true);
200
- }
201
- else {
202
- // allow: emit minimal JSON on stdout so Claude Code's PreToolUse hook
203
- // validator accepts the response (see comment above).
204
- emitDecision(io, {});
205
- }
212
+ emitAllowEnvelope(io, options, decision);
206
213
  }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * `src/cli/commands/observability-commands-session-row.ts`
3
+ *
4
+ * `peaks observability session-row` — the production caller of the per-session
5
+ * metric row, and the reader of the compliance rate.
6
+ *
7
+ * WHY IT IS ON DEMAND. The row and the judge had no caller outside their own
8
+ * tests, so neither was reachable. This command is the caller: it reads the
9
+ * scoped session, judges every slice it recorded against the peaks-rd spec,
10
+ * writes the tracked row, and prints the rates it was built from. No session-end
11
+ * hook exists to attach to, so the row is written when the command is asked for.
12
+ *
13
+ * WHY THE RATE IS NULL WHEN NOTHING WAS JUDGED. A compliance rate is the share of
14
+ * declared steps that ran. A session with no judged slice has no such share: 0
15
+ * would read as "judged, and nothing ran", which nothing observed. So the rate
16
+ * is null and the reason says why, the same coverage rule the near-miss rate uses.
17
+ *
18
+ * WHY THE SPEC IS PEAKS-RD ONLY. The fast-lane spec's steps describe a lane that
19
+ * writes no RD artifacts, so judging an RD slice against it would report a rate
20
+ * that measures the wrong skill. Each reading names its spec, so a second spec
21
+ * can be added later without changing the shape.
22
+ */
23
+ import type { Command } from 'commander';
24
+ import { type SessionComplianceReading } from '../../services/observability/session-metric-rows.js';
25
+ import { type ProgramIO } from '../cli-helpers.js';
26
+ import { type ObservabilityQueryOptions } from './observability-commands-queries.js';
27
+ /** The compliance rate of a session, or the reason it was not observed. */
28
+ export type ComplianceSummary = {
29
+ /** The unweighted mean of the judged slices' rates, or null when none was judged. */
30
+ readonly complianceRate: number | null;
31
+ /**
32
+ * Why the rate is null, or why it covers fewer slices than the session
33
+ * recorded. Null when the rate covers every slice the session recorded.
34
+ */
35
+ readonly complianceReason: string | null;
36
+ readonly judgedSliceCount: number;
37
+ /** The recorded slices that could not be judged, and why. */
38
+ readonly rejectedSliceCount: number;
39
+ };
40
+ /** Summarise the readings. An empty set is unobserved, never a zero rate. */
41
+ export declare function summarizeCompliance(readings: readonly SessionComplianceReading[], rejectedSliceCount?: number): ComplianceSummary;
42
+ /**
43
+ * `peaks observability session-row` — write the session's tracked row and print
44
+ * its near-miss and compliance rates.
45
+ */
46
+ export declare function runSessionRow(io: ProgramIO, options: ObservabilityQueryOptions): Promise<void>;
47
+ /** Register `peaks observability session-row` under the observability command. */
48
+ export declare function registerSessionRowCommand(observability: Command, io: ProgramIO): void;
@@ -0,0 +1,201 @@
1
+ /**
2
+ * `src/cli/commands/observability-commands-session-row.ts`
3
+ *
4
+ * `peaks observability session-row` — the production caller of the per-session
5
+ * metric row, and the reader of the compliance rate.
6
+ *
7
+ * WHY IT IS ON DEMAND. The row and the judge had no caller outside their own
8
+ * tests, so neither was reachable. This command is the caller: it reads the
9
+ * scoped session, judges every slice it recorded against the peaks-rd spec,
10
+ * writes the tracked row, and prints the rates it was built from. No session-end
11
+ * hook exists to attach to, so the row is written when the command is asked for.
12
+ *
13
+ * WHY THE RATE IS NULL WHEN NOTHING WAS JUDGED. A compliance rate is the share of
14
+ * declared steps that ran. A session with no judged slice has no such share: 0
15
+ * would read as "judged, and nothing ran", which nothing observed. So the rate
16
+ * is null and the reason says why, the same coverage rule the near-miss rate uses.
17
+ *
18
+ * WHY THE SPEC IS PEAKS-RD ONLY. The fast-lane spec's steps describe a lane that
19
+ * writes no RD artifacts, so judging an RD slice against it would report a rate
20
+ * that measures the wrong skill. Each reading names its spec, so a second spec
21
+ * can be added later without changing the shape.
22
+ */
23
+ import { fail, ok } from 'peaks-loop-shared/result';
24
+ import { PEAKS_RD_SPEC } from '../../services/observability/compliance-specs/peaks-rd.spec.js';
25
+ import { buildSessionMetricRow, judgeSessionCompliance, readSkillsBlobSha, sessionMetricRowPath, writeSessionMetricRow } from '../../services/observability/session-metric-rows.js';
26
+ import { isSinglePathSegment } from '../../services/session/getSessionDir.js';
27
+ import { NUMBERED_PREFIX_RE } from '../../shared/incrementing-number.js';
28
+ import { addJsonOption, getErrorMessage, printResult } from '../cli-helpers.js';
29
+ import { hotspotRequestTypes } from './observability-commands-hotspots.js';
30
+ import { readScopedEvents, resolveProjectRoot, scopeOf, scopeWarnings } from './observability-commands-queries.js';
31
+ /** Summarise the readings. An empty set is unobserved, never a zero rate. */
32
+ export function summarizeCompliance(readings, rejectedSliceCount = 0) {
33
+ const rejectedNote = rejectedSliceCount === 0
34
+ ? null
35
+ : `${rejectedSliceCount} recorded slice id(s) could NOT be judged, because they are ` +
36
+ 'not a single safe path segment — an unobserved slice, not a failed one';
37
+ if (readings.length === 0) {
38
+ // The two reasons are different facts, and the recorded one wins when both
39
+ // hold: a session whose slices were all REJECTED did record slices, so
40
+ // saying "no slice was recorded" would deny the event stream's own content.
41
+ return {
42
+ complianceRate: null,
43
+ complianceReason: rejectedNote ??
44
+ 'no slice was recorded in this session, so no slice was judged and no compliance ' +
45
+ 'rate was observed — an absence of data, not a result',
46
+ judgedSliceCount: 0,
47
+ rejectedSliceCount
48
+ };
49
+ }
50
+ const total = readings.reduce((sum, reading) => sum + reading.complianceRate, 0);
51
+ return {
52
+ complianceRate: total / readings.length,
53
+ complianceReason: rejectedNote,
54
+ judgedSliceCount: readings.length,
55
+ rejectedSliceCount
56
+ };
57
+ }
58
+ /**
59
+ * The distinct slices the session's events name, split by whether they can be
60
+ * judged, together with the spelling each slice is judged under.
61
+ *
62
+ * WHY A SLICE ID IS CHECKED BEFORE IT BECOMES A PATH. The slice id comes from
63
+ * the event stream, and the judge substitutes it into the spec's declared
64
+ * artifact paths before probing the filesystem. A slice id carrying `..` would
65
+ * therefore move the probe OUTSIDE the session directory, and an artifact
66
+ * planted elsewhere would be credited as a step that ran inside the session.
67
+ * The event stream is a file on disk, so its contents are input like any other:
68
+ * the check belongs here, at the boundary where the id becomes a path.
69
+ *
70
+ * The predicate is the repository's own `isSinglePathSegment`, the same one the
71
+ * session id is held to. A legal slice id is a single segment, so nothing a
72
+ * real slice id carries is refused.
73
+ *
74
+ * WHY THE SLICES ARE KEYED ON THE LOGICAL ID AND NOT ON THE RAW STRING. A
75
+ * slice's id arrives in TWO spellings, from two different producers: the
76
+ * request writer stamps `NNN-` on the artifact FILENAME, while the transition
77
+ * CLI is handed the UN-NUMBERED rid — and the event stream carries both. Keyed
78
+ * on the raw string, ONE slice was judged twice, under two spellings that
79
+ * resolve DIFFERENTLY: the resolver finds the artifacts under the numbered
80
+ * spelling and misses most of them under the bare one, so the same slice was
81
+ * counted once at its real rate and once at a rate its artifacts do not
82
+ * support. The rate's denominator was then the count of SPELLINGS rather than
83
+ * the count of slices, so it was not the mean the slice's contract names.
84
+ *
85
+ * The repository's own rule says which spelling is the slice's identity:
86
+ * `NUMBERED_PREFIX_RE` — the family `buildNumberedFilename` writes and
87
+ * `requestIdFromFileName` strips. Stripping it leaves the LOGICAL slice id,
88
+ * and that is what the sets are keyed on.
89
+ *
90
+ * WHY THE NUMBERED SPELLING IS THE ONE JUDGED. The artifacts on disk carry
91
+ * that number — `rd/requests/002-<rid>.md` and `prd/handoff-002-<rid>.md`
92
+ * alike — so the numbered spelling is the one the resolver can actually find
93
+ * them under. A slice the stream named only in its bare spelling is judged
94
+ * under that spelling, because it is the only one it has.
95
+ *
96
+ * WHY THE SAFETY CHECK RUNS BEFORE THE NORMALISATION. The check is on the RAW
97
+ * id, so a hostile multi-segment id is refused rather than normalised into
98
+ * something that looks safe: stripping a leading `NNN-` can only ever REMOVE
99
+ * characters from an id that is already a single safe segment, and can never
100
+ * turn one segment into two or into a traversal.
101
+ */
102
+ function partitionSliceRids(events) {
103
+ const judged = new Map();
104
+ const rejected = new Set();
105
+ for (const event of events) {
106
+ if (event.sliceRid === undefined)
107
+ continue;
108
+ const rid = event.sliceRid;
109
+ if (!isSinglePathSegment(rid)) {
110
+ rejected.add(rid);
111
+ continue;
112
+ }
113
+ const numbered = NUMBERED_PREFIX_RE.test(rid);
114
+ const logical = rid.replace(NUMBERED_PREFIX_RE, '');
115
+ const existing = judged.get(logical);
116
+ if (existing === undefined)
117
+ judged.set(logical, { rid, numbered });
118
+ // A numbered spelling resolves artifacts the bare spelling cannot find, so
119
+ // it wins; two spellings of the same family are the same slice either way.
120
+ else if (numbered && !existing.numbered)
121
+ judged.set(logical, { rid, numbered });
122
+ }
123
+ return { judged: [...judged.values()].map((entry) => entry.rid), rejected: [...rejected] };
124
+ }
125
+ /** Judge every slice the session recorded against the peaks-rd spec. */
126
+ async function judgeSessionSlices(projectRoot, sessionId, sliceRids) {
127
+ const readings = [];
128
+ for (const sliceRid of sliceRids) {
129
+ readings.push(await judgeSessionCompliance({ projectRoot, sessionId, spec: PEAKS_RD_SPEC, sliceRid }));
130
+ }
131
+ return readings;
132
+ }
133
+ /** The warnings the envelope carries: the scope, the spec, and any unobserved rate. */
134
+ function sessionRowWarnings(projectRoot, sessionId, eventCount, compliance) {
135
+ const warnings = [
136
+ ...scopeWarnings(projectRoot, sessionId, eventCount),
137
+ `compliance is judged against the \`${PEAKS_RD_SPEC.id}\` spec only.`
138
+ ];
139
+ if (compliance.complianceReason !== null)
140
+ warnings.push(compliance.complianceReason);
141
+ return warnings;
142
+ }
143
+ /** The envelope's data: the near-miss rate, the compliance rate, and the row's location. */
144
+ function sessionRowData(projectRoot, sessionId, row, compliance) {
145
+ // The near-miss rate is null when no slice passed: the row stores 0 there,
146
+ // and the command must not present that 0 as a measured rate.
147
+ const nearMissRate = row.passedSliceCount === 0 ? null : row.nearMissRate;
148
+ return {
149
+ scope: scopeOf(sessionId),
150
+ rowPath: sessionMetricRowPath(projectRoot, sessionId),
151
+ nearMissRate,
152
+ nearMissReason: nearMissRate === null
153
+ ? 'no slice passed in this session, so the near-miss rate was not observed'
154
+ : null,
155
+ passedSliceCount: row.passedSliceCount,
156
+ nearMissSliceCount: row.nearMissSliceCount,
157
+ ...compliance,
158
+ specIds: [PEAKS_RD_SPEC.id]
159
+ };
160
+ }
161
+ /**
162
+ * `peaks observability session-row` — write the session's tracked row and print
163
+ * its near-miss and compliance rates.
164
+ */
165
+ export async function runSessionRow(io, options) {
166
+ const projectRoot = resolveProjectRoot(options.project);
167
+ try {
168
+ const { sessionId, events } = readScopedEvents(projectRoot, options);
169
+ if (sessionId === undefined) {
170
+ throw new Error('a session row belongs to one session: pass --session <sessionId>, or run without --all-sessions');
171
+ }
172
+ const { requestTypes } = hotspotRequestTypes(projectRoot, events);
173
+ const { judged, rejected } = partitionSliceRids(events);
174
+ const readings = await judgeSessionSlices(projectRoot, sessionId, judged);
175
+ const skillsBlobSha = readSkillsBlobSha(projectRoot);
176
+ const row = buildSessionMetricRow({
177
+ sessionId,
178
+ events,
179
+ requestTypes,
180
+ compliance: readings,
181
+ ...(skillsBlobSha === undefined ? {} : { skillsBlobSha })
182
+ });
183
+ writeSessionMetricRow(projectRoot, row);
184
+ const compliance = summarizeCompliance(readings, rejected.length);
185
+ printResult(io, ok('observability.session-row', sessionRowData(projectRoot, sessionId, row, compliance), sessionRowWarnings(projectRoot, sessionId, events.length, compliance)), options.json);
186
+ }
187
+ catch (error) {
188
+ printResult(io, fail('observability.session-row', 'OBSERVABILITY_SESSION_ROW_FAILED', getErrorMessage(error), { projectRoot }, []), options.json);
189
+ process.exitCode = 1;
190
+ }
191
+ }
192
+ /** Register `peaks observability session-row` under the observability command. */
193
+ export function registerSessionRowCommand(observability, io) {
194
+ addJsonOption(observability
195
+ .command('session-row')
196
+ .description("Write the tracked per-session metric row (.peaks/observability/sessions/<sessionId>.json) and print its rates. The near-miss rate is null, with a reason, when no slice passed; the compliance rate is the mean share of the peaks-rd spec's required steps that ran across the session's slices, and is null, with a reason, when no slice was recorded.")
197
+ .option('--project <path>', 'target project root (defaults to git root or cwd)')
198
+ .option('--session <sessionId>', 'scope to one session (defaults to the canonical session binding)')).action(async (options) => {
199
+ await runSessionRow(io, options);
200
+ });
201
+ }
@@ -32,6 +32,7 @@ import { aggregateHotspots } from '../../services/observability/hotspots.js';
32
32
  import { readScopedEvents, resolveProjectRoot, runFanout, runRepairCycles, runSlices, runStatus, scopeOf, scopeWarnings } from './observability-commands-queries.js';
33
33
  import { runBaseline } from './observability-commands-baseline.js';
34
34
  import { registerNearMissCommand } from './observability-commands-near-miss.js';
35
+ import { registerSessionRowCommand } from './observability-commands-session-row.js';
35
36
  import { hotspotRequestTypes, registerHotspotsCommand } from './observability-commands-hotspots.js';
36
37
  const VALID_PERIODS = ['day', 'week', 'month'];
37
38
  /** The `--all-sessions` help text, ONE string for every command that carries it. */
@@ -181,5 +182,6 @@ export function registerObservabilityCommands(program, io) {
181
182
  runReport(io, options);
182
183
  });
183
184
  registerNearMissCommand(observability, io);
185
+ registerSessionRowCommand(observability, io);
184
186
  registerHotspotsCommand(observability, io);
185
187
  }
@@ -36,7 +36,12 @@
36
36
  */
37
37
  /**
38
38
  * Every `relativePath` any request type demands, every legacy tier the
39
- * resolver probes for one, and every gate-evidence shape a declaration can
40
- * report — de-duplicated and sorted.
39
+ * resolver probes for one, every judged-declaration tier the security audit
40
+ * can live at, and every gate-evidence shape a declaration can report —
41
+ * de-duplicated and sorted.
42
+ *
43
+ * The judged tiers are read from `securityArtifactTiers` in their defining
44
+ * module, not copied here. `securityTiers` is the seam a test uses to inject
45
+ * a tier list; production callers pass nothing.
41
46
  */
42
- export declare function allPrerequisitePaths(): readonly string[];
47
+ export declare function allPrerequisitePaths(securityTiers?: (rid: string) => readonly string[]): readonly string[];
@@ -36,6 +36,7 @@
36
36
  */
37
37
  import { PREREQUISITES_BY_TYPE } from './artifact-prerequisites.js';
38
38
  import { GATE_EVIDENCE_KEYS } from '../prd/handoff-types.js';
39
+ import { securityArtifactTiers } from '../audit-independent/judged-declaration-check.js';
39
40
  /**
40
41
  * The failure statuses, keyed so that the type checks BOTH ways: a status
41
42
  * added to the reader's union fails the build here until this record names
@@ -47,12 +48,37 @@ const GATE_EVIDENCE_FAILURE_STATUSES = {
47
48
  'field-not-map': true,
48
49
  'value-not-string': true
49
50
  };
51
+ /**
52
+ * The two sources of a missing path that do NOT come from the prereq table:
53
+ * the judged-declaration tiers and the gate-evidence declaration shapes.
54
+ *
55
+ * They are read from OTHER modules' definitions rather than from the table,
56
+ * and they are gathered apart from the table walk so that
57
+ * `allPrerequisitePaths` stays inside the lint complexity ceiling.
58
+ */
59
+ function addNonTablePaths(paths, securityTiers) {
60
+ // The `<rid>` placeholder stays in place, as it does on the table paths.
61
+ for (const tier of securityTiers('<rid>')) {
62
+ paths.add(tier);
63
+ }
64
+ for (const key of GATE_EVIDENCE_KEYS) {
65
+ paths.add(`gateEvidence.${key}`);
66
+ }
67
+ for (const status of Object.keys(GATE_EVIDENCE_FAILURE_STATUSES)) {
68
+ paths.add(`gateEvidence(${status})`);
69
+ }
70
+ }
50
71
  /**
51
72
  * Every `relativePath` any request type demands, every legacy tier the
52
- * resolver probes for one, and every gate-evidence shape a declaration can
53
- * report — de-duplicated and sorted.
73
+ * resolver probes for one, every judged-declaration tier the security audit
74
+ * can live at, and every gate-evidence shape a declaration can report —
75
+ * de-duplicated and sorted.
76
+ *
77
+ * The judged tiers are read from `securityArtifactTiers` in their defining
78
+ * module, not copied here. `securityTiers` is the seam a test uses to inject
79
+ * a tier list; production callers pass nothing.
54
80
  */
55
- export function allPrerequisitePaths() {
81
+ export function allPrerequisitePaths(securityTiers = securityArtifactTiers) {
56
82
  const paths = new Set();
57
83
  for (const table of Object.values(PREREQUISITES_BY_TYPE)) {
58
84
  for (const requirements of Object.values(table)) {
@@ -69,11 +95,6 @@ export function allPrerequisitePaths() {
69
95
  }
70
96
  }
71
97
  }
72
- for (const key of GATE_EVIDENCE_KEYS) {
73
- paths.add(`gateEvidence.${key}`);
74
- }
75
- for (const status of Object.keys(GATE_EVIDENCE_FAILURE_STATUSES)) {
76
- paths.add(`gateEvidence(${status})`);
77
- }
98
+ addNonTablePaths(paths, securityTiers);
78
99
  return [...paths].sort();
79
100
  }
@@ -44,7 +44,8 @@ async function resolvePrerequisiteAbsolutePath(sessionRoot, prerequisite, reques
44
44
  const dir = dirname(exact);
45
45
  // The on-disk suffix is the SLUG of this basename — the writer lowercases the
46
46
  // rid — so a mixed-case rid used to be reported absent with the file on disk.
47
- const suffix = `-${slugifyDescription(basename(exact).replace(/\.md$/, ''))}.md`;
47
+ const stem = slugifyDescription(basename(exact).replace(/\.md$/, ''));
48
+ const suffix = `-${stem}.md`;
48
49
  let entries;
49
50
  try {
50
51
  entries = await readdir(dir);
@@ -53,8 +54,37 @@ async function resolvePrerequisiteAbsolutePath(sessionRoot, prerequisite, reques
53
54
  // TODO(g2): legacy silent catch — grace: 1 minor release (v2.14.0)
54
55
  return null;
55
56
  }
57
+ // Number-first form (`003-<rid>.md`, the `qa/test-cases/` shape).
56
58
  const match = entries.find((name) => NUMBERED_PREFIX_RE.test(name) && name.endsWith(suffix));
57
- return match ? join(dir, match) : null;
59
+ if (match !== undefined)
60
+ return join(dir, match);
61
+ return resolveKindFirstNumbered(entries, dir, stem, requestId);
62
+ }
63
+ /**
64
+ * The OTHER numbered form: the writer numbers AFTER the kind for `audit/` and
65
+ * `rd/` (`audit/security-003-<rid>.md`). `NUMBERED_PREFIX_RE` is anchored at the
66
+ * start of the name, so the number-first scan above can never see it — and the
67
+ * evidence was reported missing with the file on disk.
68
+ *
69
+ * The kind is this prerequisite's basename with the rid stripped (`security-`),
70
+ * so a look-alike such as `security-backup-<rid>.md` carries no number prefix and
71
+ * another rid's `security-003-<other>.md` fails the exact-shape check. Both stay
72
+ * unresolved, which is the correct verdict for a prereq whose evidence is absent.
73
+ */
74
+ function resolveKindFirstNumbered(entries, dir, stem, requestId) {
75
+ const ridSlug = slugifyDescription(requestId);
76
+ const ridSuffix = `-${ridSlug}`;
77
+ if (!stem.endsWith(ridSuffix))
78
+ return null;
79
+ const kind = stem.slice(0, -ridSuffix.length);
80
+ const name = entries.find((entry) => {
81
+ if (!entry.startsWith(`${kind}-`))
82
+ return false;
83
+ const rest = entry.slice(kind.length + 1);
84
+ const numbered = NUMBERED_PREFIX_RE.exec(rest);
85
+ return numbered !== null && rest.slice(numbered[0].length) === `${ridSlug}.md`;
86
+ });
87
+ return name !== undefined ? join(dir, name) : null;
58
88
  }
59
89
  /**
60
90
  * Resolve a prerequisite to an on-disk path, with a 2-tier fallback
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * peaks hook output contract. See `.claude/HOOKS.md` for the canonical doc.
3
3
  *
4
- * Three helpers, one job: enforce the stdout/stderr/exit-code discipline
4
+ * Four helpers, one job: enforce the stdout/stderr/exit-code discipline
5
5
  * that every peaks-managed hook command MUST follow. Centralising the
6
6
  * contract here lets us:
7
7
  * 1. Pin the contract in cross-platform tests (tests/unit/hooks/contract.test.ts).
@@ -49,6 +49,15 @@
49
49
  * permissionDecision='deny' to block. Setting exit=2 on top
50
50
  * of the JSON would be double-signaling.
51
51
  *
52
+ * emitResultDocument(io, envelope)
53
+ * - Writes the command's result envelope to io.stdout as ONE JSON
54
+ * document and its action lines to io.stderr as `next: ...`.
55
+ * - Carries NO root `decision` and NO hookSpecificOutput: the host
56
+ * OWNS the root `decision` key and accepts only {approve, block},
57
+ * and a pass-through grant would bypass the user's own permission
58
+ * prompt. Exit 0 is the pass-through signal.
59
+ * - Does NOT set process.exitCode.
60
+ *
52
61
  * Platform notes:
53
62
  * - The contract is platform-independent. The helpers write to ProgramIO
54
63
  * (stdout / stderr) only; no path separators, no shell escaping, no
@@ -56,6 +65,7 @@
56
65
  * - On win32, Node's process.stdout and process.stderr are binary-safe
57
66
  * and UTF-8; do not introduce \r\n anywhere. The contract is LF.
58
67
  */
68
+ import type { ResultEnvelope } from 'peaks-loop-shared/result';
59
69
  import type { ProgramIO } from '../../cli/cli-helpers.js';
60
70
  /** Exit code the host treats as a hard block (Claude Code convention). */
61
71
  export declare const HOOK_BLOCK_EXIT_CODE = 2;
@@ -89,3 +99,27 @@ export declare function emitBlock(io: ProgramIO, reason: string): EmitBlockResul
89
99
  * be used for new code.
90
100
  */
91
101
  export declare function emitDecision(io: ProgramIO, decision: DecisionShape | string): string;
102
+ /**
103
+ * Result document — a command's result envelope as ONE JSON document on
104
+ * stdout, with its action lines on stderr.
105
+ *
106
+ * This is the hook-mode replacement for `printResult(io, envelope, false)`.
107
+ * That printer is written for a human at a terminal: it flattens `data` to the
108
+ * ROOT of stdout, then appends `next: ...` prose to the same stream. For a
109
+ * command whose stdout IS the hook's decision channel, both halves are wrong.
110
+ * A payload's own `decision` becomes a ROOT `decision` — a key the host OWNS,
111
+ * with vocabulary {approve, block} — which is the "decision: Invalid option"
112
+ * error the user saw on every Bash call; and the trailing prose makes stdout
113
+ * unparseable as one document.
114
+ *
115
+ * The document emitted here is the SAME envelope `--json` already prints, so a
116
+ * command has ONE machine shape in both modes and the shape cannot drift
117
+ * between them. The prose moves to stderr, where a hint belongs and where the
118
+ * host never reads a decision from.
119
+ *
120
+ * It deliberately does NOT carry a `hookSpecificOutput` allow decision: an
121
+ * allow is a real permission GRANT that bypasses the user's own permission
122
+ * prompt, and a gate that passes a call through has no opinion to give. Exit 0
123
+ * is the pass-through signal.
124
+ */
125
+ export declare function emitResultDocument<T>(io: ProgramIO, envelope: ResultEnvelope<T>): void;
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * peaks hook output contract. See `.claude/HOOKS.md` for the canonical doc.
3
3
  *
4
- * Three helpers, one job: enforce the stdout/stderr/exit-code discipline
4
+ * Four helpers, one job: enforce the stdout/stderr/exit-code discipline
5
5
  * that every peaks-managed hook command MUST follow. Centralising the
6
6
  * contract here lets us:
7
7
  * 1. Pin the contract in cross-platform tests (tests/unit/hooks/contract.test.ts).
@@ -49,6 +49,15 @@
49
49
  * permissionDecision='deny' to block. Setting exit=2 on top
50
50
  * of the JSON would be double-signaling.
51
51
  *
52
+ * emitResultDocument(io, envelope)
53
+ * - Writes the command's result envelope to io.stdout as ONE JSON
54
+ * document and its action lines to io.stderr as `next: ...`.
55
+ * - Carries NO root `decision` and NO hookSpecificOutput: the host
56
+ * OWNS the root `decision` key and accepts only {approve, block},
57
+ * and a pass-through grant would bypass the user's own permission
58
+ * prompt. Exit 0 is the pass-through signal.
59
+ * - Does NOT set process.exitCode.
60
+ *
52
61
  * Platform notes:
53
62
  * - The contract is platform-independent. The helpers write to ProgramIO
54
63
  * (stdout / stderr) only; no path separators, no shell escaping, no
@@ -108,3 +117,32 @@ export function emitDecision(io, decision) {
108
117
  io.stdout('\n');
109
118
  return serialized;
110
119
  }
120
+ /**
121
+ * Result document — a command's result envelope as ONE JSON document on
122
+ * stdout, with its action lines on stderr.
123
+ *
124
+ * This is the hook-mode replacement for `printResult(io, envelope, false)`.
125
+ * That printer is written for a human at a terminal: it flattens `data` to the
126
+ * ROOT of stdout, then appends `next: ...` prose to the same stream. For a
127
+ * command whose stdout IS the hook's decision channel, both halves are wrong.
128
+ * A payload's own `decision` becomes a ROOT `decision` — a key the host OWNS,
129
+ * with vocabulary {approve, block} — which is the "decision: Invalid option"
130
+ * error the user saw on every Bash call; and the trailing prose makes stdout
131
+ * unparseable as one document.
132
+ *
133
+ * The document emitted here is the SAME envelope `--json` already prints, so a
134
+ * command has ONE machine shape in both modes and the shape cannot drift
135
+ * between them. The prose moves to stderr, where a hint belongs and where the
136
+ * host never reads a decision from.
137
+ *
138
+ * It deliberately does NOT carry a `hookSpecificOutput` allow decision: an
139
+ * allow is a real permission GRANT that bypasses the user's own permission
140
+ * prompt, and a gate that passes a call through has no opinion to give. Exit 0
141
+ * is the pass-through signal.
142
+ */
143
+ export function emitResultDocument(io, envelope) {
144
+ io.stdout(JSON.stringify(envelope, null, 2));
145
+ for (const action of envelope.nextActions) {
146
+ emitHint(io, `next: ${action}`);
147
+ }
148
+ }
@@ -17,6 +17,7 @@ import { readObservabilityEvents } from './observability-service.js';
17
17
  import { TERMINAL_FAIL_STATES, TERMINAL_HAPPY_STATES, ZERO_FANOUT } from './aggregation-types.js';
18
18
  import { durationMsBetween, isSliceTransition, transitionTo } from './aggregation-helpers.js';
19
19
  import { buildRepairCycleReport, computeSliceRepairMetrics } from './repair-cycle-metric.js';
20
+ import { sliceIdentity } from '../../shared/incrementing-number.js';
20
21
  // The result shapes and their data (terminal states, repair-loop cap, zeroed
21
22
  // fan-out row) live in `aggregation-types.ts`; the event-detail readers and
22
23
  // the event-source helpers live in `aggregation-helpers.ts` (wave-3 file-size
@@ -34,7 +35,7 @@ function rollupSlices(events) {
34
35
  for (const event of events) {
35
36
  if (!isSliceTransition(event))
36
37
  continue;
37
- const rid = event.sliceRid;
38
+ const rid = sliceIdentity(event.sliceRid).logical;
38
39
  let rollup = bySlice.get(rid);
39
40
  if (rollup === undefined) {
40
41
  rollup = {
@@ -132,19 +132,14 @@ export type HotspotRequestTypes = ReadonlyMap<string, RequestTypeReading>;
132
132
  /**
133
133
  * The artifact path with the `<rid>` placeholder left in place.
134
134
  *
135
- * The template is recognised by re-filling the slot with the rid and
136
- * comparing, which is exact. The template is then returned AS IT IS: the
137
- * placeholder is part of the artifact's name, and stripping it produced paths
138
- * that name no real file.
135
+ * The template is recognised by splitting it at its slot and comparing the
136
+ * path's head, tail and the id it carries between them — by LOGICAL id, since
137
+ * `rd/code-review-004-<rid>.md` and `rd/code-review-<rid>.md` name the SAME
138
+ * artifact and one file must not become two rows. The template is returned AS
139
+ * IT IS: the placeholder is part of its name, and stripping it named no file.
139
140
  *
140
- * WHY A `<rid>`-LESS PATH IS RETURNED AS IT IS. The templates matched here
141
- * are the ones that CARRY a slot, so a path that came from a template
142
- * without one — `qa/.initiated` is a real artifact — never matches and is
143
- * returned unchanged. That asymmetry is DELIBERATE: there is nothing to
144
- * canonicalise, because the path already names the artifact it is. Do not
145
- * "fix" it by widening the template list — a template with no slot would
146
- * match EVERY path it happened to equal, and the comparison is only exact
147
- * for the form that carries the substituted id.
141
+ * A `<rid>`-less path is returned unchanged — there is nothing to canonicalise.
142
+ * Do not widen the template list: a slotless template matches every path.
148
143
  */
149
144
  export declare function canonicalArtifact(path: string, rid: string): string;
150
145
  /** The owner of an artifact, or null when no row claims it. */