Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review (codex): require a read task status, and read agent metadata without the transcript (#3368)

[._.]/ Adam Eivy8ff87901227e
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index bb3a1c7a85..a01c1f6243 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -536,13 +536,17 @@ export async function recordTaskResumePointer({ task, agentId, agentMetadata })
* been persisted by `finalizeAgent` at this point, so the task's *persisted* status
* distinguishes a `pending` retry (wants the pointer) from a `blocked` task that
* exhausted its budget and is waiting on a human — a pointer there would be dead
- * metadata that `updateTask` has to strip again on the next terminal write.
+ * metadata that `updateTask` has to strip again on the next terminal write, and
+ * that a later `reviveBlockedTask` would resurrect as a live pointer to a branch
+ * nobody vetted. So the pointer needs a task record we actually READ saying
+ * `pending`; a failed read or a task deleted mid-run is not evidence of a retry.
*
* `agentMetadata` is optional: pass it when the caller already holds the agent
- * record (the runner path does, and re-reading it there would re-split the whole
- * output.txt transcript), omit it and this reads the record itself. `undefined`
- * means "not supplied" — a caller that genuinely has no metadata still gets the
- * no-op it deserves, since `resolveTaskResumePatch` bails on a non-worktree run.
+ * record (the runner path does), omit it and this reads the record itself —
+ * `getAgentRecord`, not `getAgent`, so it doesn't read and line-split the run's
+ * whole output.txt for three metadata fields. `undefined` means "not supplied" —
+ * a caller that genuinely has no metadata still gets the no-op it deserves, since
+ * `resolveTaskResumePatch` bails on a non-worktree run.
*
* @param {{agentId: string, task: object, success: boolean, agentMetadata?: object}} params
* @returns {Promise<object>} the patch that was written (empty when nothing was)
@@ -550,12 +554,17 @@ export async function recordTaskResumePointer({ task, agentId, agentMetadata })
export async function recordResumePointerIfRetrying({ agentId, task, success, agentMetadata }) {
if (success || !agentId || !task?.id) return {};
- const { getTaskById, getAgent } = await import('./cos.js');
- const persisted = await getTaskById(task.id).catch(() => null);
- if ((persisted?.status ?? 'pending') !== 'pending') return {};
+ const { getTaskById, getAgentRecord } = await import('./cos.js');
+ const persisted = await getTaskById(task.id).catch(err => {
+ emitLog('warn', `Skipping resume pointer for task ${task.id} — status unreadable: ${err.message}`, { taskId: task.id, agentId });
+ return null;
+ });
+ // A record with no `status` at all is a legacy shape that predates the field;
+ // those are pending. A record we couldn't read, or that is gone, is neither.
+ if (!persisted || (persisted.status ?? 'pending') !== 'pending') return {};
const metadata = agentMetadata === undefined
- ? (await getAgent(agentId).catch(() => null))?.metadata
+ ? (await getAgentRecord(agentId).catch(() => null))?.metadata
: agentMetadata;
return await recordTaskResumePointer({ task, agentId, agentMetadata: metadata });
}
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 69759ca116..02f1943440 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -39,7 +39,8 @@ vi.mock('./cos.js', () => ({
addTask: vi.fn().mockResolvedValue(undefined),
emitLog: vi.fn(),
getTaskById: vi.fn().mockResolvedValue(null),
- getAgent: vi.fn().mockResolvedValue(null)
+ getAgent: vi.fn().mockResolvedValue(null),
+ getAgentRecord: vi.fn().mockResolvedValue(null)
}));
vi.mock('./appActivity.js', () => ({
@@ -213,7 +214,7 @@ import { join } from 'path';
import { existsSync as existsSyncMock } from 'fs';
import { cleanupAgentWorktree, spawnMergeRecoveryTask, spawnReviewLoopFollowUp } from './subAgentSpawner.js';
import { resolveResumePointer, resolveTaskResumePatch, recordTaskResumePointer, recordResumePointerIfRetrying, resumePointerMetadata } from './agentWorktreeCleanup.js';
-import { getAgent, getTaskById, addTask, updateTask } from './cos.js';
+import { getAgent, getAgentRecord, getTaskById, addTask, updateTask } from './cos.js';
import { removeWorktree } from './worktreeManager.js';
import { PATHS } from '../lib/fileUtils.js';
import * as git from './git.js';
@@ -1240,15 +1241,17 @@ describe('recordResumePointerIfRetrying', () => {
git.getBranchComparison.mockResolvedValue({ ahead: 2, commits: [], stats: {} });
existsSyncMock.mockReturnValue(false);
getTaskById.mockResolvedValue({ id: 'task-1', status: 'pending' });
- getAgent.mockResolvedValue({ metadata: agentMetadata });
+ getAgentRecord.mockResolvedValue({ metadata: agentMetadata });
});
// The direct-CLI / TUI shape: neither spawn path holds the agent record, so the
- // helper has to read it for the worktree fields.
+ // helper has to read it for the worktree fields — via the transcript-free
+ // `getAgentRecord`, since a long TUI run's output.txt is megabytes.
it('records the pointer for a failed run whose task is still pending', async () => {
await recordResumePointerIfRetrying({ agentId: 'agent-x', task: task(), success: false });
- expect(getAgent).toHaveBeenCalledWith('agent-x');
+ expect(getAgentRecord).toHaveBeenCalledWith('agent-x');
+ expect(getAgent).not.toHaveBeenCalled();
expect(updateTask).toHaveBeenCalledWith('task-1', {
metadata: { existingBranch: DEAD_BRANCH, resumedFromAgentId: 'agent-x', resumeWorktreePath: null }
}, 'user');
@@ -1271,22 +1274,39 @@ describe('recordResumePointerIfRetrying', () => {
expect(updateTask).not.toHaveBeenCalled();
});
- // A task whose record vanished (deleted mid-run) still defaults to pending so the
- // pointer isn't silently dropped.
- it('treats an unreadable task record as pending', async () => {
- getTaskById.mockRejectedValue(new Error('gone'));
+ // "I couldn't read the status" is not "the status is pending" — guessing would
+ // stamp a pointer on a blocked task, which a later reviveBlockedTask would then
+ // resurrect as a live pointer to a branch nobody vetted.
+ it('records nothing when the task status is unreadable', async () => {
+ getTaskById.mockRejectedValue(new Error('read failed'));
+
+ await recordResumePointerIfRetrying({ agentId: 'agent-x', task: task(), success: false });
+
+ expect(updateTask).not.toHaveBeenCalled();
+ });
+
+ it('records nothing when the task was deleted mid-run', async () => {
+ getTaskById.mockResolvedValue(null);
+
+ await recordResumePointerIfRetrying({ agentId: 'agent-x', task: task(), success: false });
+
+ expect(updateTask).not.toHaveBeenCalled();
+ });
+
+ // Records written before the status field existed read as pending.
+ it('treats a status-less legacy task record as pending', async () => {
+ getTaskById.mockResolvedValue({ id: 'task-1' });
await recordResumePointerIfRetrying({ agentId: 'agent-x', task: task(), success: false });
expect(updateTask).toHaveBeenCalled();
});
- // The runner path already holds the agent record; passing it spares a re-read
- // that would re-split the whole output.txt transcript.
+ // The runner path already holds the agent record; passing it spares a re-read.
it('uses caller-supplied agent metadata instead of re-reading the record', async () => {
await recordResumePointerIfRetrying({ agentId: 'agent-x', task: task(), success: false, agentMetadata });
- expect(getAgent).not.toHaveBeenCalled();
+ expect(getAgentRecord).not.toHaveBeenCalled();
expect(updateTask).toHaveBeenCalled();
});
diff --git a/server/services/cos.js b/server/services/cos.js
index 4d7a324e2f..ba889cfabd 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -39,7 +39,7 @@ import { cosEvents, emitLog } from './cosEvents.js';
export { cosEvents, emitLog };
// Agent lifecycle (re-export for backward compat with `import * as cos`)
-export { registerAgent, updateAgent, completeAgent, appendAgentOutput, getAgents, getAgentDates, getAgentsByDate, getAgent, getAgentPrompt, terminateAgent, pauseAgent, killAgent, sendBtwToAgent, getAgentProcessStats, cleanupZombieAgents, deleteAgent, submitAgentFeedback, getFeedbackStats, extractTaskType, archiveStaleAgents, clearCompletedAgents, pruneOldAgentArchives } from './cosAgents.js';
+export { registerAgent, updateAgent, completeAgent, appendAgentOutput, getAgents, getAgentDates, getAgentsByDate, getAgent, getAgentRecord, getAgentPrompt, terminateAgent, pauseAgent, killAgent, sendBtwToAgent, getAgentProcessStats, cleanupZombieAgents, deleteAgent, submitAgentFeedback, getFeedbackStats, extractTaskType, archiveStaleAgents, clearCompletedAgents, pruneOldAgentArchives } from './cosAgents.js';
// Reports and activity (re-export for backward compat with `import * as cos`)
export { generateReport, getReport, getTodayReport, listReports, listBriefings, getBriefing, getLatestBriefing, getTodayActivity, getWhileAwayActivity, getRecentTasks, formatRelativeTime } from './cosReports.js';
diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.js
index 61a9584de0..b01df0d482 100644
--- a/server/services/cosAgentLifecycle.js
+++ b/server/services/cosAgentLifecycle.js
@@ -309,26 +309,35 @@ export async function getAgents() {
}
// Get agent by ID with full output from file
-export async function getAgent(agentId) {
+/**
+ * The agent record WITHOUT its transcript — in-memory state first, falling back
+ * to the on-disk `metadata.json` the index points at.
+ *
+ * Split out of `getAgent` so callers that only need the record's fields (the
+ * worktree/provider metadata, the status) don't pay to read and line-split a
+ * completed agent's entire output.txt — which for a long TUI run is megabytes,
+ * and whose read failing would otherwise take the whole lookup down with it.
+ * `recordResumePointerIfRetrying` is the motivating caller (#3368).
+ */
+export async function getAgentRecord(agentId) {
const state = await loadState();
- let agent = state.agents[agentId];
+ const agent = state.agents[agentId];
+ if (agent) return agent;
// Fall back to disk metadata via index if not in state
- if (!agent) {
- const idx = await loadAgentIndex();
- const dateStr = idx.get(agentId);
- if (dateStr) {
- const metaPath = join(AGENTS_DIR, dateStr, agentId, 'metadata.json');
- const content = await tryReadFile(metaPath);
- if (content) {
- const raw = safeJSONParse(content, null);
- if (raw) {
- const { output, ...rest } = raw;
- agent = { ...rest, id: raw.id || raw.agentId || agentId, status: raw.status || 'completed' };
- }
- }
- }
- }
+ const idx = await loadAgentIndex();
+ const dateStr = idx.get(agentId);
+ if (!dateStr) return null;
+ const content = await tryReadFile(join(AGENTS_DIR, dateStr, agentId, 'metadata.json'));
+ if (!content) return null;
+ const raw = safeJSONParse(content, null);
+ if (!raw) return null;
+ const { output, ...rest } = raw;
+ return { ...rest, id: raw.id || raw.agentId || agentId, status: raw.status || 'completed' };
+}
+
+export async function getAgent(agentId) {
+ let agent = await getAgentRecord(agentId);
if (!agent) return null;
// Completed agents live in date buckets; paused agents remain in the flat