@agentsignalnet/claude-plugin 0.2.133 → 0.2.134

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "agentsignal",
3
3
  "displayName": "AgentSignal",
4
- "version": "0.2.133",
4
+ "version": "0.2.134",
5
5
  "description": "Page a human from inside Claude Code, or become an addressable agent that other agents can reach.",
6
6
  "author": {
7
7
  "name": "Data Group AI",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentsignalnet/claude-plugin",
3
- "version": "0.2.133",
3
+ "version": "0.2.134",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -5,6 +5,7 @@
5
5
  * node inbox-hook.mjs check # PostToolUse -- what is already waiting
6
6
  * node inbox-hook.mjs watch # PostToolUse + asyncRewake -- what arrives mid-tool
7
7
  * node inbox-hook.mjs finish # Stop -- before the turn ends
8
+ * node inbox-hook.mjs --self-test
8
9
  *
9
10
  * THERE ARE ONLY TWO MOMENTS, NOT THREE
10
11
  *
@@ -39,9 +40,11 @@
39
40
  */
40
41
  import {
41
42
  readFileSync, writeFileSync, renameSync, mkdirSync, existsSync, appendFileSync, unlinkSync,
43
+ openSync, closeSync,
42
44
  } from 'node:fs';
43
- import { dirname, join } from 'node:path';
45
+ import { basename, dirname, join } from 'node:path';
44
46
  import { fileURLToPath } from 'node:url';
47
+ import { createHash } from 'node:crypto';
45
48
  import { stateDirs, writeDir } from './state.mjs';
46
49
  import { ensureWatcher, lockDir, apiBase } from './watchers.mjs';
47
50
  import { renderMessage, urgency } from './surface.mjs';
@@ -84,7 +87,9 @@ const mode = process.argv[2] ?? 'check';
84
87
  * Exit 0 is silence in every mode -- `watch` reserves exit 2 for the wake --
85
88
  * so one line covers all three.
86
89
  */
87
- if (process.env.AGENTSIGNAL_FROM_RESPONDER === '1') process.exit(0);
90
+ // The self-test is exempt: a gate that exits green through this guard has
91
+ // tested nothing. It strips the variable from every child it spawns.
92
+ if (process.env.AGENTSIGNAL_FROM_RESPONDER === '1' && mode !== '--self-test') process.exit(0);
88
93
 
89
94
  /**
90
95
  * The same candidate list the daemon and the MCP server use, and it must stay
@@ -96,12 +101,25 @@ if (process.env.AGENTSIGNAL_FROM_RESPONDER === '1') process.exit(0);
96
101
  * use. Falling back to the first candidate covers the first run, before a
97
102
  * daemon has ever written anything.
98
103
  */
99
- const stateDir =
100
- stateDirs().find((dir) => existsSync(join(dir, 'inbox-spool.json'))) ??
101
- writeDir();
104
+ let stateDir;
105
+ let spoolPath;
106
+ let handledPath;
107
+ let claimsDir;
102
108
 
103
- const spoolPath = join(stateDir, 'inbox-spool.json');
104
- const handledPath = join(stateDir, 'inbox-handled.json');
109
+ /**
110
+ * `let` and a function, so a long-lived caller can re-resolve: on a machine
111
+ * that registers mid-session the spool does not exist yet, and a path fixed at
112
+ * start would point at the wrong directory for good.
113
+ */
114
+ function resolvePaths() {
115
+ stateDir =
116
+ stateDirs().find((dir) => existsSync(join(dir, 'inbox-spool.json'))) ??
117
+ writeDir();
118
+ spoolPath = join(stateDir, 'inbox-spool.json');
119
+ handledPath = join(stateDir, 'inbox-handled.json');
120
+ claimsDir = join(stateDir, 'inbox-claims');
121
+ }
122
+ resolvePaths();
105
123
 
106
124
  /** Seconds `watch` will sit there before giving up. */
107
125
  const WATCH_SECONDS = Number(process.env.AGENTSIGNAL_WATCH_SECONDS ?? 600);
@@ -121,15 +139,117 @@ function writeAtomic(path, value) {
121
139
  renameSync(temporary, path);
122
140
  }
123
141
 
124
- /** Outstanding messages of one urgency, newest last so they read in order. */
142
+ /**
143
+ * A claim file's name: the SHA-256 of the delivery id, in hex. Injective in
144
+ * practice and always a safe file name -- a character-replacing name made
145
+ * `../x2` and `___x2` the same claim, so claiming one lost the other.
146
+ */
147
+ const claimName = (deliveryId) => {
148
+ const id = String(deliveryId ?? '');
149
+ return id ? createHash('sha256').update(id).digest('hex') : '';
150
+ };
151
+
152
+ /**
153
+ * ONE CLAIM PER DELIVERY, decided by the filesystem.
154
+ *
155
+ * check, watch and finish all read the same spool, and the handled list is a
156
+ * read-modify-write that two of them can race -- both read it, both see the
157
+ * message unhandled, both surface it. `wx` is exclusive create: exactly one
158
+ * process makes the file, everybody else gets EEXIST.
159
+ *
160
+ * A directory that cannot be written to degrades to surfacing (true): a
161
+ * message shown twice is recoverable, a message shown never is not.
162
+ *
163
+ * An empty name claims nothing and surfaces, the same degrade. Callers claim
164
+ * by `claimKey`, which is never empty, so a message with no delivery id is
165
+ * still claimed once -- by its content -- rather than surfaced on every hook.
166
+ */
167
+ export function claimOne(dir, deliveryId) {
168
+ const name = claimName(deliveryId);
169
+ if (!name) return true;
170
+ try {
171
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
172
+ } catch (error) {
173
+ // Its own try: EEXIST from mkdir is a FILE where the directory belongs,
174
+ // not a rival's claim, and reading it as one dropped every message.
175
+ return unclaimable(dir, error);
176
+ }
177
+ try {
178
+ closeSync(openSync(join(dir, name), 'wx', 0o600));
179
+ return true;
180
+ } catch (error) {
181
+ return error?.code === 'EEXIST' ? false : unclaimable(dir, error);
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Said, not swallowed. stderr is hook.log (see hooks.json), so a degrade that
187
+ * repeats on every hook leaves a trace instead of looking like a quiet inbox.
188
+ */
189
+ function warn(line) {
190
+ try {
191
+ process.stderr.write(`inbox-hook ${mode}: ${line}\n`);
192
+ } catch {
193
+ /* nowhere left to say it */
194
+ }
195
+ }
196
+
197
+ function unclaimable(dir, error) {
198
+ warn(`cannot claim in ${dir} (${error?.code ?? error}); surfacing unclaimed`);
199
+ return true;
200
+ }
201
+
202
+ /**
203
+ * What a message is claimed by: its delivery id, or, with none, its content.
204
+ * An id-less message used to have nothing to claim by, so it surfaced on every
205
+ * PostToolUse and every Stop for as long as it sat in the spool. The NUL keeps
206
+ * a content key from ever equalling a real delivery id.
207
+ */
208
+ const claimKey = (m) => (m?.delivery_id ? String(m.delivery_id) : `\0content:${JSON.stringify(m)}`);
209
+
210
+ // No name is no claim -- `join(claimsDir, '')` is the directory itself.
211
+ const claimed = (key) => {
212
+ const name = claimName(key);
213
+ return name !== '' && existsSync(join(claimsDir, name));
214
+ };
215
+
216
+ /**
217
+ * Outstanding messages, oldest first so they read in order. `targetUrgency`
218
+ * null means every urgency. Urgency is recalculated by surface.mjs rather than
219
+ * read off the spool, because a daemon can outlive a plugin update.
220
+ */
125
221
  function waiting(targetUrgency) {
126
222
  const spool = readJson(spoolPath, { messages: [] });
127
223
  const handled = new Set(readJson(handledPath, { delivery_ids: [] }).delivery_ids ?? []);
128
224
  return (spool.messages ?? [])
129
- .filter((m) => !handled.has(m.delivery_id) && urgency(m) === targetUrgency)
225
+ .filter(
226
+ (m) =>
227
+ (targetUrgency === null || urgency(m) === targetUrgency) &&
228
+ // An empty id is not a handled id: an older hook wrote `null` here for
229
+ // an id-less message, and that hid every later one.
230
+ !(m.delivery_id && handled.has(m.delivery_id)) &&
231
+ !claimed(claimKey(m)),
232
+ )
130
233
  .sort((a, b) => (a.created_at < b.created_at ? -1 : 1));
131
234
  }
132
235
 
236
+ /** Claim what can be claimed, then record and mark only what this process won. */
237
+ function take(messages) {
238
+ const won = messages.filter((m) => claimOne(claimsDir, claimKey(m)));
239
+ if (won.length) {
240
+ // BEFORE markHandled, so the stamp is the moment the model is told.
241
+ recordLatency(won, Date.now());
242
+ try {
243
+ markHandled(won);
244
+ } catch (error) {
245
+ // The claim already stops a second surfacing, but the handled list is
246
+ // what outlives a pruned claim -- so a failure here is said out loud.
247
+ warn(`cannot write ${handledPath} (${error?.code ?? error})`);
248
+ }
249
+ }
250
+ return won;
251
+ }
252
+
133
253
  /**
134
254
  * HOW LONG A MESSAGE WAITED, written down so the answer can be measured.
135
255
  *
@@ -186,7 +306,8 @@ function recordLatency(messages, surfacedAt) {
186
306
  function markHandled(messages) {
187
307
  const handled = readJson(handledPath, { delivery_ids: [] });
188
308
  const ids = new Set(handled.delivery_ids ?? []);
189
- for (const m of messages) ids.add(m.delivery_id);
309
+ // Only real ids: the claim is what keeps an id-less message from repeating.
310
+ for (const m of messages) if (m.delivery_id) ids.add(m.delivery_id);
190
311
  writeAtomic(handledPath, { delivery_ids: [...ids] });
191
312
  }
192
313
 
@@ -228,17 +349,14 @@ if (mode === 'check' || mode === 'finish') {
228
349
  });
229
350
  }
230
351
 
231
- const messages = waiting(mode === 'check' ? 'interrupt' : 'finish');
352
+ // Only what this process wins: another hook may be surfacing the same
353
+ // message at the same instant.
354
+ const messages = take(waiting(mode === 'check' ? 'interrupt' : 'finish'));
232
355
 
233
356
  // Nothing waiting is the common case, and a hook that prints on every tool
234
357
  // call is a hook somebody turns off.
235
358
  if (messages.length === 0) process.exit(0);
236
359
 
237
- // BEFORE markHandled, so the stamp is the moment the model is told rather
238
- // than the moment bookkeeping finished.
239
- recordLatency(messages, Date.now());
240
- markHandled(messages);
241
-
242
360
  if (mode === 'check') {
243
361
  emit(
244
362
  JSON.stringify({
@@ -391,10 +509,9 @@ if (mode === 'watch') {
391
509
  const fallbackDeadline = until();
392
510
 
393
511
  const poll = () => {
394
- const messages = waiting('interrupt');
512
+ const messages = take(waiting('interrupt'));
395
513
  if (messages.length > 0) {
396
- recordLatency(messages, Date.now());
397
- markHandled(messages);
514
+ // take() has already recorded the latency and marked these handled.
398
515
  emit(render(messages, `${messages.length} urgent AgentSignal message(s) arrived for this agent.`), 2);
399
516
  return;
400
517
  }
@@ -413,7 +530,275 @@ if (mode === 'watch') {
413
530
  };
414
531
 
415
532
  poll();
416
- } else if (mode !== 'check' && mode !== 'finish') {
417
- console.error(`Unknown mode "${mode}". Use check, watch, or finish.`);
533
+ } else if (!['check', 'finish', '--self-test'].includes(mode)) {
534
+ console.error(`Unknown mode "${mode}". Use check, watch, finish, or --self-test.`);
418
535
  process.exit(1);
419
536
  }
537
+
538
+ /**
539
+ * SELF-TEST, offline. `node inbox-hook.mjs --self-test`
540
+ *
541
+ * The claim is checked by spawning this file against a throwaway state
542
+ * directory, because the thing that matters -- several processes racing for
543
+ * one message -- only exists between processes.
544
+ */
545
+ async function selfTest() {
546
+ const { mkdtempSync, rmSync, readdirSync } = await import('node:fs');
547
+ const { tmpdir } = await import('node:os');
548
+ const { spawn } = await import('node:child_process');
549
+ const self = fileURLToPath(import.meta.url);
550
+ const checks = [];
551
+ const ok = (what, passed, detail = '') => checks.push([what, Boolean(passed), detail]);
552
+
553
+ const scratch = () => mkdtempSync(join(tmpdir(), 'agentsignal-hook-selftest-'));
554
+ // Each block gets its own scratch directory, removed even when the block
555
+ // throws -- a failing gate used to leave its preloads and barriers in tmp.
556
+ const within = async (block) => {
557
+ const dir = scratch();
558
+ try {
559
+ await block(dir);
560
+ } finally {
561
+ rmSync(dir, { recursive: true, force: true });
562
+ }
563
+ };
564
+ const msg = (i, extra = {}) => ({
565
+ delivery_id: `d${i}`,
566
+ message_id: `m${i}`,
567
+ title: `title ${i}`,
568
+ body: `body ${i}`,
569
+ priority: 0,
570
+ urgency: 'finish',
571
+ created_at: new Date(Date.now() - 1000 + i).toISOString(),
572
+ spooled_at: new Date().toISOString(),
573
+ ...extra,
574
+ });
575
+ const childEnv = (dir, extra = {}) => {
576
+ const env = { ...process.env };
577
+ delete env.AGENTSIGNAL_FROM_RESPONDER;
578
+ delete env.CLAUDE_PLUGIN_DATA;
579
+ delete env.CLAUDE_CODE_SESSION_ID;
580
+ delete env.CLAUDE_CODE_HOST_SESSION_ID;
581
+ return {
582
+ ...env,
583
+ AGENTSIGNAL_STATE_DIR: dir,
584
+ AGENTSIGNAL_NO_KEYCHAIN: '1',
585
+ AGENTSIGNAL_BASE_URL: 'http://127.0.0.1:9',
586
+ ...extra,
587
+ };
588
+ };
589
+ /**
590
+ * Whether a child with this env can only see its own scratch directory. The
591
+ * self-test runs past the responder guard, and a child that resolved a real
592
+ * state directory would read real messages, and its failure output would
593
+ * print them. So every spawn is checked against what the hook will actually
594
+ * resolve, not against what childEnv meant to set.
595
+ */
596
+ const confined = (env) => {
597
+ const dir = env.AGENTSIGNAL_STATE_DIR ?? '';
598
+ const dirs = stateDirs(env);
599
+ return (
600
+ dirname(dir) === tmpdir() &&
601
+ basename(dir).startsWith('agentsignal-hook-selftest-') &&
602
+ dirs.length === 1 && dirs[0] === dir &&
603
+ writeDir(env) === dir && lockDir(env) === dir
604
+ );
605
+ };
606
+ const run = (args, env, nodeArgs = []) =>
607
+ !confined(env)
608
+ ? Promise.resolve({ code: null, out: '', err: `refused: ${env.AGENTSIGNAL_STATE_DIR} is not a scratch state directory` })
609
+ : new Promise((resolve) => {
610
+ const child = spawn(process.execPath, [...nodeArgs, self, ...args], { env, stdio: ['ignore', 'pipe', 'pipe'] });
611
+ let out = '';
612
+ let err = '';
613
+ child.stdout.on('data', (b) => {
614
+ out += b;
615
+ });
616
+ child.stderr.on('data', (b) => {
617
+ err += b;
618
+ });
619
+ child.on('close', (code) => resolve({ code, out, err }));
620
+ });
621
+ // A real race, not a likely one: the preload holds every racer at its claim
622
+ // until all four have read the spool and seen the message unclaimed, so
623
+ // only the exclusive create can keep it to one winner. A fresh barrier per
624
+ // race, because the count is what releases it.
625
+ //
626
+ // A racer that gives up waiting says so in `<barrier>-late`: on a slow host
627
+ // one child can time out and finish before the others arrive, and that is
628
+ // no race at all -- one winner would then prove nothing. `met` checks it.
629
+ let races = 0;
630
+ const met = (preload) => {
631
+ const barrier = preload.replace(/race-(\d+)\.mjs$/, 'barrier-$1');
632
+ return readdirSync(barrier).length === 4 && !existsSync(`${barrier}-late`);
633
+ };
634
+ const racer = (dir) => {
635
+ races += 1;
636
+ const barrier = join(dir, `barrier-${races}`);
637
+ mkdirSync(barrier);
638
+ const preload = join(dir, `race-${races}.mjs`);
639
+ writeFileSync(preload, [
640
+ "import fs from 'node:fs';",
641
+ "import { syncBuiltinESMExports } from 'node:module';",
642
+ 'const real = fs.openSync;',
643
+ 'fs.openSync = (path, ...rest) => {',
644
+ " if (String(path).includes('inbox-claims')) {",
645
+ ` fs.writeFileSync(${JSON.stringify(barrier)} + '/' + process.pid, '');`,
646
+ ' const until = Date.now() + 5000;',
647
+ ` while (fs.readdirSync(${JSON.stringify(barrier)}).length < 4 && Date.now() < until);`,
648
+ ` if (fs.readdirSync(${JSON.stringify(barrier)}).length < 4) fs.writeFileSync(${JSON.stringify(`${barrier}-late`)}, '');`,
649
+ ' }',
650
+ ' return real(path, ...rest);',
651
+ '};',
652
+ 'syncBuiltinESMExports();',
653
+ ].join('\n'));
654
+ return preload;
655
+ };
656
+
657
+ // --- a block that throws still removes its scratch directory
658
+ {
659
+ let left = null;
660
+ await within(async (dir) => {
661
+ left = dir;
662
+ throw new Error('a failing block');
663
+ }).catch(() => {});
664
+ ok('a self-test block that throws leaves no scratch directory', left && !existsSync(left), left);
665
+ }
666
+
667
+ // --- one claim, one winner
668
+ await within(async (dir) => {
669
+ ok('a delivery is claimed once', claimOne(join(dir, 'c'), 'x1') && !claimOne(join(dir, 'c'), 'x1'));
670
+ const c2 = join(dir, 'c2');
671
+ const both = claimOne(c2, '../x2') && claimOne(c2, '___x2') && claimOne(c2, '__/x2');
672
+ const names = existsSync(c2) ? readdirSync(c2) : [];
673
+ ok('distinct delivery ids never share a claim', both && names.length === 3, names);
674
+ ok('a claim file stays inside the claims directory, whatever the id', names.every((n) => /^[0-9a-f]{64}$/.test(n)) && !existsSync(join(dir, 'x2')), names);
675
+ ok('an empty delivery id surfaces without a claim', claimOne(c2, '') && claimOne(c2, undefined) && readdirSync(c2).length === 3);
676
+ writeFileSync(join(dir, 'inbox-spool.json'), JSON.stringify({ messages: [msg(1)] }));
677
+ const env = childEnv(dir);
678
+ const preload = racer(dir);
679
+ const results = await Promise.all([1, 2, 3, 4].map(() => run(['finish'], env, ['--import', preload])));
680
+ const winners = results.filter((r) => r.out.includes('title 1')).length;
681
+ ok('four racing hooks surface one message once', winners === 1 && met(preload), results.map((r) => r.out.length));
682
+ const again = await run(['finish'], env);
683
+ ok('a claimed message is not surfaced again', again.code === 0 && again.out === '', again);
684
+ writeFileSync(join(dir, 'inbox-spool.json'), JSON.stringify({ messages: [msg(9)] }));
685
+ const responder = await run(['finish'], { ...env, AGENTSIGNAL_FROM_RESPONDER: '1' });
686
+ ok('a responder session surfaces nothing', responder.code === 0 && responder.out === '', responder);
687
+ const handled = readJson(join(dir, 'inbox-handled.json'), { delivery_ids: [] }).delivery_ids ?? [];
688
+ const claimFile = join(dir, 'inbox-claims', claimName('d9'));
689
+ ok('a responder session claims nothing', !existsSync(claimFile) && !handled.includes('d9'), handled);
690
+ const unclaimed = await run(['finish'], env);
691
+ ok('a working session still surfaces what a responder skipped', unclaimed.out.includes('title 9'), unclaimed.out.length);
692
+ });
693
+
694
+ // --- check and watch claim too: urgency interrupt, the other two surfacing sites
695
+ for (const hook of ['check', 'watch']) await within(async (dir) => {
696
+ // watch polls until its deadline; two seconds lets the losers give up.
697
+ const env = childEnv(dir, { AGENTSIGNAL_WATCH_SECONDS: '2' });
698
+ // Priority 1, because surface.mjs recalculates urgency rather than trust
699
+ // the stamp: priority 0 with no sender key reads as finish.
700
+ writeFileSync(join(dir, 'inbox-spool.json'), JSON.stringify({ messages: [msg(5, { priority: 1, urgency: 'interrupt' })] }));
701
+ const preload = racer(dir);
702
+ const results = await Promise.all([1, 2, 3, 4].map(() => run([hook], env, ['--import', preload])));
703
+ const winners = results.filter((r) => r.out.includes('title 5'));
704
+ const woke = hook === 'watch' ? winners.every((r) => r.code === 2) : true;
705
+ ok(`four racing ${hook} hooks surface one message once`, winners.length === 1 && woke && met(preload), results.map((r) => [r.code, r.out.length]));
706
+ const again = await run([hook], env);
707
+ ok(`a message ${hook} claimed is not surfaced again`, again.code === 0 && again.out === '', again);
708
+ });
709
+
710
+ // --- every child is held to its scratch directory, and starts no daemon
711
+ await within(async (dir) => {
712
+ const leaks = [{ AGENTSIGNAL_STATE_DIR: '' }, { AGENTSIGNAL_STATE_DIR: tmpdir() }, { AGENTSIGNAL_STATE_DIR: join(dir, '..', 'elsewhere') }];
713
+ const refused = await Promise.all(leaks.map((leak) => run(['finish'], { ...childEnv(dir), ...leak })));
714
+ ok('the self-test spawns nothing outside a scratch state directory', refused.every((r) => r.code === null && r.err.startsWith('refused')), refused);
715
+ const env = childEnv(dir);
716
+ writeFileSync(join(dir, 'inbox-spool.json'), JSON.stringify({ messages: [] }));
717
+ const checked = await run(['check'], env);
718
+ // ensureWatcher stamps this before it spawns, and only then.
719
+ ok('a self-test check starts no watcher daemon', checked.code === 0 && !existsSync(join(dir, 'watcher-start.json')), readdirSync(dir));
720
+ });
721
+
722
+ // --- the usage line names every mode the header does
723
+ await within(async (dir) => {
724
+ const bad = await run(['bogus'], childEnv(dir));
725
+ const named = ['check', 'watch', 'finish', '--self-test'].every((m) => bad.err.includes(m));
726
+ ok('an unknown mode exits 1 and lists every mode', bad.code === 1 && named, bad);
727
+ });
728
+
729
+ // --- a message with no delivery id is shown, never dropped
730
+ await within(async (dir) => {
731
+ const env = childEnv(dir);
732
+ // A claimed message first, so the claims directory exists: `claimed('')`
733
+ // used to resolve to that directory and hide every id-less message.
734
+ writeFileSync(join(dir, 'inbox-spool.json'), JSON.stringify({ messages: [msg(1)] }));
735
+ await run(['finish'], env);
736
+ const bare = msg(2);
737
+ delete bare.delivery_id;
738
+ writeFileSync(join(dir, 'inbox-spool.json'), JSON.stringify({ messages: [bare, msg(3, { delivery_id: '' })] }));
739
+ const shown = await run(['finish'], env);
740
+ ok('an id-less message is surfaced, not dropped', shown.out.includes('title 2') && shown.out.includes('title 3'), shown);
741
+ const twice = await run(['finish'], env);
742
+ ok('an id-less message is surfaced once, not on every hook', twice.code === 0 && twice.out === '', twice);
743
+ writeFileSync(join(dir, 'inbox-spool.json'), JSON.stringify({ messages: [msg(4, { delivery_id: null })] }));
744
+ await run(['finish'], env);
745
+ const ids = readJson(join(dir, 'inbox-handled.json'), { delivery_ids: [] }).delivery_ids ?? [];
746
+ ok('an id-less message leaves no null in the handled list', !ids.some((id) => !id), ids);
747
+ // An older hook did write that null, and `handled.has(null)` then hid every
748
+ // later message whose id is null.
749
+ writeFileSync(join(dir, 'inbox-handled.json'), JSON.stringify({ delivery_ids: [null] }));
750
+ writeFileSync(join(dir, 'inbox-spool.json'), JSON.stringify({ messages: [msg(6, { delivery_id: null })] }));
751
+ const later = await run(['finish'], env);
752
+ ok('a null in the handled list hides no id-less message', later.out.includes('title 6'), later);
753
+ });
754
+
755
+ // --- a claim or handled-list failure is reported, and never costs the message
756
+ await within(async (dir) => {
757
+ const env = childEnv(dir);
758
+ mkdirSync(join(dir, 'inbox-handled.json'));
759
+ writeFileSync(join(dir, 'inbox-spool.json'), JSON.stringify({ messages: [msg(7)] }));
760
+ const unwritable = await run(['finish'], env);
761
+ ok('an unwritable handled list is reported, and the message surfaces', unwritable.out.includes('title 7') && unwritable.err.includes('inbox-handled'), unwritable);
762
+ });
763
+ await within(async (dir) => {
764
+ // A FILE where the claims directory belongs: mkdir says EEXIST, which is
765
+ // not somebody else's claim.
766
+ writeFileSync(join(dir, 'inbox-claims'), '');
767
+ writeFileSync(join(dir, 'inbox-spool.json'), JSON.stringify({ messages: [msg(8)] }));
768
+ const blocked = await run(['finish'], childEnv(dir));
769
+ ok('a claims path that is not a directory is reported, and the message surfaces', blocked.out.includes('title 8') && blocked.err.includes('inbox-claims'), blocked);
770
+ // A directory the claim cannot be created in: read-only for a user, /proc
771
+ // for root (whom a mode does not stop).
772
+ const root = process.getuid?.() === 0;
773
+ const closed = root ? (existsSync('/proc/self') ? '/proc/self' : null) : join(dir, 'closed');
774
+ if (closed && !root) mkdirSync(closed, { mode: 0o500 });
775
+ if (closed) {
776
+ const write = process.stderr.write;
777
+ let said = '';
778
+ process.stderr.write = (chunk) => ((said += chunk), true);
779
+ let surfaced;
780
+ try {
781
+ surfaced = claimOne(closed, 'x3');
782
+ } finally {
783
+ process.stderr.write = write;
784
+ }
785
+ ok('a claim that cannot be created is reported, and surfaces', surfaced && said.includes(closed), said);
786
+ }
787
+ });
788
+
789
+ let failed = 0;
790
+ for (const [what, passed, detail] of checks) {
791
+ if (!passed) {
792
+ failed += 1;
793
+ console.error(` x ${what}: ${JSON.stringify(detail)}`);
794
+ }
795
+ }
796
+ console.log(
797
+ failed === 0
798
+ ? `Inbox hook: ${checks.length} checks passed.`
799
+ : `Inbox hook: ${failed} of ${checks.length} FAILED.`,
800
+ );
801
+ process.exit(failed === 0 ? 0 : 1);
802
+ }
803
+
804
+ if (mode === '--self-test') await selfTest();