peaks-loop 4.1.23 → 4.1.24

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 (58) hide show
  1. package/.claude-plugin/marketplace.json +12 -2
  2. package/CHANGELOG.md +102 -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 +23 -8
  8. package/dist/cli/commands/gate-commands-enforce.js +27 -12
  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 +67 -1
  16. package/dist/services/hooks/output.js +74 -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 +5 -5
  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
@@ -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,59 @@ 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
+ * The `hookSpecificOutput` block this repository ships on its allow paths.
104
+ *
105
+ * Why this shape: the Claude Code PreToolUse validator (measured against
106
+ * 2.1.312) accepts a stdout document whose root carries `hookSpecificOutput`
107
+ * with `permissionDecision` in {allow, deny, ask, defer}. It ALSO rejects a
108
+ * ROOT-level `decision` key whose value is outside {approve, block} — that is
109
+ * the exact error this slice fixes.
110
+ *
111
+ * `permissionDecision: "allow"` is the host's "this hook approves the call"
112
+ * signal. Measured: it makes the host approve the tool use, bypassing the
113
+ * user's own permission prompt, while an explicit user `deny` rule still
114
+ * overrides it. So this is a real permission grant, and the callers that use
115
+ * it must mean it.
116
+ */
117
+ export declare const HOOK_ALLOW_DECISION: DecisionShape;
118
+ /**
119
+ * Merge a payload with the allow decision into ONE JSON document.
120
+ *
121
+ * The host parses stdout as a SINGLE JSON document, so the decision and the
122
+ * payload must travel together — two documents on stdout means the second one
123
+ * is unparseable and the whole hook output degrades to plain text.
124
+ *
125
+ * The payload's own fields are preserved verbatim, so a downstream consumer
126
+ * that reads `JSON.parse(stdout).data.decision` keeps reading exactly that.
127
+ * The return type keeps the payload's own type, so a caller that passes a
128
+ * `ResultEnvelope` still gets a `ResultEnvelope` and can hand it to
129
+ * `printResult` — the merge only ADDS a key, it does not erase the shape.
130
+ */
131
+ export declare function buildAllowDocument<T extends object>(payload: T): T & {
132
+ hookSpecificOutput: DecisionShape;
133
+ };
134
+ /**
135
+ * Result document — a command's result envelope as ONE JSON document on
136
+ * stdout, with its action lines on stderr.
137
+ *
138
+ * This is the hook-mode replacement for `printResult(io, envelope, false)`.
139
+ * That printer is written for a human at a terminal: it flattens `data` to the
140
+ * ROOT of stdout, then appends `next: ...` prose to the same stream. For a
141
+ * command whose stdout IS the hook's decision channel, both halves are wrong.
142
+ * A payload's own `decision` becomes a ROOT `decision` — a key the host OWNS,
143
+ * with vocabulary {approve, block} — which is the "decision: Invalid option"
144
+ * error the user saw on every Bash call; and the trailing prose makes stdout
145
+ * unparseable as one document.
146
+ *
147
+ * The document emitted here is the SAME envelope `--json` already prints, so a
148
+ * command has ONE machine shape in both modes and the shape cannot drift
149
+ * between them. The prose moves to stderr, where a hint belongs and where the
150
+ * host never reads a decision from.
151
+ *
152
+ * It deliberately does NOT carry a `hookSpecificOutput` allow decision: an
153
+ * allow is a real permission GRANT that bypasses the user's own permission
154
+ * prompt (see HOOK_ALLOW_DECISION), and a gate that passes a call through has
155
+ * no opinion to give. Exit 0 is the pass-through signal.
156
+ */
157
+ 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,67 @@ export function emitDecision(io, decision) {
108
117
  io.stdout('\n');
109
118
  return serialized;
110
119
  }
120
+ /**
121
+ * The `hookSpecificOutput` block this repository ships on its allow paths.
122
+ *
123
+ * Why this shape: the Claude Code PreToolUse validator (measured against
124
+ * 2.1.312) accepts a stdout document whose root carries `hookSpecificOutput`
125
+ * with `permissionDecision` in {allow, deny, ask, defer}. It ALSO rejects a
126
+ * ROOT-level `decision` key whose value is outside {approve, block} — that is
127
+ * the exact error this slice fixes.
128
+ *
129
+ * `permissionDecision: "allow"` is the host's "this hook approves the call"
130
+ * signal. Measured: it makes the host approve the tool use, bypassing the
131
+ * user's own permission prompt, while an explicit user `deny` rule still
132
+ * overrides it. So this is a real permission grant, and the callers that use
133
+ * it must mean it.
134
+ */
135
+ export const HOOK_ALLOW_DECISION = {
136
+ hookEventName: CLAUDE_CODE_HOOK_EVENT,
137
+ permissionDecision: 'allow'
138
+ };
139
+ /**
140
+ * Merge a payload with the allow decision into ONE JSON document.
141
+ *
142
+ * The host parses stdout as a SINGLE JSON document, so the decision and the
143
+ * payload must travel together — two documents on stdout means the second one
144
+ * is unparseable and the whole hook output degrades to plain text.
145
+ *
146
+ * The payload's own fields are preserved verbatim, so a downstream consumer
147
+ * that reads `JSON.parse(stdout).data.decision` keeps reading exactly that.
148
+ * The return type keeps the payload's own type, so a caller that passes a
149
+ * `ResultEnvelope` still gets a `ResultEnvelope` and can hand it to
150
+ * `printResult` — the merge only ADDS a key, it does not erase the shape.
151
+ */
152
+ export function buildAllowDocument(payload) {
153
+ return { ...payload, hookSpecificOutput: HOOK_ALLOW_DECISION };
154
+ }
155
+ /**
156
+ * Result document — a command's result envelope as ONE JSON document on
157
+ * stdout, with its action lines on stderr.
158
+ *
159
+ * This is the hook-mode replacement for `printResult(io, envelope, false)`.
160
+ * That printer is written for a human at a terminal: it flattens `data` to the
161
+ * ROOT of stdout, then appends `next: ...` prose to the same stream. For a
162
+ * command whose stdout IS the hook's decision channel, both halves are wrong.
163
+ * A payload's own `decision` becomes a ROOT `decision` — a key the host OWNS,
164
+ * with vocabulary {approve, block} — which is the "decision: Invalid option"
165
+ * error the user saw on every Bash call; and the trailing prose makes stdout
166
+ * unparseable as one document.
167
+ *
168
+ * The document emitted here is the SAME envelope `--json` already prints, so a
169
+ * command has ONE machine shape in both modes and the shape cannot drift
170
+ * between them. The prose moves to stderr, where a hint belongs and where the
171
+ * host never reads a decision from.
172
+ *
173
+ * It deliberately does NOT carry a `hookSpecificOutput` allow decision: an
174
+ * allow is a real permission GRANT that bypasses the user's own permission
175
+ * prompt (see HOOK_ALLOW_DECISION), and a gate that passes a call through has
176
+ * no opinion to give. Exit 0 is the pass-through signal.
177
+ */
178
+ export function emitResultDocument(io, envelope) {
179
+ io.stdout(JSON.stringify(envelope, null, 2));
180
+ for (const action of envelope.nextActions) {
181
+ emitHint(io, `next: ${action}`);
182
+ }
183
+ }
@@ -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. */
@@ -27,6 +27,7 @@
27
27
  * Paths no template claims (a declaration key, a legacy location) keep their
