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: resume clean Deep submodule branches without moving worktrees

Adam Eivyd374f125652e
diff --git a/docs/DEEP-AUDITS.md b/docs/DEEP-AUDITS.md
index 6fde6499a3..ba432000a1 100644
--- a/docs/DEEP-AUDITS.md
+++ b/docs/DEEP-AUDITS.md
@@ -33,6 +33,6 @@ Fix delivery also requires a post-fix pass against a clean, exact tested revisio
Agents atomically replace their checkpoint files after units, under `data/cos/deep-audit-checkpoints/`, outside source worktrees. Finalization imports them on success, failure or interruption before worktree cleanup. The JSON file preserves progress during an invocation; the UI's persisted counters advance when finalization imports it. Missing or malformed reports remain partial. The files contain private audit evidence and must not be committed. They are retained with CoS data for recovery; database receipts remain authoritative after import.
-Source, inventory, capabilities, exclusions or prompt changes conservatively invalidate current evidence and retain it as historical. This first version invalidates the full generation rather than trying to prove which dependencies were unaffected. That includes resuming against a changed HEAD after an interrupted fix; the earlier discovery remains readable but does not certify the new source. Preserve and use the retained worktree/branch when recovering incomplete remediation.
+Source, inventory, capabilities, exclusions or prompt changes conservatively invalidate current evidence and retain it as historical. This first version invalidates the full generation rather than trying to prove which dependencies were unaffected. That includes resuming against a changed HEAD after an interrupted fix; the earlier discovery remains readable but does not certify the new source. Preserve and use the retained worktree/branch when recovering incomplete remediation. Git cannot move a linked worktree containing submodules: for a verified inactive, clean owned workspace, Deep resume detaches the old tree at its exact HEAD and attaches the preserved branch in a new workspace. The old files remain intact. Dirty, locked or ambiguous submodule workspaces stay blocked for explicit recovery; they are never force-deinitialized or reset.
Evidence is **agent-reported, source-verified**. The server checks assignment, scope, source blob identities, required evidence fields, ordering, separate invocation identity and exact revision bindings. It cannot prove that a natural-language trace is truthful or that a reported command actually ran. Independent challenge is a distinct invocation, not a guarantee of a different provider/model. Existing test and PR review requirements remain necessary. Deep mode may take many explicitly resumed invocations; it has no automatic repeat-until-perfect loop and launches no additional categories on its own.
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index 7bbc06cb39..672cf4f724 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -109,7 +109,7 @@ export { resolveTaskTargetBranch as resolveTaskExistingBranch } from '../lib/tas
*
* @returns {Promise<{ worktreeInfo: object, adoptedFrom: string }|{ refused: string }|null>}
*/
-async function adoptWorktreeHoldingBranch({ agentId, workspacePath, branchName, preferredPath = null, taskId, allowLiveClaim = false }) {
+async function adoptWorktreeHoldingBranch({ agentId, workspacePath, branchName, preferredPath = null, taskId, allowLiveClaim = false, deepResume = false }) {
// Fail CLOSED on an unreadable agent list: an empty protected set would read as
// "nothing is running", which is the one wrong answer here — it would move a
// live run's directory. The caller's timed pause is the safe outcome instead.
@@ -145,10 +145,12 @@ async function adoptWorktreeHoldingBranch({ agentId, workspacePath, branchName,
return null;
}
- const worktreeInfo = await adoptWorktree(agentId, workspacePath, holder.path, branchName).catch(err => {
+ const worktreeInfo = await adoptWorktree(agentId, workspacePath, holder.path, branchName, ...(deepResume ? [{ deepResume: true }] : [])).catch(err => {
+ if (err.code === 'DEEP_RESUME_PRESERVED') return { refused: err.message };
emitLog('warn', `🌳 Could not adopt ${holder.path} holding ${branchName} for task ${taskId}: ${err.message}`, { taskId });
return null;
});
+ if (worktreeInfo?.refused) return { refused: worktreeInfo.refused, deepPreserved: true };
return worktreeInfo ? { worktreeInfo, adoptedFrom: holder.agentId } : null;
}
@@ -192,6 +194,7 @@ async function prepareRequestedWorktree({
preferredPath: resumeWorktreePath,
taskId: task.id,
allowLiveClaim: isNonCommittingCoordinatorTask(task),
+ deepResume: task.metadata?.auditDepth === 'deep',
})
: Promise.resolve(null);
@@ -209,6 +212,10 @@ async function prepareRequestedWorktree({
const takeover = await takeoverPromise;
const attempt = (Number(task.metadata?.worktreeBusyAttempts) || 0) + 1;
if (takeover?.refused) {
+ if (takeover.deepPreserved) {
+ await blockTask(task, takeover.refused, 'deep-audit-partial');
+ return { outcome: 'blocked', reason: takeover.refused };
+ }
const reason = `Branch ownership prevents worktree takeover (${takeover.refused}); retrying after a short cooldown`;
await blockTask(task, reason, attempt <= WORKTREE_BUSY_MAX_ATTEMPTS ? 'worktree-busy' : 'worktree-failed',
attempt <= WORKTREE_BUSY_MAX_ATTEMPTS ? {
diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.js
index 0614aa6252..d1c7c2adc2 100644
--- a/server/services/agentWorkspacePrep.test.js
+++ b/server/services/agentWorkspacePrep.test.js
@@ -642,6 +642,16 @@ describe('prepareAgentWorkspace — the branch is checked out in another worktre
// branch. When a tree PortOS owns already has it — the finished run's own,
// preserved because it was dirty — that tree IS the workspace being asked for,
// and no cooldown was ever going to free it.
+ it('keeps a changed Deep submodule workspace blocked for explicit recovery instead of retrying or creating a fresh branch', async () => {
+ findAdoptableWorktreeForBranch.mockResolvedValue({ path: '/mock/worktrees/agent-y', agentId: 'agent-y' });
+ adoptWorktree.mockRejectedValueOnce(Object.assign(new Error('Preserve retained submodule changes'), { code: 'DEEP_RESUME_PRESERVED' }));
+ const task = followUpTask({ auditDepth: 'deep' });
+ const result = await prepareAgentWorkspace({ agentId: 'agent-new', task });
+ expect(result.outcome).toBe('blocked');
+ expect(createWorktree).not.toHaveBeenCalled();
+ expect(updateTask).toHaveBeenCalledWith(task.id, expect.objectContaining({ metadata: expect.objectContaining({ blockedCategory: 'deep-audit-partial' }) }), expect.anything());
+ });
+
it('adopts the worktree that already holds the branch instead of pausing', async () => {
findAdoptableWorktreeForBranch.mockResolvedValue({ path: '/mock/worktrees/agent-y', agentId: 'agent-y' });
adoptWorktree.mockResolvedValue({
diff --git a/server/services/deepAudit.workspace.test.js b/server/services/deepAudit.workspace.test.js
index 69e70b461d..6bc4094e34 100644
--- a/server/services/deepAudit.workspace.test.js
+++ b/server/services/deepAudit.workspace.test.js
@@ -1,14 +1,23 @@
import { beforeEach, afterEach, expect, it, vi } from 'vitest';
-import { mkdtemp, mkdir, writeFile, rm } from 'fs/promises';
+import { mkdtemp, mkdir, writeFile, readFile, rm } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
import { execGit } from '../lib/execGit.js';
+const fault = vi.hoisted(() => ({ rejectAdd: false }));
+vi.mock('../lib/execGit.js', async original => {
+ const actual = await original();
+ return { execGit: (...args) => {
+ if (fault.rejectAdd && args[0][0] === 'worktree' && args[0][1] === 'add') throw new Error('Synthetic add failure');
+ return actual.execGit(...args);
+ } };
+});
+
const paths = vi.hoisted(() => ({ worktrees: `${process.env.TMPDIR || process.env.TEMP || '/tmp'}/deep-worktrees-${process.pid}`, cos: `${process.env.TMPDIR || process.env.TEMP || '/tmp'}/deep-cos-${process.pid}` }));
vi.mock('../lib/fileUtils.js', async original => ({ ...(await original()), PATHS: paths }));
vi.mock('./instanceIdentity.js', () => ({ ensureInstanceId: async () => 'fixture-instance' }));
vi.mock('./appQualitySchedule.js', () => ({ detectRepoCapabilities: async () => ({ capabilities: {} }) }));
-import { createWorktree } from './worktreeManager.js';
+import { createWorktree, adoptWorktree } from './worktreeManager.js';
import { prepareDeepAudit, getDeepAuditSourceRevision, checkpointDeepAudit } from './deepAudit.js';
let root, repo, ledger;
@@ -23,7 +32,7 @@ const deps = {
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), 'deep-workspace-'));
repo = join(root, 'repo');
- ledger = null;
+ ledger = null; fault.rejectAdd = false;
// Local fixture transport only; no production Git configuration is changed.
vi.stubEnv('GIT_CONFIG_COUNT', '1');
vi.stubEnv('GIT_CONFIG_KEY_0', 'protocol.file.allow');
@@ -72,9 +81,31 @@ it('expands a fresh submodule at its gitlink and refuses to reset retained submo
await prepareDeepAudit({ task, agentId: 'agent-submodule', workspacePath }, deps);
expect(ledger.scope.capabilities.submodules).toEqual([]);
expect(ledger.scope.files.some(f => f.path === 'lib/child/nested.js' && f.kind === 'blob')).toBe(true);
- const nested = join(workspacePath, 'lib/child');
+ fault.rejectAdd = true;
+ await expect(adoptWorktree('agent-failed', repo, workspacePath, worktree.branchName, { deepResume: true }))
+ .rejects.toMatchObject({ code: 'DEEP_RESUME_PRESERVED', message: expect.stringContaining('Synthetic add failure') });
+ expect(await readFile(join(workspacePath, 'lib/child/nested.js'), 'utf8')).toContain('nested = true');
+ fault.rejectAdd = false;
+ // The preserved detached tree can reattach its still-unoccupied branch for a
+ // new explicit attempt; no source reset or submodule deinitialization occurs.
+ await git(['checkout', worktree.branchName], workspacePath);
+ await writeFile(join(workspacePath, 'source.js'), 'export const value = 3;\n'); await commit(workspacePath);
+ const retainedHead = await git(['rev-parse', 'HEAD'], workspacePath);
+ const replacement = await adoptWorktree('agent-next', repo, workspacePath, worktree.branchName, { deepResume: true });
+ expect(await git(['rev-parse', 'HEAD'], replacement.worktreePath)).toBe(retainedHead);
+ expect(await git(['branch', '--show-current'], workspacePath)).toBe('');
+ expect(await readFile(join(workspacePath, 'lib/child/nested.js'), 'utf8')).toContain('nested = true');
+ await prepareDeepAudit({ task, agentId: 'agent-next', workspacePath: replacement.worktreePath }, deps);
+ expect(ledger.scope.capabilities.submodules).toEqual([]);
+ const nested = join(replacement.worktreePath, 'lib/child');
+ await writeFile(join(nested, 'untracked.txt'), 'preserve me');
+ await expect(adoptWorktree('agent-dirty', repo, replacement.worktreePath, worktree.branchName, { deepResume: true })).rejects.toThrow('preserve it');
+ expect(await readFile(join(nested, 'untracked.txt'), 'utf8')).toBe('preserve me');
+ expect(await git(['branch', '--show-current'], replacement.worktreePath)).toBe(worktree.branchName);
+ await rm(join(nested, 'untracked.txt'));
await writeFile(join(nested, 'nested.js'), 'export const nested = false;\n'); await commit(nested);
const retained = await git(['rev-parse', 'HEAD'], nested);
- await expect(prepareDeepAudit({ task, agentId: 'next', workspacePath }, deps)).rejects.toThrow('clean source snapshot');
+ await expect(prepareDeepAudit({ task, agentId: 'next', workspacePath: replacement.worktreePath }, deps)).rejects.toThrow('clean source snapshot');
expect(await git(['rev-parse', 'HEAD'], nested)).toBe(retained);
+ await expect(adoptWorktree('agent-committed-child', repo, replacement.worktreePath, worktree.branchName, { deepResume: true })).rejects.toThrow('preserve it');
});
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 5dbb8511f6..5101879181 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -913,11 +913,11 @@ export async function releaseIdleSiblingNextHolder(sourceWorkspace, branchName,
* @param {string} branchName - the branch that worktree has checked out
* @returns {Promise<{worktreePath: string, branchName: string, baseBranch: null, existingBranch: true, adopted: true, instanceId: string}|null>}
*/
-export async function adoptWorktree(agentId, sourceWorkspace, existingWorktreePath, branchName) {
- return queueWorktreeCreate(sourceWorkspace, () => adoptWorktreeUnlocked(agentId, sourceWorkspace, existingWorktreePath, branchName));
+export async function adoptWorktree(agentId, sourceWorkspace, existingWorktreePath, branchName, options = {}) {
+ return queueWorktreeCreate(sourceWorkspace, () => adoptWorktreeUnlocked(agentId, sourceWorkspace, existingWorktreePath, branchName, options));
}
-async function adoptWorktreeUnlocked(agentId, sourceWorkspace, existingWorktreePath, branchName) {
+async function adoptWorktreeUnlocked(agentId, sourceWorkspace, existingWorktreePath, branchName, options) {
if (!agentId || !sourceWorkspace || !existingWorktreePath || !branchName) return null;
if (!existsSync(existingWorktreePath)) {
console.log(`🌳 Cannot adopt worktree for ${agentId} — ${existingWorktreePath} no longer exists`);
@@ -941,6 +941,32 @@ async function adoptWorktreeUnlocked(agentId, sourceWorkspace, existingWorktreeP
await ensureDir(WORKTREES_DIR);
+ if (options.deepResume) {
+ try {
+ const entries = (await execGit(['ls-files', '--stage'], existingWorktreePath)).stdout;
+ if (/^160000 /m.test(entries)) {
+ // Git cannot move linked worktrees containing submodules, even after
+ // deinit. Preserve the admitted inactive tree intact and transfer only
+ // its clean branch attachment, all under the same repository queue.
+ const currentBranch = (await execGit(['symbolic-ref', '--short', 'HEAD'], existingWorktreePath)).stdout.trim();
+ const head = (await execGit(['rev-parse', 'HEAD'], existingWorktreePath)).stdout.trim();
+ const status = (await execGit(['status', '--porcelain', '--untracked-files=all', '--ignore-submodules=none'], existingWorktreePath)).stdout.trim();
+ const listed = await listWorktrees(sourceWorkspace);
+ const holder = listed.find(entry => pathsEqual(entry.path, existingWorktreePath));
+ if (currentBranch !== branchName || !holder || holder.locked || status) {
+ throw Object.assign(new Error('Retained Deep submodule workspace is changed, locked or ambiguous; preserve it for explicit recovery'), { code: 'DEEP_RESUME_PRESERVED' });
+ }
+ await execGit(['checkout', '--detach', head], existingWorktreePath);
+ const branchHead = (await execGit(['rev-parse', `refs/heads/${branchName}`], sourceWorkspace)).stdout.trim();
+ if (branchHead !== head) throw new Error('Deep resume branch changed during handoff; preserved old workspace');
+ const replacement = await createWorktreeUnlocked(agentId, sourceWorkspace, null, { existingBranch: branchName });
+ return { ...replacement, adopted: true };
+ }
+ } catch (error) {
+ throw Object.assign(new Error(`Deep submodule handoff stopped; retained work is preserved: ${error.message}`, { cause: error }), { code: 'DEEP_RESUME_PRESERVED' });
+ }
+ }
+
// Through the retry wrapper, not raw execGit: `worktree move` mutates the same
// `.git/worktrees` bookkeeping whose per-repo lock motivated the retry (#2193).
const moved = await addWorktreeWithRetry(['worktree', 'move', existingWorktreePath, targetPath], sourceWorkspace)