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: preserve Deep audit source pins in fresh workspaces

Adam Eivy399f75d93ad0
diff --git a/docs/DEEP-AUDITS.md b/docs/DEEP-AUDITS.md
index ac95dde240..1ef2854140 100644
--- a/docs/DEEP-AUDITS.md
+++ b/docs/DEEP-AUDITS.md
@@ -12,7 +12,7 @@ Manual runs show discovery, reviewed units, satisfied/required pass requirements
## Coverage and completion
-The server pins a clean Git revision, tracked paths and blob IDs, inventory hash, detected capabilities, explicit exclusions, category prompt version, Deep contract version and effective task prompt hash. It inventories root files, code, tests, docs and configuration rather than filtering to popular source suffixes. Initialized submodules are recursively inventoried at their recorded commits. An unexpanded submodule blocks completion. Ignored runtime assets are outside the source inventory; required runtime evidence that cannot be obtained must remain blocked.
+The server pins a clean Git revision, tracked paths and blob IDs, inventory hash, detected capabilities, explicit exclusions, category prompt version, Deep contract version and effective task prompt hash. It inventories root files, code, tests, docs and configuration rather than filtering to popular source suffixes. Fresh isolated workspaces initialize submodules recursively at their recorded commits before inventory. Retained submodule changes are refused rather than reset. Fresh resume workspaces use the server-owned ledger revision even when the default branch has advanced; an unavailable pinned commit blocks launch instead of falling back to a different source. An unexpanded submodule blocks completion. Ignored runtime assets are outside the source inventory; required runtime evidence that cannot be obtained must remain blocked.
The initial units are category × source directory/subsystem × normal, failure, and concurrency/recovery scenarios. This is a minimum, not a claim that those three scenarios exhaust every workflow. Agents can add concrete workflows or entry-point scenarios through `additionalUnits`; additions increase the denominator and require the same passes. They cannot delete inventoried units.
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index c34a8f63e7..7bbc06cb39 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -168,6 +168,9 @@ async function prepareRequestedWorktree({
allowSharedWorkspaceFallback,
}) {
const isolateDependencies = resolveTaskHookType(task) === 'dependency-updates';
+ const baseCommit = task.metadata?.auditDepth === 'deep'
+ ? await (await import('./deepAudit.js')).getDeepAuditSourceRevision(task)
+ : null;
// Detecting the base branch and resolving the branch holder are independent
// reads (a git-branches lookup vs. an agent-liveness + worktree-list check) —
// kick both off before awaiting either so their I/O overlaps instead of
@@ -219,6 +222,7 @@ async function prepareRequestedWorktree({
let worktreeError = null;
const worktreeInfo = takeover?.worktreeInfo || await createWorktree(agentId, workspacePath, task.id, {
baseBranch: detectedBase || undefined,
+ ...(baseCommit ? { baseCommit } : {}),
existingBranch: existingBranch || undefined,
// Only consulted when `existingBranch` names a FORK PR's head, which has no
// `origin/<branch>` to attach to (#6064). Null for every other task, which
diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.js
index 2fb21684b0..0614aa6252 100644
--- a/server/services/agentWorkspacePrep.test.js
+++ b/server/services/agentWorkspacePrep.test.js
@@ -65,6 +65,8 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {
};
});
+vi.mock('./deepAudit.js', () => ({ getDeepAuditSourceRevision: vi.fn().mockResolvedValue('a'.repeat(40)) }));
+
import { prepareAgentWorkspace, resolveTaskExistingBranch } from './agentWorkspacePrep.js';
import { claimContinuationWorkspace } from '../lib/claimContinuation.js';
import { updateTask, addTask, getAgents } from './cos.js';
@@ -116,6 +118,13 @@ describe('prepareAgentWorkspace — Creative Director scratch cwd (#4650)', () =
});
describe('prepareAgentWorkspace', () => {
+ it('provisions a Deep replacement from its server-owned source pin', async () => {
+ createWorktree.mockResolvedValue({ worktreePath: '/mock/worktrees/agent-deep', branchName: 'cos/deep', baseBranch: 'main' });
+ const task = { id: 'deep', taskType: 'internal', metadata: { useWorktree: true, auditDepth: 'deep' } };
+ expect(await prepareAgentWorkspace({ agentId: 'agent-deep', task })).toMatchObject({ outcome: 'ready' });
+ expect(createWorktree).toHaveBeenCalledWith('agent-deep', expect.any(String), 'deep', expect.objectContaining({ baseCommit: 'a'.repeat(40) }));
+ });
+
it('normalizes legacy investigations into isolated PR delivery', async () => {
ensureLatest.mockResolvedValue({ success: true, upToDate: true });
createWorktree.mockResolvedValue({
diff --git a/server/services/deepAudit.js b/server/services/deepAudit.js
index 8ab01b07cf..59713da450 100644
--- a/server/services/deepAudit.js
+++ b/server/services/deepAudit.js
@@ -1,5 +1,5 @@
/** Machine-local, DB-primary coverage evidence. No timers or provider calls. */
-import { join } from 'path';
+import { join, resolve } from 'path';
import { ensureSchema, query, withTransaction } from '../lib/db.js';
import { execGit } from '../lib/execGit.js';
import { atomicWrite, PATHS } from '../lib/fileUtils.js';
@@ -43,7 +43,7 @@ async function inventoryDeepAudit(workspacePath, { promptHash, category }) {
} catch { /* An unreadable submodule stays in scope as an explicit blocker. */ }
}
files = [...files.filter(file => !file.expanded), ...nested].sort((a, b) => a.path.localeCompare(b.path));
- const dirty = (await execGit(['diff', '--name-only', 'HEAD', '--'], workspacePath)).stdout.trim();
+ const dirty = (await execGit(['diff', '--ignore-submodules=none', '--name-only', 'HEAD', '--'], workspacePath)).stdout.trim();
const untracked = (await execGit(['ls-files', '--others', '--exclude-standard', '-z'], workspacePath)).stdout
.split('\0').filter(path => path && !/^\.agent-done(?:-[a-zA-Z0-9_-]+)?(?:\.json)?$/.test(path));
if (dirty || untracked.length) throw new Error('Deep audit needs a clean source snapshot; tracked or untracked changes require a fresh inventory');
@@ -76,12 +76,35 @@ export async function getDeepAuditLedger(id) {
return rows[0]?.ledger ?? null;
}
+/** Read the server-owned pin before provisioning a replacement workspace. */
+export async function getDeepAuditSourceRevision(task, deps = {}) {
+ if (task.metadata?.auditDepth !== 'deep') return null;
+ const ledger = await (deps.readLedger || getDeepAuditLedger)(deepAuditId(task));
+ if (!ledger) return null;
+ const category = isAuditTaskType(resolveTaskHookType(task)) ? normalizeAuditTaskType(resolveTaskHookType(task)) : 'code-quality';
+ const delivery = task.metadata.fileIssues === true || task.metadata.fileIssues === 'true' ? 'file-issues' : 'fix';
+ if (ledger.appId !== task.metadata.app || ledger.category !== category || ledger.delivery !== delivery) {
+ throw new Error('Deep audit resume must keep the same app, category and delivery mode');
+ }
+ return ledger.scope.revision;
+}
+
+/** Expand only a clean snapshot; never reset a retained submodule's work. */
+async function initializeDeepAuditSubmodules(workspacePath) {
+ const directories = (await execGit(['rev-parse', '--git-dir', '--git-common-dir'], workspacePath)).stdout.trim().split('\n');
+ if (directories.length !== 2 || resolve(workspacePath, directories[0]) === resolve(workspacePath, directories[1])) return;
+ const dirty = (await execGit(['diff', '--ignore-submodules=none', '--name-only', 'HEAD', '--'], workspacePath)).stdout.trim();
+ if (dirty) throw new Error('Deep audit needs a clean source snapshot; retained changes must be preserved');
+ await execGit(['submodule', 'update', '--init', '--recursive'], workspacePath);
+}
+
/** Inject at the common spawn boundary, after all saved/custom/legacy task rendering. */
export async function prepareDeepAudit({ task, agentId, workspacePath }, deps = {}) {
if (task.metadata?.auditDepth !== 'deep') return null;
if (!agentId || !workspacePath || !task.metadata?.app || !deepAuditId(task)) throw new Error('Deep audit needs an identified agent, app and workspace');
const category = isAuditTaskType(resolveTaskHookType(task)) ? normalizeAuditTaskType(resolveTaskHookType(task)) : 'code-quality';
const promptHash = canonicalSnapshotChecksum({ description: task.description, prompt: task.metadata?.prompt, context: task.metadata?.context });
+ if (!deps.inventory) await initializeDeepAuditSubmodules(workspacePath);
const scope = await (deps.inventory || inventoryDeepAudit)(workspacePath, { promptHash, category });
const initial = createDeepAuditLedger({ id: deepAuditId(task), appId: task.metadata.app, category, scope,
delivery: task.metadata.fileIssues === true || task.metadata.fileIssues === 'true' ? 'file-issues' : 'fix' });
diff --git a/server/services/deepAudit.workspace.test.js b/server/services/deepAudit.workspace.test.js
new file mode 100644
index 0000000000..69e70b461d
--- /dev/null
+++ b/server/services/deepAudit.workspace.test.js
@@ -0,0 +1,80 @@
+import { beforeEach, afterEach, expect, it, vi } from 'vitest';
+import { mkdtemp, mkdir, writeFile, rm } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { execGit } from '../lib/execGit.js';
+
+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 { prepareDeepAudit, getDeepAuditSourceRevision, checkpointDeepAudit } from './deepAudit.js';
+
+let root, repo, ledger;
+const task = { id: 'audit', description: 'Inspect all source', metadata: { auditDepth: 'deep', app: 'fixture', fileIssues: true, deepAuditId: 'fixture-audit' } };
+const git = async (args, cwd = repo) => (await execGit(args, cwd)).stdout.trim();
+const commit = async cwd => git(['-c', 'user.name=Test', '-c', '[email protected]', '-c', 'commit.gpgsign=false', 'commit', '-am', 'fixture'], cwd);
+const deps = {
+ write: async () => {},
+ mutate: async (_id, initial, mutate) => (ledger = await mutate(structuredClone(ledger || initial))),
+ readLedger: async () => ledger,
+};
+beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), 'deep-workspace-'));
+ repo = join(root, 'repo');
+ ledger = null;
+ // 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');
+ vi.stubEnv('GIT_CONFIG_VALUE_0', 'always');
+ await git(['init', '-b', 'main', repo], root);
+ await writeFile(join(repo, 'source.js'), 'export const value = 1;\n');
+ await git(['add', '.']); await commit(repo);
+ await git(['init', '--bare', join(root, 'remote.git')], root);
+ await git(['remote', 'add', 'origin', join(root, 'remote.git')]);
+ await git(['push', '-u', 'origin', 'main']);
+});
+afterEach(async () => { vi.unstubAllEnvs(); await rm(root, { recursive: true, force: true }); await rm(paths.worktrees, { recursive: true, force: true }); });
+
+it('keeps accepted coverage on a fresh resume after remote main advances; Quick still follows main', async () => {
+ const first = await createWorktree('agent-first', repo, task.id, { baseBranch: 'main', linkDependencies: false });
+ await prepareDeepAudit({ task, agentId: 'agent-first', workspacePath: first.worktreePath }, deps);
+ const pin = ledger.scope.revision;
+ const attempt = ledger.attempts['agent-first'];
+ const unit = ledger.units[0];
+ const report = { version: 1, scopeHash: ledger.scopeHash, attemptId: attempt.id, prerequisiteHash: attempt.prerequisiteHash,
+ pass: attempt.pass, units: [{ id: unit.id, status: 'evidenced', reason: 'Read the full fixture source',
+ sources: unit.files.map(path => ({ path, blob: ledger.scope.files.find(f => f.path === path).blob })),
+ evidence: { method: 'Read source.js', observations: 'Exports a constant without side effects' } }], candidates: [], stopReason: 'Partial checkpoint' };
+ await checkpointDeepAudit({ task, agentId: attempt.id, workspacePath: first.worktreePath, success: true }, { ...deps, read: async () => JSON.stringify(report) });
+ expect(ledger.units[0].evidence.static).toBeTruthy();
+ await writeFile(join(repo, 'source.js'), 'export const value = 2;\n'); await commit(repo); await git(['push', 'origin', 'main']);
+ const baseCommit = await getDeepAuditSourceRevision(task, deps);
+ expect(baseCommit).toBe(pin);
+ const resumed = await createWorktree('agent-resume', repo, task.id, { baseBranch: 'main', baseCommit, linkDependencies: false });
+ await prepareDeepAudit({ task: { ...task, id: 'new-resume-task', metadata: { ...task.metadata, resumedFromAgentId: 'agent-first' } }, agentId: 'agent-resume', workspacePath: resumed.worktreePath }, deps);
+ expect(ledger.generation).toBe(1);
+ expect(ledger.units[0].evidence.static).toBeTruthy();
+ expect(await git(['rev-parse', 'HEAD'], resumed.worktreePath)).toBe(pin);
+ const quick = await createWorktree('agent-quick', repo, 'quick', { baseBranch: 'main', linkDependencies: false });
+ expect(await git(['rev-parse', 'HEAD'], quick.worktreePath)).toBe(await git(['rev-parse', 'HEAD']));
+ await expect(createWorktree('agent-missing', repo, task.id, { baseBranch: 'main', baseCommit: 'f'.repeat(40) })).rejects.toThrow();
+});
+
+it('expands a fresh submodule at its gitlink and refuses to reset retained submodule commits or dirt', async () => {
+ const child = join(root, 'child'); await mkdir(child);
+ await git(['init', child], root); await writeFile(join(child, 'nested.js'), 'export const nested = true;\n');
+ await git(['add', '.'], child); await commit(child);
+ await git(['submodule', 'add', child, 'lib/child']); await commit(repo); await git(['push', 'origin', 'main']);
+ const worktree = await createWorktree('agent-submodule', repo, task.id, { baseBranch: 'main', linkDependencies: false });
+ const workspacePath = worktree.worktreePath;
+ 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');
+ 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');
+ expect(await git(['rev-parse', 'HEAD'], nested)).toBe(retained);
+});
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index a07b9818a1..5dbb8511f6 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -583,6 +583,7 @@ async function ensureForkRemote(sourceWorkspace, forkHead, branchName) {
* @param {string} taskId - Task identifier (included in branch name for traceability)
* @param {object} options - Optional configuration
* @param {string} options.baseBranch - Branch to base the worktree on (auto-detected if omitted)
+ * @param {string} options.baseCommit - Exact server-owned source commit for a fresh Deep resume
* @param {string} options.existingBranch - Pre-existing branch to attach (creates from origin/<branch> if no local copy)
* @param {{remoteUrl: string, ownerLogin: string}} options.forkHead - Where `existingBranch` lives when it is a FORK PR's head, which has no `origin/<branch>`. Consulted only after the local and origin lookups both miss; omitting it preserves today's exact behavior, error message included.
* @param {string} options.planId - PLAN.md item slug ID — when provided, spliced into the branch name as `cos/<taskId>/<planId>/<agentId>` so other agents can detect this item is in flight by scanning branches/PRs
@@ -688,9 +689,16 @@ async function createWorktreeUnlocked(agentId, sourceWorkspace, taskId, options
}
// Prefer the remote ref (freshest state) if available
- const baseRef = await execGit(['rev-parse', `origin/${baseBranch}`], sourceWorkspace)
- .then(() => `origin/${baseBranch}`)
- .catch(() => baseBranch);
+ let baseRef;
+ if (options.baseCommit) {
+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(options.baseCommit)) throw new Error('Invalid pinned source commit');
+ // Missing pins fail closed; falling back to moving main would erase coverage.
+ baseRef = (await execGit(['rev-parse', '--verify', `${options.baseCommit}^{commit}`], sourceWorkspace)).stdout.trim();
+ } else {
+ baseRef = await execGit(['rev-parse', `origin/${baseBranch}`], sourceWorkspace)
+ .then(() => `origin/${baseBranch}`)
+ .catch(() => baseBranch);
+ }
// Create worktree with a new branch based on the latest default branch.
// `--no-track` is load-bearing, not tidiness (#4172): `baseRef` is normally the