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: serialize CoS worktree creation to prevent concurrent-spawn race (#2193)
[._.]/ Adam Eivy392a1360dfa9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 85bdcc601c..d5ca0c2538 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -5,6 +5,7 @@- **Swarm claim-issue runs now write the completion sentinel so the task actually finishes.** In `/do:next --swarm` mode the orchestrator ships every issue via a PR and never touches the working tree, so it was skipping the `.agent-done` completion sentinel — leaving the CoS task hanging with no summary as if the run never ended. Phase C of the swarm directive now explicitly instructs the orchestrator to write the sentinel (with a run summary of the issues claimed, their PRs, and merge outcomes) after the serialized merges, while still skipping the per-agent `/simplify`/push steps. (`server/services/cosTaskGenerator.js`)- **[issue-2190] OpenCode Ollama providers now accept any --model flag.** The static `OPENCODE_CONFIG_CONTENT` lacked a models map, so OpenCode rejected every model with "not valid" and the agent sat idle. The config is now built dynamically at spawn time, declaring the provider's configured models (plus the model being run) under `provider.ollama.models` with bare ids — the exact shape OpenCode's `@ai-sdk/openai-compatible` provider validates `--model ollama/<id>` against. Applied across every OpenCode spawn path (CoS CLI/TUI agents, the toolkit CLI/TUI runners, and the light fire-and-collect CLI run), and a migration backfills existing installs' `data/providers.json` so a configured model's map is persisted too. Fixes the TUI eval path for local Ollama models.- **[issue-2191] TUI agents with zero file changes are now marked failed instead of silently succeeding.** A TUI agent that idled out after showing working indicators but made no uncommitted file changes was previously finalized as `success: idle-complete` — deleting the worktree and any evidence of what happened. Now the idle-complete path checks `git status` in the worktree: if the tree is clean, it finalizes as `failure: idle-no-changes` with the TUI buffer tail as error context. Any uncommitted diff is also captured to `worktree-diff.txt` in the agent archive dir before cleanup, so post-mortems can see what (if anything) was left behind.+- **[issue-2193] Concurrent agent spawns no longer race on git worktree creation.** When two tasks for the same app spawned in the same evaluation tick, the first `git worktree add` grabbed git's per-repo worktree lock and the second failed with a lock error — blocking that task with `blockedCategory: worktree-failed` and leaving an orphan branch (`cos/task-…/agent-…`) with no worktree. Worktree creation now serializes per source repo through a single promise tail (the `issueWriteTail` pattern), so same-tick adds queue instead of colliding; `git worktree add` also retries a few times with backoff on lock errors to absorb residual external contention; and on final failure the partially-created branch is deleted (`git branch -D` + `git worktree prune`) so orphan branches stop accumulating. (`server/services/worktreeManager.js`)- **Scheduled improvement tasks with no configured model now follow the active provider's default instead of a stale hardcoded one.** When a self-improvement or managed-app improvement task had no explicit model in its schedule config, the generator pinned a hardcoded `claude-opus-4-5-20251101` into the task — a model that had since dropped out of the `claude-code-tui` provider config, so the scheduler spawned `claude --model claude-opus-4-5-20251101` even after the provider default moved to Opus 4.8. Since a per-task model pin is honored above the provider default (it's passed straight through to the CLI), that stale literal overrode the configured default on every scheduled run. The generator no longer pins a literal: with no configured model it leaves the task's model unset, so model selection resolves the active provider's tier/default model at spawn time and always uses a model the provider actually lists. An explicit per-task or per-schedule model pin still wins as before. (`server/services/cosTaskGenerator.js`)- **An explicit per-task model pin is now always honored — no more silent, expensive downgrades.** When you set a specific model on a CoS task, PortOS validated it against the provider's `models` list and, on any mismatch, *silently fell back to the provider's default (heaviest) model*. Because `claude-code-tui` lists the dated id `claude-haiku-4-5-20251001` while `claude-code` lists the undated `claude-haiku-4-5`, picking "haiku" on the TUI provider quietly ran **Opus** instead. Explicit user-specified models are now passed through to the CLI even when they're not in the convenience list (the CLIs accept any valid id; a genuine typo surfaces as a provider error rather than a costly silent substitution). Auto-selected models still fall back to the tier default as before.- **Worktree tasks now default to opening a PR instead of auto-merging to your default branch.** A CoS task run in an isolated worktree with "Open PR" off merges its commits straight back to the main development branch on completion — fine for trusted agents, dangerous for unreviewed local-model work. Creating a worktree task now defaults "Open PR" on (in the UI, enabling Worktree checks it; via the API, a worktree user-task without an explicit `openPR` defaults to `true`). You can still turn it off per-task for a quick auto-merge, and internal automation (autopilot, self-improvement) keeps its existing auto-merge behavior so nothing starts silently waiting on a human to merge a PR.diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex 7287007bca..050790f18e 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -20,6 +20,80 @@ const WORKTREES_DIR = PATHS.worktrees;// Lockfiles that npm/yarn/pnpm modify as a side-effect — safe to discard during worktree cleanupconst AUTO_GENERATED_LOCKFILES = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'];+// `git worktree add` lock-contention retry (#2193). Git guards a repo's+// worktree bookkeeping (`.git/worktrees`, `.git/index.lock`) with a per-repo+// lock, so two adds fired in the same evaluation tick race — the loser fails+// with a lock error. Serialization (queueWorktreeCreate) removes the common+// same-process race; retry handles residual external contention (a human+// `git` command, another install's tool touching a shared checkout).+const WORKTREE_ADD_MAX_ATTEMPTS = 4;+const WORKTREE_ADD_RETRY_DELAY_MS = 250;++/**+ * True when a git error message indicates lock/contention on the worktree or+ * index lock (as opposed to a genuine, non-retryable failure like a bad ref).+ * Exported for unit testing against real git lock-error wording.+ */+export function isGitLockError(message) {+ return /\.lock|index\.lock|cannot lock|unable to (?:create|write|lock)|File exists|already (?:exists|locked)|another git process/i.test(message || '');+}++/**+ * Run `git worktree add …` with retry on lock contention. Promise-chained+ * (no try/catch) so it stays idiomatic with the rest of the module: on a lock+ * error it backs off and recurses until WORKTREE_ADD_MAX_ATTEMPTS, then lets+ * the final error reject. Non-lock errors (bad base ref, etc.) reject+ * immediately — retrying them just wastes time.+ */+export function addWorktreeWithRetry(args, repo, attempt = 1) {+ return execGit(args, repo).catch((err) => {+ if (attempt >= WORKTREE_ADD_MAX_ATTEMPTS || !isGitLockError(err.message)) throw err;+ console.log(`🌳 Worktree add lock contention (attempt ${attempt}/${WORKTREE_ADD_MAX_ATTEMPTS}), retrying in ${WORKTREE_ADD_RETRY_DELAY_MS}ms: ${err.message}`);+ return new Promise(resolve => setTimeout(resolve, WORKTREE_ADD_RETRY_DELAY_MS))+ .then(() => addWorktreeWithRetry(args, repo, attempt + 1));+ });+}++// Per-source-repo serialization tail for worktree-creating git operations —+// the issueWriteTail pattern (see server/services/pipeline/issues.js). Git+// serializes its own worktree bookkeeping behind a per-repo lock, so two+// `git worktree add` calls in the same evaluation tick race and the loser is+// blocked with `blockedCategory: worktree-failed` (#2193). A single promise+// tail per repo collapses that race: each create awaits the previous one to+// settle before touching the shared `.git/worktrees` state. Keyed by+// realpath-resolved repo path so /var vs /private/var (macOS) don't split the+// tail into two lanes that can still collide.+const worktreeCreateTails = new Map();+function queueWorktreeCreate(repo, fn) {+ let key = repo;+ try { key = realpathSync(repo); } catch { /* repo may not resolve — fall back to the raw path */ }+ if (!key) key = '__unknown__';+ const prev = worktreeCreateTails.get(key) || Promise.resolve();+ const next = prev.then(fn, fn);+ const silenced = next.catch(() => {});+ worktreeCreateTails.set(key, silenced);+ silenced.finally(() => {+ if (worktreeCreateTails.get(key) === silenced) worktreeCreateTails.delete(key);+ });+ return next;+}++/**+ * Delete a branch we tried (and failed) to create a worktree for, plus prune+ * stale worktree bookkeeping — so a failed `git worktree add -b/-B` doesn't+ * leave an orphan branch with no worktree accumulating in the repo (#2193).+ * Best-effort: every step swallows its own error. Only call for NEW-branch+ * adds — never for attach-to-existing-branch, which would delete a branch we+ * didn't create.+ */+async function cleanupOrphanBranch(repo, branchName) {+ if (!branchName) return;+ await execGit(['branch', '-D', branchName], repo).catch(err => {+ console.log(`⚠️ Orphan branch cleanup failed for ${branchName}: ${err.message}`);+ });+ await execGit(['worktree', 'prune'], repo).catch(() => {});+}+/*** Remove a worktree directory robustly: try `git worktree remove --force`, and* if git refuses (locked, already-gone, broken admin files), fall back to a@@ -162,6 +236,12 @@ export function shouldRefuseDefaultBranchMerge(currentBranch, defaultBranch) {* @returns {{ worktreePath: string, branchName: string, baseBranch: string|null, existingBranch?: boolean }} paths for the new worktree*/export async function createWorktree(agentId, sourceWorkspace, taskId, options = {}) {+ // Serialize per source repo so two adds in the same evaluation tick can't+ // race on git's per-repo worktree lock (#2193). See queueWorktreeCreate.+ return queueWorktreeCreate(sourceWorkspace, () => createWorktreeUnlocked(agentId, sourceWorkspace, taskId, options));+}++async function createWorktreeUnlocked(agentId, sourceWorkspace, taskId, options = {}) {if (!existsSync(WORKTREES_DIR)) {await ensureDir(WORKTREES_DIR);}@@ -190,7 +270,7 @@ export async function createWorktree(agentId, sourceWorkspace, taskId, options =const branchName = options.existingBranch;const localExists = (await execGit(['branch', '--list', branchName], sourceWorkspace, { ignoreExitCode: true })).stdout.trim();if (localExists) {- await execGit(['worktree', 'add', worktreePath, branchName], sourceWorkspace);+ await addWorktreeWithRetry(['worktree', 'add', worktreePath, branchName], sourceWorkspace);} else {// No local copy — we need a remote ref. If `git fetch` failed AND the// remote ref isn't available, fail loudly rather than emit a confusing@@ -201,8 +281,9 @@ export async function createWorktree(agentId, sourceWorkspace, taskId, options =if (!remoteExists) {throw new Error(`Cannot attach worktree to ${branchName}: branch missing locally and origin/${branchName} unavailable${fetchSucceeded ? '' : ' (fetch failed)'}`);}- // Use -B (force-create) so we don't fail if a stale local ref exists; track origin- await execGit(['worktree', 'add', '-B', branchName, worktreePath, `origin/${branchName}`], sourceWorkspace);+ // Use -B (force-create) so we don't fail if a stale local ref exists; track origin.+ // Attach path re-uses an existing branch, so no orphan-branch cleanup on failure.+ await addWorktreeWithRetry(['worktree', 'add', '-B', branchName, worktreePath, `origin/${branchName}`], sourceWorkspace);}console.log(`🌳 Created worktree for ${agentId} at ${worktreePath} on existing branch ${branchName}`);return { worktreePath, branchName, baseBranch: null, existingBranch: true, instanceId };@@ -227,11 +308,16 @@ export async function createWorktree(agentId, sourceWorkspace, taskId, options =.then(() => `origin/${baseBranch}`).catch(() => baseBranch);- // Create worktree with a new branch based on the latest default branch- await execGit(+ // Create worktree with a new branch based on the latest default branch.+ // On final failure, delete the partially-created branch so a failed add+ // doesn't leave an orphan branch with no worktree (#2193).+ await addWorktreeWithRetry(['worktree', 'add', '-b', branchName, worktreePath, baseRef],sourceWorkspace- );+ ).catch(async (err) => {+ await cleanupOrphanBranch(sourceWorkspace, branchName);+ throw err;+ });console.log(`🌳 Created worktree for ${agentId} at ${worktreePath} (branch: ${branchName}, base: ${baseRef})`);@@ -367,6 +453,13 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio* Unlike regular worktrees, these persist across runs.*/export async function createPersistentWorktree(featureAgentId, sourceWorkspace, branchName, baseBranch) {+ // Share the per-repo serialization tail with createWorktree so a persistent+ // feature-agent add and a CoS agent add in the same tick can't race git's+ // per-repo worktree lock (#2193).+ return queueWorktreeCreate(sourceWorkspace, () => createPersistentWorktreeUnlocked(featureAgentId, sourceWorkspace, branchName, baseBranch));+}++async function createPersistentWorktreeUnlocked(featureAgentId, sourceWorkspace, branchName, baseBranch) {const FA_WORKTREES = join(WORKTREES_DIR, '..', 'feature-agents', featureAgentId, 'worktree');await ensureDir(join(WORKTREES_DIR, '..', 'feature-agents', featureAgentId));@@ -411,14 +504,18 @@ export async function createPersistentWorktree(featureAgentId, sourceWorkspace,const remoteBranchExists = (await execGit(['branch', '-r', '--list', `origin/${branchName}`], sourceWorkspace)).stdout.trim();if (localBranchExists) {- // Local branch exists - create worktree from existing branch- await execGit(['worktree', 'add', FA_WORKTREES, branchName], sourceWorkspace);+ // Local branch exists - create worktree from existing branch (no orphan+ // cleanup: the branch pre-dates this add).+ await addWorktreeWithRetry(['worktree', 'add', FA_WORKTREES, branchName], sourceWorkspace);} else if (remoteBranchExists) {- // Remote branch exists but no local - track it- await execGit(['worktree', 'add', '--track', '-b', branchName, FA_WORKTREES, `origin/${branchName}`], sourceWorkspace);+ // Remote branch exists but no local - track it. On final failure, drop the+ // partially-created local tracking branch (it re-creates from origin next run).+ await addWorktreeWithRetry(['worktree', 'add', '--track', '-b', branchName, FA_WORKTREES, `origin/${branchName}`], sourceWorkspace)+ .catch(async (err) => { await cleanupOrphanBranch(sourceWorkspace, branchName); throw err; });} else {- // New branch - create from base- await execGit(['worktree', 'add', '-b', branchName, FA_WORKTREES, baseRef], sourceWorkspace);+ // New branch - create from base. Clean up the orphan branch on final failure (#2193).+ await addWorktreeWithRetry(['worktree', 'add', '-b', branchName, FA_WORKTREES, baseRef], sourceWorkspace)+ .catch(async (err) => { await cleanupOrphanBranch(sourceWorkspace, branchName); throw err; });}console.log(`🌳 Created persistent worktree for feature agent ${featureAgentId} at ${FA_WORKTREES} (branch: ${branchName})`);diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.jsindex 48a1a37ab1..1220da6955 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -1,6 +1,19 @@-import { describe, it, expect } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { join } from 'path';-import { shouldRefuseDefaultBranchMerge, isHumanClaimWorktree, classifyWorktreeDirt } from './worktreeManager.js';++// Mock the git exec boundary so addWorktreeWithRetry's retry loop is testable+// without touching a real repo. Pure helpers below don't call execGit, so the+// mock is inert for them.+const execGitMock = vi.fn();+vi.mock('../lib/execGit.js', () => ({ execGit: (...args) => execGitMock(...args) }));++const {+ shouldRefuseDefaultBranchMerge,+ isHumanClaimWorktree,+ classifyWorktreeDirt,+ isGitLockError,+ addWorktreeWithRetry,+} = await import('./worktreeManager.js');/*** Tests for the worktree manager service.@@ -437,3 +450,63 @@ describe('Default-Branch Merge Gate (defense-in-depth)', () => {expect(shouldRefuseDefaultBranchMerge(null, null)).toBe(true);});});++describe('isGitLockError (worktree add lock detection, #2193)', () => {+ it('recognizes the canonical worktree/index lock errors', () => {+ expect(isGitLockError("fatal: Unable to create '/repo/.git/worktrees/agent-x/index.lock': File exists.")).toBe(true);+ expect(isGitLockError('fatal: could not lock config file .git/config: File exists')).toBe(true);+ expect(isGitLockError('error: cannot lock ref')).toBe(true);+ expect(isGitLockError('Another git process seems to be running in this repository')).toBe(true);+ expect(isGitLockError("fatal: '.git/worktrees/foo' already exists")).toBe(true);+ });++ it('does NOT flag genuine, non-retryable failures', () => {+ expect(isGitLockError("fatal: invalid reference: origin/nope")).toBe(false);+ expect(isGitLockError('fatal: not a valid object name')).toBe(false);+ expect(isGitLockError('')).toBe(false);+ expect(isGitLockError(undefined)).toBe(false);+ });+});++describe('addWorktreeWithRetry (lock-contention retry, #2193)', () => {+ beforeEach(() => {+ execGitMock.mockReset();+ vi.useFakeTimers();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it('resolves without retrying on first-attempt success', async () => {+ execGitMock.mockResolvedValueOnce({ stdout: '', stderr: '', exitCode: 0 });+ await addWorktreeWithRetry(['worktree', 'add', '/wt', 'main'], '/repo');+ expect(execGitMock).toHaveBeenCalledTimes(1);+ });++ it('retries a lock error then succeeds', async () => {+ execGitMock+ .mockRejectedValueOnce(new Error("Unable to create '/repo/.git/index.lock': File exists"))+ .mockResolvedValueOnce({ stdout: '', stderr: '', exitCode: 0 });+ const p = addWorktreeWithRetry(['worktree', 'add', '/wt', 'main'], '/repo');+ await vi.runAllTimersAsync();+ await p;+ expect(execGitMock).toHaveBeenCalledTimes(2);+ });++ it('gives up after the max attempts on persistent lock contention', async () => {+ execGitMock.mockRejectedValue(new Error('cannot lock ref'));+ const p = addWorktreeWithRetry(['worktree', 'add', '/wt', 'main'], '/repo');+ const assertion = expect(p).rejects.toThrow(/cannot lock ref/);+ await vi.runAllTimersAsync();+ await assertion;+ // WORKTREE_ADD_MAX_ATTEMPTS === 4+ expect(execGitMock).toHaveBeenCalledTimes(4);+ });++ it('does NOT retry a non-lock (permanent) error', async () => {+ execGitMock.mockRejectedValueOnce(new Error('fatal: invalid reference: origin/nope'));+ await expect(addWorktreeWithRetry(['worktree', 'add', '/wt', 'origin/nope'], '/repo'))+ .rejects.toThrow(/invalid reference/);+ expect(execGitMock).toHaveBeenCalledTimes(1);+ });+});