@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,271 @@
1
+ // ABOUTME: L5's event sink: it stamps every event with the envelope and appends it to one JSONL
2
+ // stream in the consumer's state directory, holding events until the verb names that directory,
3
+ // and reads the stream back.
4
+
5
+ // One event is one synchronous append of one line. The host tests read back returned emits
6
+ // after SIGKILL, and check separate writers sharing a stream at 200 bytes and 1 MiB per line.
7
+ // There is no explicit disk flush, so power loss can still lose the tail. A reader ignores
8
+ // bytes after the last newline, passes over the fragment a torn append left before a whole event
9
+ // on the same line, and refuses any other newline-terminated line that is not one event
10
+ // (ARCHITECTURE.md, "A torn tail").
11
+
12
+ import { appendFileSync, mkdirSync, readFileSync } from 'node:fs';
13
+ import { join } from 'node:path';
14
+
15
+ import { writeWhole } from '../substrate/standard-error.mjs';
16
+
17
+ const STREAM = 'events.jsonl';
18
+
19
+ // Where every line of the sink's form begins, because the envelope's `ts` comes first.
20
+ const LINE_START = '{"ts":"';
21
+
22
+ // The envelope's own keys. The sink stamps every one of them, so a layer supplying one would be
23
+ // writing a fact about the run or the card that it is not the layer to know.
24
+ const ENVELOPE = ['ts', 'run', 'layer', 'event', 'card', 'dispatch'];
25
+
26
+ /**
27
+ * What the sink cannot invent. An absent value would leave its field out of the JSON, and an
28
+ * event missing one is not the event `R-RECORD-7` asks for, so the sink says so at the call.
29
+ */
30
+ function required(value, name) {
31
+ if (value === undefined) throw new Error(`the sink was given no ${name}, which every event carries`);
32
+ }
33
+
34
+ /** The one stream L5 owns, inside the state directory the consumer named. */
35
+ export const streamPath = (directory) => join(directory, STREAM);
36
+
37
+ /**
38
+ * Open the sink for one run.
39
+ *
40
+ * `now` is the run's clock, read once per event, and it returns epoch milliseconds. `directory`
41
+ * may be left out: a verb opens the sink before its first spawn, which comes before it knows the
42
+ * state directory, and names it later (delta H5). Until then the sink holds each event, stamped
43
+ * when it was emitted.
44
+ *
45
+ * An event leaves the hold only once the append of its whole line returns, and every later append
46
+ * first appends what is still held, in emit order.
47
+ *
48
+ * `end` is idempotent, because the verb and L0's exit cleanup can each call it. A named sink first
49
+ * appends what it still holds there. A sink never named, or one whose state directory refuses that
50
+ * append, writes what it held to standard error there, and a sink never named writes any event
51
+ * after that to standard error as it arrives. A reader of standard error that stops draining it
52
+ * holds either write for no longer than `UNDRAINED_BOUND`, and what it did not take is dropped
53
+ * (`writeWhole`).
54
+ */
55
+ export function openSink({ directory, run, now }) {
56
+ required(run, 'run');
57
+ required(now, 'now');
58
+ let named = directory;
59
+ let made = false;
60
+ let ended = false;
61
+ const held = [];
62
+
63
+ /** One event onto the stream. The directory is made at the first, so a quiet verb makes none. */
64
+ function append(line) {
65
+ if (!made) mkdirSync(named, { recursive: true });
66
+ made = true;
67
+ appendFileSync(streamPath(named), line);
68
+ }
69
+
70
+ /** Every held event onto the stream, in emit order, each leaving the hold once its append returns. */
71
+ function release() {
72
+ while (held.length > 0) {
73
+ append(held[0]);
74
+ held.shift();
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Name the state directory, and write there first every event held until now.
80
+ *
81
+ * A held event was never an append, so nothing refused it. A refusal here is the first, and the
82
+ * failure names every held event its append did not write, the one it tore included, each
83
+ * indented: the sink still holds them, so its next append, or its end, writes each as a record
84
+ * line of its own, and the failure is no second copy of one.
85
+ */
86
+ function name(given) {
87
+ named = given;
88
+ try {
89
+ release();
90
+ } catch (cause) {
91
+ throw new Error(
92
+ `${cause.message}\n${held.length} held event(s) went unrecorded at this naming, and the sink still holds them:\n${held.map((line) => ` ${line}`).join('')}`,
93
+ { cause },
94
+ );
95
+ }
96
+ }
97
+
98
+ /** An emitter for one layer, and the card and dispatch its events arise under. */
99
+ function emitter({ layer, card, dispatch }) {
100
+ required(layer, 'layer');
101
+ return {
102
+ emit(event, fields) {
103
+ required(event, 'event');
104
+ const stamped = Object.keys(fields ?? {}).filter((key) => ENVELOPE.includes(key));
105
+ if (stamped.length > 0) {
106
+ throw new Error(`${event} supplied ${stamped.join(', ')}, which the sink stamps`);
107
+ }
108
+ const record = {
109
+ ts: new Date(now()).toISOString(),
110
+ run,
111
+ layer,
112
+ event,
113
+ card,
114
+ dispatch,
115
+ ...fields,
116
+ };
117
+ const line = `${JSON.stringify(record)}\n`;
118
+ if (named !== undefined) {
119
+ release();
120
+ append(line);
121
+ } else if (ended) writeWhole(line);
122
+ else held.push(line);
123
+ },
124
+ };
125
+ }
126
+
127
+ /**
128
+ * End the run's sink. A named one appends what it still holds; what it cannot append, and what a
129
+ * sink never named held, goes to standard error.
130
+ */
131
+ function end() {
132
+ ended = true;
133
+ if (named !== undefined) {
134
+ try {
135
+ release();
136
+ } catch {
137
+ // What the state directory refused is still held, and standard error is left for it.
138
+ }
139
+ }
140
+ writeWhole(held.splice(0).join(''));
141
+ }
142
+
143
+ return { emitter, name, end };
144
+ }
145
+
146
+ /** The envelope checked at L5's read boundary, before any derivation receives the event. */
147
+ function checkEventEnvelope(event) {
148
+ const describe = (value) => {
149
+ const maximumDepth = 4;
150
+ const maximumLength = 256;
151
+ const elision = '…';
152
+ // Quote only a bounded string, never an entire input object or an unbounded key/value.
153
+ const quote = (text) => JSON.stringify(text.slice(0, maximumLength));
154
+ function* members(container) {
155
+ if (Array.isArray(container)) {
156
+ for (let index = 0; index < container.length; index += 1) yield [undefined, container[index]];
157
+ } else {
158
+ for (const key in container) if (Object.hasOwn(container, key)) yield [key, container[key]];
159
+ }
160
+ }
161
+ const pending = [{ value, depth: 0 }];
162
+ let shown = '';
163
+ while (pending.length > 0 && shown.length < maximumLength) {
164
+ const part = pending.pop();
165
+ if (typeof part === 'string') {
166
+ shown += part;
167
+ } else if (part.iterator) {
168
+ const next = part.iterator.next();
169
+ if (next.done) {
170
+ shown += part.close;
171
+ continue;
172
+ }
173
+ if (!part.first) shown += ',';
174
+ part.first = false;
175
+ pending.push(part);
176
+ const [key, member] = next.value;
177
+ pending.push({ value: member, depth: part.depth });
178
+ if (key !== undefined) pending.push(`${quote(key)}:`);
179
+ } else {
180
+ const { value, depth } = part;
181
+ if (value !== null && typeof value === 'object') {
182
+ if (depth >= maximumDepth) {
183
+ shown += elision;
184
+ continue;
185
+ }
186
+ const array = Array.isArray(value);
187
+ shown += array ? '[' : '{';
188
+ pending.push({ iterator: members(value), first: true, depth: depth + 1, close: array ? ']' : '}' });
189
+ } else if (typeof value === 'string') {
190
+ shown += quote(value);
191
+ } else if (typeof value === 'number') {
192
+ shown += Object.is(value, -0) ? '-0' : String(value);
193
+ } else {
194
+ shown += JSON.stringify(value) ?? 'missing';
195
+ }
196
+ }
197
+ }
198
+ return pending.length > 0 || shown.length > maximumLength ? shown.slice(0, maximumLength - elision.length) + elision : shown;
199
+ };
200
+ if (event === null || typeof event !== 'object' || Array.isArray(event)) {
201
+ throw new Error(`its envelope is ${describe(event)}, not a plain object`);
202
+ }
203
+ const refuse = (field, contract) => {
204
+ throw new Error(`its \`${field}\` is ${describe(event[field])}, not ${contract}`);
205
+ };
206
+ const ts = event.ts;
207
+ if (typeof ts !== 'string' || !Number.isFinite(Date.parse(ts)) || new Date(ts).toISOString() !== ts) {
208
+ refuse('ts', 'an instant in UTC');
209
+ }
210
+ for (const field of ['run', 'event']) {
211
+ if (typeof event[field] !== 'string' || event[field] === '') {
212
+ refuse(field, 'a non-empty string');
213
+ }
214
+ }
215
+ if (!['L0', 'L1', 'L2', 'L3', 'L4', 'L5', 'L6'].includes(event.layer)) {
216
+ refuse('layer', 'L0 through L6');
217
+ }
218
+ if (Object.hasOwn(event, 'card') && !(Number.isSafeInteger(event.card) && event.card > 0)) {
219
+ refuse('card', 'a safe integer above zero');
220
+ }
221
+ if (Object.hasOwn(event, 'dispatch') && event.dispatch !== null && (typeof event.dispatch !== 'string' || event.dispatch === '')) {
222
+ refuse('dispatch', 'null or a non-empty string');
223
+ }
224
+ return event;
225
+ }
226
+
227
+ /**
228
+ * The event a line holds after its fragments: the one from the leftmost offset past the line's
229
+ * start where a sink line begins and the rest of the line is one event, or `undefined` for none.
230
+ */
231
+ function afterFragment(line) {
232
+ for (let offset = line.indexOf(LINE_START, 1); offset !== -1; offset = line.indexOf(LINE_START, offset + 1)) {
233
+ try {
234
+ return checkEventEnvelope(JSON.parse(line.slice(offset)));
235
+ } catch {
236
+ // Not one event from here; a later offset may be.
237
+ }
238
+ }
239
+ return undefined;
240
+ }
241
+
242
+ /**
243
+ * Every event in a state directory's stream, in the order it was recorded.
244
+ *
245
+ * The bytes after the last newline have not yet become an event. Every complete line is read
246
+ * separately, so the whole stream needs no single JavaScript string. A complete line that is not
247
+ * one event, but begins with `{` and holds one from a later offset where a sink line begins, is a
248
+ * torn append's fragment followed by that event: the event is returned and the fragment passed
249
+ * over (ARCHITECTURE.md, "A torn tail", rule 3). Any other such line is refused by its line number:
250
+ * passing over damage would contradict R-RECORD-6.
251
+ */
252
+ export function readEvents(directory) {
253
+ const path = streamPath(directory);
254
+ const stream = readFileSync(path);
255
+ const events = [];
256
+ let start = 0;
257
+ let index = 0;
258
+ for (let end = stream.indexOf(0x0a); end !== -1; end = stream.indexOf(0x0a, start)) {
259
+ const line = stream.toString('utf8', start, end);
260
+ start = end + 1;
261
+ try {
262
+ events.push(checkEventEnvelope(JSON.parse(line)));
263
+ } catch (cause) {
264
+ const event = line.startsWith('{') ? afterFragment(line) : undefined;
265
+ if (event === undefined) throw new Error(`${path} line ${index + 1} is not a recorded event`, { cause });
266
+ events.push(event);
267
+ }
268
+ index += 1;
269
+ }
270
+ return events;
271
+ }
@@ -0,0 +1 @@
1
+ {"commit":"1f3175411699244b137582e266606992c2eed599"}
@@ -0,0 +1,390 @@
1
+ // ABOUTME: L3's admission record, one immutable file per closer in `.rigger/admission/`: the one
2
+ // module that reads it, closes it, opens it and removes its closers on `resume`, recording each change.
3
+
4
+ import * as nodeFs from 'node:fs';
5
+ import { randomBytes } from 'node:crypto';
6
+ import { join } from 'node:path';
7
+
8
+ /** The kinds of closer, each by the word its file's name starts with. */
9
+ const KINDS = ['owner', 'hold'];
10
+
11
+ /** An id: a non-empty run of `0`-`9` and `a`-`z`, holding no `-` and no `.`. */
12
+ const ID = /^[0-9a-z]+$/;
13
+
14
+ /**
15
+ * A closer's name, by its kind; a hold's may carry the number after `after-`, 0 for a repository
16
+ * that held no issue or pull request, or the positive number after `issue-`.
17
+ */
18
+ const OWNER = /^owner-([0-9a-z]+)\.json$/;
19
+ const HOLD = /^hold-([0-9a-z]+)(?:-after-(0|[1-9][0-9]*)|-issue-([1-9][0-9]*))?\.json$/;
20
+
21
+ /** The admission directory inside state directory `directory`. */
22
+ export const admissionPath = (directory) => join(directory, 'admission');
23
+
24
+ /** The failures admission built itself, so a caller tells them from a value of the same shape another layer threw. */
25
+ const built = new WeakSet();
26
+ const own = (failure) => {
27
+ built.add(failure);
28
+ return failure;
29
+ };
30
+
31
+ /** Whether `value` is a failure admission built, read from admission's own record of them and never from `value`. */
32
+ export const admissions = (value) => built.has(value);
33
+
34
+ /** A fresh id, random enough that no other closer or temporary file has had it. */
35
+ const randomId = () => randomBytes(16).toString('hex');
36
+
37
+ /**
38
+ * What a closer's name says of it, or undefined where the name is of no closer form. A hold's
39
+ * number is the string of digits its name writes, so a number of any length reads back exactly.
40
+ */
41
+ function parseName(name) {
42
+ const owner = OWNER.exec(name);
43
+ if (owner) return { kind: 'owner', id: owner[1] };
44
+ const hold = HOLD.exec(name);
45
+ if (!hold) return undefined;
46
+ return { kind: 'hold', id: hold[1], ...(hold[2] !== undefined && { after: hold[2] }), ...(hold[3] !== undefined && { issue: hold[3] }) };
47
+ }
48
+
49
+ /** Whether `content` is a closer's: an object with a non-empty reason and run, and a finite time. */
50
+ const isContent = (content) => typeof content === 'object' && content !== null && !Array.isArray(content)
51
+ && typeof content.reason === 'string' && content.reason !== ''
52
+ && typeof content.time === 'number' && Number.isFinite(content.time)
53
+ && typeof content.run === 'string' && content.run !== '';
54
+
55
+ /**
56
+ * One printable line for `thrown`, whatever value was thrown, never itself a throw: an Error's
57
+ * message, a string, a Symbol's description, or the value's own string, and otherwise the kind of
58
+ * value thrown. It stands apart from `causeOf` in `src/workflow/status-issue.mjs` because this
59
+ * module is in the gate's import closure (as `.github/scripts/gate-closure.mjs` measures it), which that one is not.
60
+ */
61
+ const printable = (thrown) => {
62
+ try {
63
+ const held = thrown instanceof Error ? thrown.message : thrown;
64
+ const said = typeof held === 'string' ? held : typeof held === 'symbol' ? held.toString() : String(held);
65
+ if (said !== '') return said;
66
+ } catch {
67
+ // The value refused to be read or converted; its kind is all that is left to say.
68
+ }
69
+ return `a thrown ${typeof thrown}`;
70
+ };
71
+
72
+ /**
73
+ * A failure's code where it has one, so an answer names the cause, and otherwise its printable
74
+ * line, whatever was thrown.
75
+ */
76
+ const causeOf = (error) => {
77
+ try {
78
+ if (typeof error?.code === 'string') return error.code;
79
+ } catch {
80
+ // A value whose code cannot be read is said as `printable` says it.
81
+ }
82
+ return printable(error);
83
+ };
84
+
85
+ /**
86
+ * The admission module over state directory `directory`, as its caller resolved it. `fs` is the
87
+ * `node:fs` calls it makes, each replaceable so a test can inject what the file system will not
88
+ * give on demand.
89
+ *
90
+ * `read` is synchronous, so that `take` can list inside its synchronous claim.
91
+ */
92
+ export function admission({ directory, run, now, sink, ids = randomId, fs = nodeFs }) {
93
+ const dir = admissionPath(directory);
94
+ const emitter = sink.emitter({ layer: 'L3' });
95
+
96
+ /** Records `event` after its write, a refusal failing the call and naming the event. */
97
+ function record(event, fields) {
98
+ try {
99
+ emitter.emit(event, fields);
100
+ } catch (cause) {
101
+ // The sink's refusal is converted once, so a refusal that answers differently a second time is said as it first was.
102
+ const why = printable(cause);
103
+ throw new Error(`admission changed at ${fields.name}, and the sink refused its ${event} event: ${why}`, { cause: new Error(why) });
104
+ }
105
+ }
106
+
107
+ /** The admission directory's entries, or why it cannot be listed as a directory. */
108
+ function list() {
109
+ try {
110
+ if (!fs.lstatSync(dir).isDirectory()) return { failed: 'not a directory' };
111
+ return { entries: fs.readdirSync(dir, { withFileTypes: true }) };
112
+ } catch (error) {
113
+ if (error.code === 'ENOENT') return { entries: [] };
114
+ return { failed: causeOf(error) };
115
+ }
116
+ }
117
+
118
+ /** A closer file's content, opened without following a link, or `gone` where it vanished. */
119
+ function contentOf(path) {
120
+ let fd;
121
+ try {
122
+ fd = fs.openSync(path, nodeFs.constants.O_RDONLY | nodeFs.constants.O_NOFOLLOW);
123
+ } catch (error) {
124
+ if (error.code === 'ENOENT') return { gone: true };
125
+ return { failed: causeOf(error) };
126
+ }
127
+ try {
128
+ if (!fs.fstatSync(fd).isFile()) return { failed: 'not a regular file' };
129
+ return { content: JSON.parse(fs.readFileSync(fd, 'utf8')) };
130
+ } catch (error) {
131
+ return { failed: causeOf(error) };
132
+ } finally {
133
+ fs.closeSync(fd);
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Whether admission is open, closed naming every closer, or unreadable naming every entry it
139
+ * could not read. A name starting with `.` is no closer and is never opened. A closer listed and
140
+ * gone at its read sends the read back to list again, so the answer comes from one listing
141
+ * every name of which it read, and a closer renamed between the two is never read as open.
142
+ */
143
+ function read() {
144
+ for (;;) {
145
+ const listing = list();
146
+ if (listing.failed) return { state: 'unreadable', unreadable: [{ path: dir, cause: listing.failed }], closers: [] };
147
+ const closers = [];
148
+ const unreadable = [];
149
+ let vanished = false;
150
+ for (const entry of listing.entries) {
151
+ if (entry.name.startsWith('.')) continue;
152
+ const path = join(dir, entry.name);
153
+ const named = parseName(entry.name);
154
+ if (!named) { unreadable.push({ path, cause: 'no closer form' }); continue; }
155
+ if (!entry.isFile()) { unreadable.push({ path, cause: 'not a regular file' }); continue; }
156
+ const found = contentOf(path);
157
+ if (found.gone) { vanished = true; break; }
158
+ if (found.failed || !isContent(found.content)) { unreadable.push({ path, cause: found.failed ?? 'no reason, time or run' }); continue; }
159
+ const { reason, time, run: by } = found.content;
160
+ closers.push({ name: entry.name, path, ...named, reason, time, run: by });
161
+ }
162
+ if (vanished) continue;
163
+ if (unreadable.length > 0) return { state: 'unreadable', unreadable, closers };
164
+ return closers.length === 0 ? { state: 'open' } : { state: 'closed', closers };
165
+ }
166
+ }
167
+
168
+ /** The admission directory, made where it is absent, refused where it is not one. */
169
+ function directoryToWrite() {
170
+ try {
171
+ fs.mkdirSync(dir, { recursive: true });
172
+ if (!fs.lstatSync(dir).isDirectory()) throw Object.assign(new Error('not a directory'), { code: 'ENOTDIR' });
173
+ } catch (error) {
174
+ throw new Error(`admission cannot close through ${dir}: ${causeOf(error)}`, { cause: error });
175
+ }
176
+ }
177
+
178
+ /**
179
+ * The name of a closer present that carries `id`, under any name form, or undefined. Only the
180
+ * closers present can be checked; a removed closer's id rests on the id source (K39 D4).
181
+ */
182
+ function carrying(id) {
183
+ const listing = list();
184
+ if (listing.failed) throw new Error(`admission cannot list ${dir}: ${listing.failed}`);
185
+ return listing.entries.map((entry) => entry.name).find((name) => parseName(name)?.id === id);
186
+ }
187
+
188
+ /**
189
+ * Closes admission as `kind` for `reason`: writes a temporary file of its own, links its closer
190
+ * to it, and removes the temporary file, so the closer is then the file's only name. It records
191
+ * one `admission.close` event. A temporary file it cannot remove after the link is named in the
192
+ * answer and the event, and the close still stands. An id a present closer already carries is
193
+ * refused, and no other id is drawn.
194
+ */
195
+ async function close({ kind, reason }) {
196
+ if (!KINDS.includes(kind)) throw new Error(`admission closes only as owner or hold, not as ${JSON.stringify(kind)}`);
197
+ const content = { reason, time: now(), run };
198
+ if (!isContent(content)) throw new Error(`admission cannot record the closer ${JSON.stringify(content)}: it needs a reason, a time and a run`);
199
+ const id = ids();
200
+ if (typeof id !== 'string' || !ID.test(id)) throw new Error(`admission was handed the id ${JSON.stringify(id)}, which is not a run of 0-9 and a-z`);
201
+ directoryToWrite();
202
+ const carrier = carrying(id);
203
+ if (carrier) throw new Error(`admission was handed the id ${id}, which the closer ${join(dir, carrier)} already carries`);
204
+ const name = `${kind}-${id}.json`;
205
+ const path = join(dir, name);
206
+ const temporary = join(dir, `.tmp-${id}`);
207
+ let fd;
208
+ try {
209
+ fd = fs.openSync(temporary, 'wx');
210
+ } catch (error) {
211
+ throw new Error(`admission cannot write ${temporary}: ${causeOf(error)}`, { cause: error });
212
+ }
213
+ const discard = (at, error) => {
214
+ try { fs.unlinkSync(temporary); } catch { /* a temporary file left is never read */ }
215
+ return new Error(`admission cannot close at ${at}: ${causeOf(error)}`, { cause: error });
216
+ };
217
+ try {
218
+ fs.writeFileSync(fd, JSON.stringify(content));
219
+ } catch (error) {
220
+ fs.closeSync(fd);
221
+ throw discard(temporary, error);
222
+ }
223
+ fs.closeSync(fd);
224
+ try {
225
+ fs.linkSync(temporary, path);
226
+ } catch (error) {
227
+ throw discard(path, error);
228
+ }
229
+ let leftover;
230
+ try {
231
+ fs.unlinkSync(temporary);
232
+ } catch {
233
+ leftover = temporary;
234
+ }
235
+ record('admission.close', { kind, id, name, reason, ...(leftover && { leftover }) });
236
+ return { name, path, kind, id, ...content, ...(leftover && { leftover }) };
237
+ }
238
+
239
+ /** Removes `name` from the directory: true where it removed it, false where it was already gone. */
240
+ function remove(name) {
241
+ try {
242
+ fs.unlinkSync(join(dir, name));
243
+ return true;
244
+ } catch (error) {
245
+ if (error.code === 'ENOENT') return false;
246
+ throw error;
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Opens admission by one hold closer's name: removes exactly that closer and records one
252
+ * `admission.open` event. A name that is no hold closer's is refused, so no opening lifts the
253
+ * owner's `pause`. An entry under that name that is no readable closer, a directory, a link or a
254
+ * file that does not parse, is refused and left in place, as `resume` leaves an unreadable
255
+ * admission. A closer already gone answers so, and records nothing, since nothing changed. Where
256
+ * the close of status issue `issue` reopened it, the event names that issue as what raised it.
257
+ */
258
+ async function open(name, { issue } = {}) {
259
+ const named = parseName(name);
260
+ if (named?.kind !== 'hold') throw new Error(`admission opens only by a hold closer's name, not ${JSON.stringify(name)}`);
261
+ const path = join(dir, name);
262
+ const found = contentOf(path);
263
+ if (found.gone) return { name, ...named, alreadyGone: true };
264
+ if (found.failed || !isContent(found.content)) {
265
+ throw new Error(`admission opens only a readable closer, and ${path} is not one (${found.failed ?? 'no reason, time or run'}), so it removes nothing`);
266
+ }
267
+ if (!remove(name)) return { name, ...named, alreadyGone: true };
268
+ record('admission.open', { kind: named.kind, id: named.id, name, ...(issue === undefined ? { by: 'opening' } : { by: 'issue', issue }) });
269
+ return { name, ...named, alreadyGone: false };
270
+ }
271
+
272
+ /**
273
+ * Renames the hold closer `name` to attach where its notice can be, as L2's notice answered:
274
+ * `rename` is `after` or `issue`, and `number` the number the new name carries beside the hold's
275
+ * id, which may be 0 after `after` alone. Answers `{ name }`, the new name, and records one `admission.rename` event; or `{ gone }`
276
+ * where the closer was gone, recording nothing.
277
+ */
278
+ function rename(name, { rename: to, number }) {
279
+ const named = parseName(name);
280
+ if (named?.kind !== 'hold' || !['after', 'issue'].includes(to) || !Number.isSafeInteger(number) || number < (to === 'after' ? 0 : 1)) {
281
+ throw new Error(`admission renames only a hold closer to after or issue a number, not ${JSON.stringify(name)} to ${JSON.stringify({ to, number })}`);
282
+ }
283
+ const renamed = `hold-${named.id}-${to}-${number}.json`;
284
+ try {
285
+ fs.renameSync(join(dir, name), join(dir, renamed));
286
+ } catch (error) {
287
+ if (error.code === 'ENOENT') return { gone: true };
288
+ throw new Error(`admission cannot rename ${join(dir, name)}: ${causeOf(error)}`, { cause: error });
289
+ }
290
+ try {
291
+ record('admission.rename', { kind: 'hold', id: named.id, from: name, to: renamed, name: renamed });
292
+ } catch (refusal) {
293
+ // The rename was made: L3's own failure names where the closer now is, the refusal its cause.
294
+ throw own(Object.assign(new Error(`admission renamed ${name} to ${renamed}, and its record was refused: ${printable(refusal)}`, { cause: refusal }), { renamed }));
295
+ }
296
+ return { name: renamed };
297
+ }
298
+
299
+ /** The names in the directory now carrying hold id `id`. */
300
+ function holdNames(id) {
301
+ const listing = list();
302
+ if (listing.failed) throw new Error(`admission cannot list ${dir}: ${listing.failed}`);
303
+ return listing.entries.map((entry) => entry.name).filter((name) => {
304
+ const named = parseName(name);
305
+ return named?.kind === 'hold' && named.id === id;
306
+ });
307
+ }
308
+
309
+ /**
310
+ * Removes `closer`, a hold's under whatever name its id now carries, adding to `removed` each name
311
+ * this call unlinked, so that a failure partway still leaves every removal it made named.
312
+ */
313
+ function removeCloser(closer, removed) {
314
+ if (remove(closer.name)) removed.push(closer.name);
315
+ if (closer.kind !== 'hold') return;
316
+ for (let names = holdNames(closer.id); names.length > 0; names = holdNames(closer.id)) {
317
+ for (const name of names) if (remove(name)) removed.push(name);
318
+ }
319
+ }
320
+
321
+ /**
322
+ * The names now carrying the ids of `closers`, which a `resume` that failed partway left: a hold
323
+ * renamed since its listing is named as it now is. Where the directory cannot be listed, the
324
+ * names as listed.
325
+ */
326
+ function leftOf(closers) {
327
+ const listing = list();
328
+ if (listing.failed) return closers.map(({ name }) => name);
329
+ const ids = new Set(closers.map(({ kind, id }) => `${kind}-${id}`));
330
+ return listing.entries.map((entry) => entry.name).filter((name) => {
331
+ const named = parseName(name);
332
+ return named && ids.has(`${named.kind}-${named.id}`);
333
+ });
334
+ }
335
+
336
+ /**
337
+ * `resume`'s removal: where every closer reads, removes each closer it read, a hold's under
338
+ * whatever name its id then carries, and records one `admission.open` event raised by `resume`
339
+ * for each name it unlinked, so two names carrying one hold's id are two events. A closer already
340
+ * gone counts as removed, with no event. Where any closer is unreadable, it removes nothing and
341
+ * rejects naming each, carrying as `unreadable` the entries `read` answered, unescaped. Where a
342
+ * removal fails partway, it rejects naming the failure and each closer left, carrying as `removed`
343
+ * every closer it removed. A refused removal record is returned as `unrecorded` after the removals.
344
+ */
345
+ async function resume() {
346
+ const answer = read();
347
+ if (answer.state === 'unreadable') {
348
+ const { unreadable } = answer;
349
+ throw own(Object.assign(new Error(`admission cannot be read, so resume removes nothing: ${unreadable.map(({ path, cause }) => `${path} (${cause})`).join(', ')}`), { unreadable }));
350
+ }
351
+ const closers = answer.closers ?? [];
352
+ const unlinked = new Set();
353
+ const removed = [];
354
+ const gone = [];
355
+ const unrecorded = [];
356
+ /** One event for each name in `names`, the kind and id its name carries, after its unlink. */
357
+ const recordEach = (names) => {
358
+ for (const name of names) {
359
+ unlinked.add(name);
360
+ const { kind, id } = parseName(name);
361
+ try {
362
+ record('admission.open', { kind, id, name, by: 'resume' });
363
+ } catch (refusal) {
364
+ const why = printable(refusal).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, (character) =>
365
+ ({ '\n': '\\n', '\r': '\\r', '\t': '\\t' })[character] ?? `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`);
366
+ unrecorded.push({ name, why });
367
+ }
368
+ }
369
+ };
370
+ for (const [index, closer] of closers.entries()) {
371
+ const names = [];
372
+ try {
373
+ removeCloser(closer, names);
374
+ } catch (cause) {
375
+ // The closers removed before this one, and this one where any of its names went, stay named.
376
+ const done = names.length > 0 ? [...removed, closer] : [...removed];
377
+ recordEach(names);
378
+ const why = printable(cause);
379
+ const said = `resume left ${leftOf(closers.slice(index)).join(', ')}: ${why}`;
380
+ throw own(Object.assign(new Error(said, { cause: new Error(why) }), { removed: done, unrecorded }));
381
+ }
382
+ recordEach(names);
383
+ if (names.length > 0 || unlinked.has(closer.name)) removed.push(closer);
384
+ else gone.push(closer);
385
+ }
386
+ return { removed, gone, unrecorded };
387
+ }
388
+
389
+ return { read, close, open, resume, rename };
390
+ }