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
perf: keep local pregate focused and leave broad validation to hosted CI
[._.]/ Adam Eivy04fb5d2dd3e5
diff --git a/.githooks/pre-commit b/.githooks/pre-commitindex 7a14e1f3c7..b0ec97b90d 100755--- a/.githooks/pre-commit+++ b/.githooks/pre-commit@@ -10,12 +10,12 @@ if [ -z "$STAGED" ]; thenexit 0fi-# The same planner and runners CI uses (scripts/pregate.js), bounded to the-# changed files and the always-run guards. The hook deliberately runs nothing+# Lightweight local policy: lint, structural guards and directly owned tests.+# Hosted CI owns broad coverage; no transitive server/browser/DB/build suite. The hook deliberately runs nothing# else: it used to run the whole server suite and `npm run build --prefix# client`, which publishes the branch's build into the dist the running# install serves (#12045). Validation never swaps what `npm start` serves.-printf -- "\n🔎 pre-commit: running pregate on the staged PortOS changes\n"+printf -- "\n🔎 pre-commit: running focused local pregate on the PortOS changes\n"node scripts/pregate.jsprintf -- "✅ pre-commit checks passed\n"diff --git a/AGENTS.md b/AGENTS.mdindex f15fc112b6..56deca8b90 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -56,15 +56,19 @@ npm test --prefix client # Vitest (happy-dom) — component/unit testsnpm run test:db # DB-backed suites → portos_test ONLY (see Security Model)npm run pregate # BEFORE EVERY PUSH — CI's plan run locally; receipt in .cache/pregate/report.json-# pregate and CI skip test files whose every input already passed (the test+# Local focused tests and CI skip test files whose every input already passed (the test# memo, docs/GITHUB_ACTIONS.md "Test memo"); PORTOS_TEST_MEMO=off runs them all.-node scripts/pregate-attest.js # AFTER the push: posts the green receipt as a `pregate` commit status bound to the+node scripts/pregate-attest.js # Only after explicit --full validation and the push: posts the green receipt as a `pregate` commit status bound to the# validated tree so the PR's CI skips the attested stages; a refusal means full CI as before```**Run `npm run pregate` before every push and again after rebasing onto a moved base.** It uses CI's planner and runners, including tree-wide guards for import boundaries, catalog merges, and generated manifests. The local plan includes both committed and uncommitted changes, including untracked files.-A scoped plan runs every suite it selects, in CI's order and with CI's environment: lint, server and client tests, the client build and its bundle pin, the boot smoke, the browser suites, and the serial `portos_test` DB suite last and alone (it is pinned to `portos_test` and can never target `portos`). A full-suite plan runs only the always-run guards unless `--full` is supplied, which runs everything. A suite left to CI — by `--skip-db`, `--skip-browser`, `--skip-build`, `--skip-smoke`, by the downgrade, or because the machine lacks a prerequisite (a reachable test Postgres; Chrome, ffmpeg and the client bundler) — is named as not run in the summary and in the receipt `.cache/pregate/report.json` (plan, stage outcomes and durations, base and HEAD SHAs, and the hash of the exact working tree validated, uncommitted and untracked files included). The shipped prompt-history guard runs locally when the planner selects it. A green pregate proves only the stages it ran; the Windows job and the Linux worker-containment job are the two only CI can prove, and required CI checks still apply. After the push, `node scripts/pregate-attest.js` posts the receipt as a `pregate` commit status on the head; the pull request's planner skips the attested stages for same-repository heads the repository owner attested (`docs/GITHUB_ACTIONS.md` "Pregate attestation"). It refuses when the receipt is not green, the tree changed after pregate, or the commit is not pushed — report the refusal and let CI run everything; never rerun pregate only to attest.+The default local gate runs lint/format checks, always-run and diff-selected structural guards, and focused unit tests: explicitly changed tests and sibling tests for changed sources, including new untracked tests. It does not expand through the transitive import graph or run browser, database, build or boot-smoke suites. Changes without a direct test owner keep their broader coverage in hosted CI. Run an appropriate focused public-boundary regression as you implement; do not treat the automatic sibling selection as proof of every changed behavior.++`npm run pregate -- --full` explicitly opts into CI's selected broad suites locally. Database tests remain pinned to `portos_test`; full runs retain prerequisite, isolation and process-cleanup guards. Required hosted CI and configured reviews remain mandatory before merging. A lightweight local pass never substitutes for hosted broad coverage.++Every run records its exact tree, stages, skipped suites and `validationMode` in `.cache/pregate/report.json`. Focused receipts cannot produce CI-skipping attestations; do not run `pregate-attest.js` after the default gate or rerun validation solely to attest. Explicit full-validation and legacy receipts retain their bounded stage-proof semantics; only stages actually run may be attested, subject to the existing tree/base/trust checks. Merged-tree structural guards remain required before managed merges and run outside merge admission.## Test Strategy: Value Over Assertion Countdiff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.mdindex e858e4757f..987f526900 100644--- a/docs/CONTRIBUTING.md+++ b/docs/CONTRIBUTING.md@@ -104,44 +104,11 @@ On POSIX, incomplete process inventories also retain stale roots; a dead runnerdoes not prove its children exited. Pending identity checks apply to pool-closecleanup as well as later sweeps.-Pregate proves only the stages it runs, and it says which it did not. A scoped-plan runs every suite CI would run for it, in CI's dependency order and with-CI's environment: the hidden-content scan, early structural guards, lint,-server and client tests, the-client build plus the API Explorer bundle pin, the boot smoke, the-cross-workspace browser suites (smoke profile), and the serial `portos_test`-DB suite last and alone — never concurrently with the other suites, and never-against `portos` (both `PGDATABASE` and `PGTESTDATABASE` are pinned and-`TEST_DB_OK` is removed from the stage's environment). A full-suite plan runs-only the always-run guards unless `--full` is supplied, which runs everything-above as well.--A suite stays with CI, and is named as not run in the summary, when:--- you pass `--skip-db`, `--skip-browser`, `--skip-build` or `--skip-smoke`;-- a full plan was downgraded (no `--full`);-- a prerequisite is missing — no Postgres answering at the resolved endpoint- (exported `PG*`, then the checkout's `.env`, then `localhost:5432`), or no- Chrome, ffmpeg or client bundler for the browser suites. The line names the- remedy; the run continues.--The shipped prompt-history guard (CI's `prompt-history` job) runs locally-when the planner selects it. The Windows job and the Linux worker-containment-job (bubblewrap namespaces) are the two suites only CI can prove; both are-named as not run. Every run writes a receipt to-`.cache/pregate/report.json` (gitignored): the plan, each stage's outcome and-duration, the suites not run and why, the base and HEAD SHAs, the Node-version, platform and worker budget, and the hash of the exact working tree-that was validated — untracked and uncommitted files included, so a later-commit of that state yields the same `HEAD^{tree}`. A green summary never-claims a suite it skipped; required CI checks still apply.--Always-run and diff-selected structural guards run before broad test stages-and browser/database prerequisite probes. Their successful results are reused-only within that run while the working tree, index, HEAD and refs are unchanged;-the receipt records guard outcomes and reuse proofs. This leaves the persistent-test memo's stricter rules intact. `--guards-only` and downgraded full plans-run that same guard selection once.+`npm run pregate` is the lightweight local gate: lint/format checks, always-run and diff-selected structural guards, and directly owned unit tests. It selects edited test files and sibling tests for changed sources, including untracked new tests, without expanding through transitive imports. Browser, database, build and boot-smoke suites stay with hosted CI. Run a focused public-boundary regression for changed behavior that has no sibling test; automatic selection does not replace engineering judgment.++`npm run pregate -- --full` explicitly runs the broad CI plan locally, including selected browser/DB/build/smoke stages when prerequisites are present. Missing prerequisites and `--skip-*` options remain explicit in the receipt. DB stages run last against `portos_test` only. Required hosted checks and configured reviews remain mandatory.++The receipt at `.cache/pregate/report.json` records `validationMode` (`focused` or `ci`), exact tree/base/head, stage outcomes/durations and omitted suites. Focused mode marks server/client results as reduced coverage and cannot attest CI suites. Structural guard reuse remains confined to an unchanged snapshot within one invocation. `--guards-only --merged-with origin/<base>` retains the required current-base merge check, outside merge admission.Interrupting pregate (Ctrl-C or SIGTERM) does not leave tests running behindit: the running stage — including the test runner's npm and Vitest@@ -159,7 +126,7 @@ pregate is still settling its stage. On Windows, where `cmd.exe` has no`exec`, the repository-root `exec.cmd` shim (found first in the workingdirectory) runs the same command.-After the push (and, when you open the pull request yourself, before+The default focused receipt is local evidence only: do not invoke `pregate-attest.js` or rerun solely to attest it. After explicit `--full` validation, after the push (and, when you open the pull request yourself, before`gh pr create`), `node scripts/pregate-attest.js` posts that receipt as a`pregate` commit status on the pushed head, bound to the validated tree andnaming the platform and Node it ran on, and the pull request's impact planner@@ -317,7 +284,7 @@ npm testnpm test --prefix server -- services/creativeDirector/videoAssembly.test.js```-`npm run pregate` runs the DB suite itself when the plan selects it, after+`npm run pregate -- --full` runs the DB suite when the plan selects it, afterevery other stage, against `portos_test` only. For release validation byhand, run `npm run test:db` after the server and clientsuites finish rather than alongside them. A concurrent run is supported —diff --git a/docs/GITHUB_ACTIONS.md b/docs/GITHUB_ACTIONS.mdindex 0ce1703fdc..86345edd25 100644--- a/docs/GITHUB_ACTIONS.md+++ b/docs/GITHUB_ACTIONS.md@@ -217,6 +217,9 @@ are never executed as a substitute.### Pregate attestation+Default local pregate is focused validation, not a local CI run. Version 3 focused receipts cannot produce CI-skipping attestations. The following mechanism applies only to explicit `npm run pregate -- --full` validation and compatible legacy receipts. Hosted CI remains authoritative for broad coverage on ordinary pushes; do not rerun locally merely to obtain an attestation.++A green pregate on this machine runs the same planner, runners, environmentand `portos_test` database the Linux jobs do, so repeating those stages in CIfor the install's own pull requests buys queue time and nothing else (designdiff --git a/docs/VERSIONING.md b/docs/VERSIONING.mdindex c2b3fc636d..e54151068e 100644--- a/docs/VERSIONING.md+++ b/docs/VERSIONING.md@@ -63,6 +63,10 @@ npm run pregategit push```+The default pregate is lint/formatting, structural guards and focused tests.+Hosted CI owns broad validation; use `npm run pregate -- --full` only when+explicitly needed locally. Focused receipts never attest unrun CI suites.+A conflict-free feature branch may merge behind `main` once its current-headrequired checks and configured reviews pass. Do not restart validation solelybecause another agent merged; follow [the merge policy](../AGENTS.md#git-workflow).diff --git a/lib/slashdo b/lib/slashdoindex db6e435636..a6698f8b68 160000--- a/lib/slashdo+++ b/lib/slashdo@@ -1 +1 @@-Subproject commit db6e4356366ce70721fa63f676d8db6678de01fd+Subproject commit a6698f8b68a3c2f896bd997152e524e2b42404ecdiff --git a/scripts/lib/pregateAttestation.js b/scripts/lib/pregateAttestation.jsindex 676e884a0e..9e8e2bfdda 100644--- a/scripts/lib/pregateAttestation.js+++ b/scripts/lib/pregateAttestation.js@@ -47,6 +47,8 @@ const ATTESTABLE = new Set(ATTESTABLE_STAGES);* @returns {string[]} in ATTESTABLE_STAGES order*/export function attestedStagesFromReceipt(report) {+ // Focused local checks are not CI suite proof, even if stage names coincide.+ if (report?.validationMode === 'focused' || (report?.version >= 3 && report?.validationMode !== 'ci')) return [];const stages = Array.isArray(report?.stages) ? report.stages : [];const reduced = report?.plan?.downgraded === true ? new Set(['server', 'client']) : new Set();return ATTESTABLE_STAGES.filter((suite) => {diff --git a/scripts/lib/pregateReport.js b/scripts/lib/pregateReport.jsindex 99f6ca50a6..9f0218e16e 100644--- a/scripts/lib/pregateReport.js+++ b/scripts/lib/pregateReport.js@@ -21,11 +21,12 @@ import { dirname, join, resolve } from 'node:path';export const PREGATE_REPORT_PATH = '.cache/pregate/report.json';/**+ * Version 3 adds validationMode: focused receipts never attest CI suites.* Version 2 added `plan.downgraded`: whether a full plan was replaced by the* always-run guards. `scripts/pregate-attest.js` refuses a receipt without it,* because a downgraded server stage passing is not CI's server selection passing.*/-export const PREGATE_REPORT_VERSION = 2;+export const PREGATE_REPORT_VERSION = 3;/*** Hash the exact working tree as it stands: tracked, modified, deleted and@@ -102,6 +103,7 @@ export function buildPregateReport({const passed = stageRecords.length > 0 && stageRecords.every((stage) => stage.status === 'passed');return {version: PREGATE_REPORT_VERSION,+ validationMode: options.full ? 'ci' : 'focused',startedAt,finishedAt,passed,@@ -114,7 +116,7 @@ export function buildPregateReport({options,plan: {full: plan.full,- // True when a full plan ran only the always-run guards (no `--full`):+ // True when the local selection reduced CI coverage (no `--full`):// the server and client stages below then prove less than CI's selection.downgraded: Boolean(downgraded),reason: plan.reason,diff --git a/scripts/pregate-attest.js b/scripts/pregate-attest.jsindex a6427a18f5..a06680cefc 100644--- a/scripts/pregate-attest.js+++ b/scripts/pregate-attest.js@@ -113,6 +113,9 @@ export function planAttestation(report, { sha, treeOf, isPushed, remote, defaultif (typeof report.plan?.downgraded !== 'boolean') {throw refusal(`receipt at ${PREGATE_REPORT_PATH} predates attestation (no plan.downgraded); ${RERUN}`);}+ if (report.validationMode === 'focused' || (report.version >= 3 && report.validationMode !== 'ci')) {+ throw refusal('focused local validation does not attest CI suites; wait for required hosted CI. Do not rerun solely to attest.');+ }if (report.passed !== true) throw refusal(`receipt at ${PREGATE_REPORT_PATH} did not pass; fix the failure and ${RERUN}`);if (report.treeStable !== true) {throw refusal(`the working tree changed while pregate ran (${String(report.tree).slice(0, 12)} → ${String(report.treeAfterRun).slice(0, 12)}); ${RERUN}`);diff --git a/scripts/pregate-attest.test.js b/scripts/pregate-attest.test.jsindex fac950de27..7d0339619e 100644--- a/scripts/pregate-attest.test.js+++ b/scripts/pregate-attest.test.js@@ -27,7 +27,7 @@ const plan = { full: false, reason: 'scoped', server: { mode: 'files', files: []/** A receipt as pregate writes it, with the given stage outcomes. */const receipt = ({ stages, tree = TREE, treeAfterRun = tree, downgraded = false, skipped = [], base = { ref: 'origin/main', sha: BASE } }) => buildPregateReport({- plan, options: { base: base.ref }, base, head: { sha: SHA }, tree, treeAfterRun, stages, skipped,+ plan, options: { base: base.ref, full: true }, base, head: { sha: SHA }, tree, treeAfterRun, stages, skipped,runtime: { node: 'v26.10.0', platform: OS }, startedAt: 's', finishedAt: 'f', downgraded,});@@ -333,3 +333,13 @@ describe('runAttest', () => {expect(err[0]).toContain(USAGE);});});++describe('focused receipt boundary', () => {+ it('refuses focused or unspecified v3 proof while preserving legacy stage evidence', () => {+ const report = { version: 3, validationMode: 'focused', plan: { downgraded: false }, stages: [{ suite: 'server', status: 'passed' }] };+ expect(attestedStagesFromReceipt(report)).toEqual([]);+ expect(() => planAttestation(report, {})).toThrow(/focused local validation/);+ expect(attestedStagesFromReceipt({ ...report, validationMode: undefined })).toEqual([]);+ expect(attestedStagesFromReceipt({ ...report, version: 2, validationMode: undefined })).toEqual(['server']);+ });+});diff --git a/scripts/pregate.js b/scripts/pregate.jsindex 0db1558a66..b56aa858af 100644--- a/scripts/pregate.js+++ b/scripts/pregate.js@@ -1,53 +1,12 @@#!/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 CI's hidden-content scan and hands the SAME planner's plan to the- * SAME runners (`run-ci-lint.js`, `run-ci-tests.js`, the client build, the- * boot smoke, the browser suites and the serial `portos_test` suite), so a- * green pregate means the Linux jobs are green for the same reasons — never- * a second, drifting opinion about which tests matter. Stages run in CI's- * dependency order after early structural guards, with the DB suite last and- * alone: its per-case budgets assume no concurrent suite (docs/CONTRIBUTING.md).- *- * node scripts/pregate.js [--base <ref>] [--full] [--skip-lint] [--plan-only]- * [--skip-db] [--skip-browser] [--skip-build] [--skip-smoke]- *- * --guards-only [--merged-with <ref>] run tree-wide guards on HEAD or a temporary merged tree- *- * --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- * and reports the resource suites as not run)- * --skip-lint skip linting in both client and server workspaces- * --skip-db, --skip-browser, --skip-build, --skip-smoke- * leave that suite to CI; it is reported as not run- * --plan-only print the plan and the stages, run nothing- *- * A resource suite whose prerequisite this machine lacks (no reachable test- * Postgres; no Chrome, ffmpeg or client bundler) is reported the same way, with- * the remedy, and the run continues. The summary and the receipt both name- * every suite that was NOT run, so a green result never claims a suite it- * skipped. The Windows job and the Linux worker-containment job (bubblewrap- * namespaces) are the suites only CI can prove.- *- * The receipt (`.cache/pregate/report.json`, see scripts/lib/pregateReport.js)- * records the plan, each stage's outcome and duration, the skipped suites, the- * base and HEAD commits, and the hash of the exact working tree validated —- * untracked and uncommitted files included — so a later attestation can match- * it to the commit that ships. Attesting is deliberately NOT a flag here:- * pregate runs before the commit and the push, and a commit status can only- * be posted on a pushed commit, so `node scripts/pregate-attest.js` is its- * own step after `git push` (docs/GITHUB_ACTIONS.md "Pregate attestation").+ * Lightweight local pre-push validation: lint/format, structural invariants+ * and directly owned tests. Hosted CI keeps its broad impact plan.+ * `--full` opts into that CI plan locally, including selected resource suites.+ * `--guards-only [--merged-with <ref>]` retains current-base merge safety.+ * Receipts describe the exact tree and coverage; focused results never attest+ * CI suites. Cancellation still settles every owned stage process group.*/import { spawn, spawnSync } from 'child_process';@@ -77,7 +36,7 @@ const IS_WIN32 = process.platform === 'win32';*/export const UNCOVERED_SUITES = Object.freeze({db: 'needs a reachable test Postgres: npm run setup:db:test && npm run test:db (never against the real `portos` database)',- browser: 'needs Chrome, ffmpeg and the client bundler; run `npm run pregate --full` once they are installed',+ browser: 'needs Chrome, ffmpeg and the client bundler; run `npm run pregate -- --full` once they are installed',build: 'npm run build && npm run test --prefix client -- ApiExplorer.bundle',smoke: 'npm run smoke',windows: 'CI is the only proof',@@ -109,7 +68,7 @@ export function uncoveredSuites(plan, { options = {}, downgraded = false, prereqif (!suiteSelected(plan, suite)) continue;let reason = null;if (flags[suite]) reason = `skipped by --skip-${suite}`;- else if (downgraded) reason = 'full plan downgraded; pass --full to run it';+ else if (downgraded) reason = 'local focused mode; hosted CI runs it (opt in locally with --full)';else if (prerequisites[suite]?.ok === false) {const { reason: detail, category } = prerequisites[suite];const probeOnly = category === 'probe-failed';@@ -336,6 +295,33 @@ export function downgradeFullPlan(plan, trackedFiles, changedFiles = []) {};}+/** Local selection never expands through the transitive server import graph.+ * A sibling test or an explicitly edited test owns the focused check; broader+ * integration coverage and unowned changes remain with hosted CI.+ */+export function focusedLocalPlan(plan, trackedFiles, changedFiles) {+ const local = downgradeFullPlan(plan, trackedFiles, changedFiles);+ const tracked = new Set(trackedFiles);+ const browser = new Set(plan.browser.files);+ const unitTest = path => !browser.has(path) && /\.test\.[cm]?[jt]sx?$/.test(path)+ && !/(?:\.(?:db|browser|live)\.test\.|\/db\.test\.)/.test(path);+ const focused = new Set();+ for (const path of changedFiles) {+ if (unitTest(path) && tracked.has(path)) focused.add(path);+ if (!/\.[cm]?[jt]sx?$/.test(path) || /\.test\./.test(path)) continue;+ const stem = path.replace(/\.[cm]?[jt]sx?$/, '');+ for (const suffix of ['.test.js', '.test.jsx', '.test.ts', '.test.tsx', '.test.mjs', '.test.cjs']) {+ const test = `${stem}${suffix}`;+ if (tracked.has(test) && unitTest(test)) focused.add(test);+ }+ }+ for (const scope of ['server', 'client']) {+ const files = [...new Set([...local[scope].files, ...[...focused].filter(path => scope === 'client' ? path.startsWith('client/') : !path.startsWith('client/'))])];+ local[scope] = { mode: files.length ? 'files' : 'skip', files, sources: [] };+ }+ return local;+}+const git = (args) => execFileSync('git', args, { cwd: REPO_ROOT, encoding: 'utf8' }).trim();@@ -448,7 +434,7 @@ export const USAGE = `Usage: node scripts/pregate.js [--base <ref>] [--full] [----guards-only run only always-run and diff-selected structural guards (no attestation receipt)--merged-with <ref> validate HEAD merged with this fetched ref in an isolated temporary repository--base <ref> compare against <ref> instead of the remote default branch- --full run the complete suite when the plan demands it+ --full opt into CI-selected broad suites locally--skip-lint skip linting in both client and server workspaces--skip-db leave the portos_test DB suite to CI (reported as not run)--skip-browser leave the cross-workspace browser suites to CI (reported as not run)@@ -759,15 +745,15 @@ async function main() {};console.log(`📋 ${raw.changed_files.length} changed file(s) — ${plan.reason}.`);- const downgraded = plan.full && !options.full && !options.guardsOnly;+ const downgraded = !options.full && !options.guardsOnly;const guardPlan = downgradeFullPlan(plan, git(['ls-files', '-z']).split('\0').filter(Boolean), changedFiles);if (options.guardsOnly) {plan = guardPlan;Object.assign(plan, { lint: { mode: 'skip', files: [] }, browser: { files: [] }, db: false, windows: false, build: false, smoke: false, promptHistory: false, linuxContainment: false, supercolliderLive: false, dockerContainmentLive: false });}if (downgraded) {- plan = guardPlan;- console.log('⚠️ CI will run the FULL suite for this diff — running always-run and diff-selected structural guards only. Pass --full to run everything, including the build, smoke, browser and DB suites.');+ plan = focusedLocalPlan(plan, git(['ls-files', '--cached', '--others', '--exclude-standard', '-z']).split('\0').filter(path => path && existsSync(join(REPO_ROOT, path))), changedFiles);+ console.log('ℹ️ Local validation: lint, structural guards and focused tests only. Hosted CI owns broad coverage; pass --full for the complete CI plan locally.');}describeBrowserSelection(plan.browser.files).forEach((line) => { console.log(line); });@@ -777,7 +763,7 @@ async function main() {const uncovered = uncoveredSuites(plan, { options, downgraded, prerequisites });const skip = Object.fromEntries(uncovered.map(({ suite }) => [suite, true]));const stages = resolvePlanStages(plan, { skipLint: options.skipLint, baseSha, skip, databaseEnv,- guardPlan: options.guardsOnly || downgraded ? null : guardPlan });+ guardPlan: options.guardsOnly ? null : guardPlan });return { uncovered, stages: options.guardsOnly? stages.filter(stage => stage.suite === 'server' || stage.suite === 'client').map(stage => ({ ...stage, env: { ...stage.env, PORTOS_TEST_MEMO: 'off' } }))diff --git a/scripts/pregate.test.js b/scripts/pregate.test.jsindex 3580626e3f..38b2643f0b 100644--- a/scripts/pregate.test.js+++ b/scripts/pregate.test.js@@ -1,11 +1,5 @@-/**- * 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.+/** Local validation selection, stage execution, process ownership and receipt+ * contracts. Hosted CI owns the broader test-impact plan.*/import { cosWorkerBudget } from './lib/cosWorkerBudget.js';import { afterAll, afterEach, beforeAll, beforeEach, describe, it, expect } from 'vitest';@@ -27,6 +21,7 @@ import {describeBrowserSelection,describeStageCommand,downgradeFullPlan,+ focusedLocalPlan,parseArgs,pregateWorkerEnv,stageSpawnEnv,@@ -279,7 +274,7 @@ describe('pregate hidden-content invocation', () => {it('prints the selected guard, broad and browser stages without starting any process', () => {prepareGuardFixture({ browser: true });- const result = run('--plan-only');+ const result = run('--plan-only', '--full');expect(result.status, result.stderr).toBe(0);expect(result.stdout).toContain('Planning against');expect(result.stdout).toContain('changed file');@@ -295,7 +290,7 @@ describe('pregate hidden-content invocation', () => {// prerequisite probe, with the unfinished broad stages preserved in the receipt.it('refuses a missing helper catalog registration before broad tests or browser probes start', () => {prepareGuardFixture({ browser: true });- const result = run('--skip-lint');+ const result = run('--skip-lint', '--full');expect(result.status).not.toBe(0);expect(result.stderr).toContain('Missing helper barrel/catalog registration');const events = readFileSync(join(root, '.cache/events'), 'utf8');@@ -318,7 +313,7 @@ describe('pregate hidden-content invocation', () => {write('server/lib/index.js', "export { helper } from './helper.js';\n");write('server/lib/README.md', '# Shared helpers\nhelper\n');if (changed) write('.cache/mutate', 'mutate during lint');- const result = run();+ const result = run('--full');expect(result.status, result.stderr).toBe(0);const events = readFileSync(join(root, '.cache/events'), 'utf8').trim().split('\n');expect(events.filter(event => event === 'catalog')).toHaveLength(changed ? 2 : 1);@@ -763,10 +758,14 @@ describe('pregate hidden-content invocation', () => {expect(snapshot()).toEqual(before);});- it('plans the portos_test stages for a DB-only suite in a scoped working-tree plan', () => {+ it('leaves DB-only changes to hosted CI by default and plans portos_test only with explicit full validation', () => {mkdirSync(join(root, 'server/routes'), { recursive: true });write('server/routes/decks.db.test.js', "import { it } from 'vitest';\nit('db contract', () => {});\n");- const result = run('--plan-only');+ const focused = run('--plan-only');+ expect(focused.status, focused.stderr).toBe(0);+ expect(focused.stdout).toContain('CI will also run: db');+ expect(focused.stdout).not.toContain('• DB suite');+ const result = run('--plan-only', '--full');expect(result.status, result.stderr).toBe(0);expect(result.stdout).toContain('• DB provision (portos_test): npm run setup:db:test --prefix server');expect(result.stdout).toContain('• DB suite (portos_test): npm run test:db:ci --prefix server');@@ -1214,8 +1213,8 @@ describe('uncoveredSuites', () => {const flagged = uncoveredSuites(selected, { options: { skipDb: true, skipBuild: true }, downgraded: true });expect(flagged.map(({ suite, reason }) => [suite, reason])).toEqual([['build', 'skipped by --skip-build'],- ['smoke', 'full plan downgraded; pass --full to run it'],- ['browser', 'full plan downgraded; pass --full to run it'],+ ['smoke', 'local focused mode; hosted CI runs it (opt in locally with --full)'],+ ['browser', 'local focused mode; hosted CI runs it (opt in locally with --full)'],['db', 'skipped by --skip-db'],['windows', 'a Windows runner has no local equivalent'],]);@@ -1393,7 +1392,7 @@ describe('buildPregateReport', () => {startedAt: 's',finishedAt: 'f',});- expect(report.version).toBe(2);+ expect(report.version).toBe(3);expect(report.plan.downgraded).toBe(false);expect(report.passed).toBe(false);expect(report.treeStable).toBe(false);@@ -1465,3 +1464,14 @@ describe('validatedTreeHash', () => {}});});++describe('focused local policy', () => {+ it('runs direct behavior owners and edited unit tests without transitive or resource suites', () => {+ const tracked = ['server/lib/a.js', 'server/lib/a.test.js', 'server/lib/unrelated.test.js', 'server/lib/a.db.test.js', 'server/lib/a.browser.test.js', 'client/src/Card.jsx', 'client/src/Card.test.jsx', 'scripts/tool.test.js', 'server/services/htmlComposition/index.test.js'];+ const changed = ['server/lib/a.js', 'client/src/Card.jsx', 'scripts/tool.test.js', 'server/lib/a.db.test.js', 'server/lib/a.browser.test.js', 'docs/README.md', 'server/services/htmlComposition/index.test.js'];+ const local = focusedLocalPlan(planWith({ browser: { files: ['server/services/htmlComposition/index.test.js'] }, server: { mode: 'related', files: ['server/lib/unrelated.test.js'], sources: ['server/lib/a.js'] } }), tracked, changed);+ expect(local.server).toEqual({ mode: 'files', files: ['server/lib/a.test.js', 'scripts/tool.test.js'], sources: [] });+ expect(local.client.files).toContain('client/src/Card.test.jsx');+ expect(resolvePlanStages(local, { skip: { db: true, browser: true, build: true, smoke: true } }).every(stage => !['db', 'browser', 'build', 'smoke'].includes(stage.suite))).toBe(true);+ });+});diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.jsindex 7c4d803f57..23403f67ff 100644--- a/server/services/promptSections/completion.js+++ b/server/services/promptSections/completion.js@@ -660,7 +660,7 @@ export function buildMergeAdmissionSection(agentId, { portosMergedTreeGuards = t` printf '%s' "$ADMISSION_RESPONSE" | node -e 'const fs = require("node:fs"); const response = JSON.parse(fs.readFileSync(0,"utf8")); process.exit(response.admitted === true ? 0 : 1);'`,'}','```',- '- Otherwise (head changed, a required check is not green, or the PR is `DIRTY`/conflicting, `BEHIND` where branch rules require an up-to-date head, `BLOCKED`, or still `UNKNOWN` after a few re-reads): release with outcome resync. Then, OUTSIDE the lease, sync onto the latest default branch, rerun pregate and the affected required reviews, push, run `node scripts/pregate-attest.js` if the repository ships it (a refusal is reported, not retried), wait for required CI on the new head, and acquire again. After three resync rounds without a merge, record leave-open instead.',+ '- Otherwise (head changed, a required check is not green, or the PR is `DIRTY`/conflicting, `BEHIND` where branch rules require an up-to-date head, `BLOCKED`, or still `UNKNOWN` after a few re-reads): release with outcome resync. Then, OUTSIDE the lease, sync onto the latest default branch, rerun pregate and the affected required reviews, push, attest only an explicit CI-mode or compatible legacy receipt when the repository supports it (focused receipts never attest; a refusal is reported, not retried), wait for required CI on the new head, and acquire again. After three resync rounds without a merge, record leave-open instead.','Verify the remote state is exactly MERGED, then release with outcome merged before worktree cleanup. On a recorded failure or leave-open handoff, release with outcome leave-open. Require released:true; report a failed release without deleting or overwriting ownership state:','```bash', command('release', { token: 'TOKEN', outcome: 'merged' }), '```','The server voids an agent lease 5 minutes after acquisition and lets another run reclaim it. A check refused with lease-expired or lease-owner-mismatch means stop: do not merge on that token; acquire again and repeat the re-read. Never bypass CI, infer success from absent checks, merge without the head pin, or treat auto-merge/queued as MERGED. Admission coordinates participating runs on this install only; manual merges and other installs can still move the base, which the forge’s merge state already reflects.',diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.jsindex 5ace66a218..0b85088e34 100644--- a/server/services/promptSections/reviewLifecycle.js+++ b/server/services/promptSections/reviewLifecycle.js@@ -1095,7 +1095,7 @@ export const LEAVE_PR_OPEN_STEP = (step, jiraTracked = false) => `${step}. **Lea* numbers hold; it belongs between the push and the CI wait because the* status must exist before the impact job plans the run.*/-const PREGATE_ATTESTATION_STEP = '**Pregate attestation (GitHub, right after the push):** if this repository has `scripts/pregate-attest.js`, run it from the checkout you pushed — for a new pull request, after the push and before opening it. It posts a `pregate` commit status bound to the tree your green `npm run pregate` validated, so the pull request\'s CI skips the attested stages (docs/GITHUB_ACTIONS.md "Pregate attestation"). If it refuses, do not rerun pregate or retry just to attest: say why in your completion summary and wait for full CI as before.';+const PREGATE_ATTESTATION_STEP = '**Local validation and CI proof:** honor the repository local gate: lint/formatting, fast structural checks and focused changed-behavior tests. Do not expand a focused local policy into broad transitive/server/browser/DB/build/smoke validation on each push or review correction. Required hosted CI and configured reviews remain mandatory. If scripts/pregate-attest.js exists, read the receipt validationMode first: focused receipts are local evidence only and MUST NOT be attested. Only explicit full CI-mode or compatible legacy receipts may use the existing attestation procedure after pushing; never rerun solely to attest.';export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>', forge = 'github', alreadyMergedHint = ' (a saved `/do:pr` default can merge it for you)', localReviewers = [], localReviewRequired = false, reviewRecheckReviewers = [], mergeEquivalentLine = null, deleteBranch = true }) {const gh = forge !== 'gitlab';diff --git a/server/services/taskPromptDefaults.test.js b/server/services/taskPromptDefaults.test.jsindex 3c3266b7f3..82711a487a 100644--- a/server/services/taskPromptDefaults.test.js+++ b/server/services/taskPromptDefaults.test.js@@ -974,9 +974,11 @@ describe('taskPromptDefaults integrity snapshot', () => {// issue labels — the same per-issue routing DISPATCH_HINT_FANOUT_GUIDANCE// already gives the claim swarm's Phase B, imported verbatim rather than// retyped so the two consumers can't drift on vocabulary.- it('branch-reconcile v10 routes each fan-out sub-agent by its own branch\'s dispatch labels and leaves superseded retirement to the deterministic pass', () => {+ it('branch-reconcile v11 routes each fan-out sub-agent by its own branch\'s dispatch labels and leaves superseded retirement to the deterministic pass', () => {const current = DEFAULT_TASK_PROMPTS['branch-reconcile'];- expect(PROMPT_VERSIONS['branch-reconcile']).toBe(10);+ expect(PROMPT_VERSIONS['branch-reconcile']).toBe(11);+ expect(current).toContain('focused changed-behavior tests');+ expect(current).toContain('focused results never attest unrun suites');expect(current).toContain('the deterministic pass backs the branch up and retires it');expect(current).not.toContain('a verdict alone does not authorize removal');expect(current).toContain('Base movement alone does not require a rebase or another CI run');diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.jsonindex 7c2f32625d..e508f74f7d 100644--- a/server/services/taskPromptDefaults/integrity.snapshot.json+++ b/server/services/taskPromptDefaults/integrity.snapshot.json@@ -11,7 +11,7 @@"better-structural-drift": "ce8b7ba26e5567275b7667d082c3125a","better-test-quality": "8e305f986e9c9066da5db2aee76fc024","branch-cleanup": "60f132e83570a7a4559a7adf7af1b883",- "branch-reconcile": "234e23b6c8adc108b5a0cabeafcb8dfd",+ "branch-reconcile": "a70dae89a9ff1f0dfa0804b5ae24b00d","claim-issue": "b2e7d4a99ee4ab2f6781aacfdef4b9f8","claim-issue-gitlab": "ccf8e2a828dd5cb407d80252e974731f","claim-issue-jira": "b793412731c754db0b88b4d84d7e454f",@@ -76,7 +76,7 @@"better-runtime-safety": 4,"better-structural-drift": 2,"better-test-quality": 2,- "branch-reconcile": 10,+ "branch-reconcile": 11,"claim-issue": 47,"claim-issue-gitlab": 41,"claim-issue-jira": 27,@@ -179,7 +179,8 @@"45feea1d5ccd456bb0bec5d12c373a64","ae6e8164698faebc2a5fd4fecb3d41e8","90acf7a56c0de2147cf7463ba338a099",- "4c69ed43b274ffee3a08a8da980be2bd"+ "4c69ed43b274ffee3a08a8da980be2bd",+ "234e23b6c8adc108b5a0cabeafcb8dfd"],"claim-issue": ["37949d1b1fa8d461a15658f8f4192d97",diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.jsindex a06a7c58af..f93f50a9ef 100644--- a/server/services/taskPromptDefaults/prompts.js+++ b/server/services/taskPromptDefaults/prompts.js@@ -4278,7 +4278,7 @@ ${DISPATCH_HINT_FANOUT_GUIDANCE}- Never force-push the default branch.- **A branch can be finished, correct, and still not wanted.** Work that sat while the default branch moved may have been solved there a different way in the meantime; merging it then UNDOES what already shipped. Each branch's "Do:" line opens with the files the default branch has also changed since that branch diverged — the sub-agent reads those first and reports **SUPERSEDED** if the default branch already solves that branch's problem, by any means (a differently-named function, a policy object where the branch has a boolean, a scheduled tick where the branch has a watcher). A SUPERSEDED branch is left completely untouched: no commit, no rebase, no conflict resolution, no merge.- **A conflict you can resolve is not evidence the work is still needed.** It is the most common way a superseded branch gets merged looking deliberate — the resolution is mechanically sound and semantically a regression. Treat every conflict as a question about supersession first and a merge chore second.-- **Nothing reaches a PR unverified.** Each sub-agent fetches the default branch for comparison, checks semantic overlap and supersession, then runs the touched workspaces' test suites and lint and reads the result. A conflict-free branch may merge behind the default branch when required current-head checks and configured reviews pass. Base movement alone does not require a rebase or another CI run. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after changing the head, rerun affected validation and required reviews/checks. This overrides mandatory base-sync instructions in delegated slashdo workflows. A branch whose tests the sub-agent has not seen pass is never pushed.+- **Nothing reaches a PR unverified.** Each sub-agent fetches the default branch for comparison, checks semantic overlap and supersession, then runs the repository's local gate (lint/formatting, fast structural checks and focused changed-behavior tests) and reads the result; broad local CI is opt-in, required hosted CI remains authoritative, and focused results never attest unrun suites. A conflict-free branch may merge behind the default branch when required current-head checks and configured reviews pass. Base movement alone does not require a rebase or another CI run. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk; after changing the head, rerun affected validation and required reviews/checks. This overrides mandatory base-sync instructions in delegated slashdo workflows. A branch whose tests the sub-agent has not seen pass is never pushed.- **A branch whose "Do:" line ends in a merge is not finished until it IS merged.** Its sub-agent stays alive through CI — waiting out the check run, fixing what goes red, then merging — and reports back only when the PR is merged or a specific check/review is blocking it. "PR opened, left open for review" is a completed STEP, not a completed branch: the PR just sits green until the next run re-drives it. Do not end your own run while a sub-agent is still waiting on CI.- Merging is gated by the "Do:" line itself — required CI green, MERGEABLE, and the review that branch's flow ran (\`/do:pr\`'s reviewer loop for a PR this task opens; the named review for one already in review). That gate, not a blanket ban, is what keeps unreviewed work out of the default branch. Merge only via \`gh pr merge\`, never a local \`git merge\` into the default branch.- If a sub-agent reports a branch is incomplete, superseded, or blocked, leave it as-is and note it in your summary.diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.jsindex df75dc5a5c..151130522b 100644--- a/server/services/taskPromptDefaults/versions.js+++ b/server/services/taskPromptDefaults/versions.js@@ -22,7 +22,7 @@ export const PROMPT_VERSIONS = {'code-reviewer-b': 1, // v1: 2-stage pipeline (codebase review → triage & implement)'reference-watch': 5, // v5: upstream commit list is fenced and the prompt carries a public-forge trust-boundary clause (#12491). v4: forge proposals use plain human-readable titles and tracker-defined IDs/filing scripts; PLAN.md keeps its existing checklist IDs. The prompt delegates inventory, duplicate matching, labels, and command syntax to {trackerInstructions}. v3: record proposals in the app's RESOLVED work tracker (PLAN.md / GitHub / GitLab / JIRA) via the {trackerInstructions} block — no longer hardcodes PLAN.md, so an app configured for GitHub issues gets `gh issue create` proposals. v2: append slug-tagged checklist items to PLAN.md (Adopt + Maybe) instead of writing REFERENCE_REVIEW.md; security-flagged commits get no PLAN entry (mentioned only in final summary)'pr-watcher': 2, // v1: review-and-comment default for newly-opened PRs on the app's default branch- 'branch-reconcile': 10, // v10: SUPERSEDED verdicts are retired by the deterministic backup-first reap, not held. v9: dispatch scoped completed-checkout reviews through verified archival retirement; preserve intentional holds. v8: merge ready conflict-free branches without chasing default-branch movement; rebase only for conflicts, enforced policy or evidenced integration risk. v7: align SUPERSEDED summary instruction with deterministic cleanup pass; superseded branches with worktrees are reaped rather than held by the claim idle window. v6: prefixed labels are spelled with the forge separator — GitLab gets its scoped `::` (`model::heavy`), GitHub keeps `:` — matching slashdo v3.39.0. v5: explicit Ultra capability dispatch alongside the existing three tiers.+ 'branch-reconcile': 11, // v11: honor focused local validation; required hosted CI owns broad proof. v10: SUPERSEDED verdicts are retired by the deterministic backup-first reap, not held. v9: dispatch scoped completed-checkout reviews through verified archival retirement; preserve intentional holds. v8: merge ready conflict-free branches without chasing default-branch movement; rebase only for conflicts, enforced policy or evidenced integration risk. v7: align SUPERSEDED summary instruction with deterministic cleanup pass; superseded branches with worktrees are reaped rather than held by the claim idle window. v6: prefixed labels are spelled with the forge separator — GitLab gets its scoped `::` (`model::heavy`), GitHub keeps `:` — matching slashdo v3.39.0. v5: explicit Ultra capability dispatch alongside the existing three tiers.// v4: the prompt now interpolates DISPATCH_HINT_FANOUT_GUIDANCE next to the "spawn one sub-agent per branch" instruction and tells the coordinator to dispatch each sub-agent at ITS OWN branch's recommended model/effort — the same per-issue routing the claim swarm's Phase B already does, applied here because branch-reconcile fans out over issue-derived branches too (#6373). v3: SUPERSEDED is a first-class outcome — a branch whose problem the default branch already solved a different way is reported and left untouched, never merged (merging it undoes shipped work). A resolvable conflict is explicitly NOT evidence the work is still wanted, and every branch is rebased + test-verified before it reaches a PR. v2: a branch whose "Do:" line ends in a merge isn't finished until it IS merged — the sub-agent waits CI out in-session instead of handing back a green-but-open PR, and the old blanket "never merge unreviewed work" rule (which vetoed the per-branch merge instruction) is replaced by the explicit CI-green + MERGEABLE + review gate. v1: per-app coordinator that finishes in-flight LOCAL branches (open PR / resolve conflicts / drive review / auto-merge) after the deterministic merged-branch cleanup pass. Peer-safe (local refs only). Replaced the PortOS-only branchReconcileScheduler.'issue-reconcile': 9, // v9: API calls target the {portosApiUrl} placeholder expanded at spawn (loopback mirror on HTTPS installs), not the load-time advertised origin (#12405). v8: whole label-create commands instead of a `name hex` list (#9056). v7: prefixed labels are spelled with the forge separator — GitLab gets its scoped `::` (`model::heavy`), GitHub keeps `:` — matching slashdo v3.39.0. Shared mandatory issue-label contract and restricted contributor invitations. v4: follow-up recipes apply independent slashdo dispatch hints and contributor labels (`good first issue`/`help wanted`, Jira hyphenated equivalents) instead of only `plan`. v3: adds a JIRA arm — status-based zombies (a ticket left In Review with remaining scope + no live claim; JIRA has no `in-progress` label) detected via the PortOS JIRA API and healed through ticket transitions + `POST tickets`, routed in via the app's resolved workTracker ('jira') rather than the git host. v2: forge-aware — the scan + coordinator now cover GitLab (`glab` issues + MRs) as well as GitHub, resolved from the app's origin host; every heal command is shown as gh/glab and the injected header names the forge. v1: per-app coordinator that heals ZOMBIE issues (open + in-progress but their PR merged with no live claim) after the deterministic gh/git scan. Applies the partial-ship hybrid — close + file a scoped follow-up when the remainder is separable, else comment "done/remaining" + release the claim so the queue re-picks it.'refresh-local-llm-catalog': 4, // v4: follows the current no-per-branch-changelog contract and relies on a release-note-quality commit subject. v3: catalog maintenance now preserves the primary-lane + cross-lane recommendation taxonomy and reserves featured treatment for a deliberate first choice. v2: PortOS-only task, so it names the retired fragment command directly. v1: research current local models, refresh LOCAL_LLM_CATALOG + EDITORIAL_FAMILY_RANK, PR (PortOS repo only)