Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: use agent timeline instead of session

Gus32549a915895
diff --git a/.gitignore b/.gitignore
index eddb4e4b3..4cb2d8cb3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -14,6 +14,7 @@ docs/
.dev.vars
plans/
.agents/
+.context_timeline/
.claude/
.impeccable.md
.playwright-mcp/
\ No newline at end of file
diff --git a/src/cli/daemon/agent/claude.ts b/src/cli/daemon/agent/claude.ts
index 423bd4b39..00e1c8a8e 100644
--- a/src/cli/daemon/agent/claude.ts
+++ b/src/cli/daemon/agent/claude.ts
@@ -49,6 +49,10 @@ export class ClaudeBackend implements AgentBackend {
let lastOutput = "";
let lastError = "";
let resultStatus: AgentResult["status"] = "completed";
+ let resolveSessionId: (id: string) => void;
+ const sessionIdPromise = new Promise<string>((resolve) => {
+ resolveSessionId = resolve;
+ });
const messageQueue: AgentMessage[] = [];
let messageResolve: (() => void) | null = null;
@@ -141,7 +145,10 @@ export class ClaudeBackend implements AgentBackend {
const subtype = event.subtype as string | undefined;
if (subtype === "init") {
const sid = event.session_id as string | undefined;
- if (sid) lastSessionId = sid;
+ if (sid) {
+ lastSessionId = sid;
+ resolveSessionId(sid);
+ }
}
break;
}
@@ -175,6 +182,9 @@ export class ClaudeBackend implements AgentBackend {
lastError = stderr;
}
+ // Resolve sessionId promise (fallback if system/init never fired)
+ resolveSessionId(lastSessionId);
+
messageDone = true;
if (messageResolve) {
const r = messageResolve;
@@ -210,7 +220,7 @@ export class ClaudeBackend implements AgentBackend {
},
};
- return { messages, result: resultPromise };
+ return { pid: proc.pid, messages, sessionId: sessionIdPromise, result: resultPromise };
}
}
diff --git a/src/cli/daemon/agent/codex.ts b/src/cli/daemon/agent/codex.ts
index 885e6bdef..5bfca1a23 100644
--- a/src/cli/daemon/agent/codex.ts
+++ b/src/cli/daemon/agent/codex.ts
@@ -66,6 +66,10 @@ export class CodexBackend implements AgentBackend {
let lastError = "";
let resultStatus: AgentResult["status"] = "completed";
let sessionId = "";
+ let resolveSessionId: (id: string) => void;
+ const sessionIdPromise = new Promise<string>((resolve) => {
+ resolveSessionId = resolve;
+ });
// Protocol detection state
let notificationProtocol: NotificationProtocol = "unknown";
@@ -439,6 +443,8 @@ export class CodexBackend implements AgentBackend {
sessionId = extractThreadID(threadResponse);
}
+ resolveSessionId(sessionId);
+
// 5. Send turn/start with the prompt
await sendRpc("turn/start", {
threadId: sessionId,
@@ -471,6 +477,9 @@ export class CodexBackend implements AgentBackend {
lastError = stderr;
}
+ // Resolve sessionId promise (fallback if handshake never completed)
+ resolveSessionId(sessionId);
+
messageDone = true;
if (messageResolve) {
const r = messageResolve;
@@ -506,6 +515,6 @@ export class CodexBackend implements AgentBackend {
},
};
- return { messages, result: resultPromise };
+ return { pid: proc.pid, messages, sessionId: sessionIdPromise, result: resultPromise };
}
}
diff --git a/src/cli/daemon/agent/index.ts b/src/cli/daemon/agent/index.ts
index 2c57eb0e9..6f02ea0ff 100644
--- a/src/cli/daemon/agent/index.ts
+++ b/src/cli/daemon/agent/index.ts
@@ -5,7 +5,9 @@ import { OpenCodeBackend } from "./opencode.js";
import { execSync } from "child_process";
export interface AgentSession {
+ pid: number | undefined;
messages: AsyncIterable<AgentMessage>;
+ sessionId: Promise<string>;
result: Promise<AgentResult>;
}
diff --git a/src/cli/daemon/agent/opencode.ts b/src/cli/daemon/agent/opencode.ts
index 4cb7bc595..36dd3e6f4 100644
--- a/src/cli/daemon/agent/opencode.ts
+++ b/src/cli/daemon/agent/opencode.ts
@@ -41,6 +41,10 @@ export class OpenCodeBackend implements AgentBackend {
let lastOutput = "";
let lastError = "";
let resultStatus: AgentResult["status"] = "completed";
+ let resolveSessionId: (id: string) => void;
+ const sessionIdPromise = new Promise<string>((resolve) => {
+ resolveSessionId = resolve;
+ });
const messageQueue: AgentMessage[] = [];
let messageResolve: (() => void) | null = null;
@@ -80,7 +84,10 @@ export class OpenCodeBackend implements AgentBackend {
switch (eventType) {
case "session": {
const sessionId = event.session_id as string | undefined;
- if (sessionId) lastSessionId = sessionId;
+ if (sessionId) {
+ lastSessionId = sessionId;
+ resolveSessionId(sessionId);
+ }
break;
}
@@ -166,6 +173,9 @@ export class OpenCodeBackend implements AgentBackend {
lastError = stderr;
}
+ // Resolve sessionId promise (fallback if session event never fired)
+ resolveSessionId(lastSessionId);
+
messageDone = true;
if (messageResolve) {
const r = messageResolve;
@@ -201,6 +211,6 @@ export class OpenCodeBackend implements AgentBackend {
},
};
- return { messages, result: resultPromise };
+ return { pid: proc.pid, messages, sessionId: sessionIdPromise, result: resultPromise };
}
}
diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.ts
index 879ce7f49..dcd05241b 100644
--- a/src/cli/daemon/daemon.test.ts
+++ b/src/cli/daemon/daemon.test.ts
@@ -72,6 +72,7 @@ vi.mock("./execenv/index.js", () => ({
prepare: vi.fn(() => ({
workDir: "/tmp/ws/ws1/agent1/workdir",
logFile: "/tmp/ws/ws1/agent1/agent.log",
+ timelineDir: "/tmp/ws/ws1/agent1/workdir/.context_timeline",
env: {
ALOOK_WORKSPACE_ID: "ws1",
ALOOK_AGENT_ID: "agent1",
@@ -82,6 +83,26 @@ vi.mock("./execenv/index.js", () => ({
})),
}));
+const mockInitEntryAsync = vi.fn(async () => {});
+const mockUpdateEntry = vi.fn();
+const mockCreateTimelineEntry = vi.fn((taskId: string, prompt: string, sessionId?: string, pid?: number) => ({
+ task_id: taskId,
+ session_id: sessionId || null,
+ pid: pid ?? null,
+ status: "running",
+ datetime: "2026-04-13T10:30:00-05:00",
+ type: "user_dm_message",
+ prompt,
+ steps: [],
+ response: null,
+ errmsg: null,
+}));
+vi.mock("./execenv/timeline.js", () => ({
+ initEntryAsync: (...args: any[]) => mockInitEntryAsync(...args),
+ updateEntry: (...args: any[]) => mockUpdateEntry(...args),
+ createTimelineEntry: (...args: any[]) => mockCreateTimelineEntry(...args),
+}));
+
// Capture signal handlers and prevent actual process.exit
const signalHandlers = new Map<string, (...args: any[]) => any>();
const originalOn = process.on.bind(process);
@@ -112,8 +133,199 @@ vi.spyOn(globalThis, "clearInterval").mockImplementation(((timer: any) => {
realClearInterval(timer);
}) as any);
+import { createBackend } from "./agent/index.js";
import { startDaemon } from "./daemon.js";
+describe("daemon timeline integration", () => {
+ beforeEach(() => {
+ signalHandlers.clear();
+ intervalTimers.length = 0;
+ clearedTimers.length = 0;
+ vi.clearAllMocks();
+ mockProcessExit.mockImplementation((() => {}) as any);
+ });
+
+ afterEach(() => {
+ for (const t of intervalTimers) realClearInterval(t);
+ });
+
+ function setupTaskClaim() {
+ const fakeTask = {
+ id: "t1",
+ agent_id: "a1",
+ runtime_id: "rt1",
+ conversation_id: "c1",
+ workspace_id: "ws1",
+ prompt: "do stuff",
+ status: "dispatched",
+ priority: 0,
+ dispatched_at: null,
+ started_at: null,
+ completed_at: null,
+ created_at: "2026-01-01T00:00:00Z",
+ result: null,
+ error: null,
+ agent: { name: "Agent 1", instructions: "be helpful" },
+ prior_session_id: null,
+ };
+
+ let claimed = false;
+ mockClientInstance.claimTask.mockImplementation(async () => {
+ if (!claimed) {
+ claimed = true;
+ return { task: fakeTask };
+ }
+ return { task: null };
+ });
+
+ // Mock startTask and completeTask
+ (mockClientInstance as any).startTask = vi.fn(async () => ({}));
+ (mockClientInstance as any).completeTask = vi.fn(async () => ({}));
+ (mockClientInstance as any).failTask = vi.fn(async () => ({}));
+ (mockClientInstance as any).reportMessages = vi.fn(async () => ({}));
+
+ return fakeTask;
+ }
+
+ function setupBackend(messages: any[], result: any) {
+ async function* messageIterator() {
+ for (const msg of messages) yield msg;
+ }
+
+ const mockBackend = {
+ name: "claude",
+ execute: vi.fn(() => ({
+ pid: 12345,
+ messages: messageIterator(),
+ sessionId: Promise.resolve(result.sessionId || ""),
+ result: Promise.resolve(result),
+ })),
+ };
+
+ vi.mocked(createBackend).mockReturnValue(mockBackend);
+ return mockBackend;
+ }
+
+ it("task start writes init entry to timeline", async () => {
+ setupTaskClaim();
+ setupBackend([], {
+ status: "completed",
+ output: "Done",
+ error: "",
+ durationMs: 1000,
+ sessionId: "s1",
+ });
+
+ await startDaemon();
+
+ // Wait for async task handling
+ await new Promise((r) => setTimeout(r, 50));
+
+ expect(mockCreateTimelineEntry).toHaveBeenCalledWith("t1", "do stuff", "s1", 12345);
+ expect(mockInitEntryAsync).toHaveBeenCalledWith(
+ "/tmp/ws/ws1/agent1/workdir/.context_timeline",
+ expect.objectContaining({ task_id: "t1", session_id: "s1", pid: 12345 }),
+ );
+ });
+
+ it("assistant text messages update steps array", async () => {
+ setupTaskClaim();
+ setupBackend(
+ [
+ { type: "text", content: "Looking at code..." },
+ { type: "tool-use", tool: "read", content: undefined },
+ { type: "text", content: "Found the issue." },
+ ],
+ {
+ status: "completed",
+ output: "Fixed it",
+ error: "",
+ durationMs: 2000,
+ sessionId: "s2",
+ },
+ );
+
+ await startDaemon();
+ await new Promise((r) => setTimeout(r, 50));
+
+ // Should have been called for each text message
+ const textCalls = mockUpdateEntry.mock.calls.filter(
+ (call: any[]) => {
+ // The updater is the third argument, but we check it was called for steps
+ const updater = call[2];
+ const testEntry = { steps: [] as string[], response: null };
+ updater(testEntry);
+ return testEntry.steps.length > 0;
+ }
+ );
+ expect(textCalls.length).toBe(2);
+ });
+
+ it("task completion updates response field", async () => {
+ setupTaskClaim();
+ setupBackend([], {
+ status: "completed",
+ output: "All done!",
+ error: "",
+ durationMs: 500,
+ sessionId: "s3",
+ });
+
+ await startDaemon();
+ await new Promise((r) => setTimeout(r, 50));
+
+ // Last updateEntry call should set completion fields
+ const calls = mockUpdateEntry.mock.calls;
+ const lastCall = calls[calls.length - 1];
+ const testEntry = {
+ steps: [] as string[],
+ response: null as string | null,
+ session_id: null as string | null,
+ pid: process.pid as number | null,
+ status: "running" as string,
+ errmsg: null as string | null,
+ };
+ lastCall[2](testEntry);
+ expect(testEntry.response).toBe("All done!");
+ expect(testEntry.session_id).toBe("s3");
+ expect(testEntry.pid).toBeNull();
+ expect(testEntry.status).toBe("completed");
+ });
+
+ it("failed tasks get init entry and failure fields set", async () => {
+ setupTaskClaim();
+ setupBackend([], {
+ status: "failed",
+ output: "",
+ error: "something went wrong",
+ durationMs: 100,
+ sessionId: "s4",
+ });
+
+ await startDaemon();
+ await new Promise((r) => setTimeout(r, 50));
+
+ // initEntry should have been called
+ expect(mockInitEntryAsync).toHaveBeenCalled();
+
+ // Last updateEntry call should set failure fields
+ const calls = mockUpdateEntry.mock.calls;
+ const lastCall = calls[calls.length - 1];
+ const testEntry = {
+ steps: [] as string[],
+ response: null as string | null,
+ pid: process.pid as number | null,
+ status: "running" as string,
+ errmsg: null as string | null,
+ };
+ lastCall[2](testEntry);
+ expect(testEntry.pid).toBeNull();
+ expect(testEntry.status).toBe("failed");
+ expect(testEntry.errmsg).toBe("something went wrong");
+ expect(testEntry.response).toBeNull();
+ });
+});
+
describe("daemon shutdown", () => {
beforeEach(() => {
signalHandlers.clear();
diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.ts
index e122d62df..8adbcda92 100644
--- a/src/cli/daemon/daemon.ts
+++ b/src/cli/daemon/daemon.ts
@@ -5,11 +5,11 @@ import { buildPrompt } from "./prompt.js";
import { createBackend, detectVersion } from "./agent/index.js";
import { type Task, type TaskResult, fromApiTask } from "./types.js";
import { prepare } from "./execenv/index.js";
+import { initEntryAsync, updateEntry, createTimelineEntry, localISOString } from "./execenv/timeline.js";
import { loadCLIConfigForProfile } from "../lib/config.js";
import { log } from "../lib/logger.js";
import { cmdPrefix } from "../lib/env.js";
import { createWriteStream } from "fs";
-import { join } from "path";
import { execSync } from "child_process";
interface WorkspaceState {
@@ -231,7 +231,7 @@ async function runTask(
const prompt = buildPrompt(task);
- const { workDir, logFile, env } = prepare(
+ const { workDir, logFile, timelineDir, env } = prepare(
{ workspacesRoot: config.workspacesRoot },
task,
provider,
@@ -242,9 +242,12 @@ async function runTask(
model: model || undefined,
env,
timeout: config.agentTimeout,
- resumeSessionId: task.priorSessionId,
});
+ // Context timeline — wait for session ID, then write init entry
+ const earlySessionId = await session.sessionId;
+ await initEntryAsync(timelineDir, createTimelineEntry(task.id, task.prompt, earlySessionId, session.pid));
+
const pendingMessages: {
seq: number;
type: string;
@@ -276,7 +279,7 @@ async function runTask(
logStream = createWriteStream(logFile, { flags: "a" });
logStream.write(
JSON.stringify({
- ts: new Date().toISOString(),
+ ts: localISOString(),
type: "text",
role: "user",
content: prompt,
@@ -299,11 +302,18 @@ async function runTask(
output: msg.output,
});
+ // Context timeline — record assistant text messages as steps
+ if (msg.type === "text" && msg.content) {
+ updateEntry(timelineDir, task.id, (entry) => {
+ entry.steps.push(msg.content!);
+ });
+ }
+
if (logStream) {
try {
logStream.write(
JSON.stringify({
- ts: new Date().toISOString(),
+ ts: localISOString(),
role: "assistant",
...msg,
}) + "\n",
@@ -325,6 +335,23 @@ async function runTask(
}
const result = await session.result;
+
+ // Context timeline — finalize entry
+ if (result.status === "completed") {
+ updateEntry(timelineDir, task.id, (entry) => {
+ entry.session_id = result.sessionId || null;
+ entry.pid = null;
+ entry.status = "completed";
+ entry.response = result.output || null;
+ });
+ } else {
+ updateEntry(timelineDir, task.id, (entry) => {
+ entry.pid = null;
+ entry.status = "failed";
+ entry.errmsg = result.error || "unknown error";
+ });
+ }
+
return {
status: result.status === "completed" ? "completed" : "failed",
comment: result.output || result.error,
diff --git a/src/cli/daemon/execenv/__tests__/context.test.ts b/src/cli/daemon/execenv/__tests__/context.test.ts
index 28a54d03f..0f2c02624 100644
--- a/src/cli/daemon/execenv/__tests__/context.test.ts
+++ b/src/cli/daemon/execenv/__tests__/context.test.ts
@@ -49,6 +49,24 @@ describe("buildInstructionContent", () => {
expect(content).toContain("## System");
expect(content).not.toContain("## Agent Instructions");
});
+
+ it("includes Context Timeline section with format explanation", () => {
+ const task = makeTask();
+ const content = buildInstructionContent(task);
+
+ expect(content).toContain("## Context Timeline");
+ expect(content).toContain(".context_timeline/YYYY-MM-DD.jsonl");
+ expect(content).toContain("task_id");
+ expect(content).toContain("session_id");
+ expect(content).toContain("pid");
+ expect(content).toContain("status");
+ expect(content).toContain("datetime");
+ expect(content).toContain("prompt");
+ expect(content).toContain("steps");
+ expect(content).toContain("response");
+ expect(content).toContain("errmsg");
+ expect(content).toContain("last ~20 lines");
+ });
});
describe("writeInstructionFile", () => {
diff --git a/src/cli/daemon/execenv/__tests__/filelock.test.ts b/src/cli/daemon/execenv/__tests__/filelock.test.ts
new file mode 100644
index 000000000..e0670bea5
--- /dev/null
+++ b/src/cli/daemon/execenv/__tests__/filelock.test.ts
@@ -0,0 +1,55 @@
+import { describe, it, expect, beforeEach, afterEach } from "vitest";
+import { existsSync, mkdirSync, rmSync, utimesSync } from "fs";
+import { join } from "path";
+import { tmpdir } from "os";
+import { acquireLock, releaseLock } from "../filelock.js";
+
+describe("filelock", () => {
+ let dir: string;
+ let lockPath: string;
+
+ beforeEach(() => {
+ dir = join(tmpdir(), `filelock-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
+ mkdirSync(dir, { recursive: true });
+ lockPath = join(dir, ".test.lock");
+ });
+
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ it("acquireLock creates lock directory and returns true", () => {
+ const result = acquireLock(lockPath);
+ expect(result).toBe(true);
+ expect(existsSync(lockPath)).toBe(true);
+ });
+
+ it("acquireLock returns false when already held by another", () => {
+ acquireLock(lockPath);
+ const result = acquireLock(lockPath);
+ expect(result).toBe(false);
+ });
+
+ it("stale lock (>1 hour) is auto-cleaned and re-acquired", () => {
+ mkdirSync(lockPath);
+ // Set mtime to 2 hours ago
+ const twoHoursAgo = new Date(Date.now() - 2 * 3_600_000);
+ utimesSync(lockPath, twoHoursAgo, twoHoursAgo);
+
+ const result = acquireLock(lockPath);
+ expect(result).toBe(true);
+ expect(existsSync(lockPath)).toBe(true);
+ });
+
+ it("releaseLock removes lock directory", () => {
+ acquireLock(lockPath);
+ expect(existsSync(lockPath)).toBe(true);
+
+ releaseLock(lockPath);
+ expect(existsSync(lockPath)).toBe(false);
+ });
+
+ it("releaseLock does not throw when lock does not exist", () => {
+ expect(() => releaseLock(lockPath)).not.toThrow();
+ });
+});
diff --git a/src/cli/daemon/execenv/__tests__/index.test.ts b/src/cli/daemon/execenv/__tests__/index.test.ts
index afaf9cbba..bc981fe74 100644
--- a/src/cli/daemon/execenv/__tests__/index.test.ts
+++ b/src/cli/daemon/execenv/__tests__/index.test.ts
@@ -66,6 +66,21 @@ describe("prepare", () => {
expect(result.logFile).toBe(join(root, "ws1", "a1", "agent.log"));
});
+ it("creates .context_timeline/ directory inside workdir", () => {
+ const task = makeTask();
+ const result = prepare({ workspacesRoot: root }, task, "claude");
+
+ const timelineDir = join(result.workDir, ".context_timeline");
+ expect(existsSync(timelineDir)).toBe(true);
+ });
+
+ it("returns timelineDir in result", () => {
+ const task = makeTask();
+ const result = prepare({ workspacesRoot: root }, task, "claude");
+
+ expect(result.timelineDir).toBe(join(result.workDir, ".context_timeline"));
+ });
+
it("returns env with all expected keys", () => {
const task = makeTask();
const result = prepare({ workspacesRoot: root }, task, "claude");
diff --git a/src/cli/daemon/execenv/__tests__/timeline.test.ts b/src/cli/daemon/execenv/__tests__/timeline.test.ts
new file mode 100644
index 000000000..aca472966
--- /dev/null
+++ b/src/cli/daemon/execenv/__tests__/timeline.test.ts
@@ -0,0 +1,246 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
+import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync } from "fs";
+import { join } from "path";
+import { tmpdir } from "os";
+
+// Mock logger to prevent noise
+vi.mock("../../../lib/logger.js", () => ({
+ log: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+}));
+
+import {
+ initEntry,
+ updateEntry,
+ createTimelineEntry,
+ _todayFilename,
+ _localISOString,
+ _filenameForDate,
+ _recentFilenames,
+ type ContextTimelineEntry,
+} from "../timeline.js";
+
+describe("timeline", () => {
+ let dir: string;
+
+ beforeEach(() => {
+ dir = join(tmpdir(), `timeline-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
+ mkdirSync(dir, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ function readEntries(): ContextTimelineEntry[] {
+ const filename = _todayFilename();
+ const filePath = join(dir, filename);
+ if (!existsSync(filePath)) return [];
+ return readFileSync(filePath, "utf-8")
+ .trimEnd()
+ .split("\n")
+ .map((line) => JSON.parse(line));
+ }
+
+ it("initEntry creates file if it doesn't exist and appends valid JSON line", () => {
+ const entry = createTimelineEntry("t_abc", "do something");
+ initEntry(dir, entry);
+
+ const entries = readEntries();
+ expect(entries).toHaveLength(1);
+ expect(entries[0].task_id).toBe("t_abc");
+ expect(entries[0].session_id).toBeNull();
+ expect(entries[0].pid).toBeNull();
+ expect(entries[0].status).toBe("running");
+ expect(entries[0].prompt).toBe("do something");
+ expect(entries[0].type).toBe("user_dm_message");
+ expect(entries[0].steps).toEqual([]);
+ expect(entries[0].response).toBeNull();
+ expect(entries[0].errmsg).toBeNull();
+ });
+
+ it("createTimelineEntry stores sessionId and pid when provided", () => {
+ const entry = createTimelineEntry("t_xyz", "test", "sess_1", 99999);
+ initEntry(dir, entry);
+
+ const entries = readEntries();
+ expect(entries[0].session_id).toBe("sess_1");
+ expect(entries[0].pid).toBe(99999);
+ });
+
+ it("updateEntry finds entry by task_id and updates steps", () => {
+ const entry = createTimelineEntry("t_abc", "do something");
+ initEntry(dir, entry);
+
+ updateEntry(dir, "t_abc", (e) => {
+ e.steps.push("Step 1: Looking at the code...");
+ });
+
+ const entries = readEntries();
+ expect(entries[0].steps).toEqual(["Step 1: Looking at the code..."]);
+ });
+
+ it("updateEntry sets completion fields correctly", () => {
+ const entry = createTimelineEntry("t_abc", "do something");
+ initEntry(dir, entry);
+
+ updateEntry(dir, "t_abc", (e) => {
+ e.session_id = "sess_123";
+ e.pid = null;
+ e.status = "completed";
+ e.response = "Done! Here is the result.";
+ });
+
+ const entries = readEntries();
+ expect(entries[0].session_id).toBe("sess_123");
+ expect(entries[0].pid).toBeNull();
+ expect(entries[0].status).toBe("completed");
+ expect(entries[0].response).toBe("Done! Here is the result.");
+ expect(entries[0].errmsg).toBeNull();
+ });
+
+ it("updateEntry sets failure fields correctly", () => {
+ const entry = createTimelineEntry("t_fail", "will fail");
+ initEntry(dir, entry);
+
+ updateEntry(dir, "t_fail", (e) => {
+ e.pid = null;
+ e.status = "failed";
+ e.errmsg = "something went wrong";
+ });
+
+ const entries = readEntries();
+ expect(entries[0].pid).toBeNull();
+ expect(entries[0].status).toBe("failed");
+ expect(entries[0].errmsg).toBe("something went wrong");
+ expect(entries[0].response).toBeNull();
+ });
+
+ it("multiple entries for different task_ids coexist in same file", () => {
+ initEntry(dir, createTimelineEntry("t_1", "first task"));
+ initEntry(dir, createTimelineEntry("t_2", "second task"));
+ initEntry(dir, createTimelineEntry("t_3", "third task"));
+
+ const entries = readEntries();
+ expect(entries).toHaveLength(3);
+ expect(entries.map((e) => e.task_id)).toEqual(["t_1", "t_2", "t_3"]);
+ });
+
+ it("updateEntry only modifies the matching task_id", () => {
+ initEntry(dir, createTimelineEntry("t_1", "first task"));
+ initEntry(dir, createTimelineEntry("t_2", "second task"));
+
+ updateEntry(dir, "t_2", (e) => {
+ e.steps.push("Working on second task");
+ });
+
+ const entries = readEntries();
+ expect(entries[0].steps).toEqual([]);
+ expect(entries[1].steps).toEqual(["Working on second task"]);
+ });
+
+ it("timeline operations are best-effort — errors don't propagate", () => {
+ // updateEntry on a non-existent directory should not throw
+ expect(() => updateEntry("/nonexistent/path", "t_1", (e) => { e.steps.push("x"); })).not.toThrow();
+ });
+
+ it("updateEntry is a no-op when task_id not found", () => {
+ initEntry(dir, createTimelineEntry("t_1", "task"));
+
+ updateEntry(dir, "t_nonexistent", (e) => {
+ e.steps.push("should not happen");
+ });
+
+ const entries = readEntries();
+ expect(entries).toHaveLength(1);
+ expect(entries[0].steps).toEqual([]);
+ });
+
+ it("datetime is local timezone with UTC offset", () => {
+ const dt = _localISOString();
+ // Should match pattern like 2026-04-13T10:30:00+05:00 or 2026-04-13T10:30:00-05:00
+ expect(dt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}$/);
+ });
+
+ it("todayFilename returns YYYY-MM-DD.jsonl format", () => {
+ const filename = _todayFilename();
+ expect(filename).toMatch(/^\d{4}-\d{2}-\d{2}\.jsonl$/);
+ });
+
+ it("recentFilenames returns today first and correct count", () => {
+ const filenames = _recentFilenames(3);
+ expect(filenames).toHaveLength(3);
+ expect(filenames[0]).toBe(_todayFilename());
+ // Each should be a valid YYYY-MM-DD.jsonl
+ for (const f of filenames) {
+ expect(f).toMatch(/^\d{4}-\d{2}-\d{2}\.jsonl$/);
+ }
+ // All distinct
+ expect(new Set(filenames).size).toBe(3);
+ });
+
+ it("filenameForDate formats correctly", () => {
+ const d = new Date(2026, 0, 5); // Jan 5, 2026
+ expect(_filenameForDate(d)).toBe("2026-01-05.jsonl");
+ });
+
+ it("updateEntry finds entry in a past day's file", () => {
+ // Write entry to yesterday's file manually
+ const yesterday = new Date();
+ yesterday.setDate(yesterday.getDate() - 1);
+ const filename = _filenameForDate(yesterday);
+ const entry = createTimelineEntry("t_old", "old task");
+ const filePath = join(dir, filename);
+ writeFileSync(filePath, JSON.stringify(entry) + "\n");
+
+ // updateEntry should find it even though it's not in today's file
+ updateEntry(dir, "t_old", (e) => {
+ e.steps.push("Updated across midnight");
+ });
+
+ const content = readFileSync(filePath, "utf-8");
+ const updated: ContextTimelineEntry = JSON.parse(content.trimEnd());
+ expect(updated.steps).toEqual(["Updated across midnight"]);
+ });
+
+ it("updateEntry stops at first match and does not modify older files", () => {
+ // Write same task_id in two different day files
+ const yesterday = new Date();
+ yesterday.setDate(yesterday.getDate() - 1);
+ const todayFile = join(dir, _todayFilename());
+ const yesterdayFile = join(dir, _filenameForDate(yesterday));
+
+ const entryToday = createTimelineEntry("t_dup", "today version");
+ const entryYesterday = createTimelineEntry("t_dup", "yesterday version");
+ writeFileSync(todayFile, JSON.stringify(entryToday) + "\n");
+ writeFileSync(yesterdayFile, JSON.stringify(entryYesterday) + "\n");
+
+ updateEntry(dir, "t_dup", (e) => {
+ e.response = "done";
+ });
+
+ // Today's file should be updated
+ const todayParsed: ContextTimelineEntry = JSON.parse(readFileSync(todayFile, "utf-8").trimEnd());
+ expect(todayParsed.response).toBe("done");
+
+ // Yesterday's should be untouched
+ const yesterdayParsed: ContextTimelineEntry = JSON.parse(readFileSync(yesterdayFile, "utf-8").trimEnd());
+ expect(yesterdayParsed.response).toBeNull();
+ });
+
+ it("updateEntry is a no-op when task_id not found in any day", () => {
+ // Write entries for today and yesterday with different task_ids
+ const yesterday = new Date();
+ yesterday.setDate(yesterday.getDate() - 1);
+ writeFileSync(join(dir, _todayFilename()), JSON.stringify(createTimelineEntry("t_a", "a")) + "\n");
+ writeFileSync(join(dir, _filenameForDate(yesterday)), JSON.stringify(createTimelineEntry("t_b", "b")) + "\n");
+
+ // Should not throw, just silently no-op
+ updateEntry(dir, "t_nonexistent", (e) => {
+ e.steps.push("nope");
+ });
+
+ // Verify nothing changed
+ const todayEntries = JSON.parse(readFileSync(join(dir, _todayFilename()), "utf-8").trimEnd());
+ expect(todayEntries.steps).toEqual([]);
+ });
+});
diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.ts
index 0eef563ea..ddd0fc06c 100644
--- a/src/cli/daemon/execenv/context.ts
+++ b/src/cli/daemon/execenv/context.ts
@@ -21,6 +21,28 @@ SYSPROMPT TODO FOR ALOOK`;
${task.agent.instructions}`;
}
+ content += `
+
+## Context Timeline
+
+Your conversation history is stored in \`.context_timeline/YYYY-MM-DD.jsonl\` (today's date).
+Each line is a JSON object with these fields:
+
+- \`task_id\` — unique task identifier
+- \`session_id\` — agent session identifier (null until completion)
+- \`pid\` — daemon process ID (present while running, null when done)
+- \`status\` — "running", "completed", or "failed"
+- \`datetime\` — when the task started (local timezone)
+- \`type\` — always "user_dm_message"
+- \`prompt\` — what the user asked
+- \`steps\` — assistant text outputs during execution
+- \`response\` — final response (null if running or failed)
+- \`errmsg\` — error message (null unless status is "failed")
+
+When you start a new task, read the last ~20 lines of today's file to understand
+what has been asked and done recently. You may also check yesterday's file if
+today's is empty or very short.`;
+
return content;
}
diff --git a/src/cli/daemon/execenv/filelock.ts b/src/cli/daemon/execenv/filelock.ts
new file mode 100644
index 000000000..9e6003edd
--- /dev/null
+++ b/src/cli/daemon/execenv/filelock.ts
@@ -0,0 +1,41 @@
+import { mkdirSync, rmdirSync, statSync } from "fs";
+
+const DEFAULT_STALE_MS = 3_600_000; // 1 hour
+
+export function acquireLock(lockPath: string, staleMs = DEFAULT_STALE_MS): boolean {
+ try {
+ mkdirSync(lockPath);
+ return true;
+ } catch {
+ // Lock directory already exists — check if stale
+ try {
+ const stat = statSync(lockPath);
+ if (Date.now() - stat.mtimeMs > staleMs) {
+ rmdirSync(lockPath);
+ try {
+ mkdirSync(lockPath);
+ return true;
+ } catch {
+ return false;
+ }
+ }
+ } catch {
+ // stat failed — lock was removed between our attempts
+ try {
+ mkdirSync(lockPath);
+ return true;
+ } catch {
+ return false;
+ }
+ }
+ return false;
+ }
+}
+
+export function releaseLock(lockPath: string): void {
+ try {
+ rmdirSync(lockPath);
+ } catch {
+ // already removed or never existed
+ }
+}
diff --git a/src/cli/daemon/execenv/index.ts b/src/cli/daemon/execenv/index.ts
index 98a72e4c6..b6c9697c0 100644
--- a/src/cli/daemon/execenv/index.ts
+++ b/src/cli/daemon/execenv/index.ts
@@ -10,6 +10,7 @@ export interface ExecEnvConfig {
export interface ExecEnvResult {
workDir: string;
logFile: string;
+ timelineDir: string;
env: Record<string, string>;
}
@@ -22,6 +23,9 @@ export function prepare(
mkdirSync(workDir, { recursive: true });
+ const timelineDir = join(workDir, ".context_timeline");
+ mkdirSync(timelineDir, { recursive: true });
+
writeInstructionFile(workDir, task, provider);
cleanStaleProviderFiles(workDir, provider);
@@ -41,7 +45,7 @@ export function prepare(
ALOOK_HEALTH_PORT: process.env.ALOOK_HEALTH_PORT || "19514",
};
- return { workDir, logFile, env };
+ return { workDir, logFile, timelineDir, env };
}
export { buildInstructionContent, writeInstructionFile, cleanStaleProviderFiles } from "./context.js";
diff --git a/src/cli/daemon/execenv/timeline.ts b/src/cli/daemon/execenv/timeline.ts
new file mode 100644
index 000000000..184ea8470
--- /dev/null
+++ b/src/cli/daemon/execenv/timeline.ts
@@ -0,0 +1,202 @@
+import { appendFileSync, readFileSync, writeFileSync, renameSync } from "fs";
+import { join } from "path";
+import { acquireLock, releaseLock } from "./filelock.js";
+import { log } from "../../lib/logger.js";
+
+export interface ContextTimelineEntry {
+ task_id: string;
+ session_id: string | null;
+ pid: number | null;
+ status: "running" | "completed" | "failed";
+ datetime: string;
+ type: "user_dm_message";
+ prompt: string;
+ steps: string[];
+ response: string | null;
+ errmsg: string | null;
+}
+
+function filenameForDate(date: Date): string {
+ const y = date.getFullYear();
+ const m = String(date.getMonth() + 1).padStart(2, "0");
+ const d = String(date.getDate()).padStart(2, "0");
+ return `${y}-${m}-${d}.jsonl`;
+}
+
+function todayFilename(): string {
+ return filenameForDate(new Date());
+}
+
+function recentFilenames(maxDays: number): string[] {
+ const filenames: string[] = [];
+ const now = new Date();
+ for (let i = 0; i < maxDays; i++) {
+ const d = new Date(now);
+ d.setDate(d.getDate() - i);
+ filenames.push(filenameForDate(d));
+ }
+ return filenames;
+}
+
+function localISOString(): string {
+ const now = new Date();
+ const tzOffset = -now.getTimezoneOffset();
+ const sign = tzOffset >= 0 ? "+" : "-";
+ const absOffset = Math.abs(tzOffset);
+ const hh = String(Math.floor(absOffset / 60)).padStart(2, "0");
+ const mm = String(absOffset % 60).padStart(2, "0");
+
+ const y = now.getFullYear();
+ const mo = String(now.getMonth() + 1).padStart(2, "0");
+ const d = String(now.getDate()).padStart(2, "0");
+ const h = String(now.getHours()).padStart(2, "0");
+ const mi = String(now.getMinutes()).padStart(2, "0");
+ const s = String(now.getSeconds()).padStart(2, "0");
+
+ return `${y}-${mo}-${d}T${h}:${mi}:${s}${sign}${hh}:${mm}`;
+}
+
+function lockPathFor(timelineDir: string, filename: string): string {
+ return join(timelineDir, `.${filename}.lock`);
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+export function initEntry(
+ timelineDir: string,
+ entry: ContextTimelineEntry,
+): void {
+ const filename = todayFilename();
+ const filePath = join(timelineDir, filename);
+ const lockPath = lockPathFor(timelineDir, filename);
+
+ try {
+ const acquired = acquireLock(lockPath);
+ if (!acquired) {
+ log.debug(`Timeline initEntry: could not acquire lock for ${filename}`);
+ return;
+ }
+
+ try {
+ appendFileSync(filePath, JSON.stringify(entry) + "\n");
+ } finally {
+ releaseLock(lockPath);
+ }
+ } catch (err) {
+ log.debug("Timeline initEntry failed", err);
+ }
+}
+
+export async function initEntryAsync(
+ timelineDir: string,
+ entry: ContextTimelineEntry,
+): Promise<void> {
+ const filename = todayFilename();
+ const filePath = join(timelineDir, filename);
+ const lockPath = lockPathFor(timelineDir, filename);
+
+ try {
+ let acquired = acquireLock(lockPath);
+ if (!acquired) {
+ await sleep(200);
+ acquired = acquireLock(lockPath);
+ }
+ if (!acquired) {
+ log.debug(`Timeline initEntry: could not acquire lock for ${filename}`);
+ return;
+ }
+
+ try {
+ appendFileSync(filePath, JSON.stringify(entry) + "\n");
+ } finally {
+ releaseLock(lockPath);
+ }
+ } catch (err) {
+ log.debug("Timeline initEntry failed", err);
+ }
+}
+
+export function updateEntry(
+ timelineDir: string,
+ taskId: string,
+ updater: (entry: ContextTimelineEntry) => void,
+): void {
+ for (const filename of recentFilenames(7)) {
+ const filePath = join(timelineDir, filename);
+ const lockPath = lockPathFor(timelineDir, filename);
+
+ try {
+ const acquired = acquireLock(lockPath);
+ if (!acquired) {
+ log.debug(`Timeline updateEntry: lock held for ${filename}, skipping`);
+ continue;
+ }
+
+ try {
+ let content: string;
+ try {
+ content = readFileSync(filePath, "utf-8");
+ } catch {
+ continue; // file doesn't exist for this day
+ }
+
+ const lines = content.trimEnd().split("\n");
+ let found = false;
+
+ const updated = lines.map((line) => {
+ const entry: ContextTimelineEntry = JSON.parse(line);
+ if (entry.task_id === taskId) {
+ found = true;
+ updater(entry);
+ }
+ return JSON.stringify(entry);
+ });
+
+ if (!found) continue;
+
+ const tmpPath = join(timelineDir, `.${filename}.tmp`);
+ writeFileSync(tmpPath, updated.join("\n") + "\n");
+ renameSync(tmpPath, filePath);
+ return; // found and updated — stop searching
+ } finally {
+ releaseLock(lockPath);
+ }
+ } catch (err) {
+ log.debug(`Timeline updateEntry failed for ${filename}`, err);
+ }
+ }
+
+ log.debug(`Timeline updateEntry: task_id ${taskId} not found in last 7 days`);
+}
+
+export function createTimelineEntry(
+ taskId: string,
+ prompt: string,
+ sessionId?: string,
+ pid?: number,
+): ContextTimelineEntry {
+ return {
+ task_id: taskId,
+ session_id: sessionId || null,
+ pid: pid ?? null,
+ status: "running",
+ datetime: localISOString(),
+ type: "user_dm_message",
+ prompt,
+ steps: [],
+ response: null,
+ errmsg: null,
+ };
+}
+
+export { localISOString };
+
+// Exported for testing
+export {
+ todayFilename as _todayFilename,
+ localISOString as _localISOString,
+ filenameForDate as _filenameForDate,
+ recentFilenames as _recentFilenames,
+};
diff --git a/src/shared/src/db/queries/task.ts b/src/shared/src/db/queries/task.ts
index 7f89e4f8a..9aa1321c5 100644
--- a/src/shared/src/db/queries/task.ts
+++ b/src/shared/src/db/queries/task.ts
@@ -1,4 +1,4 @@
-import { eq, and, desc, asc, inArray, notInArray, isNotNull, count, lt } from "drizzle-orm";
+import { eq, and, desc, asc, inArray, notInArray, count, lt } from "drizzle-orm";
import { agentTaskQueue } from "../schema";
import type { Database } from "../index";
import { ClaimedTaskRowSchema } from "../../schemas";
@@ -145,28 +145,6 @@ export async function failTask(
return rows[0] ?? null;
}
-export async function getLastTaskSession(
- db: Database,
- agentId: string,
- conversationId: string
-) {
- const rows = await db
- .select({
- sessionId: agentTaskQueue.sessionId,
- })
- .from(agentTaskQueue)
- .where(
- and(
- eq(agentTaskQueue.agentId, agentId),
- eq(agentTaskQueue.conversationId, conversationId),
- eq(agentTaskQueue.status, "completed"),
- isNotNull(agentTaskQueue.sessionId)
- )
- )
- .orderBy(desc(agentTaskQueue.completedAt))
- .limit(1);
- return rows[0] ?? null;
-}
export async function listPendingTasksByRuntime(
db: Database,
diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.ts
index 45a540549..e53e8b2a4 100644
--- a/src/shared/src/db/schema.ts
+++ b/src/shared/src/db/schema.ts
@@ -2,7 +2,6 @@ import {
sqliteTable,
text,
integer,
- uniqueIndex,
index,
unique,
primaryKey,
@@ -226,9 +225,6 @@ export const agentTaskQueue = sqliteTable(
error: text("error"),
},
(t) => [
- uniqueIndex("idx_one_pending_per_conversation")
- .on(t.conversationId)
- .where(sql`status IN ('queued', 'dispatched')`),
index("idx_task_queue_pending")
.on(t.agentId, t.status)
.where(sql`status IN ('queued', 'dispatched')`),
diff --git a/src/web/migrations/0003_drop_one_pending_per_conversation.sql b/src/web/migrations/0003_drop_one_pending_per_conversation.sql
new file mode 100644
index 000000000..e9a5824ac
--- /dev/null
+++ b/src/web/migrations/0003_drop_one_pending_per_conversation.sql
@@ -0,0 +1 @@
+DROP INDEX IF EXISTS idx_one_pending_per_conversation;
diff --git a/src/web/src/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.test.ts b/src/web/src/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.test.ts
index 8372f70fe..1d0cfe7bd 100644
--- a/src/web/src/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.test.ts
+++ b/src/web/src/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.test.ts
@@ -3,7 +3,6 @@ import { NextRequest } from "next/server";
const mockClaimTaskForRuntime = vi.fn();
const mockGetAgent = vi.fn();
-const mockGetLastTaskSession = vi.fn();
const mockTaskToResponse = vi.fn();
vi.mock("@opennextjs/cloudflare", () => ({
@@ -15,9 +14,7 @@ vi.mock("@alook/shared", () => ({
agent: {
getAgent: (...args: any[]) => mockGetAgent(...args),
},
- task: {
- getLastTaskSession: (...args: any[]) => mockGetLastTaskSession(...args),
- },
+ task: {},
},
}));
vi.mock("@/lib/middleware/auth", () => ({
@@ -67,7 +64,7 @@ describe("POST /api/daemon/runtimes/[runtimeId]/tasks/claim", () => {
expect(mockClaimTaskForRuntime).toHaveBeenCalledWith("rt1");
});
- it("returns task with agent data and prior session", async () => {
+ it("returns task with agent data and prior_session_id always null", async () => {
const fakeTask = {
id: "t1",
agentId: "a1",
@@ -88,11 +85,9 @@ describe("POST /api/daemon/runtimes/[runtimeId]/tasks/claim", () => {
instructions: "be helpful",
runtimeConfig: { model: "gpt-4" },
};
- const fakeSession = { sessionId: "sess1" };
mockClaimTaskForRuntime.mockResolvedValue(fakeTask);
mockGetAgent.mockResolvedValue(fakeAgent);
- mockGetLastTaskSession.mockResolvedValue(fakeSession);
mockTaskToResponse.mockReturnValue({
id: "t1",
agent_id: "a1",
@@ -125,8 +120,7 @@ describe("POST /api/daemon/runtimes/[runtimeId]/tasks/claim", () => {
name: "Agent 1",
runtime_config: { model: "gpt-4" },
});
- expect(body.task.prior_session_id).toBe("sess1");
+ expect(body.task.prior_session_id).toBeNull();
expect(mockGetAgent).toHaveBeenCalledWith({}, "a1", "w1");
- expect(mockGetLastTaskSession).toHaveBeenCalledWith({}, "a1", "conv1");
});
});
diff --git a/src/web/src/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.ts b/src/web/src/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.ts
index 828ef3057..98b03d3b5 100644
--- a/src/web/src/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.ts
+++ b/src/web/src/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.ts
@@ -22,11 +22,6 @@ export const POST = withAuth(async (_req, ctx) => {
}
const agent = await queries.agent.getAgent(db, task.agentId, task.workspaceId);
- const priorSession = await queries.task.getLastTaskSession(
- db,
- task.agentId,
- task.conversationId
- );
return writeJSON({
task: {
@@ -38,7 +33,7 @@ export const POST = withAuth(async (_req, ctx) => {
runtime_config: agent.runtimeConfig || {},
}
: null,
- prior_session_id: priorSession?.sessionId ?? null,
+ prior_session_id: null,
},
});
});