@williacj/rigger 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +370 -2
  3. package/package.json +56 -4
  4. package/scripts/doc-reference-check.mjs +59 -0
  5. package/scripts/gate-check.mjs +249 -0
  6. package/scripts/lib/pack-result.mjs +9 -0
  7. package/scripts/record-commit.mjs +67 -0
  8. package/src/cli/doctor.mjs +1021 -0
  9. package/src/cli/init.mjs +384 -0
  10. package/src/cli/once.mjs +489 -0
  11. package/src/cli/pause.mjs +56 -0
  12. package/src/cli/plan.mjs +106 -0
  13. package/src/cli/recording.mjs +52 -0
  14. package/src/cli/report.mjs +242 -0
  15. package/src/cli/resume.mjs +96 -0
  16. package/src/cli/rigger.mjs +12 -0
  17. package/src/cli/run.mjs +10 -0
  18. package/src/cli/setup-board.mjs +108 -0
  19. package/src/cli/verbs.mjs +82 -0
  20. package/src/cli/verdict.mjs +180 -0
  21. package/src/config/validate.mjs +960 -0
  22. package/src/execution/groups.mjs +185 -0
  23. package/src/execution/kept-output.mjs +21 -0
  24. package/src/execution/role.mjs +171 -0
  25. package/src/execution/run.mjs +490 -0
  26. package/src/execution/step.mjs +26 -0
  27. package/src/execution/workspace.mjs +866 -0
  28. package/src/observation/push.mjs +103 -0
  29. package/src/observation/report.mjs +415 -0
  30. package/src/observation/sink.mjs +271 -0
  31. package/src/package-commit.json +1 -0
  32. package/src/scheduling/admission.mjs +390 -0
  33. package/src/scheduling/clock.mjs +98 -0
  34. package/src/scheduling/lane.mjs +160 -0
  35. package/src/scheduling/loop.mjs +1738 -0
  36. package/src/scheduling/pull-order.mjs +46 -0
  37. package/src/substrate/data-ref.mjs +147 -0
  38. package/src/substrate/forge/assets.mjs +5 -0
  39. package/src/substrate/forge/graphql.mjs +258 -0
  40. package/src/substrate/forge/item-write.mjs +74 -0
  41. package/src/substrate/forge/read.mjs +998 -0
  42. package/src/substrate/forge/repository-write.mjs +152 -0
  43. package/src/substrate/forge/runners.mjs +510 -0
  44. package/src/substrate/forge/schema-write.mjs +70 -0
  45. package/src/substrate/forge/write-made.mjs +40 -0
  46. package/src/substrate/git-environment.mjs +54 -0
  47. package/src/substrate/host.mjs +23 -0
  48. package/src/substrate/launchd.mjs +23 -0
  49. package/src/substrate/process-table.sh +48 -0
  50. package/src/substrate/process.mjs +2474 -0
  51. package/src/substrate/providers/adapters.mjs +8 -0
  52. package/src/substrate/providers/claude.mjs +427 -0
  53. package/src/substrate/providers/codex.mjs +349 -0
  54. package/src/substrate/standard-error.mjs +134 -0
  55. package/src/substrate/worktrees.mjs +517 -0
  56. package/src/workflow/clock-mark.mjs +40 -0
  57. package/src/workflow/escalation.mjs +110 -0
  58. package/src/workflow/facts.mjs +92 -0
  59. package/src/workflow/first-above.mjs +17 -0
  60. package/src/workflow/form-check.mjs +88 -0
  61. package/src/workflow/gate.mjs +62 -0
  62. package/src/workflow/judges.mjs +695 -0
  63. package/src/workflow/marker.mjs +265 -0
  64. package/src/workflow/next-action.mjs +456 -0
  65. package/src/workflow/status-issue.mjs +268 -0
  66. package/src/workflow/transitions.mjs +588 -0
  67. package/templates/claude/agents/architect.md +116 -0
  68. package/templates/claude/agents/engineer.md +57 -0
  69. package/templates/claude/agents/pm.md +114 -0
  70. package/templates/claude/agents/reviewer.md +37 -0
  71. package/templates/claude/agents/spike-engineer.md +80 -0
  72. package/templates/claude/hooks/refuse-reserved-git-commands.mjs +909 -0
  73. package/templates/claude/settings.json +50 -0
  74. package/templates/claude/skills/acceptance/SKILL.md +275 -0
  75. package/templates/claude/skills/agent-style/SKILL.md +78 -0
  76. package/templates/claude/skills/code-review/SKILL.md +242 -0
  77. package/templates/claude/skills/proposal/SKILL.md +175 -0
  78. package/templates/claude/skills/spec-style/SKILL.md +112 -0
  79. package/templates/claude/skills/tdd/SKILL.md +230 -0
  80. package/templates/codex/config.toml +19 -0
  81. package/templates/doc-reference-check.md +25 -0
  82. package/templates/githooks/pre-push +24 -0
  83. package/templates/github/workflows/rigger-gate.yml +209 -0
  84. package/templates/launchd/com.williacj.rigger.plist +31 -0
  85. package/templates/rigger.config.mjs +78 -0
