peaks-loop 4.1.22 → 4.1.23

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 (72) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +82 -0
  3. package/dist/cli/commands/observability-commands-hotspots.d.ts +54 -0
  4. package/dist/cli/commands/observability-commands-hotspots.js +222 -0
  5. package/dist/cli/commands/observability-commands-near-miss.d.ts +28 -0
  6. package/dist/cli/commands/observability-commands-near-miss.js +105 -0
  7. package/dist/cli/commands/observability-commands-queries.d.ts +61 -18
  8. package/dist/cli/commands/observability-commands-queries.js +88 -47
  9. package/dist/cli/commands/observability-commands.js +79 -20
  10. package/dist/services/artifacts/artifact-prerequisites.d.ts +3 -0
  11. package/dist/services/artifacts/artifact-prerequisites.js +1 -1
  12. package/dist/services/artifacts/prerequisite-path-census.d.ts +42 -0
  13. package/dist/services/artifacts/prerequisite-path-census.js +79 -0
  14. package/dist/services/artifacts/prerequisite-transition-event.js +13 -1
  15. package/dist/services/artifacts/rd-gate-event.d.ts +106 -0
  16. package/dist/services/artifacts/rd-gate-event.js +211 -0
  17. package/dist/services/artifacts/rd-transition-gates.d.ts +6 -0
  18. package/dist/services/artifacts/rd-transition-gates.js +65 -24
  19. package/dist/services/observability/aggregation-types.d.ts +21 -0
  20. package/dist/services/observability/aggregation.d.ts +12 -2
  21. package/dist/services/observability/aggregation.js +26 -2
  22. package/dist/services/observability/compliance-judge.d.ts +77 -0
  23. package/dist/services/observability/compliance-judge.js +143 -0
  24. package/dist/services/observability/compliance-spec.d.ts +96 -0
  25. package/dist/services/observability/compliance-spec.js +29 -0
  26. package/dist/services/observability/compliance-specs/peaks-race-code.spec.d.ts +37 -0
  27. package/dist/services/observability/compliance-specs/peaks-race-code.spec.js +66 -0
  28. package/dist/services/observability/compliance-specs/peaks-rd.spec.d.ts +50 -0
  29. package/dist/services/observability/compliance-specs/peaks-rd.spec.js +111 -0
  30. package/dist/services/observability/hotspot-attribution-summary.d.ts +84 -0
  31. package/dist/services/observability/hotspot-attribution-summary.js +74 -0
  32. package/dist/services/observability/hotspot-rows.d.ts +47 -0
  33. package/dist/services/observability/hotspot-rows.js +89 -0
  34. package/dist/services/observability/hotspot-shared.d.ts +212 -0
  35. package/dist/services/observability/hotspot-shared.js +122 -0
  36. package/dist/services/observability/hotspot-sources.d.ts +55 -0
  37. package/dist/services/observability/hotspot-sources.js +142 -0
  38. package/dist/services/observability/hotspots.d.ts +47 -0
  39. package/dist/services/observability/hotspots.js +47 -0
  40. package/dist/services/observability/near-miss-attempts.d.ts +175 -0
  41. package/dist/services/observability/near-miss-attempts.js +223 -0
  42. package/dist/services/observability/near-miss-coverage.d.ts +109 -0
  43. package/dist/services/observability/near-miss-coverage.js +108 -0
  44. package/dist/services/observability/near-miss-denominator.d.ts +81 -0
  45. package/dist/services/observability/near-miss-denominator.js +75 -0
  46. package/dist/services/observability/near-miss-difference.d.ts +98 -0
  47. package/dist/services/observability/near-miss-difference.js +132 -0
  48. package/dist/services/observability/near-miss-facts.d.ts +165 -0
  49. package/dist/services/observability/near-miss-facts.js +101 -0
  50. package/dist/services/observability/near-miss-gate-events.d.ts +75 -0
  51. package/dist/services/observability/near-miss-gate-events.js +106 -0
  52. package/dist/services/observability/near-miss-gates.d.ts +108 -0
  53. package/dist/services/observability/near-miss-gates.js +135 -0
  54. package/dist/services/observability/near-miss-records.d.ts +93 -0
  55. package/dist/services/observability/near-miss-records.js +87 -0
  56. package/dist/services/observability/near-miss.d.ts +148 -0
  57. package/dist/services/observability/near-miss.js +196 -0
  58. package/dist/services/observability/observability-schema.d.ts +17 -2
  59. package/dist/services/observability/observability-schema.js +21 -1
  60. package/dist/services/observability/owner-skill-map.d.ts +92 -0
  61. package/dist/services/observability/owner-skill-map.js +144 -0
  62. package/dist/services/observability/report-formatter-hotspots.d.ts +32 -0
  63. package/dist/services/observability/report-formatter-hotspots.js +76 -0
  64. package/dist/services/observability/report-formatter-near-miss.d.ts +48 -0
  65. package/dist/services/observability/report-formatter-near-miss.js +234 -0
  66. package/dist/services/observability/report-formatter.d.ts +49 -3
  67. package/dist/services/observability/report-formatter.js +55 -14
  68. package/dist/services/observability/retro-attribution.d.ts +129 -0
  69. package/dist/services/observability/retro-attribution.js +134 -0
  70. package/dist/services/observability/session-metric-rows.d.ts +153 -0
  71. package/dist/services/observability/session-metric-rows.js +184 -0
  72. package/package.json +5 -5
