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: surface retained merge guard recovery and sanitize failure summaries
Adam Eivye49b521f30d0
diff --git a/server/services/pendingMergeGuard.js b/server/services/pendingMergeGuard.jsindex 1800138de9..5325e037d2 100644--- a/server/services/pendingMergeGuard.js+++ b/server/services/pendingMergeGuard.js@@ -3,6 +3,8 @@ import { resolve } from 'node:path';import { promisify, stripVTControlCharacters } from 'node:util';import { execFile } from '../lib/childProcess.js';import { execGit } from '../lib/execGit.js';+import { scrubSecretTokens } from '../lib/secretText.js';+import { redactPii } from '../lib/piiRedactionPatterns.js';const run = promisify(execFile);const SHA = /^[0-9a-f]{40}$/;@@ -16,6 +18,9 @@ const readOptional = path => readFile(path, 'utf8').catch(error => {throw error;});+export const summarizeMergeGuardOutput = text => redactPii(scrubSecretTokens(stripVTControlCharacters(String(text))))+ .replace(/\s+/g, ' ').trim().slice(0, 500);+// Capability, not upstream slug: forks inherit the guard, ordinary managed apps// and older PortOS checkouts without merged-tree support keep their behavior.export async function supportsPendingMergeGuard(repoPath) {@@ -26,13 +31,15 @@ export async function supportsPendingMergeGuard(repoPath) {async function verifyCheckout(repoPath, worktreePath, branch, headSha) {if (!worktreePath || resolve(repoPath) === resolve(worktreePath)) return false;const read = async (args, cwd = worktreePath) => (await execGit(args, cwd)).stdout.trim();- const [common, primaryCommon, head, ref, status] = await Promise.all([+ const checked = await Promise.all([read(['rev-parse', '--path-format=absolute', '--git-common-dir']),read(['rev-parse', '--path-format=absolute', '--git-common-dir'], repoPath),read(['rev-parse', '--verify', 'HEAD^{commit}']),read(['symbolic-ref', '--quiet', '--short', 'HEAD']),read(['status', '--porcelain=v1', '--untracked-files=all']),- ]);+ ]).catch(() => null);+ if (!checked) return false;+ const [common, primaryCommon, head, ref, status] = checked;return common === primaryCommon && head === headSha && ref === branch && !status;}@@ -47,7 +54,8 @@ export async function preparePendingMergeGuard({ app, entry, binding, prView, re}if (!await supportsPendingMergeGuard(worktreePath)) return { ok: false, reason: 'merged-tree-command-unavailable' };const base = await readDefault();- if (!base || !SHA.test(base.sha) || prView.baseRefName !== base.name) {+ if (!base || !SHA.test(base.sha)) return { ok: false, reason: 'merged-tree-default-branch-unavailable' };+ if (prView.baseRefName !== base.name) {return { ok: false, reason: 'merged-tree-default-branch-unverified' };}// Fetch the named ref, then pin the command to the fetched object. Concurrent@@ -69,7 +77,9 @@ export async function preparePendingMergeGuard({ app, entry, binding, prView, reawait writeFile(evidence.logPath, `HEAD ${headSha}\nBASE ${base.sha}\n${result.stdout}\n${result.stderr}`, { mode: 0o600 });if (!result.ok) {const failedTest = stripVTControlCharacters(`${result.stdout}\n${result.stderr}`).match(/\bFAIL\s+([^\r\n]+)/)?.[1];- return { ok: false, reason: 'merged-tree-guards-failed', evidence: { ...evidence, failedTest: failedTest || null } };+ return { ok: false, reason: 'merged-tree-guards-failed', evidence: {+ ...evidence, failedTest: failedTest ? summarizeMergeGuardOutput(failedTest) : null,+ } };}if (!await verifyCheckout(app.repoPath, worktreePath, entry.prBranch, headSha)) {return { ok: false, reason: 'merged-tree-checkout-changed', evidence };diff --git a/server/services/pendingMergeGuard.test.js b/server/services/pendingMergeGuard.test.jsindex ebbab20c62..69f96a1668 100644--- a/server/services/pendingMergeGuard.test.js+++ b/server/services/pendingMergeGuard.test.js@@ -31,7 +31,7 @@ console.log(JSON.stringify({ args: process.argv.slice(2), memo: process.env.PORT// Stand in for a structural guard which is red only on the combined inputs.const base = execFileSync('git', ['show', process.argv[4] + ':base-contract'], { encoding: 'utf8' });if (base.trim() === 'strict' && ${fail}) {- console.error('FAIL server/routeValidationConventions.test.js > combined route inventory');+ console.error('FAIL server/routeValidationConventions.test.js > combined route inventory ' + 'ghp_' + 'x'.repeat(24) + ' ' + 'x'.repeat(600));process.exitCode = 1;}`);@@ -73,6 +73,8 @@ describe('pending merged-tree validation', () => {const { input, git, worktreePath, headSha, baseSha } = await fixture({ fail: true });const result = await preparePendingMergeGuard(input);expect(result).toMatchObject({ ok: false, reason: 'merged-tree-guards-failed', evidence: { headSha, baseSha } });+ expect(result.evidence.failedTest).toContain('[REDACTED]');+ expect(result.evidence.failedTest.length).toBeLessThanOrEqual(500);expect(await readFile(result.evidence.logPath, 'utf8')).toContain('FAIL server/routeValidationConventions.test.js > combined route inventory');expect(await git(['rev-parse', 'HEAD'], worktreePath)).toBe(headSha);expect(await git(['status', '--porcelain'], worktreePath)).toBe('');@@ -87,6 +89,12 @@ describe('pending merged-tree validation', () => {expect(await readFile(join(worktreePath, 'uncommitted'), 'utf8')).toBe('preserve me');});+ it('identifies a detached handed-off checkout as unverified without running its guard', async () => {+ const { input, git, worktreePath, headSha } = await fixture();+ await git(['checkout', '--detach', headSha], worktreePath);+ expect(await preparePendingMergeGuard(input)).toEqual({ ok: false, reason: 'merged-tree-checkout-unverified' });+ });+it('leaves an ordinary managed app without the supported command unchanged', async () => {const repoPath = await mkdtemp(join(tmpdir(), 'ordinary-managed-app-'));roots.push(repoPath);diff --git a/server/services/prWatcher.js b/server/services/prWatcher.jsindex 9a5131a459..b14f0250a6 100644--- a/server/services/prWatcher.js+++ b/server/services/prWatcher.js@@ -25,8 +25,6 @@ import { safeJSONParse } from '../lib/fileUtils.js';import { isPlainObject } from '../lib/objects.js';import { PR_COMPLETIONS, leavesPrForHuman, resolvePrCompletion } from '../lib/prDisposition.js';import { isTruthyMeta } from '../lib/metadataFlags.js';-import { scrubSecretTokens } from '../lib/secretText.js';-import { redactPii } from '../lib/piiRedactionPatterns.js';// Bound the gh query. The high-water mark (computePrCheck) advances to the max// open PR number it saw, so it can only correctly drain a backlog it received@@ -692,20 +690,24 @@ async function readPendingDefault({ origin, repoSpec, forgeExec }) {async function attemptAdmittedMerge(entry, binding, prView, ctx) {const ownerPolicy = await currentHandoffOwnerPolicy(binding);if (ownerPolicy) return { step: await holdForOwner(ctx.app, entry, binding, ownerPolicy.ownerBlocked) };- const { preparePendingMergeGuard } = await import('./pendingMergeGuard.js');+ const { preparePendingMergeGuard, summarizeMergeGuardOutput } = await import('./pendingMergeGuard.js');const guard = await preparePendingMergeGuard({ app: ctx.app, entry, binding, prView,readDefault: () => readPendingDefault(ctx), env: ctx.forgeExec.env,}).catch(error => {- const detail = redactPii(scrubSecretTokens(String(error.message))).replace(/[\r\n]+/g, ' ').slice(0, 500);+ const detail = summarizeMergeGuardOutput(error.message);console.error(`❌ Pending PR #${entry.prNumber} merged-tree validation unavailable: ${detail}`);return { ok: false, reason: 'merged-tree-validation-unavailable', evidence: { detail } };});if (!guard.ok) {- const retained = { ...entry, mergedTreeGuard: { ...guard.evidence, reason: guard.reason }, attention: guard.reason };- if (guard.reason === 'merged-tree-guards-failed') {+ const retained = { ...entry, mergedTreeGuard: { ...guard.evidence, reason: guard.reason } };+ if (['merged-tree-validation-unavailable', 'merged-tree-default-branch-unavailable'].includes(guard.reason)) {+ return { step: await advanceTicks(ctx, entry, retained, binding, { reason: guard.reason }) };+ }+ if (guard.reason !== 'merged-tree-base-moved') {retained.recoveryBlocked = guard.reason;+ retained.attention = guard.reason;await notifyPendingMergeTimeout(ctx.app, entry, null,- `PR #${entry.prNumber} failed merged-tree guards${guard.evidence?.failedTest ? `: ${guard.evidence.failedTest}` : ''}. Its receipt, checkout, and mergedTreeGuard log are retained. Repair and submit a fresh verified handoff.`);+ `PR #${entry.prNumber} cannot pass merged-tree validation: ${guard.reason}${guard.evidence?.failedTest ? ` — ${guard.evidence.failedTest}` : ''}. Its receipt, checkout, and any mergedTreeGuard log are retained. Repair and submit a fresh verified handoff.`);}return { step: { outcome: retained, tally: { waiting: 1 } } };}diff --git a/server/services/prWatcher.test.js b/server/services/prWatcher.test.jsindex 2f4f045292..503a5e8dc4 100644--- a/server/services/prWatcher.test.js+++ b/server/services/prWatcher.test.js@@ -41,7 +41,8 @@ vi.mock('./untrustedContent.js', () => ({}));const prepareGuardMock = vi.fn();const guardCurrentMock = vi.fn();-vi.mock('./pendingMergeGuard.js', () => ({+vi.mock('./pendingMergeGuard.js', async importOriginal => ({+ summarizeMergeGuardOutput: (await importOriginal()).summarizeMergeGuardOutput,preparePendingMergeGuard: (...args) => prepareGuardMock(...args),pendingMergeGuardCurrent: (...args) => guardCurrentMock(...args),}));@@ -697,6 +698,31 @@ describe('merge-only PR watcher', () => {expect(admissionState.state.mergeAdmissions).toEqual({});});+ it('notifies once and retains the owner when an unavailable prerequisite exhausts its retry budget', async () => {+ const { app } = setup();+ app.pendingMergePrs[0].ticks = MAX_PENDING_MERGE_TICKS - 1;+ prepareGuardMock.mockRejectedValue(new Error('git fetch failed: repository unavailable'));+ await processPendingMergePrs(app);+ expect(readPendingMergePrs(mockApps.get(app.id))[0]).toMatchObject({ handoff,+ ticks: MAX_PENDING_MERGE_TICKS, attention: 'merged-tree-validation-unavailable' });+ expect(addNotificationMock).toHaveBeenCalledTimes(1);+ await processPendingMergePrs(mockApps.get(app.id));+ expect(addNotificationMock).toHaveBeenCalledTimes(1);+ expect(mergePrMock).not.toHaveBeenCalled();+ });++ it('notifies and holds a checkout refusal for repair instead of retrying forever', async () => {+ const { app } = setup();+ prepareGuardMock.mockResolvedValue({ ok: false, reason: 'merged-tree-checkout-unverified' });+ await processPendingMergePrs(app);+ expect(readPendingMergePrs(mockApps.get(app.id))[0]).toMatchObject({ handoff,+ recoveryBlocked: 'merged-tree-checkout-unverified' });+ await processPendingMergePrs(mockApps.get(app.id));+ expect(prepareGuardMock).toHaveBeenCalledTimes(1);+ expect(addNotificationMock).toHaveBeenCalledTimes(1);+ expect(mergePrMock).not.toHaveBeenCalled();+ });+it('runs the guard outside admission and merges the unchanged reviewed head inside it', async () => {const { app } = setup();prepareGuardMock.mockImplementation(async () => {