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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: sweep stale .agent-done sentinels out of agent workspaces
Adam Eivyb4e5a7811948
diff --git a/server/lib/README.md b/server/lib/README.mdindex 88b35acdb6..87ae3da960 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -55,7 +55,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `agentRunReconcile.js` | CoS run reconciliation (#4540) — pure diff between a ledger projection (`projectRunStates`) and the durable run record. Closed finding vocabulary `RUN_RECONCILE_FINDINGS` (`record-open`, `record-missing`, `verdict-mismatch`, `ledger-open`), `diffRunRecord()`, `reconcileRunRecords()` with a zero-filled per-kind summary, and `planRunRecordRepair()` — the metadata patch that closes a record the ledger proves is finished. Repairs are one-directional (ledger → record) by design: a record closed while the ledger missed the close is reported, never back-filled, so the stream stays an audit of the record rather than a copy of it. I/O half: `services/agentRunReconciler.js`. || `agentRegistrationRecord.js` | The `registerAgent` payload one spawn writes, projected from its task — `buildAgentRegistration({ task, provider, … })` plus `resolveExecutionMode({ spawnHeadless, useRunner })` (`direct` / `runner` / `tui` / `runner-tui`, replacing a nested ternary chain). `agent.metadata` is a HAND-PICKED projection of `task.metadata`, never a spread: every downstream reader (run cards, `perpetualRefillPlan`, `declaresNoCommitCriterion`, the quota-burn continuation, `featureAgents`) sees the agent record alone, so an unlisted field does not survive the spawn — which is how `quotaBurnStepId` shipped persisted but unprojected (#6406) while this list was maintained inline in a 900-line orchestrator. Pure and synchronous: `primaryCheckoutBaseline` and `providerEndpoint` arrive as VALUES (both were `await`/service calls inline) and `isTruthyMetaFn` is injected the way `inlinePrLifecycleSection` takes it, keeping this leaf out of the agent-state and local-endpoint graphs. || `agentScratchPaths.js` | Runtime scratch PortOS itself writes into an agent worktree and never commits — `PUBLIC_REVIEW_INPUT_FILENAME` / `PUBLIC_REVIEW_PATCH_DIRNAME` (the public-review bundle materialized by `services/modelAbuseGuard.js`), the `AGENT_SCRATCH_PATHS` list, prefix-aware `matchesScratchRoot(path, roots)` and `isAgentScratchPath(path)`. `classifyWorktreeDirt` (`services/worktreeManager.js`) subtracts these for EVERY caller and uses the same matcher for its per-call `ignoredPaths`, so a worktree holding only scratch reads as clean end to end — before this, it was preserved by `removeWorktree`, held by `reapMergedWorktrees`, filed as a repo-state recovery task, and dispatched to a branch-reconcile coordinator, forever. Only STATIC names live here; a run-scoped name like `.agent-done-<agentId>` (`agentSentinel.js`) is passed per call instead. |-| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME`, `doneSentinelName(agentId)` → the per-instance filename `.agent-done-<agentId>` (worktree-less agents share one workspace, so a shared name lets concurrent runs clobber — and finalize on — each other's signal), `doneSentinelPath(workspacePath, agentId)` → the single path every producer and consumer resolves, + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. `extractSentinelPayloadFromTranscript(transcript, isPayload)` (async) is the third tier for programmatic-I/O types ONLY — scans the ANSI-stripped PTY transcript, newest balanced JSON block first, for a payload the model PRINTED instead of writing, and adopts it only if the owning hook's shape predicate accepts it (#3640). `PROGRAMMATIC_OUTPUT_COMPLETION_HEADING` names the briefing section that prints this run's absolute sentinel path — a task-type hook renders its prompt before spawn, so it points the agent at that section by name rather than at a filename it cannot know. |+| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME`, `doneSentinelName(agentId)` → the per-instance filename `.agent-done-<agentId>` (worktree-less agents share one workspace, so a shared name lets concurrent runs clobber — and finalize on — each other's signal), `doneSentinelPath(workspacePath, agentId)` → the single path every producer and consumer resolves, `doneSentinelAgentId(filename)` → its inverse (`''` for the bare unscoped name, `null` for a non-sentinel), so the stale-sentinel sweep in `services/agentSentinelSweep.js` matches leftovers to runs the same way the producer named them, + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. `extractSentinelPayloadFromTranscript(transcript, isPayload)` (async) is the third tier for programmatic-I/O types ONLY — scans the ANSI-stripped PTY transcript, newest balanced JSON block first, for a payload the model PRINTED instead of writing, and adopts it only if the owning hook's shape predicate accepts it (#3640). `PROGRAMMATIC_OUTPUT_COMPLETION_HEADING` names the briefing section that prints this run's absolute sentinel path — a task-type hook renders its prompt before spawn, so it points the agent at that section by name rather than at a filename it cannot know. || `persistentMind.js` | Pure persistent-CoS-mind runtime state: default-off durable shape, normalization, FIFO-message/self-wake selection, interrupted-wake requeue, accepted-route fingerprints/receipts, image-work rollback guard, bounded exponential backoff, watchdog staleness, and next-wake projection. || `persistentMindCapabilities.js` | Default-off persistent-mind action grants plus bounded typed CoS-task, private-Eidoverse, and self-cleanup contracts (app/provider/model/effort, PR completion policy, the optional exact provider/model task allowlist, and mind-owned context scopes). || `cosToolContracts.js` | Provider-neutral `portos_tool` catalog/call schema version, request-id and per-turn bounds, catalog query formats, and Persistent Mind tool-call shape. |diff --git a/server/lib/agentSentinel.js b/server/lib/agentSentinel.jsindex af2f53b8e5..15c1c808e9 100644--- a/server/lib/agentSentinel.js+++ b/server/lib/agentSentinel.js@@ -61,6 +61,25 @@ export function doneSentinelName(agentId) {return slug ? `${DONE_SENTINEL_NAME}-${slug}` : DONE_SENTINEL_NAME;}+/**+ * The agent id encoded in a done-sentinel filename.+ *+ * The inverse of `doneSentinelName`, and the only place that reverses it:+ * a sweep deciding whether a leftover `.agent-done-*` belongs to a run that is+ * still alive has to get the SAME answer the producer got, or it deletes a live+ * run's completion signal.+ *+ * Returns the id for a scoped sentinel, `''` for the bare unscoped+ * `.agent-done` (a real sentinel, attributable to no run), and `null` when the+ * name is not a sentinel at all.+ */+export function doneSentinelAgentId(name) {+ if (typeof name !== 'string') return null;+ if (name === DONE_SENTINEL_NAME) return '';+ const prefix = `${DONE_SENTINEL_NAME}-`;+ return name.startsWith(prefix) && name.length > prefix.length ? name.slice(prefix.length) : null;+}+/*** The one path this run's sentinel lives at — `null` without a workspace.*diff --git a/server/lib/agentSentinel.test.js b/server/lib/agentSentinel.test.jsindex 270a8140b8..52476f31df 100644--- a/server/lib/agentSentinel.test.js+++ b/server/lib/agentSentinel.test.js@@ -1,6 +1,6 @@import { describe, it, expect } from 'vitest';import { join } from 'path';-import { DONE_SENTINEL_NAME, doneSentinelName, doneSentinelPath, extractSentinelPayloadFromTranscript, parseSentinelPayload, salvageSentinelPayload } from './agentSentinel.js';+import { DONE_SENTINEL_NAME, doneSentinelAgentId, doneSentinelName, doneSentinelPath, extractSentinelPayloadFromTranscript, parseSentinelPayload, salvageSentinelPayload } from './agentSentinel.js';describe('agentSentinel', () => {it('exposes the sentinel filename', () => {@@ -48,6 +48,27 @@ describe('agentSentinel', () => {});});+ describe('doneSentinelAgentId', () => {+ it('round-trips every id doneSentinelName produces', () => {+ for (const id of ['agent-1a2b3c', 'agent-aaa', 'a-b.c_d']) {+ expect(doneSentinelAgentId(doneSentinelName(id))).toBe(id);+ }+ });++ it('reports the bare sentinel as belonging to no agent', () => {+ expect(doneSentinelAgentId(DONE_SENTINEL_NAME)).toBe('');+ });++ it('rejects names that are not sentinels', () => {+ // `.agent-done-` with nothing after it is a truncated name, not an id of ''+ // — treating it as the bare sentinel would delete it on the wrong rule.+ expect(doneSentinelAgentId('.agent-done-')).toBeNull();+ expect(doneSentinelAgentId('.agent-doneish')).toBeNull();+ expect(doneSentinelAgentId('README.md')).toBeNull();+ expect(doneSentinelAgentId(null)).toBeNull();+ });+ });+describe('parseSentinelPayload', () => {it('returns empty summary + null payload for missing/blank contents', () => {expect(parseSentinelPayload(null)).toEqual({ summary: '', payload: null });diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex d341e2c635..a36b65811d 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -543,7 +543,11 @@ describe('deferred imports stay deferred (#6156)', () => {// reached through `await import()`, so neither is in that closure — and// bootstrap.js gaining a static import of the notifier cost nothing, because no// server test file statically reaches bootstrap.js.-const MAX_STATIC_INSTANTIATIONS = 104400;+// +80 for services/agentSentinelSweep.test.js: a new leaf suite whose closure is+// the sweep, lib/agentSentinel.js and the fileUtils chain those two already+// share with the rest of the suite. No new edge into a heavy subtree — a new+// test file simply costs its own closure once.+const MAX_STATIC_INSTANTIATIONS = 104480;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);diff --git a/server/services/agentSentinelSweep.js b/server/services/agentSentinelSweep.jsnew file mode 100644index 0000000000..daa1fd4375--- /dev/null+++ b/server/services/agentSentinelSweep.js@@ -0,0 +1,73 @@+/**+ * Stale `.agent-done-*` sentinel sweep.+ *+ * A run's own finalize path deletes its sentinel (`releaseRunResources` in+ * agentTuiSpawning, and the CLI/finalization equivalents), so in the happy case+ * nothing is left behind. Three paths deliberately or unavoidably skip that:+ *+ * - a host shutdown ABANDONS the run and preserves the sentinel on purpose,+ * because the resume needs it (#3202);+ * - a hard kill (`pm2 restart`, SIGKILL, a machine reboot) never reaches any+ * cleanup at all;+ * - the file only vanishes with the worktree for worktree-backed runs.+ *+ * Worktree-less agents share a real checkout — the PortOS repo, or a managed+ * app's own repo — so for them a skipped cleanup leaves an untracked file in the+ * USER'S repository, forever, one per dead run. That is what this sweeps.+ *+ * Safety is the whole design: a sentinel is deleted only when its run is+ * provably not live (its agent id is absent from `protectedAgentIds`) AND the+ * file is older than `STALE_SENTINEL_MIN_AGE_MS`. The age floor covers the+ * window where a sentinel exists before its run is registered, and gives the+ * bare unscoped `.agent-done` — which names no agent and so can never be+ * matched to a live run — its only protection.+ */++import { readdir, stat } from 'fs/promises';+import { join } from 'path';++import { doneSentinelAgentId } from '../lib/agentSentinel.js';+import { HOUR, rmGuarded } from '../lib/fileUtils.js';++/** How long a sentinel must have sat untouched before it counts as abandoned. */+export const STALE_SENTINEL_MIN_AGE_MS = HOUR;++/**+ * Delete abandoned done-sentinels from the given directories.+ *+ * @param {string[]} dirs - workspace roots to sweep (duplicates are fine).+ * @param {Set<string>} protectedAgentIds - agents whose sentinel must survive:+ * everything live, paused, or otherwise not finished. Anything else is+ * "liveness unknown" and removes nothing — the caller passes a non-Set when it+ * could not read the agent state, and sweeping on that list would delete the+ * resume signal of every paused and interrupted run.+ * @returns {Promise<number>} sentinels removed.+ */+export async function sweepStaleDoneSentinels(dirs, protectedAgentIds) {+ if (!(protectedAgentIds instanceof Set)) return 0;+ const cutoff = Date.now() - STALE_SENTINEL_MIN_AGE_MS;+ let removed = 0;++ for (const dir of new Set((dirs || []).filter(d => typeof d === 'string' && d))) {+ const entries = await readdir(dir).catch(() => null);+ if (!entries) continue;++ for (const entry of entries) {+ const agentId = doneSentinelAgentId(entry);+ if (agentId === null) continue;+ if (agentId && protectedAgentIds.has(agentId)) continue;++ const target = join(dir, entry);+ const info = await stat(target).catch(() => null);+ if (!info?.isFile() || info.mtimeMs >= cutoff) continue;++ const gone = await rmGuarded(target, { force: true }).then(() => true, (err) => {+ console.warn(`⚠️ Failed to remove stale sentinel ${entry}: ${err.message}`);+ return false;+ });+ if (gone) removed++;+ }+ }++ return removed;+}diff --git a/server/services/agentSentinelSweep.test.js b/server/services/agentSentinelSweep.test.jsnew file mode 100644index 0000000000..ede9ee141c--- /dev/null+++ b/server/services/agentSentinelSweep.test.js@@ -0,0 +1,73 @@+import { mkdtemp, readdir, utimes, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';++import { describe, it, expect, beforeEach } from 'vitest';++import { sweepStaleDoneSentinels, STALE_SENTINEL_MIN_AGE_MS } from './agentSentinelSweep.js';++let dir;++/** Write a file and back-date it so the sweep's age floor is satisfied. */+async function writeAged(name, ageMs) {+ const target = join(dir, name);+ await writeFile(target, 'summary');+ const when = new Date(Date.now() - ageMs);+ await utimes(target, when, when);+ return target;+}++const OLD = STALE_SENTINEL_MIN_AGE_MS * 2;++beforeEach(async () => {+ dir = await mkdtemp(join(tmpdir(), 'sentinel-sweep-'));+});++describe('sweepStaleDoneSentinels', () => {+ it('removes an abandoned sentinel whose agent is gone, and nothing else', async () => {+ await writeAged('.agent-done-agent-dead', OLD);+ await writeAged('README.md', OLD);+ // `.agent-doneish` has no separator, so it is not a sentinel at all —+ // unlike `.agent-done-ish`, which is exactly what agent id `ish` produces.+ await writeAged('.agent-doneish', OLD);++ expect(await sweepStaleDoneSentinels([dir], new Set())).toBe(1);+ expect((await readdir(dir)).sort()).toEqual(['.agent-doneish', 'README.md']);+ });++ it('keeps the sentinel of an agent that has not finished', async () => {+ await writeAged('.agent-done-agent-live', OLD);++ expect(await sweepStaleDoneSentinels([dir], new Set(['agent-live']))).toBe(0);+ expect(await readdir(dir)).toEqual(['.agent-done-agent-live']);+ });++ it('keeps a fresh sentinel — a run may not be registered yet', async () => {+ await writeAged('.agent-done-agent-new', 1000);++ expect(await sweepStaleDoneSentinels([dir], new Set())).toBe(0);+ expect(await readdir(dir)).toEqual(['.agent-done-agent-new']);+ });++ it('removes the bare unscoped sentinel only once it is old', async () => {+ await writeAged('.agent-done', 1000);+ expect(await sweepStaleDoneSentinels([dir], new Set())).toBe(0);++ await writeAged('.agent-done', OLD);+ expect(await sweepStaleDoneSentinels([dir], new Set())).toBe(1);+ expect(await readdir(dir)).toEqual([]);+ });++ it('removes nothing when liveness is unknown', async () => {+ await writeAged('.agent-done-agent-dead', OLD);++ expect(await sweepStaleDoneSentinels([dir], null)).toBe(0);+ expect(await readdir(dir)).toEqual(['.agent-done-agent-dead']);+ });++ it('skips unreadable or missing directories instead of throwing', async () => {+ await writeAged('.agent-done-agent-dead', OLD);++ expect(await sweepStaleDoneSentinels([join(dir, 'nope'), dir, null, ''], new Set())).toBe(1);+ });+});diff --git a/server/services/autonomousJobs/scriptHandlers.js b/server/services/autonomousJobs/scriptHandlers.jsindex 6d12c1d7a6..47857d3ce2 100644--- a/server/services/autonomousJobs/scriptHandlers.js+++ b/server/services/autonomousJobs/scriptHandlers.js@@ -15,6 +15,7 @@ import { checkAndPrompt as autobiographyCheckAndPrompt } from '../autobiography.import { runGoalCheckIn } from '../goalCheckIn.js'import { cleanupOrphanedWorktrees, reapMergedWorktrees } from '../worktreeManager.js'import { getActiveAgentIds } from '../agentState.js'+import { sweepStaleDoneSentinels } from '../agentSentinelSweep.js'import { runSelfDiagnostics } from './selfDiagnostics.js'import { runBrainParitySweep } from './brainParitySweep.js'@@ -90,12 +91,43 @@ async function agentDataCleanup() {// paused agent's worktree/transcript is never reaped or rm'd out from under a// later resume. (readJSONFile keeps this off the subAgentSpawner import path.)const cosState = await readJSONFile(join(PATHS.cos, 'state.json'), null)+ // Every agent record that has not reached an outcome yet. A superset of+ // `activeIds`: it re-adds the paused agents the in-memory maps drop, and —+ // after a restart — the interrupted runs still recorded `running`, whose+ // `.agent-done` sentinel is exactly the resume state the abandon path+ // preserved on purpose (#3202). Only the sentinel sweep reads this; the+ // worktree reaps below keep using `activeIds`, since an unfinished record left+ // behind by a dead process is precisely what they exist to collect.+ const unfinishedIds = new Set(activeIds)if (cosState?.agents && typeof cosState.agents === 'object') {for (const [id, agent] of Object.entries(cosState.agents)) {if (agent?.status === 'paused') activeIds.add(id)+ if (agent?.status !== 'completed' && agent?.status !== 'failed') unfinishedIds.add(id)}}+ // Worktree-less agents run in a REAL checkout — this repo, or a managed app's+ // own repo — so a sentinel their cleanup never reached sits there as untracked+ // dirt in the user's git status forever. Sweep every workspace they can land+ // in; a worktree-backed sentinel is already carried off with its worktree.+ // Lazy, like `eidoverseProjection` above: `apps.js` drags the PM2/status+ // subtree into this registry's static graph, and this job only needs the list+ // of repo paths (see the import-budget guard in lib/importScoping.test.js).+ const apps = await import('../apps.js').then(m => m.getAllApps()).catch((err) => {+ console.warn(`⚠️ Sentinel sweep could not list apps: ${err.message}`)+ return []+ })+ // `null` when state.json could not be read: without it `unfinishedIds` is just+ // the in-memory map, which is EMPTY after a restart — sweeping on that would+ // delete the resume signal of every paused and interrupted run.+ const sentinelsRemoved = await sweepStaleDoneSentinels(+ [PATHS.root, ...apps.map(app => app?.repoPath)],+ cosState?.agents ? unfinishedIds : null+ ).catch((err) => {+ console.warn(`⚠️ Stale sentinel sweep failed: ${err.message}`)+ return 0+ })+const agentsDir = join(PATHS.cos, 'agents')let cleaned = 0if (existsSync(agentsDir)) {@@ -136,8 +168,8 @@ async function agentDataCleanup() {})const mergedCount = merged?.reaped?.length || 0- console.log(`🧹 Agent data cleanup: removed ${cleaned} dir(s) older than 7 days, reaped ${mergedCount} merged + ${worktreesReaped} orphaned worktree(s)`)- return { cleaned, mergedReaped: mergedCount, worktreesReaped }+ console.log(`🧹 Agent data cleanup: removed ${cleaned} dir(s) older than 7 days, ${sentinelsRemoved} stale sentinel(s), reaped ${mergedCount} merged + ${worktreesReaped} orphaned worktree(s)`)+ return { cleaned, sentinelsRemoved, mergedReaped: mergedCount, worktreesReaped }}/**