@@ -15,6 +15,10 @@
15
15
  * LATER ADDITION — `peaks observability repair-cycles` also grew an
16
16
  * `--all-sessions` scope, so the whole recorded history of a project can be
17
17
  * measured from the command itself.
18
+ *
19
+ * TASK 4 — the same `--all-sessions` scope now reaches `status` / `slices` /
20
+ * `fanout` / `report`, and every scoped query says so when its scope holds no
21
+ * events while OTHER sessions hold some.
18
22
  */
19
23
  import { fail, ok } from 'peaks-loop-shared/result';
20
24
  import { findProjectRoot } from '../../services/config/config-safety.js';
@@ -27,28 +31,84 @@ export function resolveProjectRoot(optionProject) {
27
31
  ? resolveCanonicalProjectRoot(optionProject)
28
32
  : (findProjectRoot(process.cwd()) ?? process.cwd());
29
33
  }
30
- export function resolveSessionId(optionSession, projectRoot) {
34
+ /**
35
+ * The session a query reads, or `undefined` for EVERY session.
36
+ *
37
+ * `allSessions` short-circuits the resolution: the whole recorded history is
38
+ * read instead of the canonical session binding, and an explicit `--session`
39
+ * does not narrow it back. That is the precedence `repair-cycles
40
+ * --all-sessions` already has.
41
+ */
42
+ export function resolveSessionId(optionSession, projectRoot, allSessions) {
43
+ if (allSessions)
44
+ return undefined;
31
45
  if (optionSession !== undefined)
32
46
  return optionSession;
33
47
  return getSessionIdCanonical(projectRoot) ?? undefined;
34
48
  }
49
+ /**
50
+ * The warnings a scoped query carries.
51
+ *
52
+ * A scoped query that reads zero events reads exactly like a project that
53
+ * recorded nothing, and the reader concludes the second — the events that ARE
54
+ * there stay invisible. So when the scope is empty while OTHER sessions hold
55
+ * events, the warning says how many sessions hold them, how many events in
56
+ * total, and names the flag that reaches them.
57
+ *
58
+ * Empty otherwise: either the scope holds events, or the scope already
59
+ * covers every session.
60
+ */
61
+ export function scopeWarnings(projectRoot, scopedSessionId, scopedEventCount) {
62
+ if (scopedSessionId === undefined)
63
+ return [];
64
+ if (scopedEventCount > 0)
65
+ return [];
66
+ const sessions = new Set();
67
+ let eventCount = 0;
68
+ for (const event of readAllSessionEvents(projectRoot)) {
69
+ if (event.sessionId === scopedSessionId)
70
+ continue;
71
+ sessions.add(event.sessionId);
72
+ eventCount += 1;
73
+ }
74
+ if (eventCount === 0)
75
+ return [];
76
+ return [
77
+ `No observability events in session \`${scopedSessionId}\`; ` +
78
+ `${sessions.size} other session(s) hold ${eventCount} event(s) in total — ` +
79
+ 'use `--all-sessions` to read them.'
80
+ ];
81
+ }
82
+ /**
83
+ * The events a scoped query answers for: the one session the scope names, or
84
+ * every session the project recorded.
85
+ */
86
+ export function readScopedEvents(projectRoot, options) {
87
+ const sessionId = resolveSessionId(options.session, projectRoot, options.allSessions === true);
88
+ const events = sessionId !== undefined
89
+ ? readSessionEvents(projectRoot, sessionId)
90
+ : readAllSessionEvents(projectRoot);
91
+ return { sessionId, events };
92
+ }
93
+ /**
94
+ * The scope a query answered for: one session, or every session.
95
+ *
96
+ * ONE spelling of that shape, exported because the report command answers
97
+ * with it too: a scope written two ways is a scope that can drift.
98
+ */
99
+ export function scopeOf(sessionId) {
100
+ return sessionId !== undefined ? { sessionId } : { allSessions: true };
101
+ }
35
102
  export function runStatus(io, options) {
36
103
  const projectRoot = resolveProjectRoot(options.project);
37
- const sessionId = resolveSessionId(options.session, projectRoot);
38
104
  try {
39
- const events = sessionId !== undefined
40
- ? readSessionEvents(projectRoot, sessionId)
41
- : readAllSessionEvents(projectRoot);
105
+ const { sessionId, events } = readScopedEvents(projectRoot, options);
42
106
  const status = aggregateStatus(events);
43
- const warnings = sessionId === undefined && status.totalEvents === 0
44
- ? [
45
- 'No observability events found in any session — emit a slice transition via `peaks request transition` to populate.'
46
- ]
47
- : [];
48
- printResult(io, ok('observability.status', {
49
- scope: sessionId !== undefined ? { sessionId } : { allSessions: true },
50
- status
51
- }, warnings), options.json);
107
+ const warnings = scopeWarnings(projectRoot, sessionId, status.totalEvents);
108
+ if (sessionId === undefined && status.totalEvents === 0) {
109
+ warnings.push('No observability events found in any session — emit a slice transition via `peaks request transition` to populate.');
110
+ }
111
+ printResult(io, ok('observability.status', { scope: scopeOf(sessionId), status }, warnings), options.json);
52
112
  }
53
113
  catch (error) {
54
114
  printResult(io, fail('observability.status', 'OBSERVABILITY_STATUS_FAILED', getErrorMessage(error), { projectRoot }, ['Run `peaks observability slices` for per-slice detail']), options.json);
@@ -57,17 +117,11 @@ export function runStatus(io, options) {
57
117
  }
58
118
  export function runSlices(io, options) {
59
119
  const projectRoot = resolveProjectRoot(options.project);
60
- const sessionId = resolveSessionId(options.session, projectRoot);
61
120
  try {
62
- const events = sessionId !== undefined
63
- ? readSessionEvents(projectRoot, sessionId)
64
- : readAllSessionEvents(projectRoot);
121
+ const { sessionId, events } = readScopedEvents(projectRoot, options);
65
122
  const slices = aggregateSlices(events);
66
- printResult(io, ok('observability.slices', {
67
- scope: sessionId !== undefined ? { sessionId } : { allSessions: true },
68
- total: slices.length,
69
- slices
70
- }, []), options.json);
123
+ const warnings = scopeWarnings(projectRoot, sessionId, events.length);
124
+ printResult(io, ok('observability.slices', { scope: scopeOf(sessionId), total: slices.length, slices }, warnings), options.json);
71
125
  }
72
126
  catch (error) {
73
127
  printResult(io, fail('observability.slices', 'OBSERVABILITY_SLICES_FAILED', getErrorMessage(error), { projectRoot }, []), options.json);
@@ -76,21 +130,14 @@ export function runSlices(io, options) {
76
130
  }
77
131
  export function runFanout(io, options) {
78
132
  const projectRoot = resolveProjectRoot(options.project);
79
- const sessionId = resolveSessionId(options.session, projectRoot);
80
133
  try {
81
- const events = sessionId !== undefined
82
- ? readSessionEvents(projectRoot, sessionId)
83
- : readAllSessionEvents(projectRoot);
134
+ const { sessionId, events } = readScopedEvents(projectRoot, options);
84
135
  const fanout = aggregateFanout(events);
85
- const warnings = fanout.total === 0
86
- ? [
87
- 'No dispatch events recorded yet — Slice C will wire `peaks sub-agent dispatch`; until then fanout is empty.'
88
- ]
89
- : [];
90
- printResult(io, ok('observability.fanout', {
91
- scope: sessionId !== undefined ? { sessionId } : { allSessions: true },
92
- fanout
93
- }, warnings), options.json);
136
+ const warnings = scopeWarnings(projectRoot, sessionId, events.length);
137
+ if (fanout.total === 0) {
138
+ warnings.push('No dispatch events recorded in this scope — the fanout breakdown counts the dispatch events of the scope that was read.');
139
+ }
140
+ printResult(io, ok('observability.fanout', { scope: scopeOf(sessionId), fanout }, warnings), options.json);
94
141
  }
95
142
  catch (error) {
96
143
  printResult(io, fail('observability.fanout', 'OBSERVABILITY_FANOUT_FAILED', getErrorMessage(error), { projectRoot }, []), options.json);
@@ -99,19 +146,13 @@ export function runFanout(io, options) {
99
146
  }
100
147
  export function runRepairCycles(io, options) {
101
148
  const projectRoot = resolveProjectRoot(options.project);
102
- // `--all-sessions` is the escape from the canonical-session binding: the
103
- // recorded history (every session in the project) is the population the
104
- // results baseline and the metric comparison are measured over.
105
- const sessionId = options.allSessions === true ? undefined : resolveSessionId(options.session, projectRoot);
106
149
  try {
107
- const events = sessionId !== undefined
108
- ? readSessionEvents(projectRoot, sessionId)
109
- : readAllSessionEvents(projectRoot);
150
+ // `--all-sessions` is the escape from the canonical-session binding: the
151
+ // recorded history (every session in the project) is the population the
152
+ // results baseline and the metric comparison are measured over.
153
+ const { sessionId, events } = readScopedEvents(projectRoot, options);
110
154
  const cycles = aggregateRepairCycles(events);
111
- printResult(io, ok('observability.repair-cycles', {
112
- scope: sessionId !== undefined ? { sessionId } : { allSessions: true },
113
- cycles
114
- }, []), options.json);
155
+ printResult(io, ok('observability.repair-cycles', { scope: scopeOf(sessionId), cycles }, scopeWarnings(projectRoot, sessionId, events.length)), options.json);
115
156
  }
116
157
  catch (error) {
117
158
  printResult(io, fail('observability.repair-cycles', 'OBSERVABILITY_REPAIR_CYCLES_FAILED', getErrorMessage(error), { projectRoot }, []), options.json);
@@ -19,53 +19,107 @@
19
19
  */
20
20
  import { fail, ok } from 'peaks-loop-shared/result';
21
21
  import { addJsonOption, getErrorMessage, printResult } from '../cli-helpers.js';
22
- import { aggregateFanout, aggregateRepairCycles, aggregateSlices, aggregateStatus, filterByPeriod, periodStartIso, readAllSessionEvents, readSessionEvents } from '../../services/observability/aggregation.js';
22
+ import { aggregateFanout, aggregateRepairCycles, aggregateSlices, aggregateStatus, filterByPeriod, periodStartIso } from '../../services/observability/aggregation.js';
23
23
  import { renderObservabilityReport } from '../../services/observability/report-formatter.js';
24
+ import { computeNearMiss } from '../../services/observability/near-miss.js';
25
+ import { aggregateHotspots } from '../../services/observability/hotspots.js';
24
26
  // Slice `b1-filesplit-campaign` (wave 3B): the four read-only query runners
25
27
  // (`runStatus` / `runSlices` / `runFanout` / `runRepairCycles`) plus the two
26
28
  // scope resolvers they share moved VERBATIM to `./observability-commands-queries.ts`
27
29
  // so this file clears the 300 raw-line cap. What they do is unchanged;
28
30
  // `runReport` — the one function here carrying a finding — stayed behind, so no
29
31
  // finding moved into the new module.
30
- import { resolveProjectRoot, resolveSessionId, runFanout, runRepairCycles, runSlices, runStatus } from './observability-commands-queries.js';
32
+ import { readScopedEvents, resolveProjectRoot, runFanout, runRepairCycles, runSlices, runStatus, scopeOf, scopeWarnings } from './observability-commands-queries.js';
31
33
  import { runBaseline } from './observability-commands-baseline.js';
34
+ import { registerNearMissCommand } from './observability-commands-near-miss.js';
35
+ import { hotspotRequestTypes, registerHotspotsCommand } from './observability-commands-hotspots.js';
32
36
  const VALID_PERIODS = ['day', 'week', 'month'];
37
+ /** The `--all-sessions` help text, ONE string for every command that carries it. */
38
+ const ALL_SESSIONS_DESCRIPTION = 'measure the whole recorded history of the project instead of the canonical session binding';
39
+ /**
40
+ * The warning a report carries when its PERIOD emptied the result.
41
+ *
42
+ * The scope and the period are two different axes: `--all-sessions` widens
43
+ * WHICH sessions are read, `--period` narrows WHICH DAYS of them count. A
44
+ * reader who scoped correctly and still saw an empty table was narrowed by
45
+ * the period, so the warning says the scope holds events and names the
46
+ * period window that reaches the most of them.
47
+ */
48
+ function periodWarnings(scopedEvents, period, now) {
49
+ if (scopedEvents.length === 0)
50
+ return [];
51
+ if (filterByPeriod(scopedEvents, period, now).length > 0)
52
+ return [];
53
+ let reaching;
54
+ let reachingCount = 0;
55
+ for (const candidate of VALID_PERIODS) {
56
+ const count = filterByPeriod(scopedEvents, candidate, now).length;
57
+ if (count > 0 && count >= reachingCount) {
58
+ reaching = candidate;
59
+ reachingCount = count;
60
+ }
61
+ }
62
+ if (reaching === undefined) {
63
+ return [
64
+ `No observability events fall inside the \`${period}\` period, and the scope's ` +
65
+ `${scopedEvents.length} event(s) are older than every period window — ` +
66
+ 'no `--period` value reaches them.'
67
+ ];
68
+ }
69
+ return [
70
+ `No observability events fall inside the \`${period}\` period, though the scope holds ` +
71
+ `${scopedEvents.length} event(s) — use \`--period ${reaching}\` to read them.`
72
+ ];
73
+ }
33
74
  function runReport(io, options) {
34
75
  const projectRoot = resolveProjectRoot(options.project);
35
- const sessionId = resolveSessionId(options.session, projectRoot);
36
76
  const period = options.period !== undefined && VALID_PERIODS.includes(options.period)
37
77
  ? options.period
38
78
  : 'day';
39
79
  try {
40
- const allEvents = sessionId !== undefined
41
- ? readSessionEvents(projectRoot, sessionId)
42
- : readAllSessionEvents(projectRoot);
43
- const periodStart = periodStartIso(period);
44
- const events = filterByPeriod(allEvents, period);
80
+ const { sessionId, events: allEvents } = readScopedEvents(projectRoot, options);
81
+ // ONE clock for the whole report: the window the events are filtered by
82
+ // and the window the warning names must be the same one.
83
+ const at = new Date();
84
+ const now = () => new Date(at);
85
+ const periodStart = periodStartIso(period, now);
86
+ const events = filterByPeriod(allEvents, period, now);
87
+ // The two measurements the report leads with. The request types are
88
+ // resolved through the hotspots command's own lookup, so the ranking in
89
+ // the report and the ranking the `hotspots` command prints cannot drift.
90
+ const { requestTypes } = hotspotRequestTypes(projectRoot, events);
91
+ const warnings = [
92
+ ...scopeWarnings(projectRoot, sessionId, allEvents.length),
93
+ ...periodWarnings(allEvents, period, now)
94
+ ];
45
95
  const markdown = renderObservabilityReport({
46
96
  scope: sessionId !== undefined ? 'session' : 'all-sessions',
47
97
  scopeId: sessionId ?? 'all',
48
98
  period,
49
- generatedAt: new Date().toISOString(),
99
+ generatedAt: at.toISOString(),
50
100
  status: aggregateStatus(events),
51
101
  slices: aggregateSlices(events),
52
102
  fanout: aggregateFanout(events),
53
- repairCycles: aggregateRepairCycles(events)
103
+ repairCycles: aggregateRepairCycles(events),
104
+ nearMiss: computeNearMiss(events, requestTypes),
105
+ hotspots: aggregateHotspots(events, requestTypes),
106
+ warnings
54
107
  });
55
108
  if (options.json === true) {
56
109
  // --json on report: emit a metadata envelope so callers can
57
110
  // machine-parse the markdown body without losing the envelope
58
111
  // contract.
59
112
  printResult(io, ok('observability.report', {
60
- scope: sessionId !== undefined ? { sessionId } : { allSessions: true },
113
+ scope: scopeOf(sessionId),
61
114
  period,
62
115
  periodStart,
63
116
  totalEventsScanned: allEvents.length,
64
117
  totalEventsInPeriod: events.length,
65
118
  markdown
66
- }, []), true);
119
+ }, warnings), true);
67
120
  return;
68
121
  }
122
+ // The warnings are IN the markdown header: the body is what gets pasted.
69
123
  io.stdout(markdown);
70
124
  }
71
125
  catch (error) {
@@ -79,23 +133,26 @@ export function registerObservabilityCommands(program, io) {
79
133
  .description('Read-only slice topology observability queries (v2.11.1). Reads JSONL metrics from .peaks/_runtime/<sessionId>/metrics/slices.jsonl.');
80
134
  addJsonOption(observability
81
135
  .command('status')
82
- .description('Aggregate metrics for the active session (or all sessions with --project + omitted --session). Includes totalEvents / totalSlices / successCount / failCount / repairCyclePeak / fanoutCostTotal.')
136
+ .description('Aggregate metrics for the active session (or all sessions with --project + omitted --session). Includes totalEvents / totalSlices / successCount / failCount / stalledCount / repairCyclePeak / fanoutCostTotal.')
83
137
  .option('--project <path>', 'target project root (defaults to git root or cwd)')
84
- .option('--session <sessionId>', 'scope to one session (defaults to the canonical session binding)')).action((options) => {
138
+ .option('--session <sessionId>', 'scope to one session (defaults to the canonical session binding)')
139
+ .option('--all-sessions', ALL_SESSIONS_DESCRIPTION)).action((options) => {
85
140
  runStatus(io, options);
86
141
  });
87
142
  addJsonOption(observability
88
143
  .command('slices')
89
144
  .description('List all slices for the scope. Per slice: rid, transition count, first/last ts, durationMs, finalState, fanoutCount, repairCycleCount, success.')
90
145
  .option('--project <path>', 'target project root (defaults to git root or cwd)')
91
- .option('--session <sessionId>', 'scope to one session (defaults to the canonical session binding)')).action((options) => {
146
+ .option('--session <sessionId>', 'scope to one session (defaults to the canonical session binding)')
147
+ .option('--all-sessions', ALL_SESSIONS_DESCRIPTION)).action((options) => {
92
148
  runSlices(io, options);
93
149
  });
94
150
  addJsonOption(observability
95
151
  .command('fanout')
96
152
  .description('Fanout cost breakdown by sub-agent role (rd / qa / code-reviewer / karpathy-reviewer / peaks-security-audit / peaks-perf-audit; v2.12.0 collapse — `security-reviewer` removed from the role enum). Returns 0 per role until Slice C wires the `peaks sub-agent dispatch` hook.')
97
153
  .option('--project <path>', 'target project root (defaults to git root or cwd)')
98
- .option('--session <sessionId>', 'scope to one session (defaults to the canonical session binding)')).action((options) => {
154
+ .option('--session <sessionId>', 'scope to one session (defaults to the canonical session binding)')
155
+ .option('--all-sessions', ALL_SESSIONS_DESCRIPTION)).action((options) => {
99
156
  runFanout(io, options);
100
157
  });
101
158
  addJsonOption(observability
@@ -103,7 +160,7 @@ export function registerObservabilityCommands(program, io) {
103
160
  .description('RD → QA repair-cycle count per slice (metric version 2: a repair cycle is a return to an RD work state after a QA phase). Cap = 3 (peaks-code repair-loop contract); capHit flag is set when any slice hits the cap. The version-1 qa-role event count is reported beside it as legacyQaEventCount — it is NOT a repair-cycle count.')
104
161
  .option('--project <path>', 'target project root (defaults to git root or cwd)')
105
162
  .option('--session <sessionId>', 'scope to one session (defaults to the canonical session binding)')
106
- .option('--all-sessions', 'measure the whole recorded history of the project instead of the canonical session binding')).action((options) => {
163
+ .option('--all-sessions', ALL_SESSIONS_DESCRIPTION)).action((options) => {
107
164
  runRepairCycles(io, options);
108
165
  });
109
166
  addJsonOption(observability
@@ -114,13 +171,15 @@ export function registerObservabilityCommands(program, io) {
114
171
  .option('--check', 'compare the computed baseline against the tracked artifact and report drift')).action((options) => {
115
172
  runBaseline(io, options);
116
173
  });
117
- observability
174
+ addJsonOption(observability
118
175
  .command('report')
119
- .description('Render a markdown summary suitable for paste into PR descriptions or .peaks/PROJECT.md timeline entries. Default period = day; --json emits an envelope wrapping the markdown body. Output sections: header + status summary + slice table + fanout table + repair-cycle table + top-N slowest slices.')
176
+ .description('Render a markdown summary suitable for paste into PR descriptions or .peaks/PROJECT.md timeline entries. Default period = day; --json emits an envelope wrapping the markdown body. Output sections: header + status summary + near-miss section (rate, denominator, per-class coverage, unobserved classes) + slice table + hotspot tables + fanout table + repair-cycle table + top-N slowest slices.')
120
177
  .option('--project <path>', 'target project root (defaults to git root or cwd)')
121
178
  .option('--session <sessionId>', 'scope to one session (defaults to the canonical session binding)')
122
179
  .option('--period <period>', 'one of: day | week | month (defaults to day)', 'day')
123
- .action((options) => {
180
+ .option('--all-sessions', ALL_SESSIONS_DESCRIPTION)).action((options) => {
124
181
  runReport(io, options);
125
182
  });
183
+ registerNearMissCommand(observability, io);
184
+ registerHotspotsCommand(observability, io);
126
185
  }
@@ -84,6 +84,9 @@ export type PrerequisiteCheckResult = {
84
84
  expiredWindow?: string;
85
85
  }>;
86
86
  };
87
+ type TransitionKey = `${RequestArtifactRole}:${RequestArtifactState}`;
88
+ type PrerequisiteTable = Partial<Record<TransitionKey, ReadonlyArray<ArtifactPrerequisite>>>;
89
+ export declare const PREREQUISITES_BY_TYPE: Record<RequestType, PrerequisiteTable>;
87
90
  export type CheckPrerequisitesOptions = {
88
91
  projectRoot: string;
89
92
  /**
@@ -327,7 +327,7 @@ const CONFIG_TABLE = {
327
327
  'rd:qa-handoff': [SECURITY_REVIEW],
328
328
  'qa:verdict-issued': [TEST_REPORT]
329
329
  };
330
- const PREREQUISITES_BY_TYPE = {
330
+ export const PREREQUISITES_BY_TYPE = {
331
331
  feature: FEATURE_TABLE,
332
332
  bugfix: BUGFIX_TABLE,
333
333
  refactor: REFACTOR_TABLE,
@@ -0,0 +1,42 @@
1
+ /**
2
+ * `src/services/artifacts/prerequisite-path-census.ts`
3
+ *
4
+ * Every path shape that can reach the prerequisite missing list, as one
5
+ * de-duplicated list.
6
+ *
7
+ * WHY THIS EXISTS. The owner-skill map has to cover the paths the gates
8
+ * actually demand, and the gates read ONE table. Reading that table through
9
+ * a census function means the coverage check and the gate can never
10
+ * disagree about which paths exist — a second hand-written list would drift
11
+ * from the table on the first table change.
12
+ *
13
+ * THE THREE SOURCES OF A MISSING PATH. `checkPrerequisites` builds its
14
+ * missing list from three places, and a census that reads only the first
15
+ * would leave the other two uncovered:
16
+ *
17
+ * 1. the table loop — the canonical `relativePath`, plus the legacy tiers
18
+ * (`legacyRelativePath` / `legacyRelativePaths`) the resolver probes
19
+ * before it calls a file absent;
20
+ * 2. the judged-declaration refusals — the security artifact's own
21
+ * location, which the resolver reports verbatim;
22
+ * 3. the handoff capsule's gate-evidence declaration — a key that names a
23
+ * file that is not on disk, reported under the KEY's name, and the
24
+ * unreadable-capsule shape beside it.
25
+ *
26
+ * The `<rid>` placeholder is left in place on the table paths: this is the
27
+ * table's own shape, and the owner lookup is a prefix match, so the
28
+ * placeholder is irrelevant to it.
29
+ *
30
+ * THE KEY SET IS READ, NOT COPIED. `GATE_EVIDENCE_KEYS` is the one
31
+ * definition of the gate-evidence vocabulary, and a second copy of it here
32
+ * would be the same drift hole this census exists to close. The failure
33
+ * statuses are held in a `Record` keyed by the reader's own status type, so
34
+ * a status added to that type fails the build here until this census
35
+ * accounts for it.
36
+ */
37
+ /**
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.
41
+ */
42
+ export declare function allPrerequisitePaths(): readonly string[];
@@ -0,0 +1,79 @@
1
+ /**
2
+ * `src/services/artifacts/prerequisite-path-census.ts`
3
+ *
4
+ * Every path shape that can reach the prerequisite missing list, as one
5
+ * de-duplicated list.
6
+ *
7
+ * WHY THIS EXISTS. The owner-skill map has to cover the paths the gates
8
+ * actually demand, and the gates read ONE table. Reading that table through
9
+ * a census function means the coverage check and the gate can never
10
+ * disagree about which paths exist — a second hand-written list would drift
11
+ * from the table on the first table change.
12
+ *
13
+ * THE THREE SOURCES OF A MISSING PATH. `checkPrerequisites` builds its
14
+ * missing list from three places, and a census that reads only the first
15
+ * would leave the other two uncovered:
16
+ *
17
+ * 1. the table loop — the canonical `relativePath`, plus the legacy tiers
18
+ * (`legacyRelativePath` / `legacyRelativePaths`) the resolver probes
19
+ * before it calls a file absent;
20
+ * 2. the judged-declaration refusals — the security artifact's own
21
+ * location, which the resolver reports verbatim;
22
+ * 3. the handoff capsule's gate-evidence declaration — a key that names a
23
+ * file that is not on disk, reported under the KEY's name, and the
24
+ * unreadable-capsule shape beside it.
25
+ *
26
+ * The `<rid>` placeholder is left in place on the table paths: this is the
27
+ * table's own shape, and the owner lookup is a prefix match, so the
28
+ * placeholder is irrelevant to it.
29
+ *
30
+ * THE KEY SET IS READ, NOT COPIED. `GATE_EVIDENCE_KEYS` is the one
31
+ * definition of the gate-evidence vocabulary, and a second copy of it here
32
+ * would be the same drift hole this census exists to close. The failure
33
+ * statuses are held in a `Record` keyed by the reader's own status type, so
34
+ * a status added to that type fails the build here until this census
35
+ * accounts for it.
36
+ */
37
+ import { PREREQUISITES_BY_TYPE } from './artifact-prerequisites.js';
38
+ import { GATE_EVIDENCE_KEYS } from '../prd/handoff-types.js';
39
+ /**
40
+ * The failure statuses, keyed so that the type checks BOTH ways: a status
41
+ * added to the reader's union fails the build here until this record names
42
+ * it, and a status dropped from that union fails here as an excess key.
43
+ */
44
+ const GATE_EVIDENCE_FAILURE_STATUSES = {
45
+ 'read-error': true,
46
+ 'frontmatter-malformed': true,
47
+ 'field-not-map': true,
48
+ 'value-not-string': true
49
+ };
50
+ /**
51
+ * 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.
54
+ */
55
+ export function allPrerequisitePaths() {
56
+ const paths = new Set();
57
+ for (const table of Object.values(PREREQUISITES_BY_TYPE)) {
58
+ for (const requirements of Object.values(table)) {
59
+ if (requirements === undefined)
60
+ continue;
61
+ for (const requirement of requirements) {
62
+ paths.add(requirement.relativePath);
63
+ if (requirement.legacyRelativePath !== undefined) {
64
+ paths.add(requirement.legacyRelativePath);
65
+ }
66
+ for (const legacy of requirement.legacyRelativePaths ?? []) {
67
+ paths.add(legacy);
68
+ }
69
+ }
70
+ }
71
+ }
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
+ }
78
+ return [...paths].sort();
79
+ }
@@ -1,4 +1,5 @@
1
1
  import { emitObservabilityEvent } from '../observability/observability-service.js';
2
+ import { ownerSkillForPath } from '../observability/owner-skill-map.js';
2
3
  /**
3
4
  * Slice C of v2.11.1 — observability hook #7/7. Fire-and-forget per PRD Q4. The
4
5
  * synchronous emit never throws and never blocks the prereq check's return
@@ -21,7 +22,18 @@ export function emitPrereqTransitionEvent(opts) {
21
22
  artifactRole: opts.role,
22
23
  to: opts.newState,
23
24
  prereqOk: opts.result.ok,
24
- missingCount: opts.result.missing.length
25
+ missingCount: opts.result.missing.length,
26
+ // The LIST, not only its length: the count says how many artifacts were
27
+ // missing, and the list says which ones and which skill owns each, so a
28
+ // reader can name the skill that failed to deliver. Ownership is per
29
+ // missing item; an aggregate owner is the reader's job, not the
30
+ // writer's.
31
+ missing: opts.result.missing.map((m) => ({
32
+ path: m.path,
33
+ description: m.description,
34
+ kind: m.kind,
35
+ ownerSkill: ownerSkillForPath(m.path)
36
+ }))
25
37
  }
26
38
  }, { projectRoot: opts.projectRoot });
27
39
  }
@@ -0,0 +1,106 @@
1
+ import type { RequestType } from './artifact-prerequisites.js';
2
+ import type { RdGatePhase, RdGateViolationKind } from './rd-transition-gates.js';
3
+ /** The gates the RD transition layer decides, by their stable ids. */
4
+ export type RdGateId = 'file-size-ratchet' | 'declared-type-corroboration' | 'claim-table';
5
+ /**
6
+ * Every gate id, as a list.
7
+ *
8
+ * A consumer that has to RECOGNISE a gate id cannot re-type the union: a
9
+ * second copy of the vocabulary is a list that rots, and it rots silently —
10
+ * a gate id added upstream would not be in the copy, so a gate that PASSED
11
+ * would be read as "not a gate we know" and never counted as evaluated.
12
+ */
13
+ export declare const RD_GATE_IDS: readonly RdGateId[];
14
+ /** What the gate decided about the transition. */
15
+ export type RdGateOutcome = 'pass' | 'block' | 'bypass';
16
+ /**
17
+ * Every gate outcome, as a list.
18
+ *
19
+ * A consumer that has to RECOGNISE an outcome cannot re-type the union: a
20
+ * second copy of the vocabulary is a list that rots, and it rots SILENTLY —
21
+ * an outcome added upstream would not be in the copy, so the reader would
22
+ * treat a `pass` as "not a pass" and report a slice that evaluated every gate
23
+ * as one that skipped one.
24
+ */
25
+ export declare const RD_GATE_OUTCOMES: readonly RdGateOutcome[];
26
+ /**
27
+ * Whether a value is one of the gate outcomes this build knows.
28
+ *
29
+ * An outcome this build does not know is UNREADABLE, not "not evaluated" —
30
+ * the two are different facts, and only the second one is a finding.
31
+ */
32
+ export declare function isRdGateOutcome(value: unknown): value is RdGateOutcome;
33
+ /** The ids of the gates the bypass note names, in the note's order. */
34
+ export declare function notedGateIds(phase: RdGatePhase): readonly RdGateId[];
35
+ /**
36
+ * The gates that are live for a transition, by its phase and by whether the
37
+ * declared type is tooling-only.
38
+ */
39
+ export declare function liveGateIds(phase: RdGatePhase, judged: boolean): readonly RdGateId[];
40
+ /** The prose the bypass note uses for one gate id. */
41
+ export declare function gateLabel(gateId: RdGateId): string;
42
+ /**
43
+ * Why ONE gate did not run, when the transition was bypassed.
44
+ *
45
+ * PER GATE, not the shared note: the note the artifact carries names the
46
+ * skipped gates in prose, and it does not name every gate that stood down —
47
+ * so it cannot be the reason for all of them. The note stays the prose; this
48
+ * is the machine-facing explanation.
49
+ */
50
+ export declare function bypassReason(gateId: RdGateId, phase: RdGatePhase): string;
51
+ /**
52
+ * Why the claim table could not be evaluated. The causes are DIFFERENT facts
53
+ * — no artifact at all, or a table some rid never filled in — and a consumer
54
+ * has to be able to tell them apart. (The third cause, a diff that could not
55
+ * be obtained, is a `block` with its own `violationKind`.)
56
+ */
57
+ export declare function claimTableReason(artifactCount: number, missingCount: number): string;
58
+ /** The transition a gate decision belongs to. */
59
+ export type RdGateContext = {
60
+ readonly projectRoot: string;
61
+ readonly sessionId: string;
62
+ readonly sliceRid: string;
63
+ readonly phase: RdGatePhase;
64
+ /**
65
+ * The declared type of the slice, as the transition judged it. It travels
66
+ * with the event because the LIVE SET depends on it: a consumer that wants
67
+ * to know whether a gate was applicable has to read it HERE, not from the
68
+ * request artifact — `peaks request retag` rewrites the artifact's type
69
+ * line with no state guard, so the artifact carries the CURRENT type, not
70
+ * the type the transition ran under. A metric that has to re-read mutable
71
+ * session state is not reproducible from the events alone.
72
+ */
73
+ readonly declaredType: RequestType;
74
+ };
75
+ /** The decision half of a gate event: what the gate decided, and why. */
76
+ export type RdGateDecision = {
77
+ readonly violationKind?: RdGateViolationKind | undefined;
78
+ readonly reason?: string | undefined;
79
+ };
80
+ /** The recorder for ONE transition: it fills in the transition's identity. */
81
+ export type RdGateRecorder = (gateId: RdGateId, outcome: RdGateOutcome, decision?: RdGateDecision) => void;
82
+ /** Bind the transition's identity, once. */
83
+ export declare function rdGateRecorder(context: RdGateContext): RdGateRecorder;
84
+ /**
85
+ * Record ONE gate decision in the session's observability stream.
86
+ *
87
+ * The detail carries the DECLARED TYPE, not a derived "was this slice
88
+ * tooling-only" boolean: the type is the more informative datum, and a consumer
89
+ * that has to re-read the request artifact to learn whether a gate was live
90
+ * cannot reproduce the answer from the events alone.
91
+ *
92
+ * The optional fields carry `| undefined` on purpose: this repository
93
+ * compiles with `exactOptionalPropertyTypes`, so a caller that forwards a
94
+ * possibly-absent value could not pass it to a plain optional property.
95
+ */
96
+ export declare function emitRdGateEvent(opts: {
97
+ readonly projectRoot: string;
98
+ readonly sessionId: string;
99
+ readonly sliceRid: string;
100
+ readonly gateId: RdGateId;
101
+ readonly phase: RdGatePhase;
102
+ readonly declaredType: RequestType;
103
+ readonly outcome: RdGateOutcome;
104
+ readonly violationKind?: RdGateViolationKind | undefined;
105
+ readonly reason?: string | undefined;
106
+ }): void;