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

add `npm run pregate` so CI's own test plan runs before the push, not after

[._.]/ Adam Eivy97743f92e652
diff --git a/AGENTS.md b/AGENTS.md
index a37194c44b..3070bbcf05 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -19,8 +19,14 @@ cd client && npm test # Vitest (happy-dom) — component/unit tests
# because PortOS runs under PM2 with NODE_ENV=development and a suite that
# inherits it aims at the real Postgres.
npm run test:db # DB-backed suites → portos_test ONLY (see Security Model)
+
+npm run pregate # BEFORE EVERY PUSH — runs what CI will run on this branch
```
+**`npm run pregate` is the pre-push gate.** It asks CI's own planner (`scripts/ci-test-plan.js`) what this branch's diff selects, then runs that plan through CI's own runners — so a green pregate means the Linux lint and test jobs are green for the same reasons, not a second opinion that can drift. It takes seconds on a scoped diff, and it is the only local command that reaches the tree-wide guards nothing imports: the import budget (`server/lib/importScoping.test.js`), server→client import purity, union-merged catalog rows, generated-manifest drift. Those are the failures that otherwise cost a push and a CI round to discover — and the ones that reproduce only *after* a rebase, so **run it again after every rebase onto a moved `main`**, not just once before the first push.
+
+It plans from **committed** work only and says so when the tree is dirty; commit, then re-run. A diff big enough to force CI's full suite runs the always-run guards here instead (`--full` opts into everything). It never runs the DB suites, the Windows job, the client build, or the boot smoke — it names the ones your diff implicated and leaves them to CI, which is the only honest answer for a check this machine cannot perform.
+
## Test Strategy: Value Over Assertion Count
- **Default to the highest practical public boundary** — an Express route, service workflow, persisted-store adapter, socket exchange, or rendered user interaction. Cover the success path plus the materially different failure/compatibility paths; do not enumerate every internal branch because it exists.
@@ -203,7 +209,7 @@ This complements the Security Model (the deployed product) — this section gove
## Git Workflow
- **main**: active development. **release**: push `main` to `release` to trigger the GitHub Release workflow.
-- **Push pattern**: `git pull --rebase --autostash && git push`
+- **Push pattern**: `npm run pregate && git pull --rebase --autostash && npm run pregate && git push` — the gate runs CI's own plan locally (see Commands). Run it **again after the rebase**: the import budget and the tree-wide guards are properties of your branch *merged with* the new `main`, so a rebase is exactly when a clean branch starts failing, and the first run cannot have seen it.
- **No per-branch changelog entries.** PRs do not write a changelog file or fragment — commit messages are the record, and `/do:release` synthesizes the release notes from the commit log since the last tag into `.changelog/v{version}.md`. **Write commit subjects/bodies for a human release-note reader** (see "Git commits and PRs" in the global instructions). Rationale: `.changelog/README.md`.
- **Release quality snapshot**: before a release, run `npm run quality:snapshot` on the install holding PortOS audit evidence. It publishes numeric local assessments only (no provider calls, no private run prose) into the repo-root `.quality.json`; with no local evidence it commits nothing and says so.
- **Versioning**: `package.json` reflects the last release. Do not bump during development — `/do:release` handles it.
diff --git a/package.json b/package.json
index f8a162d302..b3f2a27722 100644
--- a/package.json
+++ b/package.json
@@ -44,6 +44,7 @@
"setup:hooks": "bash scripts/setup-git-hooks.sh",
"update": "node -e \"const{spawnSync:s}=require('child_process');const w=process.platform==='win32';const r=s(w?'powershell':'bash',w?['-NoProfile','-ExecutionPolicy','Bypass','-File','update.ps1']:['update.sh'],{stdio:'inherit'});process.exit(r.status??1)\"",
"test": "npm test --prefix server && npm test --prefix client",
+ "pregate": "node scripts/pregate.js",
"quality:snapshot": "node scripts/publish-quality-snapshot.js",
"scan:hidden-content": "node scripts/scan-diff-hidden-content.js",
"eidoverse:assay": "node scripts/eidoverse-resilience-assay.js",
diff --git a/scripts/pregate.js b/scripts/pregate.js
new file mode 100644
index 0000000000..9bd0659d22
--- /dev/null
+++ b/scripts/pregate.js
@@ -0,0 +1,224 @@
+#!/usr/bin/env node
+
+/**
+ * Run the checks CI will run on this branch — locally, before pushing.
+ *
+ * CI already decides what to run from the diff (`scripts/ci-test-plan.js`),
+ * but nothing could ask it that question outside Actions, so the recurring
+ * failures were the ones no local command covers: an import-budget overshoot
+ * that only appears after a rebase, a server->client import-purity violation,
+ * a doubled catalog row from a union merge, a tree-wide guard that no changed
+ * 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
+ * jobs are green for the same reasons — never a second, drifting opinion about
+ * which tests matter.
+ *
+ * node scripts/pregate.js [--base <ref>] [--full] [--skip-lint] [--plan-only]
+ *
+ * --base <ref> compare against <ref> instead of the remote default branch
+ * --full actually run the complete suite when the plan demands it
+ * (without this, a full plan runs the always-run guards only)
+ * --skip-lint skip the client lint stage
+ * --plan-only print the plan and the stages, run nothing
+ *
+ * What it deliberately does NOT cover, because each needs a resource this
+ * checkout does not have: the DB suites (a provisioned `portos_test` —
+ * `npm run setup:db:test && npm run test:db`), the Windows job (a Windows
+ * runner), and the client build / boot smoke. The summary names the ones the
+ * plan flagged so they are a decision rather than a surprise.
+ */
+
+import { spawnSync } from 'child_process';
+import { execFileSync } from 'child_process';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+import { ALWAYS_RUN_TESTS } from './ci-test-plan.js';
+import { isDirectlyInvoked } from './lib/directInvocation.js';
+
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+
+/**
+ * Suites the plan can request that this machine cannot honestly run.
+ *
+ * Keyed by the plan field, valued by what the operator would have to run
+ * instead. Reported rather than silently dropped: a pregate that stayed quiet
+ * about a DB-risk diff would read as "CI is covered" while the one suite that
+ * can destroy real data went unmentioned.
+ */
+export const UNCOVERED_SUITES = Object.freeze({
+ db: 'npm run setup:db:test && npm run test:db (never against the real `portos` database)',
+ windows: 'a Windows runner — no local equivalent; CI is the only proof',
+ build: 'npm run build',
+ smoke: 'npm run smoke',
+});
+
+/**
+ * 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.
+ */
+export function resolvePlanStages(plan, { skipLint = false } = {}) {
+ const stages = [];
+
+ if (!skipLint && plan.lint.mode !== 'skip') {
+ stages.push({
+ name: 'client lint',
+ script: 'run-ci-lint.js',
+ args: [],
+ env: { CI_LINT_MODE: plan.lint.mode, CI_LINT_FILES: JSON.stringify(plan.lint.files) },
+ });
+ }
+
+ ['server', 'client'].forEach((scope) => {
+ const scoped = plan[scope];
+ if (scoped.mode === 'skip') return;
+ stages.push({
+ name: `${scope} tests`,
+ script: 'run-ci-tests.js',
+ args: [scope],
+ env: {
+ CI_TEST_MODE: scoped.mode,
+ CI_TEST_FILES: JSON.stringify(scoped.files),
+ CI_TEST_SOURCES: JSON.stringify(scoped.sources),
+ },
+ });
+ });
+
+ return stages;
+}
+
+/**
+ * Replace a full-suite plan with the always-run guards.
+ *
+ * A full plan is CI's answer to "this diff could break anything", which is
+ * correct there and unusable here — the complete suite is far longer than
+ * anyone runs before a push, so the honest local default is the subset that
+ * catches the tree-wide guards, plus a line saying what was dropped. `--full`
+ * opts back in.
+ */
+export function downgradeFullPlan(plan, trackedFiles) {
+ const tracked = new Set(trackedFiles);
+ return {
+ ...plan,
+ full: false,
+ server: { mode: 'files', files: ALWAYS_RUN_TESTS.filter((path) => tracked.has(path)), sources: [] },
+ client: { mode: 'skip', files: [], sources: [] },
+ lint: { mode: 'full', files: [] },
+ };
+}
+
+const git = (args) => execFileSync('git', args, { cwd: REPO_ROOT, encoding: 'utf8' }).trim();
+
+/** The remote default branch (`origin/main` unless this fork says otherwise). */
+function defaultBaseRef() {
+ const head = spawnSync('git', ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], {
+ cwd: REPO_ROOT, encoding: 'utf8',
+ });
+ const resolved = head.status === 0 ? head.stdout.trim() : '';
+ return resolved || 'origin/main';
+}
+
+/** Parse argv into the flags documented in the header. */
+export function parseArgs(argv) {
+ const baseIndex = argv.indexOf('--base');
+ return {
+ base: baseIndex === -1 ? null : argv[baseIndex + 1],
+ full: argv.includes('--full'),
+ skipLint: argv.includes('--skip-lint'),
+ planOnly: argv.includes('--plan-only'),
+ };
+}
+
+function main() {
+ const options = parseArgs(process.argv.slice(2));
+ const baseRef = options.base || defaultBaseRef();
+
+ const mergeBase = spawnSync('git', ['merge-base', baseRef, 'HEAD'], { cwd: REPO_ROOT, encoding: 'utf8' });
+ if (mergeBase.status !== 0) {
+ console.error(`❌ Cannot resolve a merge base with ${baseRef} — fetch it first (git fetch origin).`);
+ process.exit(2);
+ }
+ const baseSha = mergeBase.stdout.trim();
+ console.log(`🔎 Planning against ${baseRef} (${baseSha.slice(0, 9)}).`);
+
+ // Uncommitted work is invisible to a `<base>...HEAD` diff, so it is invisible
+ // to the plan. Saying so is the difference between "pregate passed" and
+ // "pregate passed on what you have committed".
+ const dirty = git(['status', '--porcelain']).split('\n').filter(Boolean);
+ if (dirty.length > 0) {
+ console.log(`⚠️ ${dirty.length} uncommitted change(s) are NOT in this plan — the plan only sees committed work.`);
+ console.log('⚠️ Commit first and re-run, or a green pregate says nothing about the edits still in your tree.');
+ }
+
+ const planned = spawnSync(process.execPath, [join(REPO_ROOT, 'scripts', 'ci-test-plan.js')], {
+ cwd: REPO_ROOT,
+ encoding: 'utf8',
+ // The planner writes step outputs when Actions' env is present; stripping
+ // it keeps a local run from appending to a stale $GITHUB_OUTPUT file.
+ env: { ...process.env, CI_BASE_SHA: baseSha, CI_FORCE_FULL: 'false', CI_BASE_REF: '', GITHUB_OUTPUT: '', GITHUB_STEP_SUMMARY: '' },
+ });
+ if (planned.status !== 0) {
+ console.error(`❌ ci-test-plan.js failed: ${planned.stderr || planned.error?.message || 'unknown error'}`);
+ process.exit(2);
+ }
+
+ const raw = JSON.parse(planned.stdout);
+ let plan = {
+ full: raw.full,
+ reason: raw.reason,
+ server: { mode: raw.server_mode, files: JSON.parse(raw.server_files), sources: JSON.parse(raw.server_sources) },
+ client: { mode: raw.client_mode, files: JSON.parse(raw.client_files), sources: JSON.parse(raw.client_sources) },
+ lint: { mode: raw.lint_mode, files: JSON.parse(raw.lint_files) },
+ db: raw.db,
+ windows: raw.windows,
+ build: raw.build,
+ smoke: raw.smoke,
+ };
+ console.log(`📋 ${raw.changed_files.length} changed file(s) — ${plan.reason}.`);
+
+ if (plan.full && !options.full) {
+ plan = downgradeFullPlan(plan, git(['ls-files']).split('\n').filter(Boolean));
+ 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 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);
+ }
+
+ for (const stage of stages) {
+ console.log(`▶️ ${stage.name}`);
+ const result = spawnSync(process.execPath, [join(REPO_ROOT, 'scripts', stage.script), ...stage.args], {
+ cwd: REPO_ROOT,
+ stdio: 'inherit',
+ env: { ...process.env, ...stage.env },
+ });
+ if (result.error) {
+ console.error(`❌ ${stage.name} could not start: ${result.error.message}`);
+ process.exit(1);
+ }
+ if (result.status !== 0) {
+ console.error(`❌ ${stage.name} failed — fix it before pushing (CI would fail the same way).`);
+ process.exit(result.status ?? 1);
+ }
+ }
+
+ const caveat = uncovered.length > 0 ? ` (${uncovered.join(', ')} still only provable in CI)` : '';
+ console.log(`✅ Pregate passed: ${stages.map((stage) => stage.name).join(', ')}${caveat}.`);
+}
+
+if (isDirectlyInvoked(import.meta.url)) main();
diff --git a/scripts/pregate.test.js b/scripts/pregate.test.js
new file mode 100644
index 0000000000..36619e9653
--- /dev/null
+++ b/scripts/pregate.test.js
@@ -0,0 +1,123 @@
+/**
+ * Contract for the local pre-push gate (`npm run pregate`).
+ *
+ * The value of this gate is that it runs exactly what CI runs, so the failures
+ * worth pinning are the ones where it would quietly diverge: handing a runner a
+ * scope CI skipped (or skipping one CI selected), passing the wrong selector
+ * 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 { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+import { buildCiTestPlan, ALWAYS_RUN_TESTS } from './ci-test-plan.js';
+import { resolvePlanStages, downgradeFullPlan, parseArgs, UNCOVERED_SUITES } from './pregate.js';
+
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+
+const planWith = (overrides = {}) => ({
+ full: false,
+ reason: 'test plan',
+ server: { mode: 'files', files: ['server/lib/a.test.js'], sources: [] },
+ client: { mode: 'skip', files: [], sources: [] },
+ lint: { mode: 'skip', files: [] },
+ db: false,
+ windows: false,
+ build: false,
+ smoke: false,
+ ...overrides,
+});
+
+describe('resolvePlanStages', () => {
+ it('runs only the scopes the plan selected', () => {
+ const stages = resolvePlanStages(planWith());
+ expect(stages.map((stage) => stage.name)).toEqual(['server tests']);
+ });
+
+ it('hands each runner the plan\'s own selector lists', () => {
+ 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');
+ expect(stage.args).toEqual(['server']);
+ expect(stage.env).toEqual({
+ CI_TEST_MODE: 'related',
+ CI_TEST_FILES: '["server/lib/a.test.js"]',
+ CI_TEST_SOURCES: '["server/lib/a.js"]',
+ });
+ });
+
+ it('puts lint first, so the one-second verdict is not queued behind Vitest', () => {
+ 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"]' });
+ });
+
+ it('drops the lint stage under --skip-lint but keeps the test stages', () => {
+ const stages = resolvePlanStages(
+ planWith({ lint: { mode: 'files', files: ['client/src/App.jsx'] } }),
+ { skipLint: true },
+ );
+ expect(stages.map((stage) => stage.name)).toEqual(['server tests']);
+ });
+});
+
+describe('downgradeFullPlan', () => {
+ it('replaces the full suite with the tracked always-run guards', () => {
+ const tracked = ALWAYS_RUN_TESTS.slice(0, 3);
+ const downgraded = downgradeFullPlan(planWith({ full: true }), tracked);
+ expect(downgraded.full).toBe(false);
+ expect(downgraded.server).toEqual({ mode: 'files', files: tracked, sources: [] });
+ expect(downgraded.client.mode).toBe('skip');
+ });
+
+ it('drops a guard this checkout does not track, so Vitest is never given a missing path', () => {
+ // A fork that deleted a guard, or a branch predating one, still has it in
+ // ALWAYS_RUN_TESTS; passing that path to Vitest is an error, not a skip.
+ const downgraded = downgradeFullPlan(planWith({ full: true }), []);
+ expect(downgraded.server.files).toEqual([]);
+ });
+});
+
+describe('parseArgs', () => {
+ it('reads --base as a value, not a boolean', () => {
+ expect(parseArgs(['--base', 'origin/release', '--full'])).toEqual({
+ base: 'origin/release', full: true, skipLint: false, planOnly: false,
+ });
+ });
+
+ it('defaults to a null base so the caller resolves the remote default branch', () => {
+ expect(parseArgs([])).toEqual({ base: null, full: false, skipLint: false, planOnly: false });
+ });
+});
+
+describe('UNCOVERED_SUITES', () => {
+ /**
+ * The gate reports these by reading `plan[key]`. A rename in ci-test-plan.js
+ * would make every one of them read `undefined` — the warnings would just
+ * stop appearing, and a DB-risk diff would leave here looking fully covered.
+ */
+ it('names plan fields the planner actually emits', () => {
+ const plan = buildCiTestPlan([], { trackedFiles: [], forceFull: true, forceFullReason: 'test' });
+ Object.keys(UNCOVERED_SUITES).forEach((key) => {
+ expect(plan, `plan has no '${key}' field`).toHaveProperty(key);
+ expect(typeof plan[key]).toBe('boolean');
+ });
+ });
+});
+
+describe('the gate end to end', () => {
+ it('plans this checkout and names its stages without running them', () => {
+ const output = execFileSync(
+ process.execPath,
+ [join(REPO_ROOT, 'scripts', 'pregate.js'), '--plan-only'],
+ { cwd: REPO_ROOT, encoding: 'utf8' },
+ );
+ expect(output).toMatch(/Planning against /);
+ expect(output).toMatch(/changed file\(s\)/);
+ });
+});