@agentsignalnet/claude-plugin 0.2.135 → 0.2.136

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.135",
4
+ "version": "0.2.136",
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.135",
3
+ "version": "0.2.136",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -0,0 +1,327 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * IS THE PARENT SESSION IN A TURN? Decided from its own transcript.
4
+ *
5
+ * node session-state.mjs --self-test
6
+ *
7
+ * The inbox monitor holds a priority-0 message while a turn runs and wakes the
8
+ * session with it once the session is idle. Hooks cannot say "idle": Esc
9
+ * during generation fires no hook at all, and `idle_prompt` means "no turn",
10
+ * not "no tool" (spike 0, CC 2.1.326). So the transcript is the authority and
11
+ * a UserPromptSubmit hint can only ADD busy, for the moment before the prompt
12
+ * line is written.
13
+ *
14
+ * Line ORDER is causal, timestamps are not, so rules read entries in file
15
+ * order and take time only from the file's mtime. An open foreground tool is
16
+ * busy for as long as it runs; a backgrounded tool whose turn ended is idle.
17
+ *
18
+ * PRIVACY: this module reads transcript lines into memory to classify them.
19
+ * Above the self-test it never writes, logs, prints or sends any of it, and
20
+ * the self-test checks that structurally.
21
+ */
22
+ import { openSync, readSync, closeSync, readdirSync, existsSync } from 'node:fs';
23
+ import { homedir } from 'node:os';
24
+ import { join } from 'node:path';
25
+ import { fileURLToPath } from 'node:url';
26
+
27
+ export const QUIET_MS = 2000;
28
+ export const END_GRACE_MS = 15_000;
29
+ export const MODEL_STALL_MS = 600_000;
30
+ export const HINT_MAX_MS = 30_000;
31
+ export const TAIL_START = 256 * 1024;
32
+ export const TAIL_MAX = 4 * 1024 * 1024;
33
+
34
+ // No environment override: an inherited variable must not change when priority
35
+ // 0 may interrupt. Tests pass `stallMs` to classify directly.
36
+
37
+ // An ALLOW-list, not the deny-list of metadata types: new metadata lines keep
38
+ // appearing (ai-title, continued-in, ...) and are written after a turn ends,
39
+ // so an unknown type must never read as a turn in flight.
40
+ const CONVERSATION = new Set(['user', 'assistant', 'system', 'queue-operation']);
41
+ const blocks = (e) => (Array.isArray(e.message?.content) ? e.message.content : []);
42
+ const textOf = (e) =>
43
+ typeof e.message?.content === 'string'
44
+ ? e.message.content
45
+ : blocks(e).filter((b) => b?.type === 'text').map((b) => String(b.text ?? '')).join('');
46
+ const isInterrupt = (e) => e.type === 'user' && textOf(e).startsWith('[Request interrupted by user');
47
+ const isPrompt = (e) =>
48
+ e.type === 'user' && !e.isMeta && !isInterrupt(e) &&
49
+ !blocks(e).some((b) => b?.type === 'tool_result') &&
50
+ (typeof e.message?.content === 'string' || blocks(e).length > 0);
51
+ const isTurnEnd = (e) => e.type === 'system' && (e.subtype === 'turn_duration' || e.subtype === 'stop_hook_summary');
52
+ // Only the two subtypes above end a turn. Any other system line (local_command,
53
+ // an unfamiliar subtype, ...) after the end is the last entry and reaches the
54
+ // in-flight/stall rule, so it never releases priority 0 early. Queue operations
55
+ // are conversation entries too: a trailing dequeue (or any other queue line)
56
+ // is the last entry, so it holds busy in-flight until a prompt or the stall.
57
+ const STOPS = new Set(['end_turn', 'stop_sequence', 'max_tokens', 'refusal']);
58
+ const verdict = (busy, reason) => ({ busy, reason });
59
+
60
+ /** JSONL to entries. A tail read starts mid-line, so its first line is dropped. */
61
+ export function parseLines(text, fromStart) {
62
+ const lines = String(text).split('\n');
63
+ if (!fromStart) lines.shift();
64
+ const entries = [];
65
+ for (const line of lines) {
66
+ if (!line.trim()) continue;
67
+ try {
68
+ const entry = JSON.parse(line);
69
+ if (entry && typeof entry === 'object') entries.push(entry);
70
+ } catch {
71
+ /* a torn or foreign line: skip it */
72
+ }
73
+ }
74
+ return entries;
75
+ }
76
+
77
+ /**
78
+ * The rules of the re-plan (§3), in order. `mtimeMs` null means no transcript.
79
+ * `tail` is readTail's `{entries, complete}` snapshot, or an array a caller
80
+ * knows to be the whole history.
81
+ */
82
+ export function classify(tail, { now = Date.now(), mtimeMs = null, hintAt = null, stallMs = MODEL_STALL_MS } = {}) {
83
+ if (hintAt != null && hintAt > (mtimeMs ?? -Infinity) && now - hintAt < HINT_MAX_MS) return verdict(true, 'hint');
84
+ if (mtimeMs == null) return verdict(true, 'unknown');
85
+ const quietFor = now - mtimeMs;
86
+ if (quietFor < QUIET_MS) return verdict(true, 'quiet');
87
+ const known = tail == null || Array.isArray(tail);
88
+ // A window that neither reached byte zero nor holds a prompt may have lost a
89
+ // tool_use whose result never came: it cannot prove no tool is open, so the
90
+ // stall rule may not release it. A turn end, an interrupt or a stop still
91
+ // can, because a window with no prompt lies inside one turn and those end it.
92
+ const partial = !known && tail.complete !== true;
93
+ const entries = known ? tail : tail.entries;
94
+ const conv = (Array.isArray(entries) ? entries : []).filter((e) => e && typeof e === 'object' && CONVERSATION.has(e.type));
95
+ if (conv.length === 0) return verdict(true, 'unknown');
96
+ const stalled = quietFor >= stallMs;
97
+ const unsettled = () => (partial ? verdict(true, 'unknown') : stalled ? verdict(false, 'stalled') : verdict(true, 'in-flight'));
98
+
99
+ let start = 0;
100
+ for (let i = conv.length - 1; i >= 0; i -= 1) {
101
+ if (isPrompt(conv[i])) { start = i; break; }
102
+ }
103
+ const turn = conv.slice(start);
104
+ const open = new Set();
105
+ for (const e of turn) {
106
+ for (const b of blocks(e)) {
107
+ if (b?.type === 'tool_use' && b.id) open.add(b.id);
108
+ else if (b?.type === 'tool_result') open.delete(b.tool_use_id);
109
+ }
110
+ }
111
+ if (open.size) return verdict(true, 'open-tool');
112
+
113
+ let lastEnd = -1;
114
+ let lastQueue = -1;
115
+ conv.forEach((e, i) => {
116
+ if (isTurnEnd(e)) lastEnd = i;
117
+ if (e.type === 'queue-operation') lastQueue = i;
118
+ });
119
+ if (lastQueue > lastEnd && conv[lastQueue].operation === 'enqueue') {
120
+ return stalled && !partial ? verdict(false, 'stalled') : verdict(true, 'queued');
121
+ }
122
+
123
+ const last = conv[conv.length - 1];
124
+ if (isTurnEnd(last)) return verdict(false, 'ended');
125
+ if (isInterrupt(last)) return verdict(false, 'interrupted');
126
+ if (last.type === 'assistant' && (STOPS.has(last.message?.stop_reason) || last.isApiErrorMessage)) {
127
+ return quietFor >= END_GRACE_MS ? verdict(false, 'ended') : verdict(true, 'ending');
128
+ }
129
+ return unsettled();
130
+ }
131
+
132
+ /**
133
+ * The tail of a transcript, doubling the window until it holds a prompt, as
134
+ * `{entries, complete}`. `complete` means the read reached byte zero or holds
135
+ * a real prompt; hitting `max` or the round limit alone leaves it false.
136
+ */
137
+ export function readTail(path, size, { start = TAIL_START, max = TAIL_MAX } = {}) {
138
+ const fd = openSync(path, 'r');
139
+ try {
140
+ let entries = [];
141
+ let complete = false;
142
+ for (let want = start, round = 0; round < 16; want *= 2, round += 1) {
143
+ const len = Math.min(size, want, max);
144
+ // One byte more before the window: if it is a newline, the window starts
145
+ // on a line boundary and its first line is whole, so it is kept.
146
+ const extra = len < size ? 1 : 0;
147
+ const buffer = Buffer.alloc(len + extra);
148
+ const got = readSync(fd, buffer, 0, len + extra, size - len - extra);
149
+ const whole = extra === 0 || buffer[0] === 0x0a;
150
+ entries = parseLines(buffer.subarray(extra, got).toString('utf8'), whole);
151
+ complete = len === size || entries.some(isPrompt);
152
+ if (complete || len >= max) break;
153
+ }
154
+ return { entries, complete };
155
+ } finally {
156
+ closeSync(fd);
157
+ }
158
+ }
159
+
160
+ /** `<config>/projects/*\/<id>.jsonl`, or null. The id cannot name a path. */
161
+ export function findTranscript(sessionId, env = process.env) {
162
+ // Refused, not sanitized: two ids differing only in other characters must
163
+ // never name the same file.
164
+ const id = String(sessionId ?? '');
165
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) return null;
166
+ const root = join(env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'projects');
167
+ let dirs = [];
168
+ try {
169
+ dirs = readdirSync(root, { withFileTypes: true });
170
+ } catch {
171
+ return null;
172
+ }
173
+ for (const dir of dirs) {
174
+ const path = join(root, dir.name, `${id}.jsonl`);
175
+ if (dir.isDirectory() && existsSync(path)) return path;
176
+ }
177
+ return null;
178
+ }
179
+
180
+ // ----- SELF-TEST: everything below this line is test code -----
181
+ async function selfTest() {
182
+ const fs = await import('node:fs');
183
+ const { tmpdir } = await import('node:os');
184
+ const checks = [];
185
+ const ok = (what, passed, detail = '') => checks.push([what, Boolean(passed), detail]);
186
+ const P = (text = 'do the thing') => ({ type: 'user', message: { role: 'user', content: text } });
187
+ const A = (content, stop = null, extra = {}) => ({ type: 'assistant', message: { role: 'assistant', content, stop_reason: stop }, ...extra });
188
+ const TXT = (text) => [{ type: 'text', text }];
189
+ const TU = (...ids) => A(ids.map((id) => ({ type: 'tool_use', id, name: 'Bash', input: {} })), 'tool_use');
190
+ const TR = (id, extra = {}, result = {}) => ({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, ...extra }] }, toolUseResult: result });
191
+ const INT = (suffix = '') => ({ type: 'user', message: { role: 'user', content: TXT(`[Request interrupted by user${suffix}]`) } });
192
+ const SYS = (subtype) => ({ type: 'system', subtype });
193
+ const Q = (operation) => ({ type: 'queue-operation', operation });
194
+ const T = 1_000_000_000;
195
+ const at = (entries, dt, hintAt = null) => classify(entries, { now: T + dt, mtimeMs: T, hintAt, stallMs: MODEL_STALL_MS });
196
+ const is = (what, got, busy, reason) => ok(what, got.busy === busy && (!reason || got.reason === reason), got);
197
+ const MIN = 60_000;
198
+
199
+ const t1 = [P(), A([{ type: 'thinking', thinking: '' }]), A(TXT('partial')), INT()];
200
+ is('T1 Esc mid-generation, no hook: idle at +2s', at(t1, 2000), false, 'interrupted');
201
+ const t2 = [P(), TU('a'), TR('a', { is_error: true }), INT(' for tool use')];
202
+ is('T2 Esc mid-tool: busy quiet at +1s', at(t2, 1000), true, 'quiet');
203
+ is('T2 Esc mid-tool: idle at +2s', at(t2, 2000), false, 'interrupted');
204
+ const t3 = [P(), TU('a')];
205
+ for (const dt of [63_000, 11 * MIN, 120 * MIN]) is(`T3 a running foreground tool is busy at +${dt}ms`, at(t3, dt), true, 'open-tool');
206
+ const ended = [P(), TU('a'), TR('a', {}, { backgroundTaskId: 'bg-fake-1' }), A(TXT('started'), 'end_turn'), SYS('stop_hook_summary'), SYS('turn_duration')];
207
+ is('T4 a backgrounded tool whose turn ended is idle', at(ended, 20_000), false, 'ended');
208
+ is('T4 an enqueue not yet dequeued is busy', at([...ended, Q('enqueue')], 20_000), true, 'queued');
209
+ is('T4 dequeued, and the new turn ended: idle', at([...ended, Q('enqueue'), Q('dequeue'), P('<task-notification/>'), A(TXT('done'), 'end_turn'), SYS('turn_duration')], 20_000), false, 'ended');
210
+ is('T5 prompt only: busy in-flight at +5min', at([P()], 5 * MIN), true, 'in-flight');
211
+ is('T5 prompt only: idle stalled at +10min+1', at([P()], 10 * MIN + 1), false, 'stalled');
212
+ is('T6 parallel tools with one still open: busy at +2h', at([P(), TU('a', 'b'), TR('a')], 120 * MIN), true, 'open-tool');
213
+ const t7 = [P(), A(TXT('answer'), 'end_turn')];
214
+ is('T7 end_turn without turn_duration: busy ending at +10s', at(t7, 10_000), true, 'ending');
215
+ is('T7 end_turn without turn_duration: idle at +15s', at(t7, 15_000), false, 'ended');
216
+ is('T8 an API error is idle at +15s', at([P(), A(TXT('API Error'), null, { isApiErrorMessage: true })], 15_000), false, 'ended');
217
+ is('T9a a hint newer than the transcript and 5s old is busy', at(ended, 20_000, T + 15_000), true, 'hint');
218
+ is('T9b a hint older than the transcript does not make busy', at(ended, 20_000, T - 1000), false, 'ended');
219
+ is('T9c a hint 31s old does not make busy', at(ended, 32_000, T + 1000), false, 'ended');
220
+ is('T10 no transcript is busy unknown', classify([], { now: T, mtimeMs: null }), true, 'unknown');
221
+ is('T10 metadata only is busy unknown', at([{ type: 'attachment' }, { type: 'api-request' }, { type: 'mode' }], 20_000), true, 'unknown');
222
+ const torn = parseLines(`${ended.map((e) => JSON.stringify(e)).join('\nnot json {\n')}\n`, true);
223
+ ok('T10 a garbage line in the middle is skipped', torn.length === ended.length && at(torn, 20_000).reason === 'ended', torn.length);
224
+ for (const sub of ['local_command', 'novel_subtype_fake']) {
225
+ const after = [...ended, SYS(sub)];
226
+ is(`qa#1 end then system/${sub}: busy in-flight at +2s`, at(after, 2000), true, 'in-flight');
227
+ is(`qa#1 end then system/${sub}: busy in-flight at stall-1`, at(after, MODEL_STALL_MS - 1), true, 'in-flight');
228
+ is(`qa#1 end then system/${sub}: idle stalled at stall`, at(after, MODEL_STALL_MS), false, 'stalled');
229
+ is(`qa#1 end, system/${sub}, then a genuine end: idle`, at([...after, SYS('turn_duration')], 2000), false, 'ended');
230
+ }
231
+ const dq = [...ended, Q('enqueue'), Q('dequeue')];
232
+ // A dequeue with its prompt not written yet is the last entry: busy in-flight
233
+ // until the stall limit, never idle after a grace (r4 qa#1).
234
+ is('r4 a trailing dequeue after an end is busy in-flight at +5s', at(dq, 5000), true, 'in-flight');
235
+ is('r4 ... still busy past the end grace', at(dq, END_GRACE_MS + 1), true, 'in-flight');
236
+ is('r4 ... and released only at the stall limit', at(dq, MODEL_STALL_MS), false, 'stalled');
237
+ is('r4 end_turn with no turn_duration, then enqueue and dequeue: busy at +20s', at([P(), A(TXT('ok'), 'end_turn'), Q('enqueue'), Q('dequeue')], 20_000), true, 'in-flight');
238
+ is('r4 any other queue line after an end is the last entry: busy', at([...ended, Q('remove')], 20_000), true, 'in-flight');
239
+ is('logic#1 r2 queue operations alone are in-flight, not unknown', at([Q('enqueue'), Q('dequeue')], 5 * MIN), true, 'in-flight');
240
+ is('logic#1 r2 ... and reach the stall release', at([Q('enqueue'), Q('dequeue')], 10 * MIN + 1), false, 'stalled');
241
+ is('metadata types written after a turn ends do not make it busy', at([...ended, { type: 'ai-title' }, { type: 'continued-in' }, { type: 'last-prompt' }], 20_000), false, 'ended');
242
+
243
+ const dir = fs.mkdtempSync(join(tmpdir(), 'agentsignal-session-selftest-'));
244
+ try {
245
+ const big = join(dir, 'big.jsonl');
246
+ fs.writeFileSync(big, `${JSON.stringify(P())}\n${JSON.stringify(A(TXT('x'.repeat(300 * 1024)), 'end_turn'))}\n`);
247
+ const size = fs.statSync(big).size;
248
+ is('T11 a 300 KiB final end_turn line still classifies idle', classify(readTail(big, size), { now: T + 20_000, mtimeMs: T }), false, 'ended');
249
+
250
+ // logic#1: a capped window that holds no prompt cannot establish the open tools.
251
+ const jsonl = (es) => es.map((e) => `${JSON.stringify(e)}\n`).join('');
252
+ const PAD = { type: 'progress', pad: 'x'.repeat(4096) };
253
+ const tail = (name, text, cap) => {
254
+ const path = join(dir, name);
255
+ fs.writeFileSync(path, text);
256
+ return readTail(path, fs.statSync(path).size, { start: 64, max: cap });
257
+ };
258
+ const at2 = (snap, dt) => classify(snap, { now: T + dt, mtimeMs: T, stallMs: MODEL_STALL_MS });
259
+ const parallel = jsonl([P(), TU('A', 'B'), PAD, TR('A')]);
260
+ is('logic#1 capped window, B use outside, A result inside: busy unknown at +2h', at2(tail('par.jsonl', parallel, 1024), 120 * MIN), true, 'unknown');
261
+ is('logic#1 the complete fixture: busy open-tool for B at +2h', at2(tail('par-full.jsonl', parallel, TAIL_MAX), 120 * MIN), true, 'open-tool');
262
+ const suffixEnd = jsonl([P(), TU('A', 'B'), PAD, TR('A'), A(TXT('done'), 'end_turn'), SYS('turn_duration')]);
263
+ is('logic#1 r2 a turn end in an incomplete window releases: idle ended', at2(tail('end.jsonl', suffixEnd, 1024), 20_000), false, 'ended');
264
+ const suffixInt = jsonl([P(), TU('A', 'B'), PAD, TR('A'), INT()]);
265
+ is('logic#1 r2 an interrupt in an incomplete window releases: idle', at2(tail('int.jsonl', suffixInt, 1024), 20_000), false, 'interrupted');
266
+ const suffixStop = jsonl([P(), TU('A', 'B'), PAD, TR('A'), A(TXT('done'), 'end_turn')]);
267
+ is('logic#1 r2 a stop in an incomplete window: ending, then ended after the grace', at2(tail('stop.jsonl', suffixStop, 1024), 10_000).reason === 'ending' ? at2(tail('stop.jsonl', suffixStop, 1024), 20_000) : { busy: null }, false, 'ended');
268
+ const promptIn = jsonl([P(), TU('A', 'B'), PAD, TR('A'), TR('B'), P('next'), A(TXT('ok'), 'end_turn'), SYS('turn_duration')]);
269
+ is('logic#1 a real prompt inside a capped window: idle ended', at2(tail('prompt.jsonl', promptIn, 1024), 20_000), false, 'ended');
270
+ const exact = jsonl([TR('A'), A(TXT('ok'), 'end_turn'), SYS('turn_duration')]);
271
+ is('logic#1 a file exactly at the cap is read from byte zero: idle ended', at2(tail('exact.jsonl', exact, Buffer.byteLength(exact)), 20_000), false, 'ended');
272
+ is('logic#1 a known-complete array still classifies', at2([TR('A'), A(TXT('ok'), 'end_turn'), SYS('turn_duration')], 20_000), false, 'ended');
273
+
274
+ const config = join(dir, 'config');
275
+ fs.mkdirSync(join(config, 'projects', '-fake-project'), { recursive: true });
276
+ fs.writeFileSync(join(config, 'projects', '-fake-project', 'sess-fake-1.jsonl'), '');
277
+ fs.writeFileSync(join(config, 'projects', 'x.jsonl'), '');
278
+ const env = { CLAUDE_CONFIG_DIR: config };
279
+ ok('T12 findTranscript finds <id>.jsonl', findTranscript('sess-fake-1', env) === join(config, 'projects', '-fake-project', 'sess-fake-1.jsonl'));
280
+ ok('T12 an unknown id is null', findTranscript('sess-none', env) === null && findTranscript('', env) === null);
281
+ ok('T12 ../x cannot leave projects/', findTranscript('../x', env) === null);
282
+ // r3 security#3: an id that would need sanitizing is refused, even when the
283
+ // sanitized name exists.
284
+ fs.writeFileSync(join(config, 'projects', '-fake-project', 'a_b.jsonl'), '');
285
+ ok('r3 security#3 a/b and a.b are refused, not read as a_b', findTranscript('a/b', env) === null && findTranscript('a.b', env) === null &&
286
+ findTranscript('a_b', env) === join(config, 'projects', '-fake-project', 'a_b.jsonl'));
287
+
288
+ // r3 logic#4: a window that starts exactly on a line boundary keeps that line.
289
+ const boundary = join(dir, 'boundary.jsonl');
290
+ const lead = `${JSON.stringify({ type: 'progress', pad: 'y'.repeat(200) })}\n`;
291
+ const own = jsonl([P('the real prompt'), A(TXT('ok'), 'end_turn'), SYS('turn_duration')]);
292
+ fs.writeFileSync(boundary, lead + own);
293
+ const cut = Buffer.byteLength(own);
294
+ const snap = readTail(boundary, fs.statSync(boundary).size, { start: cut, max: cut });
295
+ ok('r3 logic#4 a prompt that starts the window exactly is kept, so the window is complete', snap.complete === true && snap.entries.length === 3, snap.entries.length);
296
+ const mid = readTail(boundary, fs.statSync(boundary).size, { start: cut - 5, max: cut - 5 });
297
+ ok('r3 logic#4 ... and a torn first line is still dropped', mid.complete === false && mid.entries.length === 2, mid.entries.length);
298
+ } finally {
299
+ fs.rmSync(dir, { recursive: true, force: true });
300
+ }
301
+
302
+ const source = fs.readFileSync(fileURLToPath(import.meta.url), 'utf8');
303
+ // Everything before the self-test function, comments stripped, so neither a
304
+ // marker string nor a comment can shrink or pad what is scanned.
305
+ const body = source.slice(0, source.indexOf(['async function', 'selfTest('].join(' '))).replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, '');
306
+ const leaks = ['writeFileSync', 'appendFileSync', 'writeSync', 'createWriteStream', 'fs.write', 'fetch(', 'console.', 'process.std',
307
+ 'require(', 'import(', 'child_process', 'node:http', 'node:https', 'node:net', 'node:dgram', 'node:tls'].filter((s) => body.includes(s));
308
+ ok('T13 nothing above the self-test writes, sends or prints', body.length > 1000 && leaks.length === 0, leaks);
309
+ // r3 security#2: the module may import only these names, so a writing or
310
+ // sending helper cannot arrive through an import either.
311
+ const ALLOWED = {
312
+ 'node:fs': ['openSync', 'readSync', 'closeSync', 'readdirSync', 'existsSync'],
313
+ 'node:os': ['homedir'], 'node:path': ['join'], 'node:url': ['fileURLToPath'],
314
+ };
315
+ const imports = [...body.matchAll(/import\s*\{([^}]*)\}\s*from\s*'([^']+)'/g)].map(([, names, from]) => [from, names.split(',').map((n) => n.trim()).filter(Boolean)]);
316
+ const stray = imports.filter(([from, names]) => !ALLOWED[from] || names.some((n) => !ALLOWED[from].includes(n)));
317
+ const bare = (body.match(/^\s*import\b/gm) ?? []).length;
318
+ ok('r3 security#2 T13 imports only the allowed names', imports.length >= 4 && stray.length === 0 && bare === imports.length, { stray, bare });
319
+ ok('r3 security#4 no AGENTSIGNAL_ setting is read from the environment', !/AGENTSIGNAL_/.test(body));
320
+
321
+ const failed = checks.filter(([, passed]) => !passed);
322
+ for (const [what, , detail] of failed) console.error(` x ${what}: ${JSON.stringify(detail)}`);
323
+ console.log(failed.length === 0 ? `Session state: ${checks.length} checks passed.` : `Session state: ${failed.length} of ${checks.length} FAILED.`);
324
+ process.exit(failed.length === 0 ? 0 : 1);
325
+ }
326
+
327
+ if (process.argv[1] === fileURLToPath(import.meta.url) && process.argv[2] === '--self-test') await selfTest();