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

fix: reconcile explicitly abandoned duplicate agents (#10557)

[._.]/6ce72420f07b
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 11c15d3c25..10470f2bbd 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -44,6 +44,28 @@ certify the old work finished. Do not delete this journal to claim readiness; pr
with the related run/job records for recovery. A backup restored on another installation
therefore starts conservatively if it contains a hold or outstanding operations.
+### Explicitly abandoned duplicate agents
+
+A local operator may reconcile a user-killed duplicate that saved no output with
+`node scripts/reconcile-abandoned-agent.mjs <agent-id> <run-id> --confirm-abandoned <reason>`.
+Begin a normal maintenance hold first. When using a reviewed isolated checkout,
+`PORTOS_DATA_ROOT` names the install root (the parent of `data/`). This is an
+explicit abandonment decision, never automatic expiry or a successful-run verdict.
+The command refuses present agent/runner ownership, live recorded PIDs, retained
+agent output (including archives), worktrees/branches, nonempty run output,
+untrusted evidence, other reservations for that agent, and failed settlement.
+The exact hold and reservation are checked under the journal transaction lock.
+
+Before releasing the matching reservation, the owning service durably publishes
+`data/workflow-maintenance/abandoned-<run-id>.json`, retaining the original operation,
+operator reason, and evidence fingerprints. Other operations and the hold remain.
+Run/task outcomes are unchanged. Repeating the same request reuses its receipt;
+it cannot settle a replacement reservation. Receipt-first interrupted publication
+can be retried after normal journal recovery; the command never steals a transaction
+lock. These machine-local recovery receipts are included in the data backup and
+never federated. This deliberately narrow command does not recover nonempty output
+or general failed saves; those still require the owning workflow's recovery.
+
## The Four Storage Classes
| Class | Bytes live | Searchable metadata | Use when | PortOS examples |
diff --git a/scripts/reconcile-abandoned-agent.mjs b/scripts/reconcile-abandoned-agent.mjs
new file mode 100644
index 0000000000..e1ed79ffdf
--- /dev/null
+++ b/scripts/reconcile-abandoned-agent.mjs
@@ -0,0 +1,9 @@
+#!/usr/bin/env node
+// Local operator tool. Does not kill work or declare an audit successful.
+import { reconcileAbandonedAgent } from '../server/services/abandonedAgentRecovery.js';
+const [agentId, runId, confirmation, ...reason] = process.argv.slice(2);
+try {
+ if (confirmation !== '--confirm-abandoned') throw new Error('Usage: node scripts/reconcile-abandoned-agent.mjs <agent-id> <run-id> --confirm-abandoned <reason>');
+ const receipt = await reconcileAbandonedAgent({ agentId, runId, confirmAbandoned: true, reason: reason.join(' ') });
+ console.log(JSON.stringify({ disposition: receipt.disposition, agentId: receipt.agentId, runId: receipt.runId, replayed: receipt.replayed ?? false }));
+} catch (error) { console.error(`❌ ${error.message}`); process.exitCode = 1; }
diff --git a/server/lib/maintenanceAdmission.js b/server/lib/maintenanceAdmission.js
index 7e2df4c4e5..b1117c37fd 100644
--- a/server/lib/maintenanceAdmission.js
+++ b/server/lib/maintenanceAdmission.js
@@ -254,9 +254,24 @@ export function createMaintenanceAdmission(dataDir = PATHS.data, { io = fs, asse
});
return status();
};
+ // Owning-service recovery only. Validation and durable receipt publication
+ // run under the same journal lock as the exact reservation removal.
+ const reconcileAbandonedAgent = ({ hold, agentId, validate, publish, replay }) => transaction(state => {
+ if (state.hold?.id !== hold.id || state.hold?.revision !== hold.revision || state.exclusive)
+ throw error('MAINTENANCE_STALE', 'The recovery hold changed or is exclusively owned.');
+ const matches = state.operations.filter(op => op.resource === agentId);
+ if (matches.length === 0) return replay();
+ if (matches.length !== 1 || matches[0].kind !== 'agent' || matches[0].unsettled)
+ throw error('MAINTENANCE_STALE', 'Recovery requires exactly one settled agent reservation.');
+ const operation = { ...matches[0] };
+ validate(operation);
+ const receipt = publish(operation);
+ state.operations = state.operations.filter(op => op.id !== operation.id);
+ return receipt;
+ });
const { observeIdle, claimReady, getExclusive, transitionExclusive, settleExclusive, issueExecutionCapability } = exclusive;
return { directory, status, held, assertOpen, admit, tryAdmit, recoverOwned, run, currentId, finish, finishResource, withResource, markResourceUnsettled, markCurrentUnsettled, continueSettlement, begin, resume, events,
- observeIdle, claimReady, getExclusive, transitionExclusive, settleExclusive, issueExecutionCapability };
+ observeIdle, claimReady, getExclusive, transitionExclusive, settleExclusive, issueExecutionCapability, reconcileAbandonedAgent };
}
// Resolve the configured data root on first use, after host/test setup.
diff --git a/server/services/abandonedAgentRecovery.js b/server/services/abandonedAgentRecovery.js
new file mode 100644
index 0000000000..928ade5059
--- /dev/null
+++ b/server/services/abandonedAgentRecovery.js
@@ -0,0 +1,113 @@
+/** Explicit operator abandonment, never a successful-run or cleanup verdict. */
+import * as fs from 'node:fs';
+import { join, resolve } from 'node:path';
+import { homedir } from 'node:os';
+import { createHash, randomUUID } from 'node:crypto';
+import { z } from 'zod';
+import { PATHS } from '../lib/paths.js';
+import { maintenance } from '../lib/maintenanceAdmission.js';
+import { execGit } from '../lib/execGit.js';
+import { getActiveAgentsFromRunner } from './cosRunnerClient.js';
+
+const inputSchema = z.object({
+ agentId: z.string().regex(/^agent-[a-zA-Z0-9-]+$/), runId: z.string().uuid(),
+ reason: z.string().trim().min(10).max(500), confirmAbandoned: z.literal(true),
+}).strict();
+const refuse = message => { throw Object.assign(new Error(message), { code: 'MAINTENANCE_STALE' }); };
+const digest = text => createHash('sha256').update(text).digest('hex');
+const absent = path => { try { fs.lstatSync(path); return false; } catch (e) { if (e.code === 'ENOENT') return true; throw e; } };
+const dead = pid => {
+ if (!Number.isInteger(pid) || pid < 1) return false;
+ try { process.kill(pid, 0); return false; } catch (e) { return e.code === 'ESRCH'; }
+};
+
+export async function reconcileAbandonedAgent(input, deps = {}) {
+ const request = inputSchema.parse(input);
+ const data = deps.data ?? PATHS.data;
+ const gate = deps.gate ?? maintenance;
+ const isDead = deps.isDead ?? dead;
+ const hold = gate.status().hold;
+ if (!hold) refuse('Begin a maintenance hold before reconciliation.');
+ const runner = await (deps.runner ?? getActiveAgentsFromRunner)();
+ if (!Array.isArray(runner) || runner.some(row => !row || typeof row.id !== 'string' || row.id === request.agentId))
+ refuse('Runner ownership is active or unreadable.');
+ const workspace = join(data, 'cos', 'worktrees', request.agentId);
+ const git = deps.git ?? (args => execGit(args, PATHS.installRoot));
+ const branches = await git(['branch', '--list', `*${request.agentId}*`]);
+ const worktrees = await git(['worktree', 'list', '--porcelain']);
+ if (branches.stdout.trim() || worktrees.stdout.split('\n').includes(`worktree ${workspace}`))
+ refuse('Preserved Git work needs recovery before abandonment.');
+ const receiptPath = join(gate.directory, `abandoned-${request.runId}.json`);
+ const readReceipt = () => {
+ const receipt = JSON.parse(fs.readFileSync(receiptPath, 'utf8'));
+ if (receipt.version !== 1 || receipt.disposition !== 'abandoned' || receipt.runId !== request.runId
+ || receipt.agentId !== request.agentId || receipt.reason !== request.reason || !receipt.operation?.id)
+ refuse('The existing abandonment receipt does not match this request.');
+ return receipt;
+ };
+ let evidence;
+ const validate = operation => {
+ const state = JSON.parse(fs.readFileSync(join(data, 'cos', 'state.json'), 'utf8'));
+ if (!state.agents || Array.isArray(state.agents) || typeof state.agents !== 'object'
+ || Object.hasOwn(state.agents, request.agentId)) refuse('Agent ownership is present or unreadable.');
+ if (!absent(workspace) || !absent(join(data, 'cos', 'agents', request.agentId)))
+ refuse('Retained agent output or workspace needs recovery.');
+ const agentsDirectory = join(data, 'cos', 'agents');
+ if (!absent(agentsDirectory) && fs.readdirSync(agentsDirectory).some(date => /^\d{4}-\d{2}-\d{2}$/.test(date)
+ && !absent(join(agentsDirectory, date, request.agentId)))) refuse('Archived agent output needs recovery.');
+ const raw = fs.readFileSync(join(data, 'runs', request.runId, 'metadata.json'), 'utf8');
+ const run = JSON.parse(raw);
+ const runWorkspace = run.workspacePath?.startsWith('~/') ? join(homedir(), run.workspacePath.slice(2)) : run.workspacePath;
+ if (run.id !== request.runId || run.agentId !== request.agentId || !runWorkspace
+ || resolve(runWorkspace) !== resolve(workspace) || run.endTime != null || run.success != null)
+ refuse('Run identity or unfinished outcome does not match.');
+ if (fs.readFileSync(join(data, 'runs', request.runId, 'output.txt')).length !== 0)
+ refuse('Run output is not empty; inspect and recover it instead.');
+ // Read both retained generations strictly: missing archive is normal, malformed data is not.
+ const events = [];
+ for (const name of ['run-events.1.jsonl', 'run-events.jsonl']) {
+ const path = join(data, 'cos', name);
+ if (name.includes('.1.') && absent(path)) continue;
+ for (const line of fs.readFileSync(path, 'utf8').split('\n').filter(Boolean)) {
+ const event = JSON.parse(line);
+ if (event.runId === request.runId || event.agentId === request.agentId) events.push(event);
+ }
+ }
+ if (!events.length || events.some(e => e.runId !== request.runId || e.agentId !== request.agentId || e.taskId !== run.taskId))
+ refuse('Run event identity is incomplete or changed.');
+ const last = events.at(-1);
+ if (last.kind !== 'run.interrupted' || last.data?.reason !== 'killed-by-user')
+ refuse('The last durable event is not a user interruption.');
+ const handoffs = events.filter(e => e.kind === 'run.handoff');
+ if (!handoffs.length || handoffs.some(e => !isDead(e.data?.pid)) || !isDead(operation.pid)) refuse('An owner process may still be alive.');
+ evidence = { metadataHash: digest(raw), eventsHash: digest(JSON.stringify(events)), interruptionEventId: last.eventId };
+ };
+ return gate.reconcileAbandonedAgent({ hold, agentId: request.agentId,
+ validate: operation => {
+ try { validate(operation); } catch (error) { refuse(error.message); }
+ },
+ replay: () => {
+ try { return { ...readReceipt(), replayed: true }; } catch (error) { refuse(error.message); }
+ },
+ publish: operation => {
+ if (!absent(receiptPath)) {
+ let prior;
+ try { prior = readReceipt(); } catch (error) { refuse(error.message); }
+ if (JSON.stringify(prior.operation) !== JSON.stringify(operation)
+ || JSON.stringify(prior.evidence) !== JSON.stringify(evidence)) refuse('Recovery evidence changed since receipt publication.');
+ return prior;
+ }
+ const receipt = { version: 1, disposition: 'abandoned', agentId: request.agentId, runId: request.runId,
+ reason: request.reason, at: new Date().toISOString(), operation, evidence };
+ const pending = `${receiptPath}.${randomUUID()}.pending`;
+ const fd = fs.openSync(pending, 'wx', 0o600);
+ try { fs.writeFileSync(fd, JSON.stringify(receipt) + '\n'); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
+ fs.renameSync(pending, receiptPath);
+ if (process.platform !== 'win32') {
+ const dir = fs.openSync(gate.directory, 'r');
+ try { fs.fsyncSync(dir); } finally { fs.closeSync(dir); }
+ }
+ return receipt;
+ },
+ });
+}
diff --git a/server/services/abandonedAgentRecovery.test.js b/server/services/abandonedAgentRecovery.test.js
new file mode 100644
index 0000000000..563ae8a6b7
--- /dev/null
+++ b/server/services/abandonedAgentRecovery.test.js
@@ -0,0 +1,88 @@
+import { afterEach, beforeEach, expect, it } from 'vitest';
+import * as fs from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { randomUUID } from 'node:crypto';
+import { createMaintenanceAdmission } from '../lib/maintenanceAdmission.js';
+import { reconcileAbandonedAgent } from './abandonedAgentRecovery.js';
+let data, gate, request, deps, operation, hold;
+const save = (path, value) => fs.writeFileSync(path, JSON.stringify(value));
+beforeEach(() => {
+ data = fs.mkdtempSync(join(tmpdir(), 'abandoned-agent-'));
+ gate = createMaintenanceAdmission(data);
+ request = { agentId: 'agent-example', runId: randomUUID(), reason: 'Operator confirms duplicate was abandoned', confirmAbandoned: true };
+ fs.mkdirSync(join(data, 'cos'), { recursive: true });
+ fs.mkdirSync(join(data, 'runs', request.runId), { recursive: true });
+ save(join(data, 'cos', 'state.json'), { agents: {} });
+ save(join(data, 'runs', request.runId, 'metadata.json'), { id: request.runId, agentId: request.agentId,
+ taskId: 'example-task', workspacePath: join(data, 'cos', 'worktrees', request.agentId), endTime: null, success: null });
+ fs.writeFileSync(join(data, 'runs', request.runId, 'output.txt'), '');
+ fs.writeFileSync(join(data, 'cos', 'run-events.jsonl'), [
+ { kind: 'run.handoff', data: { pid: 12345 } },
+ { kind: 'run.interrupted', data: { reason: 'killed-by-user' } },
+ ].map(e => JSON.stringify({ eventId: randomUUID(), runId: request.runId, agentId: request.agentId, taskId: 'example-task', ...e })).join('\n'));
+ operation = gate.admit('agent', request.agentId);
+ gate.admit('provider', 'other-work');
+ hold = gate.begin({ owner: 'Operator', reason: 'Recovery' }).hold;
+ deps = { data, gate, isDead: () => true, runner: async () => [], git: async () => ({ stdout: '' }) };
+});
+afterEach(() => fs.rmSync(data, { recursive: true, force: true }));
+it('records abandonment, preserves unrelated work and hold, and replays without claiming success', async () => {
+ const receipt = await reconcileAbandonedAgent(request, deps);
+ expect(receipt).toMatchObject({ disposition: 'abandoned', operation: { id: operation.id } });
+ expect(gate.status()).toMatchObject({ state: 'draining', hold, blockers: [{ resource: 'other-work' }] });
+ expect(JSON.parse(fs.readFileSync(join(gate.directory, `abandoned-${request.runId}.json`)))).toEqual(receipt);
+ expect(await reconcileAbandonedAgent(request, deps)).toMatchObject({ ...receipt, replayed: true });
+ expect(JSON.parse(fs.readFileSync(join(data, 'runs', request.runId, 'metadata.json'))).success).toBeNull();
+});
+it.each(['live pid', 'runner owner', 'bad runner', 'agent owner', 'saved output', 'workspace', 'branch', 'bad metadata', 'bad events', 'not user-killed', 'unsettled', 'runner reservation', 'archived output', 'later live handoff'])('preserves ownership for %s and leaves the journal usable', async problem => {
+ if (problem === 'live pid') deps.isDead = () => false;
+ if (problem === 'runner owner') deps.runner = async () => [{ id: request.agentId }];
+ if (problem === 'bad runner') deps.runner = async () => null;
+ if (problem === 'agent owner') save(join(data, 'cos', 'state.json'), { agents: { [request.agentId]: { status: 'paused' } } });
+ if (problem === 'saved output') fs.writeFileSync(join(data, 'runs', request.runId, 'output.txt'), 'unsaved work');
+ if (problem === 'workspace') fs.mkdirSync(join(data, 'cos', 'worktrees', request.agentId), { recursive: true });
+ if (problem === 'branch') deps.git = async () => ({ stdout: 'preserved-branch' });
+ if (problem === 'bad metadata') fs.writeFileSync(join(data, 'runs', request.runId, 'metadata.json'), '{');
+ if (problem === 'bad events') fs.writeFileSync(join(data, 'cos', 'run-events.jsonl'), '{');
+ if (problem === 'not user-killed') fs.writeFileSync(join(data, 'cos', 'run-events.jsonl'), JSON.stringify({ agentId: request.agentId, runId: request.runId, taskId: 'example-task', kind: 'run.completed' }));
+ if (problem === 'unsettled') operation.markUnsettled();
+ if (problem === 'archived output') fs.mkdirSync(join(data, 'cos', 'agents', '2020-01-01', request.agentId), { recursive: true });
+ if (problem === 'later live handoff') {
+ const path = join(data, 'cos', 'run-events.jsonl');
+ const events = fs.readFileSync(path, 'utf8').split('\n');
+ events.splice(1, 0, JSON.stringify({ eventId: randomUUID(), runId: request.runId, agentId: request.agentId, taskId: 'example-task', kind: 'run.handoff', data: { pid: 888 } }));
+ fs.writeFileSync(path, events.join('\n')); deps.isDead = pid => pid !== 888;
+ }
+ if (problem === 'runner reservation') gate.recoverOwned('runner', request.agentId);
+ await expect(reconcileAbandonedAgent(request, deps)).rejects.toThrow();
+ expect(gate.status().state).toBe('draining');
+ expect(gate.status().blockers).toContainEqual(expect.objectContaining({ resource: request.agentId }));
+});
+it('refuses a changed hold between runner inspection and the journal transaction', async () => {
+ deps.runner = async () => { gate.resume({ id: hold.id, revision: hold.revision }); gate.begin({ owner: 'Other', reason: 'Other hold' }); return []; };
+ await expect(reconcileAbandonedAgent(request, deps)).rejects.toThrow('hold changed');
+ expect(gate.status().blockers).toContainEqual(expect.objectContaining({ resource: request.agentId }));
+});
+it('never spends an old receipt to clear a replacement reservation', async () => {
+ await reconcileAbandonedAgent(request, deps);
+ gate.recoverOwned('agent', request.agentId);
+ await expect(reconcileAbandonedAgent(request, deps)).rejects.toThrow('evidence changed');
+ expect(gate.status().blockers).toContainEqual(expect.objectContaining({ resource: request.agentId }));
+});
+
+it('reuses a fully published receipt when the journal removal did not commit', async () => {
+ const path = join(gate.directory, 'state.json');
+ const before = fs.readFileSync(path);
+ const receipt = await reconcileAbandonedAgent(request, deps);
+ fs.writeFileSync(path, before); // disposable fixture: receipt-first interruption
+ expect(await reconcileAbandonedAgent(request, deps)).toEqual(receipt);
+ expect(gate.status().blockers).toEqual([expect.objectContaining({ resource: 'other-work' })]);
+});
+
+it('refuses a malformed prior receipt without stranding the journal lock', async () => {
+ fs.writeFileSync(join(gate.directory, `abandoned-${request.runId}.json`), '{');
+ await expect(reconcileAbandonedAgent(request, deps)).rejects.toThrow();
+ expect(gate.status().state).toBe('draining');
+ expect(gate.status().blockers).toContainEqual(expect.objectContaining({ resource: request.agentId }));
+});