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: retain merge guard diagnostics and limit subprocess credentials

Adam Eivy9c1641295455
diff --git a/server/services/pendingMergeGuard.js b/server/services/pendingMergeGuard.js
index 358a972d5a..1800138de9 100644
--- a/server/services/pendingMergeGuard.js
+++ b/server/services/pendingMergeGuard.js
@@ -7,6 +7,10 @@ import { execGit } from '../lib/execGit.js';
const run = promisify(execFile);
const SHA = /^[0-9a-f]{40}$/;
const SCRIPT = 'scripts/pregate.js';
+const GUARD_ENV_KEYS = new Set([
+ 'PATH', 'Path', 'HOME', 'USERPROFILE', 'HOMEDRIVE', 'HOMEPATH', 'SystemRoot', 'SystemDrive',
+ 'ComSpec', 'PATHEXT', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LANGUAGE', 'TZ', 'PORTOS_PREGATE_MAX_WORKERS',
+]);
const readOptional = path => readFile(path, 'utf8').catch(error => {
if (error.code === 'ENOENT') return null;
throw error;
@@ -54,7 +58,10 @@ export async function preparePendingMergeGuard({ app, entry, binding, prView, re
const gitPath = (await execGit(['rev-parse', '--git-path', `portos-merged-guards-${headSha}-${base.sha}.log`], worktreePath)).stdout.trim();
const evidence = { headSha, baseSha: base.sha, baseBranch: base.name, logPath: resolve(worktreePath, gitPath) };
const result = await run(process.execPath, [SCRIPT, '--guards-only', '--merged-with', base.sha], {
- cwd: worktreePath, env: { ...process.env, PORTOS_TEST_MEMO: 'off' },
+ cwd: worktreePath, env: {
+ ...Object.fromEntries(Object.entries(process.env).filter(([key]) => GUARD_ENV_KEYS.has(key) || key.startsWith('LC_'))),
+ PORTOS_TEST_MEMO: 'off',
+ },
timeout: 15 * 60 * 1000, maxBuffer: 16 * 1024 * 1024,
}).then(value => ({ ...value, ok: true }), error => ({
ok: false, stdout: error.stdout || '', stderr: error.stderr || error.message,
diff --git a/server/services/pendingMergeGuard.test.js b/server/services/pendingMergeGuard.test.js
index 1d53902ccc..ebbab20c62 100644
--- a/server/services/pendingMergeGuard.test.js
+++ b/server/services/pendingMergeGuard.test.js
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -7,6 +7,7 @@ import { preparePendingMergeGuard, pendingMergeGuardCurrent } from './pendingMer
const roots = [];
afterEach(async () => {
+ vi.unstubAllEnvs();
await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true })));
});
@@ -26,7 +27,7 @@ for (const arg of process.argv.slice(2)) { switch (arg) {
case '--guards-only': break;
case '--merged-with': break;
} }
-console.log(JSON.stringify({ args: process.argv.slice(2), memo: process.env.PORTOS_TEST_MEMO }));
+console.log(JSON.stringify({ args: process.argv.slice(2), memo: process.env.PORTOS_TEST_MEMO, token: process.env.PORTOS_API_TOKEN || null }));
// 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}) {
@@ -55,11 +56,12 @@ if (base.trim() === 'strict' && ${fail}) {
describe('pending merged-tree validation', () => {
it('fetches the live base, pins both full SHAs, and preserves the clean claim checkout', async () => {
+ vi.stubEnv('PORTOS_API_TOKEN', 'example-secret-not-for-tests');
const { input, git, worktreePath, headSha, baseSha } = await fixture();
const result = await preparePendingMergeGuard(input);
expect(result).toMatchObject({ ok: true, evidence: { headSha, baseSha, baseBranch: 'main' } });
const log = await readFile(result.evidence.logPath, 'utf8');
- expect(log).toContain(JSON.stringify({ args: ['--guards-only', '--merged-with', baseSha], memo: 'off' }));
+ expect(log).toContain(JSON.stringify({ args: ['--guards-only', '--merged-with', baseSha], memo: 'off', token: null }));
expect(await git(['rev-parse', 'HEAD'], worktreePath)).toBe(headSha);
expect(await git(['status', '--porcelain'], worktreePath)).toBe('');
expect(await pendingMergeGuardCurrent(result.evidence, input.prView, input.readDefault)).toBe(true);
diff --git a/server/services/prWatcher.js b/server/services/prWatcher.js
index c0ab110a88..9a5131a459 100644
--- a/server/services/prWatcher.js
+++ b/server/services/prWatcher.js
@@ -25,6 +25,8 @@ 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
@@ -655,9 +657,6 @@ async function mergeAssessedHead(entry, binding, { app, origin, repoSpec, forgeE
], undefined, { ...forgeExec, backoffKey: repoSpec }).catch(() => null), null),
}).catch(() => ({ ok: false, code: 'security-action-assessment-error' }));
const assessed = assessment.ok ? NOT_ASSESSED : await describeWithheldAssessment(assessment, expectedHeadSha);
- // Re-read the durable owner's policy inside admission, after remote
- // assessment and immediately before merge. Waiting CI is not authority to
- // ignore a later manual hold or a changed review requirement.
if (assessment.ok && guard) {
const { pendingMergeGuardCurrent } = await import('./pendingMergeGuard.js');
const livePr = await readPendingPullRequest(repoSpec, entry.prNumber, forgeExec);
@@ -666,6 +665,9 @@ async function mergeAssessedHead(entry, binding, { app, origin, repoSpec, forgeE
return { merge: { guardDeferred: true }, assessed };
}
}
+ // Re-read the durable owner's policy inside admission, after remote
+ // assessment and immediately before merge. Waiting CI is not authority to
+ // ignore a later manual hold or a changed review requirement.
const ownerPolicy = await currentHandoffOwnerPolicy(binding);
if (ownerPolicy) return { merge: ownerPolicy, assessed };
const merge = assessment.ok
@@ -676,8 +678,6 @@ async function mergeAssessedHead(entry, binding, { app, origin, repoSpec, forgeE
return { merge, assessed };
}
-// Answers `{ step }` when the entry is finished this sweep, otherwise
-// `{ assessed }` for the settle path.
async function readPendingDefault({ origin, repoSpec, forgeExec }) {
const name = await getDefaultBranch(repoSpec, forgeExec);
if (!name) return null;
@@ -687,13 +687,19 @@ async function readPendingDefault({ origin, repoSpec, forgeExec }) {
return sha ? { name, sha: sha.trim() } : null;
}
+// Answers `{ step }` when the entry is finished this sweep, otherwise
+// `{ assessed }` for the settle path.
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 guard = await preparePendingMergeGuard({ app: ctx.app, entry, binding, prView,
readDefault: () => readPendingDefault(ctx), env: ctx.forgeExec.env,
- }).catch(() => ({ ok: false, reason: 'merged-tree-validation-unavailable' }));
+ }).catch(error => {
+ const detail = redactPii(scrubSecretTokens(String(error.message))).replace(/[\r\n]+/g, ' ').slice(0, 500);
+ 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') {
diff --git a/server/services/prWatcher.test.js b/server/services/prWatcher.test.js
index 50e25aad01..2f4f045292 100644
--- a/server/services/prWatcher.test.js
+++ b/server/services/prWatcher.test.js
@@ -687,6 +687,16 @@ describe('merge-only PR watcher', () => {
expect(addNotificationMock).toHaveBeenCalledTimes(1);
});
+ it('retains an actionable diagnostic when validation prerequisites throw', async () => {
+ const { app } = setup();
+ prepareGuardMock.mockRejectedValue(new Error('git fetch failed: repository unavailable'));
+ await processPendingMergePrs(app);
+ expect(readPendingMergePrs(mockApps.get(app.id))[0]).toMatchObject({ handoff,
+ mergedTreeGuard: { reason: 'merged-tree-validation-unavailable', detail: 'git fetch failed: repository unavailable' } });
+ expect(mergePrMock).not.toHaveBeenCalled();
+ expect(admissionState.state.mergeAdmissions).toEqual({});
+ });
+
it('runs the guard outside admission and merges the unchanged reviewed head inside it', async () => {
const { app } = setup();
prepareGuardMock.mockImplementation(async () => {