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

address review (codex): protect in-use worktrees, strict cron validation, surface run errors

Adam Eivy28a8c56bff5e
diff --git a/client/src/components/settings/BranchReconcileTab.jsx b/client/src/components/settings/BranchReconcileTab.jsx
index 8b155eb405..0018647512 100644
--- a/client/src/components/settings/BranchReconcileTab.jsx
+++ b/client/src/components/settings/BranchReconcileTab.jsx
@@ -80,7 +80,11 @@ export function BranchReconcileTab() {
setRunning(false);
if (!summary) { toast.error('Reconcile run failed'); return; }
setLastRun(summary);
- if (summary.skipped === 'disabled') toast.error('Reconciler is disabled — enable and save first');
+ // The server catches run failures and returns a 200 `{ error }` summary
+ // (the run happens outside the request lifecycle), so a resolved promise is
+ // NOT proof of success — check the failure fields before toasting success.
+ if (summary.error) toast.error(`Reconcile failed: ${summary.error}`);
+ else if (summary.skipped === 'disabled') toast.error('Reconciler is disabled — enable and save first');
else toast.success(`Reconcile: cleaned ${summary.cleaned?.length ?? 0}, coordinator ${summary.queued ? 'queued' : 'not queued'}`);
};
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 6c4adb5821..20618a60a3 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -321,11 +321,12 @@ export const backupConfigSchema = z.object({
// PUT route (.partial()) and re-read on every scheduled run.
export const branchReconcileConfigSchema = z.object({
enabled: z.boolean().optional().default(false),
- // 5- or 6-field cron expression. Validated here (not just typed as a string)
- // so a malformed save can't reach `startBranchReconcileScheduler` and throw
- // out of the boot-time cron parse (which the boot `.catch` would swallow,
- // leaving the scheduler silently unregistered).
- cron: z.string().regex(/^\S+(\s+\S+){4,5}$/, 'cron must have 5 or 6 whitespace-separated fields').optional().default('0 3 * * *'),
+ // Exactly 5 whitespace-separated fields — the only shape `eventScheduler`'s
+ // parser accepts (a 6-field or arbitrary string would register a cron with no
+ // next run, silently never firing). This regex is a cheap field-count gate;
+ // the settings route additionally range-validates via the scheduler's own
+ // `isValidCron` so `99 99 * * *` is rejected too.
+ cron: z.string().regex(/^\S+(\s+\S+){4}$/, 'cron must have exactly 5 whitespace-separated fields').optional().default('0 3 * * *'),
actions: z.object(optionalBooleanMap([
'cleanupMerged', 'openPr', 'resolveConflicts', 'autoMerge'
])).optional().default({})
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index af93e3aa6e..6e00fcd44e 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -52,11 +52,11 @@ describe('validation.js', () => {
expect(branchReconcileConfigSchema.safeParse({ enabled: 'yes' }).success).toBe(false);
});
- it('rejects a malformed cron expression but accepts 5- and 6-field forms', () => {
+ it('accepts a 5-field cron and rejects other field counts', () => {
expect(branchReconcileConfigSchema.safeParse({ cron: 'not a cron' }).success).toBe(false);
- expect(branchReconcileConfigSchema.safeParse({ cron: '0 3 * *' }).success).toBe(false); // only 4 fields
+ expect(branchReconcileConfigSchema.safeParse({ cron: '0 3 * *' }).success).toBe(false); // 4 fields
+ expect(branchReconcileConfigSchema.safeParse({ cron: '0 0 3 * * *' }).success).toBe(false); // 6 fields — scheduler only parses 5
expect(branchReconcileConfigSchema.safeParse({ cron: '0 3 * * *' }).success).toBe(true);
- expect(branchReconcileConfigSchema.safeParse({ cron: '0 0 3 * * *' }).success).toBe(true); // 6-field
});
it('.partial() allows a single-field toggle patch', () => {
diff --git a/server/routes/settings.js b/server/routes/settings.js
index dd99a92525..621e1ea5a7 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -8,7 +8,8 @@ import {
CODEX_PARALLEL_MAX,
CODEX_PARALLEL_DEFAULT,
} from '../services/mediaJobQueue/index.js';
-import { asyncHandler } from '../lib/errorHandler.js';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { isValidCron } from '../services/eventScheduler.js';
import { isPlainObject } from '../lib/objects.js';
import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, branchReconcileConfigSchema, validateRequest } from '../lib/validation.js';
@@ -181,6 +182,13 @@ router.put('/', asyncHandler(async (req, res) => {
// scheduler would then choke on.
if (req.body?.branchReconcile !== undefined) {
validateRequest(branchReconcileConfigSchema.partial(), req.body.branchReconcile);
+ // Range-check the cron against the scheduler's own parser (the schema regex
+ // only counts fields — it can't reject `99 99 * * *`, which would register a
+ // job that never fires).
+ const cron = req.body.branchReconcile.cron;
+ if (cron !== undefined && !isValidCron(cron)) {
+ throw new ServerError(`Invalid cron expression: ${cron}`, { status: 400, code: 'INVALID_CRON' });
+ }
}
// User-defined catalog types moved out of settings.json into PostgreSQL
// (`catalog_user_types`, #1001). The `/api/catalog/types` routes are the only
diff --git a/server/routes/settings.test.js b/server/routes/settings.test.js
index 963cd56916..94ec56403b 100644
--- a/server/routes/settings.test.js
+++ b/server/routes/settings.test.js
@@ -81,3 +81,31 @@ describe('Settings routes — apiAccess slice', () => {
expect(res.body.apiAccess.sdapi.exposed).toBe(true);
});
});
+
+describe('Settings routes — branchReconcile slice', () => {
+ beforeEach(() => { store = {}; });
+
+ it('accepts a valid branchReconcile patch', async () => {
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ branchReconcile: { enabled: true, cron: '0 3 * * *' } });
+ expect(res.status).toBe(200);
+ expect(res.body.branchReconcile.enabled).toBe(true);
+ });
+
+ it('rejects a cron with valid field count but out-of-range values (scheduler cannot run it)', async () => {
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ branchReconcile: { enabled: true, cron: '99 99 * * *' } });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('INVALID_CRON');
+ });
+
+ it('rejects a malformed cron field count via the schema', async () => {
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ branchReconcile: { cron: '0 0 3 * * *' } }); // 6 fields
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ });
+});
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 0b9611ab0a..8134b08159 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -18,7 +18,7 @@
import { getBranches, getDefaultBranch, isBranchMergedInto, deleteBranch } from './git.js';
import { execGit } from '../lib/execGit.js';
-import { listWorktrees, forceRemoveWorktreeDir, classifyWorktreeDirt } from './worktreeManager.js';
+import { listWorktrees, forceRemoveWorktreeDir, classifyWorktreeDirt, isHumanClaimWorktree } from './worktreeManager.js';
import { execGh } from './github.js';
import { getOriginInfo } from '../lib/gitRemote.js';
import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
@@ -94,6 +94,27 @@ async function getOpenPrsByHead(repoPath) {
return byHead;
}
+/**
+ * Reason a worktree must NOT be torn down, or null if it's safe to remove.
+ * Pure — the dangerous-to-remove cases the deterministic cleanup must respect
+ * (mirrors the guards the existing worktree reaper honors):
+ * - locked → the user explicitly `git worktree lock`ed it
+ * - human `/claim` → a `claim-<slug>` worktree self-cleaned by the /claim flow
+ * - active CoS agent → an agent (`agent-<id>`) is currently running in it
+ * Sibling worktrees (`next-issue-*`, etc.) whose basename is none of these fall
+ * through to null and are cleaned normally.
+ *
+ * @param {{ path:string, locked?:boolean, activeAgentIds?:Set<string> }} input
+ * @returns {string|null}
+ */
+export function worktreeProtectionReason({ path, locked, activeAgentIds }) {
+ if (locked) return 'worktree-locked';
+ const basename = (path || '').split('/').pop() || '';
+ if (isHumanClaimWorktree(basename)) return 'worktree-human-claim';
+ if (activeAgentIds?.has(basename)) return 'worktree-active-agent';
+ return null;
+}
+
/**
* Is a worktree's working tree carrying real (non-lockfile) uncommitted changes?
* @param {string} worktreePath
@@ -124,11 +145,11 @@ export async function gatherBranchState(repoPath, { defaultBranch }) {
getOpenPrsByHead(repoPath)
]);
- // Map local branch name -> worktree path (strip the refs/heads/ prefix).
+ // Map local branch name -> worktree record (strip the refs/heads/ prefix).
const worktreeByBranch = new Map();
for (const wt of worktrees) {
const name = wt.branch?.replace(/^refs\/heads\//, '');
- if (name) worktreeByBranch.set(name, wt.path);
+ if (name) worktreeByBranch.set(name, { path: wt.path, locked: Boolean(wt.locked) });
}
const candidates = branches.filter(
@@ -137,7 +158,9 @@ export async function gatherBranchState(repoPath, { defaultBranch }) {
const inputs = [];
for (const b of candidates) {
- const worktreePath = worktreeByBranch.get(b.name) || null;
+ const wt = worktreeByBranch.get(b.name) || null;
+ const worktreePath = wt?.path || null;
+ const worktreeLocked = Boolean(wt?.locked);
const worktreeDirty = worktreePath ? await isWorktreeDirty(worktreePath) : false;
// getBranches' `merged` is ancestor-based (misses squash/rebase); confirm
// the harder cases via isBranchMergedInto (covers squash + rebase). Short
@@ -149,6 +172,7 @@ export async function gatherBranchState(repoPath, { defaultBranch }) {
isMerged,
hasWorktree: Boolean(worktreePath),
worktreePath,
+ worktreeLocked,
worktreeDirty,
openPr: prsByHead.get(b.name) || null
});
@@ -167,9 +191,11 @@ export async function gatherBranchState(repoPath, { defaultBranch }) {
* @param {string} repoPath
* @param {string} defaultBranch
* @param {object[]} merged - gathered inputs whose state === 'MERGED'
+ * @param {{ activeAgentIds?: Set<string> }} [opts] - CoS agents currently running;
+ * their worktrees are never torn down even when the branch is merged + clean.
* @returns {Promise<{cleaned:string[], skipped:{branch:string,reason:string}[]}>}
*/
-export async function cleanupMerged(repoPath, defaultBranch, merged) {
+export async function cleanupMerged(repoPath, defaultBranch, merged, { activeAgentIds = new Set() } = {}) {
const cleaned = [];
const skipped = [];
for (const b of merged) {
@@ -180,6 +206,15 @@ export async function cleanupMerged(repoPath, defaultBranch, merged) {
continue;
}
if (b.worktreePath) {
+ // Never tear down a worktree that's locked, a human /claim session, or an
+ // active CoS agent workspace — even if its branch is merged and clean.
+ const protectedReason = worktreeProtectionReason({
+ path: b.worktreePath, locked: b.worktreeLocked, activeAgentIds
+ });
+ if (protectedReason) {
+ skipped.push({ branch: b.branch, reason: protectedReason });
+ continue;
+ }
const dirty = await isWorktreeDirty(b.worktreePath);
if (dirty) {
skipped.push({ branch: b.branch, reason: 'worktree-dirty' });
@@ -204,11 +239,12 @@ export async function cleanupMerged(repoPath, defaultBranch, merged) {
* in-flight set (branches needing an agent) for the scheduler to dispatch.
*
* @param {string} [repoPath=PATHS.root]
- * @param {{ cleanup?: boolean }} [opts] - when cleanup is false, merged branches
- * are reported (in `skipped`, reason `cleanup-disabled`) but not deleted.
+ * @param {{ cleanup?: boolean, activeAgentIds?: Set<string> }} [opts] - when cleanup
+ * is false, merged branches are reported (in `skipped`, reason `cleanup-disabled`)
+ * but not deleted. `activeAgentIds` protects in-use CoS agent worktrees.
* @returns {Promise<{ defaultBranch:string, cleaned:string[], inFlight:object[], wip:object[], skipped:{branch:string,reason:string}[] }>}
*/
-export async function reconcile(repoPath = PATHS.root, { cleanup = true } = {}) {
+export async function reconcile(repoPath = PATHS.root, { cleanup = true, activeAgentIds = new Set() } = {}) {
const defaultBranch = await getDefaultBranch(repoPath).catch(() => 'main') || 'main';
const inputs = await gatherBranchState(repoPath, { defaultBranch });
const classified = classifyBranches(inputs);
@@ -218,7 +254,7 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true } = {})
const wip = classified.filter((c) => c.state === 'WIP');
const { cleaned, skipped } = cleanup
- ? await cleanupMerged(repoPath, defaultBranch, merged)
+ ? await cleanupMerged(repoPath, defaultBranch, merged, { activeAgentIds })
: { cleaned: [], skipped: merged.map((m) => ({ branch: m.branch, reason: 'cleanup-disabled' })) };
return { defaultBranch, cleaned, inFlight, wip, skipped };
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index 0b8eed80b6..dabb7fbbf0 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -23,7 +23,8 @@ vi.mock('./worktreeManager.js', () => ({
listWorktrees: vi.fn(async () => []),
forceRemoveWorktreeDir: vi.fn(async () => {}),
// Real pure classifier semantics: empty porcelain = clean.
- classifyWorktreeDirt: vi.fn((p) => ({ hasRealChanges: Boolean((p || '').trim()) }))
+ classifyWorktreeDirt: vi.fn((p) => ({ hasRealChanges: Boolean((p || '').trim()) })),
+ isHumanClaimWorktree: vi.fn((id) => typeof id === 'string' && id.startsWith('claim-'))
}));
vi.mock('./github.js', () => ({ execGh: vi.fn(async () => '[]') }));
vi.mock('../lib/gitRemote.js', () => ({
@@ -35,7 +36,7 @@ vi.mock('../lib/fileUtils.js', () => ({
}));
import {
- classifyBranch, classifyBranches, cleanupMerged, reconcile, gatherBranchState
+ classifyBranch, classifyBranches, cleanupMerged, reconcile, gatherBranchState, worktreeProtectionReason
} from './branchReconcile.js';
import * as git from './git.js';
import * as wt from './worktreeManager.js';
@@ -119,6 +120,33 @@ describe('cleanupMerged', () => {
expect(res.cleaned).toEqual(['orphan']);
expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();
});
+
+ it('never tears down a locked / human-claim / active-agent worktree', async () => {
+ git.isBranchMergedInto.mockResolvedValue(true);
+ const activeAgentIds = new Set(['agent-abc12345']);
+ const res = await cleanupMerged('/repo', 'main', [
+ { branch: 'locked-b', worktreePath: '/wt/locked', worktreeLocked: true },
+ { branch: 'claim-b', worktreePath: '/repo/data/cos/worktrees/claim-foo' },
+ { branch: 'active-b', worktreePath: '/repo/data/cos/worktrees/agent-abc12345' }
+ ], { activeAgentIds });
+ expect(res.cleaned).toEqual([]);
+ expect(res.skipped).toEqual([
+ { branch: 'locked-b', reason: 'worktree-locked' },
+ { branch: 'claim-b', reason: 'worktree-human-claim' },
+ { branch: 'active-b', reason: 'worktree-active-agent' }
+ ]);
+ expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();
+ expect(git.deleteBranch).not.toHaveBeenCalled();
+ });
+});
+
+describe('worktreeProtectionReason', () => {
+ it('flags locked, human-claim, and active-agent worktrees; passes ordinary ones', () => {
+ expect(worktreeProtectionReason({ path: '/wt/x', locked: true })).toBe('worktree-locked');
+ expect(worktreeProtectionReason({ path: '/x/claim-foo' })).toBe('worktree-human-claim');
+ expect(worktreeProtectionReason({ path: '/x/agent-1', activeAgentIds: new Set(['agent-1']) })).toBe('worktree-active-agent');
+ expect(worktreeProtectionReason({ path: '/repo/next-issue-2199', activeAgentIds: new Set(['agent-1']) })).toBeNull();
+ });
});
describe('gatherBranchState', () => {
diff --git a/server/services/branchReconcileScheduler.js b/server/services/branchReconcileScheduler.js
index f4f12dc58c..7d8d41879a 100644
--- a/server/services/branchReconcileScheduler.js
+++ b/server/services/branchReconcileScheduler.js
@@ -20,6 +20,7 @@ import { PATHS } from '../lib/fileUtils.js';
import { PRIORITY_VALUES, addTask } from './cosTaskStore.js';
import { reconcile } from './branchReconcile.js';
import { getDomainMode } from '../lib/domainAutonomy.js';
+import { getActiveAgentIds } from './agentState.js';
const CRON_ID = 'branch-reconcile';
@@ -143,7 +144,10 @@ export async function runBranchReconcile({ force = false, now = Date.now() } = {
}
const actions = cfg.actions || {};
- const result = await reconcile(PATHS.root, { cleanup: actionOn(actions, 'cleanupMerged') });
+ const result = await reconcile(PATHS.root, {
+ cleanup: actionOn(actions, 'cleanupMerged'),
+ activeAgentIds: new Set(getActiveAgentIds())
+ });
const actionable = filterActionable(result.inFlight, actions);
let queued = false;
diff --git a/server/services/branchReconcileScheduler.test.js b/server/services/branchReconcileScheduler.test.js
index 407861b289..c9bdc43c5f 100644
--- a/server/services/branchReconcileScheduler.test.js
+++ b/server/services/branchReconcileScheduler.test.js
@@ -20,6 +20,7 @@ vi.mock('./cosTaskStore.js', () => ({
}));
vi.mock('./branchReconcile.js', () => ({ reconcile: vi.fn() }));
vi.mock('./cos.js', () => ({ getConfig: vi.fn(async () => ({ domainAutonomy: { cos: 'execute' } })) }));
+vi.mock('./agentState.js', () => ({ getActiveAgentIds: vi.fn(() => []) }));
vi.mock('../lib/domainAutonomy.js', () => ({ getDomainMode: vi.fn((config) => config?.domainAutonomy?.cos || 'off') }));
import {
@@ -100,14 +101,14 @@ describe('runBranchReconcile', () => {
reconcile.mockResolvedValue({ defaultBranch: 'main', cleaned: [], inFlight: [], wip: [], skipped: [] });
const res = await runBranchReconcile({ force: true, now: 0 });
expect(res.skipped).not.toBe('disabled'); // ran, not short-circuited
- expect(reconcile).toHaveBeenCalledWith('/repo', { cleanup: true });
+ expect(reconcile).toHaveBeenCalledWith('/repo', { cleanup: true, activeAgentIds: expect.any(Set) });
});
it('passes cleanup:false when cleanupMerged disabled', async () => {
getSettings.mockResolvedValue({ branchReconcile: { enabled: true, actions: { cleanupMerged: false } } });
reconcile.mockResolvedValue({ defaultBranch: 'main', cleaned: [], inFlight: [], wip: [], skipped: [] });
await runBranchReconcile({ now: 0 });
- expect(reconcile).toHaveBeenCalledWith('/repo', { cleanup: false });
+ expect(reconcile).toHaveBeenCalledWith('/repo', { cleanup: false, activeAgentIds: expect.any(Set) });
});
it('dispatches a coordinator when actionable branches exist', async () => {
diff --git a/server/services/eventScheduler.js b/server/services/eventScheduler.js
index 671ccc4780..97d0bfee2a 100644
--- a/server/services/eventScheduler.js
+++ b/server/services/eventScheduler.js
@@ -623,6 +623,25 @@ async function triggerNow(id) {
return true
}
+/**
+ * Non-throwing predicate: can this scheduler actually parse+run the expression?
+ * The single source of truth for "a cron value the scheduler will honor" — reuse
+ * this instead of a regex so callers validate against the exact parser (5 fields,
+ * valid numeric ranges) rather than a looser approximation.
+ * @param {string} expr
+ * @returns {boolean}
+ */
+function isValidCron(expr) {
+ if (typeof expr !== 'string' || !expr.trim()) return false;
+ // parseCronToNextRun throws / returns null on an unparseable or out-of-range
+ // expression; wrap it into a boolean here so callers don't need try/catch.
+ try {
+ return Boolean(parseCronToNextRun(expr));
+ } catch {
+ return false;
+ }
+}
+
export {
schedule,
cancel,
@@ -636,5 +655,6 @@ export {
triggerNow,
parseCronToNextRun,
parseCronToPrevRun,
+ isValidCron,
MAX_TIMEOUT
}