Files
gbrain/test/core/cycle.test.ts
T
3c032d79ec v0.26.0 feat: GBrain — MCP Keys OAuth 2.1 + HTTP server + admin dashboard (#358)
* feat: OAuth 2.1 schema tables + shared token utilities

Add oauth_clients, oauth_tokens, oauth_codes tables to both PGLite and
Postgres schemas. Migration v5 creates tables for existing databases.
PGLite now includes auth infrastructure (access_tokens, mcp_request_log,
OAuth tables) because `serve --http` makes it network-accessible.

Extract hashToken() and generateToken() to src/core/utils.ts for DRY
reuse across auth.ts and oauth-provider.ts.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: GBrainOAuthProvider — MCP SDK OAuthServerProvider implementation

Implements OAuthServerProvider backed by raw SQL (PGLite or Postgres).
Supports client credentials, authorization code with PKCE, token refresh
with rotation, revocation, and legacy access_tokens fallback.

Key decisions from eng review:
- Uses raw SQL connection, not BrainEngine (OAuth is infrastructure)
- All tokens/secrets SHA-256 hashed before storage
- Legacy tokens grandfathered as read+write+admin
- sweepExpiredTokens() wrapped in try/catch (non-blocking startup)
- Client credentials: no refresh token per RFC 6749 4.4.3

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: scope + localOnly annotations on all 30 operations

Add AuthInfo, scope ('read'|'write'|'admin'), and localOnly fields to
Operation interface. Per-operation audit:
- 14 read ops, 9 write ops, 2 admin ops, 4 admin+localOnly ops
- sync_brain, file_upload, file_list, file_url: admin + localOnly
- Scope enforcement happens in serve-http.ts before handler dispatch

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: HTTP MCP server with OAuth 2.1 + 27 OAuth tests

gbrain serve --http starts Express 5 server with:
- MCP SDK mcpAuthRouter (authorize, token, register, revoke endpoints)
- Custom client_credentials handler (SDK doesn't support CC grant)
- Bearer auth + scope enforcement on /mcp tool calls
- Admin dashboard auth via HTTP-only cookie + bootstrap token
- SSE live activity feed at /admin/events
- DCR default OFF (--enable-dcr to enable)
- Rate limiting on /token (50/15min)
- localOnly operations excluded from HTTP

CLI: gbrain serve --http [--port 3131] [--token-ttl 3600] [--enable-dcr]

Dependencies: express@5.2.1, express-rate-limit@7.5.1, cors@2.8.6
SDK pinned to exact 1.29.0 (was ^1.0.0)

27 new tests covering OAuth provider, scope enforcement, auth code flow,
refresh rotation, token revocation, legacy fallback, and sweep.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: React admin dashboard — 7 screens, dark theme, Krug-designed

Admin SPA at /admin with client-side routing (#login, #dashboard,
#agents, #log). Built with Vite + React, served from admin/dist/.

Screens:
- Login: one field, one button, zero happy talk
- Dashboard: metrics bar, SSE live activity feed, token health panel
- Agents: table with scopes/badges, + Register Agent button
- Register: modal form (name, scopes), 3 mindless choices
- Credentials: full-screen modal, copy buttons, download JSON, warning
- Request Log: paginated table (50/page), time-relative timestamps
- Agent Detail: slide-out drawer, config export tabs (Perplexity/Claude/JSON)

Design tokens: #0a0a0f bg, Inter + JetBrains Mono, 4-32px spacing.
Build: bun run build:admin (Vite, 65KB gzipped).
Admin API: /admin/api/register-client endpoint for dashboard registration.
SPA serving: Express static + index.html fallback for client-side routing.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore: add admin SPA lockfile

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore: bump version and changelog (v1.0.0.0)

Milestone release: multi-agent GBrain with OAuth 2.1, HTTP server,
and React admin dashboard. See CHANGELOG.md for details.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* docs: update project documentation for v1.0.0.0

Sync README, CLAUDE.md, and docs/mcp/ with the OAuth 2.1 + HTTP server
+ admin dashboard surface that shipped in v1.0.0.0.

- README.md: new "Remote MCP with OAuth 2.1" section covering
  gbrain serve --http, admin dashboard, scoped operations, legacy
  bearer fallback; add serve --http + auth notes to the commands
  reference.
- CLAUDE.md: add src/commands/serve-http.ts, src/core/oauth-provider.ts,
  admin/ directory as key files; document scope + localOnly additions
  to Operation contract; add oauth.test.ts (27 cases) to the test list;
  add v1.0.0 key-commands section clarifying that OAuth client
  registration is via the /admin dashboard or SDK (no CLI subcommand).
- docs/mcp/DEPLOY.md: promote --http as the recommended remote path,
  add OAuth 2.1 Setup section, list ChatGPT in supported clients,
  remove the "not yet implemented" footer.
- docs/mcp/CHATGPT.md (new): unblocks the P0 TODO. Full ChatGPT
  connector setup via OAuth 2.1 + PKCE.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat: wire gbrain auth subcommand with OAuth register-client

Previously auth.ts was a standalone script invoked via
`bun run src/commands/auth.ts`. CHANGELOG and README documented
`gbrain auth ...` commands that didn't actually work.

- Export `runAuth(args)` from auth.ts (keeps standalone entry intact
  via `import.meta.url === file://${process.argv[1]}` check)
- Add `auth` to CLI_ONLY + dispatch in handleCliOnly
- New subcommand `gbrain auth register-client <name> [--grant-types]
  [--scopes]` wraps GBrainOAuthProvider.registerClientManual
- Lazy DB check: only subcommands that need DATABASE_URL error out

Now the documented CLI flow works end to end:
  gbrain auth register-client perplexity --grant-types client_credentials --scopes "read write"
  gbrain serve --http --port 3131

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* docs: reflect wired gbrain auth register-client CLI

After /ship, the doc subagent wrote docs assuming `gbrain auth
register-client` did not exist (it said so explicitly in CLAUDE.md:184).
A follow-up commit (c4a86ce) wired it into src/cli.ts + src/commands/auth.ts.
These docs were now contradicting reality.

- CLAUDE.md: removed "There is no gbrain auth register-client CLI
  subcommand" claim, documented the three registration paths
  (CLI / dashboard / SDK).
- README.md: replaced `bun run src/commands/auth.ts` hint with
  `gbrain auth create|list|revoke|test` and `gbrain auth register-client`.
- docs/mcp/DEPLOY.md: added CLI registration example above the
  programmatic example.
- TODOS.md: moved "ChatGPT MCP support (OAuth 2.1)" P0 item to
  Completed with v1.0.0.0 completion note. Closes the P0 that had been
  blocking the "every AI client" promise since v0.6.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: enable RLS on OAuth tables + loosen v24-exact test assertion

CI Tier 1 (Mechanical) was failing on 4 E2E tests after the v0.18.1 RLS
hardening landed on master (PR #343). Our v25 oauth_infrastructure migration
adds 3 new public tables (oauth_clients, oauth_tokens, oauth_codes) but
didn't enable RLS, so gbrain doctor's new check flagged them and the
"RLS on every public table" assertion failed.

Fixes:
- src/schema.sql: ALTER TABLE ... ENABLE ROW LEVEL SECURITY for the 3 OAuth
  tables inside the existing BYPASSRLS-gated DO block (fresh installs).
- src/core/migrate.ts v25: append a BYPASSRLS-gated DO block after the OAuth
  CREATE TABLE statements (existing installs on upgrade). Mirrors the v24
  rls_backfill gating pattern — RAISE WARNING if the current role lacks
  BYPASSRLS, so migrations don't silently lock the operator out.
- src/core/schema-embedded.ts: regenerated via `bun run build:schema`.
- test/e2e/mechanical.test.ts: one unrelated v24 test asserted the post-
  migration version equals exactly '24'. That breaks when any later
  migration exists (like our v25). Relaxed to `>= 24` since the test's
  intent is "v24 didn't abort the chain", not "v24 is the final version".

Verified locally: 78/78 E2E tests pass against real Postgres 16 + pgvector.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* chore: regenerate llms-full.txt for v1.0.0 docs

CI test/build-llms.test.ts > committed llms.txt + llms-full.txt match
current generator output failed. The committed llms-full.txt was built
before the v1.0.0 doc updates landed (OAuth 2.1 README section, new
docs/mcp/CHATGPT.md, CLAUDE.md serve-http references, etc.), so the
regen-drift guard flagged it.

Ran `bun run build:llms`. llms.txt is unchanged (skinny index still
matches); llms-full.txt picks up 166 net-new lines of bundled content.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* connected-gbrains PR 0 — minimal runtime (mounts, registry, aggregated RESOLVER) (#372)

* feat(mounts): connected-gbrains PR 0 foundation — registry + resolver + CLI

Lays the foundation for connected gbrains (v0.19.0) per the approved plan.
This is PR 0 — minimal runtime for direct-transport, path-mounted brains.

What this slice ships:
- src/core/brain-registry.ts — keyed BrainRegistry with lazy engine init,
  schema-validated mounts.json loader, DuplicateMountPathError (load-bearing
  identity check per Codex finding #9 correction), UnknownBrainError with
  actionable available-id list. Pure: no AsyncLocalStorage, no singleton
  mutation. ~280 LOC.

- src/core/brain-resolver.ts — 6-tier brain-id resolution mirroring
  v0.18.0's source-resolver.ts so agents learn ONE mental model:
    1. --brain <id>     2. GBRAIN_BRAIN_ID env      3. .gbrain-mount dotfile
    4. longest-path match over registered mounts    5. (reserved v2 default)
    6. 'host' fallback
  Orthogonal to --source: --brain picks which DB, --source picks the repo
  within that DB. Corruption-resistant: mounts.json load failures fall
  through to 'host' instead of breaking every CLI invocation.

- src/commands/mounts.ts — `gbrain mounts add|list|remove` (direct transport
  only). Validates on add (path exists on disk, id regex, no dupes). WARNS
  but does not block on same db_url/db_path across ids (teams may
  legitimately alias a remote brain). Password redaction in list output.
  Atomic write via temp+rename. 0600 perms. PR 1 adds pin/sync/enable;
  PR 2 adds --mcp-url + OAuth.

- src/cli.ts — wires `gbrain mounts` into handleCliOnly (no DB required
  for the config-only subcommands).

- test/brain-registry.test.ts (28 cases): schema validation across every
  malformed-input branch, ALS-free resolution, duplicate id + path detection,
  disabled-mount exclusion, UnknownBrainError context.

- test/brain-resolver.test.ts (22 cases): priority order (explicit > env >
  dotfile > path-prefix > fallback), dotfile walk-up, malformed dotfile
  recovery, longest-prefix match, sibling-path false-positive guard,
  loader-failure defense.

- test/mounts-cli.test.ts (17 cases): parseAddArgs surface, redactUrl,
  atomic write, add/list/remove roundtrip via temp HOME.

67 new tests, all green. Typecheck clean. Depends on mcp-key-mgmt (base
branch) for the OAuth/scope annotations that PR 2 will leverage.

Next in this branch: PR 0 still needs (a) the deep host-brain-bias audit
(postgres-engine internal singleton fallback + a few operations.ts
callers), (b) OperationContext threading to make ctx.brainId populated at
dispatch, (c) composeResolvers + composeManifests, (d) aggregated
~/.gbrain/mounts-cache/ for host-agent runtime ownership.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs(mounts): brains-and-sources mental model + agent routing convention

Two orthogonal axes organize GBrain knowledge. Users AND agents need to
understand both, or queries misroute silently.

  --brain  → WHICH DATABASE    (host + mounts)
  --source → WHICH REPO IN DB  (v0.18.0 sources: wiki, gstack, ...)

Both axes use the same 6-tier resolution (explicit > env > dotfile >
path-prefix > default > fallback), so learning one teaches both.

Ships:

- docs/architecture/brains-and-sources.md — canonical mental model doc.
  Covers four topologies with ASCII diagrams:
    1. Single-person developer (one brain, one source)
    2. Personal brain with multiple repos (one brain, N sources)
    3. Personal + one team brain mount (2 brains)
    4. Senior user with multiple team memberships (N mounted team brains
       alongside personal) — the CEO-class topology
  Explicit "when to move each axis" decision table. Generic example names
  throughout per the project's privacy rule.

- skills/conventions/brain-routing.md — agent-facing decision table.
  Rules for when to switch brain (team-owned question, explicit name,
  data owner changes) vs switch source (working in a repo, topic scoped
  to one repo). Cross-brain federation is latent-space only in v0.19 —
  the agent fans out; the DB never does. Anti-patterns listed: silent
  brain jumps, writing to host when data is team-owned, missing brain
  prefix in citations, ignoring .gbrain-mount dotfiles.

- CLAUDE.md — adds "Two organizational axes (read this first)" section
  at the top pointing at both new docs.

- AGENTS.md — adds brains-and-sources.md + brain-routing.md to the
  "read this order" (positions 3 and 4, before RESOLVER.md).

- skills/RESOLVER.md — adds brain-routing.md to the Conventions section
  so it appears alongside quality.md, brain-first.md, subagent-routing.md.

No code changes. Pre-existing check-resolvable warnings unchanged (2
warnings on base unrelated to this work). 67 PR-0 tests still green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(mounts): thread brainId through OperationContext + subagent chain

PR 0 plumbing for connected gbrains. Adds an optional brainId field that
identifies which database an operation targets and ensures subagents
inherit the parent job's brain instead of process-wide defaults. No
dispatch-path changes in this commit — that is PR 1 (registry wiring at
MCP + CLI entry points). The fields exist so callers can set them now
and downstream code respects them.

Changes:

- src/core/operations.ts: OperationContext grows `brainId?: string`.
  Optional for back-compat. 'host' is the implicit default when absent.
  Orthogonal to v0.18.0's source_id (source = which repo within the
  brain, brain = which database). See docs/architecture/brains-and-sources.md.

- src/core/minions/types.ts: SubagentHandlerData gains `brain_id?: string`.
  Parent jobs set this when submitting a child subagent to lock the
  child into a specific brain. Omitted = host (unchanged behavior).

- src/core/minions/handlers/subagent.ts: buildBrainTools call site
  reads data.brain_id and passes it through. Child subagents spawned
  from this handler will see the same brainId unless they override in
  their own data.

- src/core/minions/tools/brain-allowlist.ts: BuildBrainToolsOpts +
  OpContextDeps grow brainId; buildOpContext stamps it on every
  OperationContext the subagent builds for tool calls. Addresses Codex
  finding #6 (brain-allowlist hardwired parent config without brain
  awareness, so switching brain only in subagent.ts was not enough).

Tests: 166 affected tests green (subagent suite + minions + brain
registry + resolver). Typecheck clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(mounts): composeResolvers + composeManifests + aggregated cache

The runtime ownership seam for connected gbrains (Codex finding #3 from
plan review): check-resolvable.ts VALIDATES RESOLVER.md; it does not
DISPATCH skills. Host agents (Wintermute/OpenClaw/Claude Code) read
skills/RESOLVER.md directly to route user requests. Without an aggregated
resolver, mounted team brains cannot contribute skills to the host
agent's routing table.

This commit adds the aggregation:

- src/core/mounts-cache.ts (NEW): pure composeResolvers + composeManifests
  functions plus filesystem writers for ~/.gbrain/mounts-cache/. The
  aggregated files carry every host skill plus every mount skill,
  namespace-prefixed (e.g. `yc-media::ingest`). Host skills always beat
  a same-named mount skill (locked decision 1); bare-name collisions
  between two mounts surface as structured ambiguity info so doctor can
  warn (PR 1).

  Also addresses Codex finding #8: manifests compose alongside the
  resolver, else doctor conformance breaks on remote skills.

- src/commands/mounts.ts: refreshMountsCache() called on `mounts add`
  and `mounts remove` (the latter clearing the cache entirely when the
  last mount goes away). Uses findRepoRoot() to locate the host skills
  dir; skips with a stderr note when run outside a gbrain repo so the
  user isn't confused by a "cache not refreshed" error in the wrong
  cwd.

- test/mounts-cache.test.ts (NEW): 23 unit tests covering empty world,
  host-only, single mount, two-mount ambiguity, host-shadows-mount,
  disabled mount excluded, missing RESOLVER.md is a no-op, manifest
  composition with same-name collision, render shape, atomic rewrite,
  clear on missing dir.

Output format for ~/.gbrain/mounts-cache/RESOLVER.md adds a Brain column
so host agents can see which brain each trigger routes to at a glance,
plus Shadows and Ambiguous sections when those conditions exist.

Tests: 90 PR 0 tests green (brain-registry + resolver + mounts-cache +
mounts-cli). Full suite regression pending in task 11.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(mounts): force instance-level pool for mount brains + CI guard

Closes the silent-singleton-share bug Codex flagged as finding #1 from
the plan review: two direct-transport mounts with different Postgres
URLs would both fall through postgres-engine.ts's `get sql()` getter to
db.getConnection() and quietly share whichever singleton connected
first. Your yc-media writes end up in garrys-list or vice versa. No
error at the call site — just wrong data.

The fix:

- src/core/brain-registry.ts: initMountBrain now passes poolSize when
  calling engine.connect(). That forces postgres-engine.ts:33-60 down
  the instance-level path (setting this._sql) instead of the module
  singleton path (calling db.connect). Hard-coded 5 for PR 0 — per-mount
  override is PR 1. PGLite ignores poolSize (no pool concept), so this
  is Postgres-specific.

  Host brain still uses the singleton path via initHostBrain (unchanged).
  That is fine for PR 0: the singleton is "the host's one connection"
  by definition. PR 1 removes the singleton entirely once every CLI
  command is engine-injectable.

- scripts/check-no-legacy-getconnection.sh (NEW): CI grep guard against
  new db.getConnection() / db.connect() calls landing in src/core/ or
  src/commands/ (the multi-brain dispatch surface). Has an explicit
  ALLOWED list grandfathering today's legitimate callers, each marked
  "PR 1 refactors" so the list shrinks over time. Skips comment lines
  so the grep doesn't trip on doc references to the old pattern.

- package.json: scripts.test chains the new guard after the existing
  check-jsonb-pattern + check-progress-to-stdout guards. `bun run test`
  now fails the build on singleton regression.

Tests: 295 affected pass (registry, resolver, mounts-cache, mounts-cli,
minions, pglite-engine). Typecheck clean. CI guard reports "ok: no new
singleton callers" on current tree.

Left for PR 1: remove the singleton fallback in postgres-engine.ts's
`get sql()` entirely; refactor src/commands/doctor.ts, files.ts,
repair-jsonb.ts, serve-http.ts, init.ts, and the 3 localOnly ops in
operations.ts (file_list, file_upload, file_url) to accept ctx.engine
explicitly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(mounts): codex review findings — namespace survives shadow + atomic tmp names + honest PR 0 docstrings

Codex outside-voice review on PR #372 found 5 issues. Real bugs fixed, overclaims
rewritten. Details:

P2 (real bug): composeResolvers and composeManifests were silently dropping
mount entries when a host skill shared the short name, which made the
namespace-qualified form `<mount>::<skill>` unreachable once host defined
the same short name. That defeated the entire namespace-disambiguation
model — if host had `ingest`, no mount could ship an `ingest` skill even
with explicit `yc-media::ingest`. Fix: always keep namespace-qualified
mount entries in the composed output. Shadow tracking moves to metadata
(`shadows[]`) that doctor can warn on, but never drops routing.

  Before:  host ingest + yc-media ingest → only 1 entry (host), yc-media::ingest unreachable
  After:   host ingest + yc-media ingest → 2 entries: bare `ingest` = host, `yc-media::ingest` = mount
  Verified live: gbrain mounts add of a mount with `ingest` now shows
  `team-demo::ingest` alongside host `ingest` in the aggregated manifest.

P1 (real bug): writeMountsFile + writeMountsCache used fixed `.tmp`
filenames. Two concurrent `gbrain mounts add` invocations (e.g. from
parallel terminals or CI) would clobber each other's temp file and
one writer's update would be lost. Fix: tmp filenames include
`process.pid + random suffix` so every writer has its own scratch file.
The atomic rename is self-contained per-writer. (Full lock + read-modify-
write safety deferred to PR 1 under `gbrain mounts sync --lock`.)

P1 (honesty): `SubagentHandlerData.brain_id` +
`BuildBrainToolsOpts.brainId` docstrings claimed child jobs inherit the
parent's brain and brain tools target the resolved brain. True for the
`ctx.brainId` field only — `ctx.engine` is still the worker's base
engine at dispatch time because `buildOpContext` doesn't yet do the
registry lookup, and `gbrain agent run` doesn't yet accept `--brain` to
populate the field on submission. Rewrote both docstrings to state the
PR 0 behavior explicitly (field plumbed, engine routing is PR 1) so
nobody reads the code thinking multi-brain subagents already work.

Also cleaned up two `require('fs')` runtime imports left over from the
initial PR — swapped for ESM named imports (renameSync). Pre-existing
style issue surfaced by the self-review pass.

Tests: 90 PR-0 tests pass. Updated two shadow-related test cases to
assert the corrected semantics (both entries survive, host wins bare
name, namespace form routes to mount).

Not fixed in this commit (documented as known PR 0 limitations):
- `file_list` / `file_upload` / `file_url` in operations.ts still hit the
  singleton (localOnly + admin, never reachable from HTTP MCP — safe in
  practice, refactor in PR 1 alongside command-level cleanups).
- writeMountsCache's two-file swap (RESOLVER.md + manifest.json) is not
  atomic across files; readers can briefly observe mismatched pairs.
  Acceptable because the cache is recomputable at any time from
  mounts.json. Generation-directory swap is PR 1 work.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(tests): bump hook timeouts for 21-migration PGLite init under full-suite load

Root cause of 19 pre-existing full-suite flakes (CHANGELOG v0.18.0 noted
"17 pre-existing master timeouts"): every PGLite test does

  beforeAll/beforeEach(async () => {
    engine = new PGLiteEngine();
    await engine.connect({});
    await engine.initSchema();  // runs 21 migrations through v0.18.2
  });

In isolation this takes ~5s. Under full-suite contention (128 files,
process-shared FS and CPU) it exceeds bun's default 5000ms hook timeout,
beforeEach times out, engine stays undefined, then afterEach crashes
with `TypeError: undefined is not an object (evaluating 'engine.disconnect')`.
That single hook failure reports as the whole test "failing" even though
the test body never executed, which is why the failure count sometimes
looked inflated compared to the number of genuinely-broken tests.

Fix applied across 7 test files:

- Raise setup hook timeout to 30_000 (6x the default) — gives migration
  init enough headroom even under worst-case load without masking real
  regressions in a post-migration test.
- Raise teardown hook timeout to 15_000 — engine.disconnect() is usually
  fast but can stall when PGLite's WASM runtime is still completing a
  migration at shutdown.
- Add `if (engine) await engine.disconnect()` guard so afterEach doesn't
  double-fault when beforeEach already failed. This was the source of
  the opaque "(unnamed)" failures — they were disconnect crashes,
  not test-body failures.

Files:
  test/dream.test.ts                (5 beforeEach + 5 afterEach blocks)
  test/orphans.test.ts              (1 pair)
  test/brain-allowlist.test.ts      (1 pair)
  test/oauth.test.ts                (1 pair)
  test/extract-db.test.ts           (1 pair)
  test/multi-source-integration.test.ts (1 pair)
  test/core/cycle.test.ts           (1 pair)

Results on the merged PR 0 branch:
  Before: 2175 pass / 20 fail / 3 errors
  After:  2281 pass /  0 fail / 0 errors    (+106 tests running that
                                             were previously blocked
                                             by the timed-out hooks)

No changes to production code. No test assertions changed. Just
timeout-bump + null-guard discipline that should have been in these
hooks from the start. The real longer-term fix is reusing an engine
across tests where possible (brain-allowlist.test.ts already does this
via beforeAll+DELETE-pages pattern), but that's per-file structural
work — out of scope for this cleanup.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: regenerate llms-full.txt for brains-and-sources + brain-routing docs

The test/build-llms.test.ts test validates that the committed llms.txt
and llms-full.txt match the current generator output. PR 0 added
docs/architecture/brains-and-sources.md content paths and updated
CLAUDE.md + skills/RESOLVER.md in earlier commits, but the generated
bundle file wasn't regenerated alongside. This caused one of the 20
fails we chased down today — a straight content mismatch, not a runtime
bug. Running `bun run build:llms` picks up the new section content so
the bundle matches the sources again.

No functional change. Only the compiled doc bundle.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* Bump version 1.0.0.0 → 0.22.0

OAuth + admin dashboard is meaningful but doesn't quite warrant the
major-version reset to 1.0. Renumber as v0.22.0, slotting cleanly above
master's v0.21.0 (Cathedral II).

Touched:
- VERSION, package.json: 1.0.0.0 → 0.22.0
- CHANGELOG.md: heading + "BEFORE/AFTER v1.0" table + "To take advantage"
  + "pre-v1.0" all renamed. Narrative voice unchanged otherwise.
- TODOS.md: ChatGPT MCP completion stamp updated to v0.22.0 (2026-04-25).
- CLAUDE.md, README.md, docs/mcp/{DEPLOY,CHATGPT}.md, src/schema.sql,
  src/core/schema-embedded.ts: every reader-facing v1.0.0 reference
  rewritten to v0.22.0 / pre-v0.22 in the same place.
- llms-full.txt: regenerated to match.

Slug-test occurrences of "v1.0.0" (`test/slug-validation.test.ts`,
`test/file-upload-security.test.ts`) and the `HOMEBREW_FOR_PERSONAL_AI`
roadmap reference to a future v1.0 vision left intact — those are
unrelated to this branch's release version.

Typecheck clean. cli + oauth + slug + file-upload tests pass (106 tests).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* v0.26.0 fix: 4 security findings from /cso pass + version bump

Bumped 0.22.0 → 0.26.0 to slot above master's v0.21 chain with headroom
for v0.23/0.24/0.25 to ship from master between now and merge.

Security fixes (all from CSO finding writeups):

#1 cookie-parser middleware — admin dashboard auth was silently broken.
   Express 5 has no built-in cookie parsing; req.cookies was always
   undefined, so /admin/login set the cookie but every subsequent admin
   API call returned 401. Added cookie-parser@^1.4.7 + @types/cookie-parser
   as direct + dev deps. app.use(cookieParser()) wired before CORS.

#2 + #3 TOCTOU races — exchangeAuthorizationCode and exchangeRefreshToken
   used SELECT-then-DELETE, letting concurrent requests with the same
   code/refresh both pass the SELECT before either ran DELETE, both
   issuing token pairs. Switched to atomic DELETE...RETURNING. RFC 6749
   §10.5 (codes) + §10.4 (refresh detection) violations closed. Added
   regression tests that fire 10 concurrent exchanges and assert exactly
   one wins — both pass.

#5 pgArray escape + DCR redirect_uri validation — pgArray() did
   `arr.join(',')` with no escaping, so an element containing a comma
   would be parsed by Postgres as TWO array elements. With --enable-dcr
   on, this could smuggle a second redirect_uri into a registered client
   and steal auth codes. Now every element is double-quoted with `"` and
   `\` escaped. Added validateRedirectUri() per RFC 6749 §3.1.2.1:
   redirect_uris must be https:// or loopback (localhost / 127.0.0.1).
   Wired into the DCR registerClient path; CLI registration trusts the
   operator and bypasses. Regression test confirms a comma-in-URI element
   round-trips as 1 element, not 2.

#6 --public-url flag — issuerUrl was hardcoded to http://localhost:{port}.
   Behind reverse proxies / ngrok / production deploys, the issuer claim
   in tokens wouldn't match the discovery URL clients hit (RFC 8414 §3.3).
   New --public-url URL flag on `gbrain serve --http`, propagates through
   serve.ts → serve-http.ts → ServeHttpOptions.publicUrl → issuerUrl.
   Startup banner surfaces the configured issuer.

Findings #4 (admin requests filter dead code), #7 (admin register-client
hardcoded grant_types), #8 (legacy token grandfathering posture) are
documentation / minor functional fixes and are deferred per user direction.

Tests: oauth.test.ts now 34 cases (was 27). 7 new:
- single-use TOCTOU regression (10 concurrent code exchanges)
- single-use TOCTOU regression (10 concurrent refresh exchanges)
- redirect_uri http://localhost passes
- redirect_uri https://example.com passes
- redirect_uri http://example.com (non-loopback plaintext) rejected
- redirect_uri non-URL rejected
- redirect_uri with embedded comma stored as single element

Files:
- VERSION, package.json: 0.22.0 → 0.26.0
- CHANGELOG.md: heading + table + "To take advantage" + "pre-v0.22" → v0.26;
  new "Security hardening (post-/cso pass)" subsection at top of itemized
  changes; CLI flag list updated for --public-url.
- src/core/oauth-provider.ts: pgArray escape, validateRedirectUri,
  registerClient enforces validation, DELETE...RETURNING in
  exchangeAuthorizationCode + exchangeRefreshToken.
- src/commands/serve-http.ts: cookie-parser import + wire-up,
  publicUrl option, issuerUrl honors it, startup banner shows issuer.
- src/commands/serve.ts: parses --public-url and threads through.
- src/cli.ts: help text adds --public-url URL flag.
- test/oauth.test.ts: +7 regression tests (now 34 total).
- llms-full.txt: regenerated.

Typecheck clean. 34 oauth + 14 cli tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-02 22:01:05 -07:00

543 lines
22 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Unit tests for src/core/cycle.ts — runCycle primitive.
*
* Tests use mock.module to replace each phase's library function with
* deterministic stubs. Zero fixtures, zero DB, zero network. Covers
* the dryRun × phases × lock_held × engine-null matrix.
*
* The lock primitives are tested against an in-memory PGLite engine
* so they exercise real SQL paths.
*/
import { describe, test, expect, mock, beforeEach, beforeAll, afterAll, afterEach } from 'bun:test';
import { existsSync, unlinkSync } from 'fs';
// ─── Mocks ──────────────────────────────────────────────────────────
// Track what each phase was called with so tests can assert.
let lintCalls: Array<{ target: string; fix: boolean; dryRun: boolean | undefined }> = [];
let backlinksCalls: Array<{ action: string; dir: string; dryRun: boolean | undefined }> = [];
let syncCalls: Array<{ dryRun: boolean | undefined; noPull: boolean | undefined; noExtract: boolean | undefined; sourceId: string | undefined }> = [];
let extractCalls: Array<{ mode: string; dir: string; slugs: string[] | undefined }> = [];
let embedCalls: Array<{ stale: boolean | undefined; dryRun: boolean | undefined }> = [];
let orphansCalls: number = 0;
// Mock lint
mock.module('../../src/commands/lint.ts', () => ({
runLintCore: async (opts: any) => {
lintCalls.push({ target: opts.target, fix: opts.fix, dryRun: opts.dryRun });
return { total_issues: 2, total_fixed: opts.dryRun ? 0 : 2, pages_scanned: 5 };
},
}));
// Mock backlinks
mock.module('../../src/commands/backlinks.ts', () => ({
runBacklinksCore: async (opts: any) => {
backlinksCalls.push({ action: opts.action, dir: opts.dir, dryRun: opts.dryRun });
return { action: opts.action, gaps_found: 3, fixed: opts.dryRun ? 0 : 3, pages_affected: 2, dryRun: !!opts.dryRun };
},
// keep other exports present so import doesn't error
extractEntityRefs: () => [],
extractPageTitle: () => '',
hasBacklink: () => false,
buildBacklinkEntry: () => '',
findBacklinkGaps: () => [],
fixBacklinkGaps: () => 0,
runBacklinks: async () => {},
}));
// Mock sync
mock.module('../../src/commands/sync.ts', () => ({
performSync: async (_engine: any, opts: any) => {
syncCalls.push({ dryRun: opts.dryRun, noPull: opts.noPull, noExtract: opts.noExtract, sourceId: opts.sourceId });
return {
status: opts.dryRun ? 'dry_run' : 'synced',
fromCommit: 'abcd',
toCommit: 'efgh',
added: opts.dryRun ? 0 : 4,
modified: opts.dryRun ? 0 : 2,
deleted: 0,
renamed: 0,
chunksCreated: opts.dryRun ? 0 : 10,
embedded: 0,
pagesAffected: opts.dryRun ? [] : ['a', 'b'],
};
},
runSync: async () => {},
buildSyncManifest: () => ({ added: [], modified: [], deleted: [], renamed: [] }),
isSyncable: () => true,
pathToSlug: (s: string) => s,
}));
// Mock extract
mock.module('../../src/commands/extract.ts', () => ({
runExtractCore: async (_engine: any, opts: any) => {
extractCalls.push({ mode: opts.mode, dir: opts.dir, slugs: opts.slugs });
return { links_created: 7, timeline_entries_created: 3, pages_processed: opts.slugs?.length ?? 5 };
},
walkMarkdownFiles: () => [],
extractMarkdownLinks: () => [],
resolveSlug: () => null,
}));
// Mock embed
mock.module('../../src/commands/embed.ts', () => ({
runEmbedCore: async (_engine: any, opts: any) => {
embedCalls.push({ stale: opts.stale, dryRun: opts.dryRun });
return {
embedded: opts.dryRun ? 0 : 8,
skipped: 2,
would_embed: opts.dryRun ? 8 : 0,
total_chunks: 10,
pages_processed: 3,
dryRun: !!opts.dryRun,
};
},
runEmbed: async () => {},
}));
// Mock orphans
mock.module('../../src/commands/orphans.ts', () => ({
findOrphans: async () => {
orphansCalls++;
return {
orphans: [],
total_orphans: 1,
total_linkable: 20,
total_pages: 20,
excluded: 0,
};
},
queryOrphanPages: async () => [],
shouldExclude: () => false,
deriveDomain: () => 'root',
formatOrphansText: () => '',
}));
// Import after mocks.
const { runCycle, ALL_PHASES } = await import('../../src/core/cycle.ts');
const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');
// Shared PGLite engine per describe block. Each block does its own
// beforeAll/afterAll (below). `truncateCycleLocks` clears the cycle
// lock row between tests so state doesn't leak across assertions.
async function truncateCycleLocks(engine: InstanceType<typeof PGLiteEngine>) {
await (sharedEngine as any).db.query('DELETE FROM gbrain_cycle_locks');
}
// One shared PGLite engine for the whole file. Creating a fresh engine
// per describe (15 migrations each) was causing the parallel test suite
// to hit beforeAll timeouts. truncateCycleLocks between tests keeps
// state clean.
let sharedEngine: InstanceType<typeof PGLiteEngine>;
beforeAll(async () => {
sharedEngine = new PGLiteEngine();
await sharedEngine.connect({});
await sharedEngine.initSchema();
}, 60_000); // OAuth v25 + full migration chain needs breathing room
afterAll(async () => {
if (sharedEngine) await sharedEngine.disconnect();
}, 60_000);
beforeEach(() => {
lintCalls = [];
backlinksCalls = [];
syncCalls = [];
extractCalls = [];
embedCalls = [];
orphansCalls = 0;
});
// ─── dryRun propagation (regression guards) ────────────────────────
describe('runCycle — dryRun propagates to every phase', () => {
beforeEach(async () => {
await truncateCycleLocks(sharedEngine);
});
test('dryRun:true reaches lint, backlinks, sync, embed', async () => {
await runCycle(sharedEngine,{ brainDir: '/tmp/brain', dryRun: true });
expect(lintCalls.at(-1)?.dryRun).toBe(true);
expect(backlinksCalls.at(-1)?.dryRun).toBe(true);
expect(syncCalls.at(-1)?.dryRun).toBe(true);
expect(embedCalls.at(-1)?.dryRun).toBe(true);
});
test('dryRun:false writes in every phase', async () => {
await runCycle(sharedEngine,{ brainDir: '/tmp/brain', dryRun: false });
expect(lintCalls.at(-1)?.dryRun).toBe(false);
expect(backlinksCalls.at(-1)?.dryRun).toBe(false);
expect(syncCalls.at(-1)?.dryRun).toBe(false);
expect(embedCalls.at(-1)?.dryRun).toBe(false);
});
test('dryRun skips extract phase (no dry-run support)', async () => {
const report = await runCycle(sharedEngine,{ brainDir: '/tmp/brain', dryRun: true });
expect(extractCalls.length).toBe(0);
const extractPhase = report.phases.find(p => p.phase === 'extract');
expect(extractPhase?.status).toBe('skipped');
expect(extractPhase?.details.reason).toBe('no_dry_run_support');
});
});
// ─── Phase selection ──────────────────────────────────────────────
describe('runCycle — phase selection', () => {
beforeEach(async () => {
await truncateCycleLocks(sharedEngine);
});
test('default: all 6 phases run in order', async () => {
const report = await runCycle(sharedEngine,{ brainDir: '/tmp/brain' });
expect(report.phases.map(p => p.phase)).toEqual(ALL_PHASES);
});
test('--phase lint only runs lint', async () => {
const report = await runCycle(sharedEngine,{ brainDir: '/tmp/brain', phases: ['lint'] });
expect(report.phases.map(p => p.phase)).toEqual(['lint']);
expect(lintCalls.length).toBe(1);
expect(backlinksCalls.length).toBe(0);
expect(syncCalls.length).toBe(0);
});
test('--phase orphans only runs orphans', async () => {
await runCycle(sharedEngine,{ brainDir: '/tmp/brain', phases: ['orphans'] });
expect(orphansCalls).toBe(1);
expect(syncCalls.length).toBe(0);
});
});
// ─── Lock-skip for non-DB-write phase selections ──────────────────
describe('runCycle — cycle lock acquire/release semantics', () => {
beforeEach(async () => {
await truncateCycleLocks(sharedEngine);
});
test('phases: [orphans] (read-only) skips the lock entirely', async () => {
// We can tell the lock wasn't acquired because the lock table is
// never written to. Seeding a stale holder and verifying it survives
// the run would also work, but a simpler assertion: no rows ever
// existed for a read-only-only selection.
await runCycle(sharedEngine,{ brainDir: '/tmp/brain', phases: ['orphans'] });
const { rows } = await (sharedEngine as any).db.query('SELECT COUNT(*)::int AS n FROM gbrain_cycle_locks');
expect(rows[0].n).toBe(0);
});
test('phases including lint DOES acquire + release (table empty after run)', async () => {
await runCycle(sharedEngine,{ brainDir: '/tmp/brain', phases: ['lint'] });
// Lock is released in finally, so no rows survive the run.
const { rows } = await (sharedEngine as any).db.query('SELECT COUNT(*)::int AS n FROM gbrain_cycle_locks');
expect(rows[0].n).toBe(0);
});
test('phases including sync DOES acquire + release the lock', async () => {
await runCycle(sharedEngine,{ brainDir: '/tmp/brain', phases: ['sync'] });
const { rows } = await (sharedEngine as any).db.query('SELECT COUNT(*)::int AS n FROM gbrain_cycle_locks');
expect(rows[0].n).toBe(0);
});
});
// ─── Lock held by another live holder ──────────────────────────────
describe('runCycle — cycle_already_running skip', () => {
beforeEach(async () => {
await truncateCycleLocks(sharedEngine);
});
test('returns status=skipped when lock is held by live pid in the future', async () => {
// Seed a lock row that looks live (far-future TTL, different PID).
await (sharedEngine as any).db.query(
`INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at)
VALUES ('gbrain-cycle', 99999, 'other-host', NOW(), NOW() + INTERVAL '1 hour')`
);
const report = await runCycle(sharedEngine,{ brainDir: '/tmp/brain' });
expect(report.status).toBe('skipped');
expect(report.reason).toBe('cycle_already_running');
expect(report.phases.length).toBe(0);
// None of the phase runners were called.
expect(lintCalls.length).toBe(0);
expect(syncCalls.length).toBe(0);
});
test('TTL-expired lock is auto-claimed (crashed holder)', async () => {
// Seed a lock row that looks stale (TTL already past).
await (sharedEngine as any).db.query(
`INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at)
VALUES ('gbrain-cycle', 99999, 'crashed-host', NOW() - INTERVAL '2 hours', NOW() - INTERVAL '1 hour')`
);
const report = await runCycle(sharedEngine,{ brainDir: '/tmp/brain' });
expect(report.status).not.toBe('skipped');
expect(syncCalls.length).toBe(1); // cycle ran
});
});
// ─── Engine null path ─────────────────────────────────────────────
describe('runCycle — engine = null (filesystem-only mode)', () => {
const lockFile = require('path').join(require('os').homedir(), '.gbrain', 'cycle.lock');
afterEach(() => {
if (existsSync(lockFile)) { try { unlinkSync(lockFile); } catch { /* */ } }
});
test('filesystem phases still run when engine is null', async () => {
const report = await runCycle(null, { brainDir: '/tmp/brain' });
// Lint and backlinks ran.
expect(lintCalls.length).toBe(1);
expect(backlinksCalls.length).toBe(1);
// DB phases skipped with reason:no_database.
const syncPhase = report.phases.find(p => p.phase === 'sync');
expect(syncPhase?.status).toBe('skipped');
expect(syncPhase?.details.reason).toBe('no_database');
const embedPhase = report.phases.find(p => p.phase === 'embed');
expect(embedPhase?.status).toBe('skipped');
// syncCalls + embedCalls are empty because DB-required phases skipped.
expect(syncCalls.length).toBe(0);
expect(embedCalls.length).toBe(0);
});
test('file lock blocks concurrent engine=null cycles', async () => {
// Seed a lock file pointing at PID 1 (init/launchd — always alive on
// unix, and never equals our test PID). Fresh mtime means "live holder".
// With engine=null + the default phases selection, lint + backlinks
// trigger NEEDS_LOCK_PHASES → acquireFileLock sees the live holder and
// returns null → runCycle returns skipped/cycle_already_running.
const { writeFileSync, mkdirSync } = require('fs');
const path = require('path');
mkdirSync(path.dirname(lockFile), { recursive: true });
writeFileSync(lockFile, `1\n${new Date().toISOString()}\n`);
const report = await runCycle(null, { brainDir: '/tmp/brain' });
expect(report.status).toBe('skipped');
expect(report.reason).toBe('cycle_already_running');
// None of the filesystem phases ran because the lock blocked entry.
expect(lintCalls.length).toBe(0);
expect(backlinksCalls.length).toBe(0);
});
});
// ─── Status derivation ─────────────────────────────────────────────
describe('runCycle — status derivation', () => {
beforeEach(async () => {
await truncateCycleLocks(sharedEngine);
});
test('ok when work was done (non-dry-run)', async () => {
const report = await runCycle(sharedEngine,{ brainDir: '/tmp/brain' });
expect(['ok', 'partial']).toContain(report.status);
// Non-dry-run fixtures produce work (fixes:2, added:4 etc.), so:
expect(report.status).toBe('ok');
expect(report.totals.lint_fixes).toBe(2);
expect(report.totals.backlinks_added).toBe(3);
expect(report.totals.pages_synced).toBe(6); // added + modified from sync mock
expect(report.totals.pages_embedded).toBe(8);
expect(report.totals.orphans_found).toBe(1);
});
test('schema_version is stable at "1"', async () => {
const report = await runCycle(sharedEngine,{ brainDir: '/tmp/brain' });
expect(report.schema_version).toBe('1');
});
test('CycleReport shape includes all required top-level fields', async () => {
const report = await runCycle(sharedEngine,{ brainDir: '/tmp/brain' });
expect(report).toHaveProperty('schema_version');
expect(report).toHaveProperty('timestamp');
expect(report).toHaveProperty('duration_ms');
expect(report).toHaveProperty('status');
expect(report).toHaveProperty('brain_dir');
expect(report).toHaveProperty('phases');
expect(report).toHaveProperty('totals');
});
});
// ─── yieldBetweenPhases hook ─────────────────────────────────────
describe('runCycle — yieldBetweenPhases hook', () => {
beforeEach(async () => {
await truncateCycleLocks(sharedEngine);
});
test('hook is called between every phase', async () => {
let hookCalls = 0;
await runCycle(sharedEngine,{
brainDir: '/tmp/brain',
yieldBetweenPhases: async () => {
hookCalls++;
},
});
// v0.23: 8 phases → 8 yield calls (one after each).
expect(hookCalls).toBe(8);
});
test('hook exceptions do not abort the cycle', async () => {
const report = await runCycle(sharedEngine,{
brainDir: '/tmp/brain',
yieldBetweenPhases: async () => {
throw new Error('synthetic hook error');
},
});
// Cycle still completed all phases (v0.23: 8).
expect(report.phases.length).toBe(8);
});
});
// ─────────────────────────────────────────────────────────────────
// Wave regression guards (#417 + Codex F2)
// ─────────────────────────────────────────────────────────────────
describe('runCycle — incremental extract slug propagation (#417)', () => {
beforeEach(async () => {
await truncateCycleLocks(sharedEngine);
syncCalls = [];
extractCalls = [];
});
test('cycle threads sync.pagesAffected into extract phase as the slugs argument', async () => {
// performSync mock returns pagesAffected = ['a', 'b']. The extract phase
// must receive those exact slugs, not undefined (which would trigger a full walk).
await runCycle(sharedEngine, { brainDir: '/tmp/brain' });
// Sync ran once
expect(syncCalls.length).toBe(1);
// Extract ran once with the slugs from sync (not undefined)
expect(extractCalls.length).toBe(1);
expect(extractCalls[0].slugs).toEqual(['a', 'b']);
});
test('extract phase falls back to full walk when sync was skipped (slugs undefined)', async () => {
// Run only the extract phase — sync didn't run, so syncPagesAffected
// is undefined and extract should walk the full directory (slugs:undefined).
await runCycle(sharedEngine, { brainDir: '/tmp/brain', phases: ['extract'] });
expect(syncCalls.length).toBe(0);
expect(extractCalls.length).toBe(1);
expect(extractCalls[0].slugs).toBeUndefined();
});
});
describe('runCycle — Codex F2: noExtract is gated on whether extract phase runs', () => {
beforeEach(async () => {
await truncateCycleLocks(sharedEngine);
syncCalls = [];
extractCalls = [];
});
test('full cycle (sync + extract): noExtract=true so sync skips inline extraction (extract phase handles it)', async () => {
await runCycle(sharedEngine, { brainDir: '/tmp/brain', phases: ['sync', 'extract'] });
expect(syncCalls.length).toBe(1);
expect(syncCalls[0].noExtract).toBe(true); // dedupe enabled
expect(extractCalls.length).toBe(1); // extract phase ran
});
test('phases:[sync] only: noExtract=false so sync runs inline extraction (no silent extract drop)', async () => {
await runCycle(sharedEngine, { brainDir: '/tmp/brain', phases: ['sync'] });
expect(syncCalls.length).toBe(1);
// Critical: noExtract must be false here. If it were true, the user just lost
// their extraction without any indication. This is the F2 regression guard.
expect(syncCalls[0].noExtract).toBe(false);
expect(extractCalls.length).toBe(0); // extract phase did NOT run
});
});
// ─── sourceId resolution (regression #475) ─────────────────────────
//
// Production OpenClaw deployment hit a 30+ min hang on every autopilot
// cycle because runPhaseSync was calling performSync without sourceId,
// so sync read the global config.sync.last_commit key (which had drifted
// out of git history after a force-push GC'd the commit). The per-source
// sources.last_commit anchor was valid the entire time. PR #475 added
// resolveSourceForDir() so the cycle reads the per-source anchor instead.
//
// These tests pin the resolver -> performSync(opts.sourceId) plumbing.
describe('runCycle — sourceId resolution (regression #475)', () => {
beforeEach(async () => {
await truncateCycleLocks(sharedEngine);
await (sharedEngine as any).db.query('DELETE FROM sources');
});
test('seeded sources row → performSync receives matching sourceId', async () => {
await (sharedEngine as any).db.query(
`INSERT INTO sources (id, name, local_path) VALUES ($1, $2, $3)`,
['default', 'default', '/tmp/brain-475-a'],
);
await runCycle(sharedEngine, { brainDir: '/tmp/brain-475-a' });
expect(syncCalls.at(-1)?.sourceId).toBe('default');
});
test('no matching sources row → performSync receives sourceId=undefined', async () => {
await runCycle(sharedEngine, { brainDir: '/tmp/brain-475-b' });
expect(syncCalls.at(-1)?.sourceId).toBeUndefined();
});
test('different brainDir than registered source → undefined (no cross-match)', async () => {
await (sharedEngine as any).db.query(
`INSERT INTO sources (id, name, local_path) VALUES ($1, $2, $3)`,
['other', 'other', '/some/other/brain'],
);
await runCycle(sharedEngine, { brainDir: '/tmp/brain-475-c' });
expect(syncCalls.at(-1)?.sourceId).toBeUndefined();
});
test('sources table missing (very old brain) → catch returns undefined, sync still runs', async () => {
// CRITICAL: do NOT DROP TABLE on the shared engine. initSchema() only
// re-runs PENDING migrations; once schema_version is at latest, the
// v20 migration that creates `sources` will not re-execute. Use a
// fresh one-shot engine so the shared engine isn't degraded for
// every later test in this file.
const fresh = new PGLiteEngine();
await fresh.connect({});
await fresh.initSchema();
await (fresh as any).db.query('DROP TABLE IF EXISTS sources CASCADE');
try {
await runCycle(fresh, { brainDir: '/tmp/brain-475-d' });
expect(syncCalls.at(-1)?.sourceId).toBeUndefined();
} finally {
await fresh.disconnect();
}
});
test('multiple rows with same local_path → resolver returns one matching id (non-deterministic)', async () => {
// Schema has no UNIQUE on local_path; SQL has no ORDER BY. Either id
// is acceptable; the contract is "any matching id, never null when
// matches exist." This test pins behavior so the follow-up
// UNIQUE-constraint TODO has a regression target.
await (sharedEngine as any).db.query(
`INSERT INTO sources (id, name, local_path) VALUES
('first', 'first', '/tmp/brain-475-e'),
('second', 'second', '/tmp/brain-475-e')`,
);
await runCycle(sharedEngine, { brainDir: '/tmp/brain-475-e' });
const sourceId = syncCalls.at(-1)?.sourceId;
expect(sourceId).toBeDefined();
expect(['first', 'second']).toContain(sourceId as string);
});
test('empty-string id row → resolver propagates as "" (defensive)', async () => {
// Schema has id as PRIMARY KEY (NOT NULL), so NULL id can't happen.
// Empty string CAN be inserted, and the resolver's `rows[0]?.id`
// would treat any falsy id as "no source" via the optional chain.
// This test pins the current behavior (we DO pass '' through to
// performSync) so a future refactor doesn't silently regress it.
await (sharedEngine as any).db.query(
`INSERT INTO sources (id, name, local_path) VALUES ('', 'empty', '/tmp/brain-475-f')`,
);
await runCycle(sharedEngine, { brainDir: '/tmp/brain-475-f' });
expect(syncCalls.at(-1)?.sourceId).toBe('');
});
});