@@ -0,0 +1,103 @@
1
+ // ABOUTME: L5's serialized stream pushes at drains and normal returns, their recorded outcomes,
2
+ // and the shared line naming a push that did not succeed ("Pushing the stream").
3
+
4
+ import { readFileSync } from 'node:fs';
5
+
6
+ import { DATA_REF, pushStream } from '../substrate/data-ref.mjs';
7
+ import { EVENT_REFUSED } from '../substrate/process.mjs';
8
+ import { writeWhole } from '../substrate/standard-error.mjs';
9
+ import { streamPath } from './sink.mjs';
10
+
11
+ /**
12
+ * What the push uses where its caller hands nothing else: L0's push side, the write to standard
13
+ * error L5's sink makes, and the clock `ms` is read on.
14
+ */
15
+ export const PUSH_DEFAULTS = { side: pushStream, write: writeWhole, now: Date.now };
16
+
17
+ /**
18
+ * The push `recording` makes as a verb returns normally, handed `{ sink, run, config, repository,
19
+ * directory, answer }`: the run's sink and id, the config the verb read and the validator admitted,
20
+ * the repository it named, that repository's state directory and the verb's answer. It answers the
21
+ * answer the verb then gives.
22
+ *
23
+ * It pushes only where `telemetry.push` is exactly `true`, since `R-SAFE-3` keeps the copy off
24
+ * until the owner plainly turns it on, and only where the stream holds a line stamped with this
25
+ * run's id, so a verb whose sink appended nothing makes no push ("When L5 pushes"). The push side is
26
+ * handed the stream's bytes as they stand at the push's start, and an `L0` emitter on the sink.
27
+ *
28
+ * A push that did not succeed leaves the verb's answer as it was, and `write` says so in one line.
29
+ * An event the sink refused is no push that failed ("Failure model"): the verb exits 1, its own text
30
+ * kept and followed by one line naming what went unrecorded. `side`, `spawn`, `write` and `now`
31
+ * stand in for L0's push side, its spawn, the write to standard error and the clock in tests.
32
+ *
33
+ * A drain supplies `handOver` instead of `answer`: its unsuccessful push goes there as `{ push }`,
34
+ * and a refused event as `{ failure }`, once the push settles. One closure belongs to one verb
35
+ * invocation. It holds one active copy and at most one waiting request; drains coalesce, and a
36
+ * return replaces a waiting drain and waits for its own copy. Bytes are read only when a request
37
+ * leaves the queue.
38
+ */
39
+ export function pushAtReturn({ side = PUSH_DEFAULTS.side, spawn, write = PUSH_DEFAULTS.write, now = PUSH_DEFAULTS.now } = {}) {
40
+ let flying = false;
41
+ let queued;
42
+ /** Starts one copy; a queued return replaces the one drain follow-up it serves. */
43
+ const start = ({ given, resolve, reject }) => {
44
+ flying = true;
45
+ perform(given).then(resolve, reject).then(() => {
46
+ flying = false;
47
+ const next = queued;
48
+ queued = undefined;
49
+ if (next !== undefined) start(next);
50
+ });
51
+ };
52
+ const perform = async ({ sink, run, config, repository, directory, answer, handOver }) => {
53
+ if (config?.telemetry?.push !== true) return answer;
54
+ const start = now();
55
+ let stream;
56
+ try {
57
+ stream = readFileSync(streamPath(directory));
58
+ } catch {
59
+ // A stream absent, or one L5 cannot read, holds no line it can show is this run's own.
60
+ return answer;
61
+ }
62
+ // Every line the sink writes opens with `ts` and then `run`, as `JSON.stringify` orders the
63
+ // envelope, so a line of this run's own holds this text.
64
+ if (!stream.includes(`"run":${JSON.stringify(run)}`)) return answer;
65
+ let answered;
66
+ try {
67
+ answered = await side({ repository, stream, emitter: sink.emitter({ layer: 'L0' }), now, ...(spawn === undefined ? {} : { spawn }) });
68
+ } catch (failure) {
69
+ if (failure?.code === EVENT_REFUSED) return handOver === undefined ? refused(answer, failure.message) : handOver({ failure });
70
+ answered = { outcome: 'failed', reason: failure?.message ?? String(failure) };
71
+ }
72
+ const { outcome, ...fields } = answered;
73
+ try {
74
+ sink.emitter({ layer: 'L5', dispatch: null }).emit('push.end', { ref: DATA_REF, outcome, ms: now() - start, ...fields });
75
+ } catch (refusal) {
76
+ const said = `the sink refused push.end, so it went unrecorded: ${refusal.message}`;
77
+ return handOver === undefined ? refused(answer, said) : handOver({ failure: new Error(said, { cause: refusal }) });
78
+ }
79
+ if (outcome !== 'pushed') {
80
+ if (handOver === undefined) write(failedPushLine(answered));
81
+ else handOver({ push: answered });
82
+ }
83
+ return answer;
84
+ };
85
+ return (given) => new Promise((resolve, reject) => {
86
+ const request = { given, resolve, reject };
87
+ if (!flying) start(request);
88
+ else if (given.handOver === undefined) queued = request;
89
+ else {
90
+ if (queued === undefined || queued.given.handOver !== undefined) queued = request;
91
+ resolve();
92
+ }
93
+ });
94
+ }
95
+
96
+ /** The failure line shared by a return's push and a drain's hand-over. */
97
+ export const failedPushLine = ({ outcome, reason }) => `rigger: the push of the event stream to ${DATA_REF} ended ${outcome}: ${oneLine(reason)}\n`;
98
+
99
+ /** The verb's answer where the sink refused an event of the push's: its own text, then the refusal. */
100
+ const refused = (answer, said) => ({ text: `${answer.text}\nrigger: ${oneLine(said)}`, code: 1 });
101
+
102
+ /** `text` on one line, its line breaks read as separators. */
103
+ const oneLine = (text) => String(text).split(/\r?\n/).filter(Boolean).join('; ');
@@ -0,0 +1,415 @@
1
+ // ABOUTME: L5's report: L0's, L1's, L2's, L3's and L4's signals and marker dispatch checks derived
2
+ // from one state directory's event stream.
3
+
4
+ import { existsSync } from 'node:fs';
5
+
6
+ import { readEvents, streamPath } from './sink.mjs';
7
+
8
+ /** Milliseconds in an hour: the unit throughput is counted per, and a duration is printed in. */
9
+ export const HOUR = 3_600_000;
10
+
11
+ /** `events` grouped by run, each run's events in line order, the runs in the order each first appears. */
12
+ function byRun(events) {
13
+ const runs = new Map();
14
+ for (const event of events) {
15
+ if (!runs.has(event.run)) runs.set(event.run, []);
16
+ runs.get(event.run).push(event);
17
+ }
18
+ return runs;
19
+ }
20
+
21
+ /**
22
+ * L0's substrate fault rate, for the forge and for git, per run in the order each run first
23
+ * appears and across the stream: `faults` of `calls`. `calls` is the L0 `call.end` events whose
24
+ * `system` is that system, excluding none; `faults` is those whose `outcome` is `failed` or
25
+ * `timed-out`. Beyond the `layer` and `event` that select a `call.end`, it reads `run`, `system`
26
+ * and `outcome`, and no other event or field.
27
+ */
28
+ function l0Signals(events) {
29
+ const rate = (recorded, system) => {
30
+ const calls = recorded.filter((event) => event.layer === 'L0' && event.event === 'call.end' && event.system === system);
31
+ return { faults: calls.filter((event) => ['failed', 'timed-out'].includes(event.outcome)).length, calls: calls.length };
32
+ };
33
+ const rates = (recorded) => ({ forge: rate(recorded, 'forge'), git: rate(recorded, 'git') });
34
+ return { runs: [...byRun(events)].map(([run, recorded]) => ({ run, ...rates(recorded) })), stream: rates(events) };
35
+ }
36
+
37
+ /**
38
+ * L1's signals per run, in the order each run first appears, and across the stream.
39
+ *
40
+ * - **Execution duration:** each L1 `dispatch.end`'s `dispatch`, `card` where it carries one, and
41
+ * `ms`. The stream's figure is the count of those ends, each listed under its run.
42
+ * - **Survivor rate:** `killed` of `of`. `of` is the L1 `dispatch.end` events, less those carrying
43
+ * `reason`, which L1 records where it got no result for the command. `killed` is those whose id an
44
+ * L0 `survivor.killed` or `group.killed` carries as its `dispatch`, anywhere in the stream; a kill
45
+ * naming no dispatch, null or absent alike, is counted nowhere.
46
+ * - **Attempts:** work claims that dispatched, across the stream, with redos after an
47
+ * interruption counted and named apart from first attempts.
48
+ */
49
+ function l1Signals(events) {
50
+ const ends = (recorded) => recorded.filter((event) => event.layer === 'L1' && event.event === 'dispatch.end');
51
+ const killed = new Set(events
52
+ .filter((event) => event.layer === 'L0' && ['survivor.killed', 'group.killed'].includes(event.event) && event.dispatch != null)
53
+ .map((event) => event.dispatch));
54
+ const survivors = (recorded) => {
55
+ const counted = ends(recorded).filter((event) => event.reason === undefined);
56
+ return { killed: counted.filter((event) => killed.has(event.dispatch)).length, of: counted.length };
57
+ };
58
+ const runs = [...byRun(events)].map(([run, recorded]) => ({
59
+ run, durations: ends(recorded).map(({ dispatch, card, ms }) => ({ dispatch, card, ms })), survivors: survivors(recorded),
60
+ }));
61
+ return { runs, stream: { ended: ends(events).length, survivors: survivors(events), ...attempts(events) } };
62
+ }
63
+
64
+ /** Whether `event` is a host fault L2 recorded under a card: `R-RECORD-2`'s "how often a host fault interrupted it". */
65
+ const hostFault = (event) => event.layer === 'L2' && event.card != null && (['maker.failed', 'judge.withheld'].includes(event.event)
66
+ || (event.event === 'attempt.failed' && event.class === 'environment' && event.maker === undefined));
67
+
68
+ /**
69
+ * The work claims among one run's events. A claim of a card runs from an L3 `pull` under it to its
70
+ * next, and is a work claim where no L3 `merge.start` under the card falls within it. Only L3's
71
+ * `dispatch` says it did something, and only its own run's `slot.release` says it was not interrupted.
72
+ */
73
+ function workClaims(recorded) {
74
+ const current = new Map();
75
+ const claims = [];
76
+ for (const event of recorded) {
77
+ if (event.layer !== 'L3' || event.card == null) continue;
78
+ if (event.event === 'pull') {
79
+ const claim = { pull: event, merging: false, didSomething: false, interrupted: true };
80
+ current.set(event.card, claim);
81
+ claims.push(claim);
82
+ }
83
+ const claim = current.get(event.card);
84
+ if (!claim) continue;
85
+ if (event.event === 'merge.start') claim.merging = true;
86
+ if (event.event === 'dispatch') claim.didSomething = true;
87
+ if (event.event === 'slot.release') claim.interrupted = false;
88
+ }
89
+ return claims.filter((claim) => !claim.merging);
90
+ }
91
+
92
+ /** First attempts and redos, in stream line order, as "Redos after an interruption" defines them. */
93
+ function attempts(events) {
94
+ const claims = new Map([...byRun(events).values()].flatMap(workClaims).map((claim) => [claim.pull, claim]));
95
+ const previous = new Map();
96
+ const redos = [];
97
+ let firstAttempts = 0;
98
+ for (const event of events) {
99
+ const claim = claims.get(event);
100
+ if (!claim?.didSomething) continue;
101
+ const earlier = previous.get(event.card);
102
+ if (earlier && earlier.pull.run !== event.run && earlier.interrupted) redos.push({ card: event.card, run: event.run });
103
+ else firstAttempts += 1;
104
+ previous.set(event.card, claim);
105
+ }
106
+ return { firstAttempts, redos };
107
+ }
108
+
109
+ /** Distinct cards escalated by L2 and pulled by L3, counted independently over the given span. */
110
+ function escalationsIn(recorded) {
111
+ const escalations = recorded.filter((event) => event.layer === 'L2' && event.event === 'review.escalate' && event.card != null);
112
+ const pulls = recorded.filter((event) => event.layer === 'L3' && event.event === 'pull' && event.card != null);
113
+ return {
114
+ escalated: new Set(escalations.map((event) => event.card)).size, pulled: new Set(pulls.map((event) => event.card)).size,
115
+ entries: escalations.map(({ card, category, raiser, reason, destination }) => ({ card, category, raiser, reason, destination })),
116
+ };
117
+ }
118
+
119
+ /** Escalation events grouped only by their recorded run and class, with absent classes named null. */
120
+ function escalationCauses(events) {
121
+ const recorded = events.filter((event) => event.layer === 'L2' && event.event === 'review.escalate' && event.card != null);
122
+ const counts = (entries) => {
123
+ const classes = new Map();
124
+ for (const event of entries) {
125
+ const cause = event.class ?? null;
126
+ classes.set(cause, (classes.get(cause) ?? 0) + 1);
127
+ }
128
+ return { classes: [...classes].map(([cause, count]) => ({ class: cause, count })),
129
+ infrastructure: (classes.get('environment') ?? 0) + (classes.get('card-local') ?? 0) };
130
+ };
131
+ return { runs: [...byRun(recorded)].map(([run, entries]) => ({ run, ...counts(entries) })), stream: counts(recorded) };
132
+ }
133
+
134
+ /** Distinct merged cards with an all-sound decision before a successful end at that card/head. */
135
+ function freshMerges(events) {
136
+ const merged = new Set();
137
+ const decisions = new Map();
138
+ const fresh = new Set();
139
+ for (const event of events) {
140
+ if (event.card == null) continue;
141
+ if (event.layer === 'L2' && event.event === 'transition' && ['merged', 'mergedFromOwner'].includes(event.cause)) merged.add(event.card);
142
+ if (event.layer === 'L2' && event.event === 'merge.decided' && event.judges?.every(({ verdict }) => verdict === 'sound')) {
143
+ if (!decisions.has(event.card)) decisions.set(event.card, new Set());
144
+ decisions.get(event.card).add(event.head);
145
+ }
146
+ if (event.layer === 'L3' && event.event === 'merge.end' && event.outcome === 'merged' && decisions.get(event.card)?.has(event.head)) fresh.add(event.card);
147
+ }
148
+ const flagged = [...merged].filter((card) => !fresh.has(card));
149
+ return { fresh: merged.size - flagged.length, of: merged.size, flagged };
150
+ }
151
+
152
+ /** The one rounds derivation: distinct head/digest pairs per card over all L2 marker reads. */
153
+ function roundsPerCard(events) {
154
+ const cards = new Map();
155
+ const kinds = new Map();
156
+ for (const event of events) {
157
+ if (event.layer === 'L3' && event.event === 'pull' && event.card != null && event.kind != null) kinds.set(event.card, event.kind);
158
+ if (event.layer !== 'L2' || event.event !== 'marker.read' || event.card == null) continue;
159
+ if (!cards.has(event.card)) cards.set(event.card, new Set());
160
+ cards.get(event.card).add(JSON.stringify([event.head, event.digest]));
161
+ }
162
+ return [...cards].map(([card, pairs]) => ({ card, kind: kinds.get(card) ?? null, rounds: pairs.size }));
163
+ }
164
+
165
+ /**
166
+ * Each role dispatch's window, in the line order of its L3 `dispatch`: `dispatch`, `role`, `card`,
167
+ * whether it is a maker dispatch, and `from` and `to` in epoch milliseconds. A role dispatch is an
168
+ * L3 `dispatch` carrying `role` and no `step`; a maker dispatch also carries `attempt`. A window runs
169
+ * from its L1 `dispatch.start`'s `ts` to its `dispatch.end`'s, both ends included. With no end it
170
+ * ends at the first L3 `run.start` after its start in line order, or stays open to the stream's end.
171
+ * A role dispatch with no `dispatch.start` has no window.
172
+ */
173
+ function windows(events) {
174
+ const starts = new Map();
175
+ const ends = new Map();
176
+ for (const [index, event] of events.entries()) {
177
+ if (event.layer === 'L1' && event.event === 'dispatch.start' && !starts.has(event.dispatch)) starts.set(event.dispatch, { index, ts: Date.parse(event.ts) });
178
+ if (event.layer === 'L1' && event.event === 'dispatch.end' && !ends.has(event.dispatch)) ends.set(event.dispatch, Date.parse(event.ts));
179
+ }
180
+ const restarts = [...events.entries()].filter(([, event]) => event.layer === 'L3' && event.event === 'run.start');
181
+ return events.filter((event) => event.layer === 'L3' && event.event === 'dispatch' && event.role !== undefined && event.step === undefined
182
+ && starts.has(event.dispatch)).map(({ card, dispatch, role, attempt }) => {
183
+ const { index, ts } = starts.get(dispatch);
184
+ const restart = restarts.find(([at]) => at > index);
185
+ const to = ends.get(dispatch) ?? (restart ? Date.parse(restart[1].ts) : Infinity);
186
+ return { card, dispatch, role, maker: attempt !== undefined, from: ts, to };
187
+ });
188
+ }
189
+
190
+ /** Each card's `acceptance.history` revisions, de-duplicated by `editedAt` and oldest first, with its `opened` and `author`. */
191
+ function histories(events) {
192
+ const cards = new Map();
193
+ for (const event of events) {
194
+ if (event.layer !== 'L2' || event.event !== 'acceptance.history' || event.card == null) continue;
195
+ if (!cards.has(event.card)) cards.set(event.card, { opened: event.opened, author: undefined, revisions: new Map() });
196
+ const card = cards.get(event.card);
197
+ card.author ??= event.author;
198
+ for (const revision of event.revisions ?? []) {
199
+ if (!card.revisions.has(revision.editedAt)) card.revisions.set(revision.editedAt, revision);
200
+ }
201
+ }
202
+ return [...cards].map(([card, { opened, author, revisions }]) => ({
203
+ card, opened, author, revisions: [...revisions.values()].sort((a, b) => Date.parse(a.editedAt) - Date.parse(b.editedAt)),
204
+ }));
205
+ }
206
+
207
+ /**
208
+ * L2's acceptance changes across the stream, as "Acceptance changes and who made them" defines
209
+ * them: each change, with its `editor`, the role dispatches whose window holds its `editedAt`, by id
210
+ * and `role`, and whether one is the card's maker dispatch; each deleted revision, as content
211
+ * deleted; each revision after the card's first `pull` holding more `items` than the nearest
212
+ * revision carrying `items` at or before it; and each card's author. A change is a revision whose
213
+ * `digest` differs from the nearest earlier revision carrying one, and a deleted revision is never
214
+ * one. It reads `acceptance.history` by `card`, `opened`, `revisions` and `author`, L1's
215
+ * `dispatch.start` and `dispatch.end` by `ts` and `dispatch`, L3's `dispatch` by `card`,
216
+ * `dispatch`, `role`, `attempt` and `step`, and L3's `run.start` and `pull` by `ts`, `pull` also by
217
+ * `card`, and no other event or field.
218
+ */
219
+ function acceptanceChanges(events) {
220
+ const held = windows(events);
221
+ const holding = (time) => held.filter(({ from, to }) => from <= time && time <= to);
222
+ const pulled = new Map();
223
+ for (const event of events) {
224
+ if (event.layer === 'L3' && event.event === 'pull' && event.card != null && !pulled.has(event.card)) pulled.set(event.card, Date.parse(event.ts));
225
+ }
226
+ const answer = { changes: [], deleted: [], grew: [], authors: [] };
227
+ for (const { card, opened, author, revisions } of histories(events)) {
228
+ let digest;
229
+ let admitted;
230
+ for (const { editedAt, editor, deleted, digest: current, items } of revisions) {
231
+ const time = Date.parse(editedAt);
232
+ if (deleted) {
233
+ answer.deleted.push({ card, editedAt, editor });
234
+ continue;
235
+ }
236
+ if (digest !== undefined && current !== digest) {
237
+ const by = holding(time);
238
+ answer.changes.push({ card, editedAt, editor, dispatches: by.map(({ dispatch, role }) => ({ dispatch, role })),
239
+ duringMaker: by.some((window) => window.maker && window.card === card) });
240
+ }
241
+ digest = current;
242
+ if (!pulled.has(card) || time <= pulled.get(card)) admitted = items;
243
+ else if (admitted !== undefined && items > admitted) answer.grew.push({ card, editedAt, items, admitted });
244
+ }
245
+ const roles = [...new Set(holding(Date.parse(opened?.at)).map(({ role }) => role))];
246
+ answer.authors.push(author !== undefined ? { card, source: 'author', names: [author] }
247
+ : roles.length > 0 ? { card, source: 'dispatches', names: roles } : { card, source: 'owner', names: [] });
248
+ }
249
+ return answer;
250
+ }
251
+
252
+ /**
253
+ * L2's host faults per run, in the order each run first appears, and across the stream: `faults`
254
+ * of `claims`. `faults` counts each `maker.failed`, each `judge.withheld`, and each
255
+ * `attempt.failed` carrying `class: 'environment'` and no `maker`, under a card; one carrying
256
+ * `maker` records the fault its `maker.failed` already counts. `claims` is the work claims, by
257
+ * `run` and `card`, so the stream's is the sum of its runs'. Escalations count distinct cards
258
+ * independently in each span; rounds read the whole stream once through roundsPerCard, and
259
+ * acceptance changes through acceptanceChanges.
260
+ */
261
+ function l2Signals(events) {
262
+ const runs = [...byRun(events)].map(([run, recorded]) => ({
263
+ run, hostFaults: { faults: recorded.filter(hostFault).length, claims: workClaims(recorded).length }, escalations: escalationsIn(recorded),
264
+ }));
265
+ const claims = runs.reduce((sum, { hostFaults }) => sum + hostFaults.claims, 0);
266
+ return { runs, escalationCauses: escalationCauses(events), stream: {
267
+ hostFaults: { faults: events.filter(hostFault).length, claims },
268
+ escalations: escalationsIn(events), rounds: roundsPerCard(events), freshMerges: freshMerges(events), acceptance: acceptanceChanges(events),
269
+ } };
270
+ }
271
+
272
+ /**
273
+ * L3's signals for each run in `events`, in the order each run first appears.
274
+ *
275
+ * - **Throughput:** slot-release events per hour, over the span from the run's first event to its
276
+ * last, whichever layer recorded them.
277
+ * - **Utilization:** the sum of each card's pull-to-release interval, divided by the run's
278
+ * recorded N, the `concurrency` its `run.start` carries, multiplied by that span.
279
+ * - **Queue carried:** each L3 `pull`'s `card` and `queueDepth`, the pullable cards it left
280
+ * unclaimed, in line order, a merge claim's among them, as `queue`.
281
+ *
282
+ * Each run answers the facts the two are computed from as well as the two, so a reader can check
283
+ * the arithmetic: `from` and `to` in epoch milliseconds, `releases`, `pulled` (the summed
284
+ * intervals, in milliseconds) and `n`. Where the span is zero neither signal is a number, and
285
+ * `throughput` and `utilization` are null. A run that recorded no `run.start`, which a pull fired
286
+ * alone does not, has no N, and its `n` is undefined and its `utilization` null.
287
+ */
288
+ function l3Signals(events) {
289
+ return [...byRun(events)].map(([run, recorded]) => {
290
+ const times = recorded.map((event) => Date.parse(event.ts));
291
+ const [from, to] = [times[0], times.at(-1)];
292
+ const l3 = recorded.filter((event) => event.layer === 'L3');
293
+ const n = l3.find((event) => event.event === 'run.start')?.concurrency;
294
+ const pulledAt = new Map();
295
+ let releases = 0;
296
+ let pulled = 0;
297
+ for (const event of l3) {
298
+ if (event.event === 'pull') pulledAt.set(event.card, Date.parse(event.ts));
299
+ if (event.event === 'slot.release') {
300
+ releases += 1;
301
+ pulled += Date.parse(event.ts) - pulledAt.get(event.card);
302
+ pulledAt.delete(event.card);
303
+ }
304
+ }
305
+ const span = to - from;
306
+ const queue = l3.filter((event) => event.event === 'pull').map(({ card, queueDepth }) => ({ card, queueDepth }));
307
+ return {
308
+ run, from, to, releases, pulled, n, queue,
309
+ throughput: span === 0 ? null : releases / (span / HOUR),
310
+ utilization: span === 0 || n === undefined ? null : pulled / (n * span),
311
+ };
312
+ });
313
+ }
314
+
315
+ /** Admission hold closes per recorded close-run and across the stream, joined to opens by id alone. */
316
+ function admissionHolds(events) {
317
+ const closes = events.filter((event) => event.layer === 'L3' && event.event === 'admission.close');
318
+ const opened = new Set(events.filter((event) => event.layer === 'L3' && event.event === 'admission.open').map(({ id }) => id));
319
+ const counts = (recorded) => {
320
+ const entries = recorded.filter(({ kind }) => kind === 'hold').map(({ id, reason }) => ({ id, reason, opened: opened.has(id) }));
321
+ return { count: entries.length, entries };
322
+ };
323
+ return { runs: [...byRun(closes)].map(([run, recorded]) => ({ run, ...counts(recorded) })), stream: counts(closes) };
324
+ }
325
+
326
+ /** The four `transition` causes that send a card back for more work: L4's rework. */
327
+ const REWORK = new Set(['continued', 'continuedFromOwner', 'conflicted', 'conflictedFromOwner']);
328
+
329
+ /** How many of `recorded`'s L2 `transition` events send a card back, by their `cause`. */
330
+ const rework = (recorded) => recorded.filter((event) => event.layer === 'L2' && event.event === 'transition' && REWORK.has(event.cause)).length;
331
+
332
+ /**
333
+ * L4's first-pass rate across the stream: `first` of `of`. `of` is the cards under which an L2
334
+ * `transition` whose `cause` is `merged` or `mergedFromOwner` is recorded, less those with no
335
+ * `marker.read`; `first` is those with exactly one round, as L2's roundsPerCard counts rounds.
336
+ */
337
+ function firstPass(events) {
338
+ const merged = new Set(events
339
+ .filter((event) => event.layer === 'L2' && event.event === 'transition' && ['merged', 'mergedFromOwner'].includes(event.cause))
340
+ .map((event) => event.card));
341
+ const judged = roundsPerCard(events).filter(({ card }) => merged.has(card));
342
+ return { first: judged.filter(({ rounds }) => rounds === 1).length, of: judged.length };
343
+ }
344
+
345
+ /**
346
+ * L4's tier accuracy across the stream: `accurate` of `of`. `of` is the pairs of a card and a role
347
+ * with an L3 `dispatch` carrying `role` and `tier` and no `step`; `accurate` is those with no tier
348
+ * correction, a dispatch at another `tier` than the pair's nearest earlier one carrying a `tier`.
349
+ * A role dispatch carrying no `tier` is not read (the architect's ruling, 1067#6459717512).
350
+ */
351
+ function tierAccuracy(events) {
352
+ const tiers = new Map();
353
+ const corrected = new Set();
354
+ for (const event of events) {
355
+ if (event.layer !== 'L3' || event.event !== 'dispatch' || event.card == null || event.step !== undefined
356
+ || event.role === undefined || event.tier === undefined) continue;
357
+ const pair = JSON.stringify([event.card, event.role]);
358
+ if (tiers.has(pair) && tiers.get(pair) !== event.tier) corrected.add(pair);
359
+ tiers.set(pair, event.tier);
360
+ }
361
+ return { accurate: tiers.size - corrected.size, of: tiers.size };
362
+ }
363
+
364
+ /** L4's signals: rework per run, in the order each run first appears, and rework, the first-pass rate and tier accuracy across the stream. */
365
+ function l4Signals(events) {
366
+ return {
367
+ runs: [...byRun(events)].map(([run, recorded]) => ({ run, rework: rework(recorded) })),
368
+ stream: { rework: rework(events), firstPass: firstPass(events), tierAccuracy: tierAccuracy(events) },
369
+ };
370
+ }
371
+
372
+ /** Whether L3 and L1 recorded the judge dispatch that could have written this marker. */
373
+ function wroteMarker(marker, dispatches, starts) {
374
+ if (typeof marker.dispatch !== 'string' || marker.dispatch === '') return false;
375
+ const l3 = dispatches.get(marker.dispatch);
376
+ const l1 = starts.get(marker.dispatch);
377
+ return l3?.card === marker.card && l3.role === marker.role
378
+ && l1?.facts?.pull === marker.pull && l1.facts.head === marker.head
379
+ && typeof l1.digest === 'string' && l1.digest === marker.evidence;
380
+ }
381
+
382
+ /** Agent marker reads with no unique matching dispatch, counted once across repeated reads. */
383
+ function unwrittenMarkers(events) {
384
+ const dispatches = new Map(events.filter((event) => event.layer === 'L3' && event.event === 'dispatch').map((event) => [event.dispatch, event]));
385
+ const starts = new Map(events.filter((event) => event.layer === 'L1' && event.event === 'dispatch.start').map((event) => [event.dispatch, event]));
386
+ const distinct = new Map();
387
+ for (const event of events) {
388
+ if (event.layer !== 'L2' || event.event !== 'marker.read' || event.role === 'owner') continue;
389
+ const key = JSON.stringify([event.card, event.role, event.head, event.digest, event.evidence, event.dispatch, event.verdict, event.reason]);
390
+ if (!distinct.has(key)) distinct.set(key, event);
391
+ }
392
+ const uses = new Map();
393
+ for (const marker of distinct.values()) {
394
+ if (typeof marker.dispatch !== 'string' || marker.dispatch === '') continue;
395
+ uses.set(marker.dispatch, (uses.get(marker.dispatch) ?? 0) + 1);
396
+ }
397
+ return [...distinct.values()]
398
+ .filter((marker) => (uses.get(marker.dispatch) ?? 0) > 1 || !wroteMarker(marker, dispatches, starts))
399
+ .map(({ card, role, head, dispatch, reason }) => ({ card, role, head, dispatch, reason }));
400
+ }
401
+
402
+ /**
403
+ * The report over the state directory `directory`: its stream's `path`, L0's, L1's and L2's
404
+ * signals per run and across the stream, L3's signals per run and admission holds per run and
405
+ * across the stream, L4's rework per run and its signals
406
+ * across the stream, and agent markers with no unique matching recorded dispatch. The latter joins
407
+ * the whole stream, across runs. It reads through the sink and writes nothing; an unreadable line throws as the
408
+ * reader does, naming that line.
409
+ */
410
+ export function report(directory) {
411
+ const path = streamPath(directory);
412
+ if (!existsSync(path)) return { path, l0: null, l1: null, l2: null, runs: null, holds: null, l4: null, markers: null };
413
+ const events = readEvents(directory);
414
+ return { path, l0: l0Signals(events), l1: l1Signals(events), l2: l2Signals(events), runs: l3Signals(events), holds: admissionHolds(events), l4: l4Signals(events), markers: unwrittenMarkers(events) };
415
+ }