Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
ci: upgrade-from-N matrix (GBRA-224 W2)
garrytanb84ee79ae184
diff --git a/.github/workflows/nightly-watch.yml b/.github/workflows/nightly-watch.ymlindex 0be4f37383..b915ce906a 100644--- a/.github/workflows/nightly-watch.yml+++ b/.github/workflows/nightly-watch.yml@@ -57,6 +57,7 @@ on:- OSV-Scanner- CI health- TLA+ specs+ - Upgrade matrixtypes: [completed]branches: [master]workflow_dispatch:diff --git a/.github/workflows/upgrade-matrix.yml b/.github/workflows/upgrade-matrix.ymlnew file mode 100644index 0000000000..2f53f8a197--- /dev/null+++ b/.github/workflows/upgrade-matrix.yml@@ -0,0 +1,279 @@+name: Upgrade matrix++# GBRA-224 W2: install published old releases exactly as a user does, upgrade+# each through its own updater to one candidate, and check the candidate on the+# upgraded brain (scripts/upgrade-matrix.ts; docs/ci-upgrade-matrix.md).+#+# The gate runs from master: dispatch and schedule runs refuse any other ref,+# check out master's harness (this workflow and scripts/upgrade-matrix*), and+# take the candidate as an input that is only ever installed as the subject.+# The plan job records the harness commit, the candidate tag, commit and tree,+# and the from-versions in the upgrade-matrix-plan artifact; the summary job+# writes the upgrade-matrix-receipt artifact. A candidate therefore cannot+# change the gate that qualifies it. Pull-request runs are developer feedback,+# not gate evidence: they run the pull request's own harness against its head+# (their receipt records event pull_request and harness = candidate).+#+# Triggers:+# workflow_dispatch full matrix against the candidate input (default: the+# newest release); optional explicit from-versions and a+# proof-only fault injection.+# schedule nightly, full matrix against the newest release; a red+# run opens or updates one upgrade-break issue (the label+# that holds stable promotion) and a green run closes it.+# pull_request reduced subset (N-1 and N-50, PGLite and Postgres,+# keyless, repo-less) against the head, only when schema,+# migration, self-upgrade or harness paths change.+#+# This workflow does not gate releases to the latest lane; stable promotion+# reads its receipt (GBRA-224 W1).++on:+ workflow_dispatch:+ inputs:+ candidate:+ description: Release tag (v0.60.475.0) or commit to qualify; empty means the newest published release+ required: false+ type: string+ default: ''+ from:+ description: Comma-separated release tags to upgrade from instead of the resolved N-1/N-10/N-50/30-day/stable set (red proofs, bisecting)+ required: false+ type: string+ default: ''+ fault:+ description: Proof only. Corrupt canonical content after the upgrade in every cell; such a run is always red+ required: false+ type: choice+ options: [none, corrupt-after-upgrade]+ default: none+ schedule:+ - cron: '41 6 * * *'+ pull_request:+ paths:+ - 'src/schema.sql'+ - 'src/core/schema-migrations/**'+ - 'src/core/schema-embedded.generated.ts'+ - 'src/core/pglite-schema.generated.ts'+ - 'src/core/engine-sql/bootstrap.ts'+ - 'src/core/migrate.ts'+ - 'src/core/migration-ledger.ts'+ - 'src/core/migration-orchestration-lock.ts'+ - 'src/core/self-upgrade.ts'+ - 'src/core/stable-channel.ts'+ - 'src/core/bun-floor.ts'+ - 'src/core/binary-self-update.ts'+ - 'src/core/upgrade-restart.ts'+ - 'src/commands/upgrade.ts'+ - 'src/commands/upgrade-restart.ts'+ - 'src/commands/self-upgrade.ts'+ - 'src/commands/check-update.ts'+ - 'src/commands/apply-migrations.ts'+ - 'src/commands/apply-migrations-schema.ts'+ - 'src/commands/migrations/**'+ - 'scripts/postinstall.ts'+ - 'scripts/upgrade-matrix.ts'+ - 'scripts/upgrade-matrix/**'+ - '.github/workflows/upgrade-matrix.yml'++permissions: {}++concurrency:+ group: upgrade-matrix-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}++jobs:+ plan:+ name: plan (resolve candidate and from-versions)+ runs-on: ubicloud-standard-2-ubuntu-2404+ timeout-minutes: 10+ permissions:+ contents: read+ outputs:+ matrix: ${{ steps.plan.outputs.matrix }}+ candidate_sha: ${{ steps.plan.outputs.candidate_sha }}+ harness_sha: ${{ steps.harness.outputs.sha }}+ steps:+ - name: Refuse a gate run from any ref but master+ if: github.event_name != 'pull_request' && github.ref != 'refs/heads/master'+ env:+ REF: ${{ github.ref }}+ run: |+ echo "::error::The upgrade matrix gate runs only from master's workflow and harness (this run is on $REF). Dispatch it with --ref master and pass the candidate as the input."+ exit 1+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ with:+ ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}+ fetch-depth: 0+ persist-credentials: false+ - id: harness+ run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ with:+ bun-version: 1.4.4+ - name: Install dependencies (bounded, retried once)+ timeout-minutes: 8+ run: bun scripts/ci-bun-install.ts --frozen-lockfile --ignore-scripts+ - id: plan+ name: Resolve the candidate and from-versions (recorded once for every job)+ env:+ GITHUB_TOKEN: ${{ github.token }}+ EVENT: ${{ github.event_name }}+ PR_HEAD: ${{ github.event.pull_request.head.sha }}+ INPUT_CANDIDATE: ${{ inputs.candidate }}+ INPUT_FROM: ${{ inputs.from }}+ run: |+ set -euo pipefail+ # Named exception (docs/ci-event-parity.md): pull requests run the reduced+ # pr profile against their head; the nightly Upgrade matrix schedule runs+ # the full profile.+ case "$EVENT" in+ pull_request) candidate="$PR_HEAD"; profile=pr ;;+ workflow_dispatch) candidate="$INPUT_CANDIDATE"; profile=full ;;+ *) candidate=""; profile=full ;;+ esac+ args=(plan --candidate "$candidate" --profile "$profile" --out upgrade-matrix-plan.json)+ if [ -n "${INPUT_FROM:-}" ]; then args+=(--from "$INPUT_FROM"); fi+ bun scripts/upgrade-matrix.ts "${args[@]}"+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: upgrade-matrix-plan+ path: upgrade-matrix-plan.json+ retention-days: 30++ cell:+ name: cell (${{ matrix.from }} ${{ matrix.engine }} ${{ matrix.keys }} ${{ matrix.brain }})+ needs: plan+ runs-on: ubicloud-standard-4-ubuntu-2404+ timeout-minutes: 40+ permissions:+ contents: read+ strategy:+ fail-fast: false+ matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}+ services:+ postgres:+ # An empty image skips the container on PGLite cells.+ image: ${{ matrix.engine == 'postgres' && 'pgvector/pgvector:pg16' || '' }}+ env:+ POSTGRES_USER: postgres+ POSTGRES_PASSWORD: postgres+ POSTGRES_DB: postgres+ ports:+ - 5432:5432+ options: >-+ --shm-size=1g+ --health-cmd pg_isready+ --health-interval 5s+ --health-timeout 5s+ --health-retries 20+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ with:+ ref: ${{ needs.plan.outputs.harness_sha }}+ fetch-depth: 0+ persist-credentials: false+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ with:+ bun-version: 1.4.4+ - name: Install dependencies (bounded, retried once)+ timeout-minutes: 8+ run: bun scripts/ci-bun-install.ts --frozen-lockfile --ignore-scripts+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4+ with:+ name: upgrade-matrix-plan+ - name: Restore old-release archives and the Bun package cache+ uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4+ with:+ path: ~/.cache/upgrade-matrix+ key: upgrade-matrix-v1-${{ matrix.from }}-${{ needs.plan.outputs.candidate_sha }}+ restore-keys: |+ upgrade-matrix-v1-${{ matrix.from }}-+ upgrade-matrix-v1-+ - name: Run the cells+ env:+ FROM: ${{ matrix.from }}+ ENGINE: ${{ matrix.engine }}+ KEYS: ${{ matrix.keys }}+ BRAIN: ${{ matrix.brain }}+ FAULT: ${{ inputs.fault }}+ UPGRADE_MATRIX_POSTGRES_URL: ${{ matrix.engine == 'postgres' && 'postgresql://postgres:[email protected]:5432/postgres' || '' }}+ run: |+ set -euo pipefail+ args=(cell --plan upgrade-matrix-plan.json --from "$FROM" --engine "$ENGINE" --keys "$KEYS" --brain "$BRAIN" --cache-dir "$HOME/.cache/upgrade-matrix" --out-dir "$RUNNER_TEMP/upgrade-matrix")+ if [ -n "${FAULT:-}" ] && [ "$FAULT" != none ]; then args+=(--fault "$FAULT"); fi+ bun scripts/upgrade-matrix.ts "${args[@]}"+ - name: Upload receipts and cell logs+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: upgrade-matrix-cell-${{ matrix.from }}-${{ matrix.engine }}-${{ matrix.keys }}-${{ matrix.brain }}+ path: |+ ${{ runner.temp }}/upgrade-matrix/receipt-*.json+ ${{ runner.temp }}/upgrade-matrix/cells/*/snapshot-*.json+ ${{ runner.temp }}/upgrade-matrix/cells/*/service-calls.log+ ${{ runner.temp }}/upgrade-matrix/cells/*/logs/+ retention-days: 30+ if-no-files-found: warn++ summary:+ name: upgrade-matrix+ needs: [plan, cell]+ if: always() && needs.plan.result == 'success'+ runs-on: ubicloud-standard-2-ubuntu-2404+ timeout-minutes: 10+ permissions:+ contents: read+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ with:+ ref: ${{ needs.plan.outputs.harness_sha }}+ persist-credentials: false+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ with:+ bun-version: 1.4.4+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4+ with:+ name: upgrade-matrix-plan+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4+ with:+ pattern: upgrade-matrix-cell-*+ path: receipts+ - name: Summarize (red on any failing, missing or faulted cell)+ run: bun scripts/upgrade-matrix.ts summarize --plan upgrade-matrix-plan.json --receipts receipts --out upgrade-matrix-receipt.json+ - name: Upload the run receipt+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: upgrade-matrix-receipt+ path: upgrade-matrix-receipt.json+ retention-days: 90+ if-no-files-found: error++ issue:+ name: upgrade-break issue (nightly)+ needs: [plan, summary]+ # Named exception (docs/ci-event-parity.md): only the nightly Upgrade matrix+ # schedule writes the upgrade-break issue; dispatch and pull-request runs+ # report in their summary.+ if: always() && github.event_name == 'schedule' && needs.plan.result == 'success' && needs.summary.result != 'skipped' && needs.summary.result != 'cancelled'+ runs-on: ubicloud-standard-2-ubuntu-2404+ timeout-minutes: 5+ permissions:+ contents: read+ issues: write+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ with:+ ref: ${{ needs.plan.outputs.harness_sha }}+ persist-credentials: false+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ with:+ bun-version: 1.4.4+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4+ with:+ name: upgrade-matrix-receipt+ - name: Open, update or close the upgrade-break issue+ env:+ GITHUB_TOKEN: ${{ github.token }}+ run: bun scripts/upgrade-matrix.ts issue --summary upgrade-matrix-receipt.jsondiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9bdfa4a6c8..8ad9539542 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -32,6 +32,22 @@ Imports now make that text inert before it reaches the page. Every `gbrain:` mar- `POST /ingest` is unchanged: its caller is an authenticated writer with the same rights as `put_page`. Files the ingestion daemon picks up are unchanged too, because they're the owner's own.- New connectors should pass every outside field through `neutralizeOutsideText` in `src/core/outside-content.ts`.+## [Unreleased]++**Upgrades are now tested from real published releases every night.**++A new Upgrade matrix workflow installs older gbrain releases the way the README says (`bun install -g github:garrytan/gbrain`), builds a small brain on each, and upgrades it with that release's own `gbrain upgrade` to the newest release. It then checks that the installed files are the new release's, that a running `gbrain serve` comes back on the new build, that migrations finish at the schema head, that doctor is clean, that pages, facts and sources are unchanged, that new writes and searches work, and that the old binary can still read the upgraded brain. Each old release (one, ten and fifty releases back, about 30 days back, and stable when it exists) runs on PGLite and Postgres, with and without an embedding key (a local stand-in, nothing billed), on a brain with and without a Git repository.++The updater only ever sees the release under test: GitHub traffic goes to a local fixture and every other host except the npm registry is refused. A failing nightly run opens one `upgrade-break` issue and a later green run closes it. Pull requests that touch migrations, the schema or the updater run a smaller subset. Details: `docs/ci-upgrade-matrix.md`.++### What changed++| Situation | Before | Now |+|---|---|---|+| A migration fails on brains created by an older release | found by users after the release | the nightly matrix fails the schema-head and apply-migrations checks (it catches the v0.60.390.0 → v0.60.465.0 PGLite failure fixed in 0.60.466.0) |+| An upgrade rewrites page content | unnoticed | the preservation check lists every changed field; upgrading a v0.59.2.0 brain is tracked as a known exception (#7814) |+| `gh workflow run upgrade-matrix.yml -f candidate=<tag>` | — | runs the full matrix against that release and uploads a plan and receipt |+## [0.60.475.0] - 2026-10-27**A repository's own commit checks now apply to commits gbrain makes.**diff --git a/docs/architecture/key-files/ci-health-and-test-guards.md b/docs/architecture/key-files/ci-health-and-test-guards.mdindex 83b4e01261..bf3275080f 100644--- a/docs/architecture/key-files/ci-health-and-test-guards.md+++ b/docs/architecture/key-files/ci-health-and-test-guards.md@@ -4,6 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.- `.github/workflows/nightly-watch.yml` + `scripts/nightly-issue.ts` — nightly-red and master-red incidents. `workflow_run` fires only for master-branch completions; the `resolve` job admits scheduled runs and push-to-master runs of Test and E2E Tests from this repository (head repository checked) plus dispatch, and `nightly-issue.ts --resolve` turns every entry path into the target workflow id and track (`schedule`, `push`; a replay writes `push`); `watch` queues on one group per repository + workflow + track. `nightly-issue.ts --run-id <id> [--replay-issue <n>] [--dry-run]` routes the run (`routeRun`: pull-request, fork, other-branch and non-allowlisted push runs are refused with a next step). Scheduled runs keep one `Nightly red: <workflow>` issue (label `nightly-red`): open on red with job/step pairs, every failing test file with its reproduce line, sanitized error excerpts, the first red run, the last green SHA and compare link, a "Next step for the agent" and a JSON block; update while red; reopen on a flap; close only on a later green scheduled run with complete evidence where every previously failing job executed. Rows in `.github/nightly-known-red.tsv` (at most 3; race-hunt jobs refused) keep a matching incident open under `known-red`. A scheduled Test or E2E Tests run also feeds that workflow's open master-red issue. Push runs go to `scripts/lib/master-red.ts`. A ratchet test fails when a scheduled workflow is not watched. Tests: `test/scripts/nightly-issue.test.ts`. Process: `docs/RELEASING.md#nightly-red-issues`, `docs/ci-red-runbook.md`.+- `.github/workflows/upgrade-matrix.yml` + `scripts/upgrade-matrix.ts` (modules in `scripts/upgrade-matrix/`) — upgrade-from-N matrix (GBRA-224 W2). `plan` resolves the candidate and from-versions (N-1, N-10, N-50, 30 days, stable) from release tags; `cell` installs a from-version with `bun install -g github:garrytan/gbrain` in an isolated HOME, seeds a brain, runs that release's `gbrain upgrade` against `github-fixture.ts` (per-cell bare mirror via git `insteadOf`, loopback tarball API, TLS fixture behind `HTTPS_PROXY`; every other host refused), then checks install identity, one build across a running serve, apply-migrations, schema head, doctor, canonical preservation (`snapshot.ts`), writes, keyed vector query on the mock provider and the old binary on the upgraded brain; `summarize` judges red/hold/green (`verdict.ts`, `known-exceptions.json`, the `W4 SWITCH POINT` for `doctor --alert`); `issue` keeps one `upgrade-break` issue. Tests: `test/scripts/upgrade-matrix.test.ts`. Docs: `docs/ci-upgrade-matrix.md`.- `scripts/lib/gh-issue.ts` — the GitHub seam shared by the CI watchers. `inert()` makes run-derived text (job, step and test names, error text) safe to show an agent: control characters stripped, length capped, backticks and pipes replaced, mentions and links neutralized; `redactCredentials()` strips user:password from database URLs. `GitHubClient` is the one interface the watchers call (`restClient()` uses `GH_TOKEN`/`GITHUB_TOKEN` in Actions or the authenticated `gh api` locally; `download()` reads artifact archives without forwarding the token to blob storage). `findIssueByTitle` finds an issue by label and exact title, open first, else the most recently updated closed one; `listLabeled`, `getIssue` and `linkedPulls` (PRs cross-referencing an issue) back master-red and CI health; `fetchArtifactJson` + `readZipEntry` read one JSON file from a run artifact and return a reason instead of throwing.- `.github/workflows/ci-health.yml` + `scripts/ci-health-report.ts` — CI health report. Reads one window (`--days`, default 7, or `--since/--until`, also dispatch inputs) of same-repository pull-request and push-to-master runs of test.yml and e2e.yml (runs, jobs, check-run annotations, issues; never logs, fork runs or fork artifacts), paging the whole window (`listRuns` splits a query over the 1000-result search cap). It reports first-attempt pass rates (`firstAttempt()`), the exit criteria (master >= 95%, PR >= 90%; met, missed or indeterminate when the window cannot be read in full), stress-gate failures, failure classes, cancellation and completion coverage, master-red time to first response, the nightly-watch residual, the test files with the most failure annotations, shard spread and the count of fork runs it did not read; an explicit window with a missed target opens a follow-up issue. Tests: `test/scripts/ci-health-report.test.ts`. Docs: `docs/ci-red-runbook.md#ci-health-report`.- `scripts/lib/master-red.ts` — master-red reconciliation for push-to-master runs of Test and E2E Tests (`PUSH_ALLOWLIST`). Each watch evaluates every completed push run above the high-water mark (`evaluated`: run number, then attempt) stored in the newest `Master red: <workflow>` issue's `master-red:json` block (`applyRun` folds runs; cancelled runs change nothing); a missing or malformed block is rebuilt from the actions API (`pendingRuns`). It opens on red with the suspect range (`suspectRange`: compare plus commit-to-PR lookups), updates while red, closes when every previously failing job (E2E Tests: every failing file, from the manifest) ran and passed with complete evidence, records an incident that opened and closed between watches, and keeps a not-run-since failure open with the manual-close step. A newest issue closed by hand while its block is red ends that incident (`closed_by_hand`): later runs are recorded on it as green, and only a new red run opens a new issue. `externalPass` lets a scheduled run or an issue-bound E2E replay clear failures. Closing without a merged linked repair PR opens `flake` issues (`flakeFor`, `flake:json`); `closeFlakes` closes one after its repair PR merged and a later complete run passed its file and arm. Writes re-read the issue first and re-plan when it moved; a create race closes the newer duplicate. Tests: `test/scripts/nightly-issue.test.ts`. Docs: `docs/ci-red-runbook.md`.diff --git a/docs/ci-event-parity.md b/docs/ci-event-parity.mdindex 3c02c4abf7..fb135febc0 100644--- a/docs/ci-event-parity.md+++ b/docs/ci-event-parity.md@@ -42,6 +42,7 @@ checks ([below](#full-ci-on-pull-requests)), never per-cell matrix names.| `heavy-tests.yml` | `opencode-door-canary` | Named exception: schedule-only, non-gating canary | Itself || `macos-validation.yml` | Label-gated on pull requests | Named exception | Nightly macOS validation schedule || `scale-tier.yml` | Path- or label-gated 10k on pull requests | Named exception | Nightly Scale tier schedule (10k-50k) |+| `upgrade-matrix.yml` | Pull requests run N-1 and N-50, keyless repo-less cells only, against the head; the full matrix (N-1, N-10, N-50, 30 days, stable × both engines × keys × brain shapes) is schedule and dispatch only, and those refuse any ref but master ([docs](ci-upgrade-matrix.md)) | Named exception | Nightly Upgrade matrix schedule || `semgrep.yml` | PR diff scan vs full-tree scan | Named exception | Weekly Semgrep schedule || `osv-scanner.yml` | Pull requests scan only on a manifest change | Named exception | Weekly OSV schedule; `dependency-audit` on every PR || `nightly-watch.yml` | `workflow_run` event guard | Not a test scope: it files issues from qualifying scheduled and push-to-master runs | — |diff --git a/docs/ci-upgrade-matrix.md b/docs/ci-upgrade-matrix.mdnew file mode 100644index 0000000000..d71b166dca--- /dev/null+++ b/docs/ci-upgrade-matrix.md@@ -0,0 +1,196 @@+# Upgrade matrix++[.github/workflows/upgrade-matrix.yml](../.github/workflows/upgrade-matrix.yml)+installs published gbrain releases exactly as a user does, builds a small brain+on each, upgrades it through that release's own updater to one candidate, and+checks the candidate on the upgraded brain. The driver is+[scripts/upgrade-matrix.ts](../scripts/upgrade-matrix.ts) with its modules in+[scripts/upgrade-matrix/](../scripts/upgrade-matrix/).++It does not gate releases to the latest lane. Stable promotion reads its run+receipt (GBRA-224 W1).++## What a run tests++**From-versions.** Resolved once per run from published release tags (the+releases API, authenticated with the workflow token) and recorded in the plan:+N-1, N-10 and N-50 (the 1st, 10th and 50th newest release older than the+candidate), the release published closest to 30 days before the candidate, and+the current `stable` tag when it exists and is older. A role that cannot be+filled is recorded as skipped with its reason. Pull requests run N-1 and N-50+only.++**Cells.** Every from-version runs on PGLite and Postgres, keyless and keyed,+repo-less and repo brain (32 to 40 cells; one job per from-version, engine and+key mode runs both brain shapes). Pull requests run PGLite and Postgres,+keyless, repo-less only. Keyed cells set a Voyage key (gbrain's default+embedding provider) and the fixture forwards `api.voyageai.com` to the local+fake provider in `scripts/bench/retrieval-scale/mock-providers.ts`, so the+brain keeps the provider's real URL and nothing is billed. Repo cells run+`gbrain init --git`; repo-less cells keep the default content directory+without Git.++**Each cell**, in its own HOME, GBRAIN_HOME, BUN_INSTALL and global git config:++1. Installs the old release with the README command,+ `bun install -g github:garrytan/gbrain`, while the fixture's default branch+ and `latest-stable` point at that release, and checks `gbrain --version`.+2. Runs `gbrain init` for the cell's shape and seeds pages, a page with a facts+ fence, a remembered fact, a soft-deleted page, embeddings (keyed) and one+ `gbrain dream` pass (recorded, not judged: the old release ran it). It+ snapshots the canonical content and keeps a copy of the old install.+3. Starts `gbrain serve` as an agent harness does (stdio, stdin held open) and+ checks it answers MCP as the old version; on Postgres it also starts+ `gbrain jobs supervisor start --detach`.+4. Moves every fixture ref to the candidate and runs `gbrain upgrade` (the old+ release's code). When it refuses with `restart_refused` for the MCP server+ it reruns with `--stop-mcp`, the documented fix.+5. Checks the install is the candidate: `gbrain --version`, the commit Bun+ pinned in its lockfile, and every installed file against the candidate's+ git tree. The fixture log must show the candidate tarball and no other+ commit after the switch.+6. One build: an old serve still running is restarted with the candidate's+ `gbrain upgrade --restart-only --stop-mcp` (old releases have no restart+ step); the restarted serve must report the candidate version over MCP and+ find a seeded page through the `search` tool. On Postgres doctor's+ `runtime_build_skew` must be ok with serve and the supervisor running. No+ process for the brain may remain once both are stopped.+7. `gbrain apply-migrations --yes --non-interactive` exits 0, doctor's+ `schema_version` is at the candidate's head, and doctor reports no failing+ check outside the skill category (see the W4 switch point below).+8. Preservation: the canonical content snapshot equals the one taken before+ the upgrade (below).+9. A new page is written and found by keyword search; keyed cells embed it,+ and `gbrain query` must embed the question and return the matching seed+ page; one `gbrain dream` pass exits 0.+10. Mixed versions: the old install runs `--version`, `search`,+ `doctor --json` and `serve` (MCP initialize and one search) on the+ upgraded brain; the schema catalog and canonical content must not change.++Services the upgrade tries to install go to stub `crontab`, `systemctl`,+`launchctl` and `loginctl` on the cell's PATH; the receipt lists the calls+(`service_calls`) and nothing reaches the runner.++**Preservation snapshot.** Per page: source id, slug, type, kind, title,+content hash, frontmatter, provenance columns (`source_kind`, `source_uri`,+`ingested_via`, `source_path`) and deletion state. Per fact: entity, claim,+row number, kind, visibility, notability, context, source, confidence, valid+dates, typed-claim columns, and expired or superseded state. Per source: id,+name and archive state. Timestamps, ids, vectors, chunks and bookkeeping are+left out, so a migration that adds columns or re-chunks pages compares equal; a+canonical column the upgrade drops is a difference. The catalog snapshot adds+columns, indexes, constraints, triggers, function bodies, views and the+schema version. A PGLite brain is read with the PGLite build of the release+installed at that moment, never the harness's own.++## How the updater is interposed++The old release's updater must only ever see the candidate:++- **git**: `url.<per-cell bare mirror>.insteadOf https://github.com/garrytan/gbrain`+ in the cell's global git config. The mirror borrows the harness checkout's+ objects and holds only the fixture refs (`master`, `latest-stable`,+ `stable`, the old tag and `v<candidate version>`), so `git ls-remote`+ lists the candidate as the newest release.+- **Bun's tarball fetch**: `GITHUB_API_URL` points at the fixture's loopback+ server, which answers `/repos/garrytan/gbrain/tarball/<ref>` with+ `git archive` of the ref's commit.+- **Every other HTTPS request** (raw.githubusercontent.com for VERSION and the+ Bun-floor package.json, api.github.com, codeload, github.com): an+ `HTTPS_PROXY` sends the GitHub hosts to a local TLS server whose certificate a+ per-run CA signs (`NODE_EXTRA_CA_CERTS`), tunnels only `registry.npmjs.org`+ to the internet for dependencies, and refuses every other host. Refused hosts+ are listed in the receipt (`interposition.denied`).++Every from-version installs and upgrades through these paths today, so no+from-version is listed as un-interposable. The binary updater+(`gbrain self-upgrade` on a compiled binary) is not exercised: the matrix+installs through Bun as the README says.++## Verdicts++A cell is `pass`, `fail` (a candidate check failed), `error` (the old+release could not be installed, initialized or seeded in that shape, so there+is no candidate verdict) or `known_exception` (every failure matches an entry+below). A run is **red** when any cell fails, a planned cell left no receipt, a+fault was injected, or a receipt names another candidate or harness; **hold**+when it is otherwise clean but a cell errored or a door could not run;+**green** when every planned cell passed. A hold never qualifies a candidate+and never opens an issue.++<a id="known-exceptions"></a>+**Known exceptions** live in+[scripts/upgrade-matrix/known-exceptions.json](../scripts/upgrade-matrix/known-exceptions.json):+each names one check, an explicit list of old release tags (no wildcards) and+the issue that tracks it. Setup errors cannot be excepted. Old releases that+mutate the brain when started again after the upgrade belong here, linked to+#7776 or a narrower issue; the candidate's own `client_behind` refusal is+tested in the unit suite, since a frozen old binary cannot carry it.++**W4 switch point.** Until `gbrain doctor --alert` ships, the doctor check is+the legacy report (`DOCTOR_ARGV` and `doctorVerdict` in+`scripts/upgrade-matrix/verdict.ts`); a report that carries `alert.level` is+judged by it. When W4 lands, change `DOCTOR_ARGV` there and drop the legacy+branch.++## Runs and receipts++- **Nightly** (06:41 UTC): full matrix against the newest release. A red run+ opens or updates one issue carrying the `upgrade-break` label (found by the+ marker `<!-- gbrain-upgrade-matrix:nightly -->`) and a later green run+ comments and closes it. Nightly watch also tracks the workflow like every+ scheduled run.+- **Dispatch**: `gh workflow run upgrade-matrix.yml --ref master -f candidate=v0.60.475.0`+ (empty candidate: the newest release; `-f from=v0.60.390.0,v0.60.425.0`+ replaces the resolved from-versions; `-f fault=corrupt-after-upgrade` is the+ proof that preservation catches a corrupted upgrade, and is always red).+- **Pull requests** touching schema, migrations, self-upgrade, `upgrade.ts`,+ `apply-migrations` or the harness: the reduced subset against the head.++The gate runs from master's workflow and harness: dispatch and schedule runs+refuse any other ref, and the candidate is only installed as the subject. The+`upgrade-matrix-plan` artifact records the harness commit, the workflow ref,+the candidate tag, commit and tree, and the from-versions with their roles; the+`upgrade-matrix-receipt` artifact adds every cell's verdict and failures. Cell+artifacts keep each cell's receipt, logs and snapshots. A pull-request run's+harness is its own head and is not gate evidence.++Run a cell locally (Postgres cells need a superuser URL, for example the+`docs/TESTING.md` test container):++```bash+bun scripts/upgrade-matrix.ts plan --candidate v0.60.475.0 --out plan.json+bun scripts/upgrade-matrix.ts cell --plan plan.json --from v0.60.474.0 --engine pglite --keys keyless --brain both --out-dir out+UPGRADE_MATRIX_POSTGRES_URL=postgresql://postgres:postgres@localhost:5434/postgres \+ bun scripts/upgrade-matrix.ts cell --plan plan.json --from v0.60.474.0 --engine postgres --keys keyed --out-dir out+bun scripts/upgrade-matrix.ts summarize --plan plan.json --receipts out --out summary.json+```++## Coverage++Against the upgrade-breakage classes in the GBRA-224 plan:++| Class | Covered |+| --- | --- |+| A: schema bring-up from an old version | Yes: every from-version, both engines, through apply-migrations and the schema head check |+| D: the updater targets an unpublished or wrong version | Yes: the old updater runs against the fixture; the installed tree must be the candidate's |+| H: false-healthy signals | Yes: doctor after the upgrade, and the serve answering on the candidate build |+| I: packaged skill and host migrations | Yes: `apply-migrations` runs every orchestrator on a brain the old release created |+| J: embedding backfill holds created by an upgrade | Yes on keyed cells: embedding a new page and vector query after the upgrade |+| C: mixed versions, stale resident processes | Partly: a stdio serve and (Postgres) a supervisor across the upgrade, one build afterwards, and the old binary on the upgraded brain; not long-lived multi-host fleets |+| E: runtime floor, postinstall, Bun | Partly: the real Bun-floor read and global install on the runner's Bun; not older Bun versions |+| G: migration orchestrator chain on managed brains | Partly: the chain on fresh small brains; not managed multi-writer brains |++Not covered: scale (classes B and F stay with the production soak and the+scale tier), multi-host timing, launchd and systemd restart behaviour (service+calls go to stubs), custom database roles, the compiled-binary updater, and+older Bun versions.++## Cost++A cell takes 40 to 70 seconds on a 4-vCPU runner (install from the Bun cache,+seed, upgrade, checks, mixed-version probe); a job adds about two minutes of+checkout, `bun install` and cache restore. A full run is 20 cell jobs of about+four minutes on `ubicloud-standard-4` plus the plan, summary and issue jobs on+`ubicloud-standard-2`: about 330 vCPU-minutes. The pull-request subset is+4 jobs, about 50 vCPU-minutes.diff --git a/scripts/upgrade-matrix.ts b/scripts/upgrade-matrix.tsnew file mode 100644index 0000000000..89c31a8a1c--- /dev/null+++ b/scripts/upgrade-matrix.ts@@ -0,0 +1,255 @@+#!/usr/bin/env bun+/**+ * Upgrade matrix (GBRA-224 W2): install published old releases, upgrade each+ * through its own updater to one candidate, and check the candidate on the+ * upgraded brain. Workflow: .github/workflows/upgrade-matrix.yml. Docs:+ * docs/ci-upgrade-matrix.md.+ *+ * bun scripts/upgrade-matrix.ts plan --candidate <vX.Y.Z.W | sha | ''> [--profile full|pr] [--from v1,v2] --out plan.json+ * bun scripts/upgrade-matrix.ts cell --plan plan.json --from <tag> --engine pglite|postgres --keys keyless|keyed+ * [--brain repo-less|repo|both] [--postgres-url <superuser url>] [--fault corrupt-after-upgrade] --out-dir <dir>+ * bun scripts/upgrade-matrix.ts summarize --plan plan.json --receipts <dir> --out summary.json+ * bun scripts/upgrade-matrix.ts issue --summary summary.json [--dry-run]+ *+ * The plan resolves the candidate (tag, commit, tree) and the from-versions+ * once and records them with the harness commit; cells and the summary read+ * only the plan, so every job of a run agrees on what it tested.+ */+import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';+import { execFileSync, spawnSync } from 'node:child_process';+import { join, resolve } from 'node:path';+import { fetchReleases, hasEnoughHistory, RELEASE_TAG, resolveFromVersions, type Candidate, type FromVersion, type Profile, type Release } from './upgrade-matrix/versions.ts';+import { cellId, runCell, type BrainShape, type Engine, type Fault, type Keys } from './upgrade-matrix/cell.ts';+import { CHECKS, loadKnownExceptions, summarize, type CellSummary } from './upgrade-matrix/verdict.ts';++const REPO = 'garrytan/gbrain';+const ROOT = resolve(import.meta.dir, '..');+const BT = '\x60';+export const ISSUE_MARKER = '<!-- gbrain-upgrade-matrix:nightly -->';+export const ISSUE_LABEL = 'upgrade-break';++const argv = process.argv.slice(2);+const flag = (name: string, fallback?: string) => { const i = argv.indexOf(name); return i >= 0 && i + 1 < argv.length ? argv[i + 1]! : fallback; };+const git = (...args: string[]) => execFileSync('git', ['-C', ROOT, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();++function ensureCommit(ref: string): string {+ const has = spawnSync('git', ['-C', ROOT, 'rev-parse', '--verify', '--quiet', ref + '^{commit}'], { encoding: 'utf8' });+ if (has.status === 0) return has.stdout.trim();+ const fetch = RELEASE_TAG.test(ref) || ref === 'stable'+ ? ['fetch', '--quiet', '--no-tags', 'origin', '+refs/tags/' + ref + ':refs/tags/' + ref]+ : ['fetch', '--quiet', '--no-tags', 'origin', ref];+ execFileSync('git', ['-C', ROOT, ...fetch], { stdio: ['ignore', 'pipe', 'pipe'] });+ return git('rev-parse', ref + '^{commit}');+}++const commitVersion = (sha: string) => git('show', sha + ':VERSION').split('\n')[0]!.trim();+const commitTime = (sha: string) => new Date(Number(git('log', '-1', '--format=%ct', sha)) * 1000).toISOString();++export interface Plan {+ schema: 'gbrain-upgrade-matrix-plan/1';+ harness: { sha: string; dirty: boolean; workflow_ref: string | null; workflow_sha: string | null; event: string | null; run_url: string | null };+ candidate: Candidate;+ profile: Profile | 'explicit';+ from: Array<FromVersion & { sha: string }>;+ skipped: Array<{ role: string; reason: string }>;+ jobs: Array<{ from: string; engine: Engine; keys: Keys; brain: BrainShape | 'both' }>;+ cells: string[];+}++async function plan(): Promise<void> {+ const profile = flag('--profile', 'full') as Profile;+ if (profile !== 'full' && profile !== 'pr') throw new Error('--profile takes full or pr');+ const input = (flag('--candidate', '') ?? '').trim();+ const releases = await fetchReleases(REPO, rs => {+ const newest = rs[0];+ return !!newest && hasEnoughHistory(rs, candidateHint(rs, input) ?? newest);+ });+ if (!releases.length) throw new Error('no published releases found');+ let candidate: Candidate;+ if (!input || RELEASE_TAG.test(input)) {+ const rel = input ? releases.find(r => r.tag === input) : [...releases].sort((a, b) => Date.parse(b.published_at) - Date.parse(a.published_at))[0];+ if (!rel) throw new Error('candidate ' + input + ' is not a published release');+ const sha = ensureCommit(rel.tag);+ candidate = { tag: rel.tag, sha, tree: git('rev-parse', sha + '^{tree}'), version: rel.version, published_at: rel.published_at };+ } else {+ const sha = ensureCommit(input);+ candidate = { tag: null, sha, tree: git('rev-parse', sha + '^{tree}'), version: commitVersion(sha), published_at: commitTime(sha) };+ }+ const explicit = flag('--from');+ let from: FromVersion[];+ let skipped: Plan['skipped'] = [];+ if (explicit) {+ from = explicit.split(',').map(t => t.trim()).filter(Boolean).map(tag => {+ const m = RELEASE_TAG.exec(tag);+ if (!m) throw new Error('--from takes release tags: ' + tag);+ return { tag, version: m[1]!, published_at: releases.find(r => r.tag === tag)?.published_at ?? '', roles: ['explicit' as never] };+ });+ } else {+ const resolved = resolveFromVersions(releases, candidate, { profile, stableVersion: stableVersion() });+ from = resolved.from;+ skipped = resolved.skipped;+ }+ const withSha = from.map(f => ({ ...f, sha: ensureCommit(f.tag) }));+ const reduced = profile === 'pr' && !explicit;+ const keys: Keys[] = reduced ? ['keyless'] : ['keyless', 'keyed'];+ const brain: BrainShape | 'both' = reduced ? 'repo-less' : 'both';+ const jobs = withSha.flatMap(f => (['pglite', 'postgres'] as Engine[]).flatMap(engine => keys.map(k => ({ from: f.tag, engine, keys: k, brain }))));+ const cells = jobs.flatMap(j => (j.brain === 'both' ? ['repo-less', 'repo'] : [j.brain]).map(b => cellId({ from: { tag: j.from }, engine: j.engine, keys: j.keys, brain: b })));+ const out: Plan = {+ schema: 'gbrain-upgrade-matrix-plan/1',+ harness: {+ sha: git('rev-parse', 'HEAD'), dirty: git('status', '--porcelain', '--untracked-files=no').length > 0,+ workflow_ref: process.env.GITHUB_WORKFLOW_REF ?? null, workflow_sha: process.env.GITHUB_WORKFLOW_SHA ?? null, event: process.env.GITHUB_EVENT_NAME ?? null,+ run_url: process.env.GITHUB_RUN_ID ? (process.env.GITHUB_SERVER_URL ?? 'https://github.com') + '/' + (process.env.GITHUB_REPOSITORY ?? REPO) + '/actions/runs/' + process.env.GITHUB_RUN_ID : null,+ },+ candidate, profile: explicit ? 'explicit' : profile, from: withSha, skipped, jobs, cells,+ };+ writeFileSync(flag('--out', 'upgrade-matrix-plan.json')!, JSON.stringify(out, null, 2) + '\n');+ if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, 'matrix=' + JSON.stringify({ include: jobs }) + '\ncandidate_sha=' + candidate.sha + '\n');+ console.log('candidate ' + (candidate.tag ?? '(commit)') + ' ' + candidate.sha.slice(0, 12) + ' v' + candidate.version + '; from ' + withSha.map(f => f.tag + ' [' + f.roles.join(',') + ']').join(', ')+ + (skipped.length ? '; skipped ' + skipped.map(s => s.role + ': ' + s.reason).join('; ') : '') + '; ' + cells.length + ' cells in ' + jobs.length + ' jobs');+}++/** The stable tag's release version, or null when the tag does not exist or cannot be read. */+function stableVersion(): string | null {+ const ls = spawnSync('git', ['-C', ROOT, 'ls-remote', '--tags', 'origin', 'refs/tags/stable'], { encoding: 'utf8' });+ if (ls.status !== 0 || !ls.stdout.trim()) return null;+ try { return commitVersion(ensureCommit('stable')); } catch { return null; }+}++function candidateHint(releases: Release[], input: string): { version: string; published_at: string } | null {+ if (!input) return null;+ const rel = releases.find(r => r.tag === input);+ if (rel) return rel;+ try { const sha = ensureCommit(input); return { version: commitVersion(sha), published_at: commitTime(sha) }; } catch { return null; }+}++async function cell(): Promise<void> {+ const p = JSON.parse(readFileSync(flag('--plan', 'upgrade-matrix-plan.json')!, 'utf8')) as Plan;+ const tag = flag('--from');+ const from = p.from.find(f => f.tag === tag);+ if (!from) throw new Error('--from ' + tag + ' is not in the plan (' + p.from.map(f => f.tag).join(', ') + ')');+ const engine = flag('--engine') as Engine, keys = flag('--keys') as Keys, brainFlag = flag('--brain', 'both')!;+ if (!['pglite', 'postgres'].includes(engine) || !['keyless', 'keyed'].includes(keys)) throw new Error('--engine pglite|postgres and --keys keyless|keyed are required');+ const brains: BrainShape[] = brainFlag === 'both' ? ['repo-less', 'repo'] : [brainFlag as BrainShape];+ const outDir = resolve(flag('--out-dir', 'upgrade-matrix-out')!);+ mkdirSync(outDir, { recursive: true });+ ensureCommit(from.sha);+ ensureCommit(p.candidate.sha);+ const exceptions = loadKnownExceptions();+ let red = false;+ for (const brain of brains) {+ const receipt = await runCell({+ from: { tag: from.tag, version: from.version, sha: from.sha, roles: from.roles }, candidate: p.candidate, engine, keys, brain,+ harnessRoot: ROOT, harnessSha: git('rev-parse', 'HEAD'), workDir: join(outDir, 'cells'), cacheDir: resolve(flag('--cache-dir', join(outDir, 'cache'))!),+ postgresUrl: flag('--postgres-url') ?? process.env.UPGRADE_MATRIX_POSTGRES_URL, fault: (flag('--fault') as Fault | undefined) ?? null, exceptions,+ });+ writeFileSync(join(outDir, 'receipt-' + receipt.id + '.json'), JSON.stringify(receipt, null, 2) + '\n');+ const failures = receipt.failures as Array<{ check: string; detail: string }>;+ console.log(String(receipt.verdict).toUpperCase() + ' ' + receipt.id + ' (' + receipt.elapsed_s + ' s)' + failures.map(f => '\n - ' + f.check + ': ' + f.detail.split('\n')[0]).join(''));+ if (receipt.verdict !== 'pass' && receipt.verdict !== 'known_exception') red = true;+ }+ if (red) process.exitCode = 1;+}++function loadReceipts(dir: string): any[] {+ const out: any[] = [];+ const walk = (d: string) => {+ for (const e of readdirSync(d, { withFileTypes: true })) {+ const p = join(d, e.name);+ if (e.isDirectory()) walk(p);+ else if (/^(receipt|door)-.*\.json$/.test(e.name)) out.push(JSON.parse(readFileSync(p, 'utf8')));+ }+ };+ if (existsSync(dir)) walk(dir);+ return out;+}++export function buildSummary(p: Plan, receipts: any[]): any {+ const doors = receipts.filter(r => r.schema === 'gbrain-upgrade-matrix-door/1');+ const cellReceipts = receipts.filter(r => r.schema === 'gbrain-upgrade-matrix-cell/1');+ const foreign = [...cellReceipts, ...doors].filter(r => r.candidate?.sha !== p.candidate.sha || r.harness_sha !== p.harness.sha);+ const cells: CellSummary[] = cellReceipts.filter(r => !foreign.includes(r)).map(r => ({+ id: r.id, from: r.from.tag, roles: r.from.roles, shape: [r.shape.engine, r.shape.keys, r.shape.brain].join(' '), verdict: r.verdict,+ open: r.failures ?? [], excepted: (r.known_exceptions ?? []).map((e: any) => ({ check: e.check, issue: e.issue })), fault: r.fault,+ }));+ const s = summarize(p.cells, cells);+ const doorRed = doors.filter(d => !foreign.includes(d) && d.verdict === 'fail');+ const doorHold = doors.filter(d => !foreign.includes(d) && d.verdict === 'hold');+ return {+ schema: 'gbrain-upgrade-matrix-run/1', harness: p.harness, candidate: p.candidate, profile: p.profile, from: p.from, skipped: p.skipped,+ status: s.red.length || foreign.length || doorRed.length ? 'red' : s.holds.length || doorHold.length ? 'hold' : 'green',+ cells, red: [...s.red.map(c => c.id), ...doorRed.map(d => 'door:' + d.door)], holds: [...s.holds.map(c => c.id), ...doorHold.map(d => 'door:' + d.door)], foreign_receipts: foreign.map(r => r.id ?? r.door),+ doors: doors.map(d => ({ door: d.door, verdict: d.verdict, reason: d.reason ?? null })),+ };+}++function summarizeRun(): void {+ const p = JSON.parse(readFileSync(flag('--plan', 'upgrade-matrix-plan.json')!, 'utf8')) as Plan;+ const summary = buildSummary(p, loadReceipts(flag('--receipts', 'receipts')!));+ writeFileSync(flag('--out', 'upgrade-matrix-summary.json')!, JSON.stringify(summary, null, 2) + '\n');+ const md = renderSummary(summary);+ console.log(md);+ if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, md + '\n');+ if (summary.status === 'red') process.exitCode = 1;+}++export function renderSummary(s: any): string {+ const cellRow = (c: any) => '| ' + c.from + ' ' + c.shape + ' | ' + c.verdict + (c.fault ? ' (fault ' + c.fault + ')' : '') + ' | '+ + [...c.open.map((f: any) => f.check + ': ' + String(f.detail).split('\n')[0]!.replace(/\|/g, '/').slice(0, 160)), ...c.excepted.map((e: any) => e.check + ' (known: ' + e.issue + ')')].join('<br>') + ' |';+ const lines = [+ '## Upgrade matrix: ' + String(s.status).toUpperCase(),+ '',+ 'Candidate ' + (s.candidate.tag ?? '(unreleased commit)') + ' ' + BT + s.candidate.sha + BT + ' (v' + s.candidate.version + ', tree ' + BT + s.candidate.tree.slice(0, 12) + BT + '); harness ' + BT + s.harness.sha.slice(0, 12) + BT + ' (' + (s.harness.workflow_ref ?? 'local') + ').',+ 'From: ' + s.from.map((f: any) => f.tag + ' (' + f.roles.join(', ') + ')').join(', ') + (s.skipped.length ? '. Skipped: ' + s.skipped.map((k: any) => k.role + ' (' + k.reason + ')').join('; ') : '') + '.',+ '',+ '| Cell | Verdict | Failures |',+ '| --- | --- | --- |',+ ...s.cells.map(cellRow),+ ];+ const missing = s.red.filter((id: string) => !id.startsWith('door:') && !s.cells.some((c: any) => c.id === id));+ if (missing.length) lines.push('', 'No receipt: ' + missing.join(', '));+ if (s.foreign_receipts.length) lines.push('', 'Receipts from another candidate or harness (ignored; the run is red): ' + s.foreign_receipts.join(', '));+ for (const d of s.doors ?? []) lines.push('', 'Door ' + d.door + ': ' + String(d.verdict).toUpperCase() + (d.reason ? ' (' + d.reason + ')' : ''));+ lines.push('', 'Checks: ' + Object.keys(CHECKS).map(k => BT + k + BT).join(', ') + '. Docs: docs/ci-upgrade-matrix.md');+ return lines.join('\n');+}++async function issue(): Promise<void> {+ const s = JSON.parse(readFileSync(flag('--summary', 'upgrade-matrix-summary.json')!, 'utf8'));+ const dry = argv.includes('--dry-run');+ const auth = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;+ const api = async (method: string, path: string, body?: unknown) => {+ const res = await fetch('https://api.github.com/repos/' + (process.env.GITHUB_REPOSITORY ?? REPO) + path, {+ method, headers: { accept: 'application/vnd.github+json', 'user-agent': 'gbrain-upgrade-matrix', ...(auth ? { authorization: 'Bearer ' + auth } : {}) }, body: body ? JSON.stringify(body) : undefined,+ });+ if (!res.ok) throw new Error(method + ' ' + path + ' returned HTTP ' + res.status + ': ' + (await res.text()).slice(0, 300));+ return res.status === 204 ? null : res.json();+ };+ const existing = (await api('GET', '/issues?state=all&labels=' + ISSUE_LABEL + '&per_page=100') as any[]).find(i => !i.pull_request && String(i.body ?? '').includes(ISSUE_MARKER));+ const body = ISSUE_MARKER + '\n' + renderSummary(s) + '\n\nRun: ' + (s.harness.run_url ?? '(local)') + '\n\nThis issue carries the ' + BT + ISSUE_LABEL + BT + ' label, which holds stable promotion while it is open. The nightly matrix closes it when a later run is green.';+ if (s.status === 'red') {+ const title = 'Upgrade matrix red: upgrading to ' + (s.candidate.tag ?? s.candidate.sha.slice(0, 12)) + ' fails ' + s.red.length + ' cell(s)';+ if (dry) { console.log((existing ? 'update #' + existing.number : 'create') + ': ' + title + '\n' + body); return; }+ if (existing) {+ await api('PATCH', '/issues/' + existing.number, { title, body, state: 'open' });+ await api('POST', '/issues/' + existing.number + '/comments', { body: 'Still red on ' + (s.candidate.tag ?? s.candidate.sha) + ': ' + s.red.join(', ') + '. ' + (s.harness.run_url ?? '') });+ console.log('updated #' + existing.number);+ } else {+ const created = await api('POST', '/issues', { title, body, labels: [ISSUE_LABEL] }) as any;+ console.log('created #' + created.number);+ }+ } else if (s.status === 'green' && existing?.state === 'open') {+ if (dry) { console.log('close #' + existing.number); return; }+ await api('POST', '/issues/' + existing.number + '/comments', { body: 'Green on ' + (s.candidate.tag ?? s.candidate.sha) + ': every planned cell passed. ' + (s.harness.run_url ?? '') });+ await api('PATCH', '/issues/' + existing.number, { state: 'closed', state_reason: 'completed' });+ console.log('closed #' + existing.number);+ } else console.log('no issue change (status ' + s.status + (existing ? ', issue #' + existing.number + ' ' + existing.state : '') + ')');+}++if (import.meta.main) {+ const cmd = argv[0];+ const run = cmd === 'plan' ? plan : cmd === 'cell' ? cell : cmd === 'summarize' ? async () => summarizeRun() : cmd === 'issue' ? issue : null;+ if (!run) { console.error('usage: bun scripts/upgrade-matrix.ts plan|cell|summarize|issue (see the header)'); process.exit(2); }+ await run();+}diff --git a/scripts/upgrade-matrix/cell.ts b/scripts/upgrade-matrix/cell.tsnew file mode 100644index 0000000000..e8a01c765e--- /dev/null+++ b/scripts/upgrade-matrix/cell.ts@@ -0,0 +1,395 @@+/**+ * Upgrade matrix (GBRA-224 W2): one cell. Install a published old release the+ * way the README tells a user to, build a small brain on it, run serve (and a+ * jobs supervisor on Postgres), upgrade through the old release's own updater+ * while the GitHub fixture shows only the candidate, then check the candidate+ * on that brain. docs/ci-upgrade-matrix.md lists every step and what it+ * guards.+ */+import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import { createHash } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { dirname, join } from 'node:path';+import { startGithubFixture, type FixtureHandle } from './github-fixture.ts';+import { StdioMcp } from './mcp-probe.ts';+import { diffCatalog, diffContent, type Difference, type Snapshot } from './snapshot.ts';+import { DOCTOR_ARGV, doctorVerdict, judgeCell, type Check, type Failure, type KnownException } from './verdict.ts';+import type { Candidate } from './versions.ts';+import { startMockProviders, type MockServer } from '../bench/retrieval-scale/mock-providers.ts';+import postgres from '#postgres';++export type Engine = 'pglite' | 'postgres';+export type Keys = 'keyless' | 'keyed';+export type BrainShape = 'repo-less' | 'repo';+export type Fault = 'corrupt-after-upgrade';++export interface CellSpec {+ from: { tag: string; version: string; sha: string; roles: string[] };+ candidate: Candidate;+ engine: Engine;+ keys: Keys;+ brain: BrainShape;+ harnessRoot: string;+ harnessSha: string;+ workDir: string;+ cacheDir: string;+ /** Superuser URL of the Postgres server for Postgres cells; each cell creates its own database. */+ postgresUrl?: string;+ fault?: Fault | null;+ exceptions: KnownException[];+}++export interface Step { name: string; ok: boolean; ms: number; exit?: number | null; detail?: string; log?: string }++export const cellId = (s: { from: { tag: string }; engine: string; keys: string; brain: string }) => [s.from.tag, s.engine, s.keys, s.brain].join('__');++const SEED_WORD = 'zephyrquartz';+const NEW_WORD = 'obsidianlantern';+const SEED_PAGES: Array<{ slug: string; body: string }> = [+ { slug: 'concepts/upgrade-matrix-alpha', body: '# Upgrade matrix alpha\n\nThe alpha page mentions ' + SEED_WORD + ' and links to [[concepts/upgrade-matrix-beta]].\n' },+ { slug: 'concepts/upgrade-matrix-beta', body: '# Upgrade matrix beta\n\nThe beta page is about lighthouse maintenance schedules and tidal charts.\n' },+ { slug: 'people/alice-example', body: '# Alice Example\n\nAlice Example works at acme-example on storage engines.\n\n<!--- gbrain:facts:begin -->\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|\n| 1 | Prefers written design reviews | preference | 0.9 | world | medium | 2026-01-05 | | upgrade-matrix seed | |\n| 2 | Leads the storage team at acme-example | fact | 1.0 | world | high | 2025-11-01 | | upgrade-matrix seed | |\n<!--- gbrain:facts:end -->\n' },+];+const DELETED_SLUG = 'notes/upgrade-matrix-deleted';++function stubBin(dir: string, log: string): void {+ mkdirSync(dir, { recursive: true });+ const write = (name: string, body: string) => { writeFileSync(join(dir, name), '#!/bin/sh\necho "' + name + ' $*" >> "' + log + '"\n' + body + '\n', { mode: 0o755 }); };+ write('crontab', 'case "$1" in -l) echo "no crontab for matrix" >&2; exit 1;; esac\ncat > /dev/null\nexit 0');+ write('systemctl', 'echo "Failed to connect to bus: No medium found" >&2\nexit 1');+ write('launchctl', 'exit 1');+ write('loginctl', 'exit 1');+}++export async function runCell(spec: CellSpec): Promise<Record<string, unknown>> {+ const id = cellId(spec);+ const dir = join(spec.workDir, id);+ rmSync(dir, { recursive: true, force: true });+ const home = join(dir, 'home'), bunDir = join(dir, 'bun'), logs = join(dir, 'logs'), tmp = join(dir, 'tmp');+ for (const d of [home, bunDir, logs, tmp]) mkdirSync(d, { recursive: true });+ const serviceLog = join(dir, 'service-calls.log');+ stubBin(join(dir, 'stub-bin'), serviceLog);++ const steps: Step[] = [];+ const failures: Failure[] = [];+ const fail = (check: Check, detail: string) => { failures.push({ check, detail: detail.slice(0, 2000) }); };+ const started = Date.now();+ const receipt: Record<string, unknown> = {+ schema: 'gbrain-upgrade-matrix-cell/1', id, harness_sha: spec.harnessSha,+ candidate: spec.candidate, from: spec.from, shape: { engine: spec.engine, keys: spec.keys, brain: spec.brain }, fault: spec.fault ?? null,+ };++ const mock: MockServer | null = spec.keys === 'keyed' ? startMockProviders({ manifest: { seed: 224, chunks: 64, pages: 16, dims: 1024 } }) : null;+ const fx: FixtureHandle = await startGithubFixture({+ source: spec.harnessRoot, mirrorDir: join(dir, 'mirror.git'), archiveDir: join(spec.cacheDir, 'archives'), certDir: join(spec.cacheDir, 'certs'),+ forward: mock ? { 'api.voyageai.com': mock.url } : {},+ });+ writeFileSync(join(dir, 'gitconfig'), '[url "' + fx.mirror + '"]\n\tinsteadOf = https://github.com/garrytan/gbrain\n[user]\n\tname = upgrade-matrix\n\temail = [email protected]\n[init]\n\tdefaultBranch = main\n');++ let databaseUrl: string | undefined;+ const dbName = 'um_' + createHash('sha1').update(id + process.pid + started).digest('hex').slice(0, 16);+ const env: Record<string, string> = {+ PATH: [join(dir, 'stub-bin'), join(bunDir, 'bin'), dirname(process.execPath), '/usr/local/bin', '/usr/bin', '/bin'].join(':'),+ HOME: home, GBRAIN_HOME: home, BUN_INSTALL: bunDir, BUN_INSTALL_CACHE_DIR: join(spec.cacheDir, 'bun-install-cache'), TMPDIR: tmp,+ LANG: 'C.UTF-8', NO_COLOR: '1', TERM: 'dumb', USER: process.env.USER ?? 'runner',+ GIT_CONFIG_GLOBAL: join(dir, 'gitconfig'), GIT_CONFIG_NOSYSTEM: '1',+ HTTPS_PROXY: fx.proxyUrl, HTTP_PROXY: fx.proxyUrl, https_proxy: fx.proxyUrl, http_proxy: fx.proxyUrl,+ NO_PROXY: '127.0.0.1,localhost', no_proxy: '127.0.0.1,localhost', NODE_EXTRA_CA_CERTS: fx.caFile, GITHUB_API_URL: fx.apiUrl,+ ...(mock ? { VOYAGE_API_KEY: 'pa-upgrade-matrix-mock-not-a-key' } : {}),+ };++ let logSeq = 0;+ const run = async (name: string, cmd: string[], opts: { stdin?: string; timeoutMs?: number; check?: Check; extraEnv?: Record<string, string> } = {}) => {+ const t = Date.now();+ const log = join(logs, String(++logSeq).padStart(2, '0') + '-' + name.replace(/[^a-z0-9-]+/gi, '_') + '.log');+ const proc = Bun.spawn(cmd, { cwd: home, env: { ...env, ...opts.extraEnv }, stdin: opts.stdin !== undefined ? new Blob([opts.stdin]) : 'ignore', stdout: 'pipe', stderr: 'pipe', timeout: opts.timeoutMs ?? 300_000, killSignal: 'SIGKILL' });+ const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);+ writeFileSync(log, '$ ' + cmd.join(' ') + '\n[exit ' + code + ' after ' + (Date.now() - t) + ' ms]\n--- stdout\n' + stdout + '\n--- stderr\n' + stderr);+ const step: Step = { name, ok: code === 0, ms: Date.now() - t, exit: code, log: log.slice(dir.length + 1) };+ if (code !== 0) step.detail = (stderr.trim() || stdout.trim()).split('\n').slice(-6).join('\n').slice(0, 800);+ steps.push(step);+ if (code !== 0 && opts.check) fail(opts.check, name + ' exited ' + code + ': ' + (step.detail ?? ''));+ return { code, stdout, stderr };+ };+ const note = (name: string, ok: boolean, detail?: string) => { steps.push({ name, ok, ms: 0, ...(detail ? { detail: detail.slice(0, 800) } : {}) }); };+ const gbrain = (name: string, args: string[], opts: Parameters<typeof run>[2] = {}) => run(name, ['gbrain', ...args], opts);+ const installDir = (root = join(bunDir, 'install', 'global')) => join(root, 'node_modules', 'gbrain');++ const brainChild = (name: string, extra: string[], install = installDir()) => run(name, [+ process.execPath, join(spec.harnessRoot, 'scripts', 'upgrade-matrix', 'snapshot-child.ts'),+ ...(spec.engine === 'pglite' ? ['--pglite', JSON.parse(readFileSync(join(home, '.gbrain', 'config.json'), 'utf8')).database_path, '--install', install] : ['--url', databaseUrl!]),+ ...extra,+ ], { timeoutMs: 180_000 });+ const snapshot = async (name: string, catalog: boolean): Promise<Snapshot | null> => {+ const r = await brainChild('snapshot-' + name, catalog ? ['--catalog'] : []);+ if (r.code !== 0) return null;+ writeFileSync(join(dir, 'snapshot-' + name + '.json'), r.stdout);+ return JSON.parse(r.stdout) as Snapshot;+ };++ const processes: { serve: StdioMcp | null; supervisor: boolean } = { serve: null, supervisor: false };+ const startServe = async (label: string, cli: string[] = ['gbrain']): Promise<string | null> => {+ const proc = Bun.spawn([...cli, 'serve'], { cwd: home, env, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });+ const client = new StdioMcp(proc as never);+ processes.serve = client;+ const t = Date.now();+ try {+ const version = await client.initialize();+ steps.push({ name: 'serve-' + label, ok: true, ms: Date.now() - t, detail: 'serverInfo.version ' + version });+ return version;+ } catch (e) {+ steps.push({ name: 'serve-' + label, ok: false, ms: Date.now() - t, detail: String(e) + '\n' + client.stderr.join('').slice(-600) });+ return null;+ }+ };+ const stopServe = async () => { if (processes.serve) { await processes.serve.close(); processes.serve = null; } };+ const stopAll = async () => {+ await stopServe();+ if (processes.supervisor) { await gbrain('supervisor-stop', ['jobs', 'supervisor', 'stop'], { timeoutMs: 60_000 }); processes.supervisor = false; }+ };++ try {+ // ── 1. old release, installed and seeded as a user would ──────────────+ fx.setRefs({ HEAD: spec.from.sha, 'latest-stable': spec.from.sha, stable: spec.from.sha, [spec.from.tag]: spec.from.sha });+ const install = await run('install-old', ['bun', 'install', '-g', 'github:garrytan/gbrain'], { timeoutMs: 600_000, check: 'setup' });+ const oldVersion = install.code === 0 ? (await gbrain('version-old', ['--version'], { check: 'setup' })).stdout.trim() : '';+ if (install.code === 0 && !oldVersion.endsWith(spec.from.version)) fail('setup', 'installed ' + oldVersion + ', expected ' + spec.from.version);+ if (failures.length) throw new SetupError();++ if (spec.engine === 'postgres') {+ if (!spec.postgresUrl) { fail('setup', 'a Postgres cell needs --postgres-url'); throw new SetupError(); }+ const admin = new URL(spec.postgresUrl);+ await adminSql(spec.postgresUrl, 'CREATE DATABASE ' + dbName);+ admin.pathname = '/' + dbName;+ databaseUrl = admin.toString();+ }+ const initArgs = ['init', '--non-interactive',+ ...(spec.engine === 'pglite' ? ['--pglite'] : ['--url', databaseUrl!]),+ ...(spec.keys === 'keyless' ? ['--no-embedding'] : []),+ ...(spec.brain === 'repo' ? ['--git'] : [])];+ await gbrain('init', initArgs, { check: 'setup', timeoutMs: 600_000 });+ if (failures.length) throw new SetupError();++ for (const page of SEED_PAGES) await gbrain('seed-put-' + page.slug.split('/')[1], ['put', page.slug], { stdin: page.body, check: 'setup' });+ await gbrain('seed-remember', ['remember', 'Alice Example reviews storage designs on Tuesdays', '--entity', 'people/alice-example', '--provenance', 'upgrade-matrix seed'], { check: 'setup' });+ const doomed = await gbrain('seed-put-deleted', ['put', DELETED_SLUG], { stdin: '# To be deleted\n\nThis page is soft-deleted before the upgrade.\n', check: 'setup' });+ const revision = parseJson(doomed.stdout)?.revision;+ await gbrain('seed-delete', ['delete', DELETED_SLUG, ...(typeof revision === 'string' ? ['--expected-revision', revision] : [])], { check: 'setup' });+ if (spec.keys === 'keyed') await gbrain('seed-embed', ['embed', '--stale', '--yes'], { check: 'setup' });+ const seedDream = await gbrain('seed-dream', ['dream', '--json'], { timeoutMs: 600_000 });+ receipt.seed_dream = seedDream.code === 0 ? 'ok' : 'failed (exit ' + seedDream.code + '; recorded, not judged: the old release ran it)';+ if (failures.length) throw new SetupError();++ const before = await snapshot('before', false);+ if (!before) { fail('setup', 'could not read the seeded brain'); throw new SetupError(); }+ const oldGlobal = join(dir, 'old-global');+ cpSync(join(bunDir, 'install', 'global'), oldGlobal, { recursive: true, verbatimSymlinks: true });++ const oldServeVersion = await startServe('old');+ if (oldServeVersion !== spec.from.version) { fail('setup', 'the old serve did not answer MCP as ' + spec.from.version + ' (got ' + oldServeVersion + ')'); throw new SetupError(); }+ if (spec.engine === 'postgres') {+ const sup = await gbrain('supervisor-start-old', ['jobs', 'supervisor', 'start', '--detach', '--json'], { timeoutMs: 120_000, check: 'setup' });+ processes.supervisor = sup.code === 0;+ if (failures.length) throw new SetupError();+ }+ const oldServe = processes.serve!;++ // ── 2. the old release's own updater, seeing only the candidate ───────+ const candidateTag = 'v' + spec.candidate.version;+ fx.setRefs({ HEAD: spec.candidate.sha, 'latest-stable': spec.candidate.sha, stable: spec.candidate.sha, [spec.from.tag]: spec.from.sha, [candidateTag]: spec.candidate.sha });+ const switchedAt = fx.requests.length;+ let up = await gbrain('upgrade', ['upgrade'], { timeoutMs: 900_000 });+ if (up.code === 3 && /restart_refused|--stop-mcp/.test(up.stdout + up.stderr)) {+ receipt.upgrade_needed_stop_mcp = true;+ up = await gbrain('upgrade-stop-mcp', ['upgrade', '--stop-mcp'], { timeoutMs: 900_000 });+ }+ if (up.code !== 0) fail('upgrade', 'gbrain upgrade exited ' + up.code + ': ' + (up.stderr || up.stdout).trim().split('\n').slice(-8).join('\n'));++ const served = fx.requests.slice(switchedAt);+ const foreign = served.filter(r => r.sha && r.sha !== spec.candidate.sha && r.status === 200);+ receipt.interposition = { after_switch: served, proxy: dedupe(fx.proxy), denied: dedupe(fx.proxy.filter(p => p.action === 'denied')) };+ if (foreign.length) fail('interposition', 'the updater fetched non-candidate commits: ' + foreign.map(r => r.host + r.path + '@' + r.sha!.slice(0, 7)).join(', '));+ if (!served.some(r => r.sha === spec.candidate.sha && r.status === 200 && /tarball/.test(r.path))) fail('interposition', 'the updater never fetched the candidate tarball from the fixture');++ // ── 3. the installed build is the candidate commit ────────────────────+ const newVersion = (await gbrain('version-new', ['--version'])).stdout.trim();+ const tree = compareInstalledTree(spec.harnessRoot, spec.candidate.sha, installDir());+ const lock = readFileSync(join(bunDir, 'install', 'global', 'bun.lock'), 'utf8');+ const lockSha = /"gbrain@github:garrytan\/gbrain#([0-9a-f]{7,40})"/.exec(lock)?.[1] ?? null;+ receipt.installed = { old_version: oldVersion, new_version: newVersion, lock_sha: lockSha, tree_files: tree.checked, tree_mismatches: tree.mismatches.slice(0, 20), tree_missing: tree.missing.slice(0, 20) };+ if (!newVersion.endsWith(spec.candidate.version)) fail('installed_build', 'gbrain --version says ' + newVersion + ', expected ' + spec.candidate.version);+ if (!lockSha || !spec.candidate.sha.startsWith(lockSha)) fail('installed_build', 'bun.lock pins ' + lockSha + ', expected ' + spec.candidate.sha.slice(0, 7));+ if (tree.mismatches.length || tree.missing.length) fail('installed_build', tree.mismatches.length + ' installed files differ from the candidate tree and ' + tree.missing.length + ' are missing: ' + [...tree.mismatches, ...tree.missing].slice(0, 5).join(', '));++ // ── 4. one build: nothing from before the upgrade still runs ──────────+ if (oldServe.alive) {+ receipt.restart_fix_needed = true;+ const fix = await gbrain('restart-only', ['upgrade', '--restart-only', '--stop-mcp'], { timeoutMs: 900_000 });+ if (fix.code !== 0) fail('one_build', 'gbrain upgrade --restart-only --stop-mcp exited ' + fix.code);+ await Promise.race([oldServe.proc.exited, new Promise(r => setTimeout(r, 20_000))]);+ if (oldServe.alive) fail('one_build', 'the serve started on ' + spec.from.version + ' is still running after the upgrade and restart');+ await oldServe.close();+ }+ processes.serve = null;+ const newServeVersion = await startServe('new');+ if (newServeVersion !== spec.candidate.version) fail('serve', 'the restarted serve reports ' + newServeVersion + ', expected ' + spec.candidate.version);+ else {+ try {+ const hits = await processes.serve!.callTool('search', { query: SEED_WORD });+ if (!hits.includes('upgrade-matrix-alpha')) fail('serve', 'MCP search for the seed word did not return the seeded page');+ note('serve-search', true);+ } catch (e) { fail('serve', String(e)); }+ }+ if (spec.engine === 'postgres') {+ if (processes.supervisor) await waitForWorkerHeartbeat();+ const doc = await gbrain('doctor-processes', ['doctor', '--json'], { timeoutMs: 300_000 });+ const skew = parseJson(doc.stdout)?.checks?.find((c: any) => c.name === 'runtime_build_skew');+ receipt.runtime_build_skew = skew ?? null;+ if (!skew || skew.status !== 'ok') fail('one_build', 'runtime_build_skew is ' + (skew?.status ?? 'missing') + ': ' + String(skew?.message ?? '').slice(0, 300));+ }+ await stopAll();+ const leftovers = gbrainProcessesFor(home);+ if (leftovers.length) fail('one_build', 'gbrain processes still running for this brain after stopping serve and the supervisor: ' + leftovers.join('; '));++ // ── 5. migrations, schema head, doctor ─────────────────────────────────+ await gbrain('apply-migrations', ['apply-migrations', '--yes', '--non-interactive'], { timeoutMs: 900_000, check: 'apply_migrations' });+ const doctor = await gbrain('doctor', DOCTOR_ARGV, { timeoutMs: 300_000 });+ const report = parseJson(doctor.stdout);+ const schema = report?.checks?.find((c: any) => c.name === 'schema_version');+ const m = /Version (\d+) \(latest: (\d+)\)/.exec(String(schema?.message ?? ''));+ receipt.schema_version = schema?.message ?? null;+ if (!m || m[1] !== m[2] || schema.status !== 'ok') fail('schema_head', 'schema_version check: ' + (schema ? schema.status + ' ' + schema.message : 'missing from doctor --json'));+ const dv = doctorVerdict(report);+ receipt.doctor = { source: dv.source, status: report?.status ?? null, health_score: report?.health_score ?? null, failing: dv.failing };+ if (!dv.ok) fail('doctor', dv.failing.length ? dv.failing.join('; ') : 'doctor printed no JSON report (exit ' + doctor.code + ')');++ // ── 6. preservation: canonical content equal before and after ─────────+ if (spec.fault === 'corrupt-after-upgrade') {+ const injected = await brainChild('fault-corrupt', ['--exec', "SET session_replication_role = replica; UPDATE pages SET title = title || ' (corrupted by the upgrade-matrix fault)' WHERE slug = 'concepts/upgrade-matrix-beta'; UPDATE pages SET deleted_at = NULL WHERE slug = '" + DELETED_SLUG + "'"]);+ if (injected.code !== 0) { fail('setup', 'the corruption fault could not be injected'); throw new SetupError(); }+ }+ const after = await snapshot('after', true);+ if (!after) fail('preservation', 'could not read the upgraded brain');+ else {+ const diffs = diffContent(before, after);+ receipt.preservation = { differences: diffs.slice(0, 50), compared: Object.fromEntries(Object.entries(before.content).map(([t, v]) => [t, v.rows.length])) };+ if (diffs.length) fail('preservation', diffs.length + ' canonical differences: ' + diffs.slice(0, 5).map(d => d.kind + ' ' + d.where).join('; '));+ }++ // ── 7. the upgraded brain works ────────────────────────────────────────+ const newSlug = 'concepts/upgrade-matrix-after';+ await gbrain('write', ['put', newSlug], { stdin: '# After the upgrade\n\nWritten by the candidate; it mentions ' + NEW_WORD + '.\n', check: 'write' });+ for (const [word, slug] of [[SEED_WORD, 'upgrade-matrix-alpha'], [NEW_WORD, 'upgrade-matrix-after']] as const) {+ const s = await gbrain('search-' + word, ['search', word], { check: 'keyword_search' });+ if (s.code === 0 && !s.stdout.includes(slug)) fail('keyword_search', 'search ' + word + ' did not return ' + slug);+ }+ if (mock) {+ const calls = mock.stats.embed_inputs;+ await gbrain('embed-new', ['embed', newSlug, '--yes'], { check: 'vector_search' });+ if (mock.stats.embed_inputs <= calls) fail('vector_search', 'embedding the new page made no provider call');+ const queried = mock.stats.embed_calls;+ const q = await gbrain('vector-query', ['query', 'lighthouse maintenance schedules and tidal charts'], { check: 'vector_search' });+ if (mock.stats.embed_calls <= queried) fail('vector_search', 'query did not embed the question (no vector arm)');+ if (q.code === 0 && !q.stdout.includes('upgrade-matrix-beta')) fail('vector_search', 'query did not return the matching seed page');+ }+ await gbrain('dream', ['dream', '--json'], { timeoutMs: 600_000, check: 'dream' });++ // ── 8. mixed versions: the old binary on the upgraded brain ───────────+ const pre = await snapshot('mixed-before', true);+ const oldCli = [process.execPath, join(installDir(oldGlobal), 'src', 'cli.ts')];+ await run('old-version', [...oldCli, '--version']);+ await run('old-search', [...oldCli, 'search', SEED_WORD]);+ await run('old-doctor', [...oldCli, 'doctor', '--json'], { timeoutMs: 300_000 });+ const oldAgain = await startServe('old-again', oldCli);+ receipt.old_serve_on_upgraded_brain = oldAgain ?? 'did not answer MCP (recorded, not judged)';+ if (oldAgain) { try { await processes.serve!.callTool('search', { query: SEED_WORD }); } catch { /* the old build may refuse; only mutation is judged */ } }+ await stopAll();+ const post = pre ? await snapshot('mixed-after', true) : null;+ if (!pre || !post) fail('mixed_version', 'could not snapshot the brain around the old binary');+ else {+ const diffs: Difference[] = [...diffCatalog(pre, post), ...diffContent(pre, post)];+ receipt.mixed_version = { differences: diffs.slice(0, 50) };+ if (diffs.length) fail('mixed_version', diffs.length + ' schema or content changes by ' + spec.from.version + ': ' + diffs.slice(0, 5).map(d => d.kind + ' ' + d.where).join('; '));+ }+ } catch (e) {+ if (!(e instanceof SetupError)) fail('setup', 'harness error: ' + (e instanceof Error ? e.stack ?? e.message : String(e)));+ } finally {+ await stopAll().catch(() => {});+ for (const pid of gbrainPids(home)) { try { process.kill(pid, 'SIGKILL'); } catch { /* gone */ } }+ fx.stop();+ mock?.stop();+ if (databaseUrl && spec.postgresUrl) await adminSql(spec.postgresUrl, 'DROP DATABASE IF EXISTS ' + dbName + ' WITH (FORCE)').catch(() => {});+ }++ const judged = judgeCell(spec.from.tag, failures, spec.exceptions);+ receipt.verdict = spec.fault && judged.verdict === 'pass' ? 'fail' : judged.verdict;+ receipt.failures = judged.open;+ receipt.known_exceptions = judged.excepted;+ receipt.service_calls = existsSync(serviceLog) ? readFileSync(serviceLog, 'utf8').trim().split('\n').filter(Boolean) : [];+ receipt.steps = steps;+ receipt.elapsed_s = Math.round((Date.now() - started) / 1000);+ writeFileSync(join(dir, 'receipt.json'), JSON.stringify(receipt, null, 2) + '\n');+ return receipt;+++ async function waitForWorkerHeartbeat(): Promise<void> {+ await new Promise(r => setTimeout(r, 15_000));+ }+}++class SetupError extends Error {}++async function adminSql(url: string, statement: string): Promise<void> {+ const sql = postgres(url, { max: 1, onnotice: () => {} });+ try { await sql.unsafe(statement); } finally { await sql.end({ timeout: 5 }); }+}++function parseJson(text: string): any {+ try { return JSON.parse(text); } catch {+ const start = text.indexOf('{');+ try { return start >= 0 ? JSON.parse(text.slice(start)) : null; } catch { return null; }+ }+}++function dedupe<T extends { host: string; action: string }>(rows: T[]): T[] {+ return rows.filter((r, i) => rows.findIndex(o => o.host === r.host && o.action === r.action) === i);+}++/** Every blob in the candidate's tree compared with the installed package (git hash-object), skipping paths Bun does not install. */+export function compareInstalledTree(repo: string, sha: string, installed: string): { checked: number; mismatches: string[]; missing: string[] } {+ const listing = execFileSync('git', ['-C', repo, 'ls-tree', '-r', '--full-tree', sha], { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 });+ const mismatches: string[] = [], missing: string[] = [];+ const paths: string[] = [], expected: string[] = [];+ for (const line of listing.split('\n')) {+ const m = /^(\d+) blob ([0-9a-f]+)\t(.+)$/.exec(line);+ if (!m || m[1] === '120000' || m[1] === '160000') continue;+ const path = m[3]!;+ if (path.startsWith('.git/') || /(^|\/)node_modules\//.test(path)) continue;+ if (!existsSync(join(installed, path))) { missing.push(path); continue; }+ paths.push(path); expected.push(m[2]!);+ }+ for (let i = 0; i < paths.length; i += 2000) {+ const chunk = paths.slice(i, i + 2000);+ const got = execFileSync('git', ['hash-object', '--no-filters', '--stdin-paths'], { cwd: installed, input: chunk.join('\n') + '\n', encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 }).trim().split('\n');+ chunk.forEach((p, j) => { if (got[j] !== expected[i + j]) mismatches.push(p); });+ }+ return { checked: paths.length, mismatches, missing };+}++function gbrainPids(home: string): number[] {+ const out: number[] = [];+ for (const entry of readdirSync('/proc')) {+ if (!/^\d+$/.test(entry) || Number(entry) === process.pid) continue;+ try {+ const environ = readFileSync('/proc/' + entry + '/environ', 'utf8');+ if (environ.split('\0').includes('GBRAIN_HOME=' + home)) out.push(Number(entry));+ } catch { /* gone or not ours */ }+ }+ return out;+}++function gbrainProcessesFor(home: string): string[] {+ return gbrainPids(home).map(pid => {+ try { return pid + ' ' + readFileSync('/proc/' + pid + '/cmdline', 'utf8').split('\0').join(' ').trim().slice(0, 200); } catch { return String(pid); }+ });+}diff --git a/scripts/upgrade-matrix/github-fixture.ts b/scripts/upgrade-matrix/github-fixture.tsnew file mode 100644index 0000000000..27f954b6b5--- /dev/null+++ b/scripts/upgrade-matrix/github-fixture.ts@@ -0,0 +1,222 @@+/**+ * Upgrade matrix (GBRA-224 W2): the GitHub an old release's updater sees.+ *+ * An installed release reaches GitHub four ways: Bun fetches the package+ * tarball from the API (GITHUB_API_URL, else https://api.github.com), gbrain+ * reads files from raw.githubusercontent.com (VERSION, the target's+ * package.json for the Bun floor, CHANGELOG), git ls-remote lists release+ * tags on https://github.com/garrytan/gbrain, and the binary updater reads+ * release metadata from the API. Every one of them is interposed here, so the+ * updater can only see the refs this fixture names:+ *+ * - git: url.<bare mirror>.insteadOf https://github.com/garrytan/gbrain in+ * the cell's own global git config; the mirror holds exactly the fixture's+ * refs (refs/heads/master, refs/tags/<name>).+ * - HTTP(S): an HTTPS_PROXY that tunnels the GitHub hosts to a local TLS+ * server whose certificate a per-run CA signs (trusted through+ * NODE_EXTRA_CA_CERTS), tunnels only the allowlisted hosts (the npm+ * registry) to the internet, and refuses every other host. Bun's tarball+ * API is also pointed at the plain-HTTP side with GITHUB_API_URL.+ *+ * - Embedding providers: a host in FORWARDABLE_HOSTS that a cell maps in+ * `forward` is terminated by the same TLS server and relayed to a local+ * fake provider, so a keyed brain keeps the provider's real URL and nothing+ * is billed. Unmapped, it is refused like any other host.+ *+ * Every request is logged with the commit it was answered from, so a cell can+ * assert the upgrade saw no commit other than the candidate.+ */+import { execFileSync, spawnSync } from 'node:child_process';+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { createServer, connect, type Server, type Socket } from 'node:net';+import { join } from 'node:path';++export const REPO = 'garrytan/gbrain';+export const GITHUB_HOSTS = ['api.github.com', 'codeload.github.com', 'raw.githubusercontent.com', 'github.com', 'objects.githubusercontent.com'] as const;+export const DEFAULT_ALLOW_HOSTS = ['registry.npmjs.org'];+export const FORWARDABLE_HOSTS = ['api.voyageai.com'] as const;++export interface FixtureRequest { host: string; method: string; path: string; status: number; sha?: string }+export interface ProxyDecision { host: string; port: number; action: 'fixture' | 'tunnel' | 'denied' }++export interface FixtureHandle {+ /** GITHUB_API_URL for Bun's tarball fetches (plain HTTP, loopback). */+ apiUrl: string;+ /** HTTPS_PROXY for every cell process. */+ proxyUrl: string;+ caFile: string;+ mirror: string;+ requests: FixtureRequest[];+ proxy: ProxyDecision[];+ /** Point the named refs (HEAD/master, latest-stable, stable, v<x>) at commits; every other ref disappears. */+ setRefs(refs: Record<string, string>): void;+ refs(): Record<string, string>;+ stop(): void;+}++function git(cwd: string, args: string[], input?: string): string {+ return execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', input, stdio: ['pipe', 'pipe', 'pipe'], maxBuffer: 256 * 1024 * 1024 });+}++/** A bare repository borrowing source's objects, holding no refs until setRefs. */+export function createMirror(source: string, dir: string): string {+ if (!existsSync(join(dir, 'HEAD'))) {+ mkdirSync(dir, { recursive: true });+ execFileSync('git', ['init', '--bare', '--quiet', dir]);+ const common = git(source, ['rev-parse', '--path-format=absolute', '--git-common-dir']).trim();+ writeFileSync(join(dir, 'objects', 'info', 'alternates'), join(common, 'objects') + '\n');+ }+ return dir;+}++/** Per-run CA and a leaf certificate for the GitHub hosts (openssl, valid 2 days). */+export function createCertificates(dir: string): { ca: string; cert: string; key: string } {+ mkdirSync(dir, { recursive: true });+ const ca = join(dir, 'ca.pem'), caKey = join(dir, 'ca.key'), key = join(dir, 'leaf.key'), csr = join(dir, 'leaf.csr'), cert = join(dir, 'leaf.pem'), ext = join(dir, 'leaf.ext');+ if (existsSync(cert)) return { ca, cert, key };+ const ssl = (args: string[]) => execFileSync('openssl', args, { stdio: ['ignore', 'pipe', 'pipe'] });+ ssl(['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-keyout', caKey, '-out', ca, '-days', '2', '-subj', '/CN=gbrain upgrade matrix fixture CA',+ '-addext', 'basicConstraints=critical,CA:TRUE', '-addext', 'keyUsage=critical,keyCertSign,cRLSign']);+ ssl(['req', '-newkey', 'rsa:2048', '-nodes', '-keyout', key, '-out', csr, '-subj', '/CN=github fixture']);+ writeFileSync(ext, 'basicConstraints=CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\nsubjectAltName=' + [...GITHUB_HOSTS, ...FORWARDABLE_HOSTS].map(h => 'DNS:' + h).join(',') + '\n');+ ssl(['x509', '-req', '-in', csr, '-CA', ca, '-CAkey', caKey, '-CAcreateserial', '-out', cert, '-days', '2', '-extfile', ext]);+ return { ca, cert, key };+}++function refName(ref: string): string {+ return ref === 'HEAD' || ref === 'master' ? 'refs/heads/master' : 'refs/tags/' + ref;+}++/** The ref and file a fixture-served request names, or null when the fixture does not serve it. */+export function parseFixturePath(host: string, path: string): { kind: 'tarball' | 'raw' | 'api'; ref: string; file?: string } | null {+ const p = decodeURIComponent(path.split('?')[0]!);+ const repo = '/repos/' + REPO + '/';+ if ((host === 'api.github.com' || host === 'loopback') && p.startsWith(repo)) {+ const rest = p.slice(repo.length);+ const tar = /^tarball(?:\/(.*))?$/.exec(rest);+ if (tar) return { kind: 'tarball', ref: tar[1] || 'HEAD' };+ return { kind: 'api', ref: rest };+ }+ if (host === 'codeload.github.com' && p.startsWith('/' + REPO + '/tar.gz/')) return { kind: 'tarball', ref: p.slice(REPO.length + 9) || 'HEAD' };+ if (host === 'raw.githubusercontent.com' && p.startsWith('/' + REPO + '/')) {+ const rest = p.slice(REPO.length + 2).replace(/^refs\/(heads|tags)\//, '');+ const slash = rest.indexOf('/');+ if (slash <= 0) return null;+ return { kind: 'raw', ref: rest.slice(0, slash), file: rest.slice(slash + 1) };+ }+ return null;+}++export interface FixtureOptions {+ /** Checkout whose objects the mirror borrows. */+ source: string;+ mirrorDir: string;+ /** Shared across cells: git archives by commit. */+ archiveDir: string;+ /** Shared across cells: the run's CA and leaf certificate. */+ certDir: string;+ /** FORWARDABLE_HOSTS entries relayed to a local base URL. */+ forward?: Record<string, string>;+ allowHosts?: string[];+}++export async function startGithubFixture(opts: FixtureOptions): Promise<FixtureHandle> {+ const mirror = createMirror(opts.source, opts.mirrorDir);+ const archives = opts.archiveDir;+ mkdirSync(archives, { recursive: true });+ const certs = createCertificates(opts.certDir);+ const allow = new Set(opts.allowHosts ?? DEFAULT_ALLOW_HOSTS);+ const forward = new Map(Object.entries(opts.forward ?? {}).filter(([h]) => (FORWARDABLE_HOSTS as readonly string[]).includes(h)));+ const requests: FixtureRequest[] = [];+ const proxyLog: ProxyDecision[] = [];+ let current: Record<string, string> = {};++ const resolveRef = (ref: string): string | undefined => current[ref || 'HEAD'] ?? (/^[0-9a-f]{40}$/.test(ref) && Object.values(current).includes(ref) ? ref : undefined);++ const tarball = (sha: string): string => {+ const file = join(archives, sha + '.tar.gz');+ if (!existsSync(file)) {+ const tmp = file + '.' + process.pid + '.tmp';+ execFileSync('git', ['-C', mirror, 'archive', '--format=tar.gz', '--prefix=garrytan-gbrain-' + sha.slice(0, 7) + '/', '-o', tmp, sha]);+ renameSync(tmp, file);+ }+ return file;+ };++ const handle = async (host: string, req: Request): Promise<Response> => {+ const url = new URL(req.url);+ const target = forward.get(host);+ if (target) {+ const res = await fetch(target.replace(/\/$/, '') + url.pathname + url.search, {+ method: req.method, headers: { 'content-type': req.headers.get('content-type') ?? 'application/json', authorization: req.headers.get('authorization') ?? '' },+ body: req.method === 'GET' || req.method === 'HEAD' ? undefined : await req.arrayBuffer(),+ });+ requests.push({ host, method: req.method, path: url.pathname, status: res.status });+ return new Response(await res.arrayBuffer(), { status: res.status, headers: { 'content-type': res.headers.get('content-type') ?? 'application/json' } });+ }+ const parsed = parseFixturePath(host, url.pathname);+ const record = (status: number, sha?: string) => { requests.push({ host, method: req.method, path: url.pathname, status, ...(sha ? { sha } : {}) }); };+ const sha = parsed ? resolveRef(parsed.ref) : undefined;+ if (!parsed || !sha || parsed.kind === 'api') { record(404, sha); return new Response('404: Not Found', { status: 404 }); }+ if (parsed.kind === 'tarball') {+ record(200, sha);+ return new Response(Bun.file(tarball(sha)), { headers: { 'content-type': 'application/x-gzip' } });+ }+ const show = spawnSync('git', ['-C', mirror, 'show', sha + ':' + parsed.file], { maxBuffer: 64 * 1024 * 1024 });+ if (show.status !== 0) { record(404, sha); return new Response('404: Not Found', { status: 404 }); }+ record(200, sha);+ return new Response(show.stdout);+ };++ const plain = Bun.serve({ port: 0, hostname: '127.0.0.1', fetch: req => handle('loopback', req) });+ const tls = Bun.serve({+ port: 0, hostname: '127.0.0.1',+ tls: { cert: readFileSync(certs.cert, 'utf8'), key: readFileSync(certs.key, 'utf8') },+ fetch: req => handle((req.headers.get('host') ?? '').split(':')[0]!.toLowerCase(), req),+ });++ const proxy: Server = createServer((client: Socket) => {+ client.on('error', () => client.destroy());+ client.once('data', (head: Buffer) => {+ const line = head.toString('latin1').split('\r\n')[0] ?? '';+ const m = /^CONNECT ([^:\s]+):(\d+) HTTP\/1\.[01]$/i.exec(line);+ const deny = (host: string, port: number) => { proxyLog.push({ host, port, action: 'denied' }); client.end('HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\n\r\n'); };+ if (!m) return deny(/^\w+ https?:\/\/([^/:\s]+)/i.exec(line)?.[1] ?? 'unknown', 80);+ const host = m[1]!.toLowerCase(), port = Number(m[2]);+ const fixture = (GITHUB_HOSTS as readonly string[]).includes(host) || forward.has(host);+ if (!fixture && !allow.has(host)) return deny(host, port);+ proxyLog.push({ host, port, action: fixture ? 'fixture' : 'tunnel' });+ const upstream = fixture ? connect(tls.port!, '127.0.0.1') : connect(port, host);+ upstream.on('error', () => { client.destroy(); upstream.destroy(); });+ upstream.once('connect', () => {+ client.write('HTTP/1.1 200 Connection Established\r\n\r\n');+ const rest = head.subarray(head.indexOf('\r\n\r\n') + 4);+ if (rest.length) upstream.write(rest);+ client.pipe(upstream).pipe(client);+ });+ });+ });+ await new Promise<void>(r => proxy.listen(0, '127.0.0.1', () => r()));+ const proxyPort = (proxy.address() as { port: number }).port;++ return {+ apiUrl: 'http://127.0.0.1:' + plain.port,+ proxyUrl: 'http://127.0.0.1:' + proxyPort,+ caFile: certs.ca,+ mirror,+ requests,+ proxy: proxyLog,+ setRefs(refs) {+ const next: Record<string, string> = { ...refs };+ if (next.master && !next.HEAD) next.HEAD = next.master;+ if (next.HEAD && !next.master) next.master = next.HEAD;+ const wanted = new Map(Object.entries(next).filter(([ref]) => ref !== 'HEAD').map(([ref, sha]) => [refName(ref), sha]));+ const lines = git(mirror, ['for-each-ref', '--format=%(refname)']).split('\n').filter(r => r && !wanted.has(r)).map(r => 'delete ' + r);+ for (const [ref, sha] of wanted) lines.push('update ' + ref + ' ' + sha);+ git(mirror, ['update-ref', '--stdin'], lines.join('\n') + '\n');+ current = next;+ },+ refs: () => ({ ...current }),+ stop() { plain.stop(true); tls.stop(true); proxy.close(); },+ };+}diff --git a/scripts/upgrade-matrix/known-exceptions.json b/scripts/upgrade-matrix/known-exceptions.jsonnew file mode 100644index 0000000000..c51cec8883--- /dev/null+++ b/scripts/upgrade-matrix/known-exceptions.json@@ -0,0 +1,14 @@+{+ "$comment": "Matrix failures already tracked by an issue, so a nightly run stays green while the fix lands. Each entry names one check, explicit release tags and the tracking issue; validateKnownExceptions (scripts/upgrade-matrix/verdict.ts) refuses wildcards and setup errors. Remove an entry when its issue closes. Docs: docs/ci-upgrade-matrix.md#known-exceptions",+ "exceptions": [+ {+ "id": "v0_13_1-grandfather-on-upgrade",+ "check": "preservation",+ "from": [+ "v0.59.2.0"+ ],+ "issue": "https://github.com/garrytan/gbrain/issues/7814",+ "reason": "A brain created by v0.59.2.0 still has the v0.13.0/v0.13.1 orchestrators pending; apply-migrations writes validate: false into every page's frontmatter and content hash."+ }+ ]+}diff --git a/scripts/upgrade-matrix/mcp-probe.ts b/scripts/upgrade-matrix/mcp-probe.tsnew file mode 100644index 0000000000..5402f650d9--- /dev/null+++ b/scripts/upgrade-matrix/mcp-probe.ts@@ -0,0 +1,74 @@+/**+ * Upgrade matrix: a minimal stdio MCP client for the serve a cell starts the+ * way an agent harness does (stdin held open, newline-delimited JSON-RPC).+ * It reads the server's reported version from initialize and calls one tool.+ */+import type { Subprocess } from 'bun';++export class StdioMcp {+ private buffer = '';+ private waiters = new Map<number, (msg: any) => void>();+ private nextId = 1;+ readonly stderr: string[] = [];++ constructor(readonly proc: Subprocess<'pipe', 'pipe', 'pipe'>) {+ void this.pump();+ void (async () => { for await (const chunk of proc.stderr) this.stderr.push(new TextDecoder().decode(chunk)); })().catch(() => {});+ }++ private async pump(): Promise<void> {+ try {+ for await (const chunk of this.proc.stdout) {+ this.buffer += new TextDecoder().decode(chunk);+ let nl: number;+ while ((nl = this.buffer.indexOf('\n')) >= 0) {+ const line = this.buffer.slice(0, nl).trim();+ this.buffer = this.buffer.slice(nl + 1);+ if (!line.startsWith('{')) continue;+ try {+ const msg = JSON.parse(line);+ if (typeof msg.id === 'number') this.waiters.get(msg.id)?.(msg);+ } catch { /* not a JSON-RPC line */ }+ }+ }+ } catch { /* stream closed */ }+ }++ get alive(): boolean { return this.proc.exitCode === null && this.proc.signalCode === null; }++ async request(method: string, params: unknown, timeoutMs = 60_000): Promise<any> {+ const id = this.nextId++;+ const reply = new Promise<any>((resolve, reject) => {+ const timer = setTimeout(() => { this.waiters.delete(id); reject(new Error(method + ' timed out after ' + timeoutMs + ' ms')); }, timeoutMs);+ this.waiters.set(id, msg => { clearTimeout(timer); this.waiters.delete(id); resolve(msg); });+ });+ this.proc.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');+ this.proc.stdin.flush();+ const msg = await reply;+ if (msg.error) throw new Error(method + ': ' + JSON.stringify(msg.error).slice(0, 400));+ return msg.result;+ }++ /** initialize + initialized; returns serverInfo.version. */+ async initialize(): Promise<string> {+ const result = await this.request('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'gbrain-upgrade-matrix', version: '1' } }, 120_000);+ this.proc.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');+ this.proc.stdin.flush();+ return String(result?.serverInfo?.version ?? '');+ }++ /** tools/call; returns the concatenated text content. */+ async callTool(name: string, args: Record<string, unknown>): Promise<string> {+ const result = await this.request('tools/call', { name, arguments: args });+ const text = (result?.content ?? []).map((c: any) => (typeof c?.text === 'string' ? c.text : '')).join('\n');+ if (result?.isError) throw new Error(name + ' returned an error: ' + text.slice(0, 400));+ return text;+ }++ async close(): Promise<void> {+ try { this.proc.stdin.end(); } catch { /* already closed */ }+ const exited = await Promise.race([this.proc.exited.then(() => true), new Promise<boolean>(r => setTimeout(() => r(false), 10_000))]);+ if (!exited) { this.proc.kill('SIGTERM'); await Promise.race([this.proc.exited, new Promise(r => setTimeout(r, 5_000))]); }+ if (this.alive) this.proc.kill('SIGKILL');+ }+}diff --git a/scripts/upgrade-matrix/snapshot-child.ts b/scripts/upgrade-matrix/snapshot-child.tsnew file mode 100644index 0000000000..19389b2925--- /dev/null+++ b/scripts/upgrade-matrix/snapshot-child.ts@@ -0,0 +1,49 @@+#!/usr/bin/env bun+/**+ * Upgrade matrix snapshot child: prints a content (and with --catalog, a+ * catalog) snapshot of one brain as JSON on stdout.+ *+ * bun scripts/upgrade-matrix/snapshot-child.ts --pglite <data dir> --install <gbrain package dir> [--catalog]+ * bun scripts/upgrade-matrix/snapshot-child.ts --url <postgres url> [--catalog]+ * bun scripts/upgrade-matrix/snapshot-child.ts <brain flags> --exec '<sql>; <sql>' (runs the statements in order on one connection, prints nothing)+ *+ * A PGLite brain is opened with the PGLite build of the gbrain release that is+ * installed at that moment (resolved from --install), never the harness's own,+ * so the data directory only ever meets a PGLite version the brain's own+ * release would open it with. Run it only while no gbrain process holds the+ * brain.+ */+import { takeSnapshot, type Query } from './snapshot.ts';++const argv = process.argv.slice(2);+const flag = (name: string) => { const i = argv.indexOf(name); return i >= 0 ? argv[i + 1] : undefined; };+const catalog = argv.includes('--catalog');+const exec = flag('--exec');++let query: Query;+let close: () => Promise<void>;+const dataDir = flag('--pglite');+if (dataDir) {+ const install = flag('--install');+ if (!install) throw new Error('--pglite needs --install <gbrain package dir>');+ const load = async (spec: string) => import(Bun.resolveSync(spec, install));+ const { PGlite } = await load('@electric-sql/pglite');+ const { vector } = await load('@electric-sql/pglite/vector');+ const { pg_trgm } = await load('@electric-sql/pglite/contrib/pg_trgm');+ const db = await PGlite.create({ dataDir, extensions: { vector, pg_trgm } });+ query = async (sql, params) => (await db.query(sql, params ?? [])).rows as Record<string, unknown>[];+ close = () => db.close();+} else {+ const url = flag('--url');+ if (!url) throw new Error('pass --pglite <dir> --install <dir> or --url <postgres url>');+ const postgres = (await import('#postgres')).default;+ const sql = postgres(url, { max: 1, onnotice: () => {} });+ query = async (text, params) => [...await sql.unsafe(text, (params ?? []) as never[])] as Record<string, unknown>[];+ close = () => sql.end({ timeout: 5 });+}+try {+ if (exec) for (const statement of exec.split(';').map(s => s.trim()).filter(Boolean)) await query(statement);+ else process.stdout.write(JSON.stringify(await takeSnapshot(query, { catalog })) + '\n');+} finally {+ await close();+}diff --git a/scripts/upgrade-matrix/snapshot.ts b/scripts/upgrade-matrix/snapshot.tsnew file mode 100644index 0000000000..7f7c2bbf2d--- /dev/null+++ b/scripts/upgrade-matrix/snapshot.ts@@ -0,0 +1,122 @@+/**+ * Upgrade matrix (GBRA-224 W2): what must survive an upgrade, and what an+ * older binary must not change.+ *+ * A content snapshot holds the canonical fields of every page, fact and+ * source: slugs and source ids, the content hash, title, type, frontmatter,+ * provenance columns and deletion state. Timestamps, ids, vectors and derived+ * bookkeeping are left out, so a migration that adds columns or re-chunks+ * pages still compares equal. A catalog snapshot holds the schema objects+ * (columns, indexes, constraints, triggers, functions, views) and the schema+ * version, for the mixed-version probe.+ *+ * Only columns present on both sides are compared; a canonical column the+ * upgrade dropped is itself a difference.+ */++export interface TableSpec { table: string; key: string[]; columns: string[]; flags?: Record<string, string> }++/** Canonical fields per table. flags are NULL-ness tests reported as booleans (deletion and supersession state). */+export const CANONICAL: TableSpec[] = [+ {+ table: 'pages', key: ['source_id', 'slug'],+ columns: ['source_id', 'slug', 'type', 'page_kind', 'title', 'content_hash', 'frontmatter', 'source_kind', 'source_uri', 'ingested_via', 'source_path'],+ flags: { deleted: 'deleted_at' },+ },+ {+ table: 'facts', key: ['source_id', 'entity_slug', 'fact', 'row_num'],+ columns: ['source_id', 'entity_slug', 'fact', 'row_num', 'kind', 'visibility', 'notability', 'context', 'source', 'source_session', 'confidence', 'valid_from', 'valid_until',+ 'source_markdown_slug', 'attributed_to', 'claim_metric', 'claim_value', 'claim_unit', 'claim_period'],+ flags: { expired: 'expired_at', superseded: 'superseded_by' },+ },+ { table: 'sources', key: ['id'], columns: ['id', 'name', 'archived'] },+];++export const CATALOG_QUERIES: Record<string, string> = {+ columns: "SELECT table_name || '.' || column_name AS k, data_type || ' ' || is_nullable || ' ' || coalesce(column_default, '') AS v FROM information_schema.columns WHERE table_schema = current_schema()",+ indexes: "SELECT indexname AS k, indexdef AS v FROM pg_indexes WHERE schemaname = current_schema()",+ constraints: "SELECT conrelid::regclass::text || '.' || conname AS k, pg_get_constraintdef(oid) AS v FROM pg_constraint WHERE connamespace = current_schema()::regnamespace",+ triggers: "SELECT tgrelid::regclass::text || '.' || tgname AS k, pg_get_triggerdef(oid) AS v FROM pg_trigger WHERE NOT tgisinternal",+ functions: "SELECT p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')' AS k, md5(coalesce(p.prosrc, '')) AS v FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = current_schema()",+ views: "SELECT table_name AS k, md5(coalesce(view_definition, '')) AS v FROM information_schema.views WHERE table_schema = current_schema()",+ schema_version: "SELECT key AS k, value AS v FROM config WHERE key = 'version'",+};++export interface Snapshot {+ content: Record<string, { columns: string[]; rows: Record<string, unknown>[] }>;+ catalog?: Record<string, Record<string, string>>;+}++export type Query = (sql: string, params?: unknown[]) => Promise<Record<string, unknown>[]>;++function canon(v: unknown): unknown {+ if (v === null || v === undefined) return null;+ if (v instanceof Date) return v.toISOString();+ if (typeof v === 'string' && /^[[{]/.test(v)) { try { return canon(JSON.parse(v)); } catch { return v; } }+ if (Array.isArray(v)) return v.map(canon);+ if (typeof v === 'object') return Object.fromEntries(Object.keys(v as object).sort().map(k => [k, canon((v as Record<string, unknown>)[k])]));+ if (typeof v === 'number') return Number.isInteger(v) ? v : Math.round(v * 1e6) / 1e6;+ return v;+}++export async function takeSnapshot(query: Query, opts: { catalog: boolean }): Promise<Snapshot> {+ const content: Snapshot['content'] = {};+ for (const spec of CANONICAL) {+ const present = new Set((await query('SELECT column_name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = $1', [spec.table])).map(r => String(r.column_name)));+ if (present.size === 0) continue;+ const cols = spec.columns.filter(c => present.has(c));+ const flags = Object.entries(spec.flags ?? {}).filter(([, col]) => present.has(col));+ const select = [...cols.map(c => '"' + c + '"'), ...flags.map(([name, col]) => '("' + col + '" IS NOT NULL) AS "' + name + '"')].join(', ');+ const rows = (await query('SELECT ' + select + ' FROM "' + spec.table + '"')).map(r => Object.fromEntries(Object.entries(r).map(([k, v]) => [k, canon(v)])));+ rows.sort((a, b) => rowKey(spec, a).localeCompare(rowKey(spec, b)));+ content[spec.table] = { columns: [...cols, ...flags.map(([name]) => name)], rows };+ }+ if (!opts.catalog) return { content };+ const catalog: Record<string, Record<string, string>> = {};+ for (const [name, sql] of Object.entries(CATALOG_QUERIES)) {+ catalog[name] = Object.fromEntries((await query(sql)).map(r => [String(r.k), String(r.v)]).sort(([a], [b]) => a.localeCompare(b)));+ }+ return { content, catalog };+}++function rowKey(spec: TableSpec, row: Record<string, unknown>): string {+ return JSON.stringify(spec.key.map(k => row[k] ?? null));+}++export interface Difference { kind: 'row_missing' | 'row_added' | 'field_changed' | 'column_dropped' | 'table_dropped' | 'catalog_changed'; where: string; detail: string }++/** Differences in canonical content between two snapshots (before and after). */+export function diffContent(before: Snapshot, after: Snapshot, opts: { allowAdded?: (table: string, row: Record<string, unknown>) => boolean } = {}): Difference[] {+ const out: Difference[] = [];+ for (const spec of CANONICAL) {+ const a = before.content[spec.table], b = after.content[spec.table];+ if (!a) continue;+ if (!b) { out.push({ kind: 'table_dropped', where: spec.table, detail: 'table missing after' }); continue; }+ for (const c of a.columns) if (!b.columns.includes(c)) out.push({ kind: 'column_dropped', where: spec.table + '.' + c, detail: 'canonical column missing after' });+ const shared = a.columns.filter(c => b.columns.includes(c));+ const index = (rows: Record<string, unknown>[]) => new Map(rows.map(r => [rowKey(spec, r), r]));+ const ai = index(a.rows), bi = index(b.rows);+ for (const [k, row] of ai) {+ const other = bi.get(k);+ if (!other) { out.push({ kind: 'row_missing', where: spec.table + ' ' + k, detail: 'row present before, missing after' }); continue; }+ for (const c of shared) {+ const x = JSON.stringify(row[c] ?? null), y = JSON.stringify(other[c] ?? null);+ if (x !== y) out.push({ kind: 'field_changed', where: spec.table + ' ' + k + ' ' + c, detail: x.slice(0, 160) + ' -> ' + y.slice(0, 160) });+ }+ }+ for (const [k, row] of bi) if (!ai.has(k) && !(opts.allowAdded?.(spec.table, row))) out.push({ kind: 'row_added', where: spec.table + ' ' + k, detail: 'row absent before, present after' });+ }+ return out;+}++export function diffCatalog(before: Snapshot, after: Snapshot): Difference[] {+ const out: Difference[] = [];+ const a = before.catalog ?? {}, b = after.catalog ?? {};+ for (const name of Object.keys(CATALOG_QUERIES)) {+ const x = a[name] ?? {}, y = b[name] ?? {};+ for (const k of new Set([...Object.keys(x), ...Object.keys(y)])) {+ if (x[k] !== y[k]) out.push({ kind: 'catalog_changed', where: name + ' ' + k, detail: (x[k] ?? '(absent)').slice(0, 160) + ' -> ' + (y[k] ?? '(absent)').slice(0, 160) });+ }+ }+ return out;+}diff --git a/scripts/upgrade-matrix/verdict.ts b/scripts/upgrade-matrix/verdict.tsnew file mode 100644index 0000000000..aec96ede34--- /dev/null+++ b/scripts/upgrade-matrix/verdict.ts@@ -0,0 +1,105 @@+/**+ * Upgrade matrix (GBRA-224 W2): judging a cell, applying known exceptions and+ * summarizing a run.+ */+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++/** Every check a cell can fail, with the upgrade-breakage class it guards (plan "What caused this work", item 2). */+export const CHECKS = {+ setup: 'harness: the old release could not be installed, initialized or seeded (no candidate verdict)',+ interposition: 'D: the updater saw a commit other than the candidate, or the fixture could not serve it',+ upgrade: 'D/E: the old release\'s updater failed after the documented fix',+ installed_build: 'D: the installed build is not the candidate commit',+ one_build: 'C: a process still runs the old build after the upgrade and restart',+ apply_migrations: 'A/G: apply-migrations did not exit 0',+ schema_head: 'A: the schema is not at the candidate\'s head',+ doctor: 'H: doctor reports a failing check outside the skill category',+ serve: 'C/E: the restarted serve does not answer MCP on the candidate build',+ write: 'J: a new page could not be written',+ keyword_search: 'J: keyword search does not find a page',+ vector_search: 'J: vector search or embedding failed (keyed)',+ dream: 'J: a post-upgrade maintenance pass failed',+ preservation: 'data loss: canonical content changed across the upgrade',+ mixed_version: 'C: the old binary changed schema or content on the upgraded brain',+} as const;+export type Check = keyof typeof CHECKS;++export interface Failure { check: Check; detail: string }+export interface KnownException { id: string; check: Check; from: string[]; issue: string; reason: string }++export const KNOWN_EXCEPTIONS_FILE = join(import.meta.dir, 'known-exceptions.json');++/** Every entry names an explicit from-version list, a known check and an issue; no wildcards. */+export function validateKnownExceptions(entries: unknown): string[] {+ const problems: string[] = [];+ if (!Array.isArray(entries)) return ['known-exceptions.json: "exceptions" must be an array'];+ entries.forEach((e: any, i) => {+ const at = 'exception ' + i + (e?.id ? ' (' + e.id + ')' : '');+ if (typeof e?.id !== 'string' || !e.id) problems.push(at + ': id is required');+ if (!(e?.check in CHECKS)) problems.push(at + ': check must be one of ' + Object.keys(CHECKS).join(', '));+ if (e?.check === 'setup') problems.push(at + ': setup errors are never excepted');+ if (!Array.isArray(e?.from) || e.from.length === 0 || e.from.some((v: unknown) => typeof v !== 'string' || !/^v\d+\.\d+\.\d+(\.\d+)?$/.test(v))) problems.push(at + ': from must list explicit release tags (v<x.y.z.w>), no wildcards');+ if (typeof e?.issue !== 'string' || !/^https:\/\/github\.com\/garrytan\/gbrain\/(issues|pull)\/\d+$/.test(e.issue)) problems.push(at + ': issue must be a garrytan/gbrain issue or pull URL');+ if (typeof e?.reason !== 'string' || e.reason.length < 20) problems.push(at + ': reason must say what the old release does');+ });+ return problems;+}++export function loadKnownExceptions(file = KNOWN_EXCEPTIONS_FILE): KnownException[] {+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as { exceptions: unknown };+ const problems = validateKnownExceptions(parsed.exceptions);+ if (problems.length) throw new Error(problems.join('\n'));+ return parsed.exceptions as KnownException[];+}++// W4 SWITCH POINT (GBRA-224 W4 adds doctor --alert): when it ships, change+// DOCTOR_ARGV to ['doctor', '--alert', '--json'] and drop the legacy branch in+// doctorVerdict. Until then the verdict is the legacy report: any check whose+// status is fail outside the skill category fails the cell. A report that+// already carries alert.level is judged by it.+export const DOCTOR_ARGV = ['doctor', '--json'];++export function doctorVerdict(report: any): { ok: boolean; failing: string[]; source: 'alert' | 'legacy' } {+ const level = report?.alert?.level;+ if (typeof level === 'string') {+ const items = Array.isArray(report.alert.items) ? report.alert.items.map((i: any) => String(i?.code ?? i?.check ?? 'item')) : [];+ return { ok: level === 'none', failing: level === 'none' ? [] : [level, ...items], source: 'alert' };+ }+ const checks: any[] = Array.isArray(report?.checks) ? report.checks : [];+ const failing = checks.filter(c => c?.status === 'fail' && c?.category !== 'skill').map(c => String(c.name) + ': ' + String(c.message ?? '').slice(0, 200));+ return { ok: !!report && failing.length === 0, failing, source: 'legacy' };+}++export type CellVerdict = 'pass' | 'fail' | 'error' | 'known_exception';++/** fail/error unless every failure matches a known exception for this from-version. */+export function judgeCell(fromTag: string, failures: Failure[], exceptions: KnownException[]): { verdict: CellVerdict; excepted: Array<Failure & { exception: string; issue: string }>; open: Failure[] } {+ const excepted: Array<Failure & { exception: string; issue: string }> = [];+ const open: Failure[] = [];+ for (const f of failures) {+ const e = exceptions.find(x => x.check === f.check && x.from.includes(fromTag));+ if (e) excepted.push({ ...f, exception: e.id, issue: e.issue });+ else open.push(f);+ }+ const verdict: CellVerdict = open.some(f => f.check === 'setup') ? 'error' : open.length ? 'fail' : excepted.length ? 'known_exception' : 'pass';+ return { verdict, excepted, open };+}++export interface CellSummary { id: string; from: string; roles: string[]; shape: string; verdict: CellVerdict | 'hold' | 'missing'; open: Failure[]; excepted: Array<{ check: string; issue: string }>; fault?: string | null }++/**+ * Red: a cell failed a candidate check, a planned cell left no receipt, or a+ * fault was injected. Hold: a cell could not reach a candidate verdict because+ * the old release could not be installed, initialized or seeded in that shape+ * (error), or a door could not run. Green: every planned cell passed or failed+ * only a known exception. A hold never passes a gate and never opens an+ * upgrade-break issue.+ */+export function summarize(planned: string[], cells: CellSummary[]): { green: boolean; red: CellSummary[]; holds: CellSummary[] } {+ const byId = new Map(cells.map(c => [c.id, c]));+ const all = planned.map(id => byId.get(id) ?? { id, from: '?', roles: [], shape: '?', verdict: 'missing' as const, open: [], excepted: [] });+ const red = all.filter(c => c.fault || c.verdict === 'fail' || c.verdict === 'missing');+ const holds = all.filter(c => !red.includes(c) && (c.verdict === 'hold' || c.verdict === 'error'));+ return { green: red.length === 0 && holds.length === 0, red, holds };+}diff --git a/scripts/upgrade-matrix/versions.ts b/scripts/upgrade-matrix/versions.tsnew file mode 100644index 0000000000..89a925ba57--- /dev/null+++ b/scripts/upgrade-matrix/versions.ts@@ -0,0 +1,97 @@+/**+ * Upgrade matrix (GBRA-224 W2): which published releases a run upgrades from.+ *+ * Resolved once per run from published release tags and recorded in the run+ * receipt: N-1, N-10 and N-50 (the 1st, 10th and 50th newest release older+ * than the candidate), the release published closest to 30 days before the+ * candidate, and the current stable tag when one exists and is older. The+ * pull-request profile keeps N-1 and N-50. A role that cannot be filled (too+ * few older releases, stable missing or not older) is recorded as skipped+ * with the reason, never silently dropped.+ */+import { isNewerVersion, isValidVersionString } from '../../src/core/semver.ts';++export type FromRole = 'N-1' | 'N-10' | 'N-50' | '30d' | 'stable';+export type Profile = 'full' | 'pr';+export const PROFILE_ROLES: Record<Profile, FromRole[]> = { full: ['N-1', 'N-10', 'N-50', '30d', 'stable'], pr: ['N-1', 'N-50'] };++export interface Release { tag: string; version: string; published_at: string }+export interface Candidate { tag: string | null; sha: string; tree: string; version: string; published_at: string }+export interface FromVersion { tag: string; version: string; published_at: string; roles: FromRole[] }+export interface SkippedRole { role: FromRole; reason: string }++const DAY_MS = 86_400_000;+export const RELEASE_TAG = /^v(\d+\.\d+\.\d+(?:\.\d+)?)$/;++/** Releases older than the candidate (semver), newest first. */+export function olderReleases(releases: readonly Release[], candidateVersion: string): Release[] {+ return releases+ .filter(r => isValidVersionString(r.version) && isNewerVersion(r.version, candidateVersion))+ .sort((a, b) => (isNewerVersion(a.version, b.version) ? 1 : isNewerVersion(b.version, a.version) ? -1 : 0));+}++export function resolveFromVersions(+ releases: readonly Release[],+ candidate: Pick<Candidate, 'version' | 'published_at'>,+ opts: { profile: Profile; stableVersion?: string | null },+): { from: FromVersion[]; skipped: SkippedRole[] } {+ const older = olderReleases(releases, candidate.version);+ const picked = new Map<string, FromVersion>();+ const skipped: SkippedRole[] = [];+ const take = (role: FromRole, r: Release | undefined, reason: string) => {+ if (!r) { skipped.push({ role, reason }); return; }+ const prior = picked.get(r.tag);+ if (prior) prior.roles.push(role);+ else picked.set(r.tag, { tag: r.tag, version: r.version, published_at: r.published_at, roles: [role] });+ };+ for (const role of PROFILE_ROLES[opts.profile]) {+ if (role === 'N-1' || role === 'N-10' || role === 'N-50') {+ const k = Number(role.slice(2));+ take(role, older[k - 1], 'only ' + older.length + ' published releases are older than the candidate');+ } else if (role === '30d') {+ const target = Date.parse(candidate.published_at) - 30 * DAY_MS;+ let best: Release | undefined;+ for (const r of older) {+ const d = Math.abs(Date.parse(r.published_at) - target);+ if (!best || d < Math.abs(Date.parse(best.published_at) - target)) best = r;+ }+ take(role, best, 'no published release is older than the candidate');+ } else {+ const stable = opts.stableVersion ?? null;+ if (!stable) { skipped.push({ role, reason: 'no stable tag exists' }); continue; }+ if (!isNewerVersion(stable, candidate.version)) { skipped.push({ role, reason: 'stable (' + stable + ') is not older than the candidate' }); continue; }+ take(role, older.find(r => r.version === stable), 'stable (' + stable + ') has no published release');+ }+ }+ return { from: [...picked.values()], skipped };+}++function token(): string | undefined {+ return process.env.GITHUB_TOKEN || process.env.GH_TOKEN || undefined;+}++/** Published (non-draft, non-prerelease) release tags, newest first, reading pages until 'enough' holds. */+export async function fetchReleases(repo: string, enough: (releases: Release[]) => boolean, fetchImpl: typeof fetch = fetch): Promise<Release[]> {+ const out: Release[] = [];+ const auth = token();+ for (let page = 1; page <= 30; page++) {+ const res = await fetchImpl('https://api.github.com/repos/' + repo + '/releases?per_page=100&page=' + page, {+ headers: { accept: 'application/vnd.github+json', 'user-agent': 'gbrain-upgrade-matrix', ...(auth ? { authorization: 'Bearer ' + auth } : {}) },+ });+ if (!res.ok) throw new Error('GET releases page ' + page + ' returned HTTP ' + res.status + (auth ? '' : ' (unauthenticated: set GITHUB_TOKEN)'));+ const rows = await res.json() as Array<{ tag_name: string; published_at: string | null; draft: boolean; prerelease: boolean }>;+ for (const r of rows) {+ const m = RELEASE_TAG.exec(r.tag_name);+ if (m && !r.draft && !r.prerelease && r.published_at) out.push({ tag: r.tag_name, version: m[1]!, published_at: r.published_at });+ }+ if (rows.length < 100 || enough(out)) break;+ }+ return out;+}++/** Enough history for every role: 50 older releases and one published 31 days before the candidate. */+export function hasEnoughHistory(releases: readonly Release[], candidate: Pick<Candidate, 'version' | 'published_at'>): boolean {+ const older = olderReleases(releases, candidate.version);+ const horizon = Date.parse(candidate.published_at) - 31 * DAY_MS;+ return older.length >= 50 && older.some(r => Date.parse(r.published_at) < horizon);+}diff --git a/test/scripts/upgrade-matrix.test.ts b/test/scripts/upgrade-matrix.test.tsnew file mode 100644index 0000000000..7f80788122--- /dev/null+++ b/test/scripts/upgrade-matrix.test.ts@@ -0,0 +1,228 @@+/**+ * Upgrade matrix harness (GBRA-224 W2): from-version resolution, the GitHub+ * fixture the old updater sees, preservation snapshots on real PGLite, and+ * the verdict rules. The matrix itself runs in .github/workflows/upgrade-matrix.yml.+ */+import { describe, expect, test } from 'bun:test';+import { PGlite } from '@electric-sql/pglite';+import { execFileSync } from 'node:child_process';+import { mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { resolveFromVersions, type Release } from '../../scripts/upgrade-matrix/versions.ts';+import { parseFixturePath, startGithubFixture } from '../../scripts/upgrade-matrix/github-fixture.ts';+import { compareInstalledTree } from '../../scripts/upgrade-matrix/cell.ts';+import { diffCatalog, diffContent, takeSnapshot, type Query } from '../../scripts/upgrade-matrix/snapshot.ts';+import { CHECKS, doctorVerdict, judgeCell, loadKnownExceptions, summarize, validateKnownExceptions, type CellSummary } from '../../scripts/upgrade-matrix/verdict.ts';+import { buildSummary, type Plan } from '../../scripts/upgrade-matrix.ts';++const DAY = 86_400_000;+const T0 = Date.parse('2026-10-27T00:00:00Z');+/** 80 releases v0.60.1.0 .. v0.60.80.0, one a day, newest last. */+const releases: Release[] = Array.from({ length: 80 }, (_, i) => ({ tag: 'v0.60.' + (i + 1) + '.0', version: '0.60.' + (i + 1) + '.0', published_at: new Date(T0 - (80 - i) * DAY).toISOString() }));++describe('from-version resolution', () => {+ test('N-1, N-10, N-50 and 30 days are picked from releases older than the candidate; a missing stable is skipped with its reason', () => {+ const candidate = releases[79]!;+ const r = resolveFromVersions(releases, candidate, { profile: 'full', stableVersion: null });+ const byRole = Object.fromEntries(r.from.flatMap(f => f.roles.map(role => [role, f.tag])));+ expect(byRole).toEqual({ 'N-1': 'v0.60.79.0', 'N-10': 'v0.60.70.0', 'N-50': 'v0.60.30.0', '30d': 'v0.60.50.0' });+ expect(r.skipped).toEqual([{ role: 'stable', reason: expect.stringContaining('stable') }]);+ });++ test('a role shared by two picks is one from-version with both roles; too few releases skips N-50 instead of dropping it', () => {+ const few = releases.slice(0, 12);+ const r = resolveFromVersions(few, few[11]!, { profile: 'full', stableVersion: '0.60.2.0' });+ expect(r.skipped.map(s => s.role)).toEqual(['N-50']);+ expect(r.skipped[0]!.reason).toContain('only 11 published releases');+ const stable = r.from.find(f => f.roles.includes('stable'))!;+ expect(stable.tag).toBe('v0.60.2.0');+ const tags = r.from.map(f => f.tag);+ expect(new Set(tags).size).toBe(tags.length);+ });++ test('an unreleased candidate (a pull-request head) upgrades from releases below its version; the pr profile keeps N-1 and N-50', () => {+ const r = resolveFromVersions(releases, { version: '0.60.81.0', published_at: new Date(T0).toISOString() }, { profile: 'pr' });+ expect(r.from.map(f => [f.tag, f.roles])).toEqual([['v0.60.80.0', ['N-1']], ['v0.60.31.0', ['N-50']]]);+ expect(r.skipped).toEqual([]);+ });+});++function gitRepo(): { dir: string; first: string; second: string } {+ const dir = mkdtempSync(join(tmpdir(), 'um-src-'));+ const git = (...args: string[]) => execFileSync('git', ['-C', dir, '-c', 'user.name=t', '-c', '[email protected]', ...args], { encoding: 'utf8' }).trim();+ git('init', '-q', '-b', 'master');+ writeFileSync(join(dir, 'VERSION'), '0.0.1\n');+ writeFileSync(join(dir, 'package.json'), '{"name":"gbrain","version":"0.0.1"}\n');+ git('add', '.'); git('commit', '-qm', 'one');+ const first = git('rev-parse', 'HEAD');+ writeFileSync(join(dir, 'VERSION'), '0.0.2\n');+ git('commit', '-qam', 'two');+ return { dir, first, second: git('rev-parse', 'HEAD') };+}++/** Async on purpose: the fixture serves from this process, so a blocking spawn would starve it. */+async function curl(args: string[]): Promise<{ status: number; stdout: string }> {+ const p = Bun.spawn(['curl', '-sS', '--max-time', '20', ...args], { stdout: 'pipe', stderr: 'pipe' });+ const stdout = await new Response(p.stdout).text();+ return { status: await p.exited, stdout };+}++describe('GitHub fixture', () => {+ test('parses the tarball, codeload and raw paths it serves, and nothing else', () => {+ expect(parseFixturePath('loopback', '/repos/garrytan/gbrain/tarball/v1.2.3.4')).toEqual({ kind: 'tarball', ref: 'v1.2.3.4' });+ expect(parseFixturePath('api.github.com', '/repos/garrytan/gbrain/tarball')).toEqual({ kind: 'tarball', ref: 'HEAD' });+ expect(parseFixturePath('codeload.github.com', '/garrytan/gbrain/tar.gz/master')).toEqual({ kind: 'tarball', ref: 'master' });+ expect(parseFixturePath('raw.githubusercontent.com', '/garrytan/gbrain/refs/heads/master/VERSION')).toEqual({ kind: 'raw', ref: 'master', file: 'VERSION' });+ expect(parseFixturePath('api.github.com', '/repos/garrytan/gbrain/releases/latest')).toEqual({ kind: 'api', ref: 'releases/latest' });+ expect(parseFixturePath('raw.githubusercontent.com', '/someone/else/master/VERSION')).toBeNull();+ expect(parseFixturePath('github.com', '/garrytan/gbrain')).toBeNull();+ });++ test('serves only the refs it names, over the proxy with its CA, and logs the commit behind each answer', async () => {+ const src = gitRepo(), work = mkdtempSync(join(tmpdir(), 'um-fx-'));+ const fx = await startGithubFixture({ source: src.dir, mirrorDir: join(work, 'mirror.git'), archiveDir: join(work, 'archives'), certDir: join(work, 'certs') });+ try {+ fx.setRefs({ HEAD: src.first, 'v0.0.1': src.first });+ const raw = async (ref: string) => (await curl(['--proxy', fx.proxyUrl, '--cacert', fx.caFile, 'https://raw.githubusercontent.com/garrytan/gbrain/' + ref + '/VERSION'])).stdout;+ expect(await raw('master')).toBe('0.0.1\n');+ expect(await raw('v0.0.2')).toBe('404: Not Found');+ fx.setRefs({ HEAD: src.second, 'v0.0.2': src.second });+ expect(await raw('master')).toBe('0.0.2\n');+ expect(await raw('v0.0.1')).toBe('404: Not Found');+ const tar = join(work, 't.tgz');+ expect((await curl(['-o', tar, fx.apiUrl + '/repos/garrytan/gbrain/tarball/v0.0.2'])).status).toBe(0);+ const listing = execFileSync('tar', ['-tzf', tar], { encoding: 'utf8' });+ expect(listing).toContain('garrytan-gbrain-' + src.second.slice(0, 7) + '/VERSION');+ const lsRemote = execFileSync('git', ['ls-remote', fx.mirror], { encoding: 'utf8' });+ expect(lsRemote).toContain(src.second + '\trefs/tags/v0.0.2');+ expect(lsRemote).not.toContain('v0.0.1');+ expect(fx.requests.filter(r => r.status === 200).map(r => r.sha)).toEqual([src.first, src.second, src.second]);+ expect(fx.proxy.every(p => p.action === 'fixture')).toBe(true);+ } finally {+ fx.stop();+ rmSync(work, { recursive: true, force: true }); rmSync(src.dir, { recursive: true, force: true });+ }+ }, 60_000);++ test('refuses every host that is neither GitHub nor allowlisted, and relays a forwarded provider host to its local stand-in', async () => {+ const src = gitRepo(), work = mkdtempSync(join(tmpdir(), 'um-fx-'));+ const provider = Bun.serve({ port: 0, hostname: '127.0.0.1', fetch: async req => Response.json({ path: new URL(req.url).pathname, body: await req.text() }) });+ const fx = await startGithubFixture({ source: src.dir, mirrorDir: join(work, 'mirror.git'), archiveDir: join(work, 'archives'), certDir: join(work, 'certs'), forward: { 'api.voyageai.com': 'http://127.0.0.1:' + provider.port, 'evil.example.com': 'http://127.0.0.1:1' }, allowHosts: [] });+ try {+ const denied = await curl(['--proxy', fx.proxyUrl, '--cacert', fx.caFile, 'https://example.com/']);+ expect(denied.status).not.toBe(0);+ const notForwardable = await curl(['--proxy', fx.proxyUrl, '--cacert', fx.caFile, 'https://evil.example.com/']);+ expect(notForwardable.status).not.toBe(0);+ expect(fx.proxy.filter(p => p.action === 'denied').map(p => p.host)).toEqual(['example.com', 'evil.example.com']);+ const relayed = await curl(['--proxy', fx.proxyUrl, '--cacert', fx.caFile, '-H', 'content-type: application/json', '-d', '{"input":["x"]}', 'https://api.voyageai.com/v1/embeddings']);+ expect(JSON.parse(relayed.stdout)).toEqual({ path: '/v1/embeddings', body: '{"input":["x"]}' });+ } finally {+ fx.stop(); provider.stop(true);+ rmSync(work, { recursive: true, force: true }); rmSync(src.dir, { recursive: true, force: true });+ }+ }, 60_000);++ test('compareInstalledTree finds an installed file that differs from the commit, and one that is missing', () => {+ const src = gitRepo(), installed = mkdtempSync(join(tmpdir(), 'um-inst-'));+ try {+ execFileSync('sh', ['-c', 'git -C "$0" archive ' + src.second + ' | tar -x -C "$1"', src.dir, installed]);+ expect(compareInstalledTree(src.dir, src.second, installed)).toEqual({ checked: 2, mismatches: [], missing: [] });+ expect(compareInstalledTree(src.dir, src.first, installed).mismatches).toEqual(['VERSION']);+ unlinkSync(join(installed, 'package.json'));+ expect(compareInstalledTree(src.dir, src.second, installed)).toEqual({ checked: 1, mismatches: [], missing: ['package.json'] });+ } finally {+ rmSync(installed, { recursive: true, force: true }); rmSync(src.dir, { recursive: true, force: true });+ }+ });+});++describe('preservation and mixed-version snapshots (real PGLite)', () => {+ test('timestamps and bookkeeping changes are not differences; canonical changes are', async () => {+ const db = await PGlite.create();+ try {+ await db.exec(`+ CREATE TABLE config (key text PRIMARY KEY, value text);+ INSERT INTO config VALUES ('version', '270');+ CREATE TABLE sources (id text PRIMARY KEY, name text, archived boolean DEFAULT false);+ INSERT INTO sources (id, name) VALUES ('default', 'default');+ CREATE TABLE pages (id serial PRIMARY KEY, source_id text, slug text, type text, title text, content_hash text, frontmatter jsonb, deleted_at timestamptz, updated_at timestamptz DEFAULT now());+ INSERT INTO pages (source_id, slug, type, title, content_hash, frontmatter) VALUES+ ('default', 'concepts/alpha-example', 'concept', 'Alpha', 'h1', '{"b":1,"a":2}'),+ ('default', 'notes/gone-example', 'note', 'Gone', 'h2', '{}');+ UPDATE pages SET deleted_at = now() WHERE slug = 'notes/gone-example';+ CREATE TABLE facts (id serial PRIMARY KEY, source_id text, entity_slug text, fact text, row_num int, confidence real, expired_at timestamptz);+ INSERT INTO facts (source_id, entity_slug, fact, row_num, confidence) VALUES ('default', 'concepts/alpha-example', 'alpha ships', 1, 0.9);+ `);+ const query: Query = async (sql, params) => (await db.query(sql, params ?? [])).rows as Record<string, unknown>[];+ const before = await takeSnapshot(query, { catalog: true });+ expect(before.content.pages!.rows.map(r => [r.slug, r.deleted])).toEqual([['concepts/alpha-example', false], ['notes/gone-example', true]]);+ expect(before.catalog!.schema_version).toEqual({ version: '270' });++ await db.exec("UPDATE pages SET updated_at = now() + interval '1 day'; ALTER TABLE pages ADD COLUMN embedding_model text; UPDATE pages SET frontmatter = '{\"a\":2,\"b\":1}' WHERE slug = 'concepts/alpha-example'");+ const bookkeeping = await takeSnapshot(query, { catalog: true });+ expect(diffContent(before, bookkeeping)).toEqual([]);+ expect(diffCatalog(before, bookkeeping).map(d => d.where)).toEqual(['columns pages.embedding_model']);++ await db.exec("UPDATE pages SET title = 'Alpha (changed)' WHERE slug = 'concepts/alpha-example'; UPDATE pages SET deleted_at = NULL WHERE slug = 'notes/gone-example'; UPDATE facts SET expired_at = now(); ALTER TABLE pages DROP COLUMN content_hash");+ const after = await takeSnapshot(query, { catalog: false });+ expect(diffContent(before, after).map(d => d.kind + ' ' + d.where)).toEqual([+ 'column_dropped pages.content_hash',+ 'field_changed pages ["default","concepts/alpha-example"] title',+ 'field_changed pages ["default","notes/gone-example"] deleted',+ 'field_changed facts ["default","concepts/alpha-example","alpha ships",1] expired',+ ]);+ } finally {+ await db.close();+ }+ }, 60_000);+});++const cell = (id: string, verdict: CellSummary['verdict'], extra: Partial<CellSummary> = {}): CellSummary => ({ id, from: 'v0.60.1.0', roles: ['N-1'], shape: 'pglite keyless repo-less', verdict, open: [], excepted: [], ...extra });++describe('verdicts', () => {+ test('doctor: a failing check outside the skill category fails; skill checks never do; an alert verdict wins when present', () => {+ expect(doctorVerdict({ checks: [{ name: 'schema_version', status: 'ok' }, { name: 'skill_health', status: 'fail', category: 'skill' }] })).toEqual({ ok: true, failing: [], source: 'legacy' });+ expect(doctorVerdict({ checks: [{ name: 'minions_migration', status: 'fail', message: 'pending' }] })).toMatchObject({ ok: false, failing: ['minions_migration: pending'] });+ expect(doctorVerdict(null).ok).toBe(false);+ expect(doctorVerdict({ alert: { level: 'none', items: [] }, checks: [{ name: 'x', status: 'fail' }] })).toEqual({ ok: true, failing: [], source: 'alert' });+ expect(doctorVerdict({ alert: { level: 'page', items: [{ code: 'schema_behind' }] } })).toEqual({ ok: false, failing: ['page', 'schema_behind'], source: 'alert' });+ });++ test('known exceptions name explicit releases and an issue; the shipped list is valid', () => {+ const good = { id: 'x', check: 'preservation', from: ['v0.59.2.0'], issue: 'https://github.com/garrytan/gbrain/issues/1', reason: 'the old release rewrites every page' };+ expect(validateKnownExceptions([good])).toEqual([]);+ expect(validateKnownExceptions([{ ...good, from: ['v0.59.*'] }])[0]).toContain('no wildcards');+ expect(validateKnownExceptions([{ ...good, from: [] }])[0]).toContain('explicit release tags');+ expect(validateKnownExceptions([{ ...good, issue: 'https://example.com/1' }])[0]).toContain('issue');+ expect(validateKnownExceptions([{ ...good, check: 'setup' }])[0]).toContain('never excepted');+ expect(validateKnownExceptions([{ ...good, check: 'nope' }])[0]).toContain('check must be one of');+ for (const e of loadKnownExceptions()) expect(Object.keys(CHECKS)).toContain(e.check);+ });++ test('a cell passes only with no open failures; an exception covers only its own check and releases', () => {+ const ex = [{ id: 'x', check: 'preservation' as const, from: ['v0.59.2.0'], issue: 'https://github.com/garrytan/gbrain/issues/1', reason: 'r'.repeat(20) }];+ expect(judgeCell('v0.60.1.0', [], ex).verdict).toBe('pass');+ expect(judgeCell('v0.59.2.0', [{ check: 'preservation', detail: 'd' }], ex).verdict).toBe('known_exception');+ expect(judgeCell('v0.59.3.0', [{ check: 'preservation', detail: 'd' }], ex).verdict).toBe('fail');+ expect(judgeCell('v0.59.2.0', [{ check: 'preservation', detail: 'd' }, { check: 'doctor', detail: 'd' }], ex)).toMatchObject({ verdict: 'fail', open: [{ check: 'doctor' }] });+ expect(judgeCell('v0.59.2.0', [{ check: 'setup', detail: 'init exited 1' }], ex).verdict).toBe('error');+ });++ test('a run is red on any failing, missing, faulted or foreign cell; an old release that cannot be set up, or a held door, holds instead of passing', () => {+ expect(summarize(['a', 'b'], [cell('a', 'pass'), cell('b', 'known_exception')])).toMatchObject({ green: true, red: [], holds: [] });+ expect(summarize(['a', 'b'], [cell('a', 'pass')]).red.map(c => [c.id, c.verdict])).toEqual([['b', 'missing']]);+ expect(summarize(['a'], [cell('a', 'fail')]).green).toBe(false);+ expect(summarize(['a'], [cell('a', 'pass', { fault: 'corrupt-after-upgrade' })]).red.map(c => c.id)).toEqual(['a']);+ expect(summarize(['a'], [cell('a', 'error')])).toMatchObject({ green: false, red: [], holds: [{ id: 'a' }] });++ const plan = { harness: { sha: 'h' }, candidate: { sha: 'c' }, cells: ['a'], profile: 'full', from: [], skipped: [] } as unknown as Plan;+ const receipt = (over: Record<string, unknown> = {}) => ({ schema: 'gbrain-upgrade-matrix-cell/1', id: 'a', harness_sha: 'h', candidate: { sha: 'c' }, from: { tag: 'v0.60.1.0', roles: ['N-1'] }, shape: { engine: 'pglite', keys: 'keyless', brain: 'repo-less' }, verdict: 'pass', failures: [], known_exceptions: [], fault: null, ...over });+ expect(buildSummary(plan, [receipt()]).status).toBe('green');+ expect(buildSummary(plan, [receipt({ verdict: 'error', failures: [{ check: 'setup', detail: 'x' }] })]).status).toBe('hold');+ expect(buildSummary(plan, [receipt({ candidate: { sha: 'other' } })]).status).toBe('red');+ const door = (verdict: string) => ({ schema: 'gbrain-upgrade-matrix-door/1', door: 'hermes', harness_sha: 'h', candidate: { sha: 'c' }, verdict });+ expect(buildSummary(plan, [receipt(), door('hold')])).toMatchObject({ status: 'hold', holds: ['door:hermes'] });+ expect(buildSummary(plan, [receipt(), door('fail')]).status).toBe('red');+ });+});