ceulen 0.27.0 → 0.28.1

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.
@@ -0,0 +1,724 @@
1
+ // rex delegation backend (lib/rex.ts): detection, name allocation, window/pane
2
+ // topology, prompt+wait (readiness gate, submit, freshness turn-proof),
3
+ // collection (head slice + blob tail, echo cut), and result mapping. Every CLI
4
+ // call is scripted through the `rexCli.exec` seam (the herdrCli/herdrAppCli
5
+ // precedent).
6
+
7
+ import assert from "node:assert/strict";
8
+ import { mkdtempSync, writeFileSync } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { join } from "node:path";
11
+ import { afterEach, test } from "node:test";
12
+
13
+ import {
14
+ cancelRexAgent,
15
+ clearRexRegistry,
16
+ closeRexWindow,
17
+ collectRexResult,
18
+ executeRexTask,
19
+ findRexAgent,
20
+ forgetRexAgent,
21
+ forgetRexWindow,
22
+ getRexRegistry,
23
+ getRexTerminal,
24
+ lastTiledBlock,
25
+ prepareRexTask,
26
+ probeRexBinary,
27
+ promptRexAndWait,
28
+ readRexBlock,
29
+ rexTiming,
30
+ replyBeyondEcho,
31
+ resetRexProbe,
32
+ rexCli,
33
+ rexDisabled,
34
+ rexEnvDetected,
35
+ rexWindowCloseBlockers,
36
+ wrapRexTaskPrompt,
37
+ type RexHandle,
38
+ } from "../lib/rex.ts";
39
+
40
+ type Res = { code: number; stdout?: string; stderr?: string };
41
+ type Call = { args: string[] };
42
+
43
+ /** Scripted exec: "<sub> <verb> <first-positional-if-any>" → queued replies.
44
+ * Unscripted calls answer 0/{} so a missing script fails loudly in assertions
45
+ * rather than throwing. */
46
+ function fakeCli(script: Map<string, Res[]>, calls: Call[]) {
47
+ return async (cmd: string, args: string[]) => {
48
+ // args carries the global "-s <session>" prefix; strip it for keying.
49
+ const trimmed = args[0] === "-s" ? args.slice(2) : args;
50
+ // `block call -b <id> <method>` keys on the METHOD (the interesting part);
51
+ // `block send -b <id>` keys on the verb.
52
+ // Two-word commands ("block ls", "window new", "session inspect") key on
53
+ // both words; single verbs ("split", "focus", "version") on one; `block
54
+ // call` keys on the METHOD (the interesting part of that shape).
55
+ const twoWord = new Set(["block ls", "block send-key", "block send", "block close", "window ls", "window new", "window close", "session inspect"]);
56
+ let key = trimmed.slice(0, 2).join(" ");
57
+ if (!twoWord.has(key)) key = trimmed[0] ?? "";
58
+ if (trimmed[0] === "block" && trimmed[1] === "call") key = `block call ${trimmed[4] ?? ""}`;
59
+ const res = { code: 0, stdout: "{}", stderr: "", ...script.get(`${cmd} ${key}`)?.shift() };
60
+ calls.push({ args });
61
+ return res;
62
+ };
63
+ }
64
+
65
+ /** Root status record for a live pi in a given state. */
66
+ function piStatus(state: string, updatedAt: string): Res {
67
+ return {
68
+ code: 0,
69
+ stdout: JSON.stringify({ records: [{ state, app: "pi", effective_app: "pi", updated_at: updatedAt }] }),
70
+ };
71
+ }
72
+
73
+ function liveProc(cwd = "/repo"): Res {
74
+ return { code: 0, stdout: JSON.stringify({ last_exit: null, foreground: { cwd, name: "node" } }) };
75
+ }
76
+
77
+ function exitedProc(): Res {
78
+ return { code: 0, stdout: JSON.stringify({ last_exit: { code: 0 }, foreground: { name: "node" } }) };
79
+ }
80
+
81
+ const T0 = "2026-11-18T09:41:43.810154+07:00";
82
+ const T1 = "2026-11-18T09:42:05.510036+07:00";
83
+ const T2 = "2026-11-18T09:42:07.913979+07:00";
84
+
85
+ // Failure-path windows are wall-clock; shrink them (the herdrHeartbeat
86
+ // precedent) so the suite stays fast, then restore.
87
+ const DEFAULT_TIMING = { ...rexTiming };
88
+ test.before(() => {
89
+ rexTiming.readyTimeoutMs = 800;
90
+ rexTiming.pollMs = 20;
91
+ rexTiming.unsentGraceMs = 200;
92
+ });
93
+ test.after(() => Object.assign(rexTiming, DEFAULT_TIMING));
94
+
95
+ afterEach(() => {
96
+ clearRexRegistry();
97
+ resetRexProbe();
98
+ rexCli.exec = ((cmd: string) => Promise.resolve({ code: 0, stdout: "{}", stderr: "" })) as typeof rexCli.exec;
99
+ delete process.env.REX_SESSION;
100
+ delete process.env.REX_BLOCK;
101
+ delete process.env.PI_SUBAGENT_HERDR;
102
+ });
103
+
104
+ // ---------------------------------------------------------------------------
105
+ // Detection
106
+ // ---------------------------------------------------------------------------
107
+
108
+ test("rexEnvDetected: REX_SESSION is the marker; REX_BLOCK alone is not enough", () => {
109
+ delete process.env.REX_SESSION;
110
+ delete process.env.REX_BLOCK;
111
+ assert.equal(rexEnvDetected(), false);
112
+ process.env.REX_BLOCK = "block:1";
113
+ assert.equal(rexEnvDetected(), false);
114
+ process.env.REX_SESSION = "session:1";
115
+ assert.equal(rexEnvDetected(), true);
116
+ });
117
+
118
+ test("rexDisabled: subagent.herdr:\"off\" and the child recursion guard both disable", () => {
119
+ assert.equal(rexDisabled(undefined), false);
120
+ assert.equal(rexDisabled({ herdr: "off" }), true);
121
+ assert.equal(rexDisabled({ herdr: "auto" }), false);
122
+ process.env.PI_SUBAGENT_HERDR = "off";
123
+ assert.equal(rexDisabled(undefined), true);
124
+ });
125
+
126
+ test("probeRexBinary: `rex version` must answer; successes cache, failures do not", async () => {
127
+ const calls: Call[] = [];
128
+ rexCli.exec = fakeCli(new Map([["rex version", [{ code: 1 }]]]), calls) as typeof rexCli.exec;
129
+ assert.equal(await probeRexBinary(rexCli.exec), false);
130
+ assert.ok(calls.some((c) => c.args[0] === "version"));
131
+
132
+ const okCalls: Call[] = [];
133
+ rexCli.exec = fakeCli(new Map([["rex version", [{ code: 0, stdout: "rex 0.1.0\n" }]]]), okCalls) as typeof rexCli.exec;
134
+ assert.equal(await probeRexBinary(rexCli.exec), true);
135
+ });
136
+
137
+ // ---------------------------------------------------------------------------
138
+ // Terminal state
139
+ // ---------------------------------------------------------------------------
140
+
141
+ test("getRexTerminal: maps the root status record, keeps the clock, fails closed", async () => {
142
+ rexCli.exec = fakeCli(new Map([
143
+ ["rex block call program_status", [piStatus("working", T1)]],
144
+ ["rex block call process", [liveProc("/repo")]],
145
+ ]), []) as typeof rexCli.exec;
146
+ const info = await getRexTerminal("block:1", rexCli.exec);
147
+ assert.equal(info?.status, "working");
148
+ assert.equal(info?.app, "pi");
149
+ assert.equal(info?.state, "live");
150
+ assert.equal(info?.cwd, "/repo");
151
+ assert.equal(info?.statusAt, Date.parse(T1));
152
+
153
+ // An unreported/unknown state must never read as idle.
154
+ rexCli.exec = fakeCli(new Map([
155
+ ["rex block call program_status", [{ code: 0, stdout: JSON.stringify({ records: [{ state: "future-state", app: "pi", updated_at: T1 }] }) }]],
156
+ ["rex block call process", [liveProc()]],
157
+ ]), []) as typeof rexCli.exec;
158
+ assert.equal((await getRexTerminal("block:1", rexCli.exec))?.status, "unknown");
159
+
160
+ // A reported last_exit means the program ended.
161
+ rexCli.exec = fakeCli(new Map([
162
+ ["rex block call program_status", [piStatus("done", T2)]],
163
+ ["rex block call process", [exitedProc()]],
164
+ ]), []) as typeof rexCli.exec;
165
+ assert.equal((await getRexTerminal("block:1", rexCli.exec))?.state, "finished");
166
+
167
+ // Both calls failing = no information at all.
168
+ rexCli.exec = fakeCli(new Map([
169
+ ["rex block call program_status", [{ code: 1, stderr: "not found" }]],
170
+ ["rex block call process", [{ code: 1, stderr: "not found" }]],
171
+ ]), []) as typeof rexCli.exec;
172
+ assert.equal(await getRexTerminal("nope", rexCli.exec), undefined);
173
+ });
174
+
175
+ // ---------------------------------------------------------------------------
176
+ // Layout helpers
177
+ // ---------------------------------------------------------------------------
178
+
179
+ test("lastTiledBlock: LAST leaf in layout order, falls back to the focused block", () => {
180
+ const splitWindow = {
181
+ focused_block_id: "block:a",
182
+ layers: [{
183
+ kind: "tiled",
184
+ layout: {
185
+ rect: [0, 0, 1, 1],
186
+ split: {
187
+ split_id: "split:1",
188
+ direction: "vertical",
189
+ ratio: 0.5,
190
+ before: { rect: [0, 0, 1, 0.5], block_id: "block:a" },
191
+ after: { rect: [0, 0.5, 1, 0.5], block_id: "block:b" },
192
+ },
193
+ },
194
+ }],
195
+ };
196
+ assert.equal(lastTiledBlock(splitWindow), "block:b");
197
+ // No layout at all → the focused block; nothing at all → undefined.
198
+ assert.equal(lastTiledBlock({ focused_block_id: "block:z", layers: [] }), "block:z");
199
+ assert.equal(lastTiledBlock({ layers: [] }), undefined);
200
+ });
201
+
202
+ // ---------------------------------------------------------------------------
203
+ // Prepare: topology
204
+ // ---------------------------------------------------------------------------
205
+
206
+ function spacesEmpty(): Res {
207
+ return { code: 0, stdout: JSON.stringify({ windows: [] }) };
208
+ }
209
+
210
+ test("prepare: creates one window per agent type with the pi argv (and env wrapper)", async () => {
211
+ process.env.REX_SESSION = "session:1";
212
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-rex-prep-"));
213
+ const calls: Call[] = [];
214
+ rexCli.exec = fakeCli(new Map([
215
+ ["rex block ls", [{ code: 0, stdout: JSON.stringify({ blocks: [] }) }]],
216
+ ["rex window ls", [spacesEmpty()]],
217
+ ["rex window new", [{ code: 0, stdout: JSON.stringify({ window_id: "window:1", block_ids: ["block:10"] }) }]],
218
+ ]), calls) as typeof rexCli.exec;
219
+ const handle = await prepareRexTask({
220
+ agentType: "scout",
221
+ systemPrompt: "you are scout",
222
+ task: "find things",
223
+ cwd,
224
+ model: "router/ds-flash",
225
+ thinking: "off",
226
+ tools: ["read", "grep"],
227
+ timeoutMs: 60_000,
228
+ });
229
+ assert.equal(handle.tabId, "window:1");
230
+ assert.equal(handle.address, "block:10");
231
+ assert.equal(handle.paneId, "block:10");
232
+ assert.equal(handle.tabCreatedHere, true);
233
+ assert.ok(handle.resultFile.startsWith(join(cwd, ".pi", "rex")));
234
+ assert.equal(findRexAgent("block:10")?.address, "block:10");
235
+ assert.equal(findRexAgent(handle.name)?.address, "block:10");
236
+
237
+ const windowNew = calls.find((c) => c.args.includes("new") && c.args.includes("window"));
238
+ assert.ok(windowNew);
239
+ const argv = windowNew!.args;
240
+ // The window label is POSITIONAL (right after the subcommand) and `--`
241
+ // introduces the command, so a label can never be read as a command word.
242
+ const newIdx = argv.indexOf("new");
243
+ assert.equal(argv[newIdx + 1], "scout");
244
+ assert.ok(argv.includes("--focus=false"));
245
+ assert.ok(argv.includes("--json"));
246
+ const sep = argv.indexOf("--");
247
+ assert.ok(sep > 0);
248
+ const command = argv.slice(sep + 1);
249
+ assert.equal(command[0], "/usr/bin/env");
250
+ assert.ok(command.includes("PI_SUBAGENT_HERDR=off"), "child must not recurse into rex dispatch");
251
+ assert.ok(command.some((a) => a.startsWith("CEULEN_ADVISOR_MARKER=")), "advisor marker must reach the child");
252
+ const pi = command.indexOf("pi");
253
+ assert.ok(pi > 0);
254
+ const piArgs = command.slice(pi + 1);
255
+ assert.ok(piArgs.includes("--append-system-prompt"));
256
+ assert.ok(piArgs.includes("--model"));
257
+ assert.ok(piArgs.includes("--tools"));
258
+ assert.ok(piArgs.includes("--session-id"));
259
+ assert.ok(piArgs.includes("--name"));
260
+ });
261
+
262
+ test("prepare: adopts an existing same-type window (never close-eligible) and splits a pane", async () => {
263
+ process.env.REX_SESSION = "session:1";
264
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-rex-prep-"));
265
+ const calls: Call[] = [];
266
+ rexCli.exec = fakeCli(new Map([
267
+ ["rex block ls", [
268
+ { code: 0, stdout: JSON.stringify({ blocks: [{ block_id: "block:5", label: "scout-1", window_id: "window:1" }] }) },
269
+ { code: 0, stdout: JSON.stringify({ blocks: [{ block_id: "block:5", label: "scout-1", window_id: "window:1" }] }) },
270
+ ]],
271
+ ["rex window ls", [{ code: 0, stdout: JSON.stringify({ windows: [{ window_id: "window:1", label: "scout" }] }) }]],
272
+ ["rex session inspect", [{
273
+ code: 0,
274
+ stdout: JSON.stringify({
275
+ windows: [{
276
+ window_id: "window:1",
277
+ label: "scout",
278
+ focused_block_id: "block:5",
279
+ layers: [{ kind: "tiled", layout: { rect: [0, 0, 1, 1], block_id: "block:5" } }],
280
+ }],
281
+ }),
282
+ }]],
283
+ ["rex split", [{ code: 0, stdout: JSON.stringify({ anchor_id: "block:5", block_ids: ["block:11"] }) }]],
284
+ ]), calls) as typeof rexCli.exec;
285
+ const handle = await prepareRexTask({ agentType: "scout", systemPrompt: "s", task: "t", cwd, timeoutMs: 60_000 });
286
+ assert.equal(handle.tabId, "window:1");
287
+ assert.equal(handle.tabCreatedHere, false); // adopted → not ours to close
288
+ assert.equal(handle.address, "block:11");
289
+ assert.notEqual(handle.name, "scout-1"); // allocateName avoided the live label
290
+ const split = calls.find((c) => c.args.includes("split"));
291
+ assert.ok(split);
292
+ assert.ok(split!.args.includes("block:5")); // anchored on the window's only block
293
+ assert.ok(split!.args.includes("--label"));
294
+ // `session inspect` takes the session POSITIONALLY and rejects the global
295
+ // `-s` prefix (live 2026-11-18: the prefixed form made every adoption fail
296
+ // with "window has no block to split beside"). It must stay unprefixed.
297
+ const inspect = calls.find((c) => c.args.includes("inspect"));
298
+ assert.ok(inspect);
299
+ assert.equal(inspect!.args[0], "session");
300
+ assert.ok(!inspect!.args.includes("-s"));
301
+ });
302
+
303
+ test("prepare: no window to adopt and no anchor → clear failure, no orphan registry entry", async () => {
304
+ process.env.REX_SESSION = "session:1";
305
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-rex-prep-"));
306
+ rexCli.exec = fakeCli(new Map([
307
+ ["rex block ls", [{ code: 0, stdout: JSON.stringify({ blocks: [] }) }]],
308
+ ["rex window ls", [{ code: 0, stdout: JSON.stringify({ windows: [{ window_id: "window:1", label: "scout" }] }) }]],
309
+ ["rex session inspect", [{ code: 0, stdout: JSON.stringify({ windows: [{ window_id: "window:1", label: "scout", layers: [] }] }) }]],
310
+ ]), []) as typeof rexCli.exec;
311
+ await assert.rejects(
312
+ () => prepareRexTask({ agentType: "scout", systemPrompt: "s", task: "t", cwd, timeoutMs: 60_000 }),
313
+ /no block to split beside/,
314
+ );
315
+ assert.equal(getRexRegistry().length, 0);
316
+ });
317
+
318
+ test("prepare: window new failure leaves no registry entry behind", async () => {
319
+ process.env.REX_SESSION = "session:1";
320
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-rex-prep-"));
321
+ rexCli.exec = fakeCli(new Map([
322
+ ["rex block ls", [{ code: 0, stdout: JSON.stringify({ blocks: [] }) }]],
323
+ ["rex window ls", [spacesEmpty()]],
324
+ ["rex window new", [{ code: 1, stderr: "rex window new failed: bad label" }]],
325
+ ]), []) as typeof rexCli.exec;
326
+ await assert.rejects(() => prepareRexTask({ agentType: "scout", systemPrompt: "s", task: "t", cwd, timeoutMs: 60_000 }), /window new failed/);
327
+ assert.equal(getRexRegistry().length, 0);
328
+ });
329
+
330
+ // ---------------------------------------------------------------------------
331
+ // Prompt + wait
332
+ // ---------------------------------------------------------------------------
333
+
334
+ test("promptRexAndWait: readiness gate, paste+enter, settle on done", async () => {
335
+ const calls: Call[] = [];
336
+ rexCli.exec = fakeCli(new Map([
337
+ // Booting (working) first, then ready idle at T0.
338
+ ["rex block call program_status", [piStatus("working", T0), piStatus("idle", T0), piStatus("done", T2)]],
339
+ ["rex block call process", [liveProc(), liveProc(), liveProc()]],
340
+ ["rex block send", [{ code: 0, stdout: "{}" }]],
341
+ ["rex block send-key", [{ code: 0, stdout: "{}" }]],
342
+ ]), calls) as typeof rexCli.exec;
343
+ const out = await promptRexAndWait({ address: "block:1", text: "hi", timeoutMs: 60_000, exec: rexCli.exec });
344
+ assert.deepEqual(out, { state: "done", delivered: true });
345
+ // Readiness polls happened BEFORE the paste; the paste is send + send-key.
346
+ const sendIdx = calls.findIndex((c) => c.args.includes("send"));
347
+ const statusPollsBefore = calls.slice(0, sendIdx).filter((c) => c.args.includes("program_status")).length;
348
+ assert.equal(statusPollsBefore, 2);
349
+ const sendKeyIdx = calls.findIndex((c) => c.args.includes("send-key"));
350
+ assert.ok(sendKeyIdx > sendIdx);
351
+ assert.ok(calls[sendKeyIdx]!.args.includes("enter"));
352
+ });
353
+
354
+ test("promptRexAndWait: a paste that never submitted is NOT a delivery (no fresh status)", async () => {
355
+ rexCli.exec = fakeCli(new Map([
356
+ // Ready at T0 and stays there: the composer holds the text, nothing ran.
357
+ ["rex block call program_status", Array.from({ length: 40 }, () => piStatus("idle", T0))],
358
+ ["rex block call process", Array.from({ length: 40 }, () => liveProc())],
359
+ ["rex block send", [{ code: 0, stdout: "{}" }]],
360
+ ["rex block send-key", [{ code: 0, stdout: "{}" }]],
361
+ ]), []) as typeof rexCli.exec;
362
+ const out = await promptRexAndWait({ address: "block:1", text: "hi", timeoutMs: 60_000, exec: rexCli.exec });
363
+ assert.equal(out.delivered, false);
364
+ assert.match(out.error ?? "", /never submitted/);
365
+ });
366
+
367
+ test("promptRexAndWait: idle with a FRESH timestamp settles (turn finished unwatched)", async () => {
368
+ rexCli.exec = fakeCli(new Map([
369
+ ["rex block call program_status", [piStatus("idle", T0), piStatus("idle", T1)]],
370
+ ["rex block call process", [liveProc(), liveProc()]],
371
+ ["rex block send", [{ code: 0, stdout: "{}" }]],
372
+ ["rex block send-key", [{ code: 0, stdout: "{}" }]],
373
+ ]), []) as typeof rexCli.exec;
374
+ const out = await promptRexAndWait({ address: "block:1", text: "hi", timeoutMs: 60_000, exec: rexCli.exec });
375
+ assert.deepEqual(out, { state: "idle", delivered: true });
376
+ });
377
+
378
+ test("promptRexAndWait: blocked settles as blocked without a delivery", async () => {
379
+ rexCli.exec = fakeCli(new Map([
380
+ ["rex block call program_status", [piStatus("idle", T0), piStatus("blocked", T1)]],
381
+ ["rex block call process", [liveProc(), liveProc()]],
382
+ ["rex block send", [{ code: 0, stdout: "{}" }]],
383
+ ["rex block send-key", [{ code: 0, stdout: "{}" }]],
384
+ ]), []) as typeof rexCli.exec;
385
+ const out = await promptRexAndWait({ address: "block:1", text: "hi", timeoutMs: 60_000, exec: rexCli.exec });
386
+ assert.equal(out.state, "blocked");
387
+ assert.equal(out.delivered, false);
388
+ assert.match(out.error ?? "", /blocked/i);
389
+ });
390
+
391
+ test("promptRexAndWait: a working child that never settles reports timeout, still delivered", async () => {
392
+ rexCli.exec = fakeCli(new Map([
393
+ ["rex block call program_status", [piStatus("idle", T0), ...Array.from({ length: 60 }, () => piStatus("working", T1))]],
394
+ ["rex block call process", Array.from({ length: 61 }, () => liveProc())],
395
+ ["rex block send", [{ code: 0, stdout: "{}" }]],
396
+ ["rex block send-key", [{ code: 0, stdout: "{}" }]],
397
+ ]), []) as typeof rexCli.exec;
398
+ const out = await promptRexAndWait({ address: "block:1", text: "hi", timeoutMs: 400, exec: rexCli.exec });
399
+ assert.equal(out.delivered, true);
400
+ assert.match(out.error ?? "", /timeout after 400ms/);
401
+ });
402
+
403
+ test("promptRexAndWait: never sends to a child that is not a ready pi", async () => {
404
+ const calls: Call[] = [];
405
+ rexCli.exec = fakeCli(new Map([
406
+ ["rex block call program_status", Array.from({ length: 400 }, () => ({ code: 0, stdout: JSON.stringify({ records: [{ state: "working", app: "pi", updated_at: T1 }] }) }))],
407
+ ["rex block call process", Array.from({ length: 400 }, () => liveProc())],
408
+ ]), calls) as typeof rexCli.exec;
409
+ const out = await promptRexAndWait({ address: "block:1", text: "x", timeoutMs: 300, exec: rexCli.exec });
410
+ assert.equal(out.delivered, false);
411
+ assert.equal(calls.some((c) => c.args.includes("send")), false);
412
+ });
413
+
414
+ test("promptRexAndWait: a pre-aborted signal never touches the CLI", async () => {
415
+ const calls: Call[] = [];
416
+ rexCli.exec = fakeCli(new Map(), calls) as typeof rexCli.exec;
417
+ const controller = new AbortController();
418
+ controller.abort();
419
+ const out = await promptRexAndWait({ address: "block:1", text: "hi", timeoutMs: 1_000, exec: rexCli.exec, signal: controller.signal });
420
+ assert.equal(out.delivered, false);
421
+ assert.match(out.error ?? "", /aborted/);
422
+ assert.deepEqual(calls, []);
423
+ });
424
+
425
+ test("promptRexAndWait: a finished child is reported, never prompted", async () => {
426
+ rexCli.exec = fakeCli(new Map([
427
+ ["rex block call program_status", [piStatus("done", T0)]],
428
+ ["rex block call process", [exitedProc()]],
429
+ ]), []) as typeof rexCli.exec;
430
+ const out = await promptRexAndWait({ address: "block:1", text: "hi", timeoutMs: 5_000, exec: rexCli.exec });
431
+ assert.equal(out.delivered, false);
432
+ assert.match(out.error ?? "", /exited before its task was sent/);
433
+ });
434
+
435
+ // ---------------------------------------------------------------------------
436
+ // Collection
437
+ // ---------------------------------------------------------------------------
438
+
439
+ function handleWith(cwd: string, overrides: Partial<RexHandle> = {}): RexHandle {
440
+ return {
441
+ name: "scout-1", agentType: "scout", tabId: "window:1", address: "block:10", paneId: "block:10",
442
+ task: "t", resultFile: join(cwd, "report.md"), advisorMarker: join(cwd, "m.json"),
443
+ model: "router/x", timeoutMs: 60_000, tabCreatedHere: true,
444
+ ...overrides,
445
+ };
446
+ }
447
+
448
+ test("collectRexResult: the report file wins over the pane", async () => {
449
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-rex-collect-"));
450
+ const handle = handleWith(cwd);
451
+ writeFileSync(handle.resultFile, "REPORT BODY");
452
+ const calls: Call[] = [];
453
+ rexCli.exec = fakeCli(new Map(), calls) as typeof rexCli.exec;
454
+ const out = await collectRexResult({ handle, exec: rexCli.exec });
455
+ assert.deepEqual(out, { output: "REPORT BODY", source: "file" });
456
+ assert.equal(calls.length, 0); // no pane read when the contract file exists
457
+ });
458
+
459
+ test("readRexBlock: the head slice is tailed through blob_read when more remains", async () => {
460
+ const calls: Call[] = [];
461
+ rexCli.exec = fakeCli(new Map([
462
+ ["rex block call format", [{ code: 0, stdout: JSON.stringify({ content: "head", total: 100_000, id: 7 }) }]],
463
+ ["rex block call blob_read", [{ code: 0, stdout: JSON.stringify({ id: 7, data: "TAIL", total: 100_000, eof: true }) }]],
464
+ ]), calls) as typeof rexCli.exec;
465
+ const res = await readRexBlock("block:10", rexCli.exec, 1_000);
466
+ assert.deepEqual(res, { ok: true, text: "TAIL" });
467
+ const blob = calls.find((c) => c.args.includes("blob_read"));
468
+ assert.ok(blob);
469
+ const args = JSON.parse(blob!.args[blob!.args.length - 1]!) as { id: number; offset: number };
470
+ assert.equal(args.id, 7);
471
+ assert.equal(args.offset, 99_000); // total - maxBytes
472
+ });
473
+
474
+ test("readRexBlock: a reply carrying an id is re-read from the END even when total < cap", async () => {
475
+ // Live 2026-11-18: a 892-byte pane returned 365 bytes of boot chrome WITH an
476
+ // id (more remains). Comparing `total` against the cap instead of checking
477
+ // the id kept the head and lost the child's actual reply.
478
+ const calls: Call[] = [];
479
+ rexCli.exec = fakeCli(new Map([
480
+ ["rex block call format", [{ code: 0, stdout: JSON.stringify({ content: "boot chrome head", total: 892, id: 4 }) }]],
481
+ ["rex block call blob_read", [{ code: 0, stdout: JSON.stringify({ id: 4, data: "THE ACTUAL REPLY", total: 892, eof: true }) }]],
482
+ ]), calls) as typeof rexCli.exec;
483
+ const res = await readRexBlock("block:10", rexCli.exec);
484
+ assert.deepEqual(res, { ok: true, text: "THE ACTUAL REPLY" });
485
+ const blob = calls.find((c) => c.args.includes("blob_read"));
486
+ assert.ok(blob, "the reply must be re-read, not the head kept");
487
+ const args = JSON.parse(blob!.args[blob!.args.length - 1]!) as { offset: number };
488
+ assert.equal(args.offset, 892 - 64 * 1024 < 0 ? 0 : 892 - 64 * 1024);
489
+ });
490
+
491
+ test("collectRexResult: an echo-only pane is NOT a reply", async () => {
492
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-rex-echo-"));
493
+ const task = "Write exactly WORKER-PROBE-OK to the report file, then reply.";
494
+ const handle = handleWith(cwd, { task });
495
+ rexCli.exec = fakeCli(new Map([
496
+ ["rex block call format", [{
497
+ code: 0,
498
+ stdout: JSON.stringify({
499
+ content: [
500
+ "▀▀█ v1.5.2",
501
+ " π > model > repo",
502
+ task,
503
+ "---",
504
+ "Delivery: when your task is complete, write your full final report as Markdown to `/r.md` " +
505
+ "(create parent directories if needed), then reply with a one-line summary only. " +
506
+ "If follow-up feedback arrives after delivery (e.g. an advisor review), apply it and update the report file to the corrected version.",
507
+ ].join("\n"),
508
+ }),
509
+ }]],
510
+ ]), []) as typeof rexCli.exec;
511
+ const out = await collectRexResult({ handle, exec: rexCli.exec });
512
+ assert.deepEqual(out, { output: "", source: "none" });
513
+ });
514
+
515
+ test("collectRexResult: a real inline reply comes through beyond the contract", async () => {
516
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-rex-reply-"));
517
+ const task = "Reply with exactly SCOUT-INLINE-OK and nothing else.";
518
+ const handle = handleWith(cwd, { task, readOnly: true });
519
+ rexCli.exec = fakeCli(new Map([
520
+ ["rex block call format", [{
521
+ code: 0,
522
+ stdout: JSON.stringify({
523
+ content: [
524
+ "▀▀█ v1.5.2",
525
+ task,
526
+ "---",
527
+ "Delivery: this session has read-only tools — do NOT write any files. Reply with your full final report as your final message.",
528
+ "SCOUT-INLINE-OK",
529
+ "↑74 ↓7 R35K CH99.8% · (router) R:90%/54M W:92%/6D M:41%/11D",
530
+ " π > ⬢ ocg/deepseek-v4.1-flash · max > 📁 /tmp > ⑂ main",
531
+ ].join("\n"),
532
+ }),
533
+ }]],
534
+ ]), []) as typeof rexCli.exec;
535
+ const out = await collectRexResult({ handle, exec: rexCli.exec });
536
+ assert.equal(out.source, "pane");
537
+ assert.match(out.output, /SCOUT-INLINE-OK/);
538
+ // Status chrome and the composer must not leak into the payload.
539
+ assert.doesNotMatch(out.output, /↑74/);
540
+ assert.doesNotMatch(out.output, /π >/);
541
+ });
542
+
543
+ test("replyBeyondEcho: cuts at the delivery contract, else at the task echo", () => {
544
+ const text = [
545
+ "chrome",
546
+ "Do the thing.",
547
+ "---",
548
+ "Delivery: this session has read-only tools — do NOT write any files. Reply with your full final report as your final message.",
549
+ "THE ANSWER",
550
+ ].join("\n");
551
+ assert.equal(replyBeyondEcho(text, "Do the thing."), "THE ANSWER");
552
+ // No contract (a follow-up the child typed): cut after the task echo.
553
+ assert.equal(replyBeyondEcho("echoed prompt FOLLOWUP ANSWER", "echoed prompt"), "FOLLOWUP ANSWER");
554
+ });
555
+
556
+ // ---------------------------------------------------------------------------
557
+ // Execute: full flow, abort, timeout
558
+ // ---------------------------------------------------------------------------
559
+
560
+ test("executeRexTask: collects the report and stamps the rex pane in the usage line", async () => {
561
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-rex-exec-"));
562
+ const handle = handleWith(cwd);
563
+ writeFileSync(handle.resultFile, "FINAL REPORT");
564
+ rexCli.exec = fakeCli(new Map([
565
+ ["rex block call program_status", [piStatus("idle", T0), piStatus("done", T1)]],
566
+ ["rex block call process", [liveProc(), liveProc()]],
567
+ ["rex block send", [{ code: 0, stdout: "{}" }]],
568
+ ["rex block send-key", [{ code: 0, stdout: "{}" }]],
569
+ ]), []) as typeof rexCli.exec;
570
+ const result = await executeRexTask(handle, { exec: rexCli.exec });
571
+ assert.equal(result.status, "success");
572
+ assert.match(result.model ?? "", /rex pane:scout-1/);
573
+ assert.equal(result.bestEffort, false);
574
+ const text = (result.messages[0] as any)?.content?.[0]?.text;
575
+ assert.equal(text, "FINAL REPORT");
576
+ });
577
+
578
+ test("executeRexTask: a timeout interrupts the pane and says so", async () => {
579
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-rex-exec-"));
580
+ const handle = handleWith(cwd, { timeoutMs: 400 });
581
+ const calls: Call[] = [];
582
+ rexCli.exec = fakeCli(new Map([
583
+ ["rex block call program_status", [piStatus("idle", T0), ...Array.from({ length: 80 }, () => piStatus("working", T1))]],
584
+ ["rex block call process", Array.from({ length: 90 }, () => liveProc())],
585
+ ["rex block send", [{ code: 0, stdout: "{}" }]],
586
+ ["rex block send-key", Array.from({ length: 10 }, () => ({ code: 0, stdout: "{}" }) as Res)],
587
+ ]), calls) as typeof rexCli.exec;
588
+ const result = await executeRexTask(handle, { exec: rexCli.exec });
589
+ assert.equal(result.status, "timeout");
590
+ assert.match(result.errorMessage ?? "", /may still complete its current write/);
591
+ assert.ok(calls.some((c) => c.args.includes("esc")));
592
+ });
593
+
594
+ test("executeRexTask: an aborted parent maps to status aborted, never success", async () => {
595
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-rex-exec-"));
596
+ const handle = handleWith(cwd);
597
+ writeFileSync(handle.resultFile, "REPORT");
598
+ rexCli.exec = fakeCli(new Map([
599
+ ["rex block call program_status", [piStatus("idle", T0), piStatus("done", T1)]],
600
+ ["rex block call process", [liveProc(), liveProc()]],
601
+ ["rex block send", [{ code: 0, stdout: "{}" }]],
602
+ ["rex block send-key", [{ code: 0, stdout: "{}" }]],
603
+ ]), []) as typeof rexCli.exec;
604
+ const controller = new AbortController();
605
+ const promise = executeRexTask(handle, { exec: rexCli.exec, signal: controller.signal });
606
+ controller.abort();
607
+ const result = await promise;
608
+ assert.equal(result.status, "aborted");
609
+ assert.equal(result.stopReason, "aborted");
610
+ });
611
+
612
+ test("cancelRexAgent: esc then ctrl+c only while still working", async () => {
613
+ const escalate: Call[] = [];
614
+ rexCli.exec = fakeCli(new Map([
615
+ ["rex block call program_status", [{ code: 0, stdout: JSON.stringify({ records: [{ state: "working", app: "pi", updated_at: T1 }] }) }]],
616
+ ["rex block call process", [liveProc()]],
617
+ ["rex block send-key", [{ code: 0, stdout: "{}" }, { code: 0, stdout: "{}" }]],
618
+ ]), escalate) as typeof rexCli.exec;
619
+ await cancelRexAgent("block:10", rexCli.exec);
620
+ assert.ok(escalate.some((c) => c.args.includes("ctrl+c")));
621
+
622
+ const calm: Call[] = [];
623
+ rexCli.exec = fakeCli(new Map([
624
+ ["rex block call program_status", [piStatus("idle", T0)]],
625
+ ["rex block call process", [liveProc()]],
626
+ ["rex block send-key", [{ code: 0, stdout: "{}" }]],
627
+ ]), calm) as typeof rexCli.exec;
628
+ await cancelRexAgent("block:10", rexCli.exec);
629
+ assert.equal(calm.some((c) => c.args.includes("ctrl+c")), false);
630
+ });
631
+
632
+ // ---------------------------------------------------------------------------
633
+ // Delivery contract + registry + control-tool guards
634
+ // ---------------------------------------------------------------------------
635
+
636
+ test("wrapRexTaskPrompt: writable children get the report-file contract; read-only reply inline", () => {
637
+ assert.match(wrapRexTaskPrompt("do it", "/tmp/r.md"), /write your full final report as Markdown to `\/tmp\/r\.md`/);
638
+ assert.match(wrapRexTaskPrompt("do it", "/tmp/r.md", true), /do NOT write any files/);
639
+ assert.match(wrapRexTaskPrompt("do it", "/tmp/r.md", true), /Reply with your full final report/);
640
+ });
641
+
642
+ test("registry: two dispatches register, lookup by name/block id, forget by window drops both", async () => {
643
+ process.env.REX_SESSION = "session:1";
644
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-rex-reg-"));
645
+ rexCli.exec = fakeCli(new Map([
646
+ ["rex block ls", [
647
+ { code: 0, stdout: JSON.stringify({ blocks: [] }) },
648
+ { code: 0, stdout: JSON.stringify({ blocks: [{ block_id: "block:30", label: "scout-1", window_id: "window:1" }] }) },
649
+ { code: 0, stdout: JSON.stringify({ blocks: [{ block_id: "block:30", label: "scout-1", window_id: "window:1" }] }) },
650
+ { code: 0, stdout: JSON.stringify({ blocks: [{ block_id: "block:30", label: "scout-1", window_id: "window:1" }] }) },
651
+ ]],
652
+ ["rex window ls", [
653
+ { code: 0, stdout: JSON.stringify({ windows: [] }) },
654
+ { code: 0, stdout: JSON.stringify({ windows: [{ window_id: "window:1", label: "scout" }] }) },
655
+ ]],
656
+ ["rex session inspect", [{
657
+ code: 0,
658
+ stdout: JSON.stringify({ windows: [{ window_id: "window:1", label: "scout", focused_block_id: "block:30", layers: [{ kind: "tiled", layout: { rect: [0, 0, 1, 1], block_id: "block:30" } }] }] }),
659
+ }]],
660
+ ["rex window new", [{ code: 0, stdout: JSON.stringify({ window_id: "window:1", block_ids: ["block:30"] }) }]],
661
+ ["rex split", [{ code: 0, stdout: JSON.stringify({ block_ids: ["block:31"] }) }]],
662
+ ]), []) as typeof rexCli.exec;
663
+ const first = await prepareRexTask({ agentType: "scout", systemPrompt: "s", task: "one", cwd, timeoutMs: 60_000 });
664
+ const second = await prepareRexTask({ agentType: "scout", systemPrompt: "s", task: "two", cwd, timeoutMs: 60_000 });
665
+ assert.equal(getRexRegistry().length, 2);
666
+ assert.notEqual(first.name, second.name);
667
+ assert.equal(findRexAgent("block:30")?.name, first.name); // block-id lookup
668
+ assert.equal(findRexAgent(second.name)?.address, "block:31");
669
+ forgetRexWindow("window:1"); // by window id drops every sibling in it
670
+ assert.equal(getRexRegistry().length, 0);
671
+ assert.equal(findRexAgent("block:30"), undefined);
672
+ forgetRexAgent("nope"); // no-op, no throw
673
+ });
674
+
675
+ test("rexWindowCloseBlockers: a busy or unverifiable sibling blocks the close", async () => {
676
+ process.env.REX_SESSION = "session:1";
677
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-rex-blockers-"));
678
+ rexCli.exec = fakeCli(new Map([
679
+ ["rex block ls", [
680
+ { code: 0, stdout: JSON.stringify({ blocks: [] }) },
681
+ { code: 0, stdout: JSON.stringify({ blocks: [{ block_id: "block:30", label: "scout-1", window_id: "window:1" }] }) },
682
+ { code: 0, stdout: JSON.stringify({ blocks: [{ block_id: "block:30", label: "scout-1", window_id: "window:1" }] }) },
683
+ ]],
684
+ ["rex window ls", [
685
+ { code: 0, stdout: JSON.stringify({ windows: [] }) },
686
+ { code: 0, stdout: JSON.stringify({ windows: [{ window_id: "window:1", label: "scout" }] }) },
687
+ ]],
688
+ ["rex session inspect", [{
689
+ code: 0,
690
+ stdout: JSON.stringify({ windows: [{ window_id: "window:1", label: "scout", focused_block_id: "block:30", layers: [{ kind: "tiled", layout: { rect: [0, 0, 1, 1], block_id: "block:30" } }] }] }),
691
+ }]],
692
+ ["rex window new", [{ code: 0, stdout: JSON.stringify({ window_id: "window:1", block_ids: ["block:30"] }) }]],
693
+ ["rex split", [{ code: 0, stdout: JSON.stringify({ block_ids: ["block:31"] }) }]],
694
+ // Sibling probe: block:31 is mid-turn; the named block:30 is at rest.
695
+ ["rex block call program_status", [piStatus("working", T1), piStatus("idle", T0)]],
696
+ ["rex block call process", [liveProc(), liveProc()]],
697
+ ]), []) as typeof rexCli.exec;
698
+ const first = await prepareRexTask({ agentType: "scout", systemPrompt: "s", task: "one", cwd, timeoutMs: 60_000 });
699
+ await prepareRexTask({ agentType: "scout", systemPrompt: "s", task: "two", cwd, timeoutMs: 60_000 });
700
+ const { siblings, self } = await rexWindowCloseBlockers(first, rexCli.exec);
701
+ assert.equal(siblings.length, 1); // the working sibling blocks the close
702
+ assert.equal(self, undefined); // the named agent itself is settled
703
+ });
704
+
705
+ test("closeRexWindow: reports CLI failure instead of claiming success", async () => {
706
+ rexCli.exec = fakeCli(new Map([
707
+ ["rex window close", [{ code: 1, stderr: "window not found" }]],
708
+ ]), []) as typeof rexCli.exec;
709
+ const res = await closeRexWindow("window:1", rexCli.exec);
710
+ assert.equal(res.ok, false);
711
+ assert.match(res.error ?? "", /window not found/);
712
+ });
713
+
714
+ test("prepareRexTask: task over the argv budget is rejected before any topology", async () => {
715
+ process.env.REX_SESSION = "session:1";
716
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-rex-budget-"));
717
+ const calls: Call[] = [];
718
+ rexCli.exec = fakeCli(new Map(), calls) as typeof rexCli.exec;
719
+ await assert.rejects(
720
+ () => prepareRexTask({ agentType: "scout", systemPrompt: "s", task: "x".repeat(80 * 1024), cwd, timeoutMs: 60_000 }),
721
+ /exceeds the .*byte budget/,
722
+ );
723
+ assert.deepEqual(calls, []); // nothing spawned
724
+ });