28
28
  * own shape.
29
29
  */
30
+ import { sliceIdentity } from '../../shared/incrementing-number.js';
30
31
  import { allPrerequisitePaths } from '../artifacts/prerequisite-path-census.js';
31
32
  import { ownerSkillForPath, unownedPathReason } from './owner-skill-map.js';
32
33
  /** The templates a path can be recognised as, with the rid slot filled. */
@@ -34,23 +35,27 @@ const PREREQ_TEMPLATES = allPrerequisitePaths().filter((path) => path.includes('
34
35
  /**
35
36
  * The artifact path with the `<rid>` placeholder left in place.
36
37
  *
37
- * The template is recognised by re-filling the slot with the rid and
38
- * comparing, which is exact. The template is then returned AS IT IS: the
39
- * placeholder is part of the artifact's name, and stripping it produced paths
40
- * that name no real file.
38
+ * The template is recognised by splitting it at its slot and comparing the
39
+ * path's head, tail and the id it carries between them — by LOGICAL id, since
40
+ * `rd/code-review-004-<rid>.md` and `rd/code-review-<rid>.md` name the SAME
41
+ * artifact and one file must not become two rows. The template is returned AS
42
+ * IT IS: the placeholder is part of its name, and stripping it named no file.
41
43
  *
42
- * WHY A `<rid>`-LESS PATH IS RETURNED AS IT IS. The templates matched here
43
- * are the ones that CARRY a slot, so a path that came from a template
44
- * without one — `qa/.initiated` is a real artifact — never matches and is
45
- * returned unchanged. That asymmetry is DELIBERATE: there is nothing to
46
- * canonicalise, because the path already names the artifact it is. Do not
47
- * "fix" it by widening the template list — a template with no slot would
48
- * match EVERY path it happened to equal, and the comparison is only exact
49
- * for the form that carries the substituted id.
44
+ * A `<rid>`-less path is returned unchanged — there is nothing to canonicalise.
45
+ * Do not widen the template list: a slotless template matches every path.
50
46
  */
51
47
  export function canonicalArtifact(path, rid) {
48
+ const logical = sliceIdentity(rid).logical;
52
49
  for (const template of PREREQ_TEMPLATES) {
53
- if (template.replace('<rid>', rid) === path)
50
+ const at = template.indexOf('<rid>');
51
+ if (at < 0)
52
+ continue;
53
+ const head = template.slice(0, at);
54
+ const tail = template.slice(at + '<rid>'.length);
55
+ if (!path.startsWith(head) || !path.endsWith(tail))
56
+ continue;
57
+ const carried = path.slice(head.length, path.length - tail.length);
58
+ if (sliceIdentity(carried).logical === logical)
54
59
  return template;
55
60
  }
56
61
  return path;
@@ -31,6 +31,7 @@
31
31
  */
32
32
  import { collectAttempts, passMomentOf, unreadableVerdictOf, VERDICT_STATE } from './near-miss-attempts.js';
33
33
  import { getPrerequisitesFor } from '../artifacts/artifact-prerequisites.js';
34
+ import { sliceIdentity } from '../../shared/incrementing-number.js';
34
35
  /**
35
36
  * Whether a request type's prerequisite table has a row for the verdict
36
37
  * transition.
@@ -59,7 +60,9 @@ export function countDifferences(events, rollups, requestTypes) {
59
60
  const types = new Set();
60
61
  const slices = [];
61
62
  for (const rollup of rollups) {
62
- const sliceEvents = events.filter((event) => event.category === 'slice-transition' && event.sliceRid === rollup.sliceRid);
63
+ const sliceEvents = events.filter((event) => event.category === 'slice-transition' &&
64
+ event.sliceRid !== undefined &&
65
+ sliceIdentity(event.sliceRid).logical === rollup.sliceRid);
63
66
  const attempts = collectAttempts(sliceEvents);
64
67
  const hasPassMoment = passMomentOf(attempts) !== null;
65
68
  if (rollup.success && !hasPassMoment) {