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

name the CoS completion sentinel per agent instance so worktree-less runs cannot collide

[._.]/ Adam Eivy41ed6c0e703b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ec78203c1a..08d14beecf 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -28,6 +28,8 @@
- A series' pinned image backend now actually renders its comic pages and covers. The pin was saved on the series and honoured by first-pass portraits, but the comic stage sent the install-wide default as an explicit choice — which outranks any pin — so a series pinned to one backend quietly rendered every page and cover on another. The Pipeline visuals default from Settings → Image Gen now applies to these renders too, and a pin naming a backend you have since turned off falls back instead of failing the render.
- Typing on the Shell page no longer doubles capital letters and spaces. `Hi There` arrived at the shell — or at a watched agent TUI — as `HHii TThere`, which made typing a message to a running agent unusable. The terminal forwards most printable keys on keydown and cancels the event there, but hands capitals and space to the browser's keypress default action, which then also fires an input event for the same character. The dictation bridge (which reads those input events to keep voice dictation from garbling) was translating that second event into a second keystroke; it now recognizes an insertion the keypress path already sent and leaves it alone. Voice dictation and soft-keyboard input, which arrive with no keypress behind them, are unaffected.
+- Two CoS agents running without a worktree can no longer steal each other's completion. Agents whose task needs no code change (the issue-filing and reasoning types) all run in the primary checkout, and every one of them wrote its done-signal to the same `.agent-done` file — so with two running at once the second overwrote the first's summary, and each run's 2-second poll finalized on whichever sentinel happened to be there, attributing one agent's result to the other and killing a session that was still working. The sentinel is now named per agent instance (`.agent-done-<agentId>`), resolved from one helper by every side that touches it — the path written into the agent's prompt, the 2-second poll, the durable runner's watch, the CLI exit check, the structured-payload read, and the worktree-cleanup ignore — so a run reads, cleans up, and reports only its own. A Layered Intelligence reasoning run, where that file *is* the deliverable, was also being handed two different filenames in one prompt; its instructions now defer to the sentinel path the briefing gives it. The one behaviour to know about on upgrade: an agent still mid-run when the server restarts was told the old shared name, so it finalizes through its normal idle/exit path rather than the sentinel poll.
+
## Changed
- Adding an app no longer writes a PM2 config into the project on its own. Importing a directory ran the PM2 standardizer the instant detection finished — dropping an `ecosystem.config.cjs` into the repo, commenting the ports out of its `.env` and Vite config, and cutting a git backup branch — before you had even saved the app. Only iOS/macOS/Swift/Xcode projects were exempt, so Docker stacks, Python services, static sites, and anything else you start another way all got a PM2 config they will never use, plus an LLM call nobody asked for. Standardizing is now a button in the Add App wizard that says what it will rewrite, and it is still available later from the Apps list. The wizard also shows the standardizer's live per-step detail while it runs (including the "no git repository, backup skipped" case) instead of one undifferentiated row.
diff --git a/server/lib/README.md b/server/lib/README.md
index bf80bac9bd..b7bc43a0c8 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -26,7 +26,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `validation.js` | Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`, `isSafeRecordId`, `parsePagination`). Re-exports the per-domain validation files below so existing deep imports keep working. |
| `sharedSchemas.js` | Cross-domain Zod fragments that `validation.js` and the per-domain `*Validation.js` files both need, kept in a leaf module so the domain files never import back through `validation.js` (its hoisted `export * from` lines would TDZ). `grokVideoDurationSchema` (grok clip-length union), `cloudModelIdString(message)` (cloud-CLI model-id charset/bounds), `recordRenderPinFields` (the `imageMode`/`imageModelId` per-record render pin pair), and `isSafeSubdirFilter(v)` (relative path with no wildcard, `..` segment, or leading `/`). |
| `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). |
-| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME` + 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). |
+| `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). |
| `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. |
| `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, `QUOTA_BURN_BOUNDS` (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (`normalizeQuotaBurnConfig`). Owns the dispatch-cap sentinel too (`QUOTA_BURN_UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap`) — -1 means the window is not counted, and is the default. Also owns the queued burn task's description shape (`burnTaskDescription` / `quotaBurnFamilyOfDescription`), shared with migration 225. Pure — no storage, no provider I/O. |
| `quotaBurnPresets.js` | `QUOTA_BURN_PROMPT_PRESETS` — ready-made single-focus audit prompts for `agent-prompt` burn jobs (UX, a11y, mobile, failure paths, perf, test gaps, dead code, data safety, docs, security), each filing GitHub issues and changing no code. Templates: picking one COPIES its prompt into the job, so editing them never rewrites a configured job. `findQuotaBurnPreset(id)`. |
diff --git a/server/lib/agentSentinel.js b/server/lib/agentSentinel.js
index f5c682e6ae..9d9d541b71 100644
--- a/server/lib/agentSentinel.js
+++ b/server/lib/agentSentinel.js
@@ -1,8 +1,12 @@
/**
- * The `.agent-done` completion sentinel — shared name + parser.
+ * The `.agent-done` completion sentinel — shared naming + parser.
*
* A finishing agent writes this file into its workspace to signal completion
- * (see agentTuiSpawning's sentinel poll). Historically it held a plain-markdown
+ * (see agentTuiSpawning's sentinel poll). The file is named per agent instance
+ * (`.agent-done-<agentId>`, see `doneSentinelName`) because worktree-less runs
+ * share one workspace and would otherwise clobber each other's signal.
+ *
+ * Historically it held a plain-markdown
* task summary that gets appended to the agent's output. Programmatic-I/O task
* types (see docs/plans/2026-07-09-programmatic-io-scheduled-tasks.md) also need
* a STRUCTURED result back — e.g. Layered Intelligence's reasoner JSON — so the
@@ -16,10 +20,49 @@
* existing markdown sentinel is never misread as structured.
*/
-import { safeJSONParse } from './fileUtils.js';
+import { join } from 'path';
+
+import { safeJSONParse, sanitizeFilename } from './fileUtils.js';
export const DONE_SENTINEL_NAME = '.agent-done';
+/**
+ * The sentinel filename for one agent instance: `.agent-done-<agentId>`.
+ *
+ * Agents that run WITHOUT a worktree (`useWorktree: false` — e.g. the
+ * issue-filing and reasoning task types) all share the primary checkout as
+ * their workspace, so a single shared `.agent-done` is a cross-run hazard: two
+ * concurrent agents overwrite each other's summary, and whichever poll fires
+ * first finalizes the *other* agent's run on a sentinel it never wrote. Scoping
+ * the filename to the agent id keeps each run's done-signal its own file.
+ *
+ * The id goes through the shared `sanitizeFilename` (not a private charset
+ * regex) so this filename answers "is this token safe on disk" the same way the
+ * rest of the repo does. Falls back to the bare name when no usable id is
+ * available, so a caller without one still resolves to something readable.
+ */
+export function doneSentinelName(agentId) {
+ const slug = typeof agentId === 'string' ? sanitizeFilename(agentId.trim()).slice(0, 64) : '';
+ return slug ? `${DONE_SENTINEL_NAME}-${slug}` : DONE_SENTINEL_NAME;
+}
+
+/**
+ * The one path this run's sentinel lives at — `null` without a workspace.
+ *
+ * Every producer and consumer resolves it here: the prompt the agent is given
+ * (agentPromptBuilder), the 2s poll and the durable runner's watch
+ * (agentTuiSpawning), the CLI exit check (agentCliSpawning), and the
+ * output-hook payload read (agentFinalization). One path, not a candidate list:
+ * a second accepted name would give those pollers different answers to "did
+ * this run finish", which is the failure the scoped name exists to remove.
+ *
+ * Pure: callers do their own `existsSync` / read.
+ */
+export function doneSentinelPath(workspacePath, agentId) {
+ if (!workspacePath || typeof workspacePath !== 'string') return null;
+ return join(workspacePath, doneSentinelName(agentId));
+}
+
/**
* Parse `.agent-done` contents into `{ summary, payload }`.
* - `summary`: human-readable text for the agent output/card (never null;
diff --git a/server/lib/agentSentinel.test.js b/server/lib/agentSentinel.test.js
index 96dfa0bab1..59c2445854 100644
--- a/server/lib/agentSentinel.test.js
+++ b/server/lib/agentSentinel.test.js
@@ -1,11 +1,49 @@
import { describe, it, expect } from 'vitest';
-import { DONE_SENTINEL_NAME, extractSentinelPayloadFromTranscript, parseSentinelPayload, salvageSentinelPayload } from './agentSentinel.js';
+import { DONE_SENTINEL_NAME, doneSentinelName, doneSentinelPath, extractSentinelPayloadFromTranscript, parseSentinelPayload, salvageSentinelPayload } from './agentSentinel.js';
describe('agentSentinel', () => {
it('exposes the sentinel filename', () => {
expect(DONE_SENTINEL_NAME).toBe('.agent-done');
});
+ describe('doneSentinelName', () => {
+ it('scopes the filename to the agent instance', () => {
+ expect(doneSentinelName('agent-1a2b3c')).toBe('.agent-done-agent-1a2b3c');
+ });
+
+ it('gives two concurrent agents distinct filenames', () => {
+ expect(doneSentinelName('agent-aaa')).not.toBe(doneSentinelName('agent-bbb'));
+ });
+
+ it('falls back to the shared name when no id is available', () => {
+ expect(doneSentinelName(null)).toBe('.agent-done');
+ expect(doneSentinelName(' ')).toBe('.agent-done');
+ expect(doneSentinelName(42)).toBe('.agent-done');
+ });
+
+ it('sanitizes path separators out of the id so the name stays one file in the workspace', () => {
+ // A traversal-shaped id must not escape the workspace directory.
+ expect(doneSentinelName('../../etc/passwd')).toBe('.agent-done-passwd');
+ expect(doneSentinelName('a b/c')).toBe('.agent-done-c');
+ });
+ });
+
+ describe('doneSentinelPath', () => {
+ it('resolves the run-scoped file inside the workspace', () => {
+ // Worktree-less agents share the primary checkout: a bare `.agent-done`
+ // there may be a sibling run's, and must never finalize this one.
+ expect(doneSentinelPath('/repo', 'agent-1')).toBe('/repo/.agent-done-agent-1');
+ });
+
+ it('degrades to the shared name when no agent id is available', () => {
+ expect(doneSentinelPath('/repo', null)).toBe('/repo/.agent-done');
+ });
+
+ it('returns null without a workspace path', () => {
+ expect(doneSentinelPath(null, 'agent-1')).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/tuiHandshake.js b/server/lib/tuiHandshake.js
index a9bc3d5b07..acac1f03b4 100644
--- a/server/lib/tuiHandshake.js
+++ b/server/lib/tuiHandshake.js
@@ -785,21 +785,24 @@ export const MAX_RUNTIME_WRAP_UP_GRACE_MS = 5 * 60 * 1000;
* read. It names the sentinel path convention rather than an absolute path —
* the agent already knows its own workspace from its system prompt.
*
- * `graceMs` is interpolated so the deadline the agent is told matches the one
- * actually enforced (a drift here would tell the agent it has more time than it
- * has, and it would be reaped mid-wrap-up).
+ * Both arguments are REQUIRED, deliberately: `graceMs` is interpolated so the
+ * deadline the agent is told matches the one actually enforced (a drift there
+ * would promise it more time than it has, and it would be reaped mid-wrap-up),
+ * and `sentinelName` is the caller's per-agent filename (`doneSentinelName`).
+ * A default for either would be a silently-wrong instruction on the one message
+ * whose whole job is telling an about-to-be-reaped agent where to write.
*/
-export function buildWrapUpProdMessage(graceMs = MAX_RUNTIME_WRAP_UP_GRACE_MS) {
+export function buildWrapUpProdMessage(graceMs, sentinelName) {
const minutes = Math.max(1, Math.round(graceMs / 60000));
return [
`STOP — you have hit your maximum runtime and will be terminated in ${minutes} minute(s).`,
'',
'If your work is already shipped (PR opened/merged, or changes committed and pushed),',
- 'write your `.agent-done` sentinel in your workspace root RIGHT NOW with a short summary',
+ `write your \`${sentinelName}\` sentinel in your workspace root RIGHT NOW with a short summary`,
'so this run is recorded as a success. Do not start anything new.',
'',
'If the work is NOT shipped, commit whatever is worth keeping to your branch, push it,',
- 'and then write `.agent-done` describing exactly what is done and what is left.',
+ `and then write \`${sentinelName}\` describing exactly what is done and what is left.`,
].join('\n');
}
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 0e0831908b..48a260889f 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -38,7 +38,7 @@ import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
import { resolvePrCompletion } from '../lib/prDisposition.js';
import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';
-import { DONE_SENTINEL_NAME } from '../lib/agentSentinel.js';
+import { doneSentinelPath } from '../lib/agentSentinel.js';
import { isHostShuttingDown, shouldAbandonForHostShutdown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';
const AGENTS_DIR = PATHS.cosAgents;
@@ -620,7 +620,10 @@ export async function spawnDirectly({
const terminatedByUser = userTerminatedAgents.has(agentId);
if (terminatedByUser) userTerminatedAgents.delete(agentId);
- const completionSentinelPresent = !!workspacePath && existsSync(join(workspacePath, DONE_SENTINEL_NAME));
+ // This run's own sentinel (see doneSentinelName) — a worktree-less agent
+ // shares its workspace and must not read a sibling's signal as its own.
+ const sentinelPath = doneSentinelPath(workspacePath, agentId);
+ const completionSentinelPresent = !!sentinelPath && existsSync(sentinelPath);
const completedBeforeHostShutdown = isHostShuttingDown() && completionSentinelPresent;
// If the user terminated the agent, force success=false even if the
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index b1e03f58d9..fdb145c11a 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -60,6 +60,9 @@ vi.mock('./agentState.js', () => ({
vi.mock('../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
safeJSONParse: (str, fallback) => { try { return JSON.parse(str); } catch { return fallback; } },
+ // agentSentinel builds the per-agent sentinel filename with this — a mock
+ // missing it makes doneSentinelPath throw inside the close handler.
+ sanitizeFilename: (name) => String(name).replace(/[^a-zA-Z0-9._-]/g, '_'),
PATHS: { root: '/tmp', cosAgents: '/tmp/agents', data: '/tmp/data' },
}));
vi.mock('../lib/codexCliOutput.js', () => ({ createCodexStderrFormatter: vi.fn() }));
@@ -929,7 +932,9 @@ describe('stream error containment', () => {
it('still finalizes when the agent already wrote its completion sentinel', async () => {
const { finalizeAgent } = await import('./agentFinalization.js');
- vi.mocked(existsSync).mockImplementation((path) => path === '/tmp/.agent-done');
+ // The sentinel is named per agent instance so two worktree-less runs
+ // sharing one workspace can't be finalized on each other's signal.
+ vi.mocked(existsSync).mockImplementation((path) => path === '/tmp/.agent-done-agent-test');
await runToClose({ ...minimalArgs }, null);
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index 02c5b8e1e7..318bb944b7 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -930,9 +930,11 @@ async function dispatchTaskOutputHook({ agentId, task, success, workspacePath, r
const cwd = readPayload ? (workspacePath || task?.metadata?.repoPath || null) : null;
let payload = null;
if (cwd) {
- const { DONE_SENTINEL_NAME, parseSentinelPayload, salvageSentinelPayload } = await import('../lib/agentSentinel.js');
+ const { doneSentinelPath, parseSentinelPayload, salvageSentinelPayload } = await import('../lib/agentSentinel.js');
const { tryReadFile } = await import('../lib/fileUtils.js');
- const contents = await tryReadFile(join(cwd, DONE_SENTINEL_NAME));
+ // This run's own sentinel (see doneSentinelName) — in a shared workspace a
+ // sibling agent's file must not be consumed as this run's deliverable.
+ const contents = await tryReadFile(doneSentinelPath(cwd, agentId));
payload = parseSentinelPayload(contents).payload;
// A less-capable (often local) reasoner can emit an almost-valid
// `{ summary, payload }` envelope — ```json-fenced, prose-trailed, or with
diff --git a/server/services/agentFinalization.transcriptRescue.test.js b/server/services/agentFinalization.transcriptRescue.test.js
index 5ee1808631..af8c291c10 100644
--- a/server/services/agentFinalization.transcriptRescue.test.js
+++ b/server/services/agentFinalization.transcriptRescue.test.js
@@ -87,7 +87,8 @@ const setupRun = ({ transcript, sentinel = null }) => {
mkdirSync(agentDir, { recursive: true });
mkdirSync(workspace, { recursive: true });
if (transcript !== null) writeFileSync(join(agentDir, 'raw.txt'), transcript);
- if (sentinel !== null) writeFileSync(join(workspace, '.agent-done'), sentinel);
+ // The sentinel filename is scoped to the agent instance (doneSentinelName).
+ if (sentinel !== null) writeFileSync(join(workspace, `.agent-done-${id}`), sentinel);
return { agentId: id, workspacePath: workspace };
};
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 712a8c724b..d7344aefcd 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -390,6 +390,7 @@ async function runAgentSpawn(task) {
providerType: provider.type,
providerId: provider.id,
providerCommand: provider.command,
+ agentId, // scopes the completion sentinel filename — see doneSentinelName
leanMode,
split: splitSystemPrompt
});
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index dd7a464e48..b6094f3cbc 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -19,6 +19,7 @@ import { readJSONFile, PATHS, tryReadFile, expandHome } from '../lib/fileUtils.j
import { loadSlashdoFile, loadSlashdoLib, writeResolvedSlashdoBody } from '../lib/slashdoLoader.js';
import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, MODEL_CAPABLE_CLI_REVIEWERS, describeReviewerCli, isCliReviewer, reviewerCliBinary, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, resolveReviewerConfig, reviewerEffortArgs, buildReviewerEffortNote, resolveKeyedReviewers, buildReviewWithArgs, buildReviewersCsv } from '../lib/validation.js';
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
+import { doneSentinelName } from '../lib/agentSentinel.js';
import { canTypeSlashCommands, resolveSlashdoInvocation, buildSlashdoSection, unreachableReviewerIncludes, SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';
import { shellQuote } from '../lib/shellQuote.js';
import { detectForgeCli } from '../lib/gitForge.js';
@@ -32,6 +33,16 @@ const ROOT_DIR = PATHS.root;
const AGENTS_DIR = PATHS.cosAgents;
const SKILLS_DIR = join(ROOT_DIR, 'data/prompts/skills');
+/**
+ * Absolute path of the completion sentinel this run must write. The spawners'
+ * pollers resolve the same per-instance filename from the same helper (see
+ * `doneSentinelName`), so the path in the prompt and the path PortOS watches
+ * cannot drift apart.
+ */
+function resolveSentinelPath(worktreeInfo, workspaceDir, agentId) {
+ return `${worktreeInfo?.worktreePath || workspaceDir}/${doneSentinelName(agentId)}`;
+}
+
// Appended to every agent briefing. PortOS shares ONE pm2 daemon across many
// apps; an agent restarting "the server" once ran `pm2 kill` and took the whole
// machine (incl. PortOS) down. A PATH shim (server/lib/agentGuard) hard-blocks
@@ -1304,6 +1315,10 @@ export function buildActionOutputCompletionSection({ isTui = false, sentinelPath
* @param {string} [options.providerCommand] - Provider launch command (e.g.
* `'claude'`, `'codex'`, `'opencode'`) — the primary signal, so a
* path-configured or renamed binary is recognised.
+ * @param {string} [options.agentId] - The spawning agent's id. Scopes the
+ * completion sentinel filename to this run (`.agent-done-<agentId>`) so two
+ * worktree-less agents sharing the primary checkout can't overwrite — or
+ * finalize on — each other's done-signal. Omitted → the legacy shared name.
* @param {boolean} [options.leanMode] - Ollama-backed Claude session launched with
* `--bare` (see `applyLeanClaudeArgs`): the completion workflow drops slashdo
* commands (bare mode skips command discovery) in favor of plain `git`/`gh`.
@@ -1322,6 +1337,7 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo
const providerType = options.providerType || PROVIDER_TYPES.API;
const providerId = options.providerId || null;
const providerCommand = options.providerCommand || null;
+ const agentId = options.agentId || null;
const isTui = providerType === PROVIDER_TYPES.TUI;
const leanMode = options.leanMode === true;
@@ -1364,7 +1380,7 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo
: null;
if (LIGHT_CONTEXT_PROVIDER_TYPES.has(providerType)) {
- const lightOptions = { isTui, providerId, providerCommand, leanMode, defaultReviewers, codeReviewDefaults, localAgentLoopBody };
+ const lightOptions = { isTui, providerId, providerCommand, leanMode, agentId, defaultReviewers, codeReviewDefaults, localAgentLoopBody };
return options.split === true
? buildLightContextPromptParts(task, workspaceDir, worktreeInfo, isTruthyMetaFn, lightOptions)
: buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTruthyMetaFn, lightOptions);
@@ -1489,7 +1505,7 @@ After completing your work and before committing, ${simplifyInstruction}. Fix an
// the session, so the prompt does NOT ask the agent to `/quit` (it's a UI
// command the agent can't invoke). See `buildTuiCompletionSection` below.)
const tuiCompletionCommand = willOpenPR ? '/do:pr' : '/do:push';
- const sentinelPath = `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`;
+ const sentinelPath = resolveSentinelPath(worktreeInfo, workspaceDir, agentId);
// A discard task's completion is the sentinel-only contract (no push/PR/merge),
// and this applies to every provider type — so it wins over the isTui fork and
// over the fallback template's commit/push instructions below.
@@ -1562,7 +1578,7 @@ After your task completes, the system will spawn a follow-up agent that runs the
// rather than re-reading the lib a second time.
reviewLoopFollowUpSection = buildReviewLoopFollowUpSection(task.metadata || {}, { verbose: true, rprBody, localAgentLoopBody });
if (isTui) {
- const sentinelPath = `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`;
+ const sentinelPath = resolveSentinelPath(worktreeInfo, workspaceDir, agentId);
const branchName = worktreeInfo?.branchName || task.metadata?.reviewLoopPRBranch || null;
const sentinelTail = branchName ? ` ## Branch\n ${branchName}` : ' ## Branch\n <branch name>';
reviewLoopFollowUpSection += '\n\n' + [
@@ -1786,7 +1802,7 @@ export function buildLightContextPromptParts(task, workspaceDir, worktreeInfo, i
const BEGIN_WORKING_LINE = 'Begin working on the task now.';
-function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetaFn, { isTui = true, providerId = null, providerCommand = null, leanMode = false, defaultReviewers, codeReviewDefaults, localAgentLoopBody = null } = {}) {
+function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetaFn, { isTui = true, providerId = null, providerCommand = null, leanMode = false, agentId = null, defaultReviewers, codeReviewDefaults, localAgentLoopBody = null } = {}) {
// Idempotent with the reconcile in buildAgentPrompt; also protects the
// directly-exported buildLightContextPrompt/Parts entry points.
task = reconcileSplitContext(task);
@@ -1931,22 +1947,22 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
if (noCodeOutput) {
sections.push(buildActionOutputCompletionSection({
isTui,
- sentinelPath: `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`,
+ sentinelPath: resolveSentinelPath(worktreeInfo, workspaceDir, agentId),
}));
} else if (discardWorktree) {
// Reasoning-only task: the sentinel payload (shape set by the task-type
// output hook) is the sole output; the worktree is discarded on exit. Wins
// over the isTui / CLI push-and-PR completion workflows below.
- sections.push(buildProgrammaticOutputCompletionSection(`${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`));
+ sections.push(buildProgrammaticOutputCompletionSection(resolveSentinelPath(worktreeInfo, workspaceDir, agentId)));
} else if (isReadOnly) {
sections.push(buildReadOnlyCompletionSection({
isTui,
- sentinelPath: `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`,
+ sentinelPath: resolveSentinelPath(worktreeInfo, workspaceDir, agentId),
}));
} else if (isReviewLoopFollowUp) {
sections.push(buildReviewLoopFollowUpSection(task.metadata || {}, { verbose: false, localAgentLoopBody }));
if (isTui) {
- const sentinelPath = `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`;
+ const sentinelPath = resolveSentinelPath(worktreeInfo, workspaceDir, agentId);
const branchName = worktreeInfo?.branchName || task.metadata?.reviewLoopPRBranch || null;
const sentinelTail = branchName ? ` ## Branch\n ${branchName}` : ' ## Branch\n <branch name>';
sections.push([
@@ -1959,7 +1975,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
} else if (isTui) {
sections.push(buildTuiCompletionSection({
willOpenPR, prCompletion, simplifyEnabled, slashdoFree: tuiSlashdoFree,
- sentinelPath: `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`,
+ sentinelPath: resolveSentinelPath(worktreeInfo, workspaceDir, agentId),
branchName: worktreeInfo?.branchName || null,
baseBranch: worktreeInfo?.baseBranch || null,
leavePrOpen: leavesPrForHuman(task),
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 6b3005ac0a..92adcb0e56 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -2472,5 +2472,31 @@ describe('TUI reviewLoopFollowUp completion instructions', () => {
expect(prompt).toContain('cat > "/tmp/wt-1/.agent-done"');
expect(prompt).toContain('## Summary');
});
+
+ // Agents that never take a worktree (issue-filing / reasoning task types run
+ // with `useWorktree: false`) all write into the SAME primary checkout. A shared
+ // `.agent-done` there lets two concurrent runs overwrite each other's summary,
+ // and lets whichever poll ticks first finalize the other agent's run on a
+ // sentinel it never wrote — so the filename carries the agent id.
+ it('names the completion sentinel per agent instance so worktree-less runs cannot collide', async () => {
+ const worktreelessTask = (id) => ({
+ id,
+ description: 'File an issue',
+ metadata: { useWorktree: false, openPR: false, discardWorktree: true, providerId: 'claude-code-tui', providerCommand: 'claude' }
+ });
+ const build = (taskId, agentId) => buildLightContextPrompt(
+ worktreelessTask(taskId), '/repo', null, (v) => v === true || v === 'true',
+ { isTui: true, providerId: 'claude-code-tui', providerCommand: 'claude', agentId }
+ );
+
+ const first = await build('task-a', 'agent-aaa111');
+ const second = await build('task-b', 'agent-bbb222');
+
+ expect(first).toContain('/repo/.agent-done-agent-aaa111');
+ expect(second).toContain('/repo/.agent-done-agent-bbb222');
+ expect(first).not.toContain('/repo/.agent-done-agent-bbb222');
+ // No instruction may still point at the shared filename.
+ expect(first).not.toMatch(/\.agent-done(?![-\w])/);
+ });
});
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 52e6f4e138..22d58db802 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -18,7 +18,7 @@ import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';
import { activeAgents, userTerminatedAgents, pausedAgents, isFalsyMeta, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';
import { isProgrammaticIoTaskType, resolveTaskHookType } from './taskTypeHooks.js';
import { PATHS } from '../lib/fileUtils.js';
-import { DONE_SENTINEL_NAME, parseSentinelPayload } from '../lib/agentSentinel.js';
+import { doneSentinelName, doneSentinelPath as resolveDoneSentinelPath, parseSentinelPayload } from '../lib/agentSentinel.js';
import { shouldAbandonForHostShutdown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';
import { SENTINEL_COMPLETION_MARKER } from '../lib/agentOutputMarkers.js';
import { resolvePrCompletion } from '../lib/prDisposition.js';
@@ -113,7 +113,7 @@ const CONNECTIVITY_PROBE_LEAD_MS = 20000;
// when they've finished /simplify + /do:pr (or /do:push) — we poll for it
// here so the agent gets cleanly finalized as soon as the work is done,
// without waiting on the much longer idle timeout fallback.
-// DONE_SENTINEL_NAME is shared from ../lib/agentSentinel.js.
+// The filename is per agent instance — see doneSentinelName in ../lib/agentSentinel.js.
const DONE_POLL_INTERVAL_MS = 2000;
/**
@@ -414,7 +414,9 @@ function createPasteRetryController({
if (submitEnterTimer) clearInterval(submitEnterTimer);
submitEnterTimer = shellService.pasteToSession(
sessionId,
- buildWrapUpProdMessage(MAX_RUNTIME_WRAP_UP_GRACE_MS),
+ // The agent's OWN sentinel name — the bare `.agent-done` is a path no
+ // poller is watching.
+ buildWrapUpProdMessage(MAX_RUNTIME_WRAP_UP_GRACE_MS, doneSentinelName(agentId)),
{ label: '[cosAgents] max-runtime wrap-up' },
);
@@ -704,7 +706,9 @@ export async function spawnTuiAgent({
// finalize path; finish() also ingests the sentinel directly so the summary
// is captured even if some other path (idle/exit) finalizes first. Computed
// up front so both the watcher AND finish() can read it (see ingestDoneSentinel).
- const doneSentinelPath = workspacePath ? join(workspacePath, DONE_SENTINEL_NAME) : null;
+ // Resolved from the shared helper, so this is byte-identical to the path the
+ // prompt told the agent to write (see resolveSentinelPath).
+ const doneSentinelPath = resolveDoneSentinelPath(workspacePath, agentId);
const promptPreview = prompt.replace(/\s+/g, ' ').slice(0, 100);
const commandName = tuiConfig.command.split('/').pop();
@@ -1058,7 +1062,9 @@ export async function spawnTuiAgent({
});
if (finalized && typeof finalized.success === 'boolean') cleanupSuccess = finalized.success;
} finally {
- if (workspacePath) await rm(join(workspacePath, DONE_SENTINEL_NAME)).catch(() => {});
+ // This run's sentinel only — a sibling agent sharing this workspace owns
+ // its own file and may still be running.
+ if (doneSentinelPath) await rm(doneSentinelPath).catch(() => {});
const reviewOptions = cleanupSuccess && taskOpenPR && !agentOwnsPR
? await resolveReviewLoopOptions(task.metadata, { normalize: normalizeReviewers, isTruthyMeta: isTruthyMetaFn })
@@ -1776,7 +1782,7 @@ export async function spawnTuiAgent({
const doneSentinelTimer = doneSentinelPath ? setInterval(() => {
try {
if (finalized) return;
- if (!existsSync(doneSentinelPath)) return;
+ if (!sentinelPresent()) return;
clearInterval(doneSentinelTimer);
finish({ success: true, exitCode: 0, reason: 'agent-signaled-done' }).catch(err => {
emitLog('error', `Failed to finalize TUI agent ${agentId} after sentinel: ${err.message}`, { agentId });
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 8d16de21e0..1f9f0cc56e 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -603,7 +603,9 @@ describe('spawnTuiAgent runtime', () => {
taskId: 'task-1',
command: 'codex',
workspacePath: '/tmp/ws',
- doneSentinelPath: '/tmp/ws/.agent-done',
+ // Per-agent sentinel: `/tmp/ws` is a SHARED workspace (its basename is not
+ // the agent id), so the run watches only its own `.agent-done-agent-1`.
+ doneSentinelPath: '/tmp/ws/.agent-done-agent-1',
}));
expect(shellService.createShellSession).not.toHaveBeenCalled();
expect(shellService.registerExternalSession).toHaveBeenCalledWith(
@@ -2275,8 +2277,9 @@ describe('spawnTuiAgent runtime', () => {
const { appendFile } = await import('fs/promises');
const sentinel = '## Summary\nImplemented the fix.\n\n## PR\nhttps://example.com/pr/42';
vi.mocked(existsSync).mockReturnValue(true);
+ // The agent writes the run-scoped sentinel name the prompt gave it.
vi.mocked(readFile).mockImplementation(async (p) =>
- typeof p === 'string' && p.endsWith('.agent-done') ? sentinel : ''
+ typeof p === 'string' && p.endsWith('.agent-done-agent-1') ? sentinel : ''
);
const spawnPromise = runSpawn({ workspacePath: '/tmp/ws' });
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.js
index 4b3ca24145..461b1fa28a 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js
@@ -251,8 +251,10 @@ function buildCompletionContract() {
'commit, or open a pull request — any changes you make to this worktree are',
'discarded. Your ONLY output is the JSON described above.',
'',
- 'When you have decided, write a file named `.agent-done` in the current',
- 'directory containing a single JSON object with this shape:',
+ 'When you have decided, write your completion sentinel — the exact filename',
+ 'carries your agent id, so use the path given in the completion section of',
+ 'your briefing, NOT a bare `.agent-done`. It must contain a single JSON',
+ 'object with this shape:',
'',
'```json',
'{ "summary": "<one-line human summary of what you proposed, or that you proposed nothing>",',
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
index 5b4594c2de..f38628af87 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
@@ -287,8 +287,12 @@ describe('buildTaskInput', () => {
const res = await buildTaskInput({ app: APP });
expect(res.skip).toBeUndefined();
expect(res.prompt).toContain('REASONING PROMPT');
- // The completion contract instructing the agent to write .agent-done is appended.
- expect(res.prompt).toContain('.agent-done');
+ // The completion contract is appended. It must point at the sentinel path
+ // from the briefing (the filename carries the agent id, which this hook
+ // cannot know) rather than instructing a bare `.agent-done` no poller
+ // watches.
+ expect(res.prompt).toContain('completion sentinel');
+ expect(res.prompt).toContain('NOT a bare `.agent-done`');
expect(res.providerId).toBe('ollama');
expect(res.model).toBe('qwen');
});
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 903ca39fd7..00ffb85ad0 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -341,7 +341,7 @@ For EACH picked issue, spawn a subagent that runs the single-issue **Phases 2–
## Phase C — Serialize the merges (orchestrator, after all agents finish)
Merge the ready ${pr}s ONE AT A TIME. For each: re-sync onto the latest default branch, gate on **required** CI (one re-run on a flaky required check, then proceed; a real failure or an irreconcilable conflict leaves that ${pr} OPEN and recorded — move to the next), then \`${mergeCmd}\`. After all merges, run Phase 7 cleanup once per merged worktree.
-**Then — orchestrator only, ALWAYS, even though swarm work ships via ${pr}s with no working-tree change — write the completion sentinel** described in the **Completion Workflow** section below (\`.agent-done\`, with a short run summary of the issues claimed + their ${pr}s + merge outcomes). Skip the \`/simplify\` and push/${pr} steps of that workflow (each fan-out agent already ran them), but the sentinel write is NOT optional: it is the ONLY signal that marks this CoS task complete and hands the orchestrator's summary back. A swarm run that ends without the sentinel leaves the task hanging as if it never finished.
+**Then — orchestrator only, ALWAYS, even though swarm work ships via ${pr}s with no working-tree change — write the completion sentinel** described in the **Completion Workflow** section below (write it at the EXACT sentinel path that section gives you — the filename carries your agent id — with a short run summary of the issues claimed + their ${pr}s + merge outcomes). Skip the \`/simplify\` and push/${pr} steps of that workflow (each fan-out agent already ran them), but the sentinel write is NOT optional: it is the ONLY signal that marks this CoS task complete and hands the orchestrator's summary back. A swarm run that ends without the sentinel leaves the task hanging as if it never finished.
Everything not covered above (claim mechanics, branch naming, verify/skip rules, implement conventions, ${pr} body, review loop) is exactly the single-issue flow documented below.
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 61bf6d6397..9f4d049c53 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -483,10 +483,15 @@ describe('resolveSwarmBlock', () => {
it('instructs the orchestrator to still write the completion sentinel after a swarm run', () => {
// Swarm work ships via PRs with no working-tree change, so without an
// explicit instruction the orchestrator skips the completion sentinel and
- // the CoS task hangs as if it never finished. Phase C must name the sentinel.
+ // the CoS task hangs as if it never finished. Phase C must point at the
+ // sentinel — by reference, since the filename carries the agent id and the
+ // exact path is handed over by the Completion Workflow section.
const block = resolveSwarmBlock('claim-issue', 3);
- expect(block).toContain('.agent-done');
+ expect(block).toContain('completion sentinel');
expect(block).toContain('Completion Workflow');
+ // Naming a literal `.agent-done` here would send the orchestrator to a path
+ // no poller watches.
+ expect(block).not.toMatch(/\.agent-done/);
});
it('gives every fan-out agent its own scratch subdirectory', () => {
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 79e13671c4..84d2d25ee7 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -13,6 +13,7 @@ import { existsSync, realpathSync } from 'fs';
import { readdir, rm, stat } from 'fs/promises';
import { join } from 'path';
import { ensureDir, PATHS, sleep, tryReadFile } from '../lib/fileUtils.js';
+import { DONE_SENTINEL_NAME, doneSentinelName } from '../lib/agentSentinel.js';
import { execGit } from '../lib/execGit.js';
import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';
import { ensureInstanceId } from './instances.js';
@@ -542,12 +543,15 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio
warnings.push(`Worktree preserved — git status failed: ${err.message}`);
return { merged: false, removed: false, uncommittedSaved: false, warnings };
}
- // `.agent-done` is a completion sentinel, not authored work. It has already
- // been consumed by finalizeAgent before this cleanup runs. Ignore it for the
- // preservation decision, while still preserving the tree if any real change
- // remains; the eventual forced worktree removal discards the sentinel with the
- // rest of the completed checkout.
- const dirt = classifyWorktreeDirt(dirtyFiles, { ignoredPaths: ['.agent-done'] });
+ // The completion sentinel is not authored work: it has already been consumed
+ // by finalizeAgent before this cleanup runs. Ignore it for the preservation
+ // decision, while still preserving the tree if any real change remains; the
+ // eventual forced worktree removal discards it with the rest of the completed
+ // checkout. Both names — THIS run's `.agent-done-<agentId>` and the legacy
+ // shared one a pre-upgrade run may have left — and no other agent's.
+ const dirt = classifyWorktreeDirt(dirtyFiles, {
+ ignoredPaths: [DONE_SENTINEL_NAME, doneSentinelName(agentId)]
+ });
if (!dirt.clean && options.discardDirt) {
// Throwaway posture: the caller has already established that nothing in this
// tree is wanted. Log what is being dropped so a surprising loss is at least
diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.js
index 80b6262482..3877df40e5 100644
--- a/server/services/worktreeManager.test.js
+++ b/server/services/worktreeManager.test.js
@@ -333,6 +333,21 @@ describe('classifyWorktreeDirt (real exported helper)', () => {
expect(r.hasRealChanges).toBe(true);
expect(r.realChangePaths).toEqual(['src/index.js']);
});
+
+ it('ignores the per-agent sentinel name without hiding real work', () => {
+ // The sentinel filename carries the agent id (see doneSentinelName), so the
+ // caller passes THIS run's name — not a wildcard that would also swallow a
+ // sibling agent's sentinel.
+ const ignoredPaths = ['.agent-done', '.agent-done-agent-1'];
+ expect(classifyWorktreeDirt('?? .agent-done-agent-1', { ignoredPaths }).clean).toBe(true);
+
+ const r = classifyWorktreeDirt('?? .agent-done-agent-1\n M src/index.js', { ignoredPaths });
+ expect(r.hasRealChanges).toBe(true);
+ expect(r.realChangePaths).toEqual(['src/index.js']);
+ // Another agent's sentinel is NOT ignored — an unrelated run's file in a
+ // shared checkout is still dirt this caller must not silently discard.
+ expect(classifyWorktreeDirt('?? .agent-done-agent-2', { ignoredPaths }).clean).toBe(false);
+ });
});
describe('Broken Worktree Detection', () => {
@@ -691,6 +706,15 @@ describe('removeWorktree branch preservation for resume (#3167)', () => {
expect(result.warnings.join(' ')).toContain('notes.md');
});
+ it('removes a completed worktree whose only dirt is the consumed per-agent sentinel', async () => {
+ scriptGit({ porcelain: '?? .agent-done-agent-x' });
+
+ const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: false });
+
+ expect(result.removed).toBe(true);
+ expect(result.warnings).toEqual([]);
+ });
+
it('removes a completed worktree whose only dirt is the consumed sentinel', async () => {
scriptGit({ porcelain: '?? .agent-done' });