Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

Fix daemon inbox timeline observation (#490)

Gustavo Yef1090ebe2cf1
diff --git a/src/daemon/src/credentials/credentialProxy.test.ts b/src/daemon/src/credentials/credentialProxy.test.ts
index d1fd434e3..99fe6e286 100644
--- a/src/daemon/src/credentials/credentialProxy.test.ts
+++ b/src/daemon/src/credentials/credentialProxy.test.ts
@@ -1,6 +1,7 @@
import { describe, it, expect, afterEach, vi } from "vitest";
import * as http from "http";
import * as fs from "fs";
+import { gzipSync } from "node:zlib";
import {
CredentialBroker,
DEFAULT_CAPABILITY_RESOLVER,
@@ -20,11 +21,16 @@ interface SeenRequest {
path?: string;
contentLength?: string;
transferEncoding?: string;
+ acceptEncoding?: string;
body?: string;
}
/** A throwaway upstream that records what headers + path the proxy forwards. */
-async function startUpstream(): Promise<{ url: string; seen: SeenRequest[]; close: () => Promise<void> }> {
+async function startUpstream(response: {
+ status?: number;
+ headers?: http.OutgoingHttpHeaders;
+ body?: string | Buffer;
+} = {}): Promise<{ url: string; seen: SeenRequest[]; close: () => Promise<void> }> {
const seen: SeenRequest[] = [];
const server = http.createServer((req, res) => {
const chunks: Buffer[] = [];
@@ -39,10 +45,14 @@ async function startUpstream(): Promise<{ url: string; seen: SeenRequest[]; clos
path: req.url,
contentLength: req.headers["content-length"],
transferEncoding: req.headers["transfer-encoding"],
+ acceptEncoding: req.headers["accept-encoding"],
body: Buffer.concat(chunks).toString(),
});
- res.writeHead(200, { "content-type": "application/json" });
- res.end(JSON.stringify({ ok: true }));
+ res.writeHead(response.status ?? 200, {
+ "content-type": "application/json",
+ ...response.headers,
+ });
+ res.end(response.body ?? JSON.stringify({ ok: true }));
});
});
await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r()));
@@ -55,10 +65,10 @@ async function startUpstream(): Promise<{ url: string; seen: SeenRequest[]; clos
};
}
-async function post(url: string, voucher: string, path: string) {
+async function post(url: string, voucher: string, path: string, headers: Record<string, string> = {}) {
const res = await fetch(`${url}${path}`, {
method: "POST",
- headers: { Authorization: `Bearer ${voucher}`, "content-type": "application/json" },
+ headers: { Authorization: `Bearer ${voucher}`, "content-type": "application/json", ...headers },
body: JSON.stringify({ hi: 1 }),
});
return { status: res.status, body: await res.text() };
@@ -611,10 +621,7 @@ describe("startCredentialProxy (zero-trust end to end)", () => {
const p = await post(proxy.url, reg.voucher, "/api/community/users/me/inbox/pull");
expect(p.status).toBe(200);
// startUpstream() returns { ok: true } (no `messages`), so the callback
- // still receives a call attempt — it just doesn't call the handler with
- // a non-empty message list. What we care about is that it saw the pull
- // path and attempted parsing (proving the guard was true here vs. false
- // above).
+ // does not fire with a message list.
});
it("onInboxPullResponse fires for the canonical fold path users/me/inbox/pull, but NOT snapshot", async () => {
@@ -659,6 +666,210 @@ describe("startCredentialProxy (zero-trust end to end)", () => {
expect(seen).toEqual([]);
});
+ it("forces identity upstream for canonical inbox pull and observes a non-empty response exactly once", async () => {
+ const messages = [{ seq: "#1", channel: "/s#0001/c", sender: "@a#0001", content: { text: "hello" } }];
+ const body = JSON.stringify({ messages });
+ const upstream = await startUpstream({ body });
+ upstreamClose = upstream.close;
+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });
+ const onInboxPullResponse = vi.fn();
+ const onInboxPullObservationError = vi.fn();
+ proxy = await startCredentialProxy(broker, { onInboxPullResponse, onInboxPullObservationError });
+ const reg = broker.mint("agent-1", "l", ["read"], REAL_KEY);
+
+ const response = await post(
+ proxy.url,
+ reg.voucher,
+ "/api/community/users/me/inbox/pull",
+ { "accept-encoding": "gzip, deflate" },
+ );
+
+ expect(response).toEqual({ status: 200, body });
+ expect(upstream.seen[0]?.acceptEncoding).toBe("identity");
+ expect(onInboxPullResponse).toHaveBeenCalledTimes(1);
+ expect(onInboxPullResponse).toHaveBeenCalledWith("agent-1", messages, undefined);
+ expect(onInboxPullObservationError).not.toHaveBeenCalled();
+ });
+
+ it("preserves compression negotiation for non-pull and wrong-method lookalike routes", async () => {
+ const upstream = await startUpstream({ body: JSON.stringify({ messages: [{ seq: "#1" }] }) });
+ upstreamClose = upstream.close;
+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });
+ const onInboxPullResponse = vi.fn();
+ proxy = await startCredentialProxy(broker, { onInboxPullResponse });
+ const reg = broker.mint("agent-1", "l", ["read"], REAL_KEY);
+
+ await post(
+ proxy.url,
+ reg.voucher,
+ "/api/community/users/me/inbox/snapshot",
+ { "accept-encoding": "gzip, deflate" },
+ );
+ const getResponse = await fetch(`${proxy.url}/api/community/users/me/inbox/pull`, {
+ headers: {
+ authorization: `Bearer ${reg.voucher}`,
+ "accept-encoding": "deflate",
+ },
+ });
+ await getResponse.arrayBuffer();
+
+ expect(upstream.seen.map((request) => request.acceptEncoding)).toEqual(["gzip, deflate", "deflate"]);
+ expect(onInboxPullResponse).not.toHaveBeenCalled();
+ });
+
+ it("forwards an empty successful pull without observing or warning", async () => {
+ const body = JSON.stringify({ messages: [] });
+ const upstream = await startUpstream({ body });
+ upstreamClose = upstream.close;
+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });
+ const onInboxPullResponse = vi.fn();
+ const onInboxPullObservationError = vi.fn();
+ proxy = await startCredentialProxy(broker, { onInboxPullResponse, onInboxPullObservationError });
+ const reg = broker.mint("agent-1", "l", ["read"], REAL_KEY);
+
+ const response = await post(proxy.url, reg.voucher, "/api/community/users/me/inbox/pull");
+
+ expect(response).toEqual({ status: 200, body });
+ expect(onInboxPullResponse).not.toHaveBeenCalled();
+ expect(onInboxPullObservationError).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ {
+ name: "unexpected gzip",
+ body: gzipSync(JSON.stringify({ messages: [{ seq: "#1", content: { text: "private gzip body" } }] })),
+ headers: { "content-encoding": "gzip" },
+ expectedBody: JSON.stringify({ messages: [{ seq: "#1", content: { text: "private gzip body" } }] }),
+ reason: "unexpected_content_encoding",
+ contentEncoding: "gzip",
+ },
+ {
+ name: "invalid JSON",
+ body: "private invalid json body",
+ headers: {},
+ expectedBody: "private invalid json body",
+ reason: "invalid_json",
+ contentEncoding: "identity",
+ },
+ {
+ name: "missing messages",
+ body: JSON.stringify({ secret: "private missing-shape body" }),
+ headers: {},
+ expectedBody: JSON.stringify({ secret: "private missing-shape body" }),
+ reason: "invalid_inbox_shape",
+ contentEncoding: "identity",
+ },
+ {
+ name: "non-array messages",
+ body: JSON.stringify({ messages: { secret: "private wrong-shape body" } }),
+ headers: {},
+ expectedBody: JSON.stringify({ messages: { secret: "private wrong-shape body" } }),
+ reason: "invalid_inbox_shape",
+ contentEncoding: "identity",
+ },
+ ])("forwards $name unchanged and emits one bounded observation failure", async ({
+ body,
+ headers,
+ expectedBody,
+ reason,
+ contentEncoding,
+ }) => {
+ const upstream = await startUpstream({ body, headers });
+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });
+ const onInboxPullResponse = vi.fn();
+ const onInboxPullObservationError = vi.fn();
+ const runningProxy = await startCredentialProxy(broker, { onInboxPullResponse, onInboxPullObservationError });
+ const reg = broker.mint("agent-1", "l", ["read"], REAL_KEY);
+ try {
+ const response = await post(runningProxy.url, reg.voucher, "/api/community/users/me/inbox/pull");
+ expect(response).toEqual({ status: 200, body: expectedBody });
+ expect(onInboxPullResponse).not.toHaveBeenCalled();
+ expect(onInboxPullObservationError).toHaveBeenCalledTimes(1);
+ expect(onInboxPullObservationError).toHaveBeenCalledWith({
+ agentId: "agent-1",
+ reason,
+ contentEncoding,
+ });
+ const warning = JSON.stringify(onInboxPullObservationError.mock.calls);
+ expect(warning).not.toContain("private");
+ expect(warning).not.toContain(REAL_KEY);
+ expect(warning).not.toContain(reg.voucher);
+ } finally {
+ await runningProxy.close();
+ await upstream.close();
+ }
+ });
+
+ it("keeps non-2xx inbox responses transparent and outside observation", async () => {
+ const body = JSON.stringify({ error: "private upstream failure" });
+ const upstream = await startUpstream({ status: 503, body });
+ upstreamClose = upstream.close;
+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });
+ const onInboxPullResponse = vi.fn();
+ const onInboxPullObservationError = vi.fn();
+ proxy = await startCredentialProxy(broker, { onInboxPullResponse, onInboxPullObservationError });
+ const reg = broker.mint("agent-1", "l", ["read"], REAL_KEY);
+
+ const response = await post(proxy.url, reg.voucher, "/api/community/users/me/inbox/pull");
+
+ expect(response).toEqual({ status: 503, body });
+ expect(onInboxPullResponse).not.toHaveBeenCalled();
+ expect(onInboxPullObservationError).not.toHaveBeenCalled();
+ });
+
+ it("keeps a successful pull transparent when the observer throws and reports only the failure class", async () => {
+ const body = JSON.stringify({ messages: [{ seq: "#1", content: { text: "private observer body" } }] });
+ const upstream = await startUpstream({ body });
+ upstreamClose = upstream.close;
+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });
+ const onInboxPullObservationError = vi.fn();
+ proxy = await startCredentialProxy(broker, {
+ onInboxPullResponse: () => {
+ throw new Error("private observer exception");
+ },
+ onInboxPullObservationError,
+ });
+ const reg = broker.mint("agent-1", "l", ["read"], REAL_KEY);
+
+ const response = await post(proxy.url, reg.voucher, "/api/community/users/me/inbox/pull");
+
+ expect(response).toEqual({ status: 200, body });
+ expect(onInboxPullObservationError).toHaveBeenCalledWith({
+ agentId: "agent-1",
+ reason: "observer_failed",
+ contentEncoding: "identity",
+ });
+ expect(JSON.stringify(onInboxPullObservationError.mock.calls)).not.toContain("private");
+ });
+
+ it("keeps a successful pull transparent when observation setup throws", async () => {
+ const body = JSON.stringify({ messages: [{ seq: "#1" }] });
+ const upstream = await startUpstream({ body });
+ upstreamClose = upstream.close;
+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });
+ const onInboxPullResponse = vi.fn();
+ const onInboxPullObservationError = vi.fn();
+ proxy = await startCredentialProxy(broker, {
+ onInboxPullStart: () => {
+ throw new Error("private setup exception");
+ },
+ onInboxPullResponse,
+ onInboxPullObservationError,
+ });
+ const reg = broker.mint("agent-1", "l", ["read"], REAL_KEY);
+
+ const response = await post(proxy.url, reg.voucher, "/api/community/users/me/inbox/pull");
+
+ expect(response).toEqual({ status: 200, body });
+ expect(onInboxPullResponse).toHaveBeenCalledWith("agent-1", [{ seq: "#1" }], undefined);
+ expect(onInboxPullObservationError).toHaveBeenCalledWith({
+ agentId: "agent-1",
+ reason: "observer_failed",
+ contentEncoding: "identity",
+ });
+ expect(JSON.stringify(onInboxPullObservationError.mock.calls)).not.toContain("private");
+ });
+
it("captures each inbox observation token at pull start even when responses finish out of order", async () => {
const pending: http.ServerResponse[] = [];
const upstreamServer = http.createServer((_req, res) => pending.push(res));
diff --git a/src/daemon/src/credentials/credentialProxy.ts b/src/daemon/src/credentials/credentialProxy.ts
index c1bab5a7e..cbfb52d2e 100644
--- a/src/daemon/src/credentials/credentialProxy.ts
+++ b/src/daemon/src/credentials/credentialProxy.ts
@@ -310,13 +310,15 @@ export interface CredentialProxyOptions {
/** Path → capability mapping for scoping. Default `DEFAULT_CAPABILITY_RESOLVER`. */
capabilityResolver?: CapabilityResolver;
/**
- * Called after a successful inboxPull response is forwarded back to the agent.
+ * Called after a successful inboxPull response is validated and before it is
+ * forwarded back to the agent.
* The proxy knows the agentId (from voucher) and can parse the response body to
* surface the pulled messages — used by the daemon to write timeline entries
* regardless of whether the agent is an in-process stub or a real subprocess.
*/
onInboxPullStart?: (agentId: string) => unknown;
onInboxPullResponse?: (agentId: string, messages: Message[], observationToken?: unknown) => void;
+ onInboxPullObservationError?: (failure: InboxPullObservationFailure) => void;
/**
* Called once per successfully-authorized upstream proxy request, BEFORE the
* upstream is dispatched. Fires only on `verdict.ok === true` — never on
@@ -344,6 +346,20 @@ export interface CredentialProxyOptions {
upstreamTimeoutMs?: number;
}
+export type InboxPullObservationFailureReason =
+ | "unexpected_content_encoding"
+ | "invalid_json"
+ | "invalid_inbox_shape"
+ | "observer_failed";
+
+export type InboxPullContentEncoding = "identity" | "gzip" | "deflate" | "br" | "other";
+
+export interface InboxPullObservationFailure {
+ agentId: string;
+ reason: InboxPullObservationFailureReason;
+ contentEncoding: InboxPullContentEncoding;
+}
+
export interface RunningProxy {
url: string;
port: number;
@@ -355,6 +371,13 @@ function writeJson(res: http.ServerResponse, status: number, body: unknown): voi
res.end(JSON.stringify(body));
}
+function normalizeContentEncoding(value: string | string[] | undefined): InboxPullContentEncoding {
+ const normalized = (Array.isArray(value) ? value.join(",") : value ?? "").trim().toLowerCase();
+ if (!normalized || normalized === "identity") return "identity";
+ if (normalized === "gzip" || normalized === "deflate" || normalized === "br") return normalized;
+ return "other";
+}
+
function isCanonicalChannelScope(channel: string): boolean {
try {
const parsed = parseRef(channel);
@@ -468,6 +491,13 @@ export async function startCredentialProxy(
const onPull = options.onInboxPullResponse;
const onProxyRequest = options.onProxyRequest;
+ const reportInboxPullObservationError = (failure: InboxPullObservationFailure): void => {
+ try {
+ options.onInboxPullObservationError?.(failure);
+ } catch {
+ // Observational callback — never disrupt the proxy response.
+ }
+ };
const server = http.createServer((req, res) => {
const pathname = new URL(req.url ?? "/", "http://placeholder").pathname;
@@ -530,14 +560,18 @@ export async function startCredentialProxy(
// `callInboxPull` sends this full path directly, no rewrite). The flat
// `/api/inboxPull` verb is deleted (flat-delete step). inboxSnapshot is
// deliberately EXCLUDED (peek, no `{ messages }` to record).
- const isInboxPull = onPull && pathname === "/api/community/users/me/inbox/pull";
+ const isInboxPull = req.method === "POST" && pathname === "/api/community/users/me/inbox/pull";
+ const shouldObserveInboxPull = Boolean(isInboxPull && onPull);
let inboxPullObservationToken: unknown;
- if (isInboxPull) {
+ if (shouldObserveInboxPull) {
try {
inboxPullObservationToken = options.onInboxPullStart?.(reg.agentId);
} catch {
- // Observational callback — a generation snapshot failure must never
- // interrupt the agent's real inbox pull.
+ reportInboxPullObservationError({
+ agentId: reg.agentId,
+ reason: "observer_failed",
+ contentEncoding: "identity",
+ });
}
}
@@ -559,6 +593,7 @@ export async function startCredentialProxy(
outHeaders[broker.headerNames.agentId.toLowerCase()] = reg.agentId;
outHeaders[broker.headerNames.client.toLowerCase()] = broker.clientLabel;
outHeaders[broker.headerNames.capabilities.toLowerCase()] = [...reg.capabilities].join(",");
+ if (isInboxPull) outHeaders["accept-encoding"] = "identity";
// `responded` guards only against writing a second response to the
// DOWNSTREAM client (writeHead/end can't fire twice) — it does NOT gate
@@ -595,18 +630,65 @@ export async function startCredentialProxy(
};
res_.on("error", destroyResIfIncomplete);
res_.on("close", destroyResIfIncomplete);
- if (isInboxPull && res_.statusCode && res_.statusCode < 300) {
+ if (
+ shouldObserveInboxPull
+ && res_.statusCode !== undefined
+ && res_.statusCode >= 200
+ && res_.statusCode < 300
+ ) {
// Buffer the inboxPull response to surface pulled messages to the daemon.
const chunks: Buffer[] = [];
res_.on("data", (chunk: Buffer) => chunks.push(chunk));
res_.on("end", () => {
const body = Buffer.concat(chunks);
+ const contentEncoding = normalizeContentEncoding(res_.headers["content-encoding"]);
+ if (contentEncoding !== "identity") {
+ reportInboxPullObservationError({
+ agentId: reg.agentId,
+ reason: "unexpected_content_encoding",
+ contentEncoding,
+ });
+ } else {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(body.toString("utf8"));
+ } catch {
+ reportInboxPullObservationError({
+ agentId: reg.agentId,
+ reason: "invalid_json",
+ contentEncoding,
+ });
+ }
+ if (parsed !== undefined) {
+ if (
+ !parsed
+ || typeof parsed !== "object"
+ || Array.isArray(parsed)
+ || !Array.isArray((parsed as { messages?: unknown }).messages)
+ ) {
+ reportInboxPullObservationError({
+ agentId: reg.agentId,
+ reason: "invalid_inbox_shape",
+ contentEncoding,
+ });
+ } else {
+ const messages = (parsed as { messages: Message[] }).messages;
+ if (messages.length > 0) {
+ try {
+ onPull!(reg.agentId, messages, inboxPullObservationToken);
+ } catch {
+ reportInboxPullObservationError({
+ agentId: reg.agentId,
+ reason: "observer_failed",
+ contentEncoding,
+ });
+ }
+ }
+ }
+ }
+ }
res.writeHead(res_.statusCode!, res_.headers);
res.end(body);
- try {
- const parsed = JSON.parse(body.toString()) as { messages?: Message[] };
- if (parsed.messages) onPull(reg.agentId, parsed.messages, inboxPullObservationToken);
- } catch { /* best-effort */ }
});
} else {
res.writeHead(res_.statusCode ?? 502, res_.headers);
diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.ts
index d51e5f0bb..cce1ad47b 100644
--- a/src/daemon/src/daemon/createDaemon.test.ts
+++ b/src/daemon/src/daemon/createDaemon.test.ts
@@ -36,6 +36,10 @@ const timelineSweepHarness = vi.hoisted(() => {
};
});
+const credentialProxyHarness = vi.hoisted(() => ({
+ onInboxPullObservationError: undefined as ((failure: Record<string, unknown>) => void) | undefined,
+}));
+
vi.mock("../timeline/index.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../timeline/index.js")>();
return {
@@ -44,11 +48,27 @@ vi.mock("../timeline/index.js", async (importOriginal) => {
};
});
+vi.mock("../credentials/index.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../credentials/index.js")>();
+ return {
+ ...actual,
+ startCredentialProxy: (
+ ...args: Parameters<typeof actual.startCredentialProxy>
+ ): ReturnType<typeof actual.startCredentialProxy> => {
+ credentialProxyHarness.onInboxPullObservationError = args[1]?.onInboxPullObservationError as
+ | ((failure: Record<string, unknown>) => void)
+ | undefined;
+ return actual.startCredentialProxy(...args);
+ },
+ };
+});
+
const startupSweepDirs: string[] = [];
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
timelineSweepHarness.reset();
+ credentialProxyHarness.onInboxPullObservationError = undefined;
for (const dir of startupSweepDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
@@ -520,6 +540,40 @@ describe("createDaemon", () => {
await daemon.stop();
});
+ it("wires inbox observation failures to one bounded redacted daemon warning", async () => {
+ const sockets: FakeSocket[] = [];
+ const logger = stubLogger();
+ const daemon = await createDaemon({
+ machineKey: "cmk_observation_warning",
+ serverUrl: "http://localhost:9999",
+ serverWsUrl: "ws://x",
+ webSocketFactory: factory(sockets) as any,
+ runtimeReport: [],
+ driverFor: () => fakeDriver,
+ capabilities: [],
+ logger,
+ });
+
+ expect(credentialProxyHarness.onInboxPullObservationError).toBeTypeOf("function");
+ credentialProxyHarness.onInboxPullObservationError?.({
+ agentId: "agent-1",
+ reason: "invalid_json",
+ contentEncoding: "gzip",
+ body: "private message body",
+ authorization: "Bearer private-runner-key",
+ });
+
+ const warnings = logger.calls.warn.filter(([, message]) => message === "inbox pull timeline observation failed");
+ expect(warnings).toEqual([[
+ "root",
+ "inbox pull timeline observation failed",
+ [{ agentId: "agent-1", reason: "invalid_json", contentEncoding: "gzip" }],
+ ]]);
+ expect(JSON.stringify(warnings)).not.toContain("private");
+ expect(JSON.stringify(warnings)).not.toContain("Bearer");
+ await daemon.stop();
+ });
+
it("starts the timeline sweep immediately without awaiting its completion", async () => {
const sockets: FakeSocket[] = [];
const workingDirectoryBase = mkdtempSync(join(tmpdir(), "timeline-startup-"));
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index 9fb035b0e..581f04e3b 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -415,6 +415,9 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
channelRef?.recordModelSeen(agentId, messages, observationToken);
}
},
+ onInboxPullObservationError: ({ agentId, reason, contentEncoding }) => {
+ log.warn("inbox pull timeline observation failed", { agentId, reason, contentEncoding });
+ },
onMessageReminderArm: (input) =>
reminderSchedulerRef?.arm(input) ?? { armed: false, reason: "reminder_scheduler_unavailable" },
// Bot audit log — Producer B (authoritative for `alook <sub>`). Fires
diff --git a/src/daemon/src/timeline/recorder.test.ts b/src/daemon/src/timeline/recorder.test.ts
index 243d6c19b..f8fd868df 100644
--- a/src/daemon/src/timeline/recorder.test.ts
+++ b/src/daemon/src/timeline/recorder.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, afterEach } from "vitest";
+import { describe, it, expect, afterEach, vi } from "vitest";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
@@ -27,6 +27,16 @@ const msg = (seq: string, text: string): Message => ({
});
describe("createTimelineRecorder (append-only, 4-field schema)", () => {
+ it("treats an empty pull as a no-op before resolving or preparing the timeline directory", () => {
+ const timelineDirFor = vi.fn(() => {
+ throw new Error("must not resolve a directory for an empty pull");
+ });
+ const rec = createTimelineRecorder({ timelineDirFor, now: NOW });
+
+ expect(() => rec.appendEntryForAgent("agent_1", [])).not.toThrow();
+ expect(timelineDirFor).not.toHaveBeenCalled();
+ });
+
it("bakes the session id (set before the pull) into the opened entry, then accumulates responses", () => {
const dir = mkDir();
const rec = createTimelineRecorder({ timelineDirFor: () => dir, providerFor: () => "claude", now: NOW });
@@ -76,6 +86,28 @@ describe("createTimelineRecorder (append-only, 4-field schema)", () => {
expect(rows[0].agent_responses).toEqual(["reply to both"]);
});
+ it("writes a non-empty pull after local midnight only to the new day's file", () => {
+ const dir = mkDir();
+ let current = new Date("2026-06-25T12:00:00");
+ const rec = createTimelineRecorder({
+ timelineDirFor: () => dir,
+ providerFor: () => "claude",
+ now: () => current,
+ });
+ rec.setSession("agent_1", "sess-1");
+ rec.appendEntryForAgent("agent_1", [msg("#1", "before midnight")]);
+
+ current = new Date("2026-06-26T12:00:00");
+ rec.appendEntryForAgent("agent_1", [msg("#2", "after midnight")]);
+
+ const firstDay = fs.readFileSync(path.join(dir, filenameForDate(new Date("2026-06-25T12:00:00"))), "utf8");
+ const secondDay = fs.readFileSync(path.join(dir, filenameForDate(current)), "utf8");
+ expect(firstDay).toContain("before midnight");
+ expect(firstDay).not.toContain("after midnight");
+ expect(secondDay).toContain("after midnight");
+ expect(secondDay).not.toContain("before midnight");
+ });
+
it("does NOT merge when session_id differs (new session = new entry)", () => {
const dir = mkDir();
const rec = createTimelineRecorder({ timelineDirFor: () => dir, providerFor: () => "claude", now: NOW });
diff --git a/src/daemon/src/timeline/recorder.ts b/src/daemon/src/timeline/recorder.ts
index fc6405bc1..fbefcb58f 100644
--- a/src/daemon/src/timeline/recorder.ts
+++ b/src/daemon/src/timeline/recorder.ts
@@ -85,6 +85,7 @@ export function createTimelineRecorder(opts: TimelineRecorderOptions): TimelineR
sessionByAgent.set(agentId, sessionId);
},
appendEntryForAgent(agentId, messages) {
+ if (messages.length === 0) return;
const dir = dirFor(agentId);
if (!prepareTimelineDirectory(dir)) return;
appendOrMergeEntry(