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: run hidden-content checks before pregate validation (#7880)

[._.]/ Adam Eivy61f3f39ea6ce
diff --git a/docs/GITHUB_ACTIONS.md b/docs/GITHUB_ACTIONS.md
index 04ab86994d..3e1e09ccae 100644
--- a/docs/GITHUB_ACTIONS.md
+++ b/docs/GITHUB_ACTIONS.md
@@ -42,6 +42,12 @@ is the single gate a release ships behind.
### Hidden-content gate
+`npm run pregate` runs this same scanner before lint or tests, using its resolved
+merge base. It checks committed, staged, and unstaged diffs separately, plus
+untracked files, without changing the index or file contents. The scan remains
+active with `--skip-lint` or an empty test plan; `--plan-only` lists it without
+executing it. A diff read failure fails the gate.
+
The `impact` job runs `node scripts/scan-diff-hidden-content.js` before it
plans anything, and every other job needs `impact` — so a finding stops the
whole run, before a reviewer (human, `/do:pr` reviewer, or PR bot) ever reads
diff --git a/scripts/pregate.js b/scripts/pregate.js
index 0d36d99cd2..33164fc3f8 100644
--- a/scripts/pregate.js
+++ b/scripts/pregate.js
@@ -11,8 +11,8 @@
* file imports. Each cost a push, a ~20-minute CI round, and a diagnosis from
* a log. They are all static and take seconds to answer here.
*
- * This runs the SAME planner CI runs and hands its plan to the SAME runners
- * (`run-ci-lint.js`, `run-ci-tests.js`), so a green pregate means those Linux
+ * This runs CI's hidden-content scan and hands the SAME planner's plan to the
+ * SAME runners (`run-ci-lint.js`, `run-ci-tests.js`), so a green pregate means those Linux
* jobs are green for the same reasons — never a second, drifting opinion about
* which tests matter.
*
@@ -59,11 +59,15 @@ export const UNCOVERED_SUITES = Object.freeze({
* The ordered stages to run for a plan, each a spawnable command.
*
* Pure, so the plan -> stage mapping is testable without spawning Vitest.
- * Order is cheapest-signal-first: lint answers in about a second, and a
- * failure there means the test stages would only delay the same verdict.
+ * The hidden-content scan always runs first, even if lint/tests select no work.
*/
-export function resolvePlanStages(plan, { skipLint = false } = {}) {
- const stages = [];
+export function resolvePlanStages(plan, { skipLint = false, baseSha } = {}) {
+ const stages = [{
+ name: 'hidden-content scan',
+ script: 'scan-diff-hidden-content.js',
+ args: ['--base', baseSha, '--worktree'],
+ env: {},
+ }];
if (!skipLint && plan.lint.mode !== 'skip') {
stages.push({
@@ -135,7 +139,7 @@ export function statusPaths(output) {
export function collectPregateChangedFiles(baseSha, { cwd = REPO_ROOT } = {}) {
const committed = gitPaths(['diff', '-z', '--name-only', '--diff-filter=ACMRD', `${baseSha}...HEAD`], cwd);
const status = execFileSync(
- 'git', ['status', '--porcelain=v1', '-z', '--untracked-files=all'],
+ 'git', ['--no-optional-locks', 'status', '--porcelain=v1', '-z', '--untracked-files=all'],
{ cwd, encoding: 'utf8' },
);
const workingTree = statusPaths(status);
@@ -221,15 +225,10 @@ function main() {
console.log('⚠️ CI will run the FULL suite for this diff — running the always-run guards only. Pass --full to run everything.');
}
- const stages = resolvePlanStages(plan, { skipLint: options.skipLint });
+ const stages = resolvePlanStages(plan, { skipLint: options.skipLint, baseSha });
const uncovered = Object.keys(UNCOVERED_SUITES).filter((key) => plan[key]);
uncovered.forEach((key) => console.log(`ℹ️ CI will also run: ${key} — not covered here; run ${UNCOVERED_SUITES[key]}`));
- if (stages.length === 0) {
- console.log('✅ Nothing for this gate to run — the plan selected no lint or test work.');
- process.exit(0);
- }
-
if (options.planOnly) {
stages.forEach((stage) => console.log(`• ${stage.name}: ${stage.script} ${stage.args.join(' ')}`));
process.exit(0);
diff --git a/scripts/pregate.test.js b/scripts/pregate.test.js
index 6499179dff..2b7a2f845c 100644
--- a/scripts/pregate.test.js
+++ b/scripts/pregate.test.js
@@ -7,12 +7,13 @@
* list, naming a downgraded test file that is not tracked, or reporting
* "CI will also run: db" from a plan field that has since been renamed.
*/
-import { describe, it, expect } from 'vitest';
-import { execFileSync } from 'child_process';
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { afterEach, beforeEach, describe, it, expect } from 'vitest';
+import { execFileSync, spawnSync } from 'child_process';
+import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
+import { destroyGitSandbox, makeGitSandbox } from '../server/lib/gitTestRepo.js';
import {
buildCiTestPlan,
collectPlanInputs,
@@ -44,11 +45,11 @@ const planWith = (overrides = {}) => ({
describe('resolvePlanStages', () => {
it('runs only the scopes the plan selected', () => {
const stages = resolvePlanStages(planWith());
- expect(stages.map((stage) => stage.name)).toEqual(['server tests']);
+ expect(stages.map((stage) => stage.name)).toEqual(['hidden-content scan', 'server tests']);
});
it('hands each runner the plan\'s own selector lists', () => {
- const [stage] = resolvePlanStages(planWith({
+ const [, stage] = resolvePlanStages(planWith({
server: { mode: 'related', files: ['server/lib/a.test.js'], sources: ['server/lib/a.js'] },
}));
expect(stage.script).toBe('run-ci-tests.js');
@@ -60,13 +61,17 @@ describe('resolvePlanStages', () => {
});
});
- it('puts lint first, so the one-second verdict is not queued behind Vitest', () => {
+ it('scans hidden content before lint and tests using the resolved base', () => {
const stages = resolvePlanStages(planWith({
lint: { mode: 'files', files: ['client/src/App.jsx'] },
client: { mode: 'files', files: ['client/src/App.test.jsx'], sources: [] },
- }));
- expect(stages.map((stage) => stage.name)).toEqual(['client lint', 'server tests', 'client tests']);
- expect(stages[0].env).toEqual({ CI_LINT_MODE: 'files', CI_LINT_FILES: '["client/src/App.jsx"]' });
+ }), { baseSha: 'resolved-base' });
+ expect(stages.map((stage) => stage.name)).toEqual(['hidden-content scan', 'client lint', 'server tests', 'client tests']);
+ expect(stages[0]).toEqual({
+ name: 'hidden-content scan', script: 'scan-diff-hidden-content.js',
+ args: ['--base', 'resolved-base', '--worktree'], env: {},
+ });
+ expect(stages[1].env).toEqual({ CI_LINT_MODE: 'files', CI_LINT_FILES: '["client/src/App.jsx"]' });
});
it('drops the lint stage under --skip-lint but keeps the test stages', () => {
@@ -74,7 +79,129 @@ describe('resolvePlanStages', () => {
planWith({ lint: { mode: 'files', files: ['client/src/App.jsx'] } }),
{ skipLint: true },
);
- expect(stages.map((stage) => stage.name)).toEqual(['server tests']);
+ expect(stages.map((stage) => stage.name)).toEqual(['hidden-content scan', 'server tests']);
+ });
+});
+
+// These regressions need the actual CLI and Git, not mocked stage dispatch:
+// a later Git state can hide an earlier addition, no-index uses exit 1 for
+// success, and even a read-only `git status` can refresh the caller's index.
+describe('pregate hidden-content invocation', () => {
+ let scratch;
+ let root;
+ let base;
+ const trackedPath = 'docs/tracked note.md';
+ const clean = '# Example\n';
+ const hidden = `${clean}hidden: \u200B\n`;
+ const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8' }).trim();
+ const write = (path, content) => writeFileSync(join(root, path), content);
+ const run = (...args) => spawnSync(process.execPath, ['scripts/pregate.js', '--base', base, ...args], {
+ cwd: root, encoding: 'utf8',
+ });
+ const snapshot = () => ({
+ status: git('--no-optional-locks', 'status', '--porcelain=v1', '-z', '--untracked-files=all'),
+ index: readFileSync(join(root, '.git', 'index')),
+ });
+
+ beforeEach(async () => {
+ ({ scratch, repo: root } = await makeGitSandbox({ prefix: 'portos-pregate-cli-' }));
+ git('config', 'core.hooksPath', join(scratch, 'empty-hooks'));
+ // Copy the real builtin-only entrypoints so REPO_ROOT targets this fixture.
+ // No runners or test files: docs-only changes produce an empty test plan.
+ for (const path of [
+ 'scripts/pregate.js', 'scripts/scan-diff-hidden-content.js',
+ 'scripts/ci-test-plan.js', 'scripts/ci-base-sha.js',
+ 'scripts/lib/directInvocation.js', 'scripts/lib/githubOutput.js',
+ 'server/lib/diffHiddenContentScan.js', 'server/lib/modelAbuseGuard.js',
+ 'server/lib/textUtils.js',
+ ]) {
+ mkdirSync(dirname(join(root, path)), { recursive: true });
+ copyFileSync(join(REPO_ROOT, path), join(root, path));
+ }
+ write('package.json', '{"type":"module"}\n');
+ mkdirSync(join(root, 'docs'));
+ write(trackedPath, clean);
+ git('add', '--all');
+ git('commit', '-qm', 'pregate fixture');
+ base = git('rev-parse', 'HEAD');
+ });
+
+ afterEach(async () => {
+ await destroyGitSandbox(scratch);
+ });
+
+ it.each(['committed', 'staged', 'unstaged', 'untracked'])(
+ 'rejects %s hidden content without changing files or staging state', (state) => {
+ const path = state === 'untracked' ? 'docs/untracked note.md' : trackedPath;
+ write(path, hidden);
+ if (state === 'committed' || state === 'staged') git('add', '--', path);
+ if (state === 'committed') git('commit', '-qm', 'hidden fixture');
+ // A clean worktree must not conceal the staged or committed addition.
+ if (state === 'committed' || state === 'staged') write(path, clean);
+ const before = snapshot();
+ const contents = readFileSync(join(root, path));
+ const result = run('--skip-lint');
+ expect(result.status, result.stderr).toBe(1);
+ expect(result.stderr).toContain(`${path}:2 — hidden-unicode:`);
+ expect(result.stdout).not.toContain('Pregate passed');
+ expect(snapshot()).toEqual(before);
+ expect(readFileSync(join(root, path))).toEqual(contents);
+
+ if (state === 'committed') {
+ const ci = spawnSync(process.execPath, ['scripts/scan-diff-hidden-content.js', '--base', base], {
+ cwd: root, encoding: 'utf8',
+ });
+ expect(ci.status).toBe(1);
+ expect(result.stderr).toContain(ci.stderr.trim());
+ }
+ },
+ );
+
+ it('passes clean uncommitted changes even when the plan selects no lint or tests', () => {
+ write(trackedPath, `${clean}staged\n`);
+ git('add', '--', trackedPath);
+ write(trackedPath, `${clean}unstaged\n`);
+ write('docs/new note.md', 'ordinary text\n');
+ const before = snapshot();
+ const result = run('--skip-lint');
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.stdout).toContain('Pregate passed: hidden-content scan.');
+ expect(snapshot()).toEqual(before);
+ });
+
+ it('lists the mandatory scan in plan-only mode without scanning hidden content', () => {
+ write('docs/new note.md', hidden);
+ const before = snapshot();
+ const result = run('--plan-only', '--skip-lint');
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.stdout).toContain(`hidden-content scan: scan-diff-hidden-content.js --base ${base} --worktree`);
+ expect(result.stdout).not.toContain('▶️');
+ expect(result.stderr).toBe('');
+ expect(snapshot()).toEqual(before);
+ });
+
+ it('preserves binary and empty-file path findings for untracked additions', () => {
+ const emptyPath = 'docs/empty\u200B.md';
+ write(emptyPath, '');
+ write('docs/payload.bin', Buffer.from([0, 1, 2]));
+ const before = snapshot();
+ const result = run('--skip-lint');
+ expect(result.status, result.stderr).toBe(1);
+ expect(result.stderr).toContain(`${emptyPath}:1 — hidden-unicode: filename`);
+ expect(result.stderr).toContain('docs/payload.bin:1 — opaque-binary:');
+ expect(snapshot()).toEqual(before);
+ });
+
+ it('fails closed when Git cannot read a blob in the requested committed diff', () => {
+ const blob = git('rev-parse', `HEAD:${trackedPath}`);
+ write(trackedPath, `${clean}ordinary addition\n`);
+ git('add', '--', trackedPath);
+ git('commit', '-qm', 'changed fixture');
+ rmSync(join(root, '.git', 'objects', blob.slice(0, 2), blob.slice(2)));
+ const result = run('--skip-lint');
+ expect(result.status).toBe(2);
+ expect(result.stderr).toContain('Hidden-content scan failed:');
+ expect(result.stdout).not.toContain('Pregate passed');
});
});
diff --git a/scripts/scan-diff-hidden-content.js b/scripts/scan-diff-hidden-content.js
index 551f082443..a4832efa14 100644
--- a/scripts/scan-diff-hidden-content.js
+++ b/scripts/scan-diff-hidden-content.js
@@ -18,12 +18,13 @@
* Usage:
* node scripts/scan-diff-hidden-content.js # vs CI_BASE_SHA, else origin/main
* node scripts/scan-diff-hidden-content.js --base <ref>
+ * node scripts/scan-diff-hidden-content.js --base <ref> --worktree
* git diff | node scripts/scan-diff-hidden-content.js --stdin
*
* Exit codes: 0 clean, 1 findings, 2 the diff could not be read.
*/
-import { execFileSync } from 'node:child_process';
+import { execFileSync, spawnSync } from 'node:child_process';
import { gitRevParse } from './ci-base-sha.js';
import { isDirectlyInvoked } from './lib/directInvocation.js';
import {
@@ -36,6 +37,42 @@ import {
// so a runaway input fails loudly instead of exhausting the box.
const MAX_DIFF_BYTES = 256 * 1024 * 1024;
+// Keep the patch visible even when local diff drivers are configured, and do
+// not let Git refresh the caller's index as a side effect of a read.
+const DIFF_ARGS = [
+ '--no-optional-locks', '-c', 'core.quotepath=false', 'diff',
+ '--no-ext-diff', '--no-textconv', '--unified=0', '--no-color',
+];
+
+/** Read each Git state independently: a later removal must not hide an addition. */
+function* readDiffs(base, includeWorktree) {
+ const readDiff = (args) => execFileSync('git', [...DIFF_ARGS, ...args], {
+ encoding: 'utf8', maxBuffer: MAX_DIFF_BYTES,
+ });
+ // Three-dot matches CI: only this branch's additions since the merge base.
+ yield readDiff([`${base}...HEAD`]);
+ if (!includeWorktree) return;
+ yield readDiff(['--cached', 'HEAD']);
+ yield readDiff([]);
+
+ const untracked = execFileSync('git', ['ls-files', '--others', '--exclude-standard', '-z'], {
+ encoding: 'utf8', maxBuffer: MAX_DIFF_BYTES,
+ }).split('\0').filter(Boolean);
+ for (const path of untracked) {
+ // --no-index preserves Git's binary/file-mode/filename presentation without
+ // staging the file (including empty files and symlinks). Exit 1 means a
+ // difference, not a read error; every other nonzero result fails closed.
+ const result = spawnSync('git', [...DIFF_ARGS, '--no-index', '--', '/dev/null', path], {
+ encoding: 'utf8', maxBuffer: MAX_DIFF_BYTES,
+ });
+ if (result.error) throw result.error;
+ if (result.status !== 0 && result.status !== 1) {
+ throw new Error(`Cannot read untracked diff for ${path}: ${result.stderr.trim() || result.signal || result.status}`);
+ }
+ yield result.stdout;
+ }
+}
+
const readStdin = async (stream) => {
const chunks = [];
for await (const chunk of stream) chunks.push(chunk);
@@ -72,10 +109,10 @@ export async function runHiddenContentScan({
} = {}) {
const baseFlag = argv.indexOf('--base');
const explicit = baseFlag === -1 ? null : argv[baseFlag + 1];
- let diff;
+ let diffs;
if (argv.includes('--stdin')) {
- diff = typeof stdin === 'string' ? stdin : await readStdin(stdin || process.stdin);
+ diffs = [typeof stdin === 'string' ? stdin : await readStdin(stdin || process.stdin)];
} else {
const base = resolveDiffBase(explicit);
if (!base) {
@@ -91,16 +128,11 @@ export async function runHiddenContentScan({
: '⏭️ Hidden-content scan skipped: this run has no pull-request diff base'],
};
}
- // Three-dot: only what this branch added, not what the base moved on to.
- // quotepath=false so a filename carrying invisible Unicode arrives as those
- // code points rather than as octal escapes the detector would miss.
- diff = execFileSync('git', ['-c', 'core.quotepath=false', 'diff', '--unified=0', '--no-color', `${base}...HEAD`], {
- encoding: 'utf8',
- maxBuffer: MAX_DIFF_BYTES,
- });
+ diffs = readDiffs(base, argv.includes('--worktree'));
}
- const findings = scanDiffForHiddenContent(diff);
+ const findings = [];
+ for (const diff of diffs) findings.push(...scanDiffForHiddenContent(diff));
if (findings.length === 0) {
return { code: 0, lines: ['✅ Hidden-content scan clean: no invisible Unicode or encoded payloads in the added lines'] };
}