Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix: sync awake time after automatic idle reset (#558)

Gustavo Ye2c3cf92018f3
diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.ts
index de73ca6f4..a05ab5b36 100644
--- a/src/daemon/src/daemon/createDaemon.test.ts
+++ b/src/daemon/src/daemon/createDaemon.test.ts
@@ -30,6 +30,7 @@ import {
DAEMON_SELF_SLEEP_TIMEOUT_MS,
type DaemonSelfSleepClock,
} from "./daemonSelfSleep";
+import { createTimelineRecorder } from "../timeline/index.js";
const timelineSweepHarness = vi.hoisted(() => {
let implementation: (workingDirectoryBase: string) => Promise<unknown> =
@@ -1949,6 +1950,59 @@ describe("createDaemon — logging", () => {
await daemon.stop();
});
+ it("replays the same durable idle-reset completion after daemon reconstruction", async () => {
+ const base = mkdtempSync(join(tmpdir(), "daemon-audit-outbox-"));
+ startupSweepDirs.push(base);
+ const completion = {
+ eventId: "bae_process_rebuild",
+ occurredAt: "2026-08-25T12:00:00.000Z",
+ };
+ const timelineDirFor = (agentId: string) => join(base, agentId, ".context_timeline");
+ mkdirSync(join(base, "bot_1"));
+ const recorder = createTimelineRecorder({ timelineDirFor });
+ expect(recorder.forgetSession("bot_1", "reset_session", "sess-old", completion)).toBe(true);
+ global.fetch = vi.fn(async () => new Response(JSON.stringify({
+ bots: [{ id: "bot_1", name: "Bot", discriminator: "0001" }],
+ }), { status: 200 })) as unknown as typeof fetch;
+
+ const start = async (sockets: FakeSocket[]) => {
+ const daemon = await createDaemon({
+ machineKey: "cmk_outbox",
+ serverUrl: "http://localhost:9999",
+ serverWsUrl: "ws://x",
+ webSocketFactory: factory(sockets) as any,
+ runtimeReport: [],
+ driverFor: () => fakeDriver,
+ workingDirectoryBase: base,
+ capabilities: [],
+ });
+ sockets[0].emit("open");
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ return daemon;
+ };
+
+ const firstSockets: FakeSocket[] = [];
+ const firstDaemon = await start(firstSockets);
+ const firstFrame = firstSockets[0].sent.map((raw) => JSON.parse(raw)).find(
+ (frame) => frame.type === "bot_audit_event",
+ );
+ expect(firstFrame).toMatchObject({ ...completion, agentId: "bot_1" });
+ await firstDaemon.stop();
+
+ const rebuiltSockets: FakeSocket[] = [];
+ const rebuiltDaemon = await start(rebuiltSockets);
+ const replay = rebuiltSockets[0].sent.map((raw) => JSON.parse(raw)).find(
+ (frame) => frame.type === "bot_audit_event",
+ );
+ expect(replay).toEqual(firstFrame);
+ rebuiltSockets[0].emit("message", JSON.stringify({
+ type: "bot_audit_event_ack",
+ eventId: completion.eventId,
+ }));
+ expect(createTimelineRecorder({ timelineDirFor }).pendingIdleResetEvents("bot_1")).toEqual([]);
+ await rebuiltDaemon.stop();
+ });
+
it("logs enrollAgent's failure branch (bot known, enroll HTTP call fails)", async () => {
global.fetch = vi.fn(async (url: string | URL) => {
const href = String(url);
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index ebd531a4a..752f46b84 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -427,6 +427,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
| { kind: "cli_invocation"; payload: { subcommand: string } }
| { kind: "tool_call"; payload: { name: string; target?: string } }
| { kind: "thinking"; payload: { text: string; truncated: boolean; chars: number } }
+ | { kind: "session_reset"; payload: { trigger: "idle_timeout" } }
| {
kind: "error";
payload: {
@@ -436,10 +437,17 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
model: string | null;
};
},
- context?: { sessionId?: string | null; launchId?: string | null }
+ context?: {
+ sessionId?: string | null;
+ launchId?: string | null;
+ eventId?: string;
+ occurredAt?: string;
+ }
) => {
void channelRef?.reportBotAuditEvent?.({
type: "bot_audit_event",
+ ...(context?.eventId ? { eventId: context.eventId } : {}),
+ ...(context?.occurredAt ? { occurredAt: context.occurredAt } : {}),
agentId,
sessionId: context?.sessionId ?? null,
launchId: context?.launchId ?? null,
@@ -615,6 +623,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
ownerName: b.ownerName,
ownerDiscriminator: b.ownerDiscriminator,
});
+ restorePendingIdleResetEvents(b.id);
}
botCacheReady = true;
}
@@ -732,10 +741,26 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
headers: { Authorization: `Bearer ${opts.machineKey}` },
webSocketFactory: opts.webSocketFactory as never,
onAuthRejected: opts.onAuthRejected,
+ onBotAuditEventAck: ({ agentId, eventId }) =>
+ timeline.acknowledgeIdleResetEvent(agentId, eventId),
logger: log.child("ws"),
});
channelRef = channel;
+ function restorePendingIdleResetEvents(agentId: string): void {
+ for (const pending of timeline.pendingIdleResetEvents(agentId)) {
+ channel.restorePendingBotAuditEvent({
+ type: "bot_audit_event",
+ eventId: pending.eventId,
+ occurredAt: pending.occurredAt,
+ agentId,
+ sessionId: null,
+ launchId: null,
+ event: { kind: "session_reset", payload: { trigger: "idle_timeout" } },
+ });
+ }
+ }
+
// Cache-side handler for bot:* frames. Runs BEFORE AgentRouter sees them,
// via a channel wrapper (registered below).
function handleBotFrame(cmd: HostCommand): void {
@@ -748,6 +773,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
ownerName: cmd.ownerName,
ownerDiscriminator: cmd.ownerDiscriminator,
});
+ restorePendingIdleResetEvents(cmd.botId);
log.debug("bot:added", { botId: cmd.botId, name: cmd.name });
break;
case "bot:updated": {
diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.ts
index 739bff8cf..389cad4dd 100644
--- a/src/daemon/src/manager/managerRuntime.test.ts
+++ b/src/daemon/src/manager/managerRuntime.test.ts
@@ -317,6 +317,7 @@ describe("AgentProcessManager — idle session reset", () => {
it("persists an exact reset barrier and clears the local session without waking an idle agent", () => {
const forgetSession = vi.fn(() => true);
const sessionFactory = vi.fn();
+ const onBotAuditEvent = vi.fn();
const mgr = new AgentProcessManager({
driverFor: () => fakeDriver("codex"),
baseContextFor: () => ({
@@ -329,20 +330,34 @@ describe("AgentProcessManager — idle session reset", () => {
sessionFactory,
timeline: { ...exactTimelineLifecycleStub(), forgetSession } as never,
now: () => 123,
+ onBotAuditEvent,
});
mgr.register("a1");
const internal = mgr as unknown as { applyEffect(effect: object): void };
internal.applyEffect({ type: "reset_idle_session", agentId: "a1", sessionId: "sess-old" });
- expect(forgetSession).toHaveBeenCalledWith("a1", "reset_session", "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 });
});
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: () => ({
@@ -354,6 +369,7 @@ describe("AgentProcessManager — idle session reset", () => {
}),
timeline: { ...exactTimelineLifecycleStub(), forgetSession } as never,
logger,
+ onBotAuditEvent,
});
mgr.register("a1");
const before = mgr.snapshot();
@@ -363,6 +379,12 @@ describe("AgentProcessManager — idle session reset", () => {
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",
@@ -407,7 +429,12 @@ describe("AgentProcessManager — idle session reset", () => {
};
internal.applyEffect({ type: "reset_idle_session", agentId: "a1", sessionId: "sess-old" });
- expect(forgetSession).toHaveBeenCalledWith("a1", "reset_session", "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();
diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.ts
index a4d6ffe27..ba067f0ae 100644
--- a/src/daemon/src/manager/managerRuntime.ts
+++ b/src/daemon/src/manager/managerRuntime.ts
@@ -229,6 +229,7 @@ export interface ManagerRuntimeOpts {
event:
| { kind: "tool_call"; payload: { name: string; target?: string } }
| { kind: "thinking"; payload: { text: string; truncated: boolean; chars: number } }
+ | { kind: "session_reset"; payload: { trigger: "idle_timeout" } }
| {
kind: "error";
payload: {
@@ -238,7 +239,12 @@ export interface ManagerRuntimeOpts {
model: string | null;
};
},
- context: { sessionId: string | null; launchId: string | null }
+ context: {
+ sessionId: string | null;
+ launchId: string | null;
+ eventId?: string;
+ occurredAt?: string;
+ }
) => void;
onAgentLocallyStopped?: (info: { agentId: string; reason: "stop" | "terminate_stalled" }) => void;
onRuntimeRawLine?: (agentId: string, line: string) => void;
@@ -261,7 +267,12 @@ export interface TimelineRecorder {
resolveResumeSession?(agentId: string, provider: string | null): ResumeSessionResolution;
recordSessionStall?(agentId: string, sessionId: string): boolean;
clearSessionStall?(agentId: string, sessionId: string): boolean;
- forgetSession(agentId: string, barrierType?: SystemEntryType, forgottenSessionId?: string): boolean;
+ forgetSession(
+ agentId: string,
+ barrierType?: SystemEntryType,
+ forgottenSessionId?: string,
+ pendingIdleResetEvent?: { eventId: string; occurredAt: string },
+ ): boolean;
}
const THINKING_MAX_BYTES = 4096;
const AUDIT_ERROR_MESSAGE_MAX_LEN = 2000;
@@ -524,8 +535,14 @@ export class AgentProcessManager {
agentId: string,
barrierType: "reset_session" | "nap" = "reset_session",
forgottenSessionId?: string,
+ pendingIdleResetEvent?: { eventId: string; occurredAt: string },
): boolean {
- if (!this.forgetSessionSources(agentId, barrierType, forgottenSessionId)) return false;
+ if (!this.forgetSessionSources(
+ agentId,
+ barrierType,
+ forgottenSessionId,
+ pendingIdleResetEvent,
+ )) return false;
this.dispatch({ type: "reset_session", agentId });
return true;
}
@@ -533,8 +550,16 @@ export class AgentProcessManager {
agentId: string,
barrierType: SystemEntryType,
forgottenSessionId?: string,
+ pendingIdleResetEvent?: { eventId: string; occurredAt: string },
): boolean {
- const persisted = this.opts.timeline?.forgetSession(agentId, barrierType, forgottenSessionId);
+ const persisted = pendingIdleResetEvent
+ ? this.opts.timeline?.forgetSession(
+ agentId,
+ barrierType,
+ forgottenSessionId,
+ pendingIdleResetEvent,
+ )
+ : this.opts.timeline?.forgetSession(agentId, barrierType, forgottenSessionId);
if (persisted === false) return false;
this.resumeSessions.delete(agentId);
this.liveSessions.delete(agentId);
@@ -1220,10 +1245,15 @@ export class AgentProcessManager {
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", {
@@ -1240,6 +1270,23 @@ export class AgentProcessManager {
}
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,
diff --git a/src/daemon/src/server/wsControlChannel.test.ts b/src/daemon/src/server/wsControlChannel.test.ts
index 5240d37c9..74a00aa83 100644
--- a/src/daemon/src/server/wsControlChannel.test.ts
+++ b/src/daemon/src/server/wsControlChannel.test.ts
@@ -310,6 +310,97 @@ describe("WsControlChannel — bot audit event reports", () => {
).resolves.toBeUndefined();
expect(sockets[0].frames().some((f) => f.type === "bot_audit_event")).toBe(false);
});
+
+ it("replays a disconnected idle reset and clears it only after the server ack", async () => {
+ const { ch, sockets } = makeChannel();
+ ch.onResync(() => ({ ready: { runtimeReport: [], runningAgents: [] }, sessions: [] }));
+ ch.connect();
+
+ await ch.reportBotAuditEvent({
+ type: "bot_audit_event",
+ eventId: "bae_disconnected",
+ occurredAt: "2026-08-25T14:00:00.000Z",
+ agentId: "bot_1",
+ sessionId: null,
+ launchId: null,
+ event: { kind: "session_reset", payload: { trigger: "idle_timeout" } },
+ });
+ expect(sockets[0].frames().some((f) => f.type === "bot_audit_event")).toBe(false);
+
+ sockets[0].emit("open");
+ const first = sockets[0].frames().find((f) => f.type === "bot_audit_event");
+ expect(first).toMatchObject({
+ agentId: "bot_1",
+ sessionId: null,
+ launchId: null,
+ event: { kind: "session_reset", payload: { trigger: "idle_timeout" } },
+ });
+ expect(first.eventId).toBe("bae_disconnected");
+
+ sockets[0].emit("message", JSON.stringify({
+ type: "bot_audit_event_ack",
+ eventId: first.eventId,
+ }));
+ sockets[0].emit("close");
+ await new Promise((r) => setTimeout(r, 10));
+ sockets[1].emit("open");
+ expect(sockets[1].frames().some((f) => f.type === "bot_audit_event")).toBe(false);
+ });
+
+ it("retries the same idle-reset event id when the socket drops before ack", async () => {
+ const { ch, sockets } = makeChannel();
+ ch.onResync(() => ({ ready: { runtimeReport: [], runningAgents: [] }, sessions: [] }));
+ ch.connect();
+ sockets[0].emit("open");
+
+ await ch.reportBotAuditEvent({
+ type: "bot_audit_event",
+ eventId: "bae_before_ack",
+ occurredAt: "2026-08-25T14:00:00.000Z",
+ agentId: "bot_1",
+ event: { kind: "session_reset", payload: { trigger: "idle_timeout" } },
+ });
+ const first = sockets[0].frames().find((f) => f.type === "bot_audit_event");
+
+ sockets[0].emit("close");
+ await new Promise((r) => setTimeout(r, 10));
+ sockets[1].emit("open");
+ const replay = sockets[1].frames().find((f) => f.type === "bot_audit_event");
+ expect(replay).toEqual(first);
+ });
+
+ it("retries on an open socket after the ack timeout and stops after ack", async () => {
+ vi.useFakeTimers();
+ try {
+ const onBotAuditEventAck = vi.fn(() => true);
+ const { ch, sockets } = makeChannel({ auditAckRetryMs: 100, onBotAuditEventAck });
+ ch.onResync(() => ({ ready: { runtimeReport: [], runningAgents: [] }, sessions: [] }));
+ ch.connect();
+ sockets[0].emit("open");
+ await ch.reportBotAuditEvent({
+ type: "bot_audit_event",
+ eventId: "bae_no_ack",
+ occurredAt: "2026-08-25T14:00:00.000Z",
+ agentId: "bot_1",
+ event: { kind: "session_reset", payload: { trigger: "idle_timeout" } },
+ });
+
+ expect(sockets[0].frames().filter((f) => f.eventId === "bae_no_ack")).toHaveLength(1);
+ await vi.advanceTimersByTimeAsync(100);
+ expect(sockets[0].frames().filter((f) => f.eventId === "bae_no_ack")).toHaveLength(2);
+
+ sockets[0].emit("message", JSON.stringify({
+ type: "bot_audit_event_ack",
+ eventId: "bae_no_ack",
+ }));
+ expect(onBotAuditEventAck).toHaveBeenCalledWith({ agentId: "bot_1", eventId: "bae_no_ack" });
+ await vi.advanceTimersByTimeAsync(500);
+ expect(sockets[0].frames().filter((f) => f.eventId === "bae_no_ack")).toHaveLength(2);
+ ch.close();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
});
describe("WsControlChannel — HTTP 401s are non-terminal", () => {
diff --git a/src/daemon/src/server/wsControlChannel.ts b/src/daemon/src/server/wsControlChannel.ts
index 6a109f6bb..c9d913d4c 100644
--- a/src/daemon/src/server/wsControlChannel.ts
+++ b/src/daemon/src/server/wsControlChannel.ts
@@ -22,6 +22,7 @@
* (reconnect/heartbeat and frame (de)serialization) end to end, rather than
* shortcut in-process.
*/
+import { BotAuditEventAckFrameSchema } from "@alook/shared";
import type {
HostControlChannel,
HostCommand,
@@ -61,6 +62,8 @@ const DEFAULT_PONG_TIMEOUT_MS = 30_000;
const DEFAULT_RECONNECT_BASE_MS = 500;
/** Reconnect: ceiling on the exponential backoff. */
const DEFAULT_RECONNECT_MAX_MS = 30_000;
+/** Reliable audit receipt timeout; retried forever with this bounded cadence. */
+const DEFAULT_AUDIT_ACK_RETRY_MS = 5_000;
export interface WsControlChannelOpts {
url: string;
@@ -75,6 +78,10 @@ export interface WsControlChannelOpts {
};
/** Heartbeat: ping every `pingIntervalMs`, declare dead after `pongTimeoutMs`. */
heartbeat?: { pingIntervalMs?: number; pongTimeoutMs?: number };
+ /** Receipt retry cadence for durable audit completions. */
+ auditAckRetryMs?: number;
+ /** Clears the matching local durable fact; false keeps retrying. */
+ onBotAuditEventAck?: (info: { agentId: AgentId; eventId: string }) => boolean;
/**
* Called when the server explicitly rejects our machine key via an
* `AUTH_REJECTED` frame — the SOLE terminal-revocation signal. HTTP 401s
@@ -162,8 +169,10 @@ export class WsControlChannel implements HostControlChannel {
private closedByUser = false;
private authRejected = false;
private pingTimer: ReturnType<typeof setInterval> | null = null;
+ private auditRetryTimer: ReturnType<typeof setTimeout> | null = null;
private pongDeadline = 0;
private resyncProvider: ResyncProvider | null = null;
+ private readonly pendingBotAuditEvents = new Map<string, HostBotAuditEventFrame>();
private readonly log: Logger;
private readonly wakeCoordinator = new WakeCoordinator();
@@ -185,6 +194,7 @@ export class WsControlChannel implements HostControlChannel {
close(): void {
this.closedByUser = true;
this.clearHeartbeat();
+ this.clearAuditRetry();
this.ws?.close();
this.ws = null;
this.statusValue = "closed";
@@ -309,16 +319,38 @@ export class WsControlChannel implements HostControlChannel {
}
/**
- * Emit a bot audit event upward — either from the credential proxy sighting
- * (`cli_invocation`) or from a runtime `thinking` / non-Bash `tool_call`
- * event. Frame is dropped when the socket isn't open; audit events are
- * point-in-time (not resynced on reconnect), matching the ready/session
- * policy above.
+ * Emit a bot audit event upward. Automatic idle-reset completions are
+ * reliable: assign a stable id, retain before the first send, replay on
+ * reconnect, and clear only after the server acknowledges its durable write.
+ * Other audit events remain point-in-time and may drop while disconnected.
*/
async reportBotAuditEvent(frame: HostBotAuditEventFrame): Promise<void> {
+ if (
+ frame.event.kind === "session_reset" &&
+ frame.event.payload.trigger === "idle_timeout"
+ ) {
+ if (!frame.eventId || !frame.occurredAt) {
+ this.log.error("durable idle-reset audit missing local receipt", {
+ agentId: frame.agentId,
+ });
+ return;
+ }
+ this.pendingBotAuditEvents.set(frame.eventId, frame);
+ this.sendFrame(frame);
+ this.scheduleAuditRetry();
+ return;
+ }
this.sendFrame(frame);
}
+ /** Restore one completion from the timeline's durable outbox after startup. */
+ restorePendingBotAuditEvent(frame: HostBotAuditEventFrame): void {
+ if (!frame.eventId || !frame.occurredAt) return;
+ this.pendingBotAuditEvents.set(frame.eventId, frame);
+ this.sendFrame(frame);
+ this.scheduleAuditRetry();
+ }
+
/**
* Reply to an `agent:wake` HostCommand with the wake outcome — "daemon
* accepted/handled the wake command", NOT "process started" (see
@@ -378,10 +410,13 @@ export class WsControlChannel implements HostControlChannel {
// otherwise lost forever, stranding the pill on a stale state.
const liveActivities = activities ?? [];
for (const a of liveActivities) this.sendFrame({ type: "agent_activity", ...a });
+ for (const frame of this.pendingBotAuditEvents.values()) this.sendFrame(frame);
+ this.scheduleAuditRetry();
this.log.info("resync sent", {
ready: ready.runtimeReport.length,
sessions: sessions.length,
activities: liveActivities.length,
+ pendingAuditEvents: this.pendingBotAuditEvents.size,
});
}
for (const hook of this.resyncHooks) {
@@ -433,6 +468,30 @@ export class WsControlChannel implements HostControlChannel {
return;
}
+ const auditAck = BotAuditEventAckFrameSchema.safeParse(frame);
+ if (auditAck.success) {
+ this.attempt = 0;
+ const pending = this.pendingBotAuditEvents.get(auditAck.data.eventId);
+ if (!pending) return;
+ let durableCleared = this.opts.onBotAuditEventAck === undefined;
+ try {
+ durableCleared = this.opts.onBotAuditEventAck?.({
+ agentId: pending.agentId,
+ eventId: auditAck.data.eventId,
+ }) ?? true;
+ } catch (err) {
+ this.log.warn("bot audit ack local clear threw", {
+ eventId: auditAck.data.eventId,
+ err: describeErr(err),
+ });
+ }
+ if (durableCleared) this.pendingBotAuditEvents.delete(auditAck.data.eventId);
+ else this.log.warn("bot audit ack local clear deferred", { eventId: auditAck.data.eventId });
+ if (this.pendingBotAuditEvents.size === 0) this.clearAuditRetry();
+ else this.scheduleAuditRetry();
+ return;
+ }
+
// Valid server frame — reset backoff (server accepted us). AUTH_REJECTED
// (above) is an `error` frame, NOT a HostCommand, so it stays ahead of the
// schema gate and short-circuits regardless of command validity.
@@ -521,6 +580,7 @@ export class WsControlChannel implements HostControlChannel {
private onSocketClosed(code?: number, reason?: unknown): void {
this.log.warn("control channel closed", { code, reason: reason ? String(reason) : "" });
this.clearHeartbeat();
+ this.clearAuditRetry();
this.ws = null;
if (this.closedByUser) return;
if (this.authRejected) {
@@ -577,6 +637,25 @@ export class WsControlChannel implements HostControlChannel {
}
}
+ private scheduleAuditRetry(): void {
+ if (this.auditRetryTimer || this.pendingBotAuditEvents.size === 0) return;
+ const delayMs = this.opts.auditAckRetryMs ?? DEFAULT_AUDIT_ACK_RETRY_MS;
+ this.auditRetryTimer = setTimeout(() => {
+ this.auditRetryTimer = null;
+ if (this.statusValue === "open") {
+ for (const frame of this.pendingBotAuditEvents.values()) this.sendFrame(frame);
+ }
+ this.scheduleAuditRetry();
+ }, delayMs);
+ this.auditRetryTimer.unref?.();
+ }
+
+ private clearAuditRetry(): void {
+ if (!this.auditRetryTimer) return;
+ clearTimeout(this.auditRetryTimer);
+ this.auditRetryTimer = null;
+ }
+
private now(): number {
return this.opts.now ? this.opts.now() : Date.now();
}
diff --git a/src/daemon/src/timeline/recorder.test.ts b/src/daemon/src/timeline/recorder.test.ts
index be40955db..3c633cdc5 100644
--- a/src/daemon/src/timeline/recorder.test.ts
+++ b/src/daemon/src/timeline/recorder.test.ts
@@ -589,6 +589,27 @@ describe("createTimelineRecorder barriers and pending commits", () => {
});
describe("createTimelineRecorder durable resume control", () => {
+ it("recovers the same idle-reset completion after reconstruction until acked", () => {
+ const dir = mkDir();
+ const completion = {
+ eventId: "bae_crash_recovery",
+ occurredAt: "2026-06-24T12:00:00.000Z",
+ };
+ const first = createTimelineRecorder({ timelineDirFor: () => dir, now: NOW });
+ expect(first.forgetSession("a", "reset_session", "sess-old", completion)).toBe(true);
+
+ const rebuilt = createTimelineRecorder({ timelineDirFor: () => dir, now: NOW });
+ expect(rebuilt.pendingIdleResetEvents("a")).toEqual([completion]);
+ expect(rebuilt.acknowledgeIdleResetEvent("a", completion.eventId)).toBe(true);
+
+ const afterAck = createTimelineRecorder({ timelineDirFor: () => dir, now: NOW });
+ expect(afterAck.pendingIdleResetEvents("a")).toEqual([]);
+ expect(afterAck.resolveResumeSession("a", null)).toMatchObject({
+ kind: "barrier",
+ type: "reset_session",
+ });
+ });
+
it("resolves only the latest provider-compatible exact turn", () => {
const dir = mkDir();
const recorder = createTimelineRecorder({ timelineDirFor: () => dir, providerFor: () => "claude", now: NOW });
diff --git a/src/daemon/src/timeline/recorder.ts b/src/daemon/src/timeline/recorder.ts
index bd49be50d..1d148f821 100644
--- a/src/daemon/src/timeline/recorder.ts
+++ b/src/daemon/src/timeline/recorder.ts
@@ -168,7 +168,18 @@ export interface TimelineRecorderLike {
* Returns false unless the authoritative control transition was committed;
* the forensic row is appended only after that precondition.
*/
- forgetSession(agentId: string, barrierType?: SystemEntryType, forgottenSessionId?: string): boolean;
+ forgetSession(
+ agentId: string,
+ barrierType?: SystemEntryType,
+ forgottenSessionId?: string,
+ pendingIdleResetEvent?: { eventId: string; occurredAt: string },
+ ): boolean;
+ /** Durable idle-reset completions which still need a server receipt. */
+ pendingIdleResetEvents(
+ agentId: string,
+ ): ReadonlyArray<{ eventId: string; occurredAt: string }>;
+ /** Clear one durable completion only after its server receipt arrives. */
+ acknowledgeIdleResetEvent(agentId: string, eventId: string): boolean;
}
export interface TimelineRecorderOptions {
@@ -541,7 +552,7 @@ export function createTimelineRecorder(opts: TimelineRecorderOptions): TimelineR
clearSessionStall(agentId, sessionId) {
return appendStallMarker(agentId, "stall_recovery_clear", sessionId);
},
- forgetSession(agentId, barrierType = "reset_session", forgottenSessionId) {
+ forgetSession(agentId, barrierType = "reset_session", forgottenSessionId, pendingIdleResetEvent) {
retryPending(agentId);
const dir = dirFor(agentId);
// Persist the authoritative transition before clearing the in-memory
@@ -558,6 +569,11 @@ export function createTimelineRecorder(opts: TimelineRecorderOptions): TimelineR
attemptedSessionId: null,
fencedSessionId: null,
fullBarrier: barrierType,
+ pendingIdleResetEvents:
+ pendingIdleResetEvent
+ && !state.pendingIdleResetEvents.some(({ eventId }) => eventId === pendingIdleResetEvent.eventId)
+ ? [...state.pendingIdleResetEvents, pendingIdleResetEvent]
+ : state.pendingIdleResetEvents,
}));
} else if (barrierType === "stall_recovery") {
persisted = updateResumeControlState(dir, (state) => ({
@@ -592,6 +608,18 @@ export function createTimelineRecorder(opts: TimelineRecorderOptions): TimelineR
handleTrackedResult(agentId, null, result);
return true;
},
+ pendingIdleResetEvents(agentId) {
+ const state = readResumeControlState(dirFor(agentId));
+ return state.kind === "state" ? state.state.pendingIdleResetEvents.map((event) => ({ ...event })) : [];
+ },
+ acknowledgeIdleResetEvent(agentId, eventId) {
+ const dir = dirFor(agentId);
+ if (!prepareTimelineDirectory(dir)) return false;
+ return updateResumeControlState(dir, (state) => ({
+ ...state,
+ pendingIdleResetEvents: state.pendingIdleResetEvents.filter((event) => event.eventId !== eventId),
+ }));
+ },
};
function appendStallMarker(agentId: string, type: SystemEntryType, sessionId: string): boolean {
diff --git a/src/daemon/src/timeline/timeline.ts b/src/daemon/src/timeline/timeline.ts
index b65ecc83e..88db49c25 100644
--- a/src/daemon/src/timeline/timeline.ts
+++ b/src/daemon/src/timeline/timeline.ts
@@ -26,12 +26,15 @@ export const TIMELINE_READ_CHUNK_BYTES = 65_536;
const DATE_FILENAME_PATTERN = /^\d{4}-\d{2}-\d{2}\.jsonl$/;
const RESUME_CONTROL_FILENAME = ".resume-control.json";
const RESUME_CONTROL_MAX_BYTES = 4_096;
+const MAX_PENDING_IDLE_RESET_EVENTS = 32;
export interface ResumeControlState {
version: 1;
attemptedSessionId: string | null;
fencedSessionId: string | null;
fullBarrier: "reset_session" | "nap" | null;
+ /** Stable completions committed atomically with their idle-reset barrier. */
+ pendingIdleResetEvents: Array<{ eventId: string; occurredAt: string }>;
}
export type ResumeControlReadResult =
@@ -44,6 +47,7 @@ const EMPTY_RESUME_CONTROL: ResumeControlState = {
attemptedSessionId: null,
fencedSessionId: null,
fullBarrier: null,
+ pendingIdleResetEvents: [],
};
interface TimelineLine {
@@ -521,10 +525,27 @@ export function readResumeControlState(timelineDir: string): ResumeControlReadRe
const value = JSON.parse(raw) as Partial<ResumeControlState>;
const validSessionId = (candidate: unknown): candidate is string | null =>
candidate === null || (typeof candidate === "string" && candidate.length > 0 && candidate.length <= 512);
+ const pendingIdleResetEvents = value.pendingIdleResetEvents === undefined
+ ? []
+ : value.pendingIdleResetEvents;
if (
value.version !== 1
|| !validSessionId(value.attemptedSessionId)
|| !validSessionId(value.fencedSessionId)
+ || !Array.isArray(pendingIdleResetEvents)
+ || pendingIdleResetEvents.length > MAX_PENDING_IDLE_RESET_EVENTS
+ || pendingIdleResetEvents.some(
+ (event) =>
+ !event
+ || typeof event !== "object"
+ || typeof event.eventId !== "string"
+ || event.eventId.length < 1
+ || event.eventId.length > 128
+ || typeof event.occurredAt !== "string"
+ || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(event.occurredAt)
+ || !Number.isFinite(Date.parse(event.occurredAt)),
+ )
+ || new Set(pendingIdleResetEvents.map((event) => event.eventId)).size !== pendingIdleResetEvents.length
|| (
value.fullBarrier !== null
&& value.fullBarrier !== "reset_session"
@@ -538,6 +559,7 @@ export function readResumeControlState(timelineDir: string): ResumeControlReadRe
attemptedSessionId: value.attemptedSessionId,
fencedSessionId: value.fencedSessionId,
fullBarrier: value.fullBarrier,
+ pendingIdleResetEvents,
},
};
} catch {
@@ -560,11 +582,28 @@ export function updateResumeControlState(
const current = readResumeControlState(timelineDir);
const base = current.kind === "state" ? current.state : EMPTY_RESUME_CONTROL;
const next = update({ ...base });
+ if (
+ !Array.isArray(next.pendingIdleResetEvents)
+ || next.pendingIdleResetEvents.length > MAX_PENDING_IDLE_RESET_EVENTS
+ || next.pendingIdleResetEvents.some(
+ (event) =>
+ !event
+ || typeof event !== "object"
+ || typeof event.eventId !== "string"
+ || event.eventId.length < 1
+ || event.eventId.length > 128
+ || typeof event.occurredAt !== "string"
+ || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(event.occurredAt)
+ || !Number.isFinite(Date.parse(event.occurredAt)),
+ )
+ || new Set(next.pendingIdleResetEvents.map((event) => event.eventId)).size !== next.pendingIdleResetEvents.length
+ ) return false;
const canonical: ResumeControlState = {
version: 1,
attemptedSessionId: next.attemptedSessionId,
fencedSessionId: next.fencedSessionId,
fullBarrier: next.fullBarrier,
+ pendingIdleResetEvents: next.pendingIdleResetEvents,
};
const body = JSON.stringify(canonical) + "\n";
if (Buffer.byteLength(body, "utf8") > RESUME_CONTROL_MAX_BYTES) return false;
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index 5705f60e5..62d1f6545 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -894,16 +894,21 @@ export type BotAuditEventPayload =
model: string | null;
};
}
- // Reset/nap completion events, emitted upward by the DO when the reborn
- // agent's `agent_session` frame lands (not at dispatch). `trigger`
+ // Reset/nap completion events. Owner reset/nap are emitted by the DO when the
+ // reborn agent's `agent_session` frame lands; `idle_timeout` is emitted by
+ // the daemon only after its local six-hour reset barrier commits. `trigger`
// distinguishes the entry-point so my-bots can read "was reset" vs "slept";
// `actorId` never travels — it is the bot owner, resolved server-side at the
// landing (reset is owner-only). See plans/reset-nap-completion-rehome.md.
- | { kind: "session_reset"; payload: { trigger: "single" | "reset_all" } }
+ | { kind: "session_reset"; payload: { trigger: "single" | "reset_all" | "idle_timeout" } }
| { kind: "nap"; payload: { trigger: "nap" } };
export interface HostBotAuditEventFrame {
type: "bot_audit_event";
+ /** Stable id for reliable events; required on `session_reset/idle_timeout`. */
+ eventId?: string;
+ /** Durable barrier completion time; required on `session_reset/idle_timeout`. */
+ occurredAt?: string;
agentId: AgentId;
sessionId?: string | null;
launchId?: string | null;
@@ -986,9 +991,11 @@ export interface HostControlChannel {
*/
reportAgentTypingStop?(info: { agentId: AgentId; channelId: string }): void;
/**
- * Report a bot audit event (cli_invocation | tool_call | thinking) upward.
- * Optional so LocalControlChannel can omit — matches `reportAgentActivity?`
- * convention. ws-do stamps `createdAt` and enforces the 500-row retention.
+ * Report a bot audit event upward. Automatic idle-reset completions are
+ * retained and replayed by the real WS channel until the server acknowledges
+ * their durable write; other audit events remain point-in-time. Optional so
+ * LocalControlChannel can omit — matches `reportAgentActivity?` convention.
+ * ws-do stamps `createdAt` and enforces the 500-row retention.
*/
reportBotAuditEvent?(frame: HostBotAuditEventFrame): Promise<void>;
/**
diff --git a/src/shared/src/db/queries/community/bot-audit-log.ts b/src/shared/src/db/queries/community/bot-audit-log.ts
index 2acf1e693..246e0f47a 100644
--- a/src/shared/src/db/queries/community/bot-audit-log.ts
+++ b/src/shared/src/db/queries/community/bot-audit-log.ts
@@ -27,11 +27,13 @@ export type BotActivityEventRow = {
};
export type BotActivityEventInput = {
+ id?: string;
botId: string;
sessionId?: string | null;
launchId?: string | null;
kind: "cli_invocation" | "tool_call" | "thinking" | "wake_trigger" | "session_reset" | "nap" | "model_changed" | "provider_changed" | "error";
payload: string;
+ createdAt?: string;
};
/**
@@ -90,12 +92,15 @@ export function insertBotActivityEventStatement(
return db
.insert(communityBotActivityEvent)
.values({
+ ...(data.id ? { id: data.id } : {}),
botId: data.botId,
sessionId: data.sessionId ?? null,
launchId: data.launchId ?? null,
kind: data.kind,
payload: data.payload,
+ ...(data.createdAt ? { createdAt: data.createdAt } : {}),
})
+ .onConflictDoNothing({ target: communityBotActivityEvent.id })
.returning({
id: communityBotActivityEvent.id,
createdAt: communityBotActivityEvent.createdAt,
diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.ts
index d41eadbda..93253db01 100644
--- a/src/shared/src/db/queries/community/bot.ts
+++ b/src/shared/src/db/queries/community/bot.ts
@@ -18,7 +18,7 @@
* return null / 404 at the route. The victim's state must be untouched.
*/
-import { aliasedTable, and, count, eq, gte, inArray, isNull, sql } from "drizzle-orm";
+import { aliasedTable, and, count, eq, exists, gte, inArray, isNull, lt, or, sql } from "drizzle-orm";
import { user } from "../../schema";
import {
communityBotBinding,
@@ -30,6 +30,7 @@ import {
communityUserProfile,
communityReadState,
communityBotDailyActivity,
+ communityBotActivityEvent,
} from "../../community-schema";
import { communityMachine } from "../../community-machine-schema";
import type { Database } from "../../index";
@@ -744,6 +745,38 @@ export async function touchBotRefreshContext(
.where(and(eq(user.id, botId), eq(user.isBot, true), isNull(user.deletedAt)));
}
+/**
+ * Batchable Awake stamp for a reliable audit insert. The exact audit row must
+ * exist with the same validated completion timestamp, so a duplicate event-id
+ * retry cannot move Awake or create an audit/timestamp split. The monotonic
+ * predicate also prevents a delayed reset from overwriting a newer wake/reset.
+ */
+export function touchBotRefreshContextForAuditEventStatement(
+ db: Database,
+ botId: string,
+ eventId: string,
+ createdAt: string,
+) {
+ const exactInsertedEvent = db
+ .select({ id: communityBotActivityEvent.id })
+ .from(communityBotActivityEvent)
+ .where(and(
+ eq(communityBotActivityEvent.id, eventId),
+ eq(communityBotActivityEvent.botId, botId),
+ eq(communityBotActivityEvent.createdAt, createdAt),
+ ));
+ return db
+ .update(user)
+ .set({ lastRefreshContextAt: createdAt })
+ .where(and(
+ eq(user.id, botId),
+ eq(user.isBot, true),
+ isNull(user.deletedAt),
+ or(isNull(user.lastRefreshContextAt), lt(user.lastRefreshContextAt, createdAt)),
+ exists(exactInsertedEvent),
+ ));
+}
+
/**
* Drizzle statement that bumps a bot's per-day activity rollup by one, for the
* my-bots heatmap. `column` selects which counter — `handled` (rides the
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 76896cc4d..44cbb45a6 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -308,6 +308,7 @@ export {
AuditLogNapPayloadSchema,
AuditLogErrorPayloadSchema,
HostBotAuditEventFrameSchema,
+ BotAuditEventAckFrameSchema,
} from "./schemas";
export type {
@@ -393,6 +394,7 @@ export type {
BotAuditEventKind,
AuditLogWakeTriggerPayload,
AuditLogProviderChangedPayload,
+ BotAuditEventAckFrame,
} from "./schemas";
// Community agent CLI bridge contract — lifted from `src/daemon/src/server/contract.ts`.
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 63707fa66..90f51fb38 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -1427,16 +1427,15 @@ export const AuditLogWakeTriggerPayloadSchema = z.object({
export type AuditLogWakeTriggerPayload = z.infer<typeof AuditLogWakeTriggerPayloadSchema>;
/**
- * `session_reset` payload — an owner-triggered reset that has actually
- * completed (written when the reborn agent's `agent_session` lands, not at
- * dispatch). `trigger` distinguishes a single-bot reset from a machine-wide
- * "reset all" so my-bots can label them. No `actorId`: reset is owner-only, so
- * the actor is the bot owner, resolved server-side at the landing — it never
- * travels on the wire. (Rows written before this shape carried `{}` and parse
- * to null, which the lenient client parser tolerates.)
+ * `session_reset` payload — a completed context reset. Owner-triggered single
+ * and batch resets are written when the reborn agent's `agent_session` lands;
+ * `idle_timeout` is emitted after the daemon commits its local six-hour reset
+ * barrier. No `actorId`: owner reset is owner-only and automatic reset has no
+ * human actor. (Rows written before this shape carried `{}` and parse to null,
+ * which the lenient client parser tolerates.)
*/
export const AuditLogSessionResetPayloadSchema = z.object({
- trigger: z.enum(["single", "reset_all"]),
+ trigger: z.enum(["single", "reset_all", "idle_timeout"]),
});
export type AuditLogSessionResetPayload = z.infer<typeof AuditLogSessionResetPayloadSchema>;
@@ -1515,15 +1514,44 @@ export const BotAuditEventKindSchema = z.enum([
export type BotAuditEventKind = z.infer<typeof BotAuditEventKindSchema>;
/**
- * `bot_audit_event` frame — daemon → server. Two producers on the daemon side
- * feed this (credential proxy sighting for `cli_invocation`, runtime event
- * stream for `tool_call` / `thinking`); ws-do stamps `createdAt` and inserts.
+ * `bot_audit_event` frame — daemon → server. Ordinary telemetry gets a server
+ * creation time. A reliable idle reset carries the durable local barrier time
+ * so delayed delivery cannot make Web Awake younger than the actual reset.
*/
export const HostBotAuditEventFrameSchema = z.object({
type: z.literal("bot_audit_event"),
+ eventId: z.string().min(1).max(128).optional(),
+ occurredAt: z.string().datetime({ offset: true }).optional(),
agentId: z.string().min(1),
sessionId: z.string().nullable().optional(),
launchId: z.string().nullable().optional(),
event: BotAuditEventSchema,
+}).superRefine((frame, ctx) => {
+ if (
+ frame.event.kind === "session_reset" &&
+ frame.event.payload.trigger === "idle_timeout" &&
+ (!frame.eventId || !frame.occurredAt)
+ ) {
+ if (!frame.eventId) {
+ ctx.addIssue({
+ code: "custom",
+ path: ["eventId"],
+ message: "eventId is required for idle_timeout session_reset",
+ });
+ }
+ if (!frame.occurredAt) {
+ ctx.addIssue({
+ code: "custom",
+ path: ["occurredAt"],
+ message: "occurredAt is required for idle_timeout session_reset",
+ });
+ }
+ }
});
export type HostBotAuditEventFrame = z.infer<typeof HostBotAuditEventFrameSchema>;
+
+export const BotAuditEventAckFrameSchema = z.strictObject({
+ type: z.literal("bot_audit_event_ack"),
+ eventId: z.string().min(1).max(128),
+});
+export type BotAuditEventAckFrame = z.infer<typeof BotAuditEventAckFrameSchema>;
diff --git a/src/shared/test/queries/community-bot-audit-log.test.ts b/src/shared/test/queries/community-bot-audit-log.test.ts
index 719db7ee4..d2652261a 100644
--- a/src/shared/test/queries/community-bot-audit-log.test.ts
+++ b/src/shared/test/queries/community-bot-audit-log.test.ts
@@ -2,8 +2,14 @@ import Sqlite from "better-sqlite3"
import { drizzle } from "drizzle-orm/better-sqlite3"
import { afterEach, beforeEach, describe, it, expect, vi } from "vitest"
import * as q from "../../src/db/queries/community/bot-audit-log"
+import { touchBotRefreshContextForAuditEventStatement } from "../../src/db/queries/community/bot"
+import { communityBotActivityEvent } from "../../src/db/community-schema"
import type { Database } from "../../src/db"
-import { BotAuditEventSchema, HostBotAuditEventFrameSchema } from "../../src/schemas"
+import {
+ BotAuditEventAckFrameSchema,
+ BotAuditEventSchema,
+ HostBotAuditEventFrameSchema,
+} from "../../src/schemas"
/**
* Smoke test — verifies the bot-audit-log query module exports the documented
@@ -42,7 +48,8 @@ describe("listOwnedBotActivityEvents", () => {
id TEXT PRIMARY KEY,
isBot INTEGER NOT NULL DEFAULT 0,
ownerUserId TEXT,
- deletedAt TEXT
+ deletedAt TEXT,
+ lastRefreshContextAt TEXT
);
CREATE TABLE community_bot_activity_event (
id TEXT PRIMARY KEY,
@@ -55,6 +62,20 @@ describe("listOwnedBotActivityEvents", () => {
);
`)
db = drizzle(sqlite) as unknown as Database
+ ;(db as any).batch = (
+ statements: Array<{ toSQL: () => { sql: string; params: unknown[] } }>,
+ ) => sqlite.transaction(() =>
+ statements.map((statement) => {
+ const query = statement.toSQL()
+ const prepared = sqlite.prepare(query.sql)
+ if (!prepared.reader) return prepared.run(...query.params)
+ return prepared.all(...query.params).map((row: any) => {
+ if (!("created_at" in row)) return row
+ const { created_at: createdAt, ...rest } = row
+ return { ...rest, createdAt }
+ })
+ }),
+ )()
const insertUser = sqlite.prepare(
"INSERT INTO user (id, isBot, ownerUserId, deletedAt) VALUES (?, ?, ?, ?)",
@@ -152,6 +173,121 @@ describe("listOwnedBotActivityEvents", () => {
}),
).resolves.toBeNull()
})
+
+ it("atomically inserts an idle reset and stamps Awake exactly once across a retry", async () => {
+ const eventId = "bae_idle_atomic"
+ const firstCreatedAt = "2026-08-25T14:00:00.000Z"
+ const inserted = await q.insertBotActivityEventAndPrune(
+ db,
+ {
+ id: eventId,
+ botId: "bot_1",
+ kind: "session_reset",
+ payload: JSON.stringify({ trigger: "idle_timeout" }),
+ createdAt: firstCreatedAt,
+ },
+ [touchBotRefreshContextForAuditEventStatement(
+ db,
+ "bot_1",
+ eventId,
+ firstCreatedAt,
+ )],
+ )
+ expect(inserted).toEqual({ id: eventId, createdAt: firstCreatedAt })
+ expect(sqlite.prepare(
+ "SELECT lastRefreshContextAt FROM user WHERE id = 'bot_1'",
+ ).get()).toEqual({ lastRefreshContextAt: firstCreatedAt })
+
+ const retryCreatedAt = "2026-08-25T14:05:00.000Z"
+ const duplicate = await q.insertBotActivityEventAndPrune(
+ db,
+ {
+ id: eventId,
+ botId: "bot_1",
+ kind: "session_reset",
+ payload: JSON.stringify({ trigger: "idle_timeout" }),
+ createdAt: retryCreatedAt,
+ },
+ [touchBotRefreshContextForAuditEventStatement(
+ db,
+ "bot_1",
+ eventId,
+ retryCreatedAt,
+ )],
+ )
+ expect(duplicate).toBeNull()
+ expect(sqlite.prepare(
+ "SELECT count(*) AS count FROM community_bot_activity_event WHERE id = ?",
+ ).get(eventId)).toEqual({ count: 1 })
+ expect(sqlite.prepare(
+ "SELECT lastRefreshContextAt FROM user WHERE id = 'bot_1'",
+ ).get()).toEqual({ lastRefreshContextAt: firstCreatedAt })
+ })
+
+ it("does not regress Awake when an older reset completion arrives late", async () => {
+ const newerRefresh = "2026-08-25T16:00:00.000Z"
+ sqlite.prepare(
+ "UPDATE user SET lastRefreshContextAt = ? WHERE id = 'bot_1'",
+ ).run(newerRefresh)
+ const eventId = "bae_delayed_older_reset"
+ const occurredAt = "2026-08-25T14:00:00.000Z"
+
+ await expect(q.insertBotActivityEventAndPrune(
+ db,
+ {
+ id: eventId,
+ botId: "bot_1",
+ kind: "session_reset",
+ payload: JSON.stringify({ trigger: "idle_timeout" }),
+ createdAt: occurredAt,
+ },
+ [touchBotRefreshContextForAuditEventStatement(db, "bot_1", eventId, occurredAt)],
+ )).resolves.toEqual({ id: eventId, createdAt: occurredAt })
+ expect(sqlite.prepare(
+ "SELECT lastRefreshContextAt FROM user WHERE id = 'bot_1'",
+ ).get()).toEqual({ lastRefreshContextAt: newerRefresh })
+ })
+
+ it("rolls back the audit insert and Awake stamp when any statement in the batch fails", async () => {
+ sqlite.prepare(`
+ INSERT INTO community_bot_activity_event
+ (id, bot_id, kind, payload, created_at)
+ VALUES ('bae_collision', 'bot_1', 'tool_call', '{}', '2026-08-25T13:00:00.000Z')
+ `).run()
+ const eventId = "bae_atomic_failure"
+ const createdAt = "2026-08-25T14:00:00.000Z"
+ const failingStatement = (db as any)
+ .insert(communityBotActivityEvent)
+ .values({
+ id: "bae_collision",
+ botId: "bot_1",
+ kind: "tool_call",
+ payload: "{}",
+ createdAt,
+ })
+
+ await expect(q.insertBotActivityEventAndPrune(
+ db,
+ {
+ id: eventId,
+ botId: "bot_1",
+ kind: "session_reset",
+ payload: JSON.stringify({ trigger: "idle_timeout" }),
+ createdAt,
+ },
+ [
+ touchBotRefreshContextForAuditEventStatement(db, "bot_1", eventId, createdAt),
+ failingStatement,
+ ],
+ )).rejects.toThrow(/UNIQUE constraint failed/)
+
+ expect(sqlite.prepare(
+ "SELECT count(*) AS count FROM community_bot_activity_event WHERE id = ?",
+ ).get(eventId)).toEqual({ count: 0 })
+ expect(sqlite.prepare(
+ "SELECT lastRefreshContextAt FROM user WHERE id = 'bot_1'",
+ ).get()).toEqual({ lastRefreshContextAt: null })
+ })
})
describe("BotAuditEventSchema — payload discriminated union", () => {
@@ -239,6 +375,16 @@ describe("BotAuditEventSchema — payload discriminated union", () => {
})
expect(r.success).toBe(true)
})
+ it.each(["single", "reset_all", "idle_timeout"])(
+ "accepts session_reset trigger=%s",
+ (trigger) => {
+ const r = BotAuditEventSchema.safeParse({
+ kind: "session_reset",
+ payload: { trigger },
+ })
+ expect(r.success).toBe(true)
+ },
+ )
it("rejects an error payload with a bad scope", () => {
const r = BotAuditEventSchema.safeParse({
kind: "error",
@@ -289,4 +435,37 @@ describe("HostBotAuditEventFrameSchema", () => {
})
expect(r.success).toBe(false)
})
+ it("requires a stable eventId and durable completion time for idle_timeout resets", () => {
+ const withoutId = HostBotAuditEventFrameSchema.safeParse({
+ type: "bot_audit_event",
+ agentId: "bot_1",
+ event: { kind: "session_reset", payload: { trigger: "idle_timeout" } },
+ })
+ const withId = HostBotAuditEventFrameSchema.safeParse({
+ type: "bot_audit_event",
+ eventId: "bae_reset_1",
+ occurredAt: "2026-08-25T14:00:00.000Z",
+ agentId: "bot_1",
+ event: { kind: "session_reset", payload: { trigger: "idle_timeout" } },
+ })
+ const withoutOccurredAt = HostBotAuditEventFrameSchema.safeParse({
+ type: "bot_audit_event",
+ eventId: "bae_reset_1",
+ agentId: "bot_1",
+ event: { kind: "session_reset", payload: { trigger: "idle_timeout" } },
+ })
+ expect(withoutId.success).toBe(false)
+ expect(withoutOccurredAt.success).toBe(false)
+ expect(withId.success).toBe(true)
+ })
+ it("accepts only a strict audit acknowledgement with an eventId", () => {
+ expect(BotAuditEventAckFrameSchema.safeParse({
+ type: "bot_audit_event_ack",
+ eventId: "bae_reset_1",
+ }).success).toBe(true)
+ expect(BotAuditEventAckFrameSchema.safeParse({
+ type: "bot_audit_event_ack",
+ eventId: "",
+ }).success).toBe(false)
+ })
})
diff --git a/src/ws-do/src/ws-durable/machine-frames.ts b/src/ws-do/src/ws-durable/machine-frames.ts
index 0461fe053..3dd1c4eb6 100644
--- a/src/ws-do/src/ws-durable/machine-frames.ts
+++ b/src/ws-do/src/ws-durable/machine-frames.ts
@@ -71,6 +71,7 @@ export async function handleCommunityMachineMessage(
)) return
if (await handleAuditFrame(
context,
+ ws,
parsed,
identity,
)) return
diff --git a/src/ws-do/src/ws-durable/machine-telemetry.test.ts b/src/ws-do/src/ws-durable/machine-telemetry.test.ts
index 79ca63fdd..2ac9439f1 100644
--- a/src/ws-do/src/ws-durable/machine-telemetry.test.ts
+++ b/src/ws-do/src/ws-durable/machine-telemetry.test.ts
@@ -46,6 +46,7 @@ import {
mockStubFetch,
mockToSummary,
mockTouchBotRefreshContext,
+ mockTouchBotRefreshContextForAuditEventStatement,
mockTouchMachineHeartbeat,
mockUpdateProfile,
mockUpsertMachineByMachineId,
@@ -469,9 +470,114 @@ describe("WebSocketDurableObject", () => {
beforeEach(() => {
mockGetBotBindingWithOwner.mockReset()
mockInsertBotActivityEventAndPrune.mockReset()
+ mockTouchBotRefreshContext.mockReset().mockResolvedValue(undefined)
+ mockTouchBotRefreshContextForAuditEventStatement.mockReset().mockReturnValue({ __stmt: "touch-awake" })
mockStubFetch.mockClear()
})
+ it("preserves the durable completion time when a reset is replayed two hours late", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBindingWithOwner.mockResolvedValue({
+ machineId: "cm_1",
+ runtime: "codex",
+ ownerUserId: "owner_1",
+ name: "Bot",
+ discriminator: "0007",
+ })
+ mockInsertBotActivityEventAndPrune.mockImplementation(async (_db, data) => ({
+ id: data.id,
+ createdAt: data.createdAt,
+ }))
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+ const occurredAt = new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString()
+
+ await durable.webSocketMessage(
+ ws as any,
+ JSON.stringify({
+ type: "bot_audit_event",
+ eventId: "bae_idle_reset",
+ occurredAt,
+ agentId: "bot_1",
+ sessionId: null,
+ launchId: null,
+ event: { kind: "session_reset", payload: { trigger: "idle_timeout" } },
+ }),
+ )
+
+ const [, insertData, extraStatements] = mockInsertBotActivityEventAndPrune.mock.calls[0]!
+ expect(insertData).toEqual({
+ id: "bae_idle_reset",
+ botId: "bot_1",
+ sessionId: null,
+ launchId: null,
+ kind: "session_reset",
+ payload: JSON.stringify({ trigger: "idle_timeout" }),
+ createdAt: occurredAt,
+ })
+ expect(mockTouchBotRefreshContextForAuditEventStatement).toHaveBeenCalledWith(
+ expect.anything(),
+ "bot_1",
+ "bae_idle_reset",
+ insertData.createdAt,
+ )
+ expect(extraStatements).toEqual([{ __stmt: "touch-awake" }])
+ const call = mockStubFetch.mock.calls.find((c: any[]) =>
+ (c[0] as Request).url.endsWith("/community-broadcast"),
+ )
+ expect(call).toBeDefined()
+ expect(JSON.parse(await (call![0] as Request).clone().text())).toMatchObject({
+ type: "community:bot.audit_event",
+ botId: "bot_1",
+ id: "bae_idle_reset",
+ kind: "session_reset",
+ payload: { trigger: "idle_timeout" },
+ createdAt: insertData.createdAt,
+ })
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({
+ type: "bot_audit_event_ack",
+ eventId: "bae_idle_reset",
+ }))
+ })
+
+ it("rejects an idle-reset completion timestamp beyond the future-skew bound", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({
+ type: "bot_audit_event",
+ eventId: "bae_future_reset",
+ occurredAt: new Date(Date.now() + 6 * 60 * 1000).toISOString(),
+ agentId: "bot_1",
+ event: { kind: "session_reset", payload: { trigger: "idle_timeout" } },
+ }))
+
+ expect(mockGetBotBindingWithOwner).not.toHaveBeenCalled()
+ expect(mockInsertBotActivityEventAndPrune).not.toHaveBeenCalled()
+ expect(ws.send).not.toHaveBeenCalled()
+ })
+
it("inserts + prunes atomically and notifies the OWNER only when the machine owns the bot", async () => {
const { durable, store } = createDO()
store.set("community-machine-identity", {
@@ -490,6 +596,7 @@ describe("WebSocketDurableObject", () => {
id: "bae_abc",
createdAt: "2025-01-01T00:00:00.000Z",
})
+ expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
const ws = createMockWebSocket()
ws.serializeAttachment({
@@ -518,6 +625,7 @@ describe("WebSocketDurableObject", () => {
kind: "tool_call",
payload: JSON.stringify({ name: "Read" }),
}),
+ [],
)
// Owner is notified via notifyUserDO — request goes to `user:owner_1`
// and the payload carries the full audit event including createdAt
@@ -575,6 +683,7 @@ describe("WebSocketDurableObject", () => {
await durable.webSocketMessage(ws as any, frame)
expect(mockInsertBotActivityEventAndPrune).not.toHaveBeenCalled()
+ expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
expect(mockStubFetch).not.toHaveBeenCalled()
})
@@ -638,10 +747,50 @@ describe("WebSocketDurableObject", () => {
})
await durable.webSocketMessage(ws as any, frame)
+ expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
+ expect(mockStubFetch).not.toHaveBeenCalled()
+ })
+
+ it("acks an idempotent idle-reset retry without a second Awake write or broadcast", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockGetBotBindingWithOwner.mockResolvedValue({
+ machineId: "cm_1",
+ runtime: "codex",
+ ownerUserId: "owner_1",
+ name: "Bot",
+ discriminator: "0007",
+ })
+ mockInsertBotActivityEventAndPrune.mockResolvedValue(null)
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({
+ type: "bot_audit_event",
+ eventId: "bae_idle_reset",
+ occurredAt: new Date().toISOString(),
+ agentId: "bot_1",
+ event: { kind: "session_reset", payload: { trigger: "idle_timeout" } },
+ }))
+
+ expect(mockInsertBotActivityEventAndPrune).toHaveBeenCalledOnce()
expect(mockStubFetch).not.toHaveBeenCalled()
+ expect(ws.send).toHaveBeenCalledExactlyOnceWith(JSON.stringify({
+ type: "bot_audit_event_ack",
+ eventId: "bae_idle_reset",
+ }))
})
- it("drops the frame with phase='write' when the insert throws — socket stays open, no fan-out", async () => {
+ it("keeps a failed atomic idle-reset batch unacked with no fan-out", async () => {
// This is the ws_frame_dropped_write category — the audit-loss SLO
// signal. The DO must NOT close the socket, and no owner fan-out
// should be emitted (the row was never persisted).
@@ -670,12 +819,15 @@ describe("WebSocketDurableObject", () => {
const frame = JSON.stringify({
type: "bot_audit_event",
+ eventId: "bae_idle_reset",
+ occurredAt: new Date().toISOString(),
agentId: "bot_1",
- event: { kind: "tool_call", payload: { name: "Read" } },
+ event: { kind: "session_reset", payload: { trigger: "idle_timeout" } },
})
await durable.webSocketMessage(ws as any, frame)
expect(mockStubFetch).not.toHaveBeenCalled()
+ expect(ws.send).not.toHaveBeenCalled()
expect(ws.close as ReturnType<typeof vi.fn>).not.toHaveBeenCalled()
})
})
diff --git a/src/ws-do/src/ws-durable/machine-telemetry.ts b/src/ws-do/src/ws-durable/machine-telemetry.ts
index 471e49aeb..64bbf1e8f 100644
--- a/src/ws-do/src/ws-durable/machine-telemetry.ts
+++ b/src/ws-do/src/ws-durable/machine-telemetry.ts
@@ -20,6 +20,8 @@ import {
notifyUserDO,
} from "./presence-typing"
+const IDLE_RESET_MAX_FUTURE_SKEW_MS = 5 * 60 * 1000
+
/**
* Telemetry handlers are deliberately independent first-match branches. Each
* returns false only when its schema does not recognize the frame; once a
@@ -173,9 +175,10 @@ export async function handleTypingStopFrame(
* Serialization failures are not persistence loss and remain outside the
* `ws_frame_dropped_write` SLO; binding failures do too. Only the insert path
* uses the audit-write category, and successful rows notify the owner alone.
- * Insert and rolling prune stay atomic in the query layer. The server-stamped
- * row id and creation time are authoritative; daemon timestamps never enter
- * the persisted or outbound event. A null insert produces no notification.
+ * Insert, rolling prune, and the guarded Awake stamp stay atomic in the query
+ * layer. Ordinary telemetry uses server time; idle reset uses its authenticated,
+ * validated durable barrier time so delayed replay preserves product meaning.
+ * A null insert produces no notification but still receives an idempotent ack.
* This path must never use the general presence audience because per-bot
* activity is private to the owner.
* The stored payload remains a JSON string for the audit query while the
@@ -184,6 +187,7 @@ export async function handleTypingStopFrame(
*/
export async function handleAuditFrame(
context: WsDurableContext,
+ ws: WebSocket,
parsed: unknown,
identity: CommunityMachineIdentity,
): Promise<boolean> {
@@ -191,6 +195,22 @@ export async function handleAuditFrame(
if (!auditParse.success) return false
const frame = auditParse.data
+ const isIdleReset =
+ frame.event.kind === "session_reset" &&
+ frame.event.payload.trigger === "idle_timeout"
+ if (
+ isIdleReset
+ && Date.parse(frame.occurredAt!) > Date.now() + IDLE_RESET_MAX_FUTURE_SKEW_MS
+ ) {
+ context.log.warn("ws_frame_dropped", {
+ category: "ws_frame_dropped",
+ frame_type: "bot_audit_event",
+ phase: "future_occurred_at",
+ agentId: frame.agentId,
+ machineId: identity.machineId,
+ })
+ return true
+ }
let payload: string
try {
payload = JSON.stringify(frame.event.payload)
@@ -217,24 +237,45 @@ export async function handleAuditFrame(
),
isMatch: (binding) => binding.machineId === identity.machineId,
write: async (binding) => {
- const inserted = await queries.communityBotAuditLog.insertBotActivityEventAndPrune(db, {
- botId: frame.agentId,
- sessionId: frame.sessionId ?? null,
- launchId: frame.launchId ?? null,
- kind: frame.event.kind,
- payload,
- })
- if (!inserted) return
- await notifyUserDO(context, binding.ownerUserId, {
- type: WS_EVENTS.BOT_AUDIT_EVENT,
- botId: frame.agentId,
- id: inserted.id,
- kind: frame.event.kind,
- payload: frame.event.payload,
- sessionId: frame.sessionId ?? null,
- launchId: frame.launchId ?? null,
- createdAt: inserted.createdAt,
- }).catch(() => { })
+ const createdAt = isIdleReset
+ ? new Date(Date.parse(frame.occurredAt!)).toISOString()
+ : new Date().toISOString()
+ const extraStatements = isIdleReset
+ ? [queries.communityBot.touchBotRefreshContextForAuditEventStatement(
+ db,
+ frame.agentId,
+ frame.eventId!,
+ createdAt,
+ )]
+ : []
+ const inserted = await queries.communityBotAuditLog.insertBotActivityEventAndPrune(
+ db,
+ {
+ ...(frame.eventId ? { id: frame.eventId } : {}),
+ botId: frame.agentId,
+ sessionId: frame.sessionId ?? null,
+ launchId: frame.launchId ?? null,
+ kind: frame.event.kind,
+ payload,
+ ...(isIdleReset ? { createdAt } : {}),
+ },
+ extraStatements,
+ )
+ if (inserted) {
+ await notifyUserDO(context, binding.ownerUserId, {
+ type: WS_EVENTS.BOT_AUDIT_EVENT,
+ botId: frame.agentId,
+ id: inserted.id,
+ kind: frame.event.kind,
+ payload: frame.event.payload,
+ sessionId: frame.sessionId ?? null,
+ launchId: frame.launchId ?? null,
+ createdAt: inserted.createdAt,
+ }).catch(() => { })
+ }
+ if (frame.eventId) {
+ ws.send(JSON.stringify({ type: "bot_audit_event_ack", eventId: frame.eventId }))
+ }
},
})
return true
diff --git a/src/ws-do/src/ws-durable/test-harness.ts b/src/ws-do/src/ws-durable/test-harness.ts
index 521479990..b29ea4d46 100644
--- a/src/ws-do/src/ws-durable/test-harness.ts
+++ b/src/ws-do/src/ws-durable/test-harness.ts
@@ -118,12 +118,13 @@ export const mockListBotsForMachine = vi.fn<(db: unknown, machineId: string) =>
export const mockIsBotOnline = vi.fn<(db: unknown, botUserId: string) => Promise<boolean>>().mockResolvedValue(false)
export const mockGetBotBinding = vi.fn<(db: unknown, botId: string) => Promise<{ machineId: string; runtime: string } | null>>().mockResolvedValue(null)
export const mockGetBotBindingWithOwner = vi.fn<(db: unknown, botId: string) => Promise<{ machineId: string; runtime: string; ownerUserId: string; name: string; discriminator: string } | null>>().mockResolvedValue(null)
-export const mockInsertBotActivityEventAndPrune = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
+export const mockInsertBotActivityEventAndPrune = vi.fn<(db: unknown, data: any, extraStatements?: unknown[]) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
export const mockInsertBotAuditSessionReset = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
export const mockInsertBotAuditNap = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
export const mockInsertBotAuditModelChanged = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
export const mockInsertBotAuditProviderChanged = vi.fn<(db: unknown, data: unknown) => Promise<{ id: string; createdAt: string } | null>>().mockResolvedValue(null)
export const mockTouchBotRefreshContext = vi.fn<(db: unknown, botId: string, now: string) => Promise<void>>().mockResolvedValue(undefined)
+export const mockTouchBotRefreshContextForAuditEventStatement = vi.fn().mockReturnValue({ __stmt: "touch-awake" })
export const mockUpdateProfile = vi
.fn<(db: unknown, userId: string, data: { statusEmoji?: string | null; statusText?: string | null }) => Promise<unknown>>()
.mockResolvedValue({})
@@ -280,7 +281,7 @@ vi.mock("@alook/shared", async () => {
}
const HostBotAuditEventFrameSchema = {
safeParse(v: unknown) {
- const m = v as { type?: unknown; agentId?: unknown; sessionId?: unknown; launchId?: unknown; event?: unknown }
+ const m = v as { type?: unknown; eventId?: unknown; occurredAt?: unknown; agentId?: unknown; sessionId?: unknown; launchId?: unknown; event?: unknown }
if (m?.type !== "bot_audit_event") return { success: false } as const
if (typeof m.agentId !== "string" || m.agentId.length === 0) return { success: false } as const
const ev = m.event as { kind?: unknown; payload?: unknown }
@@ -293,11 +294,22 @@ vi.mock("@alook/shared", async () => {
else if (kind === "tool_call") ok = typeof payload.name === "string"
else if (kind === "thinking")
ok = typeof payload.text === "string" && typeof payload.truncated === "boolean" && typeof payload.chars === "number"
+ else if (kind === "session_reset")
+ ok = payload.trigger === "single" || payload.trigger === "reset_all" || payload.trigger === "idle_timeout"
+ if (kind === "session_reset" && payload.trigger === "idle_timeout") {
+ ok = ok
+ && typeof m.eventId === "string"
+ && m.eventId.length > 0
+ && typeof m.occurredAt === "string"
+ && Number.isFinite(Date.parse(m.occurredAt))
+ }
if (!ok) return { success: false } as const
return {
success: true as const,
data: {
type: "bot_audit_event" as const,
+ eventId: typeof m.eventId === "string" ? m.eventId : undefined,
+ occurredAt: typeof m.occurredAt === "string" ? m.occurredAt : undefined,
agentId: m.agentId,
sessionId: typeof m.sessionId === "string" ? m.sessionId : m.sessionId === null ? null : undefined,
launchId: typeof m.launchId === "string" ? m.launchId : m.launchId === null ? null : undefined,
@@ -474,6 +486,8 @@ vi.mock("@alook/shared", async () => {
getBotBinding: (...a: [unknown, string]) => mockGetBotBinding(...a),
getBotBindingWithOwner: (...a: [unknown, string]) => mockGetBotBindingWithOwner(...a),
touchBotRefreshContext: (...a: [unknown, string, string]) => mockTouchBotRefreshContext(...a),
+ touchBotRefreshContextForAuditEventStatement: (...a: [unknown, string, string, string]) =>
+ mockTouchBotRefreshContextForAuditEventStatement(...a),
},
communityBotAuditLog: {
insertBotActivityEventAndPrune: (...a: any[]) => mockInsertBotActivityEventAndPrune(...a),