refactor(session): agent-scope rotation + accumulation; auto-register file artifacts
Sessions are already agent-scoped post-v34, but the code kept routing
rotation / accumulation / handoff through the task indirection. Heartbeat
runs (no task) silently skipped all three, letting taskless transcripts
grow past the model's context window — the 7M-token explosion.
- DB adds getSessionById(sessionId) — direct lookup bypassing
tasks.active_session_id
- session-management-service: generateHandoff(session) is now agent-scoped,
walking recent runs across tasks + heartbeats; getHandoffForAgent(agentId)
is the canonical lookup, getHandoffContext(taskId) is a thin shim for
callers that still hold a task id
- turn-context.ts::resolveSession drops the `if (!task)` early return:
rotation evaluation runs on the agent session unconditionally
- run-finished-helpers.ts::accumulateAndRotateSession drops the `!task`
gate: tokens accumulate and rotation fires for every run, keyed on the
agent session, not the task
- Rotation evaluator contract: evaluatePreRunSessionRotation(agentId,
connectorId) → { rotated, handoff, sessionId }; old (taskId, connectorId)
signature removed
IPC contract tightening: ipc-support::emitEvent becomes a best-effort
sink. "Render frame was disposed" during renderer reload is a lifecycle
signal, not a logic error; silently drop it instead of letting it abort
downstream event emissions.
Artifact projection: pi's write/edit tool results now upsert a
`work_products` row via a new agent-runtime/artifact-projector.ts. No
more agents writing 54 files into the workspace that the UI never sees.
Migration v40 relaxes work_products.task_id to nullable so heartbeat
artifacts can register too.
File size: split agent-event-projection.ts out of runtime-bridge.ts to
keep the bridge under the 400-line cap after adding the projector hook.
Tests: 604 unit + integration green; generateHandoff callsites updated
for the single-argument signature; artifact-projector has pure-function
coverage via the projector module's own shape.
This commit is contained in:
1 parent
61fb4b947f
commit
ff5e22092a
45 files changed
+3409
-300
No files matched your search
@@ -305,4 +305,268 @@ describe("CAS checkout", () => {
|
||||
it("STALE_LOCK_TIMEOUT_MS is 15 minutes", () => {
|
||||
expect(STALE_LOCK_TIMEOUT_MS).toBe(15 * 60 * 1000);
|
||||
});
|
||||
|
||||
it("failed dispatch (run never started) rolls task back to 'todo' so heartbeat can retry", () => {
|
||||
// Regression: workspace-lock contention calls finishRun('failed') on a
|
||||
// run that never reached 'running'. The old code cleared checkout_run_id
|
||||
// but left task.status='in_progress' — the next checkoutTask pass then
|
||||
// refused (WHERE status IN ('todo','backlog')), and the scheduler
|
||||
// deadlocked while logging "lost checkout race" every 15 seconds.
|
||||
const companyId = createTestCompany(db);
|
||||
createTestConnector(db);
|
||||
const workspaceId = createTestWorkspace(db, companyId);
|
||||
const agentId = createTestAgent(db, companyId, workspaceId);
|
||||
const taskId = createTestTask(db, companyId, null, workspaceId);
|
||||
|
||||
const { id: runId } = db.createRun({
|
||||
companyId,
|
||||
taskId,
|
||||
agentId,
|
||||
workspaceId,
|
||||
connectorId: "openai-codex",
|
||||
});
|
||||
db.checkoutTask(taskId, runId);
|
||||
expect(db.getTask(taskId).status).toBe("in_progress");
|
||||
|
||||
// Never call markRunStatus('running', ...) — this simulates the
|
||||
// "workspace already locked" bail-out inside dispatchRunToWorker.
|
||||
db.finishRun({
|
||||
runId,
|
||||
status: "failed",
|
||||
summary: null,
|
||||
errorMessage: "Workspace is locked by another run.",
|
||||
exitCode: null,
|
||||
signal: null,
|
||||
model: null,
|
||||
sessionDisplayId: null,
|
||||
unattributedCost: true,
|
||||
});
|
||||
|
||||
expect(db.getTask(taskId).status).toBe("todo");
|
||||
|
||||
// And the next CAS checkout must succeed — proving the heartbeat
|
||||
// retry path is unblocked.
|
||||
const { id: retryRunId } = db.createRun({
|
||||
companyId,
|
||||
taskId,
|
||||
agentId,
|
||||
workspaceId,
|
||||
connectorId: "openai-codex",
|
||||
});
|
||||
expect(db.checkoutTask(taskId, retryRunId)).toBe(true);
|
||||
});
|
||||
|
||||
it("cancelled run that never started also rolls task back to 'todo'", () => {
|
||||
// Workspace-contention bail-out in dispatchRunToWorker marks the run as
|
||||
// 'cancelled' (not 'failed'), so the Dashboard "Needs attention" banner
|
||||
// stays quiet. The rollback path must handle cancelled too, or the task
|
||||
// would stick in 'in_progress' just like the original 'failed' bug.
|
||||
const companyId = createTestCompany(db);
|
||||
createTestConnector(db);
|
||||
const workspaceId = createTestWorkspace(db, companyId);
|
||||
const agentId = createTestAgent(db, companyId, workspaceId);
|
||||
const taskId = createTestTask(db, companyId, null, workspaceId);
|
||||
|
||||
const { id: runId } = db.createRun({
|
||||
companyId,
|
||||
taskId,
|
||||
agentId,
|
||||
workspaceId,
|
||||
connectorId: "openai-codex",
|
||||
});
|
||||
db.checkoutTask(taskId, runId);
|
||||
db.finishRun({
|
||||
runId,
|
||||
status: "cancelled",
|
||||
summary: null,
|
||||
errorMessage: "Workspace in use by another run; will retry.",
|
||||
exitCode: null,
|
||||
signal: null,
|
||||
model: null,
|
||||
sessionDisplayId: null,
|
||||
unattributedCost: true,
|
||||
});
|
||||
|
||||
expect(db.getTask(taskId).status).toBe("todo");
|
||||
});
|
||||
|
||||
it("failed run that did start stays 'in_progress' (human retry path)", () => {
|
||||
// Counterpart to the regression above: a run that actually transitioned
|
||||
// to 'running' and then failed mid-flight is the user's problem to
|
||||
// resolve through the recovery UI — we must not silently reset its
|
||||
// task to 'todo' and lose the partial work / error context.
|
||||
const companyId = createTestCompany(db);
|
||||
createTestConnector(db);
|
||||
const workspaceId = createTestWorkspace(db, companyId);
|
||||
const agentId = createTestAgent(db, companyId, workspaceId);
|
||||
const taskId = createTestTask(db, companyId, null, workspaceId);
|
||||
|
||||
const { id: runId } = db.createRun({
|
||||
companyId,
|
||||
taskId,
|
||||
agentId,
|
||||
workspaceId,
|
||||
connectorId: "openai-codex",
|
||||
});
|
||||
db.checkoutTask(taskId, runId);
|
||||
db.markRunStatus(runId, "running", "");
|
||||
db.finishRun({
|
||||
runId,
|
||||
status: "failed",
|
||||
summary: null,
|
||||
errorMessage: "Worker crashed",
|
||||
exitCode: 1,
|
||||
signal: null,
|
||||
model: null,
|
||||
sessionDisplayId: null,
|
||||
unattributedCost: false,
|
||||
});
|
||||
|
||||
expect(db.getTask(taskId).status).toBe("in_progress");
|
||||
});
|
||||
|
||||
it("startup reconciliation unsticks tasks whose checkout_run_id points at a dead run", () => {
|
||||
// This is the shape observed in the wild: active_run_id cleared by
|
||||
// finishRun (unconditional clear), but checkout_run_id still carrying
|
||||
// a dead run id because the conditional clear's WHERE missed due to
|
||||
// a race. Task sits in 'in_progress' forever — heartbeat picks it
|
||||
// (activeRunId null), checkoutTask refuses (status != todo/backlog),
|
||||
// "lost checkout race" on loop. Reconciliation must fix it without
|
||||
// caring which reference column is null.
|
||||
const companyId = createTestCompany(db);
|
||||
createTestConnector(db);
|
||||
const workspaceId = createTestWorkspace(db, companyId);
|
||||
const agentId = createTestAgent(db, companyId, workspaceId);
|
||||
const taskId = createTestTask(db, companyId, null, workspaceId);
|
||||
|
||||
const { id: deadRunId } = db.createRun({
|
||||
companyId,
|
||||
taskId,
|
||||
agentId,
|
||||
workspaceId,
|
||||
connectorId: "openai-codex",
|
||||
});
|
||||
db.checkoutTask(taskId, deadRunId);
|
||||
// Mark the run terminal without running finishRun's clear path —
|
||||
// simulates the race where checkout_run_id survived but the run
|
||||
// itself is no longer live.
|
||||
(db as unknown as RawDb).db
|
||||
.prepare("UPDATE runs SET status = 'cancelled' WHERE id = ?")
|
||||
.run(deadRunId);
|
||||
(db as unknown as RawDb).db
|
||||
.prepare("UPDATE tasks SET active_run_id = NULL WHERE id = ?")
|
||||
.run(taskId);
|
||||
|
||||
// Pre-condition: task is stuck.
|
||||
const stuck = (db as unknown as RawDb).db
|
||||
.prepare("SELECT status, checkout_run_id as checkoutRunId, active_run_id as activeRunId FROM tasks WHERE id = ?")
|
||||
.get(taskId) as { status: string; checkoutRunId: string | null; activeRunId: string | null };
|
||||
expect(stuck.status).toBe("in_progress");
|
||||
expect(stuck.checkoutRunId).toBe(deadRunId);
|
||||
expect(stuck.activeRunId).toBeNull();
|
||||
|
||||
// Re-initialise: reconciliation should run.
|
||||
db.close();
|
||||
db = new AppDatabase(tempDir);
|
||||
db.init();
|
||||
|
||||
expect(db.lastOrphanResetCount).toBe(1);
|
||||
const reclaimed = db.getTask(taskId);
|
||||
expect(reclaimed.status).toBe("todo");
|
||||
|
||||
// And a fresh checkout must succeed — proving the task is reclaimable.
|
||||
const { id: newRunId } = db.createRun({
|
||||
companyId,
|
||||
taskId,
|
||||
agentId,
|
||||
workspaceId,
|
||||
connectorId: "openai-codex",
|
||||
});
|
||||
expect(db.checkoutTask(taskId, newRunId)).toBe(true);
|
||||
});
|
||||
|
||||
it("startup reconciliation unsticks in_review tasks with no possible reviewer", () => {
|
||||
// Observed in production: a fresh `ai_ceo` company with only a CEO
|
||||
// self-assigned a large task and set status=in_review. The reviewer
|
||||
// would be the assignee's manager (walk up reports_to), but the CEO
|
||||
// has no manager. With `requires_user_review = 0` there is no human
|
||||
// fallback either. The heartbeat falls into a loop re-proposing
|
||||
// `approve_ceo_strategy` every cycle without ever hiring or moving
|
||||
// the task. Demoting to 'todo' breaks the loop.
|
||||
const companyId = createTestCompany(db);
|
||||
createTestConnector(db);
|
||||
const workspaceId = createTestWorkspace(db, companyId);
|
||||
// Top-level agent (CEO): reports_to stays NULL.
|
||||
const ceoId = createTestAgent(db, companyId, workspaceId, "CEO");
|
||||
const taskId = createTestTask(db, companyId, ceoId, workspaceId);
|
||||
// Manually wedge the task into the dead-letter shape.
|
||||
(db as unknown as RawDb).db
|
||||
.prepare("UPDATE tasks SET status = 'in_review', requires_user_review = 0 WHERE id = ?")
|
||||
.run(taskId);
|
||||
|
||||
expect(db.getTask(taskId).status).toBe("in_review");
|
||||
|
||||
// Re-init triggers reconciliation.
|
||||
db.close();
|
||||
db = new AppDatabase(tempDir);
|
||||
db.init();
|
||||
|
||||
expect(db.lastUnreviewableResetCount).toBe(1);
|
||||
expect(db.getTask(taskId).status).toBe("todo");
|
||||
});
|
||||
|
||||
it("in_review tasks requiring user review are left alone", () => {
|
||||
// Opposite guard: when requires_user_review = 1 the task is
|
||||
// intentionally parked waiting for a human — the reconciler must
|
||||
// not steal it.
|
||||
const companyId = createTestCompany(db);
|
||||
createTestConnector(db);
|
||||
const workspaceId = createTestWorkspace(db, companyId);
|
||||
const ceoId = createTestAgent(db, companyId, workspaceId, "CEO");
|
||||
const taskId = createTestTask(db, companyId, ceoId, workspaceId);
|
||||
(db as unknown as RawDb).db
|
||||
.prepare("UPDATE tasks SET status = 'in_review', requires_user_review = 1 WHERE id = ?")
|
||||
.run(taskId);
|
||||
|
||||
db.close();
|
||||
db = new AppDatabase(tempDir);
|
||||
db.init();
|
||||
|
||||
expect(db.lastUnreviewableResetCount).toBe(0);
|
||||
expect(db.getTask(taskId).status).toBe("in_review");
|
||||
});
|
||||
|
||||
it("reconciliation does not fire when interruptStaleRuns already handled a running task", () => {
|
||||
// Opposite guard: tasks whose run was `running` at shutdown are
|
||||
// handled earlier in init by `interruptStaleRuns` — it marks the
|
||||
// run 'interrupted' and sets the task to 'blocked' for human
|
||||
// review. By the time reconciliation runs, the task is no longer
|
||||
// 'in_progress', so the cleanup's WHERE clause skips it. The user
|
||||
// sees the task surfaced in the recovery UI, not silently reset.
|
||||
const companyId = createTestCompany(db);
|
||||
createTestConnector(db);
|
||||
const workspaceId = createTestWorkspace(db, companyId);
|
||||
const agentId = createTestAgent(db, companyId, workspaceId);
|
||||
const taskId = createTestTask(db, companyId, null, workspaceId);
|
||||
|
||||
const { id: liveRunId } = db.createRun({
|
||||
companyId,
|
||||
taskId,
|
||||
agentId,
|
||||
workspaceId,
|
||||
connectorId: "openai-codex",
|
||||
});
|
||||
db.checkoutTask(taskId, liveRunId);
|
||||
db.markRunStatus(liveRunId, "running", "");
|
||||
|
||||
db.close();
|
||||
db = new AppDatabase(tempDir);
|
||||
db.init();
|
||||
|
||||
// Reconciliation counted 0 because interruptStaleRuns moved the
|
||||
// task to 'blocked' first. Both guards collaborate — neither
|
||||
// steals a task out from under an actively-working run.
|
||||
expect(db.lastOrphanResetCount).toBe(0);
|
||||
expect(db.getTask(taskId).status).toBe("blocked");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user