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
address review (agy): make the pre-reap backup fail loudly instead of silently empty
[._.]/ Adam Eivybc209018c3b0
diff --git a/server/lib/agentScratchPaths.js b/server/lib/agentScratchPaths.jsindex f8ad40c4e1..138efba0ad 100644--- a/server/lib/agentScratchPaths.js+++ b/server/lib/agentScratchPaths.js@@ -48,9 +48,16 @@ export const AGENT_SCRATCH_PATHS = [PUBLIC_REVIEW_INPUT_FILENAME, PUBLIC_REVIEW_*/export function matchesScratchRoot(path, roots = []) {if (typeof path !== 'string' || !roots.length) return false;- const normalized = path.trim().replace(/\/+$/, '');+ const strip = (value) => String(value ?? '').trim().replace(/\/+$/, '');+ const normalized = strip(path);if (!normalized) return false;- return roots.some((root) => normalized === root || normalized.startsWith(`${root}/`));+ // Both sides are stripped: `ignoredPaths: ['build/']` is the conventional way to+ // spell a directory, and matching it only in its slashless form would silently+ // ignore the option rather than fail loudly.+ return roots.some((root) => {+ const base = strip(root);+ return Boolean(base) && (normalized === base || normalized.startsWith(`${base}/`));+ });}/**diff --git a/server/lib/agentScratchPaths.test.js b/server/lib/agentScratchPaths.test.jsindex 59c667ad2a..ab91607ce4 100644--- a/server/lib/agentScratchPaths.test.js+++ b/server/lib/agentScratchPaths.test.js@@ -20,6 +20,17 @@ describe('matchesScratchRoot', () => {expect(matchesScratchRoot('.portos-public-review/nested/deep.json', roots)).toBe(true);});+ // A caller spelling a directory the conventional way must not be silently+ // ignored — 'temp' vs 'temp/' matching differently is an option that looks+ // configured and does nothing.+ it('normalizes the ROOT as well as the path', () => {+ expect(matchesScratchRoot('build/out.js', ['build/'])).toBe(true);+ expect(matchesScratchRoot('build', ['build/'])).toBe(true);+ expect(matchesScratchRoot('build/', ['build/'])).toBe(true);+ // An empty or slash-only root matches nothing, rather than everything.+ expect(matchesScratchRoot('anything', ['', '/'])).toBe(false);+ });+it('does not match a sibling that merely shares the prefix', () => {const roots = ['.portos-public-review', 'PORTOS_PUBLIC_REVIEW_INPUT.json'];expect(matchesScratchRoot('.portos-public-review-notes.md', roots)).toBe(false);diff --git a/server/services/supersededBackup.js b/server/services/supersededBackup.jsindex ff272dbc3b..8cf92a8442 100644--- a/server/services/supersededBackup.js+++ b/server/services/supersededBackup.js@@ -27,6 +27,7 @@ import { createHash } from 'node:crypto';import { cp, stat, writeFile } from 'node:fs/promises';import { dirname, join } from 'node:path';import { atomicWrite, ensureDir, PATHS } from '../lib/fileUtils.js';+import { isAgentScratchPath } from '../lib/agentScratchPaths.js';import { kebabCase } from '../lib/textUtils.js';import { execGitSafe } from './git.js';@@ -46,15 +47,32 @@ export const backupSlug = (branch) => {return `${kebabCase(name) || 'branch'}-${digest}`;};-// A single untracked file above this is almost certainly build output or a model-// artifact rather than authored work; it is named in the manifest instead of-// copied, so one stray blob can't turn a backup into a disk-filling operation.-// The tracked diff is deliberately uncapped by contrast — every byte of it is-// authored, and truncating it would break the "no backup, no delete" gate.+// Bounds on what one backup may copy, so a stray build artifact or model blob+// can't turn it into a disk-filling operation. Exceeding either REFUSES the+// backup (and with it the reap) rather than copying a subset — a partial backup+// would hand the caller a success it then deletes real work on. The tracked diff+// is deliberately uncapped by contrast: every byte of it is authored.const MAX_UNTRACKED_FILE_BYTES = 5 * 1024 * 1024;const MAX_UNTRACKED_TOTAL_BYTES = 50 * 1024 * 1024;-const gitText = async (args, cwd) => (await execGitSafe(args, cwd, { ignoreExitCode: true })).stdout || '';+/**+ * git stdout, or a THROW on a non-zero exit.+ *+ * `execGitSafe` never rejects — a locked index, an unreadable worktree or a bad+ * ref all come back as `{ exitCode: 1, stdout: '' }`. Reading only `.stdout` would+ * make every one of those indistinguishable from a legitimately empty result (a+ * branch with no commits of its own, a worktree with no tracked edits), and the+ * caller's contract is that a resolved backup means the work is safe on disk. So+ * exit status is the signal here, never emptiness: a failure throws, the reap+ * treats that as "do not delete", and the branch waits for the next pass.+ */+const gitText = async (args, cwd) => {+ const result = await execGitSafe(args, cwd, { ignoreExitCode: true });+ if (result.exitCode !== 0) {+ throw new Error(`git ${args.join(' ')} failed in ${cwd} (exit ${result.exitCode}): ${(result.stderr || '').trim() || 'no stderr'}`);+ }+ return result.stdout || '';+};/** Newline-separated git stdout → trimmed non-empty lines. */const gitLines = (stdout) => (stdout || '').split('\n').map((l) => l.trim()).filter(Boolean);@@ -65,7 +83,12 @@ const gitLines = (stdout) => (stdout || '').split('\n').map((l) => l.trim()).fil* @returns {Promise<{copied:string[], skipped:{path:string,reason:string}[]}>}*/async function copyUntracked(worktreePath, destDir) {- const paths = gitLines(await gitText(['ls-files', '--others', '--exclude-standard'], worktreePath));+ // PortOS's own scratch is not work product and must not be preserved — and on a+ // worktree branched before this scratch was gitignored, `--exclude-standard`+ // still reports it, so filtering here is what keeps it from eating the budget+ // below and pushing a real file into the refusal path.+ const paths = gitLines(await gitText(['ls-files', '--others', '--exclude-standard'], worktreePath))+ .filter((rel) => !isAgentScratchPath(rel));const copied = [];const skipped = [];const created = new Set();@@ -130,6 +153,14 @@ export async function backupSupersededBranch(repoPath, branch, { defaultBranch =// No upfront mkdir: copyUntracked creates each parent lazily, so a worktree// with nothing untracked leaves no empty directory behind.untracked = await copyUntracked(branch.worktreePath, join(dir, 'untracked'));+ // A file we could not copy is a file the reap would then delete with no copy+ // anywhere. That includes the size caps: their job is to stop one stray blob+ // from filling the disk, not to license deleting it — so an oversized file+ // refuses the reap and the branch stays put for a human to look at.+ if (untracked.skipped.length) {+ const detail = untracked.skipped.map((s) => `${s.path} (${s.reason})`).join(', ');+ throw new Error(`could not back up ${untracked.skipped.length} untracked file(s): ${detail}`);+ }}const manifest = {diff --git a/server/services/supersededBackup.test.js b/server/services/supersededBackup.test.jsindex b9bbda08d2..17b3306ee4 100644--- a/server/services/supersededBackup.test.js+++ b/server/services/supersededBackup.test.js@@ -91,6 +91,58 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('backupSupersededBranch', () => {expect(await readFile(join(replay, 'initial.txt'), 'utf8')).toBe('edited but never committed\n');});+ // The reap deletes on this function RESOLVING, so every way the copy can come+ // up short has to throw. `execGitSafe` never rejects — it returns+ // { exitCode: 1, stdout: '' } — which is indistinguishable from a legitimately+ // empty result unless exit status is what's checked.+ it('throws rather than reporting an empty backup when git fails', async () => {+ await expect(backupSupersededBranch(+ repo,+ { branch: 'no/such/branch', tip: null, worktreePath: null, verdict: {} },+ { defaultBranch: 'main', cosDir }+ )).rejects.toThrow(/git format-patch .* failed/);++ await expect(backupSupersededBranch(+ repo,+ { branch: BRANCH, tip, worktreePath: join(sandbox.scratch, 'worktrees', 'gone'), verdict: {} },+ { defaultBranch: 'main', cosDir }+ )).rejects.toThrow(/failed/);+ });++ it('refuses the backup when an untracked file exceeds the size budget', async () => {+ const big = join(worktree, 'huge.bin');+ await writeFile(big, Buffer.alloc(6 * 1024 * 1024));+ try {+ // Not "copy what fits and delete the rest" — the caps bound disk use, they+ // do not license deleting the file that tripped them.+ await expect(backupSupersededBranch(+ repo,+ { branch: BRANCH, tip, worktreePath: worktree, verdict: {} },+ { defaultBranch: 'main', cosDir }+ )).rejects.toThrow(/could not back up 1 untracked file\(s\).*huge\.bin.*too-large/s);+ } finally {+ await rm(big, { force: true });+ }+ });++ // A worktree branched before the scratch was gitignored still reports it as+ // untracked, and copying it would spend the budget on PortOS's own pipeline state.+ it('does not back up PortOS runtime scratch', async () => {+ const scratch = join(worktree, 'PORTOS_PUBLIC_REVIEW_INPUT.json');+ await writeFile(scratch, '{"screened":true}');+ try {+ const result = await backupSupersededBranch(+ repo,+ { branch: BRANCH, tip, worktreePath: worktree, verdict: {} },+ { defaultBranch: 'main', cosDir }+ );+ expect(result.untracked).not.toContain('PORTOS_PUBLIC_REVIEW_INPUT.json');+ await expect(stat(join(result.dir, 'untracked', 'PORTOS_PUBLIC_REVIEW_INPUT.json'))).rejects.toThrow();+ } finally {+ await rm(scratch, { force: true });+ }+ });+it('writes a manifest even for a branch with nothing to capture', async () => {await execGit(['branch', 'empty/branch', 'main'], repo);const result = await backupSupersededBranch(