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
Review durable memory during idle maintenance and owner resets (#821)
Gustavo Ye504bcdabe864
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.tsindex 0a7bb4062..3e3dd6413 100644--- a/src/daemon/src/cli/index.test.ts+++ b/src/daemon/src/cli/index.test.ts@@ -2123,13 +2123,12 @@ describe("message send — required bounded stdin body contract", () => {});describe("nap", () => {- it("errors when --handoff is missing, and never calls api.nap", async () => {+ it("sends an absent handoff when no file is supplied", async () => {const napSpy = vi.fn(async () => ({ napped: true }));setApiForTesting(stubApi({ nap: napSpy }));await main(["nap"]);- const env = parseEnvelope(cap.lines());- expect(typeof env.error).toBe("string");- expect(napSpy).not.toHaveBeenCalled();+ expect(parseEnvelope(cap.lines())).toEqual({ success: { napped: true } });+ expect(napSpy).toHaveBeenCalledWith({});});it("errors on a whitespace-only handoff file", async () => {diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.tsindex 975375e24..5ee6945f1 100755--- a/src/daemon/src/cli/index.ts+++ b/src/daemon/src/cli/index.ts@@ -780,10 +780,10 @@ async function cmdNap(opts: Record<string, unknown>): Promise<unknown> {filePath: fileFlag,fileOption: "--handoff <file>",});- if (handoff === undefined || handoff.trim().length === 0) {- throw new CliError("nap: a handoff is required — pass --handoff <file>");+ if (handoff !== undefined && handoff.trim().length === 0) {+ throw new CliError("nap: handoff file must not be blank");}- return await api.nap({ handoff });+ return await api.nap(handoff === undefined ? {} : { handoff });}/* ------------------------------------------------------------------ */@@ -1086,7 +1086,7 @@ function buildProgram(stdin: CliInputStream): Command {program.command("nap")- .description("end your session and start fresh, carrying a handoff to your reborn self (read the nap rule first)")+ .description("reset your session; optionally wake a fresh session with a handoff (read the nap rule first)").option("--handoff <file>", "path to your handoff note (your note to your reborn self)").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} })diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.tsindex 203feba90..cbc646d02 100644--- a/src/daemon/src/cli/proxyServerApi.ts+++ b/src/daemon/src/cli/proxyServerApi.ts@@ -469,7 +469,7 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {return parseJsonResponse<FriendRequestResult>(res, "friendRequest");}- async function callNap(req: { handoff: string }): Promise<{ napped: boolean }> {+ async function callNap(req: { handoff?: string }): Promise<{ napped: boolean }> {// RETARGETED off the flat `nap` verb onto POST bots/me/nap (route/disc// 接口树统一, Gener #215 乙; Blondie #527). nap is a bot-qua-bot self// lifecycle action — the agent resets its OWN session — so it lives underdiff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.tsindex be9e07293..088b8627b 100644--- a/src/daemon/src/drivers/systemPrompt.ts+++ b/src/daemon/src/drivers/systemPrompt.ts@@ -166,7 +166,7 @@ function cliCommandsSection(): string {"","### Context Lifecycle","",- `1. \`${CLI} nap --handoff <file>\` — reset the current session from a required handoff file.`,+ `1. \`${CLI} nap [--handoff <file>]\` — reset the current session; optionally wake a fresh session with a handoff file.`,"","### Output format","",@@ -481,9 +481,10 @@ function workspaceMemorySection(config: HostLaunchConfig): string {"","### Napping","",- `\`${CLI} nap\` resets your current session and starts a fresh one with your required handoff ` +- "injected into it. Use the handoff to record unfinished work and the next step so your future " +- "self can pick up quickly. Never nap on your own; only do it when someone explicitly asks.",+ `\`${CLI} nap\` resets your current session. With optional --handoff <file>, it starts a fresh one ` ++ "with your note injected; without it, the next real message starts fresh. Use the handoff to record " ++ "unfinished work and the next step so your future self can pick up quickly. " ++ "Never nap on your own; only do it when someone explicitly asks.","","### memory.md","",diff --git a/src/daemon/src/manager/agentRouter.test.ts b/src/daemon/src/manager/agentRouter.test.tsindex f9fad525a..ae305f330 100644--- a/src/daemon/src/manager/agentRouter.test.ts+++ b/src/daemon/src/manager/agentRouter.test.ts@@ -555,6 +555,25 @@ describe("AgentRouter — machine:reset_all (batch reset)", () => {describe("AgentRouter — agent:nap", () => {const CFG = { version: 1 as const, runtime: "mock", model: { kind: "default" as const }, mode: { kind: "default" as const } };+ it("reports no-handoff completion only after cleanup, without inventing a running agent", async () => {+ const { mgr } = fakeManager();+ let finish!: () => void;+ const resetSession = vi.fn(() => new Promise<void>((resolve) => { finish = resolve; }));+ mgr.resetSession = resetSession;+ const { ch, fire } = fakeChannel();+ ch.reportStoppedAck = vi.fn(async () => {});+ const router = new AgentRouter({ manager: mgr, channel: ch, runtimeReport: [{ id: "mock" }] });+ await router.start();+ const pending = fire({ type: "agent:nap", agentId: "a1", config: CFG, launchId: "l1" });+ await Promise.resolve();+ expect(ch.reportStoppedAck).not.toHaveBeenCalled();+ finish();+ await pending;+ expect(resetSession).toHaveBeenCalledWith("a1", { runtimeConfig: CFG, launchId: "l1", barrierType: "nap", rewakePrompt: undefined });+ expect(ch.reportStoppedAck).toHaveBeenCalledWith({ agentId: "a1", launchId: "l1", status: "ok" });+ expect(router.buildReady().runningAgents).not.toContain("a1");+ });+it("onBeforeAgent then resetSession with the handoff spliced into the rewake prompt + nap barrier, adds to running", async () => {const { mgr, resets, order } = fakeManager();const { ch, fire } = fakeChannel();diff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.tsindex bf42dd370..08d00a7c6 100644--- a/src/daemon/src/manager/agentRouter.ts+++ b/src/daemon/src/manager/agentRouter.ts@@ -144,11 +144,15 @@ function defaultFormatUnreadNoticeText(): string {* - "pull your inbox" makes it explicit that any real unread messages* queued during the reset window need to be processed.*/-const REWAKE_PROMPT =- "Your session was reset by your owner. Prior conversation context is gone. " +- "Read @memory.md and your .context_timeline for durable context, then pull your inbox " +- "before doing anything else. If it reports marked messages, run `$ALOOK_CLI message mark list` " +- "and resume that outstanding work.";+const REWAKE_PROMPT = `Your session was reset by your owner. Prior conversation context is gone. Read @memory.md and your .context_timeline for durable context, then pull your inbox. If it reports marked messages, run \`$ALOOK_CLI message mark list\` to identify outstanding work. Before continuing work, review memory.md and experiences:++1. Consistency: Read memory.md and experiences. Merge duplicates and resolve conflicting notes against original decisions. Check links.+2. Facts: Verify claims, especially work progress, against the latest original records. Search the context timeline and task discussions through their latest outcomes. Correct outdated or unsupported claims; keep uncertainty explicit.+3. Durability: Keep only lasting facts, preferences, and reusable lessons or procedures. Remove task status, milestones, temporary plans, and diaries; extract a reusable lesson only when useful. Keep memory.md brief with links; put procedures, scope, and reasons in experiences. Reason from first principles: distill specific events into underlying causes, constraints, and reusable principles. Omit incidental dates and details; retain context only when it changes the principle’s validity or scope.++Edit only your own memory files.++After completing the review and any needed edits, resume outstanding work and handle your inbox messages.`;/*** Rewake prompt for `agent:model_switch`. Unlike `REWAKE_PROMPT`, the session@@ -373,13 +377,18 @@ export class AgentRouter {launchId: string,opName: "agent:reset" | "agent:nap" | "agent:model_switch",run: () => Promise<void>,+ rewake = true,): Promise<void> {this.log.info(`${opName} received`, { agentId, launchId });try {await this.opts.onBeforeAgent?.(agentId);await run();- this.running.add(agentId);- this.scheduleReadyFrameResend();+ if (rewake) {+ this.running.add(agentId);+ this.scheduleReadyFrameResend();+ } else {+ await this.opts.channel.reportStoppedAck?.({ agentId, launchId, status: "ok" });+ }this.log.info(`${opName} ok`, { agentId });} catch (err) {if (err instanceof UnknownRuntimeError) {@@ -617,16 +626,14 @@ export class AgentRouter {}break;case "agent:nap":- // Self-initiated twin of agent:reset — same enroll → forget-session →- // fresh-rewake orchestration and `nap` timeline barrier; the only- // difference is the rewake prompt carries the agent's own handoff.await this.runRestartCommand(cmd.agentId, cmd.launchId, "agent:nap", () =>this.opts.manager.resetSession(cmd.agentId, {runtimeConfig: cmd.config,launchId: cmd.launchId,- rewakePrompt: buildNapRewakePrompt(cmd.handoff),+ rewakePrompt: cmd.handoff === undefined ? undefined : buildNapRewakePrompt(cmd.handoff),barrierType: "nap",}),+ cmd.handoff !== undefined,);break;case "agent:model_switch":diff --git a/src/daemon/src/manager/managerPolicy.test.ts b/src/daemon/src/manager/managerPolicy.test.tsindex c5eb3eb4a..ba83b7396 100644--- a/src/daemon/src/manager/managerPolicy.test.ts+++ b/src/daemon/src/manager/managerPolicy.test.ts@@ -120,10 +120,10 @@ function startAdmission(}describe("reduceManager — single-flight spawn", () => {- it("defaults to 30-minute process hibernation and 6-hour session reset", () => {+ it("defaults to 30-minute process hibernation and 3-hour idle memory maintenance", () => {const state = createInitialManagerState();expect(DEFAULT_IDLE_TIMEOUT_MS).toBe(30 * 60 * 1_000);- expect(DEFAULT_IDLE_RESET_TIMEOUT_MS).toBe(6 * 60 * 60 * 1_000);+ expect(DEFAULT_IDLE_RESET_TIMEOUT_MS).toBe(3 * 60 * 60 * 1_000);expect(state).toMatchObject({idleTimeoutMs: DEFAULT_IDLE_TIMEOUT_MS,idleResetTimeoutMs: DEFAULT_IDLE_RESET_TIMEOUT_MS,@@ -718,7 +718,7 @@ describe("reduceManager — tick: stall + idle hibernation", () => {expect(r.state.agents.a.sessionId).toBe("sess-1"); // preserved for resume});- it("keeps the per-agent idle clock across hibernation and resets the resumable session at its deadline", () => {+ it("keeps the idle clock across hibernation and requests memory maintenance without resetting", () => {let s = createInitialManagerState(100_000, 100, 100_000, 100_000, 1_000);s = register(s, "a", PERSISTENT_GATED);s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;@@ -742,20 +742,10 @@ describe("reduceManager — tick: stall + idle hibernation", () => {const due = reduceManager(s, { type: "tick", nowMs: 1_000 });expect(due.effects).toEqual([- { type: "reset_idle_session", agentId: "a", sessionId: "sess-1" },+ { type: "maintain_idle_memory", agentId: "a", sessionId: "sess-1" },]);- const committed = reduceManager(due.state, {- type: "idle_reset_committed",- agentId: "a",- nowMs: 1_000,- });- expect(committed.effects).toEqual([]);- expect(committed.state.agents.a).toMatchObject({- status: "idle",- sessionId: null,- idleSince: null,- });- expect(reduceManager(committed.state, { type: "tick", nowMs: 12_000 }).effects).toEqual([]);+ expect(due.state.agents.a).toMatchObject({ status: "idle", sessionId: "sess-1", idleSince: 1_000 });+ expect(reduceManager(due.state, { type: "tick", nowMs: 1_001 }).effects).toEqual([]);});it("cancels the idle reset clock when a new message wakes a hibernated agent", () => {@@ -789,31 +779,17 @@ describe("reduceManager — tick: stall + idle hibernation", () => {expect(reduceManager(wake.state, { type: "tick", nowMs: 2_000 }).effects).toEqual([]);});- it("commits a due idle reset for a still-running quiescent agent before stopping it", () => {+ it("requests maintenance for a quiescent session and suppresses adjacent ticks", () => {let s = createInitialManagerState(100_000, 0, 100_000, 100_000, 100);s = register(s, "a", PERSISTENT_GATED);s = reduceManager(s, { type: "wake", agentId: "a", message: { text: "m1" }, nowMs: 0 }).state;s = spawnRoot(s, 0);s = reduceManager(s, { type: "backend_session", agentId: "a", sessionId: "sess-1" }).state;s = completeRoot(s, "turn-a", 0).state;-- expect(reduceManager(s, { type: "tick", nowMs: 100 }).effects).toEqual([- { type: "reset_idle_session", agentId: "a", sessionId: "sess-1" },- ]);- const committed = reduceManager(s, {- type: "idle_reset_committed",- agentId: "a",- nowMs: 100,- });- expect(committed.effects).toEqual([- { type: "stop", agentId: "a", reason: "idle_session_reset" },- ]);- expect(committed.state.agents.a).toMatchObject({- status: "stopping",- sessionId: null,- idleSince: null,- stoppingSince: 100,- });+ const due = reduceManager(s, { type: "tick", nowMs: 100 });+ expect(due.effects).toEqual([{ type: "maintain_idle_memory", agentId: "a", sessionId: "sess-1" }]);+ expect(due.state.agents.a).toMatchObject({ status: "running", sessionId: "sess-1", resetting: false });+ expect(reduceManager(due.state, { type: "tick", nowMs: 101 }).effects).toEqual([]);});it("root progress after a stale turn_end restores active work and cancels idle hibernation", () => {diff --git a/src/daemon/src/manager/managerPolicy.ts b/src/daemon/src/manager/managerPolicy.tsindex 26df98ef5..ebb5291ae 100644--- a/src/daemon/src/manager/managerPolicy.ts+++ b/src/daemon/src/manager/managerPolicy.ts@@ -181,7 +181,6 @@ export type ManagerEvent =}| { type: "tick"; nowMs: number }| { type: "reset_session"; agentId: string }- | { type: "idle_reset_committed"; agentId: string; nowMs: number }| { type: "begin_reset"; agentId: string; nowMs: number }| { type: "rewake_after_reset"; agentId: string; message: AgentMsg }| { type: "runtime_config_queued"; agentId: string; message: AgentMsg }@@ -218,7 +217,7 @@ export type ManagerEffect =| { type: "clear_stall_recovery"; agentId: string; sessionId: string }| { type: "expire_admission"; agentId: string; sessionInstanceId: string; commandIds: string[] }| { type: "requeue_delivery"; agentId: string; message: AgentMsg; mode: "busy" | "idle" }- | { type: "reset_idle_session"; agentId: string; sessionId: string }+ | { type: "maintain_idle_memory"; agentId: string; sessionId: string }| { type: "force_exit"; agentId: string; reason: string };export const DEFAULT_STALE_THRESHOLD_MS = 120_000;@@ -230,7 +229,7 @@ export const DEFAULT_TURN_SILENCE_POLICY: TurnSilencePolicy = {normalBudgetMs: 360_000,};export const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1_000;-export const DEFAULT_IDLE_RESET_TIMEOUT_MS = 6 * 60 * 60 * 1_000;+export const DEFAULT_IDLE_RESET_TIMEOUT_MS = 3 * 60 * 60 * 1_000;export const DEFAULT_RESET_STUCK_THRESHOLD_MS = 120_000;export const DEFAULT_STOPPING_STUCK_THRESHOLD_MS = 30_000;@@ -366,21 +365,6 @@ export function reduceManager(state: ManagerState, event: ManagerEvent): ReduceRa.idleSince = null;});- case "idle_reset_committed": {- const existing = state.agents[event.agentId];- if (!existing) return { state, effects: [] };- const agent = clone(existing);- agent.sessionId = null;- agent.stalledSessionId = null;- agent.idleSince = null;- if (agent.status !== "running") return commit(state, agent, []);- agent.status = "stopping";- agent.stoppingSince = event.nowMs;- return commit(state, agent, [- { type: "stop", agentId: event.agentId, reason: "idle_session_reset" },- ]);- }-case "begin_reset":if (!state.agents[event.agentId]) return { state, effects: [] };return mutate(state, event.agentId, (a) => {@@ -861,7 +845,8 @@ function onTick(state: ManagerState, nowMs: number): ReduceResult {(a.status === "running" && lease.state === "none" && lease.lastTerminal !== null));if (idleResetEligible && nowMs - a.idleSince! >= state.idleResetTimeoutMs) {- effects.push({ type: "reset_idle_session", agentId: id, sessionId: a.sessionId! });+ agents[id] = { ...a, idleSince: nowMs };+ effects.push({ type: "maintain_idle_memory", agentId: id, sessionId: a.sessionId! });continue;}diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.tsindex c2fa99c55..01f7be7fb 100644--- a/src/daemon/src/manager/managerRuntime.test.ts+++ b/src/daemon/src/manager/managerRuntime.test.ts@@ -1,3 +1,4 @@+import { MEMORY_MAINTENANCE_PROMPT } from "./memoryMaintenancePrompt.js";import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";import { EventEmitter } from "events";import type { ChildProcess } from "child_process";@@ -363,138 +364,150 @@ function exactTimelineLifecycleStub() {};}-describe("AgentProcessManager — idle session reset", () => {- it("persists an exact reset barrier and clears the local session without waking an idle agent", () => {+describe("AgentProcessManager — nap without handoff", () => {+ it.each([false, true])("waits for physical close and preserves real queued work (%s)", async (newWork) => {+ const old = fakeSession("nap-old");+ const next = fakeSession("nap-new");+ const factory = vi.fn().mockReturnValueOnce(old).mockReturnValueOnce(next);const forgetSession = vi.fn(() => true);- const sessionFactory = vi.fn();- const onBotAuditEvent = vi.fn();+ const setSession = vi.fn(() => true);const mgr = new AgentProcessManager({driverFor: () => fakeDriver("codex"),- baseContextFor: () => ({- workingDirectory: "/tmp",- agentId: "a1",- standingPrompt: "",- config: {} as LaunchContext["config"],- credentialProxy: {} as LaunchContext["credentialProxy"],- }),- sessionFactory,- timeline: { ...exactTimelineLifecycleStub(), forgetSession } as never,- now: () => 123,- onBotAuditEvent,+ baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),+ sessionFactory: factory,+ timeline: { ...exactTimelineLifecycleStub(), setSession, forgetSession, resumeSessionId: () => null } as never,});mgr.register("a1");- const internal = mgr as unknown as { applyEffect(effect: object): void };-- internal.applyEffect({ type: "reset_idle_session", agentId: "a1", sessionId: "sess-old" });-- const completion = forgetSession.mock.calls[0]![3];- expect(forgetSession).toHaveBeenCalledWith(- "a1",- "reset_session",- "sess-old",- { eventId: expect.stringMatching(/^bae_/), occurredAt: "1970-01-01T00:00:00.123Z" },- );- expect(sessionFactory).not.toHaveBeenCalled();- expect(onBotAuditEvent).toHaveBeenCalledOnce();- expect(onBotAuditEvent).toHaveBeenCalledWith(- "a1",- { kind: "session_reset", payload: { trigger: "idle_timeout" } },- { sessionId: null, launchId: null, ...completion },- );- expect(mgr.snapshot().agents.a1).toMatchObject({ status: "idle", sessionId: null, idleSince: null });+ mgr.deliver("a1", { id: "first", text: "original work" });+ old.startResolver?.();+ await Promise.resolve();+ await old.fire("runtime_event", { kind: "session_init", sessionId: "old-backend" });+ expect(mgr.snapshot().agents.a1.sessionId).toBe("old-backend");+ let done = false;+ const nap = mgr.resetSession("a1", { runtimeConfig: B1_RUNTIME_CONFIG, launchId: "nap-launch", barrierType: "nap" }).then(() => { done = true; });+ await Promise.resolve();+ await Promise.resolve();+ expect(done).toBe(false);+ let secondDone = false;+ const secondNap = mgr.resetSession("a1", { runtimeConfig: B1_RUNTIME_CONFIG, launchId: "second-nap", barrierType: "nap" }).then(() => { secondDone = true; });+ await Promise.resolve();+ expect(secondDone).toBe(false);+ await old.fire("runtime_event", { kind: "session_init", sessionId: "late-old" });+ expect(setSession).toHaveBeenCalledTimes(1);+ expect(mgr.snapshot().agents.a1.sessionId).toBeNull();+ expect(forgetSession).toHaveBeenCalledWith("a1", "nap", undefined);+ if (newWork) mgr.deliver("a1", { id: "real", text: "new real work" });+ expect(factory).toHaveBeenCalledTimes(1);+ await old.fire("exit", { reason: "requested", code: 0 });+ await Promise.all([nap, secondNap]);+ expect(done).toBe(true);+ expect(secondDone).toBe(true);+ expect(factory).toHaveBeenCalledTimes(newWork ? 2 : 1);+ if (newWork) {+ expect(factory.mock.calls[1][0].ctx.prompt).toContain("new real work");+ expect(factory.mock.calls[1][0].ctx.config.sessionId).toBeUndefined();+ await old.fire("runtime_event", { kind: "session_init", sessionId: "stale-old" });+ expect(mgr.snapshot().agents.a1.sessionId).not.toBe("stale-old");+ } else {+ expect(mgr.snapshot().agents.a1).toMatchObject({ status: "idle", sessionId: null, resetting: false });+ for (const hours of [3, 6, 9, 24, 48, 72]) {+ const effects = (mgr as unknown as { dispatch(event: object): unknown[] }).dispatch({ type: "tick", nowMs: Date.now() + hours * 60 * 60 * 1_000 });+ expect(effects).toEqual([]);+ expect(factory).toHaveBeenCalledTimes(1);+ }+ mgr.deliver("a1", { id: "later", text: "later real work" });+ expect(factory).toHaveBeenCalledTimes(2);+ expect(factory.mock.calls[1][0].ctx.prompt).toContain("later real work");+ }});- it("defers the reset and leaves state retryable when the barrier cannot be persisted", () => {- const logger = stubLogger();- const forgetSession = vi.fn(() => false);- const onBotAuditEvent = vi.fn();- const mgr = new AgentProcessManager({- driverFor: () => fakeDriver("codex"),- baseContextFor: () => ({- workingDirectory: "/tmp",- agentId: "a1",- standingPrompt: "",- config: {} as LaunchContext["config"],- credentialProxy: {} as LaunchContext["credentialProxy"],- }),- timeline: { ...exactTimelineLifecycleStub(), forgetSession } as never,- logger,- onBotAuditEvent,- });- mgr.register("a1");- const before = mgr.snapshot();- const internal = mgr as unknown as { applyEffect(effect: object): void };-- internal.applyEffect({ type: "reset_idle_session", agentId: "a1", sessionId: "sess-old" });- internal.applyEffect({ type: "reset_idle_session", agentId: "a1", sessionId: "sess-old" });-- expect(forgetSession).toHaveBeenCalledTimes(2);- expect(- onBotAuditEvent.mock.calls.filter(([, event]) => event.kind === "session_reset"),- ).toHaveLength(0);- expect(- onBotAuditEvent.mock.calls.filter(([, event]) => event.kind === "error"),- ).toHaveLength(2);- expect(mgr.snapshot()).toBe(before);- expect(logger.calls.error.map(([message]) => message)).toEqual([- "idle session reset barrier was not persisted; reset deferred",- "idle session reset barrier was not persisted; reset deferred",- ]);+ it("leaves an empty session idle for three days and naps without a synthetic wake", async () => {+ const { mgr } = makeManager();+ for (const hours of [3, 6, 24, 48, 72]) {+ const effects = (mgr as unknown as { dispatch(event: object): unknown[] }).dispatch({ type: "tick", nowMs: hours * 60 * 60 * 1_000 });+ expect(effects).toEqual([]);+ expect(mgr.snapshot().agents.a1).toMatchObject({ status: "idle", sessionId: null });+ }+ await mgr.resetSession("a1", { runtimeConfig: B1_RUNTIME_CONFIG, launchId: "nap-idle", barrierType: "nap" });+ expect(mgr.snapshot().agents.a1).toMatchObject({ status: "idle", sessionId: null, resetting: false, inbox: [] });});+});- it("fences the old spawn owner before stop so a late session_started cannot restore the reset session", async () => {- const session = fakeSession("idle-reset-instance");- session.stop = vi.fn(session.stop.bind(session));- const setSession = vi.fn(() => true);+describe("AgentProcessManager — idle memory maintenance", () => {+ it.each([false, true])("delivers once into the prior session, including hibernation (%s), without resetting on completion", async (hibernated) => {+ let now = 0;+ const first = fakeSession("maintenance-first");+ const resumed = fakeSession("maintenance-resumed");+ const factory = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(resumed);const forgetSession = vi.fn(() => true);+ const send = vi.spyOn(first, "send");const mgr = new AgentProcessManager({driverFor: () => fakeDriver("codex"),- baseContextFor: () => ({- workingDirectory: "/tmp",- agentId: "a1",- standingPrompt: "",- config: {} as LaunchContext["config"],- credentialProxy: {} as LaunchContext["credentialProxy"],- }),- sessionFactory: sessionFactoryFor(session),- timeline: {- ...exactTimelineLifecycleStub(),- setSession,- forgetSession,- resumeSessionId: () => null,- } as never,- now: () => 123,+ baseContextFor: () => ({ workingDirectory: "/tmp", agentId: "a1", standingPrompt: "", config: {} as LaunchContext["config"], credentialProxy: {} as LaunchContext["credentialProxy"] }),+ sessionFactory: factory,+ timeline: { ...exactTimelineLifecycleStub(), setSession: () => true, forgetSession, resumeSessionId: () => "saved-session" } as never,+ now: () => now,+ idleTimeoutMs: 0,+ idleResetTimeoutMs: 1_000,});mgr.register("a1");- mgr.deliver("a1", { id: "first", text: "hello" });+ mgr.deliver("a1", { id: "first", text: "original" });+ first.startResolver?.();+ await Promise.resolve();+ await first.fire("runtime_event", { kind: "session_init", sessionId: "saved-session" });+ await first.fire("runtime_event", { kind: "turn_end", sessionId: "saved-session" });+ if (hibernated) await first.fire("exit", { reason: "requested", code: 0 });+ const tick = (time: number) => {+ now = time;+ (mgr as unknown as { dispatch(event: object): void }).dispatch({ type: "tick", nowMs: now });+ };+ tick(1_000);+ tick(1_001);+ expect(forgetSession).not.toHaveBeenCalled();+ expect(mgr.snapshot().agents.a1.sessionId).toBe("saved-session");+ if (hibernated) {+ expect(factory).toHaveBeenCalledTimes(2);+ expect(factory.mock.calls[1][0].ctx.config.sessionId).toBe("saved-session");+ expect(factory.mock.calls[1][0].ctx.prompt).toContain(MEMORY_MAINTENANCE_PROMPT);+ resumed.startResolver?.();+ await Promise.resolve();+ await resumed.fire("runtime_event", { kind: "session_init", sessionId: "saved-session" });+ await resumed.fire("runtime_event", { kind: "turn_end", sessionId: "saved-session" });+ } else {+ expect(factory).toHaveBeenCalledTimes(1);+ expect(send).toHaveBeenCalledOnce();+ expect(send.mock.calls[0][0]).toMatchObject({ text: expect.stringContaining(MEMORY_MAINTENANCE_PROMPT) });+ await first.fire("runtime_event", { kind: "turn_end", sessionId: "saved-session" });+ }+ expect(forgetSession).not.toHaveBeenCalled();+ expect(mgr.snapshot().agents.a1.sessionId).toBe("saved-session");+ });+ it.each(["failed", "timeout"] as const)("does not force reset when maintenance ends with %s", async (outcome) => {+ let now = 0;+ const { mgr, session } = makeManager({ now: () => now, idleTimeoutMs: 0, idleResetTimeoutMs: 100, staleThresholdMs: 1_000 });+ const forget = vi.spyOn(mgr, "forgetSession");+ mgr.deliver("a1", { id: "initial", text: "work" });session.startResolver?.();await Promise.resolve();- await session.fire("runtime_event", { kind: "session_init", sessionId: "sess-old" });- await session.fire("runtime_event", { kind: "turn_end", sessionId: "sess-old" });- expect(mgr.snapshot().agents.a1).toMatchObject({ sessionId: "sess-old", idleSince: 123 });-- const internal = mgr as unknown as {- applyEffect(effect: object): void;- activeSpawnState: Map<string, { discardEvents: boolean }>;+ await session.fire("runtime_event", { kind: "session_init", sessionId: "retained" });+ await session.fire("runtime_event", { kind: "turn_end", sessionId: "retained" });+ const tick = (time: number) => {+ now = time;+ (mgr as unknown as { dispatch(event: object): void }).dispatch({ type: "tick", nowMs: time });};- internal.applyEffect({ type: "reset_idle_session", agentId: "a1", sessionId: "sess-old" });-- expect(forgetSession).toHaveBeenCalledWith(- "a1",- "reset_session",- "sess-old",- { eventId: expect.stringMatching(/^bae_/), occurredAt: "1970-01-01T00:00:00.123Z" },- );- expect(internal.activeSpawnState.get("a1")?.discardEvents).toBe(true);- expect(session.stop).toHaveBeenCalledWith({ reason: "idle_timeout", forceAfterMs: 2_000 });- expect(mgr.snapshot().agents.a1.sessionId).toBeNull();- expect(setSession).toHaveBeenCalledTimes(1);-- await session.fire("runtime_event", { kind: "session_init", sessionId: "sess-old" });-- expect(setSession).toHaveBeenCalledTimes(1);- expect(mgr.snapshot().agents.a1.sessionId).toBeNull();+ tick(100);+ await Promise.resolve();+ await Promise.resolve();+ if (outcome === "failed") {+ fireManagedTurnFailure(mgr, "maintenance failed");+ } else {+ tick(1_101);+ await session.fire("exit", { reason: "requested", code: 0 });+ }+ expect(forget).not.toHaveBeenCalled();+ expect(mgr.snapshot().agents.a1.sessionId).toBe("retained");});+});describe("AgentProcessManager runtime config revisions", () => {diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.tsindex 3b78dc89a..14d372543 100644--- a/src/daemon/src/manager/managerRuntime.ts+++ b/src/daemon/src/manager/managerRuntime.ts@@ -1,3 +1,4 @@+import { MEMORY_MAINTENANCE_PROMPT } from "./memoryMaintenancePrompt.js";import {reduceManager,createInitialManagerState,@@ -753,7 +754,7 @@ export class AgentProcessManager {opts: {runtimeConfig: RuntimeConfig;launchId: string;- rewakePrompt: string;+ rewakePrompt?: string;barrierType?: "reset_session" | "nap";},): Promise<void> {@@ -772,7 +773,7 @@ export class AgentProcessManager {opts: {runtimeConfig: RuntimeConfig;launchId: string;- rewakePrompt: string;+ rewakePrompt?: string;forgetSession: boolean;barrierType?: "reset_session" | "nap";abortCause: "reset" | "nap" | "model_switch";@@ -792,8 +793,14 @@ export class AgentProcessManager {if (!opts.forgetSession) this.opts.timeline?.fenceSession(agentId);this.abortCurrentTurn(agentId, opts.abortCause);this.markResetting(agentId);+ const previousOwner = this.activeSpawnState.get(agentId);+ if (opts.forgetSession && previousOwner) previousOwner.discardEvents = true;const status = this.state.agents[agentId]?.status;if (status === "idle") {+ if (opts.rewakePrompt === undefined) {+ this.dispatch({ type: "exit", agentId });+ return;+ }try {this.deliver(agentId, {id: `${opts.launchId}:${opts.abortCause}:rewake`,@@ -809,11 +816,15 @@ export class AgentProcessManager {}return;}- this.enqueueRewake(agentId, {- id: `${opts.launchId}:${opts.abortCause}:rewake`,- text: opts.rewakePrompt,- });+ if (opts.rewakePrompt !== undefined) {+ this.enqueueRewake(agentId, {+ id: `${opts.launchId}:${opts.abortCause}:rewake`,+ text: opts.rewakePrompt,+ });+ }+ const previousSession = previousOwner?.session ?? this.sessions.get(agentId);await this.stop(agentId);+ if (opts.rewakePrompt === undefined && previousSession) await previousSession.closed;}async switchModel(agentId: string,@@ -1451,53 +1462,12 @@ export class AgentProcessManager {mode: effect.mode,});break;- case "reset_idle_session": {- const spawnState = this.activeSpawnState.get(effect.agentId);- const completion = {- eventId: `bae_${randomUUID()}`,- occurredAt: new Date(this.now()).toISOString(),- };- const persisted = this.forgetSession(- effect.agentId,- "reset_session",- effect.sessionId,- completion,- );- if (!persisted) {- this.log.error("idle session reset barrier was not persisted; reset deferred", {- agentId: effect.agentId,- sessionId: effect.sessionId,- });- this.emitErrorAudit(- effect.agentId,- "reset",- "resume_control_update_failed",- "Idle session reset deferred because resume control could not be persisted",- );- break;- }- if (spawnState) spawnState.discardEvents = true;- this.dispatch({ type: "idle_reset_committed", agentId: effect.agentId, nowMs: this.now() });- if (this.opts.onBotAuditEvent) {- try {- this.opts.onBotAuditEvent(effect.agentId, {- kind: "session_reset",- payload: { trigger: "idle_timeout" },- }, {- sessionId: null,- launchId: null,- ...completion,- });- } catch (err) {- this.log.debug("audit emit failed (idle session reset)", {- agentId: effect.agentId,- err: String(err),- });- }- }- this.log.info("idle agent session reset", {- agentId: effect.agentId,- sessionId: effect.sessionId,+ case "maintain_idle_memory": {+ const agent = this.state.agents[effect.agentId];+ if (!agent || agent.sessionId !== effect.sessionId || agent.resetting || agent.idleSince === null) break;+ this.deliver(effect.agentId, {+ id: `${effect.agentId}:memory-maintenance:${randomUUID()}`,+ text: MEMORY_MAINTENANCE_PROMPT,});break;}diff --git a/src/daemon/src/manager/memoryMaintenancePrompt.ts b/src/daemon/src/manager/memoryMaintenancePrompt.tsnew file mode 100644index 000000000..6b4f07ebb--- /dev/null+++ b/src/daemon/src/manager/memoryMaintenancePrompt.ts@@ -0,0 +1,11 @@+export const MEMORY_MAINTENANCE_PROMPT = `The daemon is preparing to reset this idle session. First, clean up your memory so the next session does not inherit incorrect or outdated notes.++1. Consistency: Read memory.md and experiences. Merge duplicates and resolve conflicting notes against original decisions. Check links.+2. Facts: Verify claims, especially work progress, against the latest original records. Search the context timeline and task discussions through their latest outcomes. Correct outdated or unsupported claims; keep uncertainty explicit.+3. Durability: Keep only lasting facts, preferences, and reusable lessons or procedures. Remove task status, milestones, temporary plans, and diaries; extract a reusable lesson only when useful. Keep memory.md brief with links; put procedures, scope, and reasons in experiences. Reason from first principles: distill specific events into underlying causes, constraints, and reusable principles. Omit incidental dates and details; retain context only when it changes the principle’s validity or scope.++Edit only your own memory files.++If new work arrives, handle it first and defer nap. Otherwise, after completing the review and any needed edits, your final action is to run the following command without --handoff. Do not finish with only a written reply. This instruction authorizes that nap:++$ALOOK_CLI nap`;diff --git a/src/daemon/src/server/wsControlChannel.test.ts b/src/daemon/src/server/wsControlChannel.test.tsindex a07eb82d6..c549e0653 100644--- a/src/daemon/src/server/wsControlChannel.test.ts+++ b/src/daemon/src/server/wsControlChannel.test.ts@@ -746,6 +746,13 @@ describe("WsControlChannel — downlink HostCommand validation (convergence #6)"}});+ it("dispatches no-handoff nap without manufacturing a handoff", () => {+ const { sockets, received } = driven();+ const frame = { type: "agent:nap", agentId: "b", config: {}, launchId: "no-handoff" };+ sockets[0].emit("message", JSON.stringify(frame));+ expect(received).toEqual([frame]);+ });+it("drops + logs a malformed frame instead of dispatching it", () => {const malformed: unknown[] = [{ type: "agent:wake", config: {}, launchId: "l", unreadNotice: {} }, // missing agentId@@ -753,7 +760,7 @@ describe("WsControlChannel — downlink HostCommand validation (convergence #6)"{ type: "agent:event", agentId: "b", config: {}, launchId: "l" }, // missing prompt{ type: "agent:event", agentId: "b", config: {}, launchId: "l", prompt: "" }, // empty prompt{ type: "agent:event", agentId: "b", config: {}, launchId: "l", prompt: "ok", includeRecentContext: "yes" },- { type: "agent:nap", agentId: "b", config: {}, launchId: "l" }, // missing handoff+ { type: "agent:nap", agentId: "b", config: {}, launchId: "l", handoff: " " },{ type: "agent:nap", agentId: "b", config: {}, launchId: "l", handoff: "" }, // empty handoff{ type: "agent:reset", agentId: "", config: {}, launchId: "l" }, // empty agentId{ type: "agent:unknown", agentId: "b" }, // unknown discriminantdiff --git a/src/daemon/src/server/wsControlChannel.ts b/src/daemon/src/server/wsControlChannel.tsindex ad2391caa..53770e119 100644--- a/src/daemon/src/server/wsControlChannel.ts+++ b/src/daemon/src/server/wsControlChannel.ts@@ -138,6 +138,7 @@ type OutboundFrame =| {type: "agent_stopped_ack";agentId: AgentId;+ launchId?: string;status: AgentCommandAckStatus;error?: AgentCommandAckError;}@@ -368,6 +369,7 @@ export class WsControlChannel implements HostControlChannel {/** Reply to an `agent:stop` HostCommand with the stop outcome. */async reportStoppedAck(info: {agentId: AgentId;+ launchId?: string;status: AgentCommandAckStatus;error?: AgentCommandAckError;}): Promise<void> {diff --git a/src/daemon/src/server/wsControlServer.ts b/src/daemon/src/server/wsControlServer.tsindex 65b255e15..67bae205d 100644--- a/src/daemon/src/server/wsControlServer.ts+++ b/src/daemon/src/server/wsControlServer.ts@@ -54,7 +54,7 @@ type InboundFrame =| ({ type: "ready" } & HostReady)| { type: "agent_session"; agentId: AgentId; sessionId: string; launchId: string }| { type: "agent_wake_ack"; agentId: AgentId; launchId: string; status: AckStatus; error?: AckError }- | { type: "agent_stopped_ack"; agentId: AgentId; status: AckStatus; error?: AckError };+ | { type: "agent_stopped_ack"; agentId: AgentId; launchId?: string; status: AckStatus; error?: AckError };export interface WsControlServerOpts {/**diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex c9e391245..7aedb7d8a 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -717,12 +717,12 @@ export interface ServerApi {pendingIncoming: FriendCard[];}>;/**- * `alook nap` — the agent resets its own session, carrying a mandatory+ * `alook nap` — the agent resets its own session, optionally carrying a* `handoff` note to its reborn self. Self-scoped: the endpoint resolves the* bot from the runner key, so `agentId` isn't sent. Returns `{ napped }` on* delivery; throws (409) if the daemon is offline.*/- nap(req: { handoff: string }): Promise<{ napped: boolean }>;+ nap(req: { handoff?: string }): Promise<{ napped: boolean }>;}/* ------------------------------------------------------------------ */@@ -815,15 +815,7 @@ export type HostCommand =* synthetic rewake — see `AgentProcessManager.resetSession`.*/| { type: "agent:reset"; agentId: AgentId; config: RuntimeConfig; launchId: string }- /**- * Agent-self-initiated reset ("nap"). Mechanically the twin of `agent:reset`- * — same register + `nap` timeline barrier + kill + fresh-session rewake —- * but self-requested and carrying a mandatory `handoff`: the agent's own- * note to its reborn self, spliced into the nap rewake prompt (NOT a message- * to anyone, NOT a persisted file). See `AgentProcessManager.resetSession`- * and the `agent:nap` case in `agentRouter`.- */- | { type: "agent:nap"; agentId: AgentId; config: RuntimeConfig; launchId: string; handoff: string }+ | { type: "agent:nap"; agentId: AgentId; config: RuntimeConfig; launchId: string; handoff?: string }/*** Owner-triggered model switch. The twin of `agent:reset` — same* stop-and-immediate-rewake orchestration and boundary conditions — but it@@ -1052,6 +1044,7 @@ export interface HostControlChannel {*/reportStoppedAck?(info: {agentId: AgentId;+ launchId?: string;status: "ok" | "error";error?: { code: string; message: string };}): Promise<void>;@@ -1518,7 +1511,7 @@ export const HostCommandSchema = z.discriminatedUnion("type", [agentId: z.string().min(1),config: z.unknown(),launchId: z.string().min(1),- handoff: z.string().min(1),+ handoff: z.string().refine((value) => value.trim().length > 0).optional(),}),z.object({type: z.literal("agent:model_switch"),diff --git a/src/shared/src/schemas.test.ts b/src/shared/src/schemas.test.tsindex d8a2da055..14942663d 100644--- a/src/shared/src/schemas.test.ts+++ b/src/shared/src/schemas.test.ts@@ -78,6 +78,10 @@ describe("CommunityServerOnboardRequestSchema", () => {})describe("CommunityAgentNapRequestSchema", () => {+ it("accepts absent handoff but rejects explicit null", () => {+ expect(CommunityAgentNapRequestSchema.parse({})).toEqual({})+ expect(CommunityAgentNapRequestSchema.safeParse({ handoff: null }).success).toBe(false)+ })it("rejects whitespace-only handoffs without trimming valid literal content", () => {expect(CommunityAgentNapRequestSchema.safeParse({ handoff: " \n\t" }).success).toBe(false)const handoff = " literal \\\\n text\n中文 🎉 \n"diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex a80da4c88..702ad7c28 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -1433,14 +1433,10 @@ export type CommunityAgentJoinServerRequest = z.infer<typeof CommunityAgentJoinServerRequestSchema>;-// `alook nap` — the agent resets its own session with a mandatory handoff (its-// note to its reborn self, spliced into the rewake prompt). Inspect `trim()` to-// reject whitespace-only handoffs, but preserve the original string byte-for--// byte for the rewake prompt.export const CommunityAgentNapRequestSchema = z.object({handoff: z.string().refine((value) => value.trim().length > 0, {- message: "handoff is required",- }),+ message: "handoff must not be blank",+ }).optional(),});export type CommunityAgentNapRequest = z.infer<typeof CommunityAgentNapRequestSchemadiff --git a/src/shared/test/community-cli-contract.test.ts b/src/shared/test/community-cli-contract.test.tsindex 811587c59..3204c7792 100644--- a/src/shared/test/community-cli-contract.test.ts+++ b/src/shared/test/community-cli-contract.test.ts@@ -304,6 +304,20 @@ describe("formatCanonicalRef", () => {});});+describe("HostCommand nap contract", () => {+ const command = { type: "agent:nap", agentId: "bot_1", config: {}, launchId: "launch_1" };++ it("accepts an omitted handoff and preserves a supplied note verbatim", () => {+ expect(HostCommandSchema.parse(command)).toEqual(command);+ const handoff = " Next step\n第二行\n";+ expect(HostCommandSchema.parse({ ...command, handoff })).toEqual({ ...command, handoff });+ });++ it.each(["", " \n\t", null])("rejects an explicit invalid handoff: %j", (handoff) => {+ expect(HostCommandSchema.safeParse({ ...command, handoff }).success).toBe(false);+ });+});+describe("HostCommand diagnostics contract", () => {it("keeps the diagnostics arm in the HostCommand type and runtime schema", () => {type DiagnosticCommand = {diff --git a/src/web/src/app/api/community/bots/me/nap/route.test.ts b/src/web/src/app/api/community/bots/me/nap/route.test.tsindex 0dc2fcf2c..47db89881 100644--- a/src/web/src/app/api/community/bots/me/nap/route.test.ts+++ b/src/web/src/app/api/community/bots/me/nap/route.test.ts@@ -75,14 +75,22 @@ describe("POST /api/community/bots/me/nap", () => {vi.clearAllMocks()})- it("missing handoff → 400 and never pushes / never touches audit", async () => {+ it("accepts no handoff without fabricating a note or writing completion early", async () => {+ mockGetBotWakeContext.mockResolvedValue(READY_CTX)+ mockPushAgentNapToMachine.mockResolvedValue({ sent: 1 })const res = await POST(req({}))- expect(res.status).toBe(400)- expect(mockPushAgentNapToMachine).not.toHaveBeenCalled()+ expect(res.status).toBe(200)+ expect(mockPushAgentNapToMachine.mock.calls[0][2].handoff).toBeUndefined()expect(mockInsertBotAuditNap).not.toHaveBeenCalled()expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()})+ it.each(["", " ", null, 1])("rejects an explicitly invalid handoff %j", async (handoff) => {+ const res = await POST(req({ handoff }))+ expect(res.status).toBe(400)+ expect(mockPushAgentNapToMachine).not.toHaveBeenCalled()+ })+it("bot wake context not ready → 409 and never pushes / never touches audit", async () => {mockGetBotWakeContext.mockResolvedValue({ state: "bot_unbound" })diff --git a/src/web/src/app/api/community/bots/me/nap/route.ts b/src/web/src/app/api/community/bots/me/nap/route.tsindex 02db36406..f67a69173 100644--- a/src/web/src/app/api/community/bots/me/nap/route.ts+++ b/src/web/src/app/api/community/bots/me/nap/route.ts@@ -12,7 +12,7 @@ import { withCommunityActor, requireBot } from "@/lib/middleware/community-actorimport { pushAgentNapToMachine } from "@/lib/community/bot-push"/**- * POST /api/community/bots/me/nap — `alook nap --handoff <file>`.+ * POST /api/community/bots/me/nap — `alook nap [--handoff <file>]`.** Relocated from the flat /api/community/nap (route/disc 接口树统一, Gener #215* 乙; Blondie #527 placement). nap is a BOT-QUA-BOT self lifecycle action — the@@ -36,13 +36,6 @@ import { pushAgentNapToMachine } from "@/lib/community/bot-push"* is the sole canonical entry; the deploy-orchestration verify-list gates* deleting it on the daemon being confirmed on this new target.*- * Agent-self-initiated session reset. The self-serve twin of the owner- * `bots/{id}/reset-session` route: build the bot's RuntimeConfig → push- * `agent:nap` (carrying the mandatory handoff) to the bot's OWN machine → on- * delivery (`sent > 0`) the daemon writes the `nap` audit row at reborn-ready.- * If the daemon is offline (`sent === 0`) return 409 and write NO audit row —- * the audit signals a real nap landed, not a request. Notifies no one: a nap is- * the agent's private self-state change.*/export const POST = withCommunityActor(async (req: NextRequest, ctx) => {const gate = requireBot(ctx.actor)@@ -59,7 +52,7 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {}const parsed = CommunityAgentNapRequestSchema.safeParse(raw)if (!parsed.success) {- return NextResponse.json({ error: "handoff is required", details: parsed.error.flatten() }, { status: 400 })+ return NextResponse.json({ error: "invalid nap request", details: parsed.error.flatten() }, { status: 400 })}const handoff = parsed.data.handoff@@ -93,10 +86,7 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {)}- // The `nap` audit row + awake-time stamp are NOT written here: they are- // re-homed to the daemon completion signal (the `agent_session` frame at- // reborn-ready), so the record reflects "the nap actually completed" rather- // than "the command was dispatched." See plans/reset-nap-completion-rehome.md.+return NextResponse.json({ napped: true })})diff --git a/src/web/src/lib/community/bot-push.ts b/src/web/src/lib/community/bot-push.tsindex 5bfda20a6..af3fabf87 100644--- a/src/web/src/lib/community/bot-push.ts+++ b/src/web/src/lib/community/bot-push.ts@@ -202,19 +202,10 @@ export async function pushBatchResetToMachine(}}-/**- * Push an agent-self-initiated `agent:nap` to the bot's OWN machine over WS.- *- * Twin of `pushAgentResetToMachine` — same narrow allowlist plus the mandatory- * `handoff` string (the agent's note to its reborn self, spliced into the nap- * rewake prompt daemon-side). Returns `{ sent }`; `sent === 0` means the daemon- * isn't connected and the caller translates it into a 409 (and writes NO audit- * row — the audit signals a real nap landed, not a request).- */export async function pushAgentNapToMachine(env: Env,machineId: string,- args: { agentId: string; config: RuntimeConfig; launchId: string; handoff: string },+ args: { agentId: string; config: RuntimeConfig; launchId: string; handoff?: string },): Promise<{ sent: number }> {const path = `/community-machine/by-id/${encodeURIComponent(machineId)}/forward-agent-nap`const body = JSON.stringify({diff --git a/src/ws-do/src/routes/community-machine-lifecycle.test.ts b/src/ws-do/src/routes/community-machine-lifecycle.test.tsindex 937007d27..e574acad4 100644--- a/src/ws-do/src/routes/community-machine-lifecycle.test.ts+++ b/src/ws-do/src/routes/community-machine-lifecycle.test.ts@@ -266,6 +266,18 @@ describe("ws-do router", () => {mockGetActiveDoNamesForMachine.mockResolvedValue([])})+ it("forwards an omitted handoff as absence", async () => {+ mockGetActiveDoNamesForMachine.mockResolvedValue(["do-a"])+ doMock.stubFetch.mockResolvedValueOnce(new Response(JSON.stringify({ sent: 1 })))+ const { handoff: _handoff, ...body } = validBody+ const res = await handler.fetch(new Request(+ "http://localhost/community-machine/by-id/machine-1/forward-agent-nap",+ { method: "POST", body: JSON.stringify(body) },+ ), env as any)+ expect(res.status).toBe(200)+ expect(await (doMock.stubFetch.mock.calls[0][0] as Request).json()).toEqual({ type: "agent:nap", ...body })+ })+it("rejects a blank handoff with the exact invalid-payload response", async () => {const res = await handler.fetch(new Request("http://localhost/community-machine/by-id/machine-1/forward-agent-nap",diff --git a/src/ws-do/src/routes/community-machine-lifecycle.ts b/src/ws-do/src/routes/community-machine-lifecycle.tsindex 24c28903c..2ddc7439e 100644--- a/src/ws-do/src/routes/community-machine-lifecycle.ts+++ b/src/ws-do/src/routes/community-machine-lifecycle.ts@@ -250,12 +250,6 @@ export async function handleMachineBatchReset({ request, env, url, traceId, log}export async function handleMachineNap({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {- // POST /community-machine/by-id/<machineId>/forward-agent-nap — agent- // self-initiated `agent:nap` push. Twin of /forward-agent-reset but the- // allowlist additionally carries the mandatory `handoff` string (the- // agent's note to its reborn self, spliced into the rewake prompt). Same- // doName resolution + `/push` fan-out + `{sent}` aggregation. Callers must- // use `pushAgentNapToMachine`.const forwardAgentNap = url.pathname.match(/^\/community-machine\/by-id\/([^/]+)\/forward-agent-nap$/)if (!forwardAgentNap || request.method !== "POST") return null@@ -289,7 +283,7 @@ export async function handleMachineNap({ request, env, url, traceId, log }: Routif (!config || typeof config !== "object") {return Response.json({ error: "invalid payload" }, { status: 400 })}- if (typeof handoff !== "string" || handoff.trim().length === 0) {+ if (handoff !== undefined && (typeof handoff !== "string" || handoff.trim().length === 0)) {return Response.json({ error: "invalid payload" }, { status: 400 })}diff --git a/src/ws-do/src/ws-durable/internal.ts b/src/ws-do/src/ws-durable/internal.tsindex ae0a5e8be..1c2b30876 100644--- a/src/ws-do/src/ws-durable/internal.ts+++ b/src/ws-do/src/ws-durable/internal.ts@@ -55,7 +55,7 @@ export const restartPendingKey = (launchId: string) => RESTART_PENDING_PREFIX +export type ResetTrigger = "single" | "reset_all" | "nap"export type RestartAttribution =| { kind: "session_reset"; trigger: "single" | "reset_all" }- | { kind: "nap" }+ | { kind: "nap"; stoppedAgentId?: string }| { kind: "model_switch"; from: string | null; to: string | null }| { kind: "provider_switch"; from: string; to: string }diff --git a/src/ws-do/src/ws-durable/machine-frames.ts b/src/ws-do/src/ws-durable/machine-frames.tsindex 3dd1c4eb6..716bc93f8 100644--- a/src/ws-do/src/ws-durable/machine-frames.ts+++ b/src/ws-do/src/ws-durable/machine-frames.ts@@ -41,6 +41,7 @@ export async function handleCommunityMachineMessage(context,parsed,identity,+ hooks,)) returnif (await handleSessionErrorFrame(context,diff --git a/src/ws-do/src/ws-durable/machine-restart.test.ts b/src/ws-do/src/ws-durable/machine-restart.test.tsindex 0f27f0f7f..4940ee15f 100644--- a/src/ws-do/src/ws-durable/machine-restart.test.ts+++ b/src/ws-do/src/ws-durable/machine-restart.test.ts@@ -128,6 +128,27 @@ describe("WebSocketDurableObject", () => {.find((r: Request) => r.url.endsWith("/community-broadcast"))}+ it("no-handoff nap completes on its matching stop receipt, never on agent_session", async () => {+ const { durable, store } = onlineDaemon()+ await pushFrame(durable, { type: "agent:nap", agentId: "bot_1", config: {}, launchId: "l_nap" })+ for (const frame of [+ { type: "agent_session", agentId: "bot_1", sessionId: "new", launchId: "l_nap" },+ { type: "agent_stopped_ack", agentId: "other", launchId: "l_nap", status: "ok" },+ { type: "agent_stopped_ack", agentId: "bot_1", launchId: "other", status: "ok" },+ { type: "agent_stopped_ack", agentId: "bot_1", status: "ok" },+ ]) {+ await durable.webSocketMessage(machineWs() as any, JSON.stringify(frame))+ }+ expect(mockInsertBotAuditNap).not.toHaveBeenCalled()+ expect(store.has("reset-pending:l_nap")).toBe(true)+ const receipt = JSON.stringify({ type: "agent_stopped_ack", agentId: "bot_1", launchId: "l_nap", status: "ok" })+ await durable.webSocketMessage(machineWs() as any, receipt)+ await durable.webSocketMessage(machineWs() as any, receipt)+ expect(mockInsertBotAuditNap).toHaveBeenCalledTimes(1)+ expect(mockTouchBotRefreshContext).toHaveBeenCalledWith(expect.anything(), "bot_1", "2025-06-01T11:00:00.000Z")+ expect(store.has("reset-pending:l_nap")).toBe(false)+ })+it("single reset: agent_session writes session_reset audit + stamps awake in lockstep + broadcasts", async () => {const { durable } = onlineDaemon()// Dispatch: an agent:reset frame is forwarded → records launchId→single.diff --git a/src/ws-do/src/ws-durable/machine-restart.ts b/src/ws-do/src/ws-durable/machine-restart.tsindex e744e1685..2e1d96c03 100644--- a/src/ws-do/src/ws-durable/machine-restart.ts+++ b/src/ws-do/src/ws-durable/machine-restart.ts@@ -28,6 +28,7 @@ export async function handleAgentCommandAck(context: WsDurableContext,parsed: unknown,identity: CommunityMachineIdentity,+ hooks: MachineRestartHooks,): Promise<boolean> {if (!parsed || typeof parsed !== "object" || !("type" in parsed) ||@@ -57,6 +58,12 @@ export async function handleAgentCommandAck(await evictPendingReset(context, ack.launchId)}} else if (ack.status === "ok") {+ if (ack.type === "agent_stopped_ack" && typeof ack.launchId === "string" && typeof ack.agentId === "string") {+ const stored = await context.ctx.storage.get<RestartAttribution>(restartPendingKey(ack.launchId))+ if (stored?.kind === "nap" && stored.stoppedAgentId === ack.agentId) {+ await completeRestart(context, identity, hooks, ack.agentId, ack.launchId, stored)+ }+ }context.log.debug("agent command ack ok", {machineId: identity.machineId,type: ack.type,@@ -102,6 +109,19 @@ export async function handleAgentSessionFrame(const stored = await context.ctx.storage.get<ResetTrigger | RestartAttribution>(restartPendingKey(launchId))if (!stored) return trueconst attribution = normalizeRestartAttribution(stored)+ if (attribution.kind === "nap" && attribution.stoppedAgentId !== undefined) return true+ await completeRestart(context, identity, hooks, agentId, launchId, attribution)+ return true+}++async function completeRestart(+ context: WsDurableContext,+ identity: CommunityMachineIdentity,+ hooks: MachineRestartHooks,+ agentId: string,+ launchId: string,+ attribution: RestartAttribution,+): Promise<void> {await evictPendingReset(context, launchId)const db = createDb(context.env.DB)await handleFrameForBoundBot(context, {@@ -161,7 +181,6 @@ export async function handleAgentSessionFrame(}).catch(() => { })},})- return true}export async function recordPendingRestarts(@@ -183,7 +202,12 @@ export async function recordPendingRestarts(if (parsed.type === "agent:reset") {await put((parsed as { launchId?: unknown }).launchId, { kind: "session_reset", trigger: "single" })} else if (parsed.type === "agent:nap") {- await put((parsed as { launchId?: unknown }).launchId, { kind: "nap" })+ const nap = parsed as { launchId?: unknown; agentId?: unknown; handoff?: unknown }+ if (nap.handoff === undefined && typeof nap.agentId !== "string") return+ await put(nap.launchId, {+ kind: "nap",+ ...(nap.handoff === undefined ? { stoppedAgentId: nap.agentId as string } : {}),+ })} else if (parsed.type === "machine:reset_all") {const resets = (parsed as { resets?: unknown }).resetsif (Array.isArray(resets)) {