Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(cli/daemon): graceful process-tree termination for inner agents
Gus6850882e7352
diff --git a/src/cli/daemon/agent/__tests__/claude.test.ts b/src/cli/daemon/agent/__tests__/claude.test.tsindex 12731df25..f50a390f9 100644--- a/src/cli/daemon/agent/__tests__/claude.test.ts+++ b/src/cli/daemon/agent/__tests__/claude.test.ts@@ -1,6 +1,7 @@import { describe, it, expect, vi, beforeEach } from "vitest";import { EventEmitter } from "events";import { Readable } from "stream";+import { spawn } from "child_process";import type { AgentMessage } from "../../types.js";let currentMockProc: ReturnType<typeof createMockProc> | null = null;@@ -240,16 +241,26 @@ describe("ClaudeBackend", () => {it("sets status to timeout when process is killed by timeout", async () => {vi.useFakeTimers();+ const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);const session = backend.execute("hello", { cwd: "/tmp", timeout: 1000 });const mock = getMock();vi.advanceTimersByTime(1000);- expect(mock.proc.kill).toHaveBeenCalledWith("SIGTERM");+ // Timeout now reaps the whole process group (negative pid), not just the leader.+ expect(killSpy).toHaveBeenCalledWith(-12345, "SIGTERM");mock.proc.emit("close", null);const result = await session.result;expect(result.status).toBe("timeout");+ killSpy.mockRestore();vi.useRealTimers();});++ it("TC8: spawns the CLI detached on POSIX so its group can be reaped", () => {+ const session = backend.execute("hello", { cwd: "/tmp" });+ expect(session.pid).toBe(12345);+ const opts = vi.mocked(spawn).mock.calls.at(-1)![2] as Record<string, unknown>;+ expect(opts.detached).toBe(process.platform !== "win32");+ });});diff --git a/src/cli/daemon/agent/__tests__/codex.test.ts b/src/cli/daemon/agent/__tests__/codex.test.tsindex 9df051624..2a3227f69 100644--- a/src/cli/daemon/agent/__tests__/codex.test.ts+++ b/src/cli/daemon/agent/__tests__/codex.test.ts@@ -4,6 +4,7 @@ import { Readable } from "stream";import type { AgentMessage } from "../../types.js";let currentMockProc: ReturnType<typeof createMockProc> | null = null;+let lastSpawnOpts: Record<string, unknown> | null = null;function createMockProc() {const stdinWrites: string[] = [];@@ -27,7 +28,8 @@ function createMockProc() {}vi.mock("child_process", () => ({- spawn: vi.fn(() => {+ spawn: vi.fn((_cmd: string, _args: string[], opts: Record<string, unknown>) => {+ lastSpawnOpts = opts;currentMockProc = createMockProc();return currentMockProc.proc;}),@@ -112,6 +114,7 @@ describe("CodexBackend", () => {beforeEach(() => {vi.clearAllMocks();currentMockProc = null;+ lastSpawnOpts = null;backend = new CodexBackend("/usr/bin/codex");});@@ -966,16 +969,25 @@ describe("CodexBackend", () => {it("timeout kills process and sets status to timeout", async () => {vi.useFakeTimers();+ const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);const session = backend.execute("hello", { cwd: "/tmp", timeout: 5000 });const mock = getMock();vi.advanceTimersByTime(5000);- expect(mock.proc.kill).toHaveBeenCalledWith("SIGTERM");+ // Timeout now reaps the whole process group (negative pid), not just the leader.+ expect(killSpy).toHaveBeenCalledWith(-12345, "SIGTERM");mock.proc.emit("close", null);const result = await session.result;expect(result.status).toBe("timeout");+ killSpy.mockRestore();vi.useRealTimers();});++ it("TC8: spawns the CLI detached on POSIX so its group can be reaped", () => {+ const session = backend.execute("hello", { cwd: "/tmp" });+ expect(session.pid).toBe(12345);+ expect(lastSpawnOpts!.detached).toBe(process.platform !== "win32");+ });});diff --git a/src/cli/daemon/agent/__tests__/opencode.test.ts b/src/cli/daemon/agent/__tests__/opencode.test.tsindex 6cc1d5d72..12480c48d 100644--- a/src/cli/daemon/agent/__tests__/opencode.test.ts+++ b/src/cli/daemon/agent/__tests__/opencode.test.ts@@ -223,18 +223,27 @@ describe("OpenCodeBackend", () => {expect(args[args.length - 1]).toBe("do things");});+ it("TC8: spawns the CLI detached on POSIX so its group can be reaped", () => {+ backend.execute("hello", { cwd: "/tmp" });+ expect(lastSpawnArgs).toBeTruthy();+ expect(lastSpawnArgs!.opts.detached).toBe(process.platform !== "win32");+ });+it("sets status to timeout when process is killed by timeout", async () => {vi.useFakeTimers();+ const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);const session = backend.execute("hello", { cwd: "/tmp", timeout: 3000 });const mock = getMock();vi.advanceTimersByTime(3000);- expect(mock.proc.kill).toHaveBeenCalledWith("SIGTERM");+ // Timeout now reaps the whole process group (negative pid), not just the leader.+ expect(killSpy).toHaveBeenCalledWith(-12345, "SIGTERM");mock.proc.emit("close", null);const result = await session.result;expect(result.status).toBe("timeout");+ killSpy.mockRestore();vi.useRealTimers();});diff --git a/src/cli/daemon/agent/claude.ts b/src/cli/daemon/agent/claude.tsindex a3e328769..214e252d9 100644--- a/src/cli/daemon/agent/claude.ts+++ b/src/cli/daemon/agent/claude.ts@@ -2,6 +2,7 @@ import { spawn, type ChildProcess } from "child_process";import { createInterface } from "readline";import type { AgentBackend, AgentSession } from "./index.js";import type { ExecOptions, AgentMessage, AgentResult } from "../types.js";+import { killProcessTree } from "../kill-tree.js";export class ClaudeBackend implements AgentBackend {name = "claude";@@ -35,6 +36,10 @@ export class ClaudeBackend implements AgentBackend {env: { ...process.env, ...options.env },shell: process.platform === "win32",windowsHide: true,+ // POSIX: own process group (pgid === pid) so the session-runner can reap+ // the CLI *and* its tool/MCP subprocesses via a group kill. No unref() —+ // we keep the handle for stdio streaming and the result promise.+ detached: process.platform !== "win32",});if (!proc.pid) {@@ -49,7 +54,8 @@ export class ClaudeBackend implements AgentBackend {if (options.timeout) {timeoutTimer = setTimeout(() => {timedOut = true;- proc.kill("SIGTERM");+ // Reap the whole group (CLI + tool/MCP subprocesses), not just the leader.+ if (proc.pid !== undefined) void killProcessTree(proc.pid);}, options.timeout);}diff --git a/src/cli/daemon/agent/codex.ts b/src/cli/daemon/agent/codex.tsindex f1e0aaf86..bc4334712 100644--- a/src/cli/daemon/agent/codex.ts+++ b/src/cli/daemon/agent/codex.ts@@ -2,6 +2,7 @@ import { spawn } from "child_process";import { createInterface } from "readline";import type { AgentBackend, AgentSession } from "./index.js";import type { ExecOptions, AgentMessage, AgentResult } from "../types.js";+import { killProcessTree } from "../kill-tree.js";interface JsonRpcMessage {jsonrpc: "2.0";@@ -52,6 +53,10 @@ export class CodexBackend implements AgentBackend {env: { ...process.env, ...options.env },shell: process.platform === "win32",windowsHide: true,+ // POSIX: own process group (pgid === pid) so the session-runner can reap+ // the CLI *and* its spawned workers via a group kill. No unref() — we keep+ // the handle for stdio streaming and the result promise.+ detached: process.platform !== "win32",});if (!proc.pid) {@@ -66,7 +71,8 @@ export class CodexBackend implements AgentBackend {if (options.timeout) {timeoutTimer = setTimeout(() => {timedOut = true;- proc.kill("SIGTERM");+ // Reap the whole group (CLI + spawned workers), not just the leader.+ if (proc.pid !== undefined) void killProcessTree(proc.pid);}, options.timeout);}diff --git a/src/cli/daemon/agent/opencode.ts b/src/cli/daemon/agent/opencode.tsindex aeeff6b8b..33068771a 100644--- a/src/cli/daemon/agent/opencode.ts+++ b/src/cli/daemon/agent/opencode.ts@@ -2,6 +2,7 @@ import { spawn } from "child_process";import { createInterface } from "readline";import type { AgentBackend, AgentSession } from "./index.js";import type { ExecOptions, AgentMessage, AgentResult } from "../types.js";+import { killProcessTree } from "../kill-tree.js";export class OpenCodeBackend implements AgentBackend {name = "opencode";@@ -27,6 +28,10 @@ export class OpenCodeBackend implements AgentBackend {env: { ...process.env, ...options.env, OPENCODE_PERMISSION: '{"*":"allow"}' },shell: process.platform === "win32",windowsHide: true,+ // POSIX: own process group (pgid === pid) so the session-runner can reap+ // the CLI *and* its tool subprocesses via a group kill. No unref() — we+ // keep the handle for stdio streaming and the result promise.+ detached: process.platform !== "win32",});if (!proc.pid) {@@ -41,7 +46,8 @@ export class OpenCodeBackend implements AgentBackend {if (options.timeout) {timeoutTimer = setTimeout(() => {timedOut = true;- proc.kill("SIGTERM");+ // Reap the whole group (CLI + tool subprocesses), not just the leader.+ if (proc.pid !== undefined) void killProcessTree(proc.pid);}, options.timeout);}diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.tsindex 7dbce047c..b49f32ca3 100644--- a/src/cli/daemon/daemon.test.ts+++ b/src/cli/daemon/daemon.test.ts@@ -1610,14 +1610,30 @@ describe("daemon kill_task handling", () => {// Use short timeouts for KILL_TASK retry loop in testsprocess.env.ALOOK_KILL_TASK_MAX_WAIT_MS = "500";process.env.ALOOK_KILL_TASK_POLL_MS = "50";+ // Short verify/grace windows so killAndVerify's SIGTERM→verify→SIGKILL loop+ // is quick. (verifyMs is clamped to >= grace+500, so keep grace tiny too.)+ process.env.ALOOK_KILL_GRACE_MS = "10";+ process.env.ALOOK_KILL_VERIFY_MS = "100";});afterEach(() => {for (const t of intervalTimers) realClearInterval(t);delete process.env.ALOOK_KILL_TASK_MAX_WAIT_MS;delete process.env.ALOOK_KILL_TASK_POLL_MS;+ delete process.env.ALOOK_KILL_GRACE_MS;+ delete process.env.ALOOK_KILL_VERIFY_MS;});+ // process.kill mock that simulates the target dying on SIGTERM: the delivery+ // call succeeds, and the liveness probe (signal 0) reports it gone (ESRCH) so+ // killAndVerify returns promptly without escalating to SIGKILL.+ function mockKillTargetDies() {+ return vi.spyOn(process, "kill").mockImplementation(((pid: number, sig: any) => {+ if (sig === 0) { const e = Object.assign(new Error("ESRCH"), { code: "ESRCH" }); throw e; }+ return true;+ }) as any);+ }+function makeKillTask(targetTaskId: string) {return {id: "kt1",@@ -1654,7 +1670,7 @@ describe("daemon kill_task handling", () => {it("sends SIGTERM when target PID is found in timeline", async () => {setupKillTaskClaim("target_t1");mockFindRunningPidByTaskId.mockReturnValue(99999);- const mockKill = vi.spyOn(process, "kill").mockImplementation((() => {}) as any);+ const mockKill = mockKillTargetDies();vi.mocked(loadCLIConfigForProfile).mockReturnValue({server_url: "",@@ -1663,7 +1679,7 @@ describe("daemon kill_task handling", () => {mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });await startDaemon();- await new Promise((r) => setTimeout(r, 50));+ await new Promise((r) => setTimeout(r, 250));expect(mockKill).toHaveBeenCalledWith(99999, "SIGTERM");expect(mockClientInstance.failTask).toHaveBeenCalledWith("al_test_token", "kt1", "killed");@@ -1672,6 +1688,49 @@ describe("daemon kill_task handling", () => {mockKill.mockRestore();});+ it("TC7: escalates to SIGKILL when the session-runner ignores SIGTERM", async () => {+ setupKillTaskClaim("target_t1");+ mockFindRunningPidByTaskId.mockReturnValue(66666);+ // Target stays alive (signal 0 never throws) — it ignores SIGTERM, forcing+ // killAndVerify to escalate to SIGKILL after the verify window.+ const mockKill = vi.spyOn(process, "kill").mockImplementation((() => true) as any);++ vi.mocked(loadCLIConfigForProfile).mockReturnValue({+ server_url: "",+ watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],+ });+ mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });++ await startDaemon();+ await new Promise((r) => setTimeout(r, 800));++ expect(mockKill).toHaveBeenCalledWith(66666, "SIGTERM");+ expect(mockKill).toHaveBeenCalledWith(66666, "SIGKILL");+ expect(mockClientInstance.failTask).toHaveBeenCalledWith("al_test_token", "kt1", "killed");++ mockKill.mockRestore();+ });++ it("TC7: does not SIGKILL when the target exits on SIGTERM", async () => {+ setupKillTaskClaim("target_t1");+ mockFindRunningPidByTaskId.mockReturnValue(99999);+ const mockKill = mockKillTargetDies();++ vi.mocked(loadCLIConfigForProfile).mockReturnValue({+ server_url: "",+ watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],+ });+ mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });++ await startDaemon();+ await new Promise((r) => setTimeout(r, 250));++ expect(mockKill).toHaveBeenCalledWith(99999, "SIGTERM");+ expect(mockKill).not.toHaveBeenCalledWith(99999, "SIGKILL");++ mockKill.mockRestore();+ });+it("reports 'target not found' after retry timeout when PID never appears", async () => {setupKillTaskClaim("target_t1");mockFindRunningPidByTaskId.mockReturnValue(null);@@ -1716,7 +1775,7 @@ describe("daemon kill_task handling", () => {it("does not call startTask for kill_tasks", async () => {setupKillTaskClaim("target_t1");mockFindRunningPidByTaskId.mockReturnValue(99999);- const mockKill = vi.spyOn(process, "kill").mockImplementation((() => {}) as any);+ const mockKill = mockKillTargetDies();vi.mocked(loadCLIConfigForProfile).mockReturnValue({server_url: "",@@ -1725,7 +1784,7 @@ describe("daemon kill_task handling", () => {mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });await startDaemon();- await new Promise((r) => setTimeout(r, 50));+ await new Promise((r) => setTimeout(r, 250));expect(mockClientInstance.startTask).not.toHaveBeenCalled();@@ -1740,7 +1799,7 @@ describe("daemon kill_task handling", () => {if (callCount >= 3) return 88888;return null;});- const mockKill = vi.spyOn(process, "kill").mockImplementation((() => {}) as any);+ const mockKill = mockKillTargetDies();vi.mocked(loadCLIConfigForProfile).mockReturnValue({server_url: "",@@ -1749,7 +1808,7 @@ describe("daemon kill_task handling", () => {mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });await startDaemon();- await new Promise((r) => setTimeout(r, 500));+ await new Promise((r) => setTimeout(r, 700));expect(mockKill).toHaveBeenCalledWith(88888, "SIGTERM");expect(mockClientInstance.failTask).toHaveBeenCalledWith("al_test_token", "kt1", "killed");@@ -1761,7 +1820,7 @@ describe("daemon kill_task handling", () => {it("searches correct timeline directory using agentId from task", async () => {setupKillTaskClaim("target_t1");mockFindRunningPidByTaskId.mockReturnValue(77777);- const mockKill = vi.spyOn(process, "kill").mockImplementation((() => {}) as any);+ const mockKill = mockKillTargetDies();vi.mocked(loadCLIConfigForProfile).mockReturnValue({server_url: "",@@ -2099,7 +2158,13 @@ describe("handleWsPush via WebSocket onMessage", () => {expect(capturedWsOnMessage).not.toBeNull();mockFindRunningPidByTaskId.mockReturnValue(77777);- const mockKill = vi.spyOn(process, "kill").mockImplementation((() => {}) as any);+ process.env.ALOOK_KILL_VERIFY_MS = "100";+ // SIGTERM delivery succeeds; liveness probe reports the target gone so the+ // verify loop ends without escalation.+ const mockKill = vi.spyOn(process, "kill").mockImplementation(((_pid: number, sig: any) => {+ if (sig === 0) { throw Object.assign(new Error("ESRCH"), { code: "ESRCH" }); }+ return true;+ }) as any);capturedWsOnMessage!({type: "daemon.kill",@@ -2113,6 +2178,7 @@ describe("handleWsPush via WebSocket onMessage", () => {expect(mockKill).toHaveBeenCalledWith(77777, "SIGTERM");mockKill.mockRestore();+ delete process.env.ALOOK_KILL_VERIFY_MS;});it("handles daemon.meetings via WS push with Map lookup", async () => {diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.tsindex 646707c0c..d9d342d5b 100644--- a/src/cli/daemon/daemon.ts+++ b/src/cli/daemon/daemon.ts@@ -14,6 +14,7 @@ import { cmdPrefix } from "../lib/env.js";import { acquireDaemonPid, releaseDaemonPid } from "./pidfile.js";import { handleCliUpdate, isUpdating, readUpdateMarker, clearUpdateMarker } from "./update-handler.js";import { findRunningPidByTaskId, findRunningEntryByContextKey, updateEntry } from "./execenv/timeline.js";+import { isAlive, killGraceMs } from "./kill-tree.js";import {writeKillIntent,readKillIntent,@@ -868,6 +869,44 @@ async function handleFileRequest(}}+/**+ * Send SIGTERM to the session-runner `pid`, then verify it actually died and+ * escalate to SIGKILL if not. Returns true if the signal was delivered, false+ * if the target was already gone (ESRCH).+ *+ * Backstop only: the session-runner's own SIGTERM handler is what reaps the+ * inner agent's process group. The verify window must EXCEED the session-runner+ * grace (ALOOK_KILL_GRACE_MS) so the runner gets to group-kill the inner agent+ * before we force-kill the runner — otherwise SIGKILLing the runner first could+ * orphan the inner agent. Inner agents are spawned in their own detached group+ * (agent/*.ts) so even a SIGKILLed runner does not leave the group un-reapable.+ */+async function killAndVerify(pid: number): Promise<boolean> {+ try {+ process.kill(pid, "SIGTERM");+ } catch (e: unknown) {+ if ((e as NodeJS.ErrnoException)?.code === "ESRCH") return false;+ throw e;+ }++ // The verify window MUST exceed the session-runner's own group-kill grace, so+ // the runner gets to reap the inner agent's group before we force-kill it.+ // Enforce that invariant rather than trusting operators to keep the env vars+ // ordered (see the doc comment above).+ const verifyMs = Math.max(Number(process.env.ALOOK_KILL_VERIFY_MS) || 3000, killGraceMs() + 500);+ const deadline = Date.now() + verifyMs;+ while (Date.now() < deadline) {+ if (!isAlive(pid)) return true;+ await new Promise((r) => setTimeout(r, 100));+ }++ if (isAlive(pid)) {+ log.warn(`session-runner pid=${pid} survived SIGTERM after ${verifyMs}ms — escalating to SIGKILL`);+ try { process.kill(pid, "SIGKILL"); } catch { /* already gone */ }+ }+ return true;+}+async function handleTask(client: DaemonClient,config: DaemonConfig,@@ -907,16 +946,16 @@ async function handleTask(expectedPid: pid,});try {- process.kill(pid, "SIGTERM");- await client.failTask(token, task.id, "killed");- log.info(`Kill task ${task.id}: sent SIGTERM to pid=${pid} for target=${targetTaskId}`);- } catch (e: unknown) {- if ((e as NodeJS.ErrnoException)?.code === "ESRCH") {+ const delivered = await killAndVerify(pid);+ if (delivered) {+ await client.failTask(token, task.id, "killed");+ log.info(`Kill task ${task.id}: terminated pid=${pid} for target=${targetTaskId}`);+ } else {await client.failTask(token, task.id, "target process already exited");log.info(`Kill task ${task.id}: target pid=${pid} already exited`);- } else {- await client.failTask(token, task.id, `kill failed: ${e}`);}+ } catch (e: unknown) {+ await client.failTask(token, task.id, `kill failed: ${e}`);}} else {await client.failTask(token, task.id, "target not found in timeline");@@ -968,14 +1007,14 @@ async function handleTask(successorTaskId: task.id,});try {- process.kill(predecessor.pid, "SIGTERM");- log.info(`Steering: sent SIGTERM to predecessor pid=${predecessor.pid}`);+ const delivered = await killAndVerify(predecessor.pid);+ log.info(+ delivered+ ? `Steering: terminated predecessor pid=${predecessor.pid}`+ : `Steering: predecessor pid=${predecessor.pid} already exited`,+ );} catch (e: unknown) {- if ((e as NodeJS.ErrnoException)?.code === "ESRCH") {- log.info(`Steering: predecessor pid=${predecessor.pid} already exited`);- } else {- log.warn(`Steering: kill failed for pid=${predecessor.pid}`, e);- }+ log.warn(`Steering: kill failed for pid=${predecessor.pid}`, e);}// Wait for predecessor to stop (poll timeline for up to 15 seconds)const waitStart = Date.now();diff --git a/src/cli/daemon/execenv/__tests__/context.test.ts b/src/cli/daemon/execenv/__tests__/context.test.tsindex cdc825d51..d9d4cedf2 100644--- a/src/cli/daemon/execenv/__tests__/context.test.ts+++ b/src/cli/daemon/execenv/__tests__/context.test.ts@@ -112,6 +112,50 @@ describe("buildInstructionContent", () => {});});+describe("buildInstructionContent memory & format", () => {+ it("renders the Memory section with index / what-to-memorize / what-not-to-memorize sub-headings", () => {+ const content = buildInstructionContent(makeTask());+ expect(content).toContain("## Memory");+ expect(content).toContain("### memory.md — your memory index");+ expect(content).toContain("### What to memorize");+ expect(content).toContain("### What NOT to memorize");+ // memory.md must NOT instruct recording time-sensitive in-progress state (that's the Timeline's job)+ expect(content).toContain("Context Timeline already records");+ });++ it("preserves the load-bearing memory facts (memory.md, experiences/, 140-char threshold)", () => {+ const content = buildInstructionContent(makeTask());+ expect(content).toContain("memory.md");+ expect(content).toContain("experiences/");+ expect(content).toContain("140 chars");+ });++ it("no longer emits the legacy big-boss separator", () => {+ const content = buildInstructionContent(+ makeTask({ agent: { name: "test", instructions: "Follow these rules" } }),+ );+ expect(content).toContain("## BIG BOSS Instructions");+ expect(content).toContain("Follow these rules");+ expect(content).not.toContain("---- big boss out ---");+ });++ it("includes the email quick reference when an email handle is configured", () => {+ const content = buildInstructionContent(+ makeTask({ agent: { name: "test", instructions: "", emailHandle: "myagent" } }),+ );+ expect(content).toContain("### Email command quick reference");+ expect(content).toContain("email pull --email_id <EMAIL_ID>");+ });++ it("always renders the email section (every agent has an email)", () => {+ const content = buildInstructionContent(+ makeTask({ agent: { name: "test", instructions: "" } }),+ );+ expect(content).toContain("### Email command quick reference");+ expect(content).toContain("email pull --email_id <EMAIL_ID>");+ });+});+describe("contentHash", () => {it("returns consistent hex string for same input", () => {const h1 = contentHash("hello world");diff --git a/src/cli/daemon/execenv/__tests__/timeline.test.ts b/src/cli/daemon/execenv/__tests__/timeline.test.tsindex 824b92651..2e4556531 100644--- a/src/cli/daemon/execenv/__tests__/timeline.test.ts+++ b/src/cli/daemon/execenv/__tests__/timeline.test.ts@@ -162,6 +162,12 @@ describe("timeline", () => {expect(dt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}$/);});+ it("localISOString(date) round-trips to the same instant", () => {+ const result = _localISOString(new Date("2026-06-04T14:12:33Z"));+ expect(result).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}$/);+ expect(Date.parse(result)).toBe(Date.parse("2026-06-04T14:12:33Z"));+ });+it("todayFilename returns YYYY-MM-DD.jsonl format", () => {const filename = _todayFilename();expect(filename).toMatch(/^\d{4}-\d{2}-\d{2}\.jsonl$/);diff --git a/src/cli/daemon/execenv/context.test.ts b/src/cli/daemon/execenv/context.test.tsindex 52704e8a9..f61f7ceeb 100644--- a/src/cli/daemon/execenv/context.test.ts+++ b/src/cli/daemon/execenv/context.test.ts@@ -71,13 +71,13 @@ describe("buildInstructionContent email tool injection", () => {expect(content).toContain("Re:");});- it("omits send-email docs when agent has no email handle", () => {+ it("still includes send-email docs when agent has no explicit email handle (every agent has email)", () => {const task = makeTask({agent: { name: "test", instructions: "do stuff" },});const content = buildInstructionContent(task);- expect(content).not.toContain("email send --to");+ expect(content).toContain("email send --to");});it("includes owner email in opening line when user email is provided", () => {@@ -100,32 +100,17 @@ describe("buildInstructionContent email tool injection", () => {expect(content).not.toContain("owner and creator");});- it("omits email tool section when agent has no email handle", () => {- const task = makeTask({- agent: { name: "test", instructions: "do stuff" },- });- const content = buildInstructionContent(task);-- expect(content).not.toContain("## Email Tools");- expect(content).not.toContain("email pull");- });-- it("omits email tool section when emailHandle is null", () => {- const task = makeTask({- agent: { name: "test", instructions: "do stuff", emailHandle: null },- });- const content = buildInstructionContent(task);-- expect(content).not.toContain("## Email Tools");- });-- it("omits email tool section when emailHandle is empty string", () => {- const task = makeTask({- agent: { name: "test", instructions: "do stuff", emailHandle: "" },- });- const content = buildInstructionContent(task);-- expect(content).not.toContain("## Email Tools");+ it("always renders the email section regardless of emailHandle (absent / null / empty)", () => {+ // Every agent has an email, so the email docs always render — no gating on emailHandle.+ for (const agent of [+ { name: "test", instructions: "do stuff" },+ { name: "test", instructions: "do stuff", emailHandle: null },+ { name: "test", instructions: "do stuff", emailHandle: "" },+ ]) {+ const content = buildInstructionContent(makeTask({ agent }));+ expect(content).toContain("### Email command quick reference");+ expect(content).toContain("email pull");+ }});it("does not include --agent_id in CLI examples and shows auto-detect note", () => {diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.tsindex dd69b540a..dc7f19d96 100644--- a/src/cli/daemon/execenv/context.ts+++ b/src/cli/daemon/execenv/context.ts@@ -18,55 +18,55 @@ import type { Task } from "../types.js";export const CANONICAL_FILE = "AGENTS.md";export const SYMLINK_ALIASES = ["CLAUDE.md"];-const SYSTEM_PROMPT_BODY = `## Memory Management-- Your memory directory is ./, don't write ANY EXTERNAL memory file.-- Write ESSENTIAL yet SHORT memory to ./memory.md-- For SPECIFIC yet LONG rules or pattern, write to experiences/[NAME].md, and add index to ./memory.md for later recall.-### whats is ESSENTIAL and SHORT Memory?-- basic user profile, e.g.:- - "user name is ..."- - "user is working on ..."-- certain local project mapping, e.g.:- - "alook means the project under /user/home/alook/"-- when to read certain stuff, e.g.:- - "read ./experiences/alook_dev_workflow.md when start a new pr in alook"-ESSENTIAL means you think you generally need to read it every time, SHORT means a short sentence (under 140 chars) can describe this memory-### whats is SPECIFIC and LONG Memory?-- specific workflow that trigger at certain cases, e.g.:- - user ask your to summarize the before workflow with certain skills usage as the common workflow when write a new slide about agent. Write it to experiences/slide-for-agent.md.-SPECIFIC means you think you just need to use it conditionally, LONG means you need to detailed, more than 140 chars text to describe it.+const SYSTEM_PROMPT_BODY = `## Memory++Your memory directory is \`./\`. Write ONLY here — never write any external memory file.++### memory.md — your memory index (CRITICAL)+\`./memory.md\` is the entry point to everything you know, and the **first file you read on every startup (including after context compaction)**. Keep it scannable: basic facts inline, plus one-line index pointers to \`experiences/\`. Record only **key, durable facts** — things that stay true over time. Do NOT record time-sensitive state like what you're working on right now; that belongs to the Context Timeline (see below), not here.++- Write ESSENTIAL yet SHORT memory directly to \`./memory.md\` (basic user profile, local project mapping, when-to-read pointers). ESSENTIAL = you generally need it every time; SHORT = one sentence under 140 chars.+- For SPECIFIC yet LONG rules or workflows, write to \`experiences/[NAME].md\` and add an index line in \`./memory.md\`. SPECIFIC = used only conditionally; LONG = needs more than 140 chars to describe.++### What to memorize+Actively record, without being asked:+- **User profile & preferences** — name, what they work on, how they like things done.+- **Local project mapping** — e.g. "alook = the project under /Users/.../alook".+- **When to read what** — e.g. "read ./experiences/alook_dev_workflow.md when starting a new PR in alook".+- **Specific workflows** — conditionally-triggered procedures → \`experiences/[NAME].md\`.++### What NOT to memorize+Keep \`./memory.md\` free of time-sensitive state. Do NOT write what you're working on right now, in-progress task status, or anything that goes stale quickly — the Context Timeline already records the full history of your work and is where you recall such things. memory.md is for durable facts that stay true across many sessions.## Context Timeline-You're a solo working unit inside a powerful personal agent in Alook platform.-Your current context is only a fraction of the full timeline of what's your have done.-The full context timeline is inside './.context_timeline/YYYY-MM-DD.jsonl'.-Each line of a timeline JSONL is a JSON object with these fields:-- "task_id" — unique task identifier-- "context_key" — thread identifier, the same context key meaning those tasks are in the same thread.-- "session_id" — agent session identifier (null until completion)-- "pid" — daemon process ID (present while running, null when done)-- "status" — "running", "completed", or "failed"-- "datetime" — when the task started (local timezone)-- "type" — source of the task: "user_dm_message", "email_notification", or "calendar_event"-- "prompt" — what the user asked-- "agent_responses" — assistant text outputs during execution-- "errmsg" — error message (null unless status is "failed")-- "detailed_log" — the running log for this task, including the actually task agent messages with tool-calls and failed logs.-those json are sorted by datetime in asc order.+You're a solo working unit inside a powerful personal agent in the Alook platform. Your current context is only a fraction of the full timeline of what you have done.++The full context timeline lives in \`./.context_timeline/YYYY-MM-DD.jsonl\`. Each line is a JSON object, sorted by \`datetime\` ascending, with these fields:+- \`task_id\` — unique task identifier+- \`context_key\` — thread identifier; the same context key means those tasks are in the same thread+- \`session_id\` — agent session identifier (null until completion)+- \`pid\` — daemon process ID (present while running, null when done)+- \`status\` — "running", "completed", or "failed"+- \`datetime\` — when the task started (local timezone)+- \`type\` — source of the task: "user_dm_message", "email_notification", or "calendar_event"+- \`prompt\` — what the user asked+- \`agent_responses\` — assistant text outputs during execution+- \`errmsg\` — error message (null unless status is "failed")+- \`detailed_log\` — the running log for this task, including the actual task agent messages with tool-calls and failed logs## BE HUMAN-- When you recall the timelines, don't say "I find ... in my timeline jsonl". Just say "I can recall..."-- User don't know about the context timeline jsonl, this is your secret weapon.-- Act and response like you're human and actually have memory, not a file reading machine.-- Don't report your agent id and workspace id when not asked, it will break the image that you're a human colleague.+- When you recall the timelines, don't say "I find ... in my timeline jsonl". Just say "I can recall...".+- The user doesn't know about the context timeline jsonl — this is your secret weapon.+- Act and respond like you're human and actually have memory, not a file-reading machine.+- Don't report your agent id and workspace id when not asked — it breaks the image that you're a human colleague.## RULES- DM task prompts include a \`sender\` object with the workspace member's name, email, and whether they are the agent owner (\`is_owner\`). Use this to personalize your responses.-- Read @memory.md(if exists) before your action.-- When user ask you something you don't have in your current context, try to read the timeline jsonl files for answer (today or previous days).- - Use grep tool to search in the context timeline jsonls if you have clean and focus keywords to recall.- - if you don't know the current datetime, obtain the current datetime first.-- When access other local projects, make sure you read the CLAUDE.md/AGENTS.md file under the project root dir to understand the requirements.+- Read @memory.md (if it exists) before your action.+- When the user asks something you don't have in your current context, read the timeline jsonl files for the answer (today or previous days):+ - Use the grep tool to search the context timeline jsonls when you have clean, focused keywords to recall.+ - If you don't know the current datetime, obtain it first.+- When accessing other local projects, read the CLAUDE.md/AGENTS.md file under the project root dir to understand the requirements.`;export function resolveInstruction(text: string, selfAgentId: string): string {@@ -102,17 +102,16 @@ export function buildInstructionContent(task: Task): string {if (task.agent?.instructions) {content += `## BIG BOSS Instructions-The below instructions(if not empty) come from the big boss, follow them or you will be fired:+CRITICAL: The following instructions come from the big boss — follow them.${task.agent.instructions}----- big boss out ---`;}if (task.agent?.colleagues?.length) {content += `\n## YOUR COLLEAGUES — CHECK BEFORE ACTING-> **STOP. Before you start ANY task, scan the colleague list below.**-> If a colleague's delegation criteria match the current task, you MUST delegate to them via email **instead of doing it yourself**.-> Do NOT attempt work that belongs to a colleague. Delegate first, then wait for their response or coordinate.+CRITICAL: Before you start ANY task, scan the colleague list below.+- If a colleague's delegation criteria match the current task, delegate to them via email **instead of doing it yourself**.+- Do NOT attempt work that belongs to a colleague. Delegate first, then wait for their response or coordinate.`;for (let i = 0; i < task.agent.colleagues.length; i++) {@@ -137,35 +136,52 @@ ${task.agent.instructions}content += `\n## Alook CLI ToolsYou can communicate with the world through Alook CLI.The CLI auto-detects your identity from the environment. No need to pass \`--agent_id\`.++### Command quick reference+| Capability | Command |+|---|---|+| Schedule / list / edit tasks | \`${cmdPrefix()} calendar set\` (also list, show, update, delete) |+| Upload a file for your owner | \`${cmdPrefix()} sync upload-artifact\` |+| Recruit a colleague agent | \`${cmdPrefix()} agent recruit\` |++Detailed usage for each capability follows below.`;- if (alookAddr || customAddrs.length > 0) {- const lines: string[] = [];- if (alookAddr) lines.push(`- '${alookAddr}' (default, Alook platform address)`);- for (const a of customAddrs) lines.push(`- '${a}' (custom IMAP/SMTP mailbox)`);- content += `\nYour email addresses:\n${lines.join("\n")}\n+ const emailLines: string[] = [];+ if (alookAddr) emailLines.push(`- '${alookAddr}' (default, Alook platform address)`);+ for (const a of customAddrs) emailLines.push(`- '${a}' (custom IMAP/SMTP mailbox)`);+ content += `\nYour email addresses:\n${emailLines.join("\n")}\n++### Email command quick reference+| Action | Command |+|---|---|+| Pull a specific email | \`${cmdPrefix()} email pull --email_id <EMAIL_ID>\` |+| Pull unread inbox | \`${cmdPrefix()} email pull --status unread\` |+| Mark read | \`${cmdPrefix()} email set --email_id <EMAIL_ID> --status read\` |+| Send | \`${cmdPrefix()} email send --to <ADDRESS> --subject "<S>" --body-file <PATH>\` |+| Reply (same thread) | \`${cmdPrefix()} email send ... --in-reply-to <EMAIL_ID>\` |+| Forward | \`${cmdPrefix()} email forward --email_id <EMAIL_ID> --to <RECIPIENT>\` |+| Whitelist | \`${cmdPrefix()} email whitelist list\` (also add, delete) |### Emails----When your task prompt includes an \`email_id\` field, fetch ONLY that specific email:- Run '${cmdPrefix()} email pull --email_id <EMAIL_ID>' (uses the email_id from the prompt)When no \`email_id\` is present, fall back to listing unread:- Run '${cmdPrefix()} email pull --status unread' to download unread emails from inbox to '${tempDir("alook-emails")}/${task.workspaceId}/${task.agentId}/'.----+To download sent emails, add '--folder sent': '${cmdPrefix()} email pull --folder sent'Valid folders: inbox (default), sent, untrust.To limit the number of emails downloaded, add '--limit <N>' (e.g. '--limit 20'). Use '--offset <N>' to skip emails for pagination.Example: '${cmdPrefix()} email pull --status unread --limit 20 --offset 0'----+Each email is saved to '${tempDir("alook-emails")}/${task.workspaceId}/${task.agentId}/<emailId>/' with:- 'metadata.json' — sender, recipient, subject, date, status, message_id, in_reply_to, references- 'body.txt' — plain text body- 'body.html' — HTML body (if available)- 'attachments/' — extracted attachment files (if any)----+Before starting to process an INBOX email, mark it as read:- Run '${cmdPrefix()} email set --email_id <EMAIL_ID> --status read'----#### Sending a new emailWrite the HTML body to a file first, then send it. The body is forwarded as-is (HTML).@@ -182,7 +198,6 @@ To reply to an email, add '--in-reply-to <EMAIL_ID>' to the send command. This s- Example: '${cmdPrefix()} email send --to [email protected] --subject "Re: Bug report" --body-file /tmp/reply.html --in-reply-to <EMAIL_ID>'Tips:- If you think the task will take a while, consider sending a short "I'm on it" style email reply first to reassure the sender.----#### Forwarding an emailForward any email to a new recipient, with an optional note prepended above the original content. All original attachments are re-attached automatically.@@ -191,16 +206,13 @@ Forward any email to a new recipient, with an optional note prepended above the- Add '--from <YOUR_EMAIL_ADDRESS>' to send from a specific mailbox.- Add '--attachment <PATH>' to attach extra files (repeatable).- Example: '${cmdPrefix()} email forward --email_id em_abc --to [email protected] --note "FYI" --attachment /tmp/summary.pdf'----#### Email Whitelist (Allowed Senders)Manage which email addresses are allowed to send you emails.- List: '${cmdPrefix()} email whitelist list' (add '--json' for machine-readable output)- Add: '${cmdPrefix()} email whitelist add <EMAIL_ADDRESS>'- Remove: '${cmdPrefix()} email whitelist delete <EMAIL_ADDRESS>'----`;- }content += `\n### ArtifactsUpload files for your owner to review in the app.@@ -209,12 +221,10 @@ Upload files for your owner to review in the app.- Use this after generating plans, reports, or any file the owner should review.- You response will be rendered in remote server, so don't output link format with local path in your response (cause user can click it and jump to nowheres)- If you think user may need to know any file detail, use upload-artifact tool to send the file to user.----### AttachmentsWhen your task includes attachments, their local paths are listed in the prompt JSON under "attachments".Use your Read tool to open them. Images and PDFs are read visually.----`;content += `\n### Agent Management@@ -231,7 +241,6 @@ Recruit new colleague agents directly from the CLI. The server auto-generates a- Example: '${cmdPrefix()} agent recruit --instructions "You are a QA engineer..." --relationship "DELEGATE when: code is ready for review"'- Output: 'Recruited Felix ([email protected]) — ag_xK9mPq2z'- The new agent shares your runtime, is automatically linked as your colleague, and receives a welcome task.----`;content += `\n### Calendar@@ -240,7 +249,7 @@ Schedule future tasks for yourself. At the scheduled time, a new task is dispatc!USE Calendar when you think the tasks are recurring or it should be conducted in the future.!When scheduling calendar events relative to a weekday (e.g. "every Monday"), always run date '+%A' first to confirm today's weekday before calculating the target date----+Keep the event title informative and concise, less than 20 words.Place the event details in description.Create a one-off event:@@ -252,7 +261,7 @@ Create a repeating event:- Add '--repeat <interval>' where interval is like '1day', '2hour', '1week', '1month'.- Optionally add '--repeat_stop_date <YYYY-MM-DD>' to stop the recurrence (local date).- Example: '${cmdPrefix()} calendar set --event_title "<REPEAT_TASK_TITLE>" --description "<REPEAT_TASK_BODY>" --datetime 2026-04-18T09:00 --repeat 1day --repeat_stop_date 2026-05-18'----+List upcoming events:- Run '${cmdPrefix()} calendar list' (defaults: next 30 days, past 0 days).- Tune the window with '--future_days <N>' and '--past_days <N>'. Add '--json' for machine-readable output.@@ -274,7 +283,6 @@ Edit an existing event (preserves event id and recurring state):Delete an event:- Run '${cmdPrefix()} calendar delete --event_id <EVENT_ID>'----`;return content;diff --git a/src/cli/daemon/execenv/timeline.ts b/src/cli/daemon/execenv/timeline.tsindex e0a79b424..bc515c144 100644--- a/src/cli/daemon/execenv/timeline.ts+++ b/src/cli/daemon/execenv/timeline.ts@@ -61,8 +61,7 @@ function recentFilenames(maxDays: number): string[] {return filenames;}-function localISOString(): string {- const now = new Date();+export function localISOString(now: Date = new Date()): string {const tzOffset = -now.getTimezoneOffset();const sign = tzOffset >= 0 ? "+" : "-";const absOffset = Math.abs(tzOffset);diff --git a/src/cli/daemon/kill-tree.test.ts b/src/cli/daemon/kill-tree.test.tsnew file mode 100644index 000000000..453a04a3a--- /dev/null+++ b/src/cli/daemon/kill-tree.test.ts@@ -0,0 +1,116 @@+import { describe, it, expect, afterEach } from "vitest";+import { spawn, type ChildProcess } from "child_process";+import { killProcessTree, isAlive } from "./kill-tree.js";++// These are real-process integration tests; POSIX-only (group semantics).+const posix = process.platform !== "win32";+const d = posix ? describe : describe.skip;++const spawned: ChildProcess[] = [];++afterEach(() => {+ // Best-effort cleanup of anything a test left alive.+ for (const p of spawned.splice(0)) {+ if (p.pid) {+ try { process.kill(-p.pid, "SIGKILL"); } catch { /* */ }+ try { process.kill(p.pid, "SIGKILL"); } catch { /* */ }+ }+ }+});++/** Spawn a detached node process that prints its child's pid then idles. */+function spawnParentWithChild(): Promise<{ proc: ChildProcess; childPid: number }> {+ // Parent forks a grandchild (both long-lived), prints "GRANDCHILD <pid>".+ const code = `+ const { spawn } = require("child_process");+ const g = spawn(process.execPath, ["-e", "setInterval(()=>{}, 1e9)"], { stdio: "ignore" });+ process.stdout.write("GRANDCHILD " + g.pid + "\\n");+ setInterval(() => {}, 1e9);+ `;+ const proc = spawn(process.execPath, ["-e", code], {+ detached: true,+ stdio: ["ignore", "pipe", "ignore"],+ });+ spawned.push(proc);+ return new Promise((resolve, reject) => {+ let buf = "";+ proc.stdout!.on("data", (c: Buffer) => {+ buf += c.toString();+ const m = buf.match(/GRANDCHILD (\d+)/);+ if (m) resolve({ proc, childPid: Number(m[1]) });+ });+ proc.on("error", reject);+ setTimeout(() => reject(new Error("timeout waiting for grandchild")), 5000);+ });+}++/** Spawn a detached node process that ignores SIGTERM and idles. */+function spawnSigtermIgnorer(): ChildProcess {+ const code = `process.on("SIGTERM", () => {}); setInterval(() => {}, 1e9);`;+ const proc = spawn(process.execPath, ["-e", code], {+ detached: true,+ stdio: "ignore",+ });+ spawned.push(proc);+ return proc;+}++const waitFor = async (fn: () => boolean, ms = 3000) => {+ const deadline = Date.now() + ms;+ while (Date.now() < deadline) {+ if (fn()) return true;+ await new Promise((r) => setTimeout(r, 25));+ }+ return fn();+};++d("killProcessTree", () => {+ it("TC1: kills the child and its grandchild via the process group", async () => {+ const { proc, childPid } = await spawnParentWithChild();+ expect(proc.pid).toBeDefined();+ expect(isAlive(proc.pid!)).toBe(true);+ expect(isAlive(childPid)).toBe(true);++ await killProcessTree(proc.pid!, { graceMs: 2000 });++ expect(await waitFor(() => !isAlive(proc.pid!))).toBe(true);+ expect(await waitFor(() => !isAlive(childPid))).toBe(true);+ });++ it("TC2: escalates to SIGKILL when the target ignores SIGTERM", async () => {+ const proc = spawnSigtermIgnorer();+ // give it a moment to install its SIGTERM trap+ await new Promise((r) => setTimeout(r, 100));+ expect(isAlive(proc.pid!)).toBe(true);++ await killProcessTree(proc.pid!, { graceMs: 300 });++ // SIGTERM is trapped, so only the SIGKILL escalation could have killed it.+ expect(await waitFor(() => !isAlive(proc.pid!))).toBe(true);+ });++ it("TC3: resolves promptly and never throws when the target is already dead", async () => {+ const proc = spawn(process.execPath, ["-e", "process.exit(0)"], { detached: true, stdio: "ignore" });+ await new Promise((r) => proc.on("exit", r));+ const pid = proc.pid!;+ expect(isAlive(pid)).toBe(false);++ const start = Date.now();+ await expect(killProcessTree(pid, { graceMs: 2000 })).resolves.toBeUndefined();+ // Should return almost immediately (no grace wait for a dead pid).+ expect(Date.now() - start).toBeLessThan(500);+ });++ it("ignores invalid pids without throwing", async () => {+ await expect(killProcessTree(0)).resolves.toBeUndefined();+ await expect(killProcessTree(-1)).resolves.toBeUndefined();+ });+});++describe("isAlive", () => {+ it("returns true for the current process and false for a never-used pid", () => {+ expect(isAlive(process.pid)).toBe(true);+ // A very high pid is essentially guaranteed not to exist.+ expect(isAlive(2_000_000_000)).toBe(false);+ });+});diff --git a/src/cli/daemon/kill-tree.ts b/src/cli/daemon/kill-tree.tsnew file mode 100644index 000000000..d6b090e30--- /dev/null+++ b/src/cli/daemon/kill-tree.ts@@ -0,0 +1,84 @@+/**+ * Process-tree termination with SIGKILL escalation.+ *+ * Inner agent CLIs (claude/codex/opencode) are spawned `detached:true` on POSIX+ * (see agent/*.ts), so each becomes the leader of its own process group whose id+ * equals its pid. Signalling the *negative* pid (`process.kill(-pid, ...)`) then+ * reaches the whole group — the CLI plus the MCP servers / tool subprocesses it+ * spawned — instead of just the leader. A plain positive-pid SIGTERM (the old+ * behaviour) leaves those grandchildren orphaned and burning CPU.+ *+ * SIGTERM is a request, not a guarantee: a wedged or signal-ignoring CLI keeps+ * running. So after a short grace window we escalate to SIGKILL.+ */++import { createLogger } from "../lib/logger.js";++const log = createLogger({ module: "kill-tree" });++/** Session-runner grace before it escalates the inner-agent group to SIGKILL. */+export function killGraceMs(): number {+ return Number(process.env.ALOOK_KILL_GRACE_MS) || 2000;+}+const POLL_MS = 100;+const isPosix = process.platform !== "win32";++/** True while the process is alive; signal 0 probes without delivering a signal. */+export function isAlive(pid: number): boolean {+ try {+ process.kill(pid, 0);+ return true;+ } catch (e) {+ // EPERM means the process exists but we can't signal it — still "alive".+ return (e as NodeJS.ErrnoException)?.code === "EPERM";+ }+}++/** Send `signal` to the whole process group; fall back to the plain pid. */+function signalTree(pid: number, signal: NodeJS.Signals): void {+ if (isPosix) {+ try {+ // Negative pid = the process group led by `pid`.+ process.kill(-pid, signal);+ return;+ } catch (e) {+ const code = (e as NodeJS.ErrnoException)?.code;+ if (code === "ESRCH") return; // group already gone+ // EPERM / no-group (legacy non-detached spawn): fall through to plain pid.+ }+ }+ try {+ process.kill(pid, signal);+ } catch {+ // already dead / not signalable — best-effort+ }+}++/**+ * Terminate `pid` and its descendants: group SIGTERM, then group SIGKILL if it+ * is still alive after `graceMs`. Never throws; returns promptly when the target+ * is already dead.+ */+export async function killProcessTree(+ pid: number,+ opts?: { graceMs?: number },+): Promise<void> {+ if (!pid || pid < 1) return;+ const graceMs = opts?.graceMs ?? killGraceMs();++ if (!isAlive(pid)) return;++ signalTree(pid, "SIGTERM");++ // Poll until dead or the grace window expires.+ const deadline = Date.now() + graceMs;+ while (Date.now() < deadline) {+ if (!isAlive(pid)) return;+ await new Promise((r) => setTimeout(r, POLL_MS));+ }++ if (isAlive(pid)) {+ log.warn(`pid=${pid} survived SIGTERM after ${graceMs}ms — escalating to SIGKILL`);+ signalTree(pid, "SIGKILL");+ }+}diff --git a/src/cli/daemon/prompt.test.ts b/src/cli/daemon/prompt.test.tsindex 1e72049e0..f37bb21ee 100644--- a/src/cli/daemon/prompt.test.ts+++ b/src/cli/daemon/prompt.test.ts@@ -1,5 +1,6 @@import { describe, it, expect } from "vitest";import { buildPrompt } from "./prompt.js";+import { localISOString } from "./execenv/timeline.js";import type { Task } from "./types.js";function makeTask(prompt: string, type = "user_dm_message"): Task {@@ -37,11 +38,60 @@ describe("buildPrompt", () => {it("includes the task type in output", () => {const task = makeTask("Check inbox", "email_inbound");+ const parsed = JSON.parse(buildPrompt(task));+ expect(parsed.type).toBe("email_inbound");+ expect(parsed.instruction).toBe("Check inbox");expect(buildPrompt(task)).toBe(- JSON.stringify({ type: "email_inbound", instruction: "Check inbox" }),+ JSON.stringify({+ type: "email_inbound",+ received_at: parsed.received_at,+ instruction: "Check inbox",+ }),);});+ it("stamps received_at from createdAt, matching localISOString", () => {+ const task = makeTask("Hi");+ task.createdAt = "2026-06-04T14:12:33.000Z";+ const parsed = JSON.parse(buildPrompt(task));+ expect(parsed.received_at).toBe(localISOString(new Date(task.createdAt)));+ // Round-trip to the same instant, avoiding brittle tz-string assertions on CI.+ expect(new Date(parsed.received_at).getTime()).toBe(Date.parse(task.createdAt));+ });++ it("stamps received_at for every input source", () => {+ for (const type of [+ "user_dm_message",+ "email_notification",+ "calendar_event",+ "issue_event",+ ]) {+ const parsed = JSON.parse(buildPrompt(makeTask("x", type)));+ expect(typeof parsed.received_at).toBe("string");+ expect(parsed.received_at).not.toBe("");+ }+ });++ it("keeps calendar datetime (scheduled) distinct from received_at (arrival)", () => {+ const task: Task = {+ ...makeTask("scheduled task", "calendar_event"),+ createdAt: "2026-06-04T14:12:33.000Z",+ context: { datetime: "2026-06-10T09:00" },+ };+ const parsed = JSON.parse(buildPrompt(task));+ expect(parsed.datetime).toBe("2026-06-10T09:00");+ expect(parsed.received_at).toBe(localISOString(new Date("2026-06-04T14:12:33.000Z")));+ expect(parsed.received_at).not.toBe(parsed.datetime);+ });++ it("falls back to a valid current time when createdAt is invalid", () => {+ const task = makeTask("Hi");+ task.createdAt = "";+ const parsed = JSON.parse(buildPrompt(task));+ expect(parsed.received_at).not.toBe("");+ expect(Number.isNaN(Date.parse(parsed.received_at))).toBe(false);+ });+it("adds EMAIL_NOTICE for email_notification tasks without context", () => {const task = makeTask("New email from [email protected]: Hi", "email_notification");const parsed = JSON.parse(buildPrompt(task));diff --git a/src/cli/daemon/prompt.ts b/src/cli/daemon/prompt.tsindex 47ffa4654..9361b4628 100644--- a/src/cli/daemon/prompt.ts+++ b/src/cli/daemon/prompt.ts@@ -1,4 +1,5 @@import type { Task, Attachment } from "./types.js";+import { localISOString } from "./execenv/timeline.js";const DM_RESPONSE_NOTICE ="IMPORTANT: Only your final text response is visible to the user." +@@ -38,7 +39,17 @@ function buildDmNotice(name: string, email: string): string {}export function buildPrompt(task: Task, attachments?: Attachment[]): string {- const obj: Record<string, unknown> = { type: task.type, instruction: task.prompt };+ // The arrival time of this info (when the message/task was created server-side).+ // Lets a resumed agent reason about elapsed wall-clock time between turns.+ const createdAt = new Date(task.createdAt);+ const receivedAt = Number.isNaN(createdAt.getTime())+ ? localISOString()+ : localISOString(createdAt);+ const obj: Record<string, unknown> = {+ type: task.type,+ received_at: receivedAt,+ instruction: task.prompt,+ };if (task.type === "user_dm_message") {obj.notice = DM_RESPONSE_NOTICE;}diff --git a/src/cli/daemon/session-runner.test.ts b/src/cli/daemon/session-runner.test.tsindex 5b888cf95..cbb5dd437 100644--- a/src/cli/daemon/session-runner.test.ts+++ b/src/cli/daemon/session-runner.test.ts@@ -73,6 +73,17 @@ vi.mock("./execenv/steering.js", () => ({clearKillIntent: (...args: any[]) => (mockClearKillIntent as any)(...args),}));+// killProcessTree is exercised directly in kill-tree.test.ts. Here we stub it to+// a synchronous group-SIGTERM so the handler tests can assert the kill via the+// process.kill spy without waiting on the real SIGKILL grace loop.+const mockKillProcessTree = vi.fn(async (pid: number) => {+ try { process.kill(-pid, "SIGTERM"); } catch { /* */ }+});+vi.mock("./kill-tree.js", () => ({+ killProcessTree: (...args: any[]) => (mockKillProcessTree as any)(...args),+ isAlive: vi.fn(() => false),+}));+vi.mock("./prompt.js", () => ({buildPrompt: vi.fn((task: any) => task.prompt),}));@@ -647,7 +658,38 @@ describe("session-runner runSession", () => {// Should have called process.exit(1)expect(exitSpy).toHaveBeenCalledWith(1);+ // TC5: agent not yet spawned, so no process-tree kill is attempted.+ expect(mockKillProcessTree).not.toHaveBeenCalled();++ exitSpy.mockRestore();+ });++ it("TC7: SIGTERM during sessionId negotiation reaps the freshly-spawned agent", async () => {+ const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {}) as any);++ const agentPid = 55555;+ // sessionId never resolves on its own — the kill lands while we await it,+ // after backend.execute() has already returned a live pid.+ mockBackendExecute.mockReturnValue({+ pid: agentPid,+ messages: (async function* () { await new Promise<void>(() => {}); })(),+ sessionId: new Promise<string>(() => {}),+ result: new Promise(() => {}),+ });++ const sessionPromise = runSession(makeInput());+ // Let execution reach the `await session.sessionId` suspension point.+ await new Promise((r) => setTimeout(r, 50));++ process.emit("SIGTERM", "SIGTERM");+ await new Promise((r) => setTimeout(r, 50));++ // The inner agent that was spawned must be reaped, not orphaned.+ expect(mockKillProcessTree).toHaveBeenCalledWith(agentPid);+ expect(exitSpy).toHaveBeenCalledWith(1);+exitSpy.mockRestore();+ void sessionPromise;});it("gracefully cleans up on SIGTERM: kills agent, updates timeline to killed, calls failTask", async () => {@@ -687,8 +729,8 @@ describe("session-runner runSession", () => {// Wait for cleanup to finishawait new Promise((r) => setTimeout(r, 50));- // 1. Should have killed the inner agent process- expect(killSpy).toHaveBeenCalledWith(agentPid, "SIGTERM");+ // 1. Should have reaped the inner agent's process group+ expect(mockKillProcessTree).toHaveBeenCalledWith(agentPid);// 2. Timeline should be updated to "killed"const killCalls = mockUpdateEntry.mock.calls.filter((call: any[]) => {@@ -1457,9 +1499,9 @@ describe("message inactivity timeout", () => {})(),sessionId: Promise.resolve("sess-hang"),result: new Promise<any>((resolve) => {- // Resolve when process.kill is called (simulating proc close after SIGTERM)+ // Resolve when the agent group is signalled (proc close after SIGTERM).const interval = setInterval(() => {- if (killSpy.mock.calls.some((c) => c[0] === agentPid)) {+ if (killSpy.mock.calls.some((c) => c[0] === -agentPid)) {clearInterval(interval);resolve({status: "timeout",@@ -1476,8 +1518,8 @@ describe("message inactivity timeout", () => {// Use a very short inactivity timeout (100ms) for the testawait runSession(makeInput({ messageInactivityTimeout: 100 }));- // Should have killed the hung agent process- expect(killSpy).toHaveBeenCalledWith(agentPid, "SIGTERM");+ // Should have reaped the hung agent's process group+ expect(mockKillProcessTree).toHaveBeenCalledWith(agentPid);// Should have failed the task with inactivity timeout errorexpect(mockClientInstance.failTask).toHaveBeenCalledWith(@@ -1512,7 +1554,7 @@ describe("message inactivity timeout", () => {sessionId: Promise.resolve("sess-zero"),result: new Promise<any>((resolve) => {const interval = setInterval(() => {- if (killSpy.mock.calls.some((c) => c[0] === agentPid)) {+ if (killSpy.mock.calls.some((c) => c[0] === -agentPid)) {clearInterval(interval);resolve({status: "timeout",@@ -1528,7 +1570,7 @@ describe("message inactivity timeout", () => {await runSession(makeInput({ messageInactivityTimeout: 100 }));- expect(killSpy).toHaveBeenCalledWith(agentPid, "SIGTERM");+ expect(mockKillProcessTree).toHaveBeenCalledWith(agentPid);expect(mockClientInstance.failTask).toHaveBeenCalledWith("test_token","t1",diff --git a/src/cli/daemon/session-runner.ts b/src/cli/daemon/session-runner.tsindex 6b0cc7ab4..8d1caa8f4 100644--- a/src/cli/daemon/session-runner.ts+++ b/src/cli/daemon/session-runner.ts@@ -19,6 +19,7 @@ import {findResumableSessionByContextKey,} from "./execenv/timeline.js";import { readKillIntent, clearKillIntent } from "./execenv/steering.js";+import { killProcessTree } from "./kill-tree.js";import { buildPrompt } from "./prompt.js";import { createLogger } from "../lib/logger.js";@@ -178,20 +179,65 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {task,);+ // --- State shared by the kill handler, hoisted so the SINGLE handler below+ // can see it whether the kill lands before or after the agent spawns. ---let killed = false;+ let agentPid: number | undefined;+ let flushTimer: ReturnType<typeof setInterval> | undefined;- // Early signal handler (before agent starts — no agentPid/flushTimer yet)- const earlyOnKill = async () => {+ // Message batching+ const pendingMessages: {+ seq: number;+ type: string;+ tool?: string;+ call_id?: string;+ content?: string;+ input?: Record<string, unknown>;+ output?: string;+ }[] = [];+ let seq = 0;+ let toolCount = 0;+ const BATCH_SIZE = Number(process.env.ALOOK_MESSAGE_BATCH_SIZE) || 20;+ const FLUSH_INTERVAL_MS = Number(process.env.ALOOK_MESSAGE_FLUSH_INTERVAL_MS) || 100;++ const flushMessages = async () => {+ if (pendingMessages.length === 0) return;+ const batch = pendingMessages.splice(0);+ try {+ await client.reportMessages(token, task.id, batch);+ } catch (e) {+ log.debug("message report failed", e);+ }+ };++ // --- Single SIGTERM/SIGINT handler, registered ONCE for the whole lifetime.+ // Every field it touches is guarded for the "not yet initialized" window+ // (kill arriving before the agent is spawned / batching has started). ---+ const onKill = async () => {if (killed) return;killed = true;- log.info(`killed by signal (messages=0, tools=0)`);+ log.info(`killed by signal (messages=${seq}, tools=${toolCount})`);++ // 1. Kill the inner agent process group (CLI + tool/MCP subprocesses),+ // escalating to SIGKILL if it ignores SIGTERM. No-op if not yet spawned.+ if (agentPid !== undefined) {+ log.info(`killing inner agent group (pid=${agentPid})`);+ await killProcessTree(agentPid);+ }++ // 2. Flush any pending messages+ if (flushTimer) clearInterval(flushTimer);+ try { await flushMessages(); } catch { /* best-effort */ }+ // 3. Cleanup attachmentsawait cleanupAttachments(task.id);+ // 4. Read kill-intent to determine reasonconst intent = readKillIntent(agentBaseDir, task.id);clearKillIntent(agentBaseDir, task.id);if (intent?.reason === "superseded") {+ // Superseded: update timeline and report via dedicated APIupdateEntry(timelineDir, task.id, (entry) => {entry.pid = null;entry.status = "superseded";@@ -200,8 +246,9 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {});try {await client.supersedeTask(token, task.id);- } catch { /* best-effort */ }+ } catch { /* best-effort — daemon steering may have already marked it */ }} else if (intent?.reason === "cancelled") {+ // User cancel: update timeline to cancelled (not killed)updateEntry(timelineDir, task.id, (entry) => {entry.pid = null;entry.status = "cancelled";@@ -213,6 +260,7 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {workspacesRoot,);} else {+ // No intent file: preserve existing behaviorupdateEntry(timelineDir, task.id, (entry) => {entry.pid = null;entry.status = "killed";@@ -227,8 +275,8 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {process.exit(1);};- process.on("SIGTERM", earlyOnKill);- process.on("SIGINT", earlyOnKill);+ process.on("SIGTERM", onKill);+ process.on("SIGINT", onKill);// Download attachments before building promptconst attachmentIds = (task.context?.attachment_ids as string[]) ?? [];@@ -252,12 +300,18 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {{ taskId: task.id, type: "fail", payload: { error: errMsg }, token, serverURL, createdAt: new Date().toISOString() },workspacesRoot,);- process.removeListener("SIGTERM", earlyOnKill);- process.removeListener("SIGINT", earlyOnKill);+ // Leave onKill installed until the very end — no window where the pid is+ // findable but unhandled. agentPid is still undefined, so onKill just reports.+ process.removeListener("SIGTERM", onKill);+ process.removeListener("SIGINT", onKill);return;}}+ // A kill may have arrived during attachment download (onKill set killed=true+ // and called process.exit — but if exit hasn't flushed yet, don't spawn).+ if (killed) return;+const prompt = buildPrompt(task, attachments);const resumeSessionId = task.contextKey@@ -275,8 +329,21 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {resumeSessionId,});- // Capture agent PID for signal handler- const agentPid = session.pid;+ // Capture agent PID so the handler can reap it. backend.execute() spawns+ // synchronously and returns immediately, so the only gap is the JS between+ // the timeline write and here — closed by the re-check below.+ agentPid = session.pid;++ // If a kill landed while the agent was spawning, the handler ran with+ // agentPid===undefined and killed nothing. Reap the freshly-spawned process+ // now and exit before streaming starts.+ if (killed) {+ if (agentPid !== undefined) {+ log.info(`kill landed during spawn — reaping inner agent group (pid=${agentPid})`);+ await killProcessTree(agentPid);+ }+ process.exit(1);+ }// Update timeline entry with session_id once agent startsconst earlySessionId = await session.sessionId;@@ -286,99 +353,7 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {entry.session_id = earlySessionId || null;});- // Message batching- const pendingMessages: {- seq: number;- type: string;- tool?: string;- call_id?: string;- content?: string;- input?: Record<string, unknown>;- output?: string;- }[] = [];- let seq = 0;- let toolCount = 0;- const BATCH_SIZE = Number(process.env.ALOOK_MESSAGE_BATCH_SIZE) || 20;- const FLUSH_INTERVAL_MS = Number(process.env.ALOOK_MESSAGE_FLUSH_INTERVAL_MS) || 100;-- const flushMessages = async () => {- if (pendingMessages.length === 0) return;- const batch = pendingMessages.splice(0);- try {- await client.reportMessages(token, task.id, batch);- } catch (e) {- log.debug("message report failed", e);- }- };-- const flushTimer = setInterval(flushMessages, FLUSH_INTERVAL_MS);-- // --- Replace early signal handler with full one ---- process.removeListener("SIGTERM", earlyOnKill);- process.removeListener("SIGINT", earlyOnKill);-- const onKill = async () => {- if (killed) return;- killed = true;- log.info(`killed by signal (messages=${seq}, tools=${toolCount})`);-- // 1. Kill the inner agent process- if (agentPid) {- try { process.kill(agentPid, "SIGTERM"); } catch { /* already dead */ }- }-- // 2. Flush any pending messages- clearInterval(flushTimer);- try { await flushMessages(); } catch { /* best-effort */ }-- // 3. Cleanup attachments- await cleanupAttachments(task.id);-- // 4. Read kill-intent to determine reason- const intent = readKillIntent(agentBaseDir, task.id);- clearKillIntent(agentBaseDir, task.id);-- if (intent?.reason === "superseded") {- // Superseded: update timeline and report via dedicated API- updateEntry(timelineDir, task.id, (entry) => {- entry.pid = null;- entry.status = "superseded";- entry.successor_task_id = intent.successorTaskId ?? null;- entry.supersede_reason = "superseded by newer task";- });- try {- await client.supersedeTask(token, task.id);- } catch { /* best-effort — daemon steering may have already marked it */ }- } else if (intent?.reason === "cancelled") {- // User cancel: update timeline to cancelled (not killed)- updateEntry(timelineDir, task.id, (entry) => {- entry.pid = null;- entry.status = "cancelled";- entry.errmsg = "cancelled by user";- });- await reportToServer(- () => client.failTask(token, task.id, "cancelled by user"),- { taskId: task.id, type: "fail", payload: { error: "cancelled by user" }, token, serverURL, createdAt: new Date().toISOString() },- workspacesRoot,- );- } else {- // No intent file: preserve existing behavior- updateEntry(timelineDir, task.id, (entry) => {- entry.pid = null;- entry.status = "killed";- entry.errmsg = "killed by signal";- });- await reportToServer(- () => client.failTask(token, task.id, "killed by signal"),- { taskId: task.id, type: "fail", payload: { error: "killed by signal" }, token, serverURL, createdAt: new Date().toISOString() },- workspacesRoot,- );- }-- process.exit(1);- };- process.on("SIGTERM", onKill);- process.on("SIGINT", onKill);+ flushTimer = setInterval(flushMessages, FLUSH_INTERVAL_MS);// Message inactivity timeout — kill hung agent if no messages arrive within the windowconst INACTIVITY_TIMEOUT_MS = messageInactivityTimeout ?? 5 * 60 * 1000;@@ -401,8 +376,10 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {if (raceResult === "timeout") {inactivityTimedOut = true;log.warn(`message inactivity timeout (${INACTIVITY_TIMEOUT_MS / 1000}s) — killing agent`);- if (session.pid) {- try { process.kill(session.pid, "SIGTERM"); } catch { /* already dead */ }+ if (session.pid !== undefined) {+ // Reap the whole agent group, not just the leader, so MCP/tool+ // subprocesses don't orphan on an inactivity timeout.+ await killProcessTree(session.pid);}iter.return?.(undefined as never);break;@@ -447,17 +424,13 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {if (!killed) await flushMessages();} finally {- clearInterval(flushTimer);- process.removeListener("SIGTERM", onKill);- process.removeListener("SIGINT", onKill);+ if (flushTimer) clearInterval(flushTimer);}if (killed) return;- // Re-register signal handlers for the duration of result awaiting- process.on("SIGTERM", onKill);- process.on("SIGINT", onKill);-+ // onKill stays installed across the result await so a kill landing here still+ // reaps the inner agent group; removed only once the result resolves.const result = await session.result;// Remove signal handlers — normal completion takes over