ceulen 0.26.1 → 0.27.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.
@@ -0,0 +1,572 @@
1
+ // herdr-app delegation backend (lib/herdr-app.ts): detection, name allocation
2
+ // against `hc ls`, tab/permission topology, prompt+wait mapping, collection,
3
+ // and the abort/timeout result mapping. Every CLI call is scripted through the
4
+ // `herdrAppCli.exec` seam (the herdr.ts `herdrCli` precedent).
5
+
6
+ import assert from "node:assert/strict";
7
+ import { mkdtempSync, writeFileSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { afterEach, test } from "node:test";
11
+
12
+ import {
13
+ cancelAppAgent,
14
+ clearHerdrAppRegistry,
15
+ collectAppResult,
16
+ executeHerdrAppTask,
17
+ findHerdrAppAgent,
18
+ forgetHerdrAppTab,
19
+ getHerdrAppRegistry,
20
+ getTerminal,
21
+ herdrAppCli,
22
+ herdrAppDisabled,
23
+ herdrAppEnvDetected,
24
+ isDelegatedHerdrAppAgent,
25
+ prepareHerdrAppTask,
26
+ promptAppAndWait,
27
+ probeHerdrAppBinary,
28
+ wrapAppTaskPrompt,
29
+ type HerdrAppHandle,
30
+ } from "../lib/herdr-app.ts";
31
+
32
+ type Res = { code: number; stdout?: string; stderr?: string };
33
+ type Call = { cmd: string; args: string[] };
34
+
35
+ /** Scripted exec: "cmd key" → queued responses; unscripted calls answer 0/{}. */
36
+ function fakeCli(script: Map<string, Res[]>, calls: Call[]) {
37
+ return async (cmd: string, args: string[]) => {
38
+ const key = `${cmd} ${args[0] ?? ""}`;
39
+ const res = { code: 0, stdout: "{}", stderr: "", ...script.get(key)?.shift() };
40
+ calls.push({ cmd, args });
41
+ return res;
42
+ };
43
+ }
44
+
45
+ /** `hc get` reply: a live, input-ready pi reporting idle at `turn`. */
46
+ function readyPi(turn = 0): Res {
47
+ return { code: 0, stdout: JSON.stringify({ address: "t20", state: "live", turn, status: { app: "pi", state: "idle" } }) };
48
+ }
49
+
50
+ afterEach(() => {
51
+ clearHerdrAppRegistry();
52
+ herdrAppCli.exec = ((cmd: string, args: string[]) => {
53
+ // Reset to a benign default so a leaked script never affects another test.
54
+ return Promise.resolve({ code: 0, stdout: "{}", stderr: "" });
55
+ }) as typeof herdrAppCli.exec;
56
+ delete process.env.HC_TERMINAL_ID;
57
+ delete process.env.PI_SUBAGENT_HERDR;
58
+ });
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // Detection
62
+ // ---------------------------------------------------------------------------
63
+
64
+ test("herdrAppEnvDetected: HC_TERMINAL_ID is the marker (HERDR_ENV is the TUI's)", () => {
65
+ delete process.env.HC_TERMINAL_ID;
66
+ assert.equal(herdrAppEnvDetected(), false);
67
+ process.env.HC_TERMINAL_ID = "t2";
68
+ assert.equal(herdrAppEnvDetected(), true);
69
+ });
70
+
71
+ test("herdrAppDisabled: subagent.herdr:\"off\" and the child guard both disable", () => {
72
+ assert.equal(herdrAppDisabled(undefined), false);
73
+ assert.equal(herdrAppDisabled({ herdr: "off" }), true);
74
+ assert.equal(herdrAppDisabled({ herdr: "auto" }), false);
75
+ process.env.PI_SUBAGENT_HERDR = "off";
76
+ assert.equal(herdrAppDisabled(undefined), true);
77
+ });
78
+
79
+ test("probeHerdrAppBinary: needs BOTH binaries (app for layout, hc for terminals)", async () => {
80
+ const calls: Call[] = [];
81
+ // hc answers, herdr-app does not → not usable.
82
+ herdrAppCli.exec = fakeCli(new Map([["herdr-app --version", [{ code: 1 }]]]), calls) as typeof herdrAppCli.exec;
83
+ assert.equal(await probeHerdrAppBinary(herdrAppCli.exec), false);
84
+ assert.deepEqual(calls.map((c) => c.cmd).sort(), ["hc", "herdr-app"]);
85
+
86
+ const okCalls: Call[] = [];
87
+ herdrAppCli.exec = fakeCli(new Map([
88
+ ["herdr-app --version", [{ code: 0, stdout: "herdr-app 0.9.5" }]],
89
+ ["hc --version", [{ code: 0, stdout: "hc 0.1.21" }]],
90
+ ]), okCalls) as typeof herdrAppCli.exec;
91
+ assert.equal(await probeHerdrAppBinary(herdrAppCli.exec), true);
92
+ });
93
+
94
+ // ---------------------------------------------------------------------------
95
+ // Terminal state
96
+ // ---------------------------------------------------------------------------
97
+
98
+ test("getTerminal maps the hc status object; unknown shapes fail closed", async () => {
99
+ const calls: Call[] = [];
100
+ herdrAppCli.exec = fakeCli(new Map([
101
+ ["hc get", [{ code: 0, stdout: JSON.stringify({ address: "t7", state: "live", status: { app: "pi", state: "working" }, cwd: "/repo" }) }]],
102
+ ]), calls) as typeof herdrAppCli.exec;
103
+ const info = await getTerminal("t7", herdrAppCli.exec);
104
+ assert.equal(info?.status, "working");
105
+ assert.equal(info?.app, "pi");
106
+ assert.equal(info?.state, "live");
107
+ assert.equal(info?.cwd, "/repo");
108
+
109
+ herdrAppCli.exec = fakeCli(new Map([
110
+ ["hc get", [{ code: 0, stdout: JSON.stringify({ state: "live", status: { app: "pi", state: "something-new" } }) }]],
111
+ ]), []) as typeof herdrAppCli.exec;
112
+ assert.equal((await getTerminal("t7", herdrAppCli.exec))?.status, "unknown");
113
+
114
+ herdrAppCli.exec = fakeCli(new Map([
115
+ ["hc get", [{ code: 3, stderr: JSON.stringify({ error: { kind: "not_found", message: "no terminal" } }) }]],
116
+ ]), []) as typeof herdrAppCli.exec;
117
+ assert.equal(await getTerminal("nope", herdrAppCli.exec), undefined);
118
+ });
119
+
120
+ // ---------------------------------------------------------------------------
121
+ // Prepare: topology
122
+ // ---------------------------------------------------------------------------
123
+
124
+ const SPACES_EMPTY = JSON.stringify({ spaces: [] });
125
+ function spacesWith(tabName: string, terminals: { pane: string; terminal: string }[], tabId = "tab-existing") {
126
+ return JSON.stringify({
127
+ spaces: [{
128
+ id: "sp1",
129
+ name: "ceulen",
130
+ machine: null,
131
+ tabs: [{ id: tabId, name: tabName, terminals }],
132
+ }],
133
+ });
134
+ }
135
+
136
+ test("prepare: no app window → clear failure, no orphan registry entry", async () => {
137
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-app-prep-"));
138
+ const calls: Call[] = [];
139
+ herdrAppCli.exec = fakeCli(new Map([
140
+ ["hc ls", [{ code: 0, stdout: JSON.stringify({ terminals: [] }) }]],
141
+ ["herdr-app ls", [{ code: 0, stdout: SPACES_EMPTY }]],
142
+ ]), calls) as typeof herdrAppCli.exec;
143
+ await assert.rejects(
144
+ () => prepareHerdrAppTask({ agentType: "scout", systemPrompt: "s", task: "t", cwd, timeoutMs: 60_000 }),
145
+ /no window\/space is open/,
146
+ );
147
+ assert.equal(getHerdrAppRegistry().length, 0);
148
+ });
149
+
150
+ test("prepare: creates one tab per agent type with the pi argv from the agent contract", async () => {
151
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-app-prep-"));
152
+ const calls: Call[] = [];
153
+ herdrAppCli.exec = fakeCli(new Map([
154
+ ["hc ls", [{ code: 0, stdout: JSON.stringify({ terminals: [] }) }]],
155
+ ["herdr-app ls", [{ code: 0, stdout: JSON.stringify({ spaces: [{ id: "sp1", name: "ceulen", machine: null, tabs: [] }] }) }]],
156
+ ["herdr-app do", [{ code: 0, stdout: JSON.stringify({ space: "sp1", tab: "tab-new", terminal: "t20" }) }]],
157
+ ]), calls) as typeof herdrAppCli.exec;
158
+ const handle = await prepareHerdrAppTask({
159
+ agentType: "scout",
160
+ systemPrompt: "you are scout",
161
+ task: "find things",
162
+ cwd,
163
+ model: "router/ds-flash",
164
+ thinking: "off",
165
+ tools: ["read", "grep"],
166
+ timeoutMs: 60_000,
167
+ });
168
+ assert.equal(handle.tabName, "scout");
169
+ assert.equal(handle.tabId, "tab-new");
170
+ assert.equal(handle.address, "t20");
171
+ assert.equal(handle.tabCreatedHere, true);
172
+ assert.ok(handle.resultFile.startsWith(join(cwd, ".pi", "herdr-app")));
173
+ // The dispatch is registered so the control tool can see it.
174
+ assert.equal(isDelegatedHerdrAppAgent("t20"), true);
175
+ assert.equal(findHerdrAppAgent(handle.name)?.address, "t20");
176
+ // tab.new carries the argv + no-focus (the window must not jump).
177
+ const tabNew = calls.find((c) => c.cmd === "herdr-app" && c.args[1] === "tab.new");
178
+ assert.ok(tabNew);
179
+ const payload = JSON.parse(tabNew!.args[2]!) as Record<string, unknown>;
180
+ assert.equal(payload.name, "scout");
181
+ assert.equal(payload.folder, cwd);
182
+ assert.equal(payload.focus, false);
183
+ const argv = payload.argv as string[];
184
+ // argv[0] must be the PROGRAM: the app launcher execs argv[0] and forwards
185
+ // the rest (unlike `herdr agent start --kind pi`, which supplies pi itself).
186
+ assert.equal(argv[0], "pi");
187
+ assert.ok(argv.includes("--append-system-prompt"));
188
+ assert.ok(argv.includes("--model"));
189
+ assert.ok(argv.includes("--tools"));
190
+ assert.ok(argv.includes("--session-id"));
191
+ assert.ok(argv.includes("--name"));
192
+ });
193
+
194
+ test("prepare: adopts an existing same-type tab (never close-eligible) and splits a pane", async () => {
195
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-app-prep-"));
196
+ const calls: Call[] = [];
197
+ herdrAppCli.exec = fakeCli(new Map([
198
+ ["hc ls", [{ code: 0, stdout: JSON.stringify({ terminals: [{ address: "t5", name: "scout-1" }] }) }]],
199
+ ["herdr-app ls", [{ code: 0, stdout: spacesWith("scout", [{ pane: "p31", terminal: "t5" }]) }]],
200
+ ["herdr-app do", [{ code: 0, stdout: JSON.stringify({ pane: "p32", terminal: "t21" }) }]],
201
+ ]), calls) as typeof herdrAppCli.exec;
202
+ const handle = await prepareHerdrAppTask({ agentType: "scout", systemPrompt: "s", task: "t", cwd, timeoutMs: 60_000 });
203
+ assert.equal(handle.tabId, "tab-existing");
204
+ assert.equal(handle.tabCreatedHere, false); // adopted → not ours to close
205
+ assert.equal(handle.address, "t21");
206
+ // allocateName avoided the live name scout-1.
207
+ assert.notEqual(handle.name, "scout-1");
208
+ const split = calls.find((c) => c.args[1] === "pane.split");
209
+ assert.ok(split);
210
+ const payload = JSON.parse(split!.args[2]!) as Record<string, unknown>;
211
+ assert.equal(payload.pane, "p31"); // anchored on the last existing pane
212
+ assert.ok(payload.direction === "right" || payload.direction === "down");
213
+ });
214
+
215
+ // ---------------------------------------------------------------------------
216
+ // Prompt + wait
217
+ // ---------------------------------------------------------------------------
218
+
219
+ test("promptAppAndWait: a settled turn maps to its reported status", async () => {
220
+ herdrAppCli.exec = fakeCli(new Map([
221
+ // Readiness gate: hc get must see a live idle pi before the send.
222
+ ["hc get", [readyPi(0)]],
223
+ ["hc send", [{
224
+ code: 0,
225
+ stdout: JSON.stringify({ started: true, status: "idle", turn: 0, wait: { ended: true, reason: "status", status: "done", turn: 1 } }),
226
+ }]],
227
+ ]), []) as typeof herdrAppCli.exec;
228
+ const out = await promptAppAndWait({ address: "t20", text: "hi", timeoutMs: 60_000, exec: herdrAppCli.exec });
229
+ assert.deepEqual(out, { state: "done", delivered: true });
230
+ });
231
+
232
+ test("promptAppAndWait: blocked skill refusal (exit 9) is not a delivery", async () => {
233
+ herdrAppCli.exec = fakeCli(new Map([
234
+ ["hc get", [readyPi(0)]],
235
+ ["hc send", [{ code: 9, stderr: JSON.stringify({ error: { kind: "blocked", message: "program is blocked" } }) }]],
236
+ ]), []) as typeof herdrAppCli.exec;
237
+ const out = await promptAppAndWait({ address: "t20", text: "hi", timeoutMs: 60_000, exec: herdrAppCli.exec });
238
+ assert.equal(out.delivered, false);
239
+ assert.equal(out.state, "blocked");
240
+ assert.match(out.error ?? "", /blocked/i);
241
+ });
242
+
243
+ test("promptAppAndWait: wait timeout keeps delivery=true and reports the timeout", async () => {
244
+ herdrAppCli.exec = fakeCli(new Map([
245
+ ["hc get", [readyPi(0), { code: 0, stdout: JSON.stringify({ state: "live", status: { app: "pi", state: "working" } }) }]],
246
+ ["hc send", [{ code: 0, stdout: JSON.stringify({ started: true, wait: { ended: false, reason: "timeout", status: "working" } }) }]],
247
+ ]), []) as typeof herdrAppCli.exec;
248
+ const out = await promptAppAndWait({ address: "t20", text: "hi", timeoutMs: 5_000, exec: herdrAppCli.exec });
249
+ assert.equal(out.delivered, true);
250
+ assert.equal(out.state, "working");
251
+ assert.match(out.error ?? "", /timeout after 5000ms/);
252
+ });
253
+
254
+ test("promptAppAndWait: a pre-aborted signal never touches the CLI", async () => {
255
+ const calls: Call[] = [];
256
+ herdrAppCli.exec = fakeCli(new Map(), calls) as typeof herdrAppCli.exec;
257
+ const controller = new AbortController();
258
+ controller.abort();
259
+ const out = await promptAppAndWait({ address: "t20", text: "hi", timeoutMs: 1_000, exec: herdrAppCli.exec, signal: controller.signal });
260
+ assert.equal(out.delivered, false);
261
+ assert.match(out.error ?? "", /aborted/);
262
+ assert.deepEqual(calls, []);
263
+ });
264
+
265
+ // ---------------------------------------------------------------------------
266
+ // Readiness gate + paste-never-submitted guard (live incident 2026-11-17)
267
+ // ---------------------------------------------------------------------------
268
+
269
+ test("promptAppAndWait: waits for an input-ready pi before sending", async () => {
270
+ const calls: Call[] = [];
271
+ herdrAppCli.exec = fakeCli(new Map([
272
+ // Booting: reports no status word yet, so it is NOT ready.
273
+ ["hc get", [
274
+ { code: 0, stdout: JSON.stringify({ state: "live", status: { app: "pi", state: "working" } }) },
275
+ readyPi(0),
276
+ { code: 0, stdout: JSON.stringify({ state: "live", status: { app: "pi", state: "done" } }) },
277
+ ]],
278
+ ["hc send", [{ code: 0, stdout: JSON.stringify({ started: true, wait: { ended: true, reason: "status", status: "done", turn: 1 } }) }]],
279
+ ]), calls) as typeof herdrAppCli.exec;
280
+ const out = await promptAppAndWait({ address: "t20", text: "hi", timeoutMs: 60_000, exec: herdrAppCli.exec });
281
+ assert.equal(out.delivered, true);
282
+ // Two readiness polls happened BEFORE the send.
283
+ const sendIdx = calls.findIndex((c) => c.args[0] === "send");
284
+ const getsBefore = calls.slice(0, sendIdx).filter((c) => c.args[0] === "get").length;
285
+ assert.equal(getsBefore, 2);
286
+ });
287
+
288
+ test("promptAppAndWait: a `done` agent is ready — follow-ups to a settled pane must not time out", async () => {
289
+ // pi reports `done` for a turn that finished unwatched; that composer takes
290
+ // input exactly like `idle`. Accepting only `idle` made every follow-up
291
+ // prompt wait 120s and fail (live 2026-11-17).
292
+ herdrAppCli.exec = fakeCli(new Map([
293
+ ["hc get", [
294
+ { code: 0, stdout: JSON.stringify({ address: "t20", state: "live", turn: 1, status: { app: "pi", state: "done" } }) },
295
+ { code: 0, stdout: JSON.stringify({ address: "t20", state: "live", turn: 2, status: { app: "pi", state: "done" } }) },
296
+ ]],
297
+ ["hc send", [{ code: 0, stdout: JSON.stringify({ started: true, wait: { ended: true, reason: "status", status: "done", turn: 2 } }) }]],
298
+ ]), []) as typeof herdrAppCli.exec;
299
+ const out = await promptAppAndWait({ address: "t20", text: "follow up", timeoutMs: 10_000, exec: herdrAppCli.exec });
300
+ assert.equal(out.delivered, true);
301
+ assert.equal(out.state, "done");
302
+ });
303
+
304
+ test("waitForReady rejects a working or blocked child (not ready)", async () => {
305
+ // Nothing but `working` replies: the gate must give up, never send.
306
+ const calls: Call[] = [];
307
+ herdrAppCli.exec = fakeCli(new Map([
308
+ ["hc get", Array.from({ length: 200 }, () => ({
309
+ code: 0,
310
+ stdout: JSON.stringify({ address: "t20", state: "live", turn: 0, status: { app: "pi", state: "working" } }),
311
+ }))],
312
+ ]), calls) as typeof herdrAppCli.exec;
313
+ const out = await promptAppAndWait({ address: "t20", text: "x", timeoutMs: 5_000, exec: herdrAppCli.exec });
314
+ assert.equal(out.delivered, false);
315
+ assert.equal(calls.some((c) => c.args[0] === "send"), false); // never sent
316
+ });
317
+
318
+ test("promptAppAndWait: a settled reply with an UNCHANGED turn is not a delivery", async () => {
319
+ herdrAppCli.exec = fakeCli(new Map([
320
+ ["hc get", [readyPi(3), { code: 0, stdout: JSON.stringify({ state: "live", status: { app: "pi", state: "idle" } }) }]],
321
+ // Pasted but never submitted: the child never worked, turn stays put.
322
+ ["hc send", [{ code: 0, stdout: JSON.stringify({ started: false, wait: { ended: true, reason: "status", status: "idle", turn: 3 } }) }]],
323
+ ]), []) as typeof herdrAppCli.exec;
324
+ const out = await promptAppAndWait({ address: "t20", text: "hi", timeoutMs: 60_000, exec: herdrAppCli.exec });
325
+ assert.equal(out.delivered, false);
326
+ // Either guard may fire (started:false precedes the turn check) — both mean
327
+ // "the paste never became work".
328
+ assert.match(out.error ?? "", /did not start working|never submitted/);
329
+ });
330
+
331
+ test("collectAppResult: a pane holding only the task echo is NOT a reply", async () => {
332
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-app-echo-"));
333
+ const handle = handleWith(cwd);
334
+ // Real shape from the failed live dispatch: boot chrome + the echoed task.
335
+ const pane = [
336
+ "▀▀█ v1.5.2",
337
+ " █▀ █ escape interrupt · ctrl+c/ctrl+d clear/exit · / commands · ! bash · ctrl+o more",
338
+ "Pi can explain its own features and look up its docs. Ask it how to use or extend Pi.",
339
+ "[Context]",
340
+ " .pi/herdr-app/worker-1.system.md",
341
+ "esc interrupt · ctrl+c/ctrl+d clear/exit · / commands · ! bash · ctrl+o more",
342
+ "π > ocg/deepseek-v4.1-flash > repo",
343
+ `Write exactly WORKER-PROBE-OK to the report file, then reply.`,
344
+ "---",
345
+ "Delivery: when your task is complete, write your full final report as Markdown to `/r.md` " +
346
+ "(create parent directories if needed), then reply with a one-line summary only. " +
347
+ "If follow-up feedback arrives after delivery (e.g. an advisor review), apply it and update the report file to the corrected version.",
348
+ ].join("\n");
349
+ herdrAppCli.exec = fakeCli(new Map([["hc read", [{ code: 0, stdout: pane }]]]), []) as typeof herdrAppCli.exec;
350
+ const out = await collectAppResult({ handle, exec: herdrAppCli.exec });
351
+ assert.deepEqual(out, { output: "", source: "none" });
352
+ });
353
+
354
+ test("collectAppResult: a real inline reply still comes through (hc-wrapped)", async () => {
355
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-app-reply-"));
356
+ const handle = { ...handleWith(cwd), readOnly: true, task: "Reply with exactly SCOUT-INLINE-OK and nothing else." };
357
+ // Verbatim shape of a live read-only dispatch (alternate-screen capture):
358
+ // boot chrome, the hc-wrapped task, then the child's inline answer.
359
+ const pane = [
360
+ "▀▀█ v1.5.2",
361
+ " █▀ █ escape interrupt · ctrl+c/ctrl+d clear/exit · / commands · ! bash · ctrl+o more",
362
+ " Press ctrl+o to show full startup help and loaded resources.",
363
+ " Pi can explain its own features and look up its docs. Ask it how to use or extend Pi.",
364
+ "[Skills]",
365
+ " a2a, cron, deploy-checks, find-skills, herdr, munin, ponytail, review, web",
366
+ "[Extensions]",
367
+ " ceulen, herdr-agent-state.ts",
368
+ "[a2a] gateway channel open: remote@172.30.55.22:9920 as mbp-sao-9916 (firewall-safe receive)",
369
+ ' <hc from="t2">Reply with exactly SCOUT-INLINE-OK and nothing else.',
370
+ " ────────────────────────────────────────────────────────────────────────────────",
371
+ " Delivery: this session has read-only tools — do NOT write any files. Reply with your full final report as your final",
372
+ " message.</hc>",
373
+ " SCOUT-INLINE-OK",
374
+ "↑74 ↓7 R35K CH99.8% · (router) R:90%/54M W:92%/6D M:41%/11D",
375
+ " π > ⬢ ocg/deepseek-v4.1-flash · max > 📁 /Volumes/Dev/agents/ceulen > ⑂ main *2 ?3 ─4%─────┃1M─",
376
+ ].join("\n");
377
+ herdrAppCli.exec = fakeCli(new Map([["hc read", [{ code: 0, stdout: pane }]]]), []) as typeof herdrAppCli.exec;
378
+ const out = await collectAppResult({ handle, exec: herdrAppCli.exec });
379
+ assert.equal(out.source, "pane");
380
+ assert.match(out.output, /SCOUT-INLINE-OK/);
381
+ });
382
+
383
+ // ---------------------------------------------------------------------------
384
+ // Collection + cancel
385
+ // ---------------------------------------------------------------------------
386
+
387
+ function handleWith(cwd: string): HerdrAppHandle {
388
+ return {
389
+ tabName: "scout", tabId: "tab-1", address: "t20", paneId: "p1", name: "scout-1",
390
+ agentType: "scout", task: "t", resultFile: join(cwd, "report.md"),
391
+ advisorMarker: join(cwd, "m.json"), model: "router/x", timeoutMs: 60_000, tabCreatedHere: true,
392
+ };
393
+ }
394
+
395
+ test("collectAppResult: the report file wins over the pane", async () => {
396
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-app-collect-"));
397
+ const handle = handleWith(cwd);
398
+ writeFileSync(handle.resultFile, "REPORT BODY");
399
+ const calls: Call[] = [];
400
+ herdrAppCli.exec = fakeCli(new Map(), calls) as typeof herdrAppCli.exec;
401
+ const out = await collectAppResult({ handle, exec: herdrAppCli.exec });
402
+ assert.deepEqual(out, { output: "REPORT BODY", source: "file" });
403
+ assert.equal(calls.length, 0); // no pane read when the contract file exists
404
+ });
405
+
406
+ test("collectAppResult: falls back to hc read and marks it as a pane capture", async () => {
407
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-app-collect-"));
408
+ const handle = { ...handleWith(cwd), readOnly: true, task: "Report the pane." };
409
+ herdrAppCli.exec = fakeCli(new Map([
410
+ ["hc read", [{
411
+ code: 0,
412
+ stdout: [
413
+ "▀▀█ v1.5.2",
414
+ "[Skills]",
415
+ " review, web",
416
+ "Report the pane.",
417
+ "---",
418
+ "Delivery: this session has read-only tools — do NOT write any files. Reply with your full final report as your final message.",
419
+ "PANE CAPTURE REPLY",
420
+ "π > model > repo",
421
+ "╰─",
422
+ ].join("\n"),
423
+ }]],
424
+ ]), []) as typeof herdrAppCli.exec;
425
+ const out = await collectAppResult({ handle, exec: herdrAppCli.exec });
426
+ assert.equal(out.output, "PANE CAPTURE REPLY");
427
+ assert.equal(out.source, "pane");
428
+ });
429
+
430
+ test("cancelAppAgent: escalates to hc kill only while still working", async () => {
431
+ const escalateCalls: Call[] = [];
432
+ herdrAppCli.exec = fakeCli(new Map([
433
+ ["hc interrupt", [{ code: 0, stdout: JSON.stringify({ status: "working" }) }]],
434
+ ["hc get", [{ code: 0, stdout: JSON.stringify({ state: "live", status: { state: "working" } }) }]],
435
+ ["hc kill", [{ code: 0, stdout: JSON.stringify({ address: "t20" }) }]],
436
+ ]), escalateCalls) as typeof herdrAppCli.exec;
437
+ await cancelAppAgent("t20", herdrAppCli.exec);
438
+ assert.ok(escalateCalls.some((c) => c.args[0] === "kill"));
439
+
440
+ const calmCalls: Call[] = [];
441
+ herdrAppCli.exec = fakeCli(new Map([
442
+ ["hc interrupt", [{ code: 0, stdout: JSON.stringify({ status: "idle" }) }]],
443
+ ]), calmCalls) as typeof herdrAppCli.exec;
444
+ await cancelAppAgent("t20", herdrAppCli.exec);
445
+ assert.equal(calmCalls.some((c) => c.args[0] === "kill"), false);
446
+ });
447
+
448
+ // ---------------------------------------------------------------------------
449
+ // Execute: full flow, abort, timeout
450
+ // ---------------------------------------------------------------------------
451
+
452
+ test("executeHerdrAppTask: collects the report and stamps the app pane in the usage line", async () => {
453
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-app-exec-"));
454
+ const handle = handleWith(cwd);
455
+ writeFileSync(handle.resultFile, "FINAL REPORT");
456
+ herdrAppCli.exec = fakeCli(new Map([
457
+ ["hc get", [readyPi(0), { code: 0, stdout: JSON.stringify({ state: "live", status: { app: "pi", state: "done" } }) }]],
458
+ ["hc send", [{ code: 0, stdout: JSON.stringify({ started: true, wait: { ended: true, reason: "status", status: "done", turn: 1 } }) }]],
459
+ ]), []) as typeof herdrAppCli.exec;
460
+ const result = await executeHerdrAppTask(handle, { exec: herdrAppCli.exec });
461
+ assert.equal(result.status, "success");
462
+ assert.match(result.model ?? "", /herdr pane:scout-1/);
463
+ // Report-file source → NOT best-effort (the boolean is always present).
464
+ assert.equal(result.bestEffort, false);
465
+ const text = (result.messages[0] as any)?.content?.[0]?.text;
466
+ assert.equal(text, "FINAL REPORT");
467
+ });
468
+
469
+ test("executeHerdrAppTask: a timeout interrupts the pane and says so", async () => {
470
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-app-exec-"));
471
+ const handle = handleWith(cwd);
472
+ const calls: Call[] = [];
473
+ herdrAppCli.exec = fakeCli(new Map([
474
+ ["hc get", [readyPi(0), { code: 0, stdout: JSON.stringify({ state: "live", status: { app: "pi", state: "working" } }) }]],
475
+ ["hc send", [{ code: 0, stdout: JSON.stringify({ started: true, wait: { ended: false, reason: "timeout", status: "working" } }) }]],
476
+ ["hc interrupt", [{ code: 0, stdout: JSON.stringify({ status: "idle" }) }]],
477
+ ]), calls) as typeof herdrAppCli.exec;
478
+ const result = await executeHerdrAppTask(handle, { exec: herdrAppCli.exec });
479
+ assert.equal(result.status, "timeout");
480
+ assert.match(result.errorMessage ?? "", /may still complete its current write/);
481
+ assert.ok(calls.some((c) => c.args[0] === "interrupt"));
482
+ });
483
+
484
+ test("executeHerdrAppTask: an aborted parent maps to status aborted, never success", async () => {
485
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-app-exec-"));
486
+ const handle = handleWith(cwd);
487
+ writingReport(handle.resultFile);
488
+ herdrAppCli.exec = fakeCli(new Map([
489
+ ["hc get", [readyPi(0), { code: 0, stdout: JSON.stringify({ state: "live", status: { app: "pi", state: "done" } }) }]],
490
+ ["hc send", [{ code: 0, stdout: JSON.stringify({ started: true, wait: { ended: true, reason: "status", status: "done", turn: 1 } }) }]],
491
+ ]), []) as typeof herdrAppCli.exec;
492
+ const controller = new AbortController();
493
+ // Abort after the prompt resolves: the result must still be stamped aborted.
494
+ const promise = executeHerdrAppTask(handle, { exec: herdrAppCli.exec, signal: controller.signal });
495
+ controller.abort();
496
+ const result = await promise;
497
+ assert.equal(result.status, "aborted");
498
+ assert.equal(result.stopReason, "aborted");
499
+ });
500
+
501
+ function writingReport(file: string): void {
502
+ writeFileSync(file, "REPORT");
503
+ }
504
+
505
+ test("executeHerdrAppTask: a pane-sourced answer is flagged bestEffort as DATA, not as a text prefix", async () => {
506
+ // Live 2026-11-17: the old `[best-effort pane capture]` TEXT prefix travelled
507
+ // into `{previous}` chain substitution, and the next child read the marker
508
+ // as a prompt-injection signal and derailed. Provenance must be data.
509
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-app-be-"));
510
+ const handle = { ...handleWith(cwd), readOnly: true, task: "Reply with exactly BE-OK" };
511
+ herdrAppCli.exec = fakeCli(new Map([
512
+ ["hc get", [readyPi(0), { code: 0, stdout: JSON.stringify({ state: "live", status: { app: "pi", state: "done" } }) }]],
513
+ ["hc send", [{ code: 0, stdout: JSON.stringify({ started: true, wait: { ended: true, reason: "status", status: "done", turn: 1 } }) }]],
514
+ ["hc read", [{
515
+ code: 0,
516
+ stdout: [
517
+ "Reply with exactly BE-OK",
518
+ "---",
519
+ "Delivery: this session has read-only tools — do NOT write any files. Reply with your full final report as your final message.",
520
+ "BE-OK",
521
+ "π > model > repo",
522
+ ].join("\n"),
523
+ }]],
524
+ ]), []) as typeof herdrAppCli.exec;
525
+ const result = await executeHerdrAppTask(handle, { exec: herdrAppCli.exec });
526
+ assert.equal(result.status, "success");
527
+ assert.equal(result.bestEffort, true);
528
+ const text = (result.messages[0] as any)?.content?.[0]?.text ?? "";
529
+ assert.equal(text, "BE-OK"); // clean payload for {previous}
530
+ assert.doesNotMatch(text, /best-effort/i); // no marker in the text
531
+ });
532
+
533
+ // ---------------------------------------------------------------------------
534
+ // Delivery contract + registry
535
+ // ---------------------------------------------------------------------------
536
+
537
+ test("wrapAppTaskPrompt: writable children get the report-file contract; read-only reply inline", () => {
538
+ assert.match(wrapAppTaskPrompt("do it", "/tmp/r.md"), /write your full final report as Markdown to `\/tmp\/r\.md`/);
539
+ assert.match(wrapAppTaskPrompt("do it", "/tmp/r.md", true), /do NOT write any files/);
540
+ assert.match(wrapAppTaskPrompt("do it", "/tmp/r.md", true), /Reply with your full final report/);
541
+ });
542
+
543
+ test("registry: two dispatches register, lookup by name/address, forget by tab drops both", async () => {
544
+ const cwd = mkdtempSync(join(tmpdir(), "ceulen-app-reg-"));
545
+ herdrAppCli.exec = fakeCli(new Map([
546
+ ["hc ls", [
547
+ { code: 0, stdout: JSON.stringify({ terminals: [] }) },
548
+ { code: 0, stdout: JSON.stringify({ terminals: [{ address: "t30", name: "scout-1" }] }) },
549
+ ]],
550
+ // First prepare: empty space (create). Second: the created tab is listed
551
+ // (adopt + split) — exactly what a same-type follow-up sees.
552
+ ["herdr-app ls", [
553
+ { code: 0, stdout: JSON.stringify({ spaces: [{ id: "sp1", name: "c", machine: null, tabs: [] }] }) },
554
+ { code: 0, stdout: spacesWith("scout", [{ pane: "p1", terminal: "t30" }], "tab-1") },
555
+ ]],
556
+ ["herdr-app do", [
557
+ { code: 0, stdout: JSON.stringify({ zone: 1, tab: "tab-1", terminal: "t30" }) },
558
+ { code: 0, stdout: JSON.stringify({ pane: "p2", terminal: "t31" }) },
559
+ ]],
560
+ ]), []) as typeof herdrAppCli.exec;
561
+
562
+ const first = await prepareHerdrAppTask({ agentType: "scout", systemPrompt: "s", task: "one", cwd, timeoutMs: 60_000 });
563
+ const second = await prepareHerdrAppTask({ agentType: "scout", systemPrompt: "s", task: "two", cwd, timeoutMs: 60_000 });
564
+ // Both siblings share one tab but stay individually addressable.
565
+ assert.equal(getHerdrAppRegistry().length, 2);
566
+ assert.notEqual(first.name, second.name);
567
+ assert.equal(findHerdrAppAgent(first.name)?.address, "t30");
568
+ assert.equal(findHerdrAppAgent("t31")?.name, second.name); // address lookup
569
+ forgetHerdrAppTab("tab-1"); // by tab ID drops every sibling in it
570
+ assert.equal(getHerdrAppRegistry().length, 0);
571
+ assert.equal(isDelegatedHerdrAppAgent("t30"), false);
572
+ });
@@ -0,0 +1,81 @@
1
+ // Expand-hint rendering: the "(… to expand)" hint follows the HOST's
2
+ // configured keybinding (pi 1.5.x `KeybindingHints.keyText`) and falls back to
3
+ // the literal "Ctrl+O" when no render context supplies one (pi <1.5, widget and
4
+ // thread renderers). A null theme renders plain text, so assertions read the
5
+ // raw strings — same convention as widget.test.ts.
6
+
7
+ import assert from "node:assert/strict";
8
+ import { test } from "node:test";
9
+ import { expandKeyLabel, renderSingleResult } from "../lib/render.ts";
10
+ import type { SubAgentResult } from "../lib/runner.ts";
11
+ import type { Text } from "@earendil-works/pi-tui";
12
+
13
+ const plainTheme = {
14
+ fg: (_c: string, text: string) => text,
15
+ bold: (text: string) => text,
16
+ };
17
+
18
+ function result(overrides: Partial<SubAgentResult> = {}): SubAgentResult {
19
+ return {
20
+ agent: "scout",
21
+ task: "Recon the registry module",
22
+ exitCode: 0,
23
+ messages: [],
24
+ stderr: "",
25
+ usage: { input: 1, output: 2, cacheRead: 0, cacheWrite: 0, cost: 0.01, contextTokens: 3, turns: 1 },
26
+ ...overrides,
27
+ };
28
+ }
29
+
30
+ const renderText = (component: unknown): string => (component as Text).render(100).join("\n");
31
+
32
+ test("expandKeyLabel: host keybinding wins, literal is the fallback", () => {
33
+ assert.equal(expandKeyLabel({ keyText: () => "ctrl+o" }), "ctrl+o");
34
+ assert.equal(expandKeyLabel({ keyText: () => "" }), "Ctrl+O", "empty key list falls back");
35
+ assert.equal(expandKeyLabel({ keyText: () => { throw new Error("boom"); } }), "Ctrl+O", "throwing context falls back");
36
+ assert.equal(expandKeyLabel(undefined), "Ctrl+O", "no context (widget/thread renderers, older pi)");
37
+ });
38
+
39
+ test("renderSingleResult: collapsed hint uses the configured expand key", () => {
40
+ const r = result({
41
+ messages: [{ role: "assistant", content: [{ type: "text", text: "## Heading only" }] } as never],
42
+ });
43
+ // Host-configured key (a rebind) replaces the hardcoded literal.
44
+ const rebinded = renderText(renderSingleResult(r, false, plainTheme, undefined, "ctrl+shift+e"));
45
+ assert.match(rebinded, /ctrl\+shift\+e to expand/);
46
+ assert.doesNotMatch(rebinded, /Ctrl\+O/);
47
+ // Default parameter keeps today's behavior for callers without a context.
48
+ const fallback = renderText(renderSingleResult(r, false, plainTheme));
49
+ assert.match(fallback, /Ctrl\+O to expand/);
50
+ });
51
+
52
+ // ── Chain report: per-step results ─────────────────────────────────────────
53
+ // `{previous}` only forwards one step, so intermediate findings must be carried
54
+ // by the result text itself; the final answer stays first for callers.
55
+
56
+ test("formatChainReport: final output first, then every step with its own report", async () => {
57
+ const { formatChainReport } = await import("../lib/render.ts");
58
+ const results: SubAgentResult[] = [
59
+ { ...result({ agent: "scout" }), messages: [{ role: "assistant", content: [{ type: "text", text: "FINDINGS-1" }], stopReason: "stop" }] as never },
60
+ { ...result({ agent: "planner" }), messages: [{ role: "assistant", content: [{ type: "text", text: "FINDINGS-2" }], stopReason: "stop" }] as never },
61
+ ];
62
+ const text = formatChainReport("FINDINGS-2", results);
63
+ // Final answer leads.
64
+ assert.ok(text.startsWith("FINDINGS-2"));
65
+ // Both steps present, labeled with index/agent/status.
66
+ assert.match(text, /## Chain steps \(2\)/);
67
+ assert.match(text, /### Step 1\/2 — scout: completed\n\nFINDINGS-1/);
68
+ assert.match(text, /### Step 2\/2 — planner: completed\n\nFINDINGS-2/);
69
+ });
70
+
71
+ test("formatChainReport: failure and pane-capture provenance are both surfaced", async () => {
72
+ const { formatChainReport } = await import("../lib/render.ts");
73
+ const results: SubAgentResult[] = [
74
+ { ...result({ agent: "scout" }), status: "success", bestEffort: true, messages: [{ role: "assistant", content: [{ type: "text", text: "SCRAPED" }], stopReason: "stop" }] as never },
75
+ { ...result({ agent: "worker" }), exitCode: 1, status: "error", stopReason: "timeout", errorMessage: "timed out", messages: [] },
76
+ ];
77
+ const text = formatChainReport("(no output)", results);
78
+ assert.match(text, /Step 1\/2 — scout: completed ⚠ best-effort pane capture/);
79
+ assert.match(text, /Step 2\/2 — worker: failed \(timeout\)/);
80
+ assert.match(text, /timed out/);
81
+ });