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
fail closed when the repo-state audit cannot read a gate, and stop calling a partial probe clean
[._.]/ Adam Eivyd9489ef93b49
diff --git a/server/lib/repoStateExpectations.js b/server/lib/repoStateExpectations.jsindex 8e0ca49811..3df4f0f011 100644--- a/server/lib/repoStateExpectations.js+++ b/server/lib/repoStateExpectations.js@@ -47,8 +47,16 @@ export const REPO_STATE_SKIPS = Object.freeze({CLEANUP_WARNED: 'cleanup-already-warned',FOLLOW_UP_PENDING: 'follow-up-pending',MISSING_CONTEXT: 'missing-branch-or-workspace',- // Set by the service half when not one probe could be read.- PROBE_FAILED: 'probe-failed',+ // Both set by the service half. A gate this audit depends on could not be read+ // (the app record, the task queue) — fail CLOSED, because reading "we could not+ // ask" as "nobody owns this branch" or as "the app left the audit on" is how a+ // transient file-read failure files recovery work against a branch a follow-up+ // owns, or against an app that opted out.+ GATE_UNREADABLE: 'gate-unreadable',+ // At least one probe that could have produced a finding was unreadable, and+ // nothing diverged in what WAS readable. Not the same as clean: a firewalled+ // host must not be logged as a verified repo.+ PROBE_INCOMPLETE: 'probe-incomplete',});/**diff --git a/server/lib/repoStateExpectations.test.js b/server/lib/repoStateExpectations.test.jsindex bccf5bb868..60db3299d1 100644--- a/server/lib/repoStateExpectations.test.js+++ b/server/lib/repoStateExpectations.test.js@@ -60,13 +60,22 @@ describe('resolveRepoStateExpectation', () => {it('answers every free gate before the one the caller pays for', () => {// `followUpPending` costs two task-file reads plus the app record, so the// service resolves once WITHOUT it to short-circuit. That only works while- // every other skip outranks it.- for (const override of [- { isWorktree: false }, { isPersistentWorktree: true }, { discardWorktree: true },- { success: false }, { cleanupWarningCount: 1 }, { branchName: null }, { sourceWorkspace: null },- ]) {+ // every other skip outranks it. Assert the EXACT reason each gate gives, not+ // merely that it isn't FOLLOW_UP_PENDING — a regression returning+ // `verify: true`, or the wrong reason, would sail past the weaker check.+ const cases = [+ [{ isWorktree: false }, REPO_STATE_SKIPS.NOT_WORKTREE],+ [{ isPersistentWorktree: true }, REPO_STATE_SKIPS.PERSISTENT_WORKTREE],+ [{ discardWorktree: true }, REPO_STATE_SKIPS.DISCARDED_WORKTREE],+ [{ success: false }, REPO_STATE_SKIPS.FAILED_RUN],+ [{ cleanupWarningCount: 1 }, REPO_STATE_SKIPS.CLEANUP_WARNED],+ [{ branchName: null }, REPO_STATE_SKIPS.MISSING_CONTEXT],+ [{ sourceWorkspace: null }, REPO_STATE_SKIPS.MISSING_CONTEXT],+ ];+ for (const [override, reason] of cases) {const e = resolveRepoStateExpectation({ ...auditable, ...override, followUpPending: true });- expect(e.skipReason).not.toBe(REPO_STATE_SKIPS.FOLLOW_UP_PENDING);+ expect(e.verify, JSON.stringify(override)).toBe(false);+ expect(e.skipReason, JSON.stringify(override)).toBe(reason);}});});diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.jsindex cd789789fa..0927fc96c2 100644--- a/server/services/agentRepoStateVerification.js+++ b/server/services/agentRepoStateVerification.js@@ -57,6 +57,12 @@ import {// stalled gh (network / keychain hang) must not hold an agent lane open.const FORGE_RESOLVE_TIMEOUT_MS = 10000;+// A task in any of these still HOLDS its branch and will resume on it, so a+// branch one of them targets is owned, not leaked. `challenged` is the easy one+// to miss: it is a parked-for-dispute status, not a terminal one, and its task+// keeps its resume pointer (`cosTaskStore.js` `challengeTask`).+const PENDING_OWNER_STATUSES = new Set(['pending', 'in_progress', 'blocked', 'challenged']);+const withTimeout = (promise, ms, fallback) => Promise.race([promise,new Promise(resolve => setTimeout(() => resolve(fallback), ms)),@@ -86,17 +92,23 @@ async function branchHasPendingOwner(branchName, app) {// `resolveTaskTargetBranch` is the canonical "which branch does this task own"// reader — matching `reviewLoopPRBranch` by hand here would miss a retry holding// the same branch through `existingBranch`.- const tasks = await readAllTasksFlat().catch(() => []);+ //+ // `null` on an unreadable queue, never `false`: the caller fails closed on it.+ // Collapsing "we could not read the task file" into "nobody owns this branch" is+ // how a transient read failure files recovery work against a branch a follow-up+ // is queued to land.+ const tasks = await readAllTasksFlat().catch(() => null);+ if (!tasks) return null;const claimedByTask = tasks.some(t =>- (t.status === 'pending' || t.status === 'in_progress' || t.status === 'blocked') &&- resolveTaskTargetBranch(t.metadata) === branchName+ PENDING_OWNER_STATUSES.has(t.status) && resolveTaskTargetBranch(t.metadata) === branchName);if (claimedByTask) return true;if (!app) return false;const { readPendingMergePrs } = await import('./prWatcher.js');const pending = readPendingMergePrs(app);- return Array.isArray(pending) && pending.some(entry => entry?.prBranch === branchName);+ if (!Array.isArray(pending)) return null;+ return pending.some(entry => entry?.prBranch === branchName);}/**@@ -148,23 +160,33 @@ async function probeRepoState({ sourceWorkspace, branchName, worktreePath, brancreturn heads ? heads.has(branchName) : null;};- // GitHub only. `gh pr view` against a GitLab MR answers nothing useful, and a- // wrong answer is worse than none — leave `prState` null so the PR check simply- // does not fire on a GitLab remote. `findPullRequestForBranch` already returns- // the state in `detail`, so no second round trip is needed to read it.+ // Ask whichever forge this remote actually lives on. Both lookups share the+ // same tri-state contract and both return the change request's state in+ // `detail`, so no second round trip is needed to read it.const probePr = async () => {- if (!prExpected || !branchShouldBeGone) return { prState: null, prUrl: null };- const { cli, env } = await withTimeout(+ if (!prExpected || !branchShouldBeGone) return { prState: null, prUrl: null, cli: null, readable: true };+ const forge = await withTimeout(git.resolveForgeForRepo(sourceWorkspace).catch(() => null),FORGE_RESOLVE_TIMEOUT_MS,null- ) || {};- if (cli !== 'gh') return { prState: null, prUrl: null };- const { findPullRequestForBranch } = await import('./github.js');- const found = await findPullRequestForBranch(branchName, { cwd: sourceWorkspace, env: env || null })- .catch(() => ({ status: 'unavailable' }));- if (found.status !== 'found') return { prState: null, prUrl: null };- return { prState: found.detail ? String(found.detail).toUpperCase() : null, prUrl: found.url || null };+ );+ if (!forge?.cli) return { prState: null, prUrl: null, cli: null, readable: false };+ const { cli, env } = forge;+ const found = cli === 'glab'+ ? await (await import('./gitlab.js')).findMergeRequestForBranch(branchName, sourceWorkspace)+ .catch(() => ({ status: 'unavailable' }))+ : await (await import('./github.js')).findPullRequestForBranch(branchName, { cwd: sourceWorkspace, env: env || null })+ .catch(() => ({ status: 'unavailable' }));+ if (found.status === 'unavailable') return { prState: null, prUrl: null, cli, readable: false };+ // `none` is a real answer, not a gap — `verifyPrClaim` already owns "the agent+ // never opened one", so there is nothing here to report and nothing missing.+ if (found.status !== 'found') return { prState: null, prUrl: null, cli, readable: true };+ return {+ prState: found.detail ? String(found.detail).toUpperCase() : null,+ prUrl: found.url || null,+ cli,+ readable: !!found.detail,+ };};// `allowRemote: false` — a bookkeeping question must not block on `git remote@@ -178,7 +200,7 @@ async function probeRepoState({ sourceWorkspace, branchName, worktreePath, brancprobeLocalBranch(),probeRemoteBranch(),probeDefaultBranch(),- probePr().catch(() => ({ prState: null, prUrl: null })),+ probePr().catch(() => ({ prState: null, prUrl: null, cli: null, readable: false })),]);// Only meaningful while the branch still exists locally — `isBranchMergedInto`@@ -188,6 +210,23 @@ async function probeRepoState({ sourceWorkspace, branchName, worktreePath, branc? await git.isBranchMergedInto(sourceWorkspace, branchName, defaultBranch).catch(() => null): null;+ // Which probes that COULD have produced a finding came back unreadable. The+ // caller reports a run with any of these as `probe-incomplete` rather than+ // clean — a probe we never got an answer from has not verified anything, and+ // logging it as a verified repo is the absent-vs-empty conflation this module+ // exists to avoid. A probe that was deliberately skipped (not applicable to+ // this run's end-state shape) is NOT unreadable.+ const unreadable = [];+ if (worktreePresent === null) unreadable.push('worktree');+ if (localBranchPresent === null) unreadable.push('local-branch');+ if (branchShouldBeGone) {+ if (remoteBranchPresent === null) unreadable.push('remote-branch');+ // Merge state is only in question while the branch is still there; once it is+ // gone there is nothing left to be unmerged.+ if (localBranchPresent === true && branchMerged === null) unreadable.push('branch-merged');+ if (prExpected && !pr.readable) unreadable.push('pull-request');+ }+return {worktreePresent,localBranchPresent,@@ -195,7 +234,9 @@ async function probeRepoState({ sourceWorkspace, branchName, worktreePath, brancbranchMerged,prState: pr.prState,prUrl: pr.prUrl,+ forgeCli: pr.cli,defaultBranch,+ unreadable,};}@@ -239,11 +280,21 @@ export async function verifyAgentRepoState({ agentId, task, agentState, success,const preflight = resolveRepoStateExpectation(structural);if (!preflight.verify) return skipped(preflight.skipReason);- const app = appId ? await (await import('./apps.js')).getAppById(appId).catch(() => null) : null;+ // Both reads below fail CLOSED. `getAppById` answers `null` for "no such app"+ // AND throws for "could not read apps.json", and collapsing those would let a+ // transient read failure override an explicit per-app opt-out; likewise an+ // unreadable task queue must not read as "nobody owns this branch".+ const UNREADABLE = Symbol('unreadable');+ const app = appId+ ? await (await import('./apps.js')).getAppById(appId).catch(() => UNREADABLE)+ : null;+ if (app === UNREADABLE) return skipped(REPO_STATE_SKIPS.GATE_UNREADABLE);+const enabled = repoStateVerificationEnabled(app);- const followUpPending = enabled ? await branchHasPendingOwner(branchName, app).catch(() => false) : false;+ const owned = enabled ? await branchHasPendingOwner(branchName, app).catch(() => null) : false;+ if (owned === null) return skipped(REPO_STATE_SKIPS.GATE_UNREADABLE);- const expectation = resolveRepoStateExpectation({ ...structural, enabled, followUpPending });+ const expectation = resolveRepoStateExpectation({ ...structural, enabled, followUpPending: owned });if (!expectation.verify) return skipped(expectation.skipReason);const worktreePath = metadata.workspacePath || join(PATHS.worktrees, agentId);@@ -258,14 +309,18 @@ export async function verifyAgentRepoState({ agentId, task, agentState, success,return null;});- // Not one probe answered — a firewalled host or an unreadable repo. Reporting- // this as "verified clean" would conflate could-not-ask with nothing-wrong.- const readNothing = !observed- || [observed.worktreePresent, observed.localBranchPresent, observed.remoteBranchPresent].every(v => v === null);- if (readNothing) return skipped(REPO_STATE_SKIPS.PROBE_FAILED);+ if (!observed) return skipped(REPO_STATE_SKIPS.PROBE_INCOMPLETE);const issues = classifyRepoStateIssues(expectation, { ...observed, branchName });if (issues.length === 0) {+ // A run where some probe could not be read has not been verified — it has been+ // partially checked. Say so rather than logging a firewalled host as a clean+ // repo. Findings still stand on their own: what WAS readable is fact, so a+ // divergence below is reported even alongside an unreadable probe.+ if (observed.unreadable.length > 0) {+ emitLog('info', `🔎 Repo state only partly readable for ${agentId} (${branchName}) — could not check: ${observed.unreadable.join(', ')}`, { agentId, branchName });+ return { verified: false, skipReason: REPO_STATE_SKIPS.PROBE_INCOMPLETE, issues: [], observed, recoveryTaskId: null };+ }emitLog('info', `🔎 Repo state verified clean for ${agentId} (${branchName})`, { agentId, branchName });return { verified: true, skipReason: null, issues: [], observed, recoveryTaskId: null };}@@ -304,7 +359,12 @@ export const REPO_STATE_REMEDIATIONS = Object.freeze({`Delete the remote branch after confirming its work merged: "git push origin --delete ${branchName}".`,[REPO_STATE_ISSUES.BRANCH_UNMERGED]: ({ base }) =>`The branch has commits that are NOT on ${base}. Decide whether they are still wanted: land them (open or merge a PR, or merge locally and resolve conflicts) before deleting anything. Do NOT delete this branch until its work is on ${base}.`,- [REPO_STATE_ISSUES.PR_UNMERGED]: ({ prUrl }) => `Finish the pull request${prUrl ? ` ${prUrl}` : ''}. ${driveToMerge(prUrl || '<num>')}`,+ // Forge-aware: `driveToMerge` emits a `gh pr merge` procedure, which a GitLab+ // recovery agent cannot run. Its non-gh caveats still apply on either forge —+ // merge from the repo ROOT, and remove the worktree before deleting the branch.+ [REPO_STATE_ISSUES.PR_UNMERGED]: ({ prUrl, forgeCli }) => (forgeCli === 'glab'+ ? `Finish the merge request${prUrl ? ` ${prUrl}` : ''}: fix failing pipeline jobs, resolve threads, then merge it from the repo ROOT (not inside the branch's worktree) with "glab mr merge <iid> --remove-source-branch". Remove the worktree before deleting the local branch — the delete fails while a worktree still has it checked out.`+ : `Finish the pull request${prUrl ? ` ${prUrl}` : ''}. ${driveToMerge(prUrl || '<num>')}`),});/**@@ -319,7 +379,7 @@ export const REPO_STATE_REMEDIATIONS = Object.freeze({async function fileRepoStateRecoveryTask({ agentId, task, branchName, sourceWorkspace, worktreePath, issues, observed, appId }) {const appName = task?.metadata?.appName || appId || 'PortOS';const base = observed.defaultBranch || 'the default branch';- const ctx = { branchName, base, prUrl: observed.prUrl, worktreePath };+ const ctx = { branchName, base, prUrl: observed.prUrl, worktreePath, forgeCli: observed.forgeCli };const context = ['An agent finished successfully but the repository did not end up in the expected state.',@@ -328,7 +388,7 @@ async function fileRepoStateRecoveryTask({ agentId, task, branchName, sourceWork`Branch: ${branchName}`,`Worktree: ${worktreePath}`,`Default branch: ${base}`,- observed.prUrl ? `Pull request: ${observed.prUrl} (${observed.prState || 'state unknown'})` : 'Pull request: none found',+ observed.prUrl ? `Change request: ${observed.prUrl} (${observed.prState || 'state unknown'})` : 'Change request: none found',`Original agent: ${agentId}`,`Original task: ${task?.description || 'unknown'}`,'',diff --git a/server/services/agentRepoStateVerification.test.js b/server/services/agentRepoStateVerification.test.jsindex 989f5eb6e1..12cc037e3c 100644--- a/server/services/agentRepoStateVerification.test.js+++ b/server/services/agentRepoStateVerification.test.js@@ -35,6 +35,9 @@ vi.mock('./git.js', () => ({vi.mock('./github.js', () => ({findPullRequestForBranch: vi.fn().mockResolvedValue({ status: 'none', url: null, detail: null }),}));+vi.mock('./gitlab.js', () => ({+ findMergeRequestForBranch: vi.fn().mockResolvedValue({ status: 'none', url: null, detail: null }),+}));vi.mock('./apps.js', () => ({ getAppById: vi.fn().mockResolvedValue({ id: 'demo-app', name: 'Demo App' }) }));vi.mock('./notifications.js', () => ({addNotification: vi.fn().mockResolvedValue({}),@@ -51,6 +54,7 @@ import { listWorktrees } from './worktreeManager.js';import { listRemoteHeads } from './branchReconcile.js';import { isBranchMergedInto, resolveForgeForRepo } from './git.js';import { findPullRequestForBranch } from './github.js';+import { findMergeRequestForBranch } from './gitlab.js';import { getAppById } from './apps.js';import { addNotification, exists as notificationExists } from './notifications.js';import { readPendingMergePrs } from './prWatcher.js';@@ -103,6 +107,7 @@ beforeEach(() => {readPendingMergePrs.mockReturnValue([]);resolveForgeForRepo.mockResolvedValue({ cli: 'gh', env: null });findPullRequestForBranch.mockResolvedValue({ status: 'none', url: null, detail: null });+ findMergeRequestForBranch.mockResolvedValue({ status: 'none', url: null, detail: null });notificationExists.mockResolvedValue(false);addTask.mockResolvedValue({ id: 'task-recovery-1' });localBranch(false);@@ -270,7 +275,7 @@ describe('verifyAgentRepoState — never fires', () => {expect(getAllTasks).not.toHaveBeenCalled();});- it('reports probe-failed, not "clean", when git could not be asked at all', async () => {+ it('reports probe-incomplete, not "clean", when git could not be asked at all', async () => {// A firewalled host must not manufacture a recovery agent per run — and must// not be logged as a verified-clean repo either.listWorktrees.mockRejectedValue(new Error('not a git repository'));@@ -280,18 +285,90 @@ describe('verifyAgentRepoState — never fires', () => {const result = await run();- expect(result.skipReason).toBe(REPO_STATE_SKIPS.PROBE_FAILED);+ expect(result.skipReason).toBe(REPO_STATE_SKIPS.PROBE_INCOMPLETE);expect(result.verified).toBe(false);expect(addTask).not.toHaveBeenCalled();});- it('does not treat a GitLab remote as an unmerged PR', async () => {+ it('reports probe-incomplete when only SOME probes were unreadable', async () => {+ // The partial case is the dangerous one: worktree and branch both read clean,+ // so nothing diverged — but the forge never answered, so the PR could be+ // sitting open. Calling that "verified" is the absent-vs-empty conflation.+ findPullRequestForBranch.mockResolvedValue({ status: 'unavailable', url: null, detail: null });++ const result = await run();++ expect(result.skipReason).toBe(REPO_STATE_SKIPS.PROBE_INCOMPLETE);+ expect(result.observed.unreadable).toContain('pull-request');+ expect(addTask).not.toHaveBeenCalled();+ });++ it('still reports a divergence it COULD read alongside one it could not', async () => {+ // Partial knowledge does not suppress a finding — what was readable is fact.+ existsSync.mockReturnValue(true);+ findPullRequestForBranch.mockResolvedValue({ status: 'unavailable', url: null, detail: null });++ const result = await run();++ expect(result.issues.map(i => i.code)).toContain(REPO_STATE_ISSUES.WORKTREE_PRESENT);+ expect(addTask).toHaveBeenCalledTimes(1);+ });++ it('fails closed when the app record cannot be read', async () => {+ // A transient apps.json failure must not override an explicit per-app opt-out.+ getAppById.mockRejectedValue(new Error('apps.json unreadable'));+ existsSync.mockReturnValue(true);++ const result = await run();++ expect(result.skipReason).toBe(REPO_STATE_SKIPS.GATE_UNREADABLE);+ expect(addTask).not.toHaveBeenCalled();+ });++ it('fails closed when the task queue cannot be read', async () => {+ // "Could not read the queue" must never become "nobody owns this branch" — a+ // follow-up queued to land it would get a recovery task filed against it.+ getAllTasks.mockRejectedValue(new Error('tasks file unreadable'));+ existsSync.mockReturnValue(true);++ const result = await run();++ expect(result.skipReason).toBe(REPO_STATE_SKIPS.GATE_UNREADABLE);+ expect(addTask).not.toHaveBeenCalled();+ });++ it('defers while a CHALLENGED task still holds the branch', async () => {+ // `challenged` is a parked-for-dispute status, not a terminal one: the task+ // keeps its branch and resumes on it.+ queuedTasks([{ status: 'challenged', metadata: { existingBranch: BRANCH } }]);+ existsSync.mockReturnValue(true);++ const result = await run();++ expect(result.skipReason).toBe(REPO_STATE_SKIPS.FOLLOW_UP_PENDING);+ expect(addTask).not.toHaveBeenCalled();+ });++ it('reports an unmerged GitLab merge request', async () => {+ // GitLab is probed too — leaving it unasked would silently pass an open MR as+ // a clean repo. States come back lowercase from glab.resolveForgeForRepo.mockResolvedValue({ cli: 'glab', env: null });+ findMergeRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://gitlab.example.com/mr/4', detail: 'opened' });const result = await run();expect(findPullRequestForBranch).not.toHaveBeenCalled();- expect(result.issues).toEqual([]);+ expect(result.issues.map(i => i.code)).toEqual([REPO_STATE_ISSUES.PR_UNMERGED]);+ // The remediation must speak glab — a `gh pr merge` line is unrunnable there.+ expect(addTask.mock.calls[0][0].context).toContain('glab mr merge');+ expect(addTask.mock.calls[0][0].context).not.toContain('gh pr merge');+ });++ it('does not report a MERGED GitLab merge request', async () => {+ resolveForgeForRepo.mockResolvedValue({ cli: 'glab', env: null });+ findMergeRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://gitlab.example.com/mr/4', detail: 'merged' });+ const result = await run();+ expect(result.verified).toBe(true);});});diff --git a/server/services/agentWorktreeCleanup.repoStateAudit.test.js b/server/services/agentWorktreeCleanup.repoStateAudit.test.jsindex aa6079dc1e..95e8491466 100644--- a/server/services/agentWorktreeCleanup.repoStateAudit.test.js+++ b/server/services/agentWorktreeCleanup.repoStateAudit.test.js@@ -115,6 +115,34 @@ describe('cleanupAgentWorktree → repo-state audit', () => {releaseAudit({ verified: true, issues: [] });});+ it('audits only after the teardown it is auditing has finished', async () => {+ // The audit's whole job is to check what cleanup LEFT BEHIND, so it must not+ // observe a half-removed worktree. Every other case here uses a non-worktree+ // agent (cleanup exits before `removeWorktree`), which cannot prove ordering —+ // this one runs the real teardown and holds it open.+ getAgent.mockResolvedValue(worktreeAgent);+ const order = [];+ let finishRemoval;+ removeWorktree.mockReturnValue(new Promise(resolve => {+ finishRemoval = () => { order.push('removeWorktree'); resolve({ removed: true, warnings: [] }); };+ }));+ verifyAgentRepoState.mockImplementation(async () => {+ order.push('audit');+ return { verified: true, issues: [] };+ });++ const cleanup = cleanupAgentWorktree('agent-1', true, { originalTask: { id: 'task-1', metadata: {} } });+ // The audit must not have fired while the teardown is still in flight.+ await Promise.resolve();+ expect(order).toEqual([]);++ finishRemoval();+ await cleanup;+ await auditRan();++ expect(order).toEqual(['removeWorktree', 'audit']);+ });+it('returns the cleanup warnings unchanged, and survives an audit that throws', async () => {// The audit is an observer. A failure in it must never swallow the warnings// the caller uses to notify the user and spawn a merge recovery task.