Compare commits

..
Author SHA1 Message Date
Garry Tan e8b6894c72 Merge remote-tracking branch 'origin/master' into garrytan/claw-setup-e2e
# Conflicts:
#	CHANGELOG.md
#	CLAUDE.md
#	TODOS.md
#	VERSION
#	llms-full.txt
#	package.json
#	src/cli.ts
2026-04-29 23:41:09 -07:00
17c3c43783 v0.22.15 feat: frontmatter inference — zero-friction ingest for files without YAML headers (#506)
* feat: frontmatter inference — zero-friction ingest for files without YAML headers

The platonic ideal of agentic retrieval is: you throw stuff in and it
becomes knowledge. No manual schema, no frontmatter templates, no YAML
ceremony. This PR makes that real.

## The Problem

9,655 files in a real 81K-page brain have no YAML frontmatter. They import
fine (gray-matter is forgiving), but with minimal metadata:
- type defaults to 'concept' for everything
- title is the slugified filename ('2010 04 13 Apr 13 Founders Mtg')
- No date, no source, no tags, no folder-aware typing

These pages exist in the DB but are poorly classified, which degrades
search ranking, type-filtered queries, and entity resolution.

## The Fix

### 1. Directory-aware inference engine (src/core/frontmatter-inference.ts)

A rules table maps path patterns to rich metadata:

  Apple Notes/*          → type: apple-note, date from filename, source: apple-notes
  Apple Notes/YC/*       → adds tag: yc
  Apple Notes/Politics/* → adds tag: politics
  daily/calendar/*       → type: calendar-index, source: calendar
  people/*               → type: person, title from # heading
  personal/therapy/*     → type: therapy-session, date from filename
  personal/reflections/* → type: reflection, title from # heading
  writing/essays/*       → type: essay, date from filename
  companies/*            → type: company, title from # heading
  events/*               → type: event, date from filename
  (catch-all)            → type: note, title from # heading

Each rule specifies:
- type: page type for brain schema
- datePattern: 'filename' (YYYY-MM-DD prefix), 'dirname', or 'none'
- titleStrategy: 'filename' (strip date), 'heading' (first #), 'filename-full'
- source: optional source tag
- tags: optional additional tags

Title extraction cleans up filenames (strips date prefix, converts dashes
to spaces, preserves existing capitalization). Heading extraction looks at
the first 20 lines for a # heading.

Fully deterministic. No LLM calls. No network. Same file → same frontmatter.

### 2. Inline inference in import pipeline (src/core/import-file.ts)

importFromFile() now runs inference automatically when a file has no
frontmatter. The synthesized frontmatter is applied to the in-memory
content before parseMarkdown runs, so the downstream pipeline sees
well-formed YAML. The file on disk is NOT modified — inference is
DB-only unless you explicitly run `gbrain frontmatter generate --fix`.

### 3. CLI command: gbrain frontmatter generate (src/commands/frontmatter.ts)

  gbrain frontmatter generate /path/to/brain         # dry-run preview
  gbrain frontmatter generate /path/to/brain --fix   # write to files
  gbrain frontmatter generate /path/to/brain --json  # machine output

The dry-run output shows:
- Total scanned / already have frontmatter / would generate
- Breakdown by inferred type
- First 10 examples with inferred metadata and matched rule

### 4. Tests (test/frontmatter-inference.test.ts)

35 tests covering:
- Date extraction from various filename patterns
- Title extraction from filenames and headings
- Inference for every directory rule (Apple Notes, people, therapy, etc.)
- Serialization with YAML-safe quoting
- Integration: applyInference prepends frontmatter correctly
- Rules: ordering, catch-all, specificity

## What this enables

1. `gbrain sync` now imports bare markdown with rich metadata automatically
2. `gbrain frontmatter generate --fix` writes frontmatter to 9,655 files
3. Future: sync can optionally write-back inferred frontmatter to git
4. Future: rules table is extensible — new directory conventions = one rule

## Adding new directory conventions

Edit DIRECTORY_RULES in src/core/frontmatter-inference.ts:

  { pathPrefix: 'recipes/', type: 'recipe', titleStrategy: 'heading' }

Rules are matched first-to-last, most specific prefix wins. The catch-all
(empty prefix) is always last.

## Real-world test output

  Scanned: 81,479 files
  Already have frontmatter: 71,824
  Would generate: 9,655

  By type:
    apple-note: 5,861
    calendar-index: 3,201
    person: 56
    therapy-session: 60
    reflection: 12
    essay: 33
    ...

All 35 tests pass.

* fix: import basename in frontmatter generate dynamic path import

src/commands/frontmatter.ts:437 calls basename(rootPath) as a fallback
when relative(brainRoot, rootPath) returns the empty string, but the
dynamic import a few lines above only destructures { resolve, relative,
join } from 'path'. typecheck failed with TS2304: Cannot find name
'basename', and any user invocation of `gbrain frontmatter generate
<single-file>` would have crashed at runtime with a ReferenceError.

The unit tests cover frontmatter-inference module's pure functions; no
test exercises the CLI single-file branch, so the bug slipped through.

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

* chore: bump VERSION 0.22.8 → 0.22.15 + CHANGELOG entry

Slot v0.22.15 per the queue allocator (other PRs claim v0.22.9–v0.22.14).
CHANGELOG entry written above v0.22.8 per the never-touch-shipped-entries
rule. bun.lock and llms-full.txt are unchanged (CLAUDE.md untouched, the
inference module and CLI command come in via the feature commit).

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

---------

Co-authored-by: Wintermute <wintermute@garrytan.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 23:26:25 -07:00
Wintermute 0fb0c83d24 chore: gitignore export/ directory (generated output) 2026-04-30 06:11:34 +00:00
ed900c870e v0.22.14 feat(minions): bare-worker self-health-monitoring (#503)
* feat(minions): add self-health-monitoring to bare worker mode

Bare `gbrain jobs work` (without supervisor) previously had zero health
monitoring. If the Postgres connection dropped or the worker's event loop
deadlocked, the process stayed alive doing nothing — jobs piled up while
external process managers (systemd, Docker, cron) thought it was healthy.

Changes:

1. **Self-health-check timer** (worker.ts): Runs every 60s when not under
   a supervisor. Two probes:
   - DB liveness: `SELECT 1` — 3 consecutive failures → exit(1)
   - Stall detection: waiting jobs + 0 in-flight + no completions for 5m
     → warning; 10m → exit(1)

2. **GBRAIN_SUPERVISED env var** (supervisor.ts): Supervisor sets this on
   its child worker to prevent duplicate health checks. The supervisor
   already has its own health monitoring.

3. **RSS watchdog default** (jobs.ts): Bare workers now default to
   `--max-rss 2048` (matching supervisor default). Opt out: `--max-rss 0`.

4. **--health-interval flag** (jobs.ts): Configurable health check period.
   `--health-interval 0` disables. Default: 60000ms.

5. **parseMaxRssFlag returns undefined** when flag is absent (vs 0), so
   callers can distinguish 'not set' from 'explicitly disabled'.

The design ensures bare workers get supervisor-grade monitoring while
remaining compatible with any external process manager — the worker just
exits with code 1 on detected failure, letting the PM handle the restart.

Tests: 4 new tests (3 worker health, 1 supervisor env var). All 178 pass.

* fix(minions): harden bare-worker self-health-check after multi-round review

Layered fixes from 5 rounds of plan-eng-review + codex outside voice on top of
the original PR #503 (feat: bare-worker self-health-monitoring). Every change
below is in service of "fail-stop into the operator's process manager" without
introducing new ways the library can kill its caller.

worker.ts:
- MinionWorker now extends EventEmitter; emits `'unhealthy'` event with structured
  reason payload (`db_dead` | `stalled`). CLI subscribes; library no longer calls
  process.exit directly.
- emitUnhealthy() falls back to process.exit(1) when listenerCount('unhealthy') === 0
  so direct API consumers without a listener inherit the pre-refactor fail-stop
  default. Inline paths opt out via healthCheckInterval=0.
- Stall detection: count(*) query now filters by registered handler names
  (`AND name = ANY($2::text[])`) so workers with handlers for {embed,sync} don't
  false-positive when waiting jobs of unhandled names accumulate.
- Stall exit threshold measured from lastCompletionTime (not from warn-since), so
  defaults of 5min warn / 10min exit fire at idle=10min total — matching the
  documented contract.
- Recursive setTimeout pattern with running flag replaces setInterval, eliminating
  callback overlap on slow DB probes.
- DB liveness probe wrapped in Promise.race against AbortController-driven
  timeout (default 10s) so a hung executeRaw can't wedge the recursive chain
  forever. Hung probes count as failures and feed dbFailExitAfter.
- Constructor validates stallExitAfterMs > stallWarnAfterMs and throws loudly
  on misconfiguration. Internal timer-installation invariants documented inline.
- GBRAIN_SUPERVISED env-var check tightened from `!!process.env.X` to `=== '1'`.

types.ts:
- Added 5 new MinionWorkerOpts fields with documented contracts:
  healthCheckInterval, stallWarnAfterMs, stallExitAfterMs, dbFailExitAfter,
  dbProbeTimeoutMs.
- Exported `UnhealthyReason` discriminated union for the 'unhealthy' event payload.

supervisor.ts:
- GBRAIN_SUPERVISED=1 injected on the spawned worker child's env so the child's
  self-health timer is skipped (no double-monitoring).
- setInterval(callback, healthInterval) gated behind `> 0`, so the
  `--health-interval 0` documented disable contract actually disables instead
  of producing a tight DB-hammer loop.

jobs.ts:
- `gbrain jobs work` subscribes to 'unhealthy' and calls process.exit(1) at the
  CLI layer. Default --max-rss bumped from 0 to 2048 (matches supervisor default;
  catches memory-leak stalls that previously went undetected).
- New --health-interval flag with aggressive validation (NaN/negative/sub-1000ms
  rejected; parity with --max-rss) on both `jobs work` and `jobs supervisor`.
- `jobs submit --follow` and `jobs smoke` now pass healthCheckInterval=0 to
  disable the self-health timer entirely. These are inline/one-shot flows with
  no PM to restart them; the no-listener emitUnhealthy fallback could otherwise
  trip on a DB blip and kill the user's CLI session.
- parseMaxRssFlag returns `number | undefined` (was `number`) so callers can
  distinguish absent (use the default) from explicit-disable (--max-rss 0).

doctor.ts:
- New queue_health subcheck reports RSS-watchdog kills in the last 24h.
  Detects via exact-match `error_text = 'aborted: watchdog'` (the worker's
  failJob signature when gracefulShutdown('watchdog') aborts in-flight jobs)
  scoped to status IN ('dead','failed'). Tight match avoids over-counting parent
  jobs that propagate child failures via on_child_fail='fail_parent'.

* test(minions): self-health behavior + regression tests

7 new tests covering the production failure modes that drove the original PR,
plus regressions for fixes landed during multi-round review.

minions.test.ts:
- DB 3-strike → 'unhealthy' event with reason='db_dead' (the production-incident signature)
- DB recovery resets failure counter (no exit on intermittent failures)
- Stall warn-then-exit (clock-driven; idleMs > stallExitAfterMs is the new contract)
- inFlight > 0 blocks stall detection (long-running legitimate jobs don't false-trip)
- Regression for D1 fix: jobs of unregistered handler names don't trigger stall exit;
  also captures the SQL via probe engine and asserts the predicate text contains
  `name = ANY` so a future refactor that drops the filter is caught at test time.
- Regression for R3 constructor validation: throws when stallExitAfterMs <= stallWarnAfterMs
  (covers both `<` and `=` cases); defaults still construct cleanly.

supervisor.test.ts:
- Regression for R3: supervisor with healthInterval=0 completes a normal lifecycle
  within 10s. A tight setInterval(0) loop (the bug we fixed) would saturate the
  event loop and slow this past the cap.

Tests use a Proxy-based engine helper (makeProbeEngine) that intercepts SELECT 1
and the count(*) WHERE status='waiting' query while passing through everything
else to the real PGLite engine. This isolates health-check semantics from claim
plumbing without mocking the entire engine surface.

* docs(v0.22.14): migration walkthrough + follow-up TODOs

skills/migrations/v0.22.14.md (new):
- Pre-flight per-PM restart-policy table (systemd Restart=always, Docker
  restart: always, launchd KeepAlive, cron watchdog, supervisord autorestart).
  v0.22.14 makes bare-worker behavior fail-stop — without an external restart
  loop the worker exits and stays dead. Migration calls this out loudly so
  OpenClaw/Hermes-style downstream agents can verify their PM before upgrade.
- Five new MinionWorkerOpts fields documented with defaults and rationale.
- Worker-side process.exit(1) fallback semantics explained: CLI subscribes to
  'unhealthy', but direct API consumers without a listener inherit fail-stop.
- AskUserQuestion-driven flow for the --max-rss 2048 default (raise / opt out /
  keep) with concrete edits per PM (systemd unit, cron line, Docker compose,
  launchctl plist).
- Verification commands (gbrain jobs stats, gbrain doctor --json, RSS check)
  and a triage paragraph for opening an issue if anything fails.

TODOS.md:
- v0.22.15 embed cooperative-abort (P0, daily pain): plumb signal through
  runPhaseEmbed → embed.ts → embedBatch; check signal.aborted between OpenAI
  batch calls and between slugs. Closes the daily wedge where embed > 600s
  timeout dead-letters the job but keeps running, holding gbrain_cycle_locks
  until the lock TTL expires. PR #503 catches the symptom (worker stalled);
  this captures the cause-side fix that's the real production resolution.
- v0.23+ bare-worker engine reconnect parity: extract supervisor's
  reconnect-then-fail pattern (#406) into MinionWorker so transient PgBouncer
  blips don't force a full process restart.
- v0.23+ minion_workers heartbeat table for queue_health doctor check (B7
  follow-up): replace lock_until proxy with ground-truth worker liveness
  signal so doctor stops crying wolf on legitimately idle workers.

* chore: bump version and changelog (v0.22.14)

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

---------

Co-authored-by: Wintermute <wintermute@garrytan.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 23:06:16 -07:00
e96f054cf0 v0.22.13 feat: parallel sync — bounded concurrent imports (#490)
* feat: parallel sync — bounded concurrent imports (#489)

gbrain sync --concurrency N (alias --workers N) parallelizes the import
phase using per-worker Postgres engine instances with an atomic queue
index (same proven pattern as gbrain import --workers N).

Auto-concurrency: when a sync touches >100 files and the user didn't
explicitly set --concurrency, defaults to 4 workers. Small incremental
syncs (<50 files) stay serial. Full syncs auto-detect Postgres and
default to 4 workers.

Minion sync handler defaults to concurrency=4, configurable via job
params: {"concurrency": 8}.

Delete and rename phases remain serial (order-dependent, fast).
PGLite falls back to serial automatically (single-connection engine).

Changes:
- src/commands/sync.ts: SyncOpts.concurrency, parallel import loop in
  performSync incremental path, --workers passthrough in performFullSync
- src/commands/jobs.ts: sync handler accepts concurrency param (default 4)
- CHANGELOG.md: v0.23.0 parallel sync entry

All 37 existing sync tests pass. Typecheck clean.

* feat: shared concurrency policy + db-lock primitive

src/core/sync-concurrency.ts — single source of truth for autoConcurrency()
+ parseWorkers() + shouldRunParallel() + constants. Replaces three drifted
call-site policies (performSync, performFullSync, jobs handler).

src/core/db-lock.ts — generic tryAcquireDbLock(engine, lockId, ttlMinutes)
over the existing gbrain_cycle_locks table. Parameterized lock id so
performSync (gbrain-sync) can nest cleanly under cycle.ts (gbrain-cycle)
without deadlock.

test/sync-concurrency.test.ts — 17 cases covering PGLite-forces-serial,
explicit override clamping, auto-path threshold, parseWorkers validation
(rejects 0, negatives, NaN, decimals, trailing chars).

No consumers yet; subsequent commits wire sync.ts, import.ts, and jobs.ts
to use these helpers.

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

* fix: harden performSync — writer lock, head-drift gate, engine.kind

CODEX-2: wrap performSync body in a gbrain-sync DB lock so two concurrent
syncs (manual + autopilot, two terminals, two Conductor workspaces) cannot
both read last_commit, both write it unconditionally, and let the last
writer win. cycle.ts continues to hold gbrain-cycle for its broader scope;
the two ids nest cleanly.

CODEX-3: capture git HEAD at sync entry, re-rev-parse after the import
phase, refuse to advance last_commit if HEAD drifted (someone ran
git checkout / git pull mid-sync). Vanished files now go into failedFiles
instead of silent-skip — same gating mechanism, no more bookmark advance
past unimported work.

A1: replace both PGLite detection sites with engine.kind === 'pglite'.
The constructor.name sniff is gone (breaks under bundling) and so is the
inconsistent config?.engine string check.

A2: connect worker engines serially into an array, run inside try/finally
so disconnect always fires — even on partial connect failure, OOM, or
mid-import abort. Prior Promise.all(...disconnect) leaked the 8 worker
connections on any panic path.

Q1: explicit --workers / opts.concurrency now bypasses the >50-file floor.
User opt-in beats the auto-path safety net.

Q3: drop the config!.database_url! non-null assertions; fall back to serial
when database_url is unset instead of crashing on TypeError.

Q4: worker-count banner moves from console.log to console.error so stdout
stays clean for --json output.

test/sync-parallel.test.ts — 7 cases over PGLite covering the bookmark
gate under concurrency request, the head-drift gate, vanished-file
failure capture, PGLite-stays-serial, and the writer-lock contract.

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

* fix: import.ts — engine.kind discriminator, worker try/finally, parseWorkers

A1: replace the config?.engine === 'pglite' string sniff with
engine.kind === 'pglite' to match sync.ts and the v0.13.1 contract.

A2: wrap worker engine creation + the parallel loop in try/finally so
disconnects always fire — same pattern as sync.ts. Worker engines now
push onto an array as they connect (rather than Promise.all) so the
finally block can clean up partial-connect state.

Q2: route --workers parsing through the shared parseWorkers() helper.
parseInt-with-no-validation is gone — '0', '-3', 'foo', '1.5' now exit
with a clear error message instead of silently falling through.

Q3: drop the config!.database_url! non-null assertion; fall back to
serial when database_url is unset.

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

* fix: jobs.ts sync handler — resolve sourceId, autoConcurrency

CODEX-1: resolve sourceId at handler entry by looking up sources.local_path.
Mirrors cycle.ts:480's autopilot-cycle fix (PR #475). Without this, every
Minion sync job on a multi-source brain reads global config.sync.last_commit
instead of the per-source anchor, which on a regularly-GC'd repo can drop
out of git history and trigger 30-min full reimports every cycle.

The handler accepts an optional sourceId job param for callers that want
to override; falls back to the resolveSourceForDir lookup when absent.

CODEX-4: replace the hardcoded concurrency=4 default with the shared
autoConcurrency policy. Behavior is now consistent between CLI sync,
the Minion handler, and the autopilot cycle's sync phase. Jobs that
request a specific concurrency via job.data.concurrency still win.

noEmbed default stays at true — embed is a separate job (submit
gbrain embed --stale, OR rely on the autopilot cycle's embed phase).
The doc comment makes that contract explicit.

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

* test: e2e parallel sync against real Postgres + benchmark

DATABASE_URL-gated E2E coverage that PGLite-only tests can't reach:

T2 — happy path: 60 files imported at concurrency=4, all 60 pages land
in the DB, with a pg_stat_activity probe before/after to confirm worker
engines (4 × 2 connections) actually disconnected.

P4 — benchmark: 120-file fixture, serial vs concurrency=4 timing.
Emits a single-line `SYNC_PARALLEL_BENCH 120 files | serial=Xms |
parallel(4)=Yms | speedup=Zx` so the CHANGELOG can quote a real
number instead of an unbacked '~4×' claim. Asserts parallel <=
serial * 1.5 to allow for noisy CI but fail genuine regressions.

Skips gracefully when DATABASE_URL is unset (consistent with the rest
of test/e2e/).

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

* chore: v0.22.10 release notes + sync follow-up TODO

VERSION + package.json + bun.lock: 0.22.5/0.22.6 → 0.22.10. Repo had
existing drift between VERSION and package.json on master; this commit
brings them back in sync at the bumped value.

CHANGELOG.md: v0.22.10 entry replaces the unfinished v0.23.0 stub from
PR #490's original commit. Voice-rule clean (no em dashes, no AI
vocabulary), real benchmark numbers from the new E2E test
(serial=289ms parallel(4)=221ms speedup=1.31x), additive worker-pool
note (A3), 'To take advantage of v0.22.10' self-repair block per
CLAUDE.md convention.

TODOS.md: A4 follow-up filed — plumb resolved database_url through
SyncOpts so performSync / performFullSync / import.ts don't each call
loadConfig() separately. Deferred to a future patch; not on the
v0.22.10 critical path.

Patch (not minor) framing held even though new CLI surface lands here;
release-notes prose names the behavior change explicitly so users know
to read them.

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

* docs: update CLAUDE.md + README for v0.22.10 sync hardening

CLAUDE.md:
- New "Key files" entries for src/core/sync-concurrency.ts and
  src/core/db-lock.ts (both v0.22.10).
- New "Key files" entry for src/commands/sync.ts (covers the lock,
  head-drift gate, engine.kind discriminator, vanished-file failure
  capture, parallel branch wiring).
- Updated src/commands/jobs.ts entry with v0.22.10 sourceId
  resolution + autoConcurrency policy + noEmbed contract.
- Added test/sync-concurrency.test.ts and test/sync-parallel.test.ts
  to the unit-test list with case counts.
- Added test/e2e/sync-parallel.test.ts to the E2E section with the
  SYNC_PARALLEL_BENCH grep marker for CHANGELOG quoting.
- Added "Key commands added in v0.22.10" section: gbrain sync --workers,
  gbrain import --workers (parseWorkers validation).

README.md: added --workers flag to the IMPORT section's gbrain sync
and gbrain import lines, with the >100-file auto-parallelize note.

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

* chore: bump version slot to v0.22.13

VERSION 0.22.10 → 0.22.13. Master moved to 0.22.8 plus claimed slots
0.22.9-0.22.12 in sibling workspaces; 0.22.13 is the next free slot for
this PR's parallel-sync hardening work.

Updated all v0.22.10 references in CHANGELOG.md (release header +
self-repair block), TODOS.md (D-PR490-1 follow-up tag), CLAUDE.md
(Key files entries + tests + commands subsection), and the inline
v0.22.10 markers in src/core/sync-concurrency.ts, src/core/db-lock.ts,
src/commands/sync.ts, src/commands/import.ts, src/commands/jobs.ts,
test/sync-parallel.test.ts, test/e2e/sync-parallel.test.ts.

No behavioral change. CHANGELOG header rewrite, content unchanged.

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

* chore: regenerate llms-full.txt for v0.22.13 doc updates

CI's build-llms generator test failed because llms-full.txt was stale
relative to the README + CLAUDE.md updates this PR added (--workers
flag in the IMPORT section, sync-concurrency.ts/db-lock.ts/sync.ts
entries in the Key files section).

Per CLAUDE.md: "Run \`bun run build:llms\` after adding a new doc."
The test test/build-llms.test.ts:67 verifies committed bundles match
generator output — now they do again.

llms.txt was already in sync (no curated config additions); only
llms-full.txt needed the regen.

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

---------

Co-authored-by: root <root@localhost>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 22:53:41 -07:00
Garry Tan 7aae6ec2b0 Merge remote-tracking branch 'origin/master' into garrytan/claw-setup-e2e
# Conflicts:
#	CHANGELOG.md
#	VERSION
#	package.json
2026-04-29 22:18:08 -07:00
Garry Tan 189da55f46 chore: rebump to v0.22.16 (next free 0.22.x patch slot per queue)
PR #506 claims v0.22.15, PR #521 claims v0.22.10, intermediate slots
(.11/.12/.13/.14) are claimed by other open PRs. v0.22.16 is the next
clean PATCH slot. v0.23.0 is claimed by PR #462 so MINOR isn't free.
This release fits the 0.22.x train; v0.23.0 lands when #462 ships.

Updates VERSION, package.json, CHANGELOG.md header, TODOS.md follow-up
labels. Code is unchanged.
2026-04-29 22:14:47 -07:00
Garry Tan bbc8bba0ff fix(tests): typecheck failures + spawnWithCapture timeout headroom in CI
Three CI fixes after PR #522 landed:

1. test/agent-runner.test.ts:89 — UnavailableRunner.invoke() returns
   Promise<void> by default but the AgentRunner contract requires
   Promise<InvokeResult>. Annotate the throw-only invoke explicitly so tsc
   sees the contract is satisfied (the throw makes the body unreachable as
   far as the return type is concerned).

2. test/seed-pglite.test.ts — bun:test signature is test(name, fn, timeoutMs:
   number), not test(name, opts: {timeout}, fn). The {timeout: 30_000} object
   form was a guess that tsc on bun 1.3.13 rejects. Move the 30s cap to the
   trailing positional number arg on each PGLite-using test.

3. test/transcript-capture.test.ts — `spawnWithCapture > timeout fires
   SIGTERM/SIGKILL` blew the 10s outer cap on the GitHub runner. Two fixes:
   (a) use `exec sleep` so the child we spawn IS sleep — SIGTERM goes
   directly to it, no `/bin/sh` fork-vs-exec process-group ambiguity that
   could orphan the sleep and force the SIGKILL grace path. (b) bump outer
   cap to 30s for headroom even when the runner is slow and SIGKILL after
   the 5s grace is what actually ends the child.
2026-04-29 17:57:23 -07:00
Garry TanandClaude Opus 4.7 8200c275d6 chore: bump version and changelog (v0.24.0)
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 17:48:13 -07:00
Garry Tan 953c8e75f6 Merge remote-tracking branch 'origin/master' into garrytan/claw-setup-e2e
# Conflicts:
#	.gitignore
#	src/cli.ts
2026-04-29 17:43:37 -07:00
Garry Tan 6c64670b33 feat: register gbrain claw-test + gbrain friction; CLAUDE.md + llms sync
Wires both commands into src/cli.ts CLI_ONLY allow-list and adds dispatch
in handleCliOnly so neither command requires a brain engine connection.

CLAUDE.md gains entries for src/commands/{friction,claw-test}.ts +
src/core/claw-test/ + skills/_friction-protocol.md, and a Commands section
listing all 8 new gbrain claw-test ... and gbrain friction ... invocations
with the v0.23 marker. Documents the GBRAIN_HOME write-isolation contract
and the v1 caveat (read-side host-fingerprint detection deferred to v1.1).
llms.txt + llms-full.txt regenerated via 'bun run build:llms' so the
committed generator-output gate passes.

test/e2e/claw-test.test.ts is the scripted-mode E2E. Builds a tiny shim that
delegates to 'bun run src/cli.ts' (NOT bun --compile, which doesn't bundle
PGLite's runtime assets), points the harness at it via GBRAIN_BIN_OVERRIDE,
runs --scenario fresh-install end-to-end. Asserts exit 0, zero error/blocker
friction. Includes a deliberate-break test that proves the friction signal
fires when a phase command rejects.

test/claw-test-cli.test.ts covers shipped-scenario load + agent registry +
OpenClawRunner detection (relative-path / .. / missing-bin guards) + the
GBRAIN_FRICTION_RUN_ID env handoff between harness and friction CLI.

Closes the v0.23 claw-test E2E feature.
2026-04-29 16:13:54 -07:00
Garry Tan 4fc261a18c feat: claw-test scenario fixtures + friction-protocol skills convention
Two scenarios ship in v1 — fresh-install and upgrade-from-v0.18. Each is a
self-contained directory: brain/ (markdown pages), BRIEF.md (live-mode prompt),
expected.json (scripted-mode assertions), scenario.json (kind, expected_phases,
optional from_version + seed paths). Schema is owned by src/core/claw-test/
scenarios.ts.

upgrade-from-v0.18 ships scaffolded — seed/dump.sql is the v1.1 follow-up
(needs a real v0.18-shape PGLite dump; seed/README.md documents the gen
procedure). The harness gracefully no-ops the seed phase when dump.sql is
absent.

skills/_friction-protocol.md is a cross-cutting convention skill (like
_brain-filing-rules.md). Tells agents when to call gbrain friction log and how
to choose severity. Skills the claw-test exercises will gain a > Convention:
callout pointing here in a v1.1 sweep.

13 unit tests for the scenario loader + 'shipped scenarios load cleanly' for
both.
2026-04-29 16:13:36 -07:00
Garry Tan fe09ffaa71 feat: gbrain claw-test — end-to-end fresh-install friction harness
Two modes: scripted (CI gate, no agent) and --live (real agent subprocess).
Phases: setup → install_brain (gbrain init --pglite) → import (--no-embed) →
query → extract all --source fs → verify (gbrain doctor --json, asserts
status==='ok' and progress.jsonl phase coverage).

AgentRunner interface + registry — interface stays narrow (detect, invoke,
optional postInstallHook). v1 ships only OpenClawRunner; the registry pattern
lets v1.1 land hermes/codex as ~50-line additions without refactoring callers.
OpenClaw invocation: 'openclaw agent --local --agent <name> --message <brief>'
matching test/e2e/skills.test.ts (NOT --prompt-file, which doesn't exist).

transcript-capture: spawns child with piped stdio, async-drains via
fs.createWriteStream + 'drain' events so 256KB+ bursts don't stall the child
(D17 backpressure). Writes <run>/transcript.jsonl with schema_version + ts +
channel + byte_offset + bytes_b64. Friction entries' transcript_offset field
references byte offsets here so render --transcripts can resolve back.

progress-tail: parses gbrain's --progress-json events out of child stderr.
Phase verification asserts each scenario.expected_phases entry (dotted names
like import.files, extract.links_fs, doctor.db_checks) saw at least one event
from the actual command — proves the COMMAND ran, not that the agent obeyed
prompts.

seed-pglite: ~50 LOC SQL replay primitive for the upgrade-from-v0.18 scenario.
Existing migration helpers (test/e2e/helpers.ts) are Postgres-only; PGLite has
no equivalent. seedPglite opens a fresh PGLite, executes each statement
individually (errors name the failing one), then disconnects so gbrain init
can take over and walk forward.

53 unit tests covering registry selection, runner detection, multi-byte UTF-8
chunk-boundary safety, PIPE buffer drain, scenario load+validate, progress
event parsing, and SQL splitter.
2026-04-29 16:13:21 -07:00
Garry Tan 00843f2a5a feat: gbrain friction {log,render,list,summary} — agent friction reporter
Append-only JSONL writer at $GBRAIN_HOME/friction/<run-id>.jsonl. Schema is a
flat extension of StructuredAgentError (D20), one envelope shape across both
agent-emitted entries and harness-wrapped command failures. Run-id resolves
from --run-id > $GBRAIN_FRICTION_RUN_ID > 'standalone'.

Subcommands stay ≤30 LOC each; core lives in src/core/friction.ts (writer +
reader + renderer + redactor). render --redact (default for md output) strips
\$HOME / \$CWD to placeholders so reports paste safely in PRs/issues.

Severity: confused | error | blocker | nit. Kind: friction | delight (D7) |
phase-marker | interrupted. Readers tolerate malformed lines (skip + warn).

40 unit tests; this is the channel the claw-test harness writes to and that
agents emit through during live-mode runs.
2026-04-29 16:02:38 -07:00
Garry Tan ce6af836e7 feat: hermeticity migration — every $GBRAIN_HOME write site honors the env override
configDir() in src/core/config.ts already implemented $GBRAIN_HOME as a
parent-dir override (returns <override>/.gbrain), but ~12 consumers built paths
from os.homedir() directly and bypassed it. Critically, loadConfig/saveConfig
themselves used a private getConfigDir() that ignored the env. Fixed.

Migrated every write site to gbrainPath() — fail-improve, validator-lint, cycle
lock, shell-audit, backpressure-audit, sync-failures, integrity logs,
integrations heartbeat, init pglite path, migrate-engine manifest, import
checkpoint, v0_13_1 rollback, v0_14_0 host-work. Read-side host-detection in
init.ts (~/.claude / ~/.openclaw probes) intentionally NOT migrated; that's a
v1.1 follow-up under a separate $GBRAIN_HOST_HOME override.

Adds gbrainPath(...segments) sugar plus path validation: $GBRAIN_HOME must be
absolute and contain no '..' segments (throws GbrainHomeInvalidError).

test/gbrain-home-isolation.test.ts proves write-isolation across all migrated
sites. test/migrations-v0_14_0.test.ts updated to use $GBRAIN_HOME instead of
the old HOME-swap pattern.

Closes part of the claw-test E2E harness preconditions (D13 + D21).
2026-04-29 16:02:20 -07:00
66 changed files with 5855 additions and 102 deletions
+5
View File
@@ -17,4 +17,9 @@ eval/data/world-v1/world.html
# BrainBench amara-life-v1 Opus cache (regenerate via eval:generate-amara-life)
eval/data/amara-life-v1/_cache/
# claw-test E2E build cache (shim + scratch outputs)
test/.cache/
.claude/
export/
+225
View File
@@ -2,6 +2,231 @@
All notable changes to GBrain will be documented in this file.
## [0.22.16] - 2026-04-29
**End-to-end claw-test friction harness — every release now gets a fresh-install dry-run.**
**`gbrain claw-test` spins up a hermetic tempdir, walks the canonical first-day flow, and surfaces friction the way a real new user would hit it.**
Before this release, every gbrain release shipped on faith: docs said "the agent runs `gbrain init`, then `gbrain import`, then `gbrain query`," and we'd find out at user-feedback time which step actually broke. Issue #239/#243/#266/#357/#366/#374/#375/#378/#395/#396 — ten upgrade-wedge incidents in two years — all came from this gap. There was no harness that exercised the user's-eye experience: spin up a fresh tempdir, install gbrain, watch what breaks.
Now there is. `gbrain claw-test --scenario fresh-install` in scripted mode is a CI gate (~30s, no API keys). `gbrain claw-test --live --agent openclaw` spawns a real openclaw subprocess, hands it `BRIEF.md`, captures every byte of its stdin/stdout/stderr to `transcript.jsonl`, and lets the agent log friction whenever something is confusing or wrong. End-of-run renders a markdown report grouped by severity and phase, with `<HOME>` redaction so it pastes safely into PRs.
The friction signal comes from a new `gbrain friction {log,render,list,summary}` CLI. Schema is a flat extension of `StructuredAgentError`. Run-id resolves from `--run-id` > `$GBRAIN_FRICTION_RUN_ID` > `standalone.jsonl`, so the same CLI works inside a harness session, manually during normal use, or from a scripted test. Append-only JSONL; readers tolerate malformed lines.
**$GBRAIN_HOME is finally honored everywhere it should be.** `configDir()` in `src/core/config.ts` always supported the parent-dir override, but ~12 consumers built paths from `os.homedir()` directly and bypassed it. Critically, `loadConfig`/`saveConfig` themselves used a private helper that ignored the env. Migrated every write site to a new `gbrainPath()` helper: fail-improve, validator-lint, cycle lock, audit handlers, sync-failures, integrity logs, integrations heartbeat, init pglite path, migrate-engine manifest, import checkpoint, migration rollbacks. Read-side host-detection (`~/.claude` / `~/.openclaw` probes for mod fingerprinting) intentionally stays as-is; v1.1 will add a separate `$GBRAIN_HOST_HOME`.
### Itemized changes
#### Added
- `gbrain claw-test --scenario {fresh-install|upgrade-from-v0.18}` — scripted-mode CI gate that runs the canonical first-day flow against a fresh tempdir. Asserts every expected `--progress-json` phase fired and doctor's `status === 'ok'`. ~30s, no API keys.
- `gbrain claw-test --live --agent openclaw` — friction-discovery mode. Spawns real openclaw, hands it `BRIEF.md`, captures stdin/stdout/stderr to `<run>/transcript.jsonl`, lets the agent log friction. ~510 min and ~$12 in tokens.
- `gbrain claw-test --list-agents` — reports which agent runners are registered + their detection state.
- `gbrain friction log --severity {confused|error|blocker|nit} --phase <name> --message <text> [--hint ...] [--kind {friction|delight}] [--run-id ...]` — append a friction or delight entry.
- `gbrain friction render --run-id <id> [--json] [--transcripts] [--no-redact]` — markdown report grouped by severity + phase; `--redact` defaults on for md output.
- `gbrain friction list [--json]` — recent run-ids with friction/delight counts; interrupted runs marked `(interrupted)`.
- `gbrain friction summary --run-id <id> [--json]` — two-column friction + delight summary.
- `skills/_friction-protocol.md` — cross-cutting convention skill telling agents when to call `gbrain friction log`. Routes from any skill the claw-test exercises.
- `gbrainPath(...segments)` helper in `src/core/config.ts` — single sugar for resolving paths under the active `$GBRAIN_HOME`. `$GBRAIN_HOME` is now validated (must be absolute, no `..` segments).
- Two scenario fixtures in `test/fixtures/claw-test-scenarios/`: `fresh-install` (canonical 5-min flow) and `upgrade-from-v0.18` (scaffolded; real v0.18 SQL dump documented as a v1.1 follow-up).
- New `src/core/claw-test/` module with `agent-runner.ts` (interface + registry), `transcript-capture.ts` (async-drain capture so 256KB+ bursts don't stall the child), `progress-tail.ts`, `scenarios.ts`, and `seed-pglite.ts` (~50 LOC PGLite SQL replay primitive).
#### Changed
- Every `~/.gbrain/...` write site now resolves through `gbrainPath()` instead of building paths from `os.homedir()`. Affected: `src/core/{fail-improve,output/post-write,cycle,sync}.ts`, `src/core/minions/{handlers/shell-audit,backpressure-audit}.ts`, `src/commands/{integrity,integrations,init,migrate-engine,import,migrations/v0_13_1,migrations/v0_14_0}.ts`. Tests that previously used the `process.env.HOME = tmpdir` workaround now use `process.env.GBRAIN_HOME` directly.
- `loadConfig`/`saveConfig` honor `$GBRAIN_HOME`. Previously, the public `configDir()` honored it but the internal `getConfigDir()` did not — so the config file itself silently leaked into the developer's real `~/.gbrain` regardless of the env override.
#### Tests
- 113 new unit tests covering: writer atomicity (concurrent appends), renderer redaction, agent registry resolution + selection precedence, multi-byte UTF-8 chunk-boundary safety, PIPE buffer drain under 256KB+ bursts, scenario load + validation, progress event parsing, SQL splitter (single-quote + line-comment handling), and full claw-test E2E (`test/e2e/claw-test.test.ts` builds a tiny `bun run src/cli.ts` shim and runs --scenario fresh-install end-to-end + a deliberate-break test that proves the friction signal fires).
- `test/gbrain-home-isolation.test.ts` is the regression gate: spawns `gbrain init --pglite` and `gbrain import --no-embed` with `GBRAIN_HOME=<tmp>`, asserts no writes outside `<tmp>/.gbrain` (covers `import.ts:54`, `sync.ts:317`, `upgrade.ts:117`, audit dirs).
## [0.22.15] - 2026-04-29
## **Throw bare markdown into your brain and it becomes properly typed knowledge. No YAML ceremony.**
A real 81K-page brain has 9,655 files with no frontmatter. They imported fine, but every one of them landed in the DB as `type: concept`, `title: <slugified-filename>`, no date, no source, no tags. Search ranking suffered. Type-filtered queries missed them. Entity resolution fell over.
This release adds path-aware frontmatter inference. `gbrain sync` now synthesizes type, date, source, and tags from the filesystem path and first heading the moment a bare-frontmatter file imports. No LLM call, fully deterministic, file on disk untouched. An Apple Note at `Apple Notes/2010-04-13 founders mtg.md` lands as `type: apple-note, title: founders mtg, date: 2010-04-13, source: apple-notes` instead of `type: concept, title: 2010 04 13 Founders Mtg`.
If you want the inference written back to git, the new `gbrain frontmatter generate <path> --fix` walks a brain dir, infers frontmatter for every file that lacks it, and writes back with `.bak` safety backups. Dry-run by default.
### The 9,655 numbers that matter
Measured against my actual brain (gbrain v0.22.8 + the new inference path).
| Behavior | Before v0.22.15 | After v0.22.15 |
|---|---|---|
| Files importing as `type: concept` (no frontmatter) | 9,655 | 0 |
| Apple Notes typed correctly (`apple-note`) | 0 | 5,861 |
| Calendar indexes typed correctly (`calendar-index`) | 0 | 3,201 |
| Therapy sessions typed + dated | 0 | 60 |
| Essay drafts typed + dated | 0 | 33 |
| LLM cost for the full reclassification | n/a | $0 |
The agent doing type-filtered queries on your brain (`type: person`, `type: meeting`, `type: essay`) now actually finds those pages instead of treating everything as `concept`.
### What this means for you
If you've been resisting frontmatter ceremony — same. Throw bare markdown into your brain and inference handles it. The rules table in `src/core/frontmatter-inference.ts` covers the obvious directories (`people/`, `companies/`, `daily/calendar/`, `writing/`, `meetings/`, `personal/`, etc.) plus a generic catch-all. Adding a new convention is one line in `DIRECTORY_RULES`.
## To take advantage of v0.22.15
`gbrain upgrade` should do this automatically. Then:
1. **Run a dry-run preview:**
```bash
gbrain frontmatter generate ~/brain
```
You'll see how many files would get inferred frontmatter and the breakdown by type.
2. **Optionally write back to git:**
```bash
gbrain frontmatter generate ~/brain --fix
```
Each modified file gets a `.bak` backup before rewrite.
3. **Re-sync to pick up the new metadata:**
```bash
gbrain sync ~/brain
```
Inferred frontmatter is folded into `content_hash`, so previously-bare files re-import once with proper types and re-embed. Subsequent syncs are idempotent.
4. **If anything looks off,** please file an issue: https://github.com/garrytan/gbrain/issues with the path of the misclassified file and the rule that matched.
### Itemized changes
#### Features
- `src/core/frontmatter-inference.ts` (new module) — Path-aware frontmatter synthesis. `DIRECTORY_RULES` table maps path prefixes to type/date/title/source/tags. First-match-wins. Date extraction from filenames (`YYYY-MM-DD` prefix or anywhere). Title extraction with date-prefix stripping and first-`#`-heading fallback (20-line window). YAML-safe serialization with quoting for special characters.
- `src/core/import-file.ts``importFromFile()` runs inference inline before `parseMarkdown()` when `opts.inferFrontmatter !== false` (default on). The synthesized frontmatter folds into the in-memory content for parsing, chunking, embedding, and content-hash computation. The file on disk is not modified.
- `src/commands/frontmatter.ts` — New `gbrain frontmatter generate <path> [--fix] [--dry-run] [--json]` subcommand. Walks a directory (skips `.git`, `node_modules`, `.obsidian`, symlinks), runs inference on every `.md` file without frontmatter, optionally writes back with `.bak` backups. Auto-detects brain root by walking up for `.git`. Shows per-type breakdown and first-10 examples.
#### Fixes
- `src/commands/frontmatter.ts:344``runGenerate` dynamic path import now includes `basename`. Single-file invocation (`gbrain frontmatter generate <file>`) previously crashed with `ReferenceError: basename is not defined` on the relative-path-empty fallback at line 437.
#### Tests
- `test/frontmatter-inference.test.ts` (new, 35 cases) — date extraction (5), title extraction from filenames (5) and headings (4 incl. 20-line boundary), inference for every directory rule (13 incl. Apple Notes subfolder tagging), serialization with YAML-safe quoting (4), `applyInference` integration (2), rule ordering and catch-all coverage (2).
## [0.22.14] - 2026-04-29
**Bare `gbrain jobs work` now self-monitors and fail-stops cleanly when its database dies or the queue stalls.**
**The wedged-worker class of bug — process alive, jobs piling up, your `pgrep` check happily green — is gone.**
A production brain (54K pages, Supabase Postgres, 3-concurrency worker under a cron-based PM)
hit it last week: worker process state=Sl at 13:15 UTC, stopped claiming jobs, 21 jobs stacked
in `waiting` over two hours, 5 autopilot-cycles dead-lettered at the 600s timeout, then 150
zombie processes accumulated over the container's 31-day life. The PM's `pgrep` saw a live
PID and reported green the entire time.
Pre-v0.22.14, bare `gbrain jobs work` had **zero** health monitoring. The supervisor (`gbrain
jobs supervisor`) had the right protections — DB liveness probes, stall detection, RSS
watchdog, reconnect on transient PgBouncer blips — but the supervisor wraps `jobs work` as a
child, and many production deployments run bare `jobs work` directly under systemd, Docker,
launchd, cron watchdog, or supervisord. That mode got nothing.
This release moves health monitoring into the bare worker itself, gated by `GBRAIN_SUPERVISED=1`
so it doesn't double up under the supervisor. When the worker detects it's wedged, it emits an
`'unhealthy'` event with a structured reason, and the CLI calls `process.exit(1)` so the external
PM restarts it cleanly. **This is fail-stop:** the worker exits and stays dead until your PM
brings it back. If you run bare `jobs work` without a restart loop, you need one now.
### The numbers that matter
Detection signatures the new health check catches, measured against the production incident
above (and the 30-day deployment running under the band-aid bash watchdog Garry deployed before
this fix):
| Failure mode | Before v0.22.14 | After v0.22.14 |
|---|---|---|
| DB connection death (Supabase/PgBouncer drop) | undetected; worker idles forever | 3 consecutive `SELECT 1` failures (≤3min) → `'unhealthy'`+exit |
| Hung DB probe (network partition) | timer wedged forever, monitoring silently disabled | 10s probe timeout per tick → counted as failure → exit at strike 3 |
| Worker stall (event loop alive, claim returns null) | undetected; jobs pile up in `waiting` | 5min warn, 10min `'unhealthy'`+exit (measured from last completion) |
| Memory leak (RSS climbing past 2GB) | undetected on bare workers | watchdog default 2048 MB triggers `gracefulShutdown('watchdog')` |
| Worker stalled but waiting jobs are unhandled type | ❌ false-positive exit (restart loop) | filter by registered handler names, no exit |
Operationally: from the band-aid bash watchdog Garry deployed before this fix, fresh worker
restart cleared 21 waiting → 0 in 2 minutes, then ran stable for 30+ min with 130 MB RSS,
autopilot-cycles completing in 0.20.6s instead of timing out at 600s.
### What this means for operators
Add a restart policy to your bare-worker invocation BEFORE upgrading. The new behavior is
fail-stop, not self-healing — without a restart loop, your worker will exit on the first DB
blip and stay dead. systemd `Restart=always`, Docker `restart: always`, launchd `KeepAlive`,
cron watchdog, supervisord `autorestart=true`. The migration walks every PM. If you're using
`gbrain jobs supervisor`, you're already protected — the supervisor handles spawn-on-crash
itself.
The default `--max-rss` for bare workers also bumped from 0 (off) to 2048 MB. If you ran bare
workers with intentionally large embed/import jobs, raise the limit (`--max-rss 4096`) or opt
out (`--max-rss 0`). The migration includes per-PM unit-file edits.
## To take advantage of v0.22.14
`gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor` warns about
a bare worker exiting with watchdog signatures:
1. **Confirm your bare-worker invocations have a restart policy:**
```bash
# systemd
grep -E '^Restart=' ~/.config/systemd/user/gbrain-worker.service /etc/systemd/system/gbrain-worker.service 2>/dev/null
# crontab
crontab -l | grep "gbrain jobs work"
# launchctl
plutil -p ~/Library/LaunchAgents/com.user.gbrain-worker.plist | grep -A1 KeepAlive
```
2. **Decide on RSS posture:**
- Default 2048 MB matches supervisor behavior. Most bare workers fit.
- Embed/import jobs > 2GB? Pass `--max-rss 4096` (or higher).
- Intentionally unbounded? Pass `--max-rss 0`.
3. **Walk the migration:** `skills/migrations/v0.22.14.md` has the full per-PM table and a
verification block.
4. **Verify:**
```bash
gbrain jobs stats
gbrain doctor --json | jq '.checks[] | select(.name == "queue_health")'
```
Worker startup line should now read:
`Minion worker started (queue: default, concurrency: 3, watchdog: 2048MB, health-check: 60s)`
Under supervisor: the `health-check: Ns` segment is absent (supervisor handles it).
5. **If anything fails or numbers look wrong**, file an issue at
https://github.com/garrytan/gbrain/issues with `gbrain doctor` output and the contents of
`~/.gbrain/upgrade-errors.jsonl` if it exists.
### Itemized changes
#### Added
- `MinionWorkerOpts.{healthCheckInterval, stallWarnAfterMs, stallExitAfterMs, dbFailExitAfter, dbProbeTimeoutMs}` — five new tuning knobs. Defaults: 60s probe interval, 5min warn / 10min exit, 3 DB strikes, 10s per-probe timeout.
- `MinionWorker` now extends `EventEmitter`. Emits `'unhealthy'` with `{ reason: 'db_dead', consecutiveFailures, message } | { reason: 'stalled', waitingCount, idleMinutes }`. CLI subscribes; direct API consumers without a listener inherit a fail-stop fallback that calls `process.exit(1)` to preserve pre-refactor semantics.
- `gbrain jobs work --health-interval MS` — tune the self-health-check cadence (0 disables; rejects NaN/negative/sub-1000ms typos).
- `gbrain jobs supervisor --health-interval MS` — same flag, same validation, same `0 = disable` contract on the supervisor's own probe.
- `GBRAIN_SUPERVISED=1` env var on the supervisor's spawned worker child (skips the child's self-health timer to avoid double-monitoring).
- `gbrain doctor` `queue_health` subcheck reports RSS-watchdog kills in the last 24h via exact match on `error_text = 'aborted: watchdog'` scoped to `status IN ('dead','failed')`.
- `skills/migrations/v0.22.14.md` — full migration walkthrough with per-PM restart-policy preflight, RSS-posture decision tree, and per-system unit-file edits.
#### Changed
- **Default `--max-rss` for `gbrain jobs work`: 0 → 2048 MB.** Matches supervisor default. Catches memory-leak stalls that previously went undetected on bare workers. Opt out with `--max-rss 0`.
- **Bare-worker behavior is now fail-stop** when the DB is unreachable or the queue stalls. Pre-v0.22.14 the worker idled silently. Now it exits and relies on the external PM (systemd, Docker, launchd, cron, supervisord) to restart cleanly.
- Stall query at `worker.ts` filters by registered handler names (`AND name = ANY($2::text[])`) so workers don't false-positive when waiting jobs of unhandled names accumulate.
- Stall exit threshold measured from `lastCompletionTime` (not from when the warning fired), so 5min warn / 10min exit means total idle of 10 min — not 15 min.
- DB liveness probe wrapped in `Promise.race` against a 10s timeout so a hung `executeRaw` cannot wedge the recursive `setTimeout` chain forever.
- `setInterval` → recursive `setTimeout` with a `running` flag throughout. Eliminates timer-callback overlap on slow probes.
- `parseMaxRssFlag` returns `number | undefined` (was `number`) so callers distinguish absent from explicit-disable.
- `process.env.GBRAIN_SUPERVISED` check tightened from `!!env.X` to `=== '1'` (precise contract; no fuzzy matching on `'0'` or `'false'`).
- `MinionWorker` constructor throws when `stallExitAfterMs <= stallWarnAfterMs` so misconfigurations fail loudly at startup.
#### Fixed
- **Wedged-worker false-positive on heterogeneous queues** — workers registering only some handlers no longer interpret waiting jobs of other names as a stall. Repeated `process.exit(1)` → restart loop is gone.
- **Hung DB probe wedge** — pre-fix, a hung `executeRaw('SELECT 1')` kept the recursive `setTimeout` from rescheduling, silently disabling the entire health monitor. Post-fix, the probe times out and counts as a failure.
- **`--health-interval 0` no longer DB-hammers the supervisor.** Pre-fix, the documented "0 disables" contract was a lie — `setInterval(cb, 0)` schedules a tight loop. Now gated behind `> 0`.
- **Inline `jobs submit --follow` and `jobs smoke` no longer kill the user's CLI session** on a DB blip. Both now pass `healthCheckInterval: 0` so the no-listener fallback can't trip on one-shot runs.
- Doctor's RSS-watchdog hint matches the actual error_text signature (`'aborted: watchdog'`) instead of the wrong `'memory limit'` literal that never matched.
#### For contributors
- `MinionWorker extends EventEmitter` — if you import the class directly, the `on('unhealthy', ...)` event is now part of the public surface. The `UnhealthyReason` discriminated union is exported from `src/core/minions/worker.ts`.
- New regression-test infrastructure in `test/minions.test.ts`: `makeProbeEngine(overrides)` is a Proxy-based engine wrapper that intercepts `SELECT 1` and the stall `count(*)` query while passing every other call through to the real PGLite engine. Useful for any future test that needs to inject DB liveness or stall semantics without mocking the entire engine surface.
### Adjacent (separate PR, v0.22.15)
PR #503 catches the *symptom* of one specific failure mode. The cause-side fix — `runPhaseEmbed → embed.ts → embedBatch` not honoring `signal.aborted` between OpenAI batch calls — ships in v0.22.15 (highest-priority TODO; daily wedge driver). Plumbing is documented in `TODOS.md`.
## [0.22.13] - 2026-04-28
**Sync got faster, and the bookmark stopped lying.**
+13
View File
@@ -114,6 +114,9 @@ strict behavior when unset.
- `src/commands/sync.ts``gbrain sync` CLI + the `performSync` / `performFullSync` library entrypoints (consumed by the autopilot cycle and the Minion sync handler). v0.22.13 (PR #490): `performSync` wraps its body in a `gbrain-sync` writer lock so two concurrent syncs (manual + autopilot, two terminals, two Conductor workspaces) cannot both write `last_commit` and let the last writer win. Head-drift gate after the import phase re-checks `git rev-parse HEAD`; if HEAD moved (someone ran `git checkout` / `git pull` mid-sync), the bookmark refuses to advance. Vanished files now record a failedFiles entry instead of silent-skip — the silent-skip-then-advance pathology that survived prior hardening passes is dead. Worker engines wrap in try/finally so disconnect always fires (panic-path leak fix). Both PGLite-detection sites use `engine.kind === 'pglite'`. CLI accepts `--workers N` (alias `--concurrency N`), validated via `parseWorkers`. Explicit `--workers` bypasses the auto-path file-count floor; auto path defers to `autoConcurrency()`. Banner moved to stderr.
- `src/core/cycle.ts` — v0.17 brain maintenance cycle primitive. `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes 6 phases in semantically-driven order (lint → backlinks → sync → extract → embed → orphans). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon's inline path, and the Minions `autopilot-cycle` handler (`src/commands/jobs.ts`). One source of truth for what the brain does overnight. Coordination via `gbrain_cycle_locks` DB table (TTL-based; works through PgBouncer transaction pooling, unlike session-scoped `pg_try_advisory_lock`) + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite / engine=null mode. `CycleReport.schema_version: "1"` is the stable agent-consumable shape. `PhaseResult.error: { class, code, message, hint?, docs_url? }` is Stripe-API-tier structured failure info. `yieldBetweenPhases` hook awaited between every phase — Minions handler uses this to renew its job lock and prevent v0.14 stall-death regression. Engine nullable: filesystem phases (lint, backlinks) run without DB; DB phases skip with `status: "skipped", reason: "no_database"`. Lock-skip: read-only phase selections (`--phase orphans`) bypass the cycle lock. v0.22.1 (#403): `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal; `checkAborted()` fires between every phase and throws if the signal is aborted (cooperative — can't interrupt a phase mid-execution). v0.22.1 (#417): `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult`; `runCycle` captures it and threads to `runPhaseExtract` as the 4th arg, enabling incremental extract on the cycle path. v0.22.1 (Codex F2): `runPhaseSync` takes `willRunExtractPhase: boolean` and sets `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. v0.22.5 (#475): new `resolveSourceForDir(engine, brainDir)` helper queries `SELECT id FROM sources WHERE local_path = $1 LIMIT 1`; `runPhaseSync` threads result as `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor instead of the drift-prone global `config.sync.last_commit` key. Bare try/catch lets pre-v0.18 brains fall through to the global key. Closes the prod hang where every autopilot cycle ran a 30-min full reimport because the global anchor commit had been GC'd from git history.
- `src/commands/dream.ts` — v0.17 `gbrain dream` CLI. ~80-line thin alias over `runCycle`. brainDir resolution requires explicit `--dir` OR `sync.repo_path` config (no more walk-up-cwd-for-.git footgun). Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`. Exit code 1 on status=failed (partial/warn not fatal — don't page on warnings).
- `src/commands/friction.ts` + `src/core/friction.ts` (v0.23) — `gbrain friction {log,render,list,summary}` reporter. Append-only JSONL under `$GBRAIN_HOME/friction/<run-id>.jsonl`. Schema is a flat extension of `StructuredAgentError` (D20). Render groups by severity → phase, defaults to `--redact` for md output (strips `$HOME`/`$CWD` to placeholders so reports paste safely in PRs). Run-id resolves from `--run-id` > `$GBRAIN_FRICTION_RUN_ID` > `standalone.jsonl`. Skills the claw-test exercises gain a `_friction-protocol.md` callout so agents know when to log friction.
- `src/commands/claw-test.ts` + `src/core/claw-test/` (v0.23) — `gbrain claw-test [--scenario <name>] [--live --agent openclaw]`. End-to-end "fresh user" friction harness. Two modes: scripted (CI gate, agent-free) and live (real openclaw subprocess, $12 in tokens). Sets `GBRAIN_HOME=<tempdir>` for hermeticity and captures gbrain's `--progress-json` events from each child's stderr to verify expected phases ran (`import.files`, `extract.links_fs`, `doctor.db_checks`). Phases for scripted mode: setup → install_brain (`gbrain init --pglite`) → import (`--no-embed`) → query → extract → verify (`gbrain doctor --json`, asserts `status: 'ok'`) → render. Live mode hands `BRIEF.md` from `test/fixtures/claw-test-scenarios/<name>/` to the agent runner. v1 ships with the OpenClaw runner only (`src/core/claw-test/runners/openclaw.ts`, invokes `openclaw agent --local --agent <name> --message <brief>`); hermes runner deferred to v1.1. Transcript capture (`transcript-capture.ts`) uses `fs.createWriteStream` with `'drain'`-event backpressure — D17 fix for the 256KB-burst child-stall scenario. v0.18 upgrade scenario seeded via `seed-pglite.ts` SQL replay.
- `skills/_friction-protocol.md` (v0.23) — shared cross-cutting convention skill (like `_brain-filing-rules.md`). Tells agents when to call `gbrain friction log` and how to choose a severity. Routes to friction CLI from any skill the claw-test exercises.
- `scripts/check-progress-to-stdout.sh` — CI guard against regressing to `\r`-on-stdout progress. Wired into `bun run test` via `scripts/check-progress-to-stdout.sh && bun test` in package.json.
- `docs/progress-events.md` — Canonical JSON event schema reference. Stable from v0.15.2, additive only.
- `src/core/markdown.ts` — Frontmatter parsing + body splitter. `splitBody` requires an explicit timeline sentinel (`<!-- timeline -->`, `--- timeline ---`, or `---` immediately before `## Timeline`/`## History`). Plain `---` in body text is a markdown horizontal rule, not a separator. `inferType` auto-types `/wiki/analysis/` → analysis, `/wiki/guides/` → guide, `/wiki/hardware/` → hardware, `/wiki/architecture/` → architecture, `/writing/` → writing (plus the existing people/companies/deals/etc heuristics).
@@ -227,6 +230,16 @@ Key commands added in v0.22.13 (PR #490):
- `gbrain sync --workers N` (alias `--concurrency N`) — parallelize the import phase using per-worker Postgres engines (small pool of 2 each) with an atomic queue index. Auto-concurrency: defaults to 4 workers when the diff exceeds 100 files. Smaller diffs stay serial. Explicit `--workers` always wins (even on a 30-file diff). PGLite forces serial regardless. Validation rejects `0`, negatives, non-integers loud (replaces the prior silent fall-through to auto-concurrency).
- `gbrain import --workers N` — same `parseWorkers()` validation as sync; same try/finally worker-engine cleanup. Behavior surface unchanged.
Key commands added in v0.22.16 (claw-test friction loop):
- `gbrain claw-test [--scenario fresh-install|upgrade-from-v0.18] [--keep-tempdir]` — scripted-mode CI gate that runs the full canonical first-day flow against a fresh tempdir. Asserts every expected `--progress-json` phase fired and doctor's `status === 'ok'`. ~30s, no API keys.
- `gbrain claw-test --live --agent openclaw` — friction-discovery mode. Spawns real openclaw, hands it `BRIEF.md`, captures stdin/stdout/stderr to `<run>/transcript.jsonl`, lets the agent log friction via the friction CLI. Run on demand; ~510 min and ~$12 in tokens.
- `gbrain claw-test --list-agents` — reports which agent runners are registered + their detection state (binary path or unavailable reason).
- `gbrain friction log --severity {confused|error|blocker|nit} --phase <name> --message <text> [--hint ...] [--kind {friction|delight}] [--run-id ...]` — append a friction or delight entry to the active run JSONL.
- `gbrain friction render --run-id <id> [--json] [--transcripts] [--no-redact]` — markdown report grouped by severity + phase; `--redact` is the default for md output (strips `$HOME`/`$CWD` placeholders so reports paste safely in PRs/issues).
- `gbrain friction list [--json]` — recent run-ids with friction/delight counts; interrupted runs marked `(interrupted)`.
- `gbrain friction summary --run-id <id> [--json]` — two-column friction + delight summary.
- `GBRAIN_HOME` env override is now honored uniformly across every gbrain write site (config, audit, friction, sync-failures, import checkpoint, integrity log, integrations heartbeat, migration rollback, etc.) — `gbrainPath(...)` from `src/core/config.ts` is the canonical helper. Read-side host-fingerprint detection (`~/.claude`/`~/.openclaw` etc.) intentionally NOT confined in v1; that's a v1.1 follow-up.
## Testing
`bun test` runs all tests. After the v0.12.1 release: ~75 unit test files + 8 E2E test files (1412 unit pass, 119 E2E when `DATABASE_URL` is set — skip gracefully otherwise). Unit tests run
+207
View File
@@ -1,5 +1,212 @@
# TODOS
## claw-test E2E (v0.22.16 follow-ups)
### Hermes runner — `src/core/claw-test/runners/hermes.ts`
**Priority:** P2
**What:** Add a Hermes implementation of the `AgentRunner` interface. v1 ships only OpenClaw; v1.1 lands hermes once we have real friction reports from openclaw to validate the contract against.
**Why:** Cross-agent diff (`gbrain friction diff --base openclaw --compare hermes`) is the highest-leverage next signal. Friction unique to one agent vs common-to-both separates "agent contract bug" from "gbrain bug" automatically.
**Effort:** S (CC ~30m). Depends on: v1 openclaw runner producing real friction reports first.
---
### Friction analytics suite — `diff` / `trend` / `migration-stub`
**Priority:** P2
**What:** Three new `gbrain friction` subcommands deferred from v1:
- `gbrain friction diff --base <run-or-agent> --compare <run-or-agent>` (cross-agent comparison; ~80 LOC)
- `gbrain friction trend [--since <version-or-date>] [--phase <name>]` (time-series across runs; ~60 LOC)
- `gbrain friction migration-stub [--threshold N]` (clusters friction by phase + tokens, emits `skills/migrations/v[N+1].md` stub; ~150 LOC)
**Why:** Turns point-in-time reports into a slope. Pairs with the v1.1 public scoreboard.
**Effort:** M (CC ~2h total).
---
### Scenario expansion — `supabase-migration` and `supervisor-restart`
**Priority:** P2
**What:** Two more scenarios under `test/fixtures/claw-test-scenarios/`:
- `supabase-migration``gbrain init --pglite` then `gbrain migrate --to supabase`; verifies the cross-engine migration path
- `supervisor-restart` — kill worker mid-job; verify supervisor recovers without data loss
**Why:** These are the other highest-historical-pain regression points (per CLAUDE.md fix-wave history). v1 ships only `fresh-install` + `upgrade-from-v0.18` because Codex flagged that mixing them dilutes the fresh-install signal; v1.1 lands them as separate scenarios.
**Effort:** M (CC ~1h each).
---
### Real v0.18 SQL dump for upgrade scenario
**Priority:** P2
**What:** The `upgrade-from-v0.18` scenario ships scaffolded — `seed/dump.sql` is missing. The harness gracefully no-ops the seed phase when absent, so the scenario currently behaves like fresh-install. v1.1: generate a real v0.18-shape PGLite dump per the procedure documented in `test/fixtures/claw-test-scenarios/upgrade-from-v0.18/seed/README.md`.
**Why:** Without a real seed, the scenario doesn't actually exercise the migration chain forward-walk. That's the whole point of the upgrade scenario — proves issue #239/#243/#266/#357 class regressions stay fixed.
**Effort:** S (CC ~30m once a v0.18 checkout is handy). Depends on: ability to run a v0.18 gbrain build.
---
### Public scoreboard — `gbrain-evals.io/friction`
**Priority:** P3
**What:** Sibling-repo PR in `garrytan/gbrain-evals` that renders friction JSONL into a public dashboard. Friction count per version per agent, line charts over time. v1's JSONL already includes `gbrain_version` + `agent` tags so the scoreboard is a thin layer on top.
**Why:** Marketing surface. Proves install quality is improving release-over-release. The friction loop becomes visible to the world, not just maintainers.
**Effort:** M. Depends on: a working live mode and ≥10 real friction reports.
---
### PTY-mode transcript capture
**Priority:** P3
**What:** `transcript-capture.ts` currently uses plain `child_process.spawn` pipes. Some agents only emit ANSI colors / progress UI on a TTY. v1.1 adds a PTY mode (likely via `node-pty`) so live-mode transcripts capture the full agent UX.
**Why:** Faithful transcripts make the friction → reasoning link more useful. v1 accepts that some agent UI is lost.
**Effort:** S (CC ~30m). Mostly a ~30 LOC swap inside `spawnWithCapture`.
---
### Read-side host-isolation (`$GBRAIN_HOST_HOME`)
**Priority:** P3
**What:** v0.22.16 confined every `~/.gbrain` write site to honor `$GBRAIN_HOME`. But `src/commands/init.ts:299-313` still reads real `~/.claude` / `~/.openclaw` / `~/.codex` / `~/.factory` / `~/.kiro` for module fingerprinting (host detection). Even with write-isolation, a claw-test running on a developer's box discovers their real installed mods. v1.1: add a separate `$GBRAIN_HOST_HOME` override for the read-side detection so the claw-test can run truly hermetic.
**Why:** v1's hermeticity contract is "writes are isolated, reads are not." v1.1 closes the read-side gap.
**Effort:** S (CC ~30m).
---
### Routing-callout sweep — annotate skills the claw-test exercises
**Priority:** P3
**What:** `skills/_friction-protocol.md` is a cross-cutting convention. v1.1: sweep the 46 skills the claw-test actually exercises (setup, brain-ops, query, ingest, smoke-test, the migrations the test covers) and add a `> **Convention:** see [skills/_friction-protocol.md](_friction-protocol.md).` callout via the existing `src/core/dry-fix.ts` shape so DRY auto-fix doesn't fight it.
**Why:** Right now agents only call `gbrain friction log` if they find the protocol skill on their own. The callouts route them there proactively from any harness-exercised skill.
**Effort:** S (CC ~15m).
---
## minions / worker (v0.22.14 follow-ups)
### v0.22.15 — Embed cooperative-abort (HIGHEST PRIORITY — daily pain)
**Priority:** P0
**What:** Plumb `signal: AbortSignal` through `runPhaseEmbed`
`src/commands/embed.ts``embedBatch` in `src/core/embedding.ts`. Check
`signal?.aborted` between OpenAI batch calls (every ~100 texts, ~2s
real-time) and between slugs in the per-slug loop.
**Why:** Embed phase ignores `signal.aborted` between batches today. Job
wall-clock timeout fires → handler keeps running → cycle's finally block
unreachable → `gbrain_cycle_locks` row stays held indefinitely. Every
subsequent autopilot cron cycle sees `cycle_already_running` → skips. Lock
TTL is 30 min; new cycles give up before that. Doctor reports UNHEALTHY.
**The chain in production:** ~5min cron submits cycle → 22K stale pages →
embed phase takes 1015 min → 600s timeout fires → job dead-lettered → embed
keeps running → lock held → all subsequent cycles skip. Garry hits this
DAILY on his production brain.
**Pros:** Closes the daily wedge. Makes timeouts actually effective. Lets
operators bump worker timeouts confidently knowing abort actually stops
work.
**Cons:** Touching the embed hot path; small risk of botching the abort
checks. Mitigation: between-batch granularity (~2s), not per-text (too fine)
or per-slug (too coarse for 500+ chunk slugs).
**Context:** PR #503 (v0.22.14) catches the SYMPTOM (worker stalled, queue
piling up) via self-health-monitoring. This PR catches the CAUSE for one
specific failure class. Both fixes are needed; they're complementary, not
duplicative.
**Files to touch:**
- `src/core/cycle.ts:579``runPhaseEmbed(engine, dryRun)` → add
`signal?: AbortSignal` arg
- `src/core/cycle.ts:803` — pass `opts.signal` through
- `src/commands/embed.ts:~363` — accept signal, check between slugs
- `src/core/embedding.ts:51-56``embedBatch(texts, onProgress?, signal?)`,
check between for-loop iterations of `BATCH_SIZE` slices
**Tests required:**
1. embedBatch checks signal between OpenAI calls; aborts within one batch (~2s)
2. Per-slug loop in `embed.ts` checks signal between slugs
3. End-to-end: cycle handler with embed phase + signal aborted mid-flight →
finally runs → `gbrain_cycle_locks` row deleted
4. Regression: 1K+ chunks scenario — embed does NOT block lock release when
timeout fires
**Effort:** M (human: ~3 hr / CC: ~30 min).
**Depends on / blocked by:** Nothing. v0.22.14 ships first.
### v0.23+ — Bare-worker engine reconnect parity with supervisor
**Priority:** P2
**What:** Extract the supervisor's reconnect-then-fail pattern into
`MinionWorker` so bare workers can retry transient DB blips before exiting.
Today the supervisor calls `engine.reconnect()` after 3 consecutive DB health
failures (#406); the bare worker just emits `'unhealthy'` and the CLI calls
`process.exit(1)`.
**Why:** Bare-worker behavior is more disruptive than supervised behavior on
transient PgBouncer blips. A bare worker restarts the entire process; a
supervised worker just reconnects the pool. Operationally the supervisor
approach is gentler (no in-flight job loss, no PM restart latency).
**Pros:** Unifies bare and supervised behavior. Reduces process churn on
transient network blips.
**Cons:** More code in MinionWorker; risk of reconnect masking a real
problem. Mitigation: cap retry attempts, fall through to `'unhealthy'`
emission after the cap.
**Context:** Filed during v0.22.14 plan-eng-review. The asymmetry is
documented in v0.22.14 CHANGELOG as deliberate; this TODO captures the
"unify someday" intent.
**Effort:** S (human: ~2 hr / CC: ~20 min).
**Depends on / blocked by:** Nothing.
### v0.23+ — `minion_workers` heartbeat table for queue_health doctor (B7)
**Priority:** P3
**What:** Add a `minion_workers` table (`worker_id` PK, `hostname`,
`last_heartbeat`, `queue`, `concurrency`, `started_at`) so the existing
`queue_health` doctor check (Postgres path) can detect dead workers via
heartbeat staleness instead of relying on the indirect `lock_until` proxy.
**Why:** v0.19.1 added `queue_health` checks for stalled-active jobs and
waiting-depth threshold. The worker-heartbeat subcheck was deferred (B7)
because the `lock_until`-on-active-jobs proxy can't distinguish "worker
exited cleanly" from "worker idle" — a check that cries wolf erodes trust
in every doctor check. With a real heartbeat row, doctor can say "no worker
seen in N intervals" with confidence.
**Pros:** Doctor's `queue_health` becomes ground-truth. Detects "worker
container died but cron didn't restart it" scenario.
**Cons:** New table, schema migration, every health-tick UPSERTs. Costs
a write per worker per minute (default).
**Context:** Filed during v0.22.14 plan-eng-review. PR #503's self-health
monitoring is the worker-side liveness; this would be the queue-side
ground-truth.
**Effort:** M (human: ~1 day / CC: ~1 hr).
**Depends on / blocked by:** Schema migration system; nothing else.
## sync (v0.22.13 follow-up — PR #490 review)
### D-PR490-1 — Plumb resolved `database_url` through `SyncOpts`
+1 -1
View File
@@ -1 +1 @@
0.22.13
0.22.16
+13
View File
@@ -193,6 +193,9 @@ strict behavior when unset.
- `src/commands/sync.ts` — `gbrain sync` CLI + the `performSync` / `performFullSync` library entrypoints (consumed by the autopilot cycle and the Minion sync handler). v0.22.13 (PR #490): `performSync` wraps its body in a `gbrain-sync` writer lock so two concurrent syncs (manual + autopilot, two terminals, two Conductor workspaces) cannot both write `last_commit` and let the last writer win. Head-drift gate after the import phase re-checks `git rev-parse HEAD`; if HEAD moved (someone ran `git checkout` / `git pull` mid-sync), the bookmark refuses to advance. Vanished files now record a failedFiles entry instead of silent-skip — the silent-skip-then-advance pathology that survived prior hardening passes is dead. Worker engines wrap in try/finally so disconnect always fires (panic-path leak fix). Both PGLite-detection sites use `engine.kind === 'pglite'`. CLI accepts `--workers N` (alias `--concurrency N`), validated via `parseWorkers`. Explicit `--workers` bypasses the auto-path file-count floor; auto path defers to `autoConcurrency()`. Banner moved to stderr.
- `src/core/cycle.ts` — v0.17 brain maintenance cycle primitive. `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes 6 phases in semantically-driven order (lint → backlinks → sync → extract → embed → orphans). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon's inline path, and the Minions `autopilot-cycle` handler (`src/commands/jobs.ts`). One source of truth for what the brain does overnight. Coordination via `gbrain_cycle_locks` DB table (TTL-based; works through PgBouncer transaction pooling, unlike session-scoped `pg_try_advisory_lock`) + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite / engine=null mode. `CycleReport.schema_version: "1"` is the stable agent-consumable shape. `PhaseResult.error: { class, code, message, hint?, docs_url? }` is Stripe-API-tier structured failure info. `yieldBetweenPhases` hook awaited between every phase — Minions handler uses this to renew its job lock and prevent v0.14 stall-death regression. Engine nullable: filesystem phases (lint, backlinks) run without DB; DB phases skip with `status: "skipped", reason: "no_database"`. Lock-skip: read-only phase selections (`--phase orphans`) bypass the cycle lock. v0.22.1 (#403): `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal; `checkAborted()` fires between every phase and throws if the signal is aborted (cooperative — can't interrupt a phase mid-execution). v0.22.1 (#417): `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult`; `runCycle` captures it and threads to `runPhaseExtract` as the 4th arg, enabling incremental extract on the cycle path. v0.22.1 (Codex F2): `runPhaseSync` takes `willRunExtractPhase: boolean` and sets `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. v0.22.5 (#475): new `resolveSourceForDir(engine, brainDir)` helper queries `SELECT id FROM sources WHERE local_path = $1 LIMIT 1`; `runPhaseSync` threads result as `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor instead of the drift-prone global `config.sync.last_commit` key. Bare try/catch lets pre-v0.18 brains fall through to the global key. Closes the prod hang where every autopilot cycle ran a 30-min full reimport because the global anchor commit had been GC'd from git history.
- `src/commands/dream.ts` — v0.17 `gbrain dream` CLI. ~80-line thin alias over `runCycle`. brainDir resolution requires explicit `--dir` OR `sync.repo_path` config (no more walk-up-cwd-for-.git footgun). Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`. Exit code 1 on status=failed (partial/warn not fatal — don't page on warnings).
- `src/commands/friction.ts` + `src/core/friction.ts` (v0.23) — `gbrain friction {log,render,list,summary}` reporter. Append-only JSONL under `$GBRAIN_HOME/friction/<run-id>.jsonl`. Schema is a flat extension of `StructuredAgentError` (D20). Render groups by severity → phase, defaults to `--redact` for md output (strips `$HOME`/`$CWD` to placeholders so reports paste safely in PRs). Run-id resolves from `--run-id` > `$GBRAIN_FRICTION_RUN_ID` > `standalone.jsonl`. Skills the claw-test exercises gain a `_friction-protocol.md` callout so agents know when to log friction.
- `src/commands/claw-test.ts` + `src/core/claw-test/` (v0.23) — `gbrain claw-test [--scenario <name>] [--live --agent openclaw]`. End-to-end "fresh user" friction harness. Two modes: scripted (CI gate, agent-free) and live (real openclaw subprocess, $12 in tokens). Sets `GBRAIN_HOME=<tempdir>` for hermeticity and captures gbrain's `--progress-json` events from each child's stderr to verify expected phases ran (`import.files`, `extract.links_fs`, `doctor.db_checks`). Phases for scripted mode: setup → install_brain (`gbrain init --pglite`) → import (`--no-embed`) → query → extract → verify (`gbrain doctor --json`, asserts `status: 'ok'`) → render. Live mode hands `BRIEF.md` from `test/fixtures/claw-test-scenarios/<name>/` to the agent runner. v1 ships with the OpenClaw runner only (`src/core/claw-test/runners/openclaw.ts`, invokes `openclaw agent --local --agent <name> --message <brief>`); hermes runner deferred to v1.1. Transcript capture (`transcript-capture.ts`) uses `fs.createWriteStream` with `'drain'`-event backpressure — D17 fix for the 256KB-burst child-stall scenario. v0.18 upgrade scenario seeded via `seed-pglite.ts` SQL replay.
- `skills/_friction-protocol.md` (v0.23) — shared cross-cutting convention skill (like `_brain-filing-rules.md`). Tells agents when to call `gbrain friction log` and how to choose a severity. Routes to friction CLI from any skill the claw-test exercises.
- `scripts/check-progress-to-stdout.sh` — CI guard against regressing to `\r`-on-stdout progress. Wired into `bun run test` via `scripts/check-progress-to-stdout.sh && bun test` in package.json.
- `docs/progress-events.md` — Canonical JSON event schema reference. Stable from v0.15.2, additive only.
- `src/core/markdown.ts` — Frontmatter parsing + body splitter. `splitBody` requires an explicit timeline sentinel (`<!-- timeline -->`, `--- timeline ---`, or `---` immediately before `## Timeline`/`## History`). Plain `---` in body text is a markdown horizontal rule, not a separator. `inferType` auto-types `/wiki/analysis/` → analysis, `/wiki/guides/` → guide, `/wiki/hardware/` → hardware, `/wiki/architecture/` → architecture, `/writing/` → writing (plus the existing people/companies/deals/etc heuristics).
@@ -306,6 +309,16 @@ Key commands added in v0.22.13 (PR #490):
- `gbrain sync --workers N` (alias `--concurrency N`) — parallelize the import phase using per-worker Postgres engines (small pool of 2 each) with an atomic queue index. Auto-concurrency: defaults to 4 workers when the diff exceeds 100 files. Smaller diffs stay serial. Explicit `--workers` always wins (even on a 30-file diff). PGLite forces serial regardless. Validation rejects `0`, negatives, non-integers loud (replaces the prior silent fall-through to auto-concurrency).
- `gbrain import --workers N` — same `parseWorkers()` validation as sync; same try/finally worker-engine cleanup. Behavior surface unchanged.
Key commands added in v0.22.16 (claw-test friction loop):
- `gbrain claw-test [--scenario fresh-install|upgrade-from-v0.18] [--keep-tempdir]` — scripted-mode CI gate that runs the full canonical first-day flow against a fresh tempdir. Asserts every expected `--progress-json` phase fired and doctor's `status === 'ok'`. ~30s, no API keys.
- `gbrain claw-test --live --agent openclaw` — friction-discovery mode. Spawns real openclaw, hands it `BRIEF.md`, captures stdin/stdout/stderr to `<run>/transcript.jsonl`, lets the agent log friction via the friction CLI. Run on demand; ~510 min and ~$12 in tokens.
- `gbrain claw-test --list-agents` — reports which agent runners are registered + their detection state (binary path or unavailable reason).
- `gbrain friction log --severity {confused|error|blocker|nit} --phase <name> --message <text> [--hint ...] [--kind {friction|delight}] [--run-id ...]` — append a friction or delight entry to the active run JSONL.
- `gbrain friction render --run-id <id> [--json] [--transcripts] [--no-redact]` — markdown report grouped by severity + phase; `--redact` is the default for md output (strips `$HOME`/`$CWD` placeholders so reports paste safely in PRs/issues).
- `gbrain friction list [--json]` — recent run-ids with friction/delight counts; interrupted runs marked `(interrupted)`.
- `gbrain friction summary --run-id <id> [--json]` — two-column friction + delight summary.
- `GBRAIN_HOME` env override is now honored uniformly across every gbrain write site (config, audit, friction, sync-failures, import checkpoint, integrity log, integrations heartbeat, migration rollback, etc.) — `gbrainPath(...)` from `src/core/config.ts` is the canonical helper. Read-side host-fingerprint detection (`~/.claude`/`~/.openclaw` etc.) intentionally NOT confined in v1; that's a v1.1 follow-up.
## Testing
`bun test` runs all tests. After the v0.12.1 release: ~75 unit test files + 8 E2E test files (1412 unit pass, 119 E2E when `DATABASE_URL` is set — skip gracefully otherwise). Unit tests run
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "gbrain",
"version": "0.22.13",
"version": "0.22.16",
"description": "Postgres-native personal knowledge brain with hybrid RAG search",
"type": "module",
"main": "src/core/index.ts",
+60
View File
@@ -0,0 +1,60 @@
# Friction protocol — convention
> Cross-cutting rule shared by skills the claw-test harness exercises (setup,
> brain-ops, query, ingest, smoke-test, migrations). Reference via
> `> **Convention:** see [skills/_friction-protocol.md](_friction-protocol.md).`
When you encounter friction running gbrain — anything confusing, missing, surprising, or wrong — log it via `gbrain friction log` so maintainers can see it without you writing a bug report. Friction reports drive the claw-test feedback loop (the harness collects, renders, and re-runs).
## When to log
Log friction when any of these happens:
- A command failed with a non-actionable error message
- A doc said one thing and the tool did another
- You couldn't find the next step
- A setup command needed a manual workaround
- A flag exists but isn't documented in `--help`
- A success condition was unclear (you couldn't tell if the command worked)
Log delight (positive signal) when:
- Something worked on the first try and the docs were exactly right
- An error message handed you the fix
- A flag you guessed at turned out to exist with the obvious name
## How to log
```
gbrain friction log \
--severity {confused|error|blocker|nit} \
--phase <which-phase-or-command> \
--message "<one-line-what-happened>" \
[--hint "<one-line-what-could-be-better>"]
```
For delight, add `--kind delight` and pick any severity.
The CLI auto-fills `ts`, `cwd`, `gbrain_version`, and resolves `run_id` from `$GBRAIN_FRICTION_RUN_ID` (set by the harness) or falls back to `standalone.jsonl`. So you can call this anywhere — inside a harness run, manually during normal use, or from a scripted test.
## Severity guide
| severity | meaning |
|------------|---------|
| `blocker` | Couldn't proceed at all. Hard stop. |
| `error` | Command failed unexpectedly. |
| `confused` | Docs/tool mismatch, ambiguity, missing pointer. |
| `nit` | Polish opportunity. Cosmetic or low-impact. |
Be specific: "doctor says `schema_version=0` and points at apply-migrations, but apply-migrations exits 0 with no output" beats "doctor was confusing."
## Inspecting reports
```
gbrain friction list # recent runs with counts
gbrain friction render --run-id <id> # markdown report (default)
gbrain friction render --run-id <id> --json
gbrain friction summary --run-id <id> # friction + delight side-by-side
```
`render` defaults to `--redact` for markdown (strips `$HOME`/`$CWD` to `<HOME>`/`<CWD>` placeholders) so reports paste safely into PRs and issues.
+210
View File
@@ -0,0 +1,210 @@
---
feature_pitch:
headline: Bare workers now self-monitor and fail-stop into your PM's restart loop
body: |
Bare `gbrain jobs work` now ships with the same health protection the
supervisor already had: DB liveness probes (with per-probe timeout so a
hung connection can't wedge the monitor), stall detection filtered by
registered handler names, and an RSS watchdog default of 2048 MB.
When the worker detects it's wedged (stuck pgbouncer connection, hung
event loop, stalled job claim), it emits `'unhealthy'` and the CLI calls
`process.exit(1)`. This is **fail-stop**: it requires an external process
manager (systemd, Docker `restart: always`, launchd `KeepAlive`, cron
watchdog) to bring the worker back. Without one, the process exits and
stays dead — that's a regression from pre-v0.22.14 self-healing.
Pre-v0.22.14 behavior: bare workers had ZERO health monitoring. A wedged
worker stayed alive doing nothing while jobs piled up in `waiting` and
your PM's `pgrep` check happily reported green.
If you're using `gbrain jobs supervisor`, you're already protected — the
supervisor handles spawn-on-crash itself. The fail-stop concern only
applies to direct `gbrain jobs work` invocations.
---
# v0.22.14 — Bare-worker self-health-monitoring
## ⚠️ Pre-flight: confirm you have a process supervisor
If you run `gbrain jobs work` directly (NOT under `gbrain jobs supervisor`),
verify your process manager is configured to restart the worker on exit
BEFORE upgrading:
| Manager | What to check |
|---|---|
| systemd | `Restart=always` (or `Restart=on-failure`) in the `.service` unit |
| Docker | `restart: always` / `restart: unless-stopped` in compose, OR `--restart` flag |
| launchd (macOS) | `<key>KeepAlive</key><true/>` in the plist |
| cron watchdog | Cron entry that re-spawns when `pgrep -f "gbrain jobs work"` is empty |
| supervisord | `autorestart=true` |
**If your bare worker has no restart loop, the v0.22.14 fail-stop behavior
will leave you with a dead worker after the first DB blip.** Either add a
restart policy OR switch to `gbrain jobs supervisor` (which spawns its own
child + restarts on crash internally).
## What ships
- DB liveness probes inside `gbrain jobs work` (60s interval, 3 strikes → exit)
- Stall detection (5min warn / 10min exit when waiting jobs accumulate but
in-flight is empty)
- `--max-rss` defaults to 2048 MB for bare workers (matches supervisor default;
was 0 = disabled)
- New `MinionWorkerOpts.{healthCheckInterval, stallWarnAfterMs,
stallExitAfterMs, dbFailExitAfter, dbProbeTimeoutMs}` for tuning (5 fields)
- `MinionWorker` now extends `EventEmitter`; emits `'unhealthy'` event with
a structured reason payload. **No-listener fallback**: if the caller does
not subscribe to `'unhealthy'`, the worker calls `process.exit(1)` itself
to preserve the pre-refactor fail-stop behavior. The CLI subscribes; direct
API consumers without a listener inherit the fail-stop default. Inline
paths (`jobs submit --follow`, `jobs smoke`) explicitly pass
`healthCheckInterval: 0` to disable the timer entirely so the fallback
cannot trip on a one-shot run.
- `GBRAIN_SUPERVISED=1` env var (set by supervisor on its child) causes the
child worker to skip its own health timer (no double-monitoring)
- Constructor validation: throws if `stallExitAfterMs <= stallWarnAfterMs`
(the contract requires strict greater-than)
## ⚠️ Breaking change you may need to act on
**`gbrain jobs work` now defaults `--max-rss 2048` (MB).** Pre-v0.22.14, bare
workers had no RSS limit. If you ran bare workers with intentionally large
embed/import working sets, your worker may now get killed by the watchdog after
upgrade.
**You need to act if any of the following is true:**
- You run `gbrain jobs work` directly under a process manager (systemd, Docker,
cron, supervisord, your own bash wrapper)
- Your worker handles large embed batches, multi-GB import jobs, or
memory-intensive subagent tasks that legitimately exceed 2 GB RSS
- You rely on bare-worker resident memory exceeding 2 GB
**You do NOT need to act if:**
- You run `gbrain jobs supervisor` (the supervisor already defaulted to
`--max-rss 2048` and has reconnect-then-fail logic on top)
- Your typical worker stays well under 2 GB RSS
## What the agent should do post-upgrade
### 1. Run the orchestrator (mechanical migration)
```bash
gbrain apply-migrations --yes
```
This is a no-op for v0.22.14 — there's no schema migration. The mechanical work
is in the binary; the user-side decision is the breaking-change handling below.
### 2. Detect bare-worker deployments
If the user runs OpenClaw, Hermes, or any agent fork that uses `gbrain jobs
work` directly (NOT under `gbrain jobs supervisor`), they need to know. Check:
```bash
# Look for bare worker invocations in cron, systemd, Docker, launchctl, etc.
grep -r "gbrain jobs work" ~/.config/systemd/ /etc/systemd/ 2>/dev/null | head
crontab -l 2>/dev/null | grep "gbrain jobs work" | head
launchctl list 2>/dev/null | grep gbrain | head
ps -ef | grep "gbrain jobs work" | grep -v grep | grep -v supervisor
```
If you find bare-worker invocations, surface them to the user.
### 3. Ask about RSS profile
Use AskUserQuestion to confirm whether the user's bare workers need >2 GB RSS:
> "v0.22.14 changes `gbrain jobs work` to default `--max-rss 2048` (MB).
> Pre-v0.22.14 bare workers had no limit. If your worker handles large embed
> batches or multi-GB imports, the watchdog may now kill it. Do you want
> to keep the new 2 GB default, raise the limit, or opt out entirely?"
Options:
- **A) Keep 2 GB default (recommended for most)** — protects against memory
leaks; restarts on overflow; matches supervisor behavior.
- **B) Raise to N GB (specify N)** — pass `--max-rss <N*1024>` to the worker
invocation.
- **C) Opt out** — pass `--max-rss 0`.
### 4. Apply the user's choice
For each bare-worker invocation, edit the unit/cron/launchctl/script to add
the chosen `--max-rss` flag.
**systemd (~/.config/systemd/user/gbrain-worker.service):**
```ini
ExecStart=/usr/local/bin/gbrain jobs work --queue default --concurrency 3 --max-rss 4096
# Or to opt out: --max-rss 0
```
Then `systemctl --user daemon-reload && systemctl --user restart gbrain-worker`.
**cron (`crontab -e`):**
```cron
@reboot /usr/local/bin/gbrain jobs work --queue default --concurrency 3 --max-rss 4096
```
**Docker compose:**
```yaml
command: ["gbrain", "jobs", "work", "--queue", "default", "--concurrency", "3", "--max-rss", "4096"]
```
**launchctl (~/Library/LaunchAgents/com.user.gbrain-worker.plist):**
```xml
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/gbrain</string>
<string>jobs</string>
<string>work</string>
<string>--max-rss</string>
<string>4096</string>
</array>
```
Then `launchctl unload ... && launchctl load ...`.
### 5. (Optional) Tune health-check thresholds
The new opts default to sensible values (60s probe interval, 5min warn / 10min
exit, 3 DB failures). If you have specific SLAs, you can pass `--health-interval
<ms>` to adjust the probe cadence. Stall thresholds are not yet CLI-exposed
(only the API; CLI flags coming in a follow-up).
To disable self-monitoring entirely (e.g. you have your own external health
checker):
```bash
gbrain jobs work --health-interval 0 --max-rss 0
```
### 6. Verify
```bash
gbrain jobs stats # queue should be flowing normally
gbrain doctor --json | jq '.' # no critical warnings
ps -o rss= -p $(pgrep -f "gbrain jobs work") | awk '{print $1/1024 " MB"}'
```
Worker startup log line should now show health-check status:
```
Minion worker started (queue: default, concurrency: 3, watchdog: 2048MB, health-check: 60s)
```
If running under supervisor, you'll see the watchdog but NOT the `health-check:
60s` segment (because `GBRAIN_SUPERVISED=1` skips the child's self-monitor).
### 7. If anything fails
Open an issue at https://github.com/garrytan/gbrain/issues with:
- Output of `gbrain doctor`
- Contents of `~/.gbrain/upgrade-errors.jsonl` if it exists
- Your bare-worker invocation (systemd unit / cron line / Dockerfile snippet)
- Which step broke
+9 -1
View File
@@ -19,7 +19,7 @@ for (const op of operations) {
}
// CLI-only commands that bypass the operation layer
const CLI_ONLY = new Set(['init', 'upgrade', 'post-upgrade', 'check-update', 'integrations', 'publish', 'check-backlinks', 'lint', 'report', 'import', 'export', 'files', 'embed', 'serve', 'call', 'config', 'doctor', 'migrate', 'eval', 'sync', 'extract', 'features', 'autopilot', 'graph-query', 'jobs', 'agent', 'apply-migrations', 'skillpack-check', 'skillpack', 'resolvers', 'integrity', 'repair-jsonb', 'orphans', 'sources', 'dream', 'check-resolvable', 'routing-eval', 'skillify', 'smoke-test', 'storage', 'repos', 'code-def', 'code-refs', 'reindex-code', 'code-callers', 'code-callees', 'frontmatter', 'auth']);
const CLI_ONLY = new Set(['init', 'upgrade', 'post-upgrade', 'check-update', 'integrations', 'publish', 'check-backlinks', 'lint', 'report', 'import', 'export', 'files', 'embed', 'serve', 'call', 'config', 'doctor', 'migrate', 'eval', 'sync', 'extract', 'features', 'autopilot', 'graph-query', 'jobs', 'agent', 'apply-migrations', 'skillpack-check', 'skillpack', 'resolvers', 'integrity', 'repair-jsonb', 'orphans', 'sources', 'dream', 'check-resolvable', 'routing-eval', 'skillify', 'smoke-test', 'storage', 'repos', 'code-def', 'code-refs', 'reindex-code', 'code-callers', 'code-callees', 'frontmatter', 'auth', 'friction', 'claw-test']);
async function main() {
// Parse global flags (--quiet / --progress-json / --progress-interval)
@@ -343,6 +343,14 @@ async function handleCliOnly(command: string, args: string[]) {
await runSkillpack(args);
return;
}
if (command === 'friction') {
const { runFriction } = await import('./commands/friction.ts');
process.exit(runFriction(args));
}
if (command === 'claw-test') {
const { runClawTest } = await import('./commands/claw-test.ts');
process.exit(await runClawTest(args));
}
if (command === 'report') {
const { runReport } = await import('./commands/report.ts');
await runReport(args);
+424
View File
@@ -0,0 +1,424 @@
/**
* gbrain claw-test end-to-end "fresh user" test harness.
*
* Two tiers:
* gbrain claw-test scripted (no LLM, CI gate)
* gbrain claw-test --live --agent openclaw real agent, friction discovery
*
* Phases (scripted mode):
* setup install_brain import query extract verify render
*
* The harness sets GBRAIN_HOME=<tempdir> so the run is hermetic. Each child
* gbrain invocation runs with --progress-json and the harness captures stderr
* to assert expected_phases from scenario.json fired.
*
* See ~/.claude/plans/system-instruction-you-are-working-noble-biscuit.md
* for the full design rationale (D1D23 decisions).
*/
import { spawn } from 'child_process';
import { mkdtempSync, writeFileSync, mkdirSync, rmSync, existsSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { randomBytes } from 'crypto';
import { logFriction, frictionDir } from '../core/friction.ts';
import { loadScenario, listScenarios, readBrief, type ScenarioConfig } from '../core/claw-test/scenarios.ts';
import { parseProgressEvents, verifyExpectedPhases } from '../core/claw-test/progress-tail.ts';
import { resolveAgentRunner, listRegisteredAgents, registerAgentRunner } from '../core/claw-test/agent-runner.ts';
import { OpenClawRunner } from '../core/claw-test/runners/openclaw.ts';
import { createTranscriptSink } from '../core/claw-test/transcript-capture.ts';
// Ensure built-in runners are registered.
registerAgentRunner('openclaw', () => new OpenClawRunner());
interface HarnessOpts {
scenario: string;
live: boolean;
agent: string;
keepTempdir: boolean;
listAgents: boolean;
help: boolean;
/** Path to the gbrain binary used to invoke child commands. Defaults to argv[0]. */
gbrainBin?: string;
}
interface PhaseOutcome {
phase: string;
exitCode: number;
durationMs: number;
stderrEvents: number;
stdoutTail: string;
stderrTail: string;
}
const TAIL_BYTES = 4_096;
const SUBPROCESS_TIMEOUT_MS = 5 * 60_000; // 5 minutes per phase
export async function runClawTest(args: string[]): Promise<number> {
const opts = parseArgs(args);
if (opts.help) {
printHelp();
return 0;
}
if (opts.listAgents) {
return cmdListAgents();
}
let scenario: ScenarioConfig;
try {
scenario = loadScenario(opts.scenario);
} catch (e) {
console.error(`scenario load failed: ${e instanceof Error ? e.message : String(e)}`);
const available = listScenarios();
if (available.length) console.error(`available scenarios: ${available.join(', ')}`);
return 2;
}
const runId = newRunId(opts.agent);
const runRoot = mkdtempSync(join(tmpdir(), `claw-test-${runId}-`));
const gbrainHome = runRoot; // configDir() appends '.gbrain' itself
const transcriptPath = join(runRoot, 'transcript.jsonl');
console.log(`run-id: ${runId}`);
console.log(`tempdir: ${runRoot}`);
// SIGINT/SIGTERM finalization (D11)
let interrupted = false;
const onSignal = () => {
interrupted = true;
try {
logFriction({
runId,
phase: 'harness',
message: 'run interrupted by signal',
kind: 'interrupted',
source: 'harness',
agent: opts.agent,
});
} catch { /* best effort */ }
};
process.once('SIGINT', onSignal);
process.once('SIGTERM', onSignal);
let exitCode = 0;
try {
if (opts.live) {
exitCode = await runLive(opts, scenario, { runId, runRoot, gbrainHome, transcriptPath });
} else {
exitCode = await runScripted(opts, scenario, { runId, runRoot, gbrainHome });
}
} finally {
process.off('SIGINT', onSignal);
process.off('SIGTERM', onSignal);
if (!opts.keepTempdir && !interrupted) {
try { rmSync(runRoot, { recursive: true, force: true }); } catch { /* best effort */ }
} else {
console.log(`tempdir kept at: ${runRoot}`);
}
}
// Always render at the end so the operator can immediately see the report.
console.log('---');
console.log(`friction log: ${join(frictionDir(), runId + '.jsonl')}`);
console.log(`render report: gbrain friction render --run-id ${runId}`);
if (interrupted) return 130;
return exitCode;
}
// ---------------------------------------------------------------------------
// Scripted mode
// ---------------------------------------------------------------------------
async function runScripted(
opts: HarnessOpts,
scenario: ScenarioConfig,
ctx: { runId: string; runRoot: string; gbrainHome: string },
): Promise<number> {
const childEnv: Record<string, string> = {
...process.env as Record<string, string>,
GBRAIN_HOME: ctx.gbrainHome,
GBRAIN_FRICTION_RUN_ID: ctx.runId,
};
const phases: { name: string; argv: string[] }[] = [];
// Phase 2: install_brain
phases.push({ name: 'install_brain', argv: ['init', '--pglite'] });
// Phase 3: import (only when scenario has a brain dir)
if (scenario.brainRelative) {
const brainDir = join(scenario.dir, scenario.brainRelative);
phases.push({ name: 'import', argv: ['import', brainDir, '--no-embed', '--progress-json'] });
}
// Phase 4: query (best-effort sanity)
phases.push({ name: 'query', argv: ['query', 'the'] });
// Phase 5: extract (positional argument is required: 'all' covers links + timeline)
phases.push({ name: 'extract', argv: ['extract', 'all', '--source', 'fs', '--progress-json'] });
// Phase 6: verify
phases.push({ name: 'verify', argv: ['doctor', '--json', '--progress-json'] });
// Pre-phase: upgrade scenario seeds the database
if (scenario.kind === 'upgrade' && scenario.seedRelative) {
const seedSql = join(scenario.dir, scenario.seedRelative, 'dump.sql');
if (existsSync(seedSql)) {
const dbPath = join(ctx.gbrainHome, '.gbrain', 'brain.pglite');
mkdirSync(join(ctx.gbrainHome, '.gbrain'), { recursive: true });
const { seedPgliteFromFile } = await import('../core/claw-test/seed-pglite.ts');
try {
await seedPgliteFromFile({ dbPath, sqlPath: seedSql });
console.log(`[seed] replayed ${seedSql}${dbPath}`);
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
logFriction({
runId: ctx.runId,
phase: 'seed',
message: `seed replay failed: ${msg}`,
severity: 'blocker',
source: 'harness',
agent: opts.agent,
});
return 1;
}
}
}
const allStderr: string[] = [];
const outcomes: PhaseOutcome[] = [];
for (const phase of phases) {
const outcome = await invokeGbrain(opts.gbrainBin ?? 'gbrain', phase.argv, ctx.runRoot, childEnv);
outcome.phase = phase.name;
outcomes.push(outcome);
allStderr.push(outcome.stderrTail);
if (outcome.exitCode !== 0) {
logFriction({
runId: ctx.runId,
phase: phase.name,
message: `command failed (exit ${outcome.exitCode}): gbrain ${phase.argv.join(' ')}`,
severity: 'error',
hint: outcome.stderrTail.trim().slice(0, 500),
source: 'harness',
agent: opts.agent,
});
return 1;
} else {
logFriction({
runId: ctx.runId,
phase: phase.name,
message: `phase complete in ${outcome.durationMs}ms`,
kind: 'phase-marker',
marker: 'end',
source: 'harness',
agent: opts.agent,
});
}
}
// Phase verification: collect all events from every captured stderr and assert coverage.
const events = allStderr.flatMap(parseProgressEvents);
const missing = verifyExpectedPhases(events, scenario.expectedPhases);
if (missing.length) {
for (const phaseName of missing) {
logFriction({
runId: ctx.runId,
phase: phaseName,
message: `expected progress event for "${phaseName}" never fired`,
severity: 'blocker',
hint: 'either the command did not run or it did not emit progress events; check phase log above',
source: 'harness',
agent: opts.agent,
});
}
return 1;
}
return 0;
}
// ---------------------------------------------------------------------------
// Live mode
// ---------------------------------------------------------------------------
async function runLive(
opts: HarnessOpts,
scenario: ScenarioConfig,
ctx: { runId: string; runRoot: string; gbrainHome: string; transcriptPath: string },
): Promise<number> {
let runner;
try {
runner = resolveAgentRunner(opts.agent);
} catch (e) {
console.error(e instanceof Error ? e.message : String(e));
return 2;
}
const detected = await runner.detect();
if (!detected.available) {
console.error(`agent "${opts.agent}" not available: ${detected.reason ?? 'unknown'}`);
logFriction({
runId: ctx.runId,
phase: 'agent_detect',
message: `agent ${opts.agent} not available: ${detected.reason ?? 'unknown'}`,
severity: 'blocker',
hint: opts.agent === 'openclaw' ? 'install openclaw or set OPENCLAW_BIN' : undefined,
source: 'harness',
agent: opts.agent,
});
return 2;
}
const sink = createTranscriptSink(ctx.transcriptPath);
const env: Record<string, string> = {
GBRAIN_HOME: ctx.gbrainHome,
GBRAIN_FRICTION_RUN_ID: ctx.runId,
};
const brief = readBrief(scenario);
let result;
try {
result = await runner.invoke({
cwd: ctx.runRoot,
brief,
env,
timeoutMs: SUBPROCESS_TIMEOUT_MS,
transcriptSink: sink,
});
} finally {
await sink.close();
}
if (result.exitCode !== 0) {
logFriction({
runId: ctx.runId,
phase: 'agent_invoke',
message: `agent exited with code ${result.exitCode} after ${result.durationMs}ms`,
severity: 'error',
source: 'harness',
agent: opts.agent,
});
return result.exitCode;
}
return 0;
}
// ---------------------------------------------------------------------------
// Subprocess helpers
// ---------------------------------------------------------------------------
function invokeGbrain(
bin: string,
argv: string[],
cwd: string,
env: Record<string, string>,
): Promise<PhaseOutcome> {
return new Promise((resolve) => {
const start = Date.now();
const child = spawn(bin, argv, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'], shell: false });
const stdout: Buffer[] = [];
const stderr: Buffer[] = [];
child.stdout?.on('data', (b: Buffer) => stdout.push(b));
child.stderr?.on('data', (b: Buffer) => stderr.push(b));
child.on('error', (err) => {
const stderrJoined = Buffer.concat(stderr).toString('utf-8') + '\nspawn error: ' + err.message;
resolve({
phase: '',
exitCode: 127,
durationMs: Date.now() - start,
stderrEvents: 0,
stdoutTail: tailOf(Buffer.concat(stdout).toString('utf-8')),
stderrTail: tailOf(stderrJoined),
});
});
child.on('close', (code) => {
const stderrText = Buffer.concat(stderr).toString('utf-8');
resolve({
phase: '',
exitCode: typeof code === 'number' ? code : 1,
durationMs: Date.now() - start,
stderrEvents: parseProgressEvents(stderrText).length,
stdoutTail: tailOf(Buffer.concat(stdout).toString('utf-8')),
stderrTail: stderrText,
});
});
});
}
function tailOf(s: string): string {
if (s.length <= TAIL_BYTES) return s;
return s.slice(-TAIL_BYTES);
}
// ---------------------------------------------------------------------------
// Argv parsing + helpers
// ---------------------------------------------------------------------------
function parseArgs(args: string[]): HarnessOpts {
const out: HarnessOpts = {
scenario: 'fresh-install',
live: false,
agent: 'openclaw',
keepTempdir: false,
listAgents: false,
help: args.includes('--help') || args.includes('-h'),
gbrainBin: process.env.GBRAIN_BIN_OVERRIDE || process.execPath,
};
for (let i = 0; i < args.length; i++) {
const a = args[i];
if (a === '--live') out.live = true;
else if (a === '--keep-tempdir') out.keepTempdir = true;
else if (a === '--list-agents') out.listAgents = true;
else if (a === '--scenario') out.scenario = args[++i] ?? out.scenario;
else if (a === '--agent') out.agent = args[++i] ?? out.agent;
}
return out;
}
function newRunId(agent: string): string {
const now = new Date();
const ts = now.toISOString().replace(/[-:]/g, '').replace(/\..*/, '').replace('T', '-');
const suf = randomBytes(4).toString('hex');
return `claw-test-${ts}-${agent}-${suf}`;
}
function cmdListAgents(): number {
const names = listRegisteredAgents();
if (!names.length) {
console.log('no agents registered');
return 0;
}
for (const name of names) {
try {
const runner = resolveAgentRunner(name);
runner.detect().then((d) => {
const status = d.available ? `available at ${d.binPath}` : `unavailable: ${d.reason}`;
console.log(`${name}: ${status}`);
}).catch(() => { /* best effort */ });
} catch {
console.log(`${name}: (factory error)`);
}
}
return 0;
}
function printHelp() {
console.log(`gbrain claw-test — end-to-end claw-setup friction harness
Usage:
gbrain claw-test [--scenario <name>] [--live --agent <name>] [--keep-tempdir]
gbrain claw-test --list-agents
Defaults:
--scenario fresh-install
--agent openclaw (live mode only)
Scripted mode runs canonical commands without an LLM (CI gate).
Live mode spawns a real agent and lets it drive (~510 min, costs tokens).
Examples:
gbrain claw-test --scenario fresh-install
gbrain claw-test --scenario upgrade-from-v0.18 --keep-tempdir
gbrain claw-test --live --agent openclaw`);
}
+32
View File
@@ -774,6 +774,30 @@ export async function runDoctor(engine: BrainEngine | null, args: string[], dbSo
ORDER BY depth DESC
LIMIT 5
`;
// Subcheck 3 (v0.22.14): RSS-watchdog kills in the last 24h. Bare workers
// newly default to --max-rss 2048 (was 0); operators who run large embed
// or import jobs may see kills that didn't happen pre-v0.22.14. We surface
// a hint when this signature appears so the upgrade path is obvious.
// Signature: when the watchdog trips, gracefulShutdown('watchdog') aborts
// in-flight jobs with `new Error('watchdog')`. The worker's failJob path
// (worker.ts:660-664) writes `error_text = 'aborted: watchdog'` for any
// job in-flight at the moment of the kill.
//
// We deliberately DO NOT do a loose `ILIKE '%watchdog%'`:
// 1. Parent jobs that inherit `on_child_fail='fail_parent'` get
// `"child job N failed: aborted: watchdog"` — counting that
// double-counts (child + parent) for one watchdog event.
// 2. Any user error_text containing the word "watchdog" matches.
// Match the exact prefix `'aborted: watchdog'` to scope this purely to
// the worker's own kill signature.
const rssKillRows: Array<{ cnt: number }> = await sql`
SELECT count(*)::int AS cnt
FROM minion_jobs
WHERE status IN ('dead', 'failed')
AND finished_at > now() - interval '24 hours'
AND error_text = 'aborted: watchdog'
`;
const rssKillCount = rssKillRows[0]?.cnt ?? 0;
const problems: string[] = [];
if (stalledRows.length > 0) {
@@ -794,6 +818,14 @@ export async function runDoctor(engine: BrainEngine | null, args: string[], dbSo
`Fix: set maxWaiting on the submitter (or raise GBRAIN_QUEUE_WAITING_THRESHOLD).`
);
}
if (rssKillCount > 0) {
problems.push(
`${rssKillCount} job(s) dead-lettered for RSS-watchdog memory-limit kills in last 24h. ` +
`v0.22.14 changed the bare-worker --max-rss default from 0 (off) to 2048 MB. ` +
`Fix: raise the limit (e.g. \`gbrain jobs work --max-rss 4096\`) or opt out (\`--max-rss 0\`). ` +
`See skills/migrations/v0.22.14.md.`
);
}
if (problems.length === 0) {
checks.push({
+185
View File
@@ -0,0 +1,185 @@
/**
* gbrain friction friction reporter CLI.
*
* Four subcommands in v1 (analytical/clustering ones move to v1.1):
* gbrain friction log Append a friction or delight entry
* gbrain friction render Render a run as markdown or JSON
* gbrain friction list List recent runs with counts
* gbrain friction summary Side-by-side friction + delight summary
*
* Subcommands stay thin ( ~30 LOC each). Core logic lives in src/core/friction.ts.
*
* The CLI is dispatched from src/cli.ts. See `gbrain friction --help`.
*/
import {
logFriction, readFriction, listRuns, renderReport, renderSummary,
activeRunId, frictionFile,
type FrictionKind, type FrictionSeverity,
} from '../core/friction.ts';
const VALID_KINDS = new Set<FrictionKind>(['friction', 'delight', 'phase-marker', 'interrupted']);
const VALID_SEVERITIES = new Set<FrictionSeverity>(['confused', 'error', 'blocker', 'nit']);
export function runFriction(args: string[]): number {
const [sub, ...rest] = args;
switch (sub) {
case 'log': return cmdLog(rest);
case 'render': return cmdRender(rest);
case 'list': return cmdList(rest);
case 'summary': return cmdSummary(rest);
case undefined:
case '--help':
case '-h':
printHelp();
return 0;
default:
console.error(`unknown subcommand: ${sub}`);
printHelp();
return 2;
}
}
// ---------------------------------------------------------------------------
// log
// ---------------------------------------------------------------------------
function cmdLog(args: string[]): number {
const flags = parseFlags(args);
const phase = flags.string('--phase');
const message = flags.string('--message');
if (!phase || !message) {
console.error('usage: gbrain friction log --phase <name> --message <text> [--severity ...] [--hint ...] [--kind ...] [--run-id ...]');
return 2;
}
const kind = (flags.string('--kind') ?? 'friction') as FrictionKind;
if (!VALID_KINDS.has(kind)) {
console.error(`invalid --kind ${kind}; must be one of: ${[...VALID_KINDS].join(', ')}`);
return 2;
}
const severityRaw = flags.string('--severity');
const severity = severityRaw as FrictionSeverity | undefined;
if (severity && !VALID_SEVERITIES.has(severity)) {
console.error(`invalid --severity ${severity}; must be one of: ${[...VALID_SEVERITIES].join(', ')}`);
return 2;
}
try {
logFriction({
phase,
message,
kind,
severity,
hint: flags.string('--hint'),
runId: flags.string('--run-id'),
agent: flags.string('--agent'),
source: 'claw',
});
} catch (e) {
console.error(`friction log failed: ${e instanceof Error ? e.message : String(e)}`);
return 1;
}
return 0;
}
// ---------------------------------------------------------------------------
// render
// ---------------------------------------------------------------------------
function cmdRender(args: string[]): number {
const flags = parseFlags(args);
const runId = flags.string('--run-id') ?? activeRunId();
const json = flags.bool('--json');
const format = json ? 'json' : 'md';
const transcripts = flags.bool('--transcripts');
const noRedact = flags.bool('--no-redact');
// --redact is the default for md output; --no-redact disables.
const redact = noRedact ? false : (format === 'md');
try {
const out = renderReport(runId, {
format,
redact,
transcriptPath: transcripts ? flags.string('--transcript-path') ?? undefined : undefined,
});
process.stdout.write(out + '\n');
return 0;
} catch (e) {
console.error(`friction render failed: ${e instanceof Error ? e.message : String(e)}`);
return 1;
}
}
// ---------------------------------------------------------------------------
// list
// ---------------------------------------------------------------------------
function cmdList(args: string[]): number {
const flags = parseFlags(args);
const json = flags.bool('--json');
const runs = listRuns();
if (json) {
console.log(JSON.stringify(runs, null, 2));
return 0;
}
if (runs.length === 0) {
console.log('no runs yet');
return 0;
}
for (const r of runs) {
const interrupted = r.counts.interrupted ? ' (interrupted)' : '';
const sev = Object.entries(r.counts.bySeverity).map(([k, v]) => `${k}=${v}`).join(' ');
console.log(`${r.runId}${interrupted} friction=${r.counts.friction} delight=${r.counts.delight} ${sev}`);
}
return 0;
}
// ---------------------------------------------------------------------------
// summary
// ---------------------------------------------------------------------------
function cmdSummary(args: string[]): number {
const flags = parseFlags(args);
const runId = flags.string('--run-id') ?? activeRunId();
const json = flags.bool('--json');
try {
const out = renderSummary(runId, { format: json ? 'json' : 'md' });
process.stdout.write(out + '\n');
return 0;
} catch (e) {
console.error(`friction summary failed: ${e instanceof Error ? e.message : String(e)}`);
return 1;
}
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function parseFlags(args: string[]) {
return {
string(flag: string): string | undefined {
const idx = args.indexOf(flag);
return idx === -1 ? undefined : args[idx + 1];
},
bool(flag: string): boolean {
return args.includes(flag);
},
};
}
function printHelp() {
console.log(`gbrain friction — friction reporter
Subcommands:
log Append a friction or delight entry to the active run
render Render a run's entries as markdown (default) or JSON
list List recent runs with friction/delight counts
summary Two-column summary of friction + delight for a run
Examples:
gbrain friction log --severity confused --phase install --message "init didn't say which engine"
gbrain friction render --run-id claw-test-20260428-... --transcripts
gbrain friction list --json
gbrain friction summary
Run-id resolution: --run-id > $GBRAIN_FRICTION_RUN_ID > 'standalone'.`);
}
+193 -1
View File
@@ -49,6 +49,10 @@ export async function runFrontmatter(args: string[]): Promise<void> {
}
return;
}
if (sub === 'generate') {
await runGenerate(rest);
return;
}
if (sub === 'install-hook') {
const { runFrontmatterInstallHook } = await import('./frontmatter-install-hook.ts');
await runFrontmatterInstallHook(rest);
@@ -71,10 +75,11 @@ async function connectEngineForAudit(): Promise<BrainEngine> {
}
function printHelp() {
console.log(`gbrain frontmatter — frontmatter validation, audit, and auto-repair
console.log(`gbrain frontmatter — frontmatter validation, audit, auto-repair, and generation
Usage:
gbrain frontmatter validate <path> [--json] [--fix] [--dry-run]
gbrain frontmatter generate <path> [--fix] [--dry-run] [--json]
gbrain frontmatter audit [--source <id>] [--json]
gbrain frontmatter install-hook [--source <id>] [--force] [--uninstall]
@@ -91,6 +96,26 @@ validate
--dry-run Preview --fix without writing.
--json Emit a JSON envelope on stdout.
generate
Synthesize frontmatter for files that have none (MISSING_OPEN). Uses
directory-aware rules to infer type, title, date, source, and tags from
the filesystem path and file content. Zero LLM calls, fully deterministic.
Without --fix: dry-run preview showing what would be generated.
With --fix: writes frontmatter to files (with .bak safety backups).
Rules are defined in src/core/frontmatter-inference.ts DIRECTORY_RULES.
Add new directory conventions by adding rules to the table.
Examples:
gbrain frontmatter generate /path/to/brain # preview all
gbrain frontmatter generate /path/to/brain --fix # write all
gbrain frontmatter generate /path/to/brain/people/ --fix # just people/
--fix Write generated frontmatter to files (.bak safety backups).
--dry-run Preview without writing (default when --fix is omitted).
--json Emit JSON output.
audit
Read-only scan across all registered sources (or one with --source <id>).
Reports per-source counts grouped by error code. Use this in CI or doctor
@@ -297,3 +322,170 @@ function printAuditHumanReport(report: AuditReport): void {
console.log(`\nFix with: gbrain frontmatter validate <source-path> --fix`);
}
}
// ---------------------------------------------------------------------------
// generate — synthesize frontmatter for files that have none
// ---------------------------------------------------------------------------
async function runGenerate(args: string[]): Promise<void> {
const targetPath = args.find(a => !a.startsWith('-'));
const doFix = args.includes('--fix');
const dryRun = args.includes('--dry-run');
const jsonOut = args.includes('--json');
if (!targetPath) {
console.error('error: gbrain frontmatter generate requires a <path> argument');
console.error('usage: gbrain frontmatter generate <path> [--fix] [--dry-run] [--json]');
process.exitCode = 1;
return;
}
const { inferFrontmatter, serializeFrontmatter } = await import('../core/frontmatter-inference.ts');
const { resolve, relative, join, basename } = await import('path');
const { readFileSync, writeFileSync, copyFileSync, statSync, readdirSync, lstatSync } = await import('fs');
const rootPath = resolve(targetPath);
const isDir = statSync(rootPath).isDirectory();
// Find the brain root — walk up from targetPath looking for .git or known brain markers.
// Inference rules match against brain-root-relative paths (e.g., "people/alice.md").
let brainRoot = rootPath;
if (isDir) {
let candidate = rootPath;
for (let i = 0; i < 10; i++) {
try {
statSync(join(candidate, '.git'));
brainRoot = candidate;
break;
} catch {
const parent = resolve(candidate, '..');
if (parent === candidate) break;
candidate = parent;
}
}
}
interface GenerateResult {
path: string;
type: string;
title: string;
date?: string;
rule: string;
}
const results: GenerateResult[] = [];
let scanned = 0;
let skipped = 0;
let generated = 0;
let written = 0;
function processFile(absPath: string, relPath: string) {
scanned++;
if (!absPath.endsWith('.md')) return;
// Skip symlinks
try { if (lstatSync(absPath).isSymbolicLink()) return; } catch { return; }
let content: string;
try { content = readFileSync(absPath, 'utf-8'); } catch { return; }
const inferred = inferFrontmatter(relPath, content);
if (inferred.skipped) {
skipped++;
return;
}
generated++;
results.push({
path: relPath,
type: inferred.type,
title: inferred.title,
date: inferred.date,
rule: inferred.matchedRule || '(default)',
});
if (doFix && !dryRun) {
const fm = serializeFrontmatter(inferred);
const newContent = fm + '\n' + content;
// Safety: write .bak first
copyFileSync(absPath, absPath + '.bak');
writeFileSync(absPath, newContent, 'utf-8');
written++;
}
}
function walkDir(dir: string, rootForRel: string) {
let entries: string[];
try { entries = readdirSync(dir); } catch { return; }
for (const entry of entries) {
if (entry === '.git' || entry === 'node_modules' || entry === '.obsidian') continue;
const abs = join(dir, entry);
try {
const stat = statSync(abs);
if (stat.isDirectory()) {
walkDir(abs, rootForRel);
} else if (stat.isFile() && entry.endsWith('.md')) {
processFile(abs, relative(rootForRel, abs));
}
} catch { /* skip unreadable */ }
}
}
if (isDir) {
walkDir(rootPath, brainRoot);
} else {
const relPath = relative(brainRoot, rootPath) || basename(rootPath);
processFile(rootPath, relPath);
}
// Output
if (jsonOut) {
console.log(JSON.stringify({
scanned,
skipped,
generated,
written,
dryRun: !doFix || dryRun,
results: results.slice(0, 100), // Cap JSON output
totalResults: results.length,
}, null, 2));
return;
}
// Human-readable output
const mode = doFix && !dryRun ? 'WRITE' : 'DRY-RUN';
console.log(`\nFrontmatter generation (${mode})`);
console.log(` Scanned: ${scanned} files`);
console.log(` Already have frontmatter: ${skipped}`);
console.log(` Would generate: ${generated}`);
if (doFix && !dryRun) {
console.log(` Written: ${written} (with .bak backups)`);
}
// Show sample by type
const byType: Record<string, number> = {};
for (const r of results) {
byType[r.type] = (byType[r.type] || 0) + 1;
}
if (Object.keys(byType).length > 0) {
console.log(`\n By type:`);
for (const [type, count] of Object.entries(byType).sort(([, a], [, b]) => b - a)) {
console.log(` ${type}: ${count}`);
}
}
// Show first 10 examples
if (results.length > 0 && (!doFix || dryRun)) {
console.log(`\n Examples:`);
for (const r of results.slice(0, 10)) {
console.log(` ${r.path}`);
console.log(` → type: ${r.type}, title: "${r.title}"${r.date ? `, date: ${r.date}` : ''} [rule: ${r.rule}]`);
}
if (results.length > 10) {
console.log(` ... and ${results.length - 10} more`);
}
if (!doFix) {
console.log(`\n To write: gbrain frontmatter generate ${targetPath} --fix`);
}
}
}
+4 -4
View File
@@ -1,10 +1,10 @@
import { readdirSync, lstatSync, existsSync, writeFileSync, readFileSync, unlinkSync } from 'fs';
import { execFileSync } from 'child_process';
import { join, relative } from 'path';
import { cpus, totalmem, homedir } from 'os';
import { cpus, totalmem } from 'os';
import type { BrainEngine } from '../core/engine.ts';
import { importFile } from '../core/import-file.ts';
import { loadConfig } from '../core/config.ts';
import { loadConfig, gbrainPath } from '../core/config.ts';
import { createProgress } from '../core/progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
@@ -61,7 +61,7 @@ export async function runImport(engine: BrainEngine, args: string[], opts: { com
console.log(`Found ${allFiles.length} markdown files`);
// Resume from checkpoint if available
const checkpointPath = join(homedir(), '.gbrain', 'import-checkpoint.json');
const checkpointPath = gbrainPath('import-checkpoint.json');
let files = allFiles;
let resumeIndex = 0;
@@ -137,7 +137,7 @@ export async function runImport(engine: BrainEngine, args: string[], opts: { com
// Save checkpoint every 100 files — track completed file set, not just a counter
if (processed % 100 === 0) {
try {
const cpDir = join(homedir(), '.gbrain');
const cpDir = gbrainPath();
if (!existsSync(cpDir)) { const { mkdirSync } = await import('fs'); mkdirSync(cpDir, { recursive: true }); }
writeFileSync(checkpointPath, JSON.stringify({
dir, totalFiles: allFiles.length,
+2 -2
View File
@@ -6,7 +6,7 @@ import { homedir } from 'os';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
import { saveConfig, loadConfig, toEngineConfig, type GBrainConfig } from '../core/config.ts';
import { saveConfig, loadConfig, toEngineConfig, gbrainPath, type GBrainConfig } from '../core/config.ts';
import { createEngine } from '../core/engine-factory.ts';
export async function runInit(args: string[]) {
@@ -103,7 +103,7 @@ async function initMigrateOnly(opts: { jsonOutput: boolean }) {
}
async function initPGLite(opts: { jsonOutput: boolean; apiKey: string | null; customPath: string | null }) {
const dbPath = opts.customPath || join(homedir(), '.gbrain', 'brain.pglite');
const dbPath = opts.customPath || gbrainPath('brain.pglite');
console.log(`Setting up local brain with PGLite (no server needed)...`);
const engine = await createEngine({ engine: 'pglite' });
+2 -1
View File
@@ -23,6 +23,7 @@ import matter from 'gray-matter';
import { readFileSync, existsSync, writeFileSync, mkdirSync, readdirSync } from 'fs';
import { join, basename } from 'path';
import { homedir } from 'os';
import { gbrainPath } from '../core/config.ts';
import { execSync } from 'child_process';
// --- Types ---
@@ -512,7 +513,7 @@ function findRecipe(id: string): ParsedRecipe | null {
// --- Heartbeat ---
function heartbeatDir(id: string): string {
return join(homedir(), '.gbrain', 'integrations', id);
return gbrainPath('integrations', id);
}
function heartbeatPath(id: string): string {
+24 -25
View File
@@ -25,10 +25,9 @@
*/
import { appendFileSync, existsSync, readFileSync, mkdirSync, writeFileSync } from 'fs';
import { homedir } from 'os';
import { join, dirname } from 'path';
import { dirname } from 'path';
import { loadConfig, toEngineConfig } from '../core/config.ts';
import { loadConfig, toEngineConfig, gbrainPath } from '../core/config.ts';
import { createEngine } from '../core/engine-factory.ts';
import type { BrainEngine } from '../core/engine.ts';
import * as db from '../core/db.ts';
@@ -45,10 +44,10 @@ import { tweetCitation } from '../core/output/scaffold.ts';
// Paths
// ---------------------------------------------------------------------------
const GBRAIN_DIR = join(homedir(), '.gbrain');
const REVIEW_FILE = join(GBRAIN_DIR, 'integrity-review.md');
const LOG_FILE = join(GBRAIN_DIR, 'integrity.log.jsonl');
const PROGRESS_FILE = join(GBRAIN_DIR, 'integrity-progress.jsonl');
// Lazy: GBRAIN_HOME may be set after module load.
const getReviewFile = () => gbrainPath('integrity-review.md');
const getLogFile = () => gbrainPath('integrity.log.jsonl');
const getProgressFile = () => gbrainPath('integrity-progress.jsonl');
// ---------------------------------------------------------------------------
// Bare-tweet detection
@@ -158,9 +157,9 @@ interface ProgressEntry {
}
function loadProgress(): Set<string> {
if (!existsSync(PROGRESS_FILE)) return new Set();
if (!existsSync(getProgressFile())) return new Set();
const seen = new Set<string>();
const content = readFileSync(PROGRESS_FILE, 'utf-8');
const content = readFileSync(getProgressFile(), 'utf-8');
for (const line of content.split('\n')) {
if (!line.trim()) continue;
try {
@@ -174,12 +173,12 @@ function loadProgress(): Set<string> {
}
function appendProgress(entry: ProgressEntry): void {
ensureDir(PROGRESS_FILE);
appendFileSync(PROGRESS_FILE, JSON.stringify(entry) + '\n', 'utf-8');
ensureDir(getProgressFile());
appendFileSync(getProgressFile(), JSON.stringify(entry) + '\n', 'utf-8');
}
function clearProgress(): void {
if (existsSync(PROGRESS_FILE)) writeFileSync(PROGRESS_FILE, '', 'utf-8');
if (existsSync(getProgressFile())) writeFileSync(getProgressFile(), '', 'utf-8');
}
function ensureDir(path: string): void {
@@ -213,7 +212,7 @@ export async function runIntegrity(args: string[]): Promise<void> {
}
if (sub === 'reset-progress') {
clearProgress();
console.log('Cleared progress log:', PROGRESS_FILE);
console.log('Cleared progress log:', getProgressFile());
return;
}
@@ -409,7 +408,7 @@ async function cmdAuto(args: string[]): Promise<void> {
process.exit(1);
}
ensureDir(GBRAIN_DIR);
ensureDir(gbrainPath());
const engine = await connect();
const registry = getDefaultRegistry();
@@ -548,9 +547,9 @@ async function cmdAuto(args: string[]): Promise<void> {
console.log(`Review queue (≥${reviewLower} <${confidenceThreshold}): ${bucketReview}`);
console.log(`Skipped (<${reviewLower}): ${bucketSkip}`);
if (bucketErr > 0) console.log(`Resolver errors: ${bucketErr}`);
console.log(`\nReview queue: ${REVIEW_FILE}`);
console.log(`Skipped log: ${LOG_FILE}`);
console.log(`Progress: ${PROGRESS_FILE}`);
console.log(`\nReview queue: ${getReviewFile()}`);
console.log(`Skipped log: ${getLogFile()}`);
console.log(`Progress: ${getProgressFile()}`);
} finally {
await engine.disconnect();
}
@@ -561,15 +560,15 @@ async function cmdAuto(args: string[]): Promise<void> {
// ---------------------------------------------------------------------------
function cmdReview(): void {
if (!existsSync(REVIEW_FILE)) {
if (!existsSync(getReviewFile())) {
console.log(`No review queue yet. Run: gbrain integrity auto --confidence 0.8`);
return;
}
const content = readFileSync(REVIEW_FILE, 'utf-8');
const content = readFileSync(getReviewFile(), 'utf-8');
const count = (content.match(/^## /gm) ?? []).length;
console.log(`Review queue: ${REVIEW_FILE}`);
console.log(`Review queue: ${getReviewFile()}`);
console.log(`Entries: ${count}`);
console.log(`\nOpen with: $EDITOR ${REVIEW_FILE}`);
console.log(`\nOpen with: $EDITOR ${getReviewFile()}`);
}
// ---------------------------------------------------------------------------
@@ -650,7 +649,7 @@ interface ReviewArgs {
}
function appendReview(args: ReviewArgs): void {
ensureDir(REVIEW_FILE);
ensureDir(getReviewFile());
const { slug, hit, result, handle } = args;
const block = [
`## ${slug}:${hit.line} (confidence ${result.confidence.toFixed(2)})`,
@@ -664,12 +663,12 @@ function appendReview(args: ReviewArgs): void {
'---',
'',
].join('\n');
appendFileSync(REVIEW_FILE, block, 'utf-8');
appendFileSync(getReviewFile(), block, 'utf-8');
}
interface SkipArgs { slug: string; hit: BareTweetHit; reason: string }
function logSkip(args: SkipArgs): void {
ensureDir(LOG_FILE);
ensureDir(getLogFile());
const entry = {
timestamp: new Date().toISOString(),
slug: args.slug,
@@ -678,7 +677,7 @@ function logSkip(args: SkipArgs): void {
raw: args.hit.rawLine.slice(0, 200),
reason: args.reason,
};
appendFileSync(LOG_FILE, JSON.stringify(entry) + '\n', 'utf-8');
appendFileSync(getLogFile(), JSON.stringify(entry) + '\n', 'utf-8');
}
// ---------------------------------------------------------------------------
+96 -17
View File
@@ -33,14 +33,14 @@ export function parseMaxWaitingFlag(args: string[]): number | undefined {
}
/** Parse `--max-rss N` (MB). Returns:
* - 0 if the flag is absent (no watchdog by default for bare `jobs work`)
* - undefined if the flag is absent (caller decides the default)
* - 0 if `--max-rss 0` (explicit disable)
* - the value if >= 256
* Errors and exits the process if the flag is non-numeric, negative, or
* positive but < 256 (likely a GB-vs-MB unit-confusion typo). */
export function parseMaxRssFlag(args: string[]): number {
export function parseMaxRssFlag(args: string[]): number | undefined {
const raw = parseFlag(args, '--max-rss');
if (raw === undefined) return 0;
if (raw === undefined) return undefined;
const parsed = parseInt(raw, 10);
if (!Number.isFinite(parsed) || parsed < 0) {
console.error(`Error: --max-rss must be a non-negative integer (MB), got "${raw}"`);
@@ -133,6 +133,7 @@ USAGE
gbrain jobs stats
gbrain jobs smoke
gbrain jobs work [--queue Q] [--concurrency N] [--max-rss MB]
[--health-interval MS]
gbrain jobs supervisor [start] [--detach] [--json]
[--concurrency N] [--queue Q] [--pid-file PATH]
[--max-crashes N] [--health-interval N]
@@ -314,8 +315,15 @@ HANDLER TYPES (built in)
if (follow) {
console.log(`Job #${job.id} submitted (${name}). Executing inline...`);
// Inline execution: run the job in this process
const worker = new MinionWorker(engine, { queue: queueName, pollInterval: 100 });
// Inline execution: run the job in this process. Disable the
// self-health-check timer — inline flows are one-shot and don't have
// a process manager to restart them. With the timer enabled and no
// 'unhealthy' listener, a DB blip would trip emitUnhealthy's
// no-listener fallback and call process.exit(1) from inside the
// library, killing the user's CLI session.
const worker = new MinionWorker(engine, {
queue: queueName, pollInterval: 100, healthCheckInterval: 0,
});
// Register built-in handlers
await registerBuiltinHandlers(worker, engine);
@@ -489,7 +497,11 @@ HANDLER TYPES (built in)
const sigkillRescue = hasFlag(args, '--sigkill-rescue');
const wedgeRescue = hasFlag(args, '--wedge-rescue');
const worker = new MinionWorker(engine, { queue: 'smoke', pollInterval: 100 });
// Smoke harness is short-lived and has no listener — disable the health
// timer so the no-listener fallback can't trip process.exit(1) mid-test.
const worker = new MinionWorker(engine, {
queue: 'smoke', pollInterval: 100, healthCheckInterval: 0,
});
worker.register('noop', async () => ({ ok: true, at: new Date().toISOString() }));
const job = await queue.add('noop', {}, { queue: 'smoke', max_attempts: 1 });
@@ -638,19 +650,69 @@ HANDLER TYPES (built in)
const queueName = parseFlag(args, '--queue') ?? 'default';
const concurrency = resolveWorkerConcurrency(args);
// --max-rss is opt-in for bare `gbrain jobs work` — preserves pre-v0.21 behavior
// for operators with legitimately large embed/import working sets. The supervisor
// path injects a default 2048; this code path does not.
const maxRssMb = parseMaxRssFlag(args);
// --max-rss defaults to 2048 for bare workers (matching supervisor default).
// This catches memory-leak stalls that previously went undetected without
// a supervisor. Operators can opt out with `--max-rss 0`.
const maxRssExplicit = parseMaxRssFlag(args);
const maxRssMb = maxRssExplicit ?? 2048;
// --health-interval: self-health-check period in ms. 0 disables. Default: 60_000 (60s).
// Provides DB liveness probes + stall detection for bare workers.
// Automatically skipped when running under a supervisor (GBRAIN_SUPERVISED=1).
// Validated aggressively (parity with --max-rss): reject NaN/negative/non-integer
// values, and reject suspicious sub-1000ms values that are likely a unit-confusion
// typo (e.g. "--health-interval 60" thinking the unit is seconds).
const healthRaw = parseFlag(args, '--health-interval');
let healthCheckInterval = 60_000;
if (healthRaw !== undefined) {
const parsed = parseInt(healthRaw, 10);
if (!Number.isFinite(parsed) || parsed < 0) {
console.error(`Error: --health-interval must be a non-negative integer (ms), got "${healthRaw}"`);
process.exit(1);
}
if (parsed > 0 && parsed < 1000) {
console.error(
`Error: --health-interval ${parsed} is suspiciously low (likely a unit-confusion typo). ` +
`The flag takes milliseconds; for 60-second probes pass 60000. Use 0 to disable.`,
);
process.exit(1);
}
healthCheckInterval = parsed;
}
try { await queue.ensureSchema(); }
catch (e) { console.error(e instanceof Error ? e.message : String(e)); process.exit(1); }
const worker = new MinionWorker(engine, { queue: queueName, concurrency, maxRssMb });
const worker = new MinionWorker(engine, {
queue: queueName, concurrency, maxRssMb, healthCheckInterval,
});
await registerBuiltinHandlers(worker, engine);
// Subscribe to self-health failures emitted by the worker. Library code
// (worker.ts) never calls process.exit directly so it stays embeddable;
// this CLI layer is the right place to terminate the process and let
// the external PM (systemd, Docker, cron watchdog) restart cleanly.
worker.on('unhealthy', (info) => {
if (info.reason === 'db_dead') {
console.error(
`[health] FATAL: DB unreachable after ${info.consecutiveFailures} probes (${info.message}). ` +
`Exiting for process-manager restart.`,
);
} else {
console.error(
`[health] FATAL: Worker stalled — ${info.waitingCount} waiting job(s) for ` +
`registered handlers, ${info.idleMinutes}m idle. Exiting for process-manager restart.`,
);
}
process.exit(1);
});
const isSupervisedChild = process.env.GBRAIN_SUPERVISED === '1';
const watchdogNote = maxRssMb > 0 ? `, watchdog: ${maxRssMb}MB` : '';
console.log(`Minion worker started (queue: ${queueName}, concurrency: ${concurrency}${watchdogNote})`);
const healthNote = !isSupervisedChild && healthCheckInterval > 0
? `, health-check: ${Math.round(healthCheckInterval / 1000)}s`
: '';
console.log(`Minion worker started (queue: ${queueName}, concurrency: ${concurrency}${watchdogNote}${healthNote})`);
console.log(`Registered handlers: ${worker.registeredNames.join(', ')}`);
await worker.start();
break;
@@ -787,15 +849,32 @@ HANDLER TYPES (built in)
const concurrency = parseInt(parseFlag(args, '--concurrency') ?? '2', 10);
const queueName = parseFlag(args, '--queue') ?? 'default';
const maxCrashes = parseInt(parseFlag(args, '--max-crashes') ?? '10', 10);
const healthInterval = parseInt(parseFlag(args, '--health-interval') ?? '60000', 10);
// --health-interval (supervisor): validate same as `jobs work` so NaN /
// negative / sub-1000ms typos fail-fast instead of silently disabling
// the supervisor's own health probe.
const supHealthRaw = parseFlag(args, '--health-interval');
let healthInterval = 60_000;
if (supHealthRaw !== undefined) {
const parsed = parseInt(supHealthRaw, 10);
if (!Number.isFinite(parsed) || parsed < 0) {
console.error(`Error: --health-interval must be a non-negative integer (ms), got "${supHealthRaw}"`);
process.exit(1);
}
if (parsed > 0 && parsed < 1000) {
console.error(
`Error: --health-interval ${parsed} is suspiciously low (likely a unit-confusion typo). ` +
`The flag takes milliseconds; for 60-second probes pass 60000. Use 0 to disable.`,
);
process.exit(1);
}
healthInterval = parsed;
}
const allowShellJobs = hasFlag(args, '--allow-shell-jobs') ||
!!process.env.GBRAIN_ALLOW_SHELL_JOBS;
const detach = hasFlag(args, '--detach');
// Supervisor defaults --max-rss 2048 (MB) — main production path uses
// the supervisor, so the watchdog is on by default here. parseMaxRssFlag
// returns 0 when the flag is absent; substitute the supervisor default.
const maxRssRaw = parseMaxRssFlag(args);
const maxRssMb = parseFlag(args, '--max-rss') === undefined ? 2048 : maxRssRaw;
// the supervisor, so the watchdog is on by default here.
const maxRssMb = parseMaxRssFlag(args) ?? 2048;
const cliPath = parseFlag(args, '--cli-path') ?? resolveGbrainCliPath();
+3 -5
View File
@@ -8,11 +8,9 @@
*/
import { createEngine } from '../core/engine-factory.ts';
import { loadConfig, saveConfig, toEngineConfig, type GBrainConfig } from '../core/config.ts';
import { loadConfig, saveConfig, toEngineConfig, gbrainPath, type GBrainConfig } from '../core/config.ts';
import type { BrainEngine } from '../core/engine.ts';
import type { EngineConfig } from '../core/types.ts';
import { homedir } from 'os';
import { join } from 'path';
import { writeFileSync, readFileSync, existsSync, unlinkSync } from 'fs';
import { createProgress } from '../core/progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
@@ -48,7 +46,7 @@ function parseArgs(args: string[]): MigrateOpts {
}
function getManifestPath(): string {
return join(homedir(), '.gbrain', 'migrate-manifest.json');
return gbrainPath('migrate-manifest.json');
}
interface MigrateManifest {
@@ -99,7 +97,7 @@ export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]
process.exit(1);
}
} else {
targetConfig.database_path = opts.targetPath || join(homedir(), '.gbrain', 'brain.pglite');
targetConfig.database_path = opts.targetPath || gbrainPath('brain.pglite');
}
// Connect to target
+7 -6
View File
@@ -35,17 +35,17 @@
*/
import { existsSync, mkdirSync, appendFileSync } from 'fs';
import { homedir } from 'os';
import { join } from 'path';
import type { Migration, OrchestratorOpts, OrchestratorResult, OrchestratorPhaseResult } from './types.ts';
import { loadConfig, toEngineConfig } from '../../core/config.ts';
import { loadConfig, toEngineConfig, gbrainPath } from '../../core/config.ts';
import { createEngine } from '../../core/engine-factory.ts';
import type { BrainEngine } from '../../core/engine.ts';
// Bug 3 — ledger writes moved to the runner (apply-migrations.ts).
const ROLLBACK_DIR = join(homedir(), '.gbrain', 'migrations');
const ROLLBACK_FILE = join(ROLLBACK_DIR, 'v0_13_1-rollback.jsonl');
// Lazy: GBRAIN_HOME may be set after module load.
const getRollbackDir = () => gbrainPath('migrations');
const getRollbackFile = () => join(getRollbackDir(), 'v0_13_1-rollback.jsonl');
const BATCH_SIZE = 100;
// ---------------------------------------------------------------------------
@@ -251,7 +251,8 @@ async function orchestrator(opts: OrchestratorOpts): Promise<OrchestratorResult>
// ---------------------------------------------------------------------------
function ensureRollbackDir(): void {
if (!existsSync(ROLLBACK_DIR)) mkdirSync(ROLLBACK_DIR, { recursive: true });
const dir = getRollbackDir();
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
}
function appendRollbackEntry(entry: { slug: string; pre_frontmatter: Record<string, unknown> }): void {
@@ -260,7 +261,7 @@ function appendRollbackEntry(entry: { slug: string; pre_frontmatter: Record<stri
timestamp: new Date().toISOString(),
...entry,
}) + '\n';
appendFileSync(ROLLBACK_FILE, line, 'utf-8');
appendFileSync(getRollbackFile(), line, 'utf-8');
}
// ---------------------------------------------------------------------------
+5 -7
View File
@@ -22,19 +22,17 @@
*/
import { existsSync, readFileSync, mkdirSync, appendFileSync } from 'fs';
import { homedir } from 'os';
import { join } from 'path';
import type { Migration, OrchestratorOpts, OrchestratorResult, OrchestratorPhaseResult } from './types.ts';
import { loadConfig, toEngineConfig } from '../../core/config.ts';
import { loadConfig, toEngineConfig, gbrainPath } from '../../core/config.ts';
import { createEngine } from '../../core/engine-factory.ts';
import type { BrainEngine } from '../../core/engine.ts';
// Resolve HOME at CALL time, not module-load time — Bun caches os.homedir()
// and ignores later HOME mutations, which breaks test isolation and scripted
// installs. Match the preferences.ts pattern.
function resolveHome(): string { return process.env.HOME || homedir(); }
function pendingHostWorkDir(): string { return join(resolveHome(), '.gbrain', 'migrations'); }
// gbrainPath() honors GBRAIN_HOME at call time (not module-load) and routes
// through the centralized config dir, so the prior resolveHome()/HOME-env
// trick is no longer needed.
function pendingHostWorkDir(): string { return gbrainPath('migrations'); }
function pendingHostWorkPath(): string { return join(pendingHostWorkDir(), 'pending-host-work.jsonl'); }
// ---------------------------------------------------------------------------
+113
View File
@@ -0,0 +1,113 @@
/**
* AgentRunner pluggable contract for invoking external agents (openclaw,
* hermes, codex, ) inside the claw-test harness. v1 ships a single
* implementation (openclaw); the interface stays narrow and concrete so
* adding a second runner in v1.1 is a ~50-line file.
*
* The harness wraps spawn/timeout/transcript-capture; runners only have to
* answer "where's your binary?" and "how do I invoke it with this prompt?".
*
*
* harness
* resolve(name) registry AgentRunner instance
* detect() runner reports binary path/availability
* invoke(...) runner spawns child, harness captures via TranscriptSink
*
*/
export interface AgentRunner {
/** Stable agent name used by --agent flag and friction `agent` field. */
readonly name: string;
/**
* Locate the agent binary and confirm it is executable. Pure check; never
* spawns. `binPath` is always an absolute path on success. `available=false`
* with a `reason` if not found / not executable.
*/
detect(): Promise<DetectResult>;
/**
* Invoke the agent with the given prompt. The runner is responsible for
* the per-agent argv shape. The harness owns timeouts, signals, and
* transcript capture (via `transcriptSink`).
*/
invoke(opts: InvokeOpts): Promise<InvokeResult>;
/** Optional per-agent post-install hook (e.g., routing-file fixup). */
postInstallHook?(opts: { workspaceDir: string }): Promise<void>;
}
export interface DetectResult {
available: boolean;
reason?: string;
binPath?: string;
}
export interface InvokeOpts {
/** Workspace dir the agent runs in. */
cwd: string;
/** The prompt content. The runner decides whether to write a temp file or pass via argv. */
brief: string;
/** Env to merge with the runner's defaults. Caller already restricted to allow-listed keys. */
env: Record<string, string>;
/** Wall-clock kill switch in ms. Harness handles SIGTERM → 5s grace → SIGKILL. */
timeoutMs: number;
/**
* Per-channel byte sink. The runner pipes child stdin/stdout/stderr into this
* instead of inheriting the parent's. Async-drain backpressure is handled
* inside the sink (D17), so the runner can call `write()` without awaiting.
*/
transcriptSink: TranscriptSink;
/** Optional override for which sub-agent the runner targets. */
agentName?: string;
}
export interface InvokeResult {
exitCode: number;
durationMs: number;
}
/** Async-drain sink. The harness owns the underlying file stream. */
export interface TranscriptSink {
write(event: TranscriptEvent): void;
/** Returns the byte offset that the next written event would have. */
nextOffset(): number;
/** Flush + close. Idempotent. */
close(): Promise<void>;
}
export interface TranscriptEvent {
ts: number;
channel: 'stdin' | 'stdout' | 'stderr';
bytes: Buffer;
}
// ---------------------------------------------------------------------------
// Registry
// ---------------------------------------------------------------------------
type AgentRunnerFactory = () => AgentRunner;
const registry = new Map<string, AgentRunnerFactory>();
export function registerAgentRunner(name: string, factory: AgentRunnerFactory): void {
registry.set(name, factory);
}
export function resolveAgentRunner(name: string): AgentRunner {
const factory = registry.get(name);
if (!factory) {
const known = [...registry.keys()].sort().join(', ') || '(none registered)';
throw new Error(`unknown agent ${JSON.stringify(name)}; registered: ${known}`);
}
return factory();
}
export function listRegisteredAgents(): string[] {
return [...registry.keys()].sort();
}
/** Reset registry — testing only. */
export function _resetRegistryForTests(): void {
registry.clear();
}
+58
View File
@@ -0,0 +1,58 @@
/**
* progress-tail parses gbrain's --progress-json events out of child stderr.
*
* The actual contract (verified post-Codex):
* - `gbrain --progress-json <subcommand>` writes JSONL events to STDERR
* - Stable phase names are dotted snake_case: `import.files`, `extract.links_fs`,
* `embed.pages`, `doctor.db_checks`, etc.
* - Each event line is a JSON object; non-progress stderr lines (warnings,
* debug output, errors) interleave with progress events. We tolerate them.
*
* Used by the verify phase to assert that each `expected_phases` entry from
* scenario.json saw at least one event from the corresponding command.
*/
export interface ProgressEvent {
phase: string;
event?: string; // 'start' | 'tick' | 'finish' | etc per docs/progress-events.md
ts?: string;
[key: string]: unknown;
}
/** Parse a single stderr buffer into the progress events it contains. */
export function parseProgressEvents(stderr: string): ProgressEvent[] {
const out: ProgressEvent[] = [];
for (const line of stderr.split('\n')) {
const trimmed = line.trim();
if (!trimmed.startsWith('{')) continue;
let parsed: unknown;
try {
parsed = JSON.parse(trimmed);
} catch {
continue;
}
if (parsed && typeof parsed === 'object' && typeof (parsed as any).phase === 'string') {
out.push(parsed as ProgressEvent);
}
}
return out;
}
/** Group events by phase name. */
export function eventsByPhase(events: ProgressEvent[]): Map<string, ProgressEvent[]> {
const m = new Map<string, ProgressEvent[]>();
for (const e of events) {
if (!m.has(e.phase)) m.set(e.phase, []);
m.get(e.phase)!.push(e);
}
return m;
}
/**
* Verify that every `expected` phase appears at least once in `events`.
* Returns the missing phase names (empty array on full coverage).
*/
export function verifyExpectedPhases(events: ProgressEvent[], expected: string[]): string[] {
const seen = new Set(events.map(e => e.phase));
return expected.filter(p => !seen.has(p));
}
+98
View File
@@ -0,0 +1,98 @@
/**
* OpenClaw runner invokes the real `openclaw` binary in a tempdir with a
* BRIEF.md prompt. Live mode only.
*
* Invocation pattern (verified against test/e2e/skills.test.ts and
* test/e2e/bench-vs-openclaw/harness.ts):
* openclaw agent --local --agent <agent-name> --message "<brief>"
*
* NOT `openclaw run --prompt-file BRIEF.md` (that flag does not exist
* Codex pass 2 of the eng review caught the speculative shape).
*
* Binary resolution: $OPENCLAW_BIN > `which openclaw` > unavailable.
* Path validation: must be absolute, must be executable, no '..' segments.
*/
import { execSync } from 'child_process';
import { statSync } from 'fs';
import type { AgentRunner, DetectResult, InvokeOpts, InvokeResult } from '../agent-runner.ts';
import { spawnWithCapture } from '../transcript-capture.ts';
const DEFAULT_AGENT_NAME = 'default';
/** Allow-list for env propagation when spawning openclaw. */
const ENV_ALLOWLIST = [
'PATH', 'HOME', 'USER', 'LANG', 'TZ', 'NODE_ENV',
'ANTHROPIC_API_KEY', 'OPENAI_API_KEY',
'GBRAIN_HOME', 'GBRAIN_FRICTION_RUN_ID', 'GBRAIN_DATABASE_URL',
];
export class OpenClawRunner implements AgentRunner {
readonly name = 'openclaw';
async detect(): Promise<DetectResult> {
const fromEnv = process.env.OPENCLAW_BIN?.trim();
let binPath: string | undefined;
if (fromEnv) {
const validation = validateAbsolutePath(fromEnv);
if (validation) return { available: false, reason: validation };
binPath = fromEnv;
} else {
try {
const out = execSync('which openclaw', { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] });
const found = out.trim();
if (!found || !found.startsWith('/')) {
return { available: false, reason: 'openclaw not on PATH' };
}
binPath = found;
} catch {
return { available: false, reason: 'openclaw not on PATH' };
}
}
if (!binPath) return { available: false, reason: 'no binary resolved' };
try {
const s = statSync(binPath);
if (!s.isFile()) return { available: false, reason: `not a regular file: ${binPath}` };
// eslint-disable-next-line no-bitwise
if (!(s.mode & 0o111)) return { available: false, reason: `not executable: ${binPath}` };
} catch (e) {
return { available: false, reason: `stat failed: ${e instanceof Error ? e.message : String(e)}` };
}
return { available: true, binPath };
}
async invoke(opts: InvokeOpts): Promise<InvokeResult> {
const detected = await this.detect();
if (!detected.available || !detected.binPath) {
throw new Error(`openclaw runner unavailable: ${detected.reason ?? 'unknown'}`);
}
const agentName = opts.agentName ?? DEFAULT_AGENT_NAME;
const args = ['agent', '--local', '--agent', agentName, '--message', opts.brief];
// Filter env to allow-list, then merge caller overrides.
const baseEnv: Record<string, string> = {};
for (const key of ENV_ALLOWLIST) {
const v = process.env[key];
if (typeof v === 'string') baseEnv[key] = v;
}
const env: Record<string, string> = { ...baseEnv, ...opts.env };
const result = await spawnWithCapture(detected.binPath, args, {
cwd: opts.cwd,
env,
timeoutMs: opts.timeoutMs,
transcriptSink: opts.transcriptSink,
});
return { exitCode: result.exitCode, durationMs: result.durationMs };
}
}
function validateAbsolutePath(p: string): string | null {
if (!p.startsWith('/')) return `OPENCLAW_BIN must be absolute; got ${p}`;
if (p.split('/').includes('..')) return `OPENCLAW_BIN must not contain '..' segments; got ${p}`;
return null;
}
+114
View File
@@ -0,0 +1,114 @@
/**
* scenario.json loader for the claw-test harness.
*
* test/fixtures/claw-test-scenarios/<name>/scenario.json:
* { kind: "fresh-install", expected_phases: ["import.files", ...], ... }
*
* The harness reads scenario.json to know which phases to assert from
* gbrain's --progress-json events. Pure local fs; no DB, no network.
*/
import { existsSync, readdirSync, readFileSync, statSync } from 'fs';
import { dirname, join, resolve } from 'path';
import { fileURLToPath } from 'url';
export type ScenarioKind = 'fresh-install' | 'upgrade';
export interface ScenarioConfig {
/** Directory the scenario was loaded from. Always absolute. */
dir: string;
/** Stable scenario name (the directory name). */
name: string;
/** Kind of scenario; drives setup-phase behavior. */
kind: ScenarioKind;
/** Stable phase names emitted by --progress-json that the harness asserts. */
expectedPhases: string[];
/** When kind==="upgrade": version we are simulating an upgrade FROM. */
fromVersion?: string;
/** Optional human-readable summary. */
description?: string;
/** Path to BRIEF.md (relative to scenario dir, default 'BRIEF.md'). */
briefRelative: string;
/** Path to brain markdown source (relative to scenario dir). For 'fresh-install': 'brain'. */
brainRelative?: string;
/** Path to seed dir for upgrade scenarios. */
seedRelative?: string;
}
/** Default fixtures root, override via $GBRAIN_CLAW_SCENARIOS_DIR for tests. */
function defaultFixturesRoot(): string {
if (process.env.GBRAIN_CLAW_SCENARIOS_DIR) {
return resolve(process.env.GBRAIN_CLAW_SCENARIOS_DIR);
}
// src/core/claw-test/scenarios.ts → ../../../test/fixtures/claw-test-scenarios
const here = dirname(fileURLToPath(import.meta.url));
return resolve(here, '..', '..', '..', 'test', 'fixtures', 'claw-test-scenarios');
}
/** List all available scenario names. */
export function listScenarios(root?: string): string[] {
const r = root ?? defaultFixturesRoot();
if (!existsSync(r)) return [];
return readdirSync(r)
.filter(name => {
const path = join(r, name);
try {
return statSync(path).isDirectory() && existsSync(join(path, 'scenario.json'));
} catch {
return false;
}
})
.sort();
}
/** Load and validate one scenario by name. */
export function loadScenario(name: string, root?: string): ScenarioConfig {
const r = root ?? defaultFixturesRoot();
const dir = join(r, name);
const cfgPath = join(dir, 'scenario.json');
if (!existsSync(cfgPath)) {
throw new Error(`scenario ${JSON.stringify(name)} not found at ${cfgPath}`);
}
let raw: unknown;
try {
raw = JSON.parse(readFileSync(cfgPath, 'utf-8'));
} catch (e) {
throw new Error(`scenario ${JSON.stringify(name)}: malformed scenario.json (${e instanceof Error ? e.message : e})`);
}
if (!raw || typeof raw !== 'object') {
throw new Error(`scenario ${JSON.stringify(name)}: scenario.json must be a JSON object`);
}
const cfg = raw as Record<string, unknown>;
if (cfg.kind !== 'fresh-install' && cfg.kind !== 'upgrade') {
throw new Error(`scenario ${JSON.stringify(name)}: unknown kind ${JSON.stringify(cfg.kind)}`);
}
if (!Array.isArray(cfg.expected_phases) || !cfg.expected_phases.every(x => typeof x === 'string')) {
throw new Error(`scenario ${JSON.stringify(name)}: expected_phases must be a string[]`);
}
const briefRel = typeof cfg.brief === 'string' ? cfg.brief : 'BRIEF.md';
if (!existsSync(join(dir, briefRel))) {
throw new Error(`scenario ${JSON.stringify(name)}: BRIEF.md missing at ${briefRel}`);
}
const out: ScenarioConfig = {
dir,
name,
kind: cfg.kind,
expectedPhases: cfg.expected_phases as string[],
briefRelative: briefRel,
};
if (typeof cfg.from_version === 'string') out.fromVersion = cfg.from_version;
if (typeof cfg.description === 'string') out.description = cfg.description;
if (typeof cfg.brain === 'string') out.brainRelative = cfg.brain;
if (typeof cfg.seed === 'string') out.seedRelative = cfg.seed;
// Default brain path conventions
if (!out.brainRelative && existsSync(join(dir, 'brain'))) out.brainRelative = 'brain';
if (!out.seedRelative && out.kind === 'upgrade' && existsSync(join(dir, 'seed'))) {
out.seedRelative = 'seed';
}
return out;
}
/** Read BRIEF.md content for this scenario. Used by --live mode. */
export function readBrief(scenario: ScenarioConfig): string {
return readFileSync(join(scenario.dir, scenario.briefRelative), 'utf-8');
}
+123
View File
@@ -0,0 +1,123 @@
/**
* seed-pglite replay a SQL dump into a fresh PGLite database, then let
* gbrain's migration chain walk forward.
*
* Codex caught (eng review pass 2) that existing migration helpers
* (test/e2e/helpers.ts:204) are Postgres-only they rewind schema_version
* and replay against real Postgres. PGLite has no equivalent. This helper
* fills that gap so the `upgrade-from-v0.18` claw-test scenario is
* reproducible.
*
* Usage:
* const dbPath = await seedPglite('/tmp/run-x/.gbrain/brain.pglite', seedSql);
* // Then run `gbrain init --pglite --path <dbPath>` — the migration chain
* // detects the seeded schema_version and migrates forward to LATEST.
*/
import { existsSync, mkdirSync, readFileSync } from 'fs';
import { dirname } from 'path';
import { PGLiteEngine } from '../pglite-engine.ts';
export interface SeedOpts {
/** Absolute path to the .pglite file to create. */
dbPath: string;
/** Raw SQL dump to replay. */
sql: string;
}
/**
* Open a fresh PGLite at `dbPath`, execute the SQL dump, disconnect.
* Throws on SQL errors with a structured message that names the failing
* statement (helpful for debugging seed drift).
*/
export async function seedPglite(opts: SeedOpts): Promise<void> {
const dir = dirname(opts.dbPath);
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
const engine = new PGLiteEngine();
try {
await engine.connect({ engine: 'pglite', database_path: opts.dbPath });
// Execute statements one at a time so an error names the offending
// statement. The seed file is committed to source so we can normalize
// its line endings; we rely on `;\n` as the statement terminator.
const statements = splitStatements(opts.sql);
for (const stmt of statements) {
const trimmed = stmt.trim();
if (!trimmed) continue;
try {
await (engine as any).db.exec(trimmed);
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
const preview = trimmed.slice(0, 120).replace(/\s+/g, ' ');
throw new Error(`seedPglite: SQL execution failed at "${preview}…": ${msg}`);
}
}
} finally {
await engine.disconnect();
}
}
/** Read seed SQL from disk and replay into `dbPath`. */
export async function seedPgliteFromFile(opts: { dbPath: string; sqlPath: string }): Promise<void> {
if (!existsSync(opts.sqlPath)) {
throw new Error(`seedPglite: seed SQL not found at ${opts.sqlPath}`);
}
const sql = readFileSync(opts.sqlPath, 'utf-8');
return seedPglite({ dbPath: opts.dbPath, sql });
}
/**
* Split a SQL dump into individual statements. Naïve `;` split that respects
* single-quoted strings and `--` line comments. Sufficient for canonical
* pg_dump output; intentionally NOT a full SQL parser.
*/
function splitStatements(sql: string): string[] {
const out: string[] = [];
let buf = '';
let inSingle = false;
let inLineComment = false;
let i = 0;
while (i < sql.length) {
const c = sql[i];
const next = sql[i + 1];
if (inLineComment) {
buf += c;
if (c === '\n') inLineComment = false;
i++;
continue;
}
if (inSingle) {
buf += c;
if (c === "'" && next === "'") { buf += next; i += 2; continue; }
if (c === "'") inSingle = false;
i++;
continue;
}
if (c === '-' && next === '-') {
inLineComment = true;
buf += c;
i++;
continue;
}
if (c === "'") {
inSingle = true;
buf += c;
i++;
continue;
}
if (c === ';') {
buf += c;
out.push(buf);
buf = '';
i++;
continue;
}
buf += c;
i++;
}
if (buf.trim()) out.push(buf);
return out;
}
/** Exposed for tests. */
export const _internal = { splitStatements };
+172
View File
@@ -0,0 +1,172 @@
/**
* Transcript capture for live-mode agent runs (D8 + D14, D17 backpressure).
*
* The existing minions/audit infrastructure is for INTERNAL gbrain subagents
* only. External openclaw/hermes subprocesses don't write to those tables
* v1 builds its own capture channel here.
*
* Output: JSONL at `<run-tempdir>/transcript.jsonl`, one event per line.
* { schema_version: "1", ts, channel, byte_offset, bytes_b64 }
*
* child stdout/stderr piped TranscriptSink.write()
*
*
* fs.createWriteStream (flags: 'a')
*
* honors 'drain' events to avoid blocking
* the child when bursts exceed the pipe buffer
*
* transcript.jsonl (line-tolerant readers
* skip malformed; render() resolves
* byte_offset readable lines)
*
* Friction CLI's `transcript_offset` field references the byte offset INTO
* `transcript.jsonl` (not into the captured payload). Render --transcripts
* reads the file and finds the line that contains that offset.
*/
import { createWriteStream, type WriteStream } from 'fs';
import { spawn, type ChildProcess } from 'child_process';
import { dirname } from 'path';
import { mkdirSync, existsSync } from 'fs';
import type { TranscriptEvent, TranscriptSink } from './agent-runner.ts';
// ---------------------------------------------------------------------------
// Sink
// ---------------------------------------------------------------------------
export function createTranscriptSink(path: string): TranscriptSink {
const dir = dirname(path);
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
const stream: WriteStream = createWriteStream(path, { flags: 'a' });
let bytesWritten = 0;
let drainPromise: Promise<void> | null = null;
function awaitDrain(): Promise<void> {
if (drainPromise) return drainPromise;
drainPromise = new Promise<void>(resolve => {
stream.once('drain', () => {
drainPromise = null;
resolve();
});
});
return drainPromise;
}
return {
write(event: TranscriptEvent) {
const line = JSON.stringify({
schema_version: '1',
ts: event.ts,
channel: event.channel,
byte_offset: bytesWritten,
bytes_b64: event.bytes.toString('base64'),
}) + '\n';
bytesWritten += Buffer.byteLength(line, 'utf-8');
const ok = stream.write(line, 'utf-8');
// If the kernel buffer is full, write() returns false. We don't await
// here (callers don't expect that), but next callers wait on drain
// before writing further. Bun's WritableStream is small; the drain
// window is typically a few µs.
if (!ok) void awaitDrain();
},
nextOffset(): number {
return bytesWritten;
},
async close(): Promise<void> {
await new Promise<void>((resolve, reject) => {
stream.end((err?: Error | null) => err ? reject(err) : resolve());
});
},
};
}
// ---------------------------------------------------------------------------
// spawnWithCapture
// ---------------------------------------------------------------------------
export interface SpawnOpts {
cwd: string;
env: Record<string, string>;
timeoutMs: number;
transcriptSink: TranscriptSink;
/** Optional fixed input to write on stdin then close. */
stdinPayload?: string;
}
export interface SpawnResult {
exitCode: number;
durationMs: number;
/** True if SIGTERM/SIGKILL was issued due to timeout. */
timedOut: boolean;
}
const SIGTERM_GRACE_MS = 5_000;
export async function spawnWithCapture(bin: string, args: string[], opts: SpawnOpts): Promise<SpawnResult> {
const start = Date.now();
return new Promise((resolve, reject) => {
let child: ChildProcess;
try {
child = spawn(bin, args, {
cwd: opts.cwd,
env: opts.env,
stdio: ['pipe', 'pipe', 'pipe'],
shell: false,
});
} catch (e) {
reject(e);
return;
}
let timedOut = false;
let killTimer: ReturnType<typeof setTimeout> | null = null;
const wallClockTimer = setTimeout(() => {
timedOut = true;
try { child.kill('SIGTERM'); } catch { /* already gone */ }
killTimer = setTimeout(() => {
try { child.kill('SIGKILL'); } catch { /* already gone */ }
}, SIGTERM_GRACE_MS);
}, opts.timeoutMs);
child.stdout?.on('data', (chunk: Buffer) => {
opts.transcriptSink.write({ ts: Date.now(), channel: 'stdout', bytes: chunk });
});
child.stderr?.on('data', (chunk: Buffer) => {
opts.transcriptSink.write({ ts: Date.now(), channel: 'stderr', bytes: chunk });
});
if (opts.stdinPayload !== undefined && child.stdin) {
try {
opts.transcriptSink.write({
ts: Date.now(),
channel: 'stdin',
bytes: Buffer.from(opts.stdinPayload, 'utf-8'),
});
child.stdin.end(opts.stdinPayload, 'utf-8');
} catch (e) {
reject(e);
return;
}
}
child.on('error', (err) => {
clearTimeout(wallClockTimer);
if (killTimer) clearTimeout(killTimer);
reject(err);
});
child.on('close', (code) => {
clearTimeout(wallClockTimer);
if (killTimer) clearTimeout(killTimer);
resolve({
exitCode: typeof code === 'number' ? code : (timedOut ? 124 : 1),
durationMs: Date.now() - start,
timedOut,
});
});
});
}
+28 -5
View File
@@ -19,9 +19,11 @@ export type DbUrlSource =
| 'config-file-path' // PGLite: config file present, no URL but database_path set
| null;
// Lazy-evaluated to avoid calling homedir() at module scope (breaks in serverless/bundled environments)
function getConfigDir() { return join(homedir(), '.gbrain'); }
function getConfigPath() { return join(getConfigDir(), 'config.json'); }
// Internal aliases retained for backwards compatibility with the existing call
// sites below. They forward to the exported configDir()/configPath() so
// GBRAIN_HOME is honored uniformly. Lazy: never call homedir() at module scope.
function getConfigDir() { return configDir(); }
function getConfigPath() { return configPath(); }
export interface GBrainConfig {
engine: 'postgres' | 'pglite';
@@ -88,9 +90,20 @@ export function toEngineConfig(config: GBrainConfig): EngineConfig {
export function configDir(): string {
// Allow override for tests, Docker, and multi-tenant deployments.
// Matches the `GBRAIN_AUDIT_DIR` convention in src/core/minions/handlers/shell-audit.ts.
// GBRAIN_HOME is a parent dir; we always append '.gbrain' ourselves so
// setting GBRAIN_HOME=/tmp/x yields configDir() === '/tmp/x/.gbrain'.
// Validates the override: must be absolute, no '..' segments.
const override = process.env.GBRAIN_HOME;
if (override && override.trim()) return join(override, '.gbrain');
if (override && override.trim()) {
const trimmed = override.trim();
if (!trimmed.startsWith('/')) {
throw new Error(`GBRAIN_HOME must be an absolute path; got: ${trimmed}`);
}
if (trimmed.split('/').includes('..')) {
throw new Error(`GBRAIN_HOME must not contain '..' segments; got: ${trimmed}`);
}
return join(trimmed, '.gbrain');
}
return join(homedir(), '.gbrain');
}
@@ -98,6 +111,16 @@ export function configPath(): string {
return join(configDir(), 'config.json');
}
/**
* Sugar for joining paths under the active gbrain home. Use this anywhere you
* would otherwise write `join(homedir(), '.gbrain', ...rest)`. Honors
* GBRAIN_HOME, validates input, and centralizes the convention so future
* audits stay simple.
*/
export function gbrainPath(...segments: string[]): string {
return join(configDir(), ...segments);
}
/**
* Introspect where the active DB URL would come from if we tried to connect.
* Never throws, never connects. Env vars take precedence (matches loadConfig).
+5 -3
View File
@@ -39,7 +39,8 @@
import { existsSync, readFileSync, writeFileSync, unlinkSync, mkdirSync, statSync } from 'fs';
import { join } from 'path';
import { homedir, hostname } from 'os';
import { hostname } from 'os';
import { gbrainPath } from './config.ts';
import type { BrainEngine } from './engine.ts';
import { createProgress, type ProgressReporter } from './progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from './cli-options.ts';
@@ -154,7 +155,8 @@ export interface CycleOpts {
const CYCLE_LOCK_ID = 'gbrain-cycle';
const LOCK_TTL_MS = 30 * 60 * 1000; // 30 minutes
const LOCK_FILE_PATH_DEFAULT = join(homedir(), '.gbrain', 'cycle.lock');
// Lazy: GBRAIN_HOME may be set after module load; resolve at call time.
const getLockFilePathDefault = () => gbrainPath('cycle.lock');
interface LockHandle {
release: () => Promise<void>;
@@ -256,7 +258,7 @@ async function acquirePostgresLock(engine: BrainEngine): Promise<LockHandle | nu
* The file contains `{pid}\n{iso-timestamp}`. Staleness = mtime older
* than LOCK_TTL_MS OR the PID is no longer alive on this host.
*/
function acquireFileLock(lockPath = LOCK_FILE_PATH_DEFAULT): LockHandle | null {
function acquireFileLock(lockPath = getLockFilePathDefault()): LockHandle | null {
mkdirSync(join(lockPath, '..'), { recursive: true });
const pid = process.pid;
+4 -3
View File
@@ -12,7 +12,7 @@
import { appendFileSync, readFileSync, existsSync, mkdirSync, writeFileSync, renameSync } from 'fs';
import { join, dirname } from 'path';
import { homedir } from 'os';
import { gbrainPath } from './config.ts';
// ---------------------------------------------------------------------------
// Types
@@ -45,7 +45,8 @@ export interface TestCase {
source: 'fail-improve-loop';
}
const LOG_DIR = join(homedir(), '.gbrain', 'fail-improve');
// Lazy: GBRAIN_HOME may be set after module load, so resolve at call time.
const getLogDir = () => gbrainPath('fail-improve');
const MAX_ENTRIES = 1000;
// ---------------------------------------------------------------------------
@@ -76,7 +77,7 @@ export class FailImproveLoop {
private logDir: string;
constructor(logDir?: string) {
this.logDir = logDir || LOG_DIR;
this.logDir = logDir || getLogDir();
}
/**
+374
View File
@@ -0,0 +1,374 @@
/**
* Friction reporter JSONL-backed signal capture for the claw-test feedback loop.
*
* The friction CLI (`gbrain friction log/render/list/summary`) writes here.
* The claw-test harness reads here. The agent calls `gbrain friction log`
* directly when it hits something confusing, missing, or wrong.
*
* Storage shape: append-only JSONL files under `$GBRAIN_HOME/friction/`.
* - `<run-id>.jsonl` for each harness run (run-id from $GBRAIN_FRICTION_RUN_ID)
* - `standalone.jsonl` for entries logged outside a harness run
*
* Schema is a flat extension of StructuredAgentError fields (per D20). Render
* reads one level. Readers tolerate malformed lines (skip + warn) so partial
* runs don't break later analysis.
*
* appendFileSync
* writer() <runId>.jsonl (one
* (atomic if line entry per line)
* PIPE_BUF/4KB)
*
*
* reader() / render()
* skip malformed + warn
*/
import { appendFileSync, existsSync, readdirSync, readFileSync, mkdirSync, statSync } from 'fs';
import { dirname, join } from 'path';
import { homedir } from 'os';
import { gbrainPath } from './config.ts';
import { VERSION } from '../version.ts';
// ---------------------------------------------------------------------------
// Schema
// ---------------------------------------------------------------------------
export type FrictionKind = 'friction' | 'delight' | 'phase-marker' | 'interrupted';
export type FrictionSeverity = 'confused' | 'error' | 'blocker' | 'nit';
export type FrictionSource = 'claw' | 'harness';
export type PhaseMarker = 'start' | 'end';
/** One JSONL entry. Flat extension of StructuredAgentError per D20. */
export interface FrictionEntry {
schema_version: '1';
ts: string; // ISO 8601
run_id: string;
phase: string;
kind: FrictionKind;
/** Required for kind=friction|delight. Optional for phase-marker (purely informational). */
severity?: FrictionSeverity;
message: string;
hint?: string;
/** StructuredAgentError envelope fields, flattened. */
class?: string;
code?: string;
docs_url?: string;
source: FrictionSource;
cwd: string;
gbrain_version: string;
agent?: string;
/** Byte offset into the run's transcript.jsonl (live mode). */
transcript_offset?: number;
/** For phase-marker entries only. */
marker?: PhaseMarker;
}
export interface FrictionLogInput {
severity?: FrictionSeverity;
phase: string;
message: string;
hint?: string;
runId?: string;
kind?: FrictionKind;
source?: FrictionSource;
agent?: string;
transcriptOffset?: number;
marker?: PhaseMarker;
/** When the writer is called from the harness wrapping a child error. */
errorClass?: string;
errorCode?: string;
docsUrl?: string;
}
// ---------------------------------------------------------------------------
// Path resolution
// ---------------------------------------------------------------------------
/** Resolve the directory all friction JSONL files live under. */
export function frictionDir(): string {
return gbrainPath('friction');
}
/** Resolve the JSONL file path for a given run-id. */
export function frictionFile(runId: string): string {
return join(frictionDir(), `${sanitizeRunId(runId)}.jsonl`);
}
/** Resolve the active run-id, falling back to 'standalone' (D19). */
export function activeRunId(): string {
const env = process.env.GBRAIN_FRICTION_RUN_ID?.trim();
return env && env.length > 0 ? env : 'standalone';
}
/** Sanitize: only [a-zA-Z0-9._-]; reject anything else to keep filenames sane. */
function sanitizeRunId(runId: string): string {
if (!/^[a-zA-Z0-9._-]+$/.test(runId)) {
throw new Error(`invalid run-id ${JSON.stringify(runId)} (allowed: [a-zA-Z0-9._-])`);
}
return runId;
}
// ---------------------------------------------------------------------------
// Writer
// ---------------------------------------------------------------------------
/** Maximum message length; truncated to keep each line under PIPE_BUF for atomic appends. */
const MAX_MESSAGE_CHARS = 3500;
/** Append one friction entry to the run's JSONL. */
export function logFriction(input: FrictionLogInput): void {
const runId = input.runId ?? activeRunId();
const dir = frictionDir();
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
const message = truncate(input.message, MAX_MESSAGE_CHARS);
const entry: FrictionEntry = {
schema_version: '1',
ts: new Date().toISOString(),
run_id: runId,
phase: input.phase,
kind: input.kind ?? 'friction',
message,
source: input.source ?? 'claw',
cwd: process.cwd(),
gbrain_version: VERSION,
};
if (input.severity) entry.severity = input.severity;
if (input.hint) entry.hint = input.hint;
if (input.errorClass) entry.class = input.errorClass;
if (input.errorCode) entry.code = input.errorCode;
if (input.docsUrl) entry.docs_url = input.docsUrl;
if (input.agent) entry.agent = input.agent;
if (input.transcriptOffset !== undefined) entry.transcript_offset = input.transcriptOffset;
if (input.marker) entry.marker = input.marker;
const line = JSON.stringify(entry) + '\n';
appendFileSync(frictionFile(runId), line, 'utf-8');
}
function truncate(s: string, max: number): string {
if (s.length <= max) return s;
return s.slice(0, max - 14) + '…[truncated]';
}
// ---------------------------------------------------------------------------
// Reader
// ---------------------------------------------------------------------------
export interface ReadResult {
entries: FrictionEntry[];
/** Count of malformed JSONL lines that were skipped. */
malformed: number;
}
/** Read all entries from a run's JSONL, skipping malformed lines. */
export function readFriction(runId: string): ReadResult {
const path = frictionFile(runId);
if (!existsSync(path)) {
throw new Error(`run-id "${runId}" not found at ${path}`);
}
const raw = readFileSync(path, 'utf-8');
const entries: FrictionEntry[] = [];
let malformed = 0;
for (const line of raw.split('\n')) {
if (!line.trim()) continue;
try {
const parsed = JSON.parse(line);
// Light shape check: must have ts + kind + phase + message
if (typeof parsed.ts === 'string' && typeof parsed.kind === 'string' && typeof parsed.phase === 'string' && typeof parsed.message === 'string') {
entries.push(parsed as FrictionEntry);
} else {
malformed++;
}
} catch {
malformed++;
}
}
return { entries, malformed };
}
/** List run-ids with summary counts. Returns most-recent-first. */
export interface RunSummary {
runId: string;
path: string;
mtime: Date;
counts: { friction: number; delight: number; interrupted: boolean; bySeverity: Record<string, number> };
}
export function listRuns(): RunSummary[] {
const dir = frictionDir();
if (!existsSync(dir)) return [];
const out: RunSummary[] = [];
for (const file of readdirSync(dir)) {
if (!file.endsWith('.jsonl')) continue;
const runId = file.slice(0, -'.jsonl'.length);
const path = join(dir, file);
const stat = statSync(path);
let read: ReadResult;
try {
read = readFriction(runId);
} catch {
continue;
}
const counts = { friction: 0, delight: 0, interrupted: false, bySeverity: {} as Record<string, number> };
for (const e of read.entries) {
if (e.kind === 'friction') counts.friction++;
if (e.kind === 'delight') counts.delight++;
if (e.kind === 'interrupted') counts.interrupted = true;
if (e.severity) counts.bySeverity[e.severity] = (counts.bySeverity[e.severity] ?? 0) + 1;
}
out.push({ runId, path, mtime: stat.mtime, counts });
}
out.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
return out;
}
// ---------------------------------------------------------------------------
// Renderer
// ---------------------------------------------------------------------------
export interface RenderOpts {
format?: 'md' | 'json';
redact?: boolean;
/** When true, transcript_offset values are resolved against this transcript file. */
transcriptPath?: string;
}
/** Render entries grouped by severity then phase. Returns the rendered string. */
export function renderReport(runId: string, opts: RenderOpts = {}): string {
const { entries, malformed } = readFriction(runId);
const format = opts.format ?? 'md';
const redact = opts.redact ?? (format === 'md');
const transformed = entries.map(e => redact ? redactEntry(e) : e);
if (format === 'json') {
return JSON.stringify({ run_id: runId, malformed, entries: transformed }, null, 2);
}
// Markdown grouping: severity (blocker > error > confused > nit > none) → phase
const sevOrder: (FrictionSeverity | 'none')[] = ['blocker', 'error', 'confused', 'nit', 'none'];
const bySev = new Map<string, FrictionEntry[]>();
for (const e of transformed) {
if (e.kind !== 'friction' && e.kind !== 'delight') continue;
const k = e.severity ?? 'none';
if (!bySev.has(k)) bySev.set(k, []);
bySev.get(k)!.push(e);
}
const lines: string[] = [];
lines.push(`# Friction report — \`${runId}\``);
lines.push('');
const totalFriction = entries.filter(e => e.kind === 'friction').length;
const totalDelight = entries.filter(e => e.kind === 'delight').length;
lines.push(`**${totalFriction} friction · ${totalDelight} delight**${malformed > 0 ? ` · ${malformed} malformed line(s) skipped` : ''}`);
lines.push('');
if (entries.some(e => e.kind === 'interrupted')) {
lines.push('> ⚠ **Run was interrupted.** Some phases may not have completed.');
lines.push('');
}
for (const sev of sevOrder) {
const bucket = bySev.get(sev);
if (!bucket || bucket.length === 0) continue;
lines.push(`## ${sev === 'none' ? '(no severity)' : sev}`);
lines.push('');
// Group by phase within severity
const byPhase = new Map<string, FrictionEntry[]>();
for (const e of bucket) {
if (!byPhase.has(e.phase)) byPhase.set(e.phase, []);
byPhase.get(e.phase)!.push(e);
}
for (const [phase, phaseEntries] of byPhase) {
lines.push(`### \`${phase}\``);
lines.push('');
for (const e of phaseEntries) {
lines.push(`- ${e.kind === 'delight' ? '✨' : '·'} ${e.message}`);
if (e.hint) lines.push(` - hint: ${e.hint}`);
if (e.code) lines.push(` - code: \`${e.code}\``);
if (e.docs_url) lines.push(` - docs: ${e.docs_url}`);
if (opts.transcriptPath && e.transcript_offset !== undefined) {
const snippet = readTranscriptAt(opts.transcriptPath, e.transcript_offset);
if (snippet) lines.push(` - transcript: \`${snippet}\``);
}
}
lines.push('');
}
}
return lines.join('\n');
}
/** Render a friction + delight summary as two columns. */
export function renderSummary(runId: string, opts: { format?: 'md' | 'json' } = {}): string {
const { entries } = readFriction(runId);
const friction = entries.filter(e => e.kind === 'friction');
const delight = entries.filter(e => e.kind === 'delight');
if (opts.format === 'json') {
return JSON.stringify({ run_id: runId, friction, delight }, null, 2);
}
const lines: string[] = [];
lines.push(`# ${runId}`);
lines.push('');
const max = Math.max(friction.length, delight.length);
lines.push(`| friction (${friction.length}) | delight (${delight.length}) |`);
lines.push('|---|---|');
for (let i = 0; i < max; i++) {
const l = friction[i] ? friction[i].message.replace(/\|/g, '\\|') : '';
const r = delight[i] ? delight[i].message.replace(/\|/g, '\\|') : '';
lines.push(`| ${l} | ${r} |`);
}
return lines.join('\n');
}
// ---------------------------------------------------------------------------
// Redaction
// ---------------------------------------------------------------------------
/** Replace homedir/cwd segments in user-visible string fields with placeholders. */
export function redactEntry(entry: FrictionEntry): FrictionEntry {
const home = homedir();
const cwd = entry.cwd;
const transform = (s: string | undefined): string | undefined => {
if (!s) return s;
let out = s;
if (cwd && cwd.length > 1) out = out.split(cwd).join('<CWD>');
if (home && home.length > 1) out = out.split(home).join('<HOME>');
return out;
};
return {
...entry,
message: transform(entry.message) ?? entry.message,
hint: transform(entry.hint),
cwd: '<CWD>',
};
}
// ---------------------------------------------------------------------------
// Transcript snippet resolution (for --transcripts)
// ---------------------------------------------------------------------------
function readTranscriptAt(path: string, offset: number): string | null {
try {
if (!existsSync(path)) return null;
const raw = readFileSync(path, 'utf-8');
if (offset < 0 || offset >= raw.length) return null;
// Find the line that contains this offset. Transcript is JSONL.
const lineStart = raw.lastIndexOf('\n', offset) + 1;
const lineEnd = raw.indexOf('\n', offset);
const line = raw.slice(lineStart, lineEnd === -1 ? undefined : lineEnd);
try {
const parsed = JSON.parse(line);
if (parsed && typeof parsed.bytes_b64 === 'string') {
const text = Buffer.from(parsed.bytes_b64, 'base64').toString('utf-8');
// Truncate snippet for readability
return text.replace(/\n/g, '\\n').slice(0, 200);
}
} catch { /* fall through */ }
return line.slice(0, 200);
} catch {
return null;
}
}
+410
View File
@@ -0,0 +1,410 @@
/**
* Frontmatter inference synthesize YAML frontmatter from filesystem metadata.
*
* ## Why this exists
*
* GBrain's sync and import pipelines work fine without frontmatter gray-matter
* returns the full content as body, and `inferType`/`inferTitle` in markdown.ts
* provide fallbacks. But the inferred metadata is minimal:
*
* - `type` defaults to 'concept' for most paths
* - `title` is the slugified filename ("2010 04 13 Apr 13 Founders Mtg")
* - No `date` field, no `source` metadata, no folder-aware tagging
*
* This module provides **rich inference** directory-aware type mapping, date
* extraction from filenames, title cleanup (strip date prefixes, HTML entities),
* heading extraction from content, and source/folder tagging. It produces a
* complete frontmatter block that can be:
*
* 1. Written back to the file on disk (via `gbrain frontmatter generate --fix`)
* 2. Used at import time without modifying the file (DB-only inference)
* 3. Shown as a dry-run preview (via `gbrain frontmatter generate --dry-run`)
*
* ## Design principles
*
* - **Never overwrite existing frontmatter.** If a file already has `---`, skip it.
* - **Infer from filesystem first, content second.** Directory path type, filename date + title,
* first `#` heading title fallback, content entity hints.
* - **Deterministic.** Same file always produces the same frontmatter. No LLM calls, no network.
* - **Extensible via rules.** The `DIRECTORY_RULES` table maps path patterns to type + source + tags.
* Adding a new directory convention = adding one rule.
* - **Safe.** `.bak` files on write, `--dry-run` by default in CLI, idempotent.
*
* ## How it fits in the pipeline
*
* ```
* Sync/Import
* file has frontmatter? normal import (existing path)
* file has NO frontmatter?
* inferFrontmatter(filePath, content) synthesize frontmatter
* prepend to content import as usual
* optionally write back to disk (--write-back flag)
* ```
*
* The inference runs BEFORE `parseMarkdown`, so the downstream pipeline sees
* well-formed frontmatter and all the existing validation/chunking/embedding
* logic works unchanged.
*
* ## Directory rules table
*
* Each rule matches a path pattern (case-insensitive prefix) and provides:
* - `type`: page type for the brain schema
* - `source`: optional source tag (e.g., "apple-notes", "therapy")
* - `tags`: optional additional tags
* - `datePattern`: where to look for dates 'filename' (YYYY-MM-DD prefix),
* 'dirname' (parent dir name), or 'none'
* - `titleStrategy`: how to extract title 'filename' (strip date prefix),
* 'heading' (first # in content), 'filename-full' (no date strip)
*/
import { basename, dirname, relative } from 'path';
// ─── Types ───────────────────────────────────────────────────────────
export interface InferredFrontmatter {
title: string;
type: string;
date?: string;
source?: string;
tags?: string[];
/** True if the file already has frontmatter (inference skipped). */
skipped?: boolean;
/** The rule that matched, for debugging. */
matchedRule?: string;
}
export interface DirectoryRule {
/** Case-insensitive path prefix to match (e.g., 'apple notes/'). */
pathPrefix: string;
/** Page type to assign. */
type: string;
/** Optional source tag. */
source?: string;
/** Optional tags to add. */
tags?: string[];
/** Where to look for dates. Default: 'filename'. */
datePattern?: 'filename' | 'dirname' | 'none';
/** How to extract title. Default: 'filename'. */
titleStrategy?: 'filename' | 'heading' | 'filename-full';
}
// ─── Directory Rules ─────────────────────────────────────────────────
// Ordered from most specific to least specific. First match wins.
// Add new directory conventions here.
export const DIRECTORY_RULES: DirectoryRule[] = [
// Apple Notes — bulk import from Apple Notes app. Filenames are
// "YYYY-MM-DD Title.md" with HTML-styled content.
{
pathPrefix: 'apple notes/youtube shows/',
type: 'apple-note',
source: 'apple-notes',
tags: ['youtube', 'shows'],
datePattern: 'filename',
titleStrategy: 'filename',
},
{
pathPrefix: 'apple notes/yc/',
type: 'apple-note',
source: 'apple-notes',
tags: ['yc'],
datePattern: 'filename',
titleStrategy: 'filename',
},
{
pathPrefix: 'apple notes/archived/',
type: 'apple-note',
source: 'apple-notes',
tags: ['archived'],
datePattern: 'filename',
titleStrategy: 'filename',
},
{
pathPrefix: 'apple notes/politics/',
type: 'apple-note',
source: 'apple-notes',
tags: ['politics'],
datePattern: 'filename',
titleStrategy: 'filename',
},
{
pathPrefix: 'apple notes/pitch notes/',
type: 'apple-note',
source: 'apple-notes',
tags: ['pitch-notes'],
datePattern: 'filename',
titleStrategy: 'filename',
},
{
pathPrefix: 'apple notes/gstack/',
type: 'apple-note',
source: 'apple-notes',
tags: ['gstack'],
datePattern: 'filename',
titleStrategy: 'filename',
},
{
pathPrefix: 'apple notes/photo-cameras/',
type: 'apple-note',
source: 'apple-notes',
tags: ['photography'],
datePattern: 'filename',
titleStrategy: 'filename',
},
{
pathPrefix: 'apple notes/jan bowman notes/',
type: 'apple-note',
source: 'apple-notes',
tags: ['therapy', 'jan-bowman'],
datePattern: 'filename',
titleStrategy: 'filename',
},
// Catch-all for Apple Notes not in a subfolder
{
pathPrefix: 'apple notes/',
type: 'apple-note',
source: 'apple-notes',
datePattern: 'filename',
titleStrategy: 'filename',
},
// Calendar diarization files
{
pathPrefix: 'daily/calendar/',
type: 'calendar-index',
source: 'calendar',
datePattern: 'filename',
titleStrategy: 'filename',
},
// Personal sections
{
pathPrefix: 'personal/therapy/',
type: 'therapy-session',
source: 'therapy',
datePattern: 'filename',
titleStrategy: 'filename',
},
{
pathPrefix: 'personal/reflections/',
type: 'reflection',
source: 'personal',
datePattern: 'filename',
titleStrategy: 'heading',
},
{
pathPrefix: 'personal/',
type: 'personal',
source: 'personal',
datePattern: 'none',
titleStrategy: 'heading',
},
// Writing
{
pathPrefix: 'writing/essays/',
type: 'essay',
source: 'writing',
datePattern: 'filename',
titleStrategy: 'heading',
},
{
pathPrefix: 'writing/ideas/',
type: 'idea',
source: 'writing',
datePattern: 'filename',
titleStrategy: 'heading',
},
{
pathPrefix: 'writing/',
type: 'writing',
source: 'writing',
datePattern: 'filename',
titleStrategy: 'heading',
},
// Entity directories — these should already have frontmatter in most cases,
// but the 55 people pages etc. that don't get handled here.
{ pathPrefix: 'people/', type: 'person', titleStrategy: 'heading' },
{ pathPrefix: 'companies/', type: 'company', titleStrategy: 'heading' },
{ pathPrefix: 'projects/', type: 'project', titleStrategy: 'heading' },
{ pathPrefix: 'civic/', type: 'civic', titleStrategy: 'heading' },
{ pathPrefix: 'events/', type: 'event', titleStrategy: 'heading', datePattern: 'filename' },
{ pathPrefix: 'meetings/', type: 'meeting', titleStrategy: 'heading', datePattern: 'filename' },
{ pathPrefix: 'media/', type: 'media', titleStrategy: 'heading' },
// Catch-all for any remaining files
{ pathPrefix: '', type: 'note', titleStrategy: 'heading' },
];
// ─── Date extraction ─────────────────────────────────────────────────
/** Extract YYYY-MM-DD date from a filename like "2010-04-13 Apr 13 founders mtg.md" */
export function extractDateFromFilename(filename: string): string | null {
// Pattern 1: YYYY-MM-DD prefix (with - or space separator after)
const m1 = filename.match(/^(\d{4}-\d{2}-\d{2})[\s_-]/);
if (m1) return m1[1];
// Pattern 2: YYYY-MM-DD anywhere in filename
const m2 = filename.match(/(\d{4}-\d{2}-\d{2})/);
if (m2) return m2[1];
// Pattern 3: "YYYY MM DD" with spaces
const m3 = filename.match(/^(\d{4})\s+(\d{2})\s+(\d{2})\s/);
if (m3) return `${m3[1]}-${m3[2]}-${m3[3]}`;
return null;
}
// ─── Title extraction ────────────────────────────────────────────────
/** Extract title from filename, stripping date prefix and extension. */
export function extractTitleFromFilename(filename: string): string {
// Remove .md extension
let title = filename.replace(/\.md$/i, '');
// Strip YYYY-MM-DD prefix (with separator)
title = title.replace(/^\d{4}-\d{2}-\d{2}[\s_-]+/, '');
// Strip YYYY MM DD prefix (space-separated)
title = title.replace(/^\d{4}\s+\d{2}\s+\d{2}\s+/, '');
// Clean up: title case, replace dashes/underscores with spaces
title = title
.replace(/[-_]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
// Don't title-case if it already has mixed case (e.g., "YC presidency")
if (title === title.toLowerCase() || title === title.toUpperCase()) {
title = title.replace(/\b\w/g, c => c.toUpperCase());
}
return title || 'Untitled';
}
/** Extract title from first heading (# ...) in content. */
export function extractTitleFromHeading(content: string): string | null {
const lines = content.split('\n');
for (const line of lines.slice(0, 20)) {
const m = line.match(/^#\s+(.+)/);
if (m) return m[1].trim();
}
return null;
}
// ─── Core inference ──────────────────────────────────────────────────
/**
* Infer frontmatter for a file that has none.
*
* @param relativePath - Path relative to brain root (e.g., "Apple Notes/2010-04-13 Apr 13 founders mtg.md")
* @param content - File content (may be empty)
* @returns Inferred frontmatter fields
*/
export function inferFrontmatter(relativePath: string, content: string): InferredFrontmatter {
// Check if file already has frontmatter
const firstNonEmpty = content.split('\n').find(l => l.trim().length > 0);
if (firstNonEmpty?.trim() === '---') {
return { title: '', type: '', skipped: true };
}
const lowerPath = relativePath.toLowerCase();
const filename = basename(relativePath);
// Find matching rule
let matchedRule: DirectoryRule | undefined;
for (const rule of DIRECTORY_RULES) {
if (lowerPath.startsWith(rule.pathPrefix.toLowerCase())) {
matchedRule = rule;
break;
}
}
// Default rule if none matched
if (!matchedRule) {
matchedRule = { pathPrefix: '', type: 'note', titleStrategy: 'heading' };
}
// Extract date
let date: string | undefined;
const datePattern = matchedRule.datePattern ?? 'filename';
if (datePattern === 'filename') {
date = extractDateFromFilename(filename) ?? undefined;
}
// Extract title
let title: string;
const titleStrategy = matchedRule.titleStrategy ?? 'filename';
if (titleStrategy === 'heading') {
title = extractTitleFromHeading(content) ?? extractTitleFromFilename(filename);
} else if (titleStrategy === 'filename-full') {
title = filename.replace(/\.md$/i, '').replace(/[-_]/g, ' ').trim();
} else {
title = extractTitleFromFilename(filename);
}
// Build tags from rule + subfolder
const tags = [...(matchedRule.tags ?? [])];
// Add subfolder as tag for Apple Notes (e.g., "YC", "Politics")
if (matchedRule.source === 'apple-notes' && matchedRule.pathPrefix === 'apple notes/') {
const parts = relativePath.split('/');
if (parts.length > 2) {
const subfolder = parts[1].toLowerCase().replace(/\s+/g, '-');
if (!tags.includes(subfolder)) tags.push(subfolder);
}
}
return {
title,
type: matchedRule.type,
date,
source: matchedRule.source,
tags: tags.length > 0 ? tags : undefined,
matchedRule: matchedRule.pathPrefix || '(default)',
};
}
/**
* Generate a YAML frontmatter block from inferred fields.
* Returns the `---\n...\n---\n` string to prepend to content.
*/
export function serializeFrontmatter(fm: InferredFrontmatter): string {
if (fm.skipped) return '';
const lines: string[] = ['---'];
// Title — quote if it contains special YAML chars
const needsQuote = /[:"'#\[\]{}|>&*!?,]/.test(fm.title);
lines.push(`title: ${needsQuote ? JSON.stringify(fm.title) : fm.title}`);
lines.push(`type: ${fm.type}`);
if (fm.date) {
lines.push(`date: "${fm.date}"`);
}
if (fm.source) {
lines.push(`source: ${fm.source}`);
}
if (fm.tags && fm.tags.length > 0) {
lines.push(`tags: [${fm.tags.map(t => JSON.stringify(t)).join(', ')}]`);
}
lines.push('---');
return lines.join('\n') + '\n';
}
/**
* Apply frontmatter inference to file content.
* Returns the content with frontmatter prepended, or the original content if it already has frontmatter.
*/
export function applyInference(relativePath: string, content: string): { content: string; inferred: InferredFrontmatter } {
const inferred = inferFrontmatter(relativePath, content);
if (inferred.skipped) {
return { content, inferred };
}
const fm = serializeFrontmatter(inferred);
return { content: fm + '\n' + content, inferred };
}
+16 -2
View File
@@ -339,7 +339,7 @@ export async function importFromFile(
engine: BrainEngine,
filePath: string,
relativePath: string,
opts: { noEmbed?: boolean } = {},
opts: { noEmbed?: boolean; inferFrontmatter?: boolean } = {},
): Promise<ImportResult> {
// Defense-in-depth: reject symlinks before reading content.
const lstat = lstatSync(filePath);
@@ -352,13 +352,27 @@ export async function importFromFile(
return { slug: relativePath, status: 'skipped', chunks: 0, error: `File too large (${stat.size} bytes)` };
}
const content = readFileSync(filePath, 'utf-8');
let content = readFileSync(filePath, 'utf-8');
// Route code files through the code import path
if (isCodeFilePath(relativePath)) {
return importCodeFile(engine, relativePath, content, opts);
}
// v0.22.8 — Frontmatter inference: if the file has no frontmatter and
// inference is enabled, synthesize it from the filesystem path + content.
// This turns bare markdown files into fully-typed, dated, tagged pages
// without requiring the user to manually add YAML headers.
// The inference is applied to the in-memory content only; the file on disk
// is not modified. Use `gbrain frontmatter generate --fix` to write back.
if (opts.inferFrontmatter !== false) {
const { applyInference } = await import('./frontmatter-inference.ts');
const { content: inferred, inferred: meta } = applyInference(relativePath, content);
if (!meta.skipped) {
content = inferred;
}
}
const parsed = parseMarkdown(content, relativePath);
// Enforce path-authoritative slug. parseMarkdown prefers frontmatter.slug over
+2 -2
View File
@@ -18,7 +18,7 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
import { gbrainPath } from '../config.ts';
export interface BackpressureAuditEvent {
ts: string;
@@ -54,7 +54,7 @@ export function computeAuditFilename(now: Date = new Date()): string {
export function resolveAuditDir(): string {
const override = process.env.GBRAIN_AUDIT_DIR;
if (override && override.trim().length > 0) return override;
return path.join(os.homedir(), '.gbrain', 'audit');
return gbrainPath('audit');
}
export function logBackpressureCoalesce(event: Omit<BackpressureAuditEvent, 'ts' | 'decision'>): void {
+2 -2
View File
@@ -15,7 +15,7 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
import { gbrainPath } from '../../config.ts';
export interface ShellAuditEvent {
ts: string;
@@ -53,7 +53,7 @@ export function computeAuditFilename(now: Date = new Date()): string {
export function resolveAuditDir(): string {
const override = process.env.GBRAIN_AUDIT_DIR;
if (override && override.trim().length > 0) return override;
return path.join(os.homedir(), '.gbrain', 'audit');
return gbrainPath('audit');
}
export function logShellSubmission(event: Omit<ShellAuditEvent, 'ts'>): void {
+11 -2
View File
@@ -225,8 +225,12 @@ export class MinionSupervisor {
process.on('SIGTERM', this.sigtermListener);
process.on('SIGINT', this.sigintListener);
// 4. Health monitoring.
this.healthTimer = setInterval(() => { void this.healthCheck(); }, this.opts.healthInterval);
// 4. Health monitoring. Skip when healthInterval=0 — that's the explicit
// "disable" contract documented on `--health-interval 0`. setInterval(0)
// would be a tight DB-hammering loop, not the no-op users expect.
if (this.opts.healthInterval > 0) {
this.healthTimer = setInterval(() => { void this.healthCheck(); }, this.opts.healthInterval);
}
// 5. Announce start.
this.emit('started', {
@@ -427,6 +431,11 @@ export class MinionSupervisor {
} else {
delete env.GBRAIN_ALLOW_SHELL_JOBS;
}
// Signal to the child worker that it's running under a supervisor.
// The worker's self-health-check (DB probes, stall detection) is
// redundant when the supervisor already provides these — setting
// this env var causes the worker to skip its own health timer.
env.GBRAIN_SUPERVISED = '1';
this.lastStartTime = Date.now();
+19
View File
@@ -170,6 +170,25 @@ export interface MinionWorkerOpts {
* case where all concurrency slots are wedged with zero job completions
* so the per-job check never fires. */
rssCheckInterval?: number;
/** Self-health-check interval in ms. 0 = disabled. Default: 60000 (1 minute).
* Automatically disabled when running under a supervisor (GBRAIN_SUPERVISED=1).
* Provides DB liveness probes and stall detection for bare `gbrain jobs work`
* deployments managed by external process managers (systemd, Docker, cron). */
healthCheckInterval?: number;
/** Stall detection: ms of continuous idle (waiting>0, inFlight=0, no completions)
* before emitting the first warning. Default: 300000 (5 minutes). */
stallWarnAfterMs?: number;
/** Stall detection: ms of continuous idle before emitting `'unhealthy'` with
* reason='stalled'. Default: 600000 (10 minutes). Must be > stallWarnAfterMs. */
stallExitAfterMs?: number;
/** DB liveness probe: number of consecutive failed `SELECT 1` probes before
* emitting `'unhealthy'` with reason='db_dead'. Default: 3. */
dbFailExitAfter?: number;
/** Per-probe wall-clock timeout in ms. A `SELECT 1` that hangs longer than
* this counts as a failure (fed into dbFailExitAfter). Without this, a
* hung probe would wedge the recursive setTimeout chain forever and
* silently disable the health monitor. Default: 10000 (10 seconds). */
dbProbeTimeoutMs?: number;
}
// --- Job Context (passed to handlers) ---
+209 -1
View File
@@ -20,8 +20,15 @@ import { UnrecoverableError } from './types.ts';
import { MinionQueue } from './queue.ts';
import { calculateBackoff } from './backoff.ts';
import { randomUUID } from 'crypto';
import { EventEmitter } from 'events';
import { evaluateQuietHours, type QuietHoursConfig } from './quiet-hours.ts';
/** Reason payload emitted with `'unhealthy'` when self-health-check trips.
* CLI layer (jobs.ts:work) subscribes and decides whether to call process.exit. */
export type UnhealthyReason =
| { reason: 'db_dead'; consecutiveFailures: number; message: string }
| { reason: 'stalled'; waitingCount: number; idleMinutes: number };
/**
* Read the quiet_hours JSONB column off a MinionJob, if present. The
* column was added in schema migration v12; older rows + versions of
@@ -42,7 +49,13 @@ interface InFlightJob {
promise: Promise<void>;
}
export class MinionWorker {
/** Type-safe `on('unhealthy', ...)` for callers. */
export interface MinionWorker {
on(event: 'unhealthy', listener: (info: UnhealthyReason) => void): this;
emit(event: 'unhealthy', info: UnhealthyReason): boolean;
}
export class MinionWorker extends EventEmitter {
private queue: MinionQueue;
private handlers = new Map<string, MinionHandler>();
private running = false;
@@ -67,6 +80,7 @@ export class MinionWorker {
private engine: BrainEngine,
opts?: MinionWorkerOpts & MinionQueueOpts,
) {
super();
this.queue = new MinionQueue(engine, {
maxSpawnDepth: opts?.maxSpawnDepth,
maxAttachmentBytes: opts?.maxAttachmentBytes,
@@ -81,7 +95,25 @@ export class MinionWorker {
maxRssMb: opts?.maxRssMb ?? 0,
getRss: opts?.getRss ?? (() => process.memoryUsage().rss),
rssCheckInterval: opts?.rssCheckInterval ?? 60000,
healthCheckInterval: opts?.healthCheckInterval ?? 60000,
stallWarnAfterMs: opts?.stallWarnAfterMs ?? 5 * 60_000,
stallExitAfterMs: opts?.stallExitAfterMs ?? 10 * 60_000,
dbFailExitAfter: opts?.dbFailExitAfter ?? 3,
dbProbeTimeoutMs: opts?.dbProbeTimeoutMs ?? 10_000,
};
// Stall thresholds contract: exit MUST be strictly greater than warn.
// If exit <= warn, the warn-then-exit semantics break: a single tick at
// idle > warn would set stallWarningSince and the subsequent tick at
// idle > exit could fire immediately without giving operators visibility.
// Reject misconfigurations at construction time so the failure mode is
// a loud throw on startup rather than a quiet contract violation.
if (this.opts.stallExitAfterMs <= this.opts.stallWarnAfterMs) {
throw new Error(
`MinionWorkerOpts: stallExitAfterMs (${this.opts.stallExitAfterMs}) must be > ` +
`stallWarnAfterMs (${this.opts.stallWarnAfterMs}). ` +
`The contract is "warn first, exit later" — they cannot fire on the same tick.`,
);
}
}
/** Register a handler for a job type. */
@@ -94,6 +126,28 @@ export class MinionWorker {
return Array.from(this.handlers.keys());
}
/** Emit 'unhealthy' with a no-listener fallback. The default contract is
* fail-stop: pre-EventEmitter-refactor behavior was process.exit(1) inside
* the timer; the refactor moved that responsibility to the CLI subscriber.
* But direct API consumers without a listener would see emit() become a
* no-op AND `healthExited=true` permanently disabling monitoring a
* silent regression. Solution: if no one subscribed, log and exit
* ourselves so the worker dies and the PM restarts it. Subscribers
* override this default by adding a listener before start(). */
private emitUnhealthy(info: UnhealthyReason): void {
if (this.listenerCount('unhealthy') === 0) {
const detail = info.reason === 'db_dead'
? `DB unreachable (${info.consecutiveFailures} probes): ${info.message}`
: `worker stalled (${info.waitingCount} waiting, ${info.idleMinutes}m idle)`;
console.error(
`[health] FATAL: ${detail}. No 'unhealthy' listener registered; ` +
`defaulting to process.exit(1) for process-manager restart.`,
);
process.exit(1);
}
this.emit('unhealthy', info);
}
/** Start the worker loop. Blocks until stopped. */
async start(): Promise<void> {
if (this.handlers.size === 0) {
@@ -155,6 +209,159 @@ export class MinionWorker {
}, this.opts.rssCheckInterval);
}
// Self-health-check — provides supervisor-grade monitoring for bare workers.
// Disabled when running under a supervisor (GBRAIN_SUPERVISED=1) or when
// healthCheckInterval is 0. Catches two failure modes that leave the process
// alive but non-functional:
// 1. DB connection death (Supabase/PgBouncer drops, network blip)
// 2. Worker stall (event loop alive but not claiming/completing jobs)
//
// On failure, emits an `'unhealthy'` event with a structured reason. The
// CLI layer (`src/commands/jobs.ts:work`) subscribes and decides whether to
// call process.exit. Library code never calls process.exit directly so
// MinionWorker stays embeddable in non-CLI contexts (tests, other hosts).
//
// Timer pattern: recursive setTimeout with a `running` flag, not setInterval.
// setInterval queues callbacks even when the prior is still awaiting; on a
// hung DB probe that piles up overlapping async checks racing on
// `consecutiveDbFailures`. The recursive pattern guarantees one tick at a time.
const isSupervisedChild = process.env.GBRAIN_SUPERVISED === '1';
let healthTimer: ReturnType<typeof setTimeout> | null = null;
if (!isSupervisedChild && this.opts.healthCheckInterval > 0) {
let consecutiveDbFailures = 0;
let lastKnownCompleted = this.jobsCompleted;
let lastCompletionTime = Date.now();
let stallWarningSince: number | null = null;
let healthRunning = false;
let healthExited = false;
// Race executeRaw against a wall-clock deadline. A hung connection
// (network-partitioned PgBouncer, deadlocked backend) would otherwise
// hold the await forever — the recursive setTimeout's next tick is only
// scheduled in `finally`, so a hung probe would silently disable the
// entire health monitor. The timeout treats hangs as failures and feeds
// them into `dbFailExitAfter`.
const probeWithTimeout = async (): Promise<void> => {
const ac = new AbortController();
const timeoutMs = this.opts.dbProbeTimeoutMs;
const timer = setTimeout(() => ac.abort(), timeoutMs);
try {
await Promise.race([
this.engine.executeRaw('SELECT 1'),
new Promise<never>((_, reject) => {
ac.signal.addEventListener('abort', () => {
reject(new Error(`probe timeout after ${timeoutMs}ms`));
});
}),
]);
} finally {
clearTimeout(timer);
}
};
const runHealthCheck = async (): Promise<void> => {
if (healthRunning || !this.running || healthExited) return;
healthRunning = true;
try {
// --- 1. DB liveness probe ---
try {
await probeWithTimeout();
consecutiveDbFailures = 0;
} catch (e) {
consecutiveDbFailures++;
const msg = e instanceof Error ? e.message : String(e);
console.error(
`[health] DB probe failed (${consecutiveDbFailures}/${this.opts.dbFailExitAfter}): ${msg}`,
);
if (consecutiveDbFailures >= this.opts.dbFailExitAfter) {
console.error(
`[health] DB unreachable after ${this.opts.dbFailExitAfter} consecutive probes. ` +
`Emitting 'unhealthy' for process-manager restart.`,
);
healthExited = true;
this.emitUnhealthy({
reason: 'db_dead',
consecutiveFailures: consecutiveDbFailures,
message: msg,
});
}
return; // Skip stall check when DB is flaky
}
// --- 2. Stall detection ---
if (this.jobsCompleted > lastKnownCompleted) {
lastKnownCompleted = this.jobsCompleted;
lastCompletionTime = Date.now();
stallWarningSince = null;
}
const idleMs = Date.now() - lastCompletionTime;
// Only check for stalls when no jobs are in-flight and it's been a while
if (idleMs > this.opts.stallWarnAfterMs && this.inFlight.size === 0) {
try {
// Filter by registered handler names so a worker that doesn't
// claim a particular job-name doesn't false-positive when those
// jobs accumulate in `waiting`. Only counts work THIS worker would
// actually have claimed.
const handlerNames = this.registeredNames;
const rows = handlerNames.length === 0
? [] as { cnt: string }[]
: await this.engine.executeRaw<{ cnt: string }>(
`SELECT count(*)::text AS cnt FROM minion_jobs
WHERE status = 'waiting'
AND queue = $1
AND name = ANY($2::text[])`,
[this.opts.queue, handlerNames],
);
const waiting = parseInt(rows[0]?.cnt ?? '0', 10);
const idleMinutes = Math.round(idleMs / 60_000);
if (waiting > 0) {
// Two thresholds, both measured from `lastCompletionTime` (NOT
// from when the warning fired). With defaults (warn=5min,
// exit=10min), the first warning fires at idle=5min and the
// unhealthy emit fires at idle=10min — matching the contract
// documented in MinionWorkerOpts.
if (!stallWarningSince) {
stallWarningSince = Date.now();
console.warn(
`[health] Possible stall: ${waiting} waiting job(s) for ` +
`registered handlers, 0 in-flight, ${idleMinutes}m since last completion`,
);
} else if (idleMs > this.opts.stallExitAfterMs) {
console.error(
`[health] Worker stalled for ${Math.round(this.opts.stallExitAfterMs / 60_000)}+ ` +
`minutes with ${waiting} waiting job(s). Emitting 'unhealthy' for process-manager restart.`,
);
healthExited = true;
this.emitUnhealthy({
reason: 'stalled',
waitingCount: waiting,
idleMinutes,
});
}
} else {
stallWarningSince = null; // Queue empty (for our handlers) — not stalled, just idle
}
} catch {
// DB query failed — the liveness probe above will catch persistent failures
}
} else {
stallWarningSince = null;
}
} finally {
healthRunning = false;
if (this.running && !healthExited) {
healthTimer = setTimeout(runHealthCheck, this.opts.healthCheckInterval);
}
}
};
// First tick scheduled after one interval so newly-started workers have
// a chance to do real work before the stall clock starts ticking.
healthTimer = setTimeout(runHealthCheck, this.opts.healthCheckInterval);
}
try {
while (this.running) {
// Promote delayed jobs
@@ -201,6 +408,7 @@ export class MinionWorker {
} finally {
clearInterval(stalledTimer);
if (rssTimer) clearInterval(rssTimer);
if (healthTimer) clearTimeout(healthTimer); // recursive setTimeout pattern
process.removeListener('SIGTERM', shutdown);
process.removeListener('SIGINT', shutdown);
+6 -5
View File
@@ -18,8 +18,8 @@
*/
import { appendFileSync, existsSync, mkdirSync } from 'fs';
import { homedir } from 'os';
import { dirname, join } from 'path';
import { dirname } from 'path';
import { gbrainPath } from '../config.ts';
import type { BrainEngine } from '../engine.ts';
import {
@@ -30,7 +30,7 @@ import {
} from './validators/index.ts';
import type { ValidationFinding, PageValidator } from './writer.ts';
const LINT_LOG_FILE = join(homedir(), '.gbrain', 'validator-lint.jsonl');
const getLintLogFile = () => gbrainPath('validator-lint.jsonl');
const LINT_CONFIG_KEY = 'writer.lint_on_put_page';
export interface PostWriteLintOpts {
@@ -124,7 +124,8 @@ export async function runPostWriteLint(
function writeLocalLintLog(slug: string, findings: ValidationFinding[]): void {
try {
const dir = dirname(LINT_LOG_FILE);
const lintLogFile = getLintLogFile();
const dir = dirname(lintLogFile);
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
const line = JSON.stringify({
ts: new Date().toISOString(),
@@ -133,7 +134,7 @@ function writeLocalLintLog(slug: string, findings: ValidationFinding[]): void {
warning_count: findings.filter(f => f.severity === 'warning').length,
findings: findings.slice(0, 20), // cap to prevent runaway log size
}) + '\n';
appendFileSync(LINT_LOG_FILE, line, 'utf-8');
appendFileSync(lintLogFile, line, 'utf-8');
} catch {
// Non-fatal; logging failure shouldn't break the main flow.
}
+2 -2
View File
@@ -301,7 +301,7 @@ export function resolveSlugForPath(filePath: string, repoPrefix?: string): strin
import { existsSync as _existsSync, readFileSync as _readFileSync, appendFileSync as _appendFileSync, mkdirSync as _mkdirSync } from 'fs';
import { join as _joinPath } from 'path';
import { homedir as _homedir } from 'os';
import { gbrainPath as _gbrainPath } from './config.ts';
import { createHash as _createHash } from 'crypto';
export interface SyncFailure {
@@ -402,7 +402,7 @@ export function formatCodeBreakdown(
}
function _failuresDir(): string {
return _joinPath(_homedir(), '.gbrain');
return _gbrainPath();
}
export function syncFailuresPath(): string {
+97
View File
@@ -0,0 +1,97 @@
/**
* AgentRunner registry + selection tests. Proves the harness contract is
* truly agent-agnostic via a fake-runner integration.
*/
import { describe, test, expect, beforeEach } from 'bun:test';
import {
registerAgentRunner, resolveAgentRunner, listRegisteredAgents,
_resetRegistryForTests,
type AgentRunner, type DetectResult, type InvokeOpts, type InvokeResult, type TranscriptSink,
} from '../src/core/claw-test/agent-runner.ts';
class FakeRunner implements AgentRunner {
readonly name: string;
invocations = 0;
detected: DetectResult = { available: true, binPath: '/usr/bin/fake-agent' };
constructor(name: string) { this.name = name; }
async detect(): Promise<DetectResult> { return this.detected; }
async invoke(_opts: InvokeOpts): Promise<InvokeResult> {
this.invocations++;
return { exitCode: 0, durationMs: 1 };
}
}
beforeEach(() => {
_resetRegistryForTests();
});
describe('registry', () => {
test('register + resolve roundtrips', () => {
registerAgentRunner('fake', () => new FakeRunner('fake'));
const r = resolveAgentRunner('fake');
expect(r.name).toBe('fake');
});
test('resolve unknown agent throws with helpful list', () => {
registerAgentRunner('alpha', () => new FakeRunner('alpha'));
registerAgentRunner('beta', () => new FakeRunner('beta'));
expect(() => resolveAgentRunner('gamma')).toThrow(/registered: alpha, beta/);
});
test('listRegisteredAgents returns sorted names', () => {
registerAgentRunner('zeta', () => new FakeRunner('zeta'));
registerAgentRunner('alpha', () => new FakeRunner('alpha'));
expect(listRegisteredAgents()).toEqual(['alpha', 'zeta']);
});
test('factory pattern produces independent instances', () => {
registerAgentRunner('fake', () => new FakeRunner('fake'));
const a = resolveAgentRunner('fake') as FakeRunner;
const b = resolveAgentRunner('fake') as FakeRunner;
expect(a).not.toBe(b);
});
});
describe('agent-agnosticism guard', () => {
test('a fake runner can satisfy the AgentRunner contract end-to-end', async () => {
registerAgentRunner('fake', () => new FakeRunner('fake'));
const runner = resolveAgentRunner('fake');
// The harness contract: detect → invoke. Nothing else.
const detected = await runner.detect();
expect(detected.available).toBe(true);
expect(detected.binPath).toBe('/usr/bin/fake-agent');
let written = 0;
const sink: TranscriptSink = {
write: () => { written++; },
nextOffset: () => 0,
close: async () => { /* noop */ },
};
const result = await runner.invoke({
cwd: '/tmp',
brief: 'hello',
env: {},
timeoutMs: 1000,
transcriptSink: sink,
});
expect(result.exitCode).toBe(0);
});
test('a runner reporting unavailable still satisfies the contract', async () => {
class UnavailableRunner implements AgentRunner {
name = 'gone';
async detect() { return { available: false, reason: 'not installed' } as DetectResult; }
async invoke(): Promise<InvokeResult> { throw new Error('should not be called'); }
}
registerAgentRunner('gone', () => new UnavailableRunner());
const r = resolveAgentRunner('gone');
const d = await r.detect();
expect(d.available).toBe(false);
expect(d.reason).toBe('not installed');
});
});
+165
View File
@@ -0,0 +1,165 @@
/**
* gbrain claw-test CLI dispatch tests.
*
* These tests exercise the harness's argument parsing, scenario loading,
* agent registry resolution, and friction-report path. They do NOT spawn
* real gbrain commands (no built binary in CI yet); the canonical scripted
* E2E that walks `gbrain init → import → query → extract → verify` lives
* in test/e2e/claw-test.test.ts and gates on a built binary.
*/
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import { mkdtempSync, rmSync, existsSync, readFileSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { runFriction } from '../src/commands/friction.ts';
import { listScenarios, loadScenario } from '../src/core/claw-test/scenarios.ts';
import {
registerAgentRunner, resolveAgentRunner, listRegisteredAgents,
_resetRegistryForTests,
type AgentRunner, type DetectResult, type InvokeOpts, type InvokeResult,
} from '../src/core/claw-test/agent-runner.ts';
let tmp: string;
const ORIG_HOME = process.env.GBRAIN_HOME;
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), 'claw-test-cli-'));
process.env.GBRAIN_HOME = tmp;
_resetRegistryForTests();
});
afterEach(() => {
process.env.GBRAIN_HOME = ORIG_HOME;
rmSync(tmp, { recursive: true, force: true });
});
describe('shipped scenarios are loadable', () => {
test('default fixtures root contains both v1 scenarios', () => {
delete process.env.GBRAIN_CLAW_SCENARIOS_DIR;
const names = listScenarios();
expect(names).toContain('fresh-install');
expect(names).toContain('upgrade-from-v0.18');
});
test('fresh-install has expected_phases', () => {
delete process.env.GBRAIN_CLAW_SCENARIOS_DIR;
const cfg = loadScenario('fresh-install');
expect(cfg.expectedPhases).toContain('import.files');
expect(cfg.expectedPhases).toContain('extract.links_fs');
expect(cfg.expectedPhases).toContain('doctor.db_checks');
});
test('upgrade-from-v0.18 declares from_version', () => {
delete process.env.GBRAIN_CLAW_SCENARIOS_DIR;
const cfg = loadScenario('upgrade-from-v0.18');
expect(cfg.kind).toBe('upgrade');
expect(cfg.fromVersion).toBe('0.18.0');
expect(cfg.seedRelative).toBe('seed');
});
});
describe('agent registry — fake-runner integration', () => {
test('a fake runner can be registered, resolved, and detect/invoke called', async () => {
let invokeCount = 0;
class FakeRunner implements AgentRunner {
readonly name = 'fake';
async detect(): Promise<DetectResult> { return { available: true, binPath: '/usr/bin/fake' }; }
async invoke(_opts: InvokeOpts): Promise<InvokeResult> {
invokeCount++;
return { exitCode: 0, durationMs: 1 };
}
}
registerAgentRunner('fake', () => new FakeRunner());
expect(listRegisteredAgents()).toContain('fake');
const r = resolveAgentRunner('fake');
const detected = await r.detect();
expect(detected.available).toBe(true);
const result = await r.invoke({
cwd: tmp,
brief: 'test',
env: {},
timeoutMs: 1000,
transcriptSink: { write: () => {}, nextOffset: () => 0, close: async () => {} },
});
expect(result.exitCode).toBe(0);
expect(invokeCount).toBe(1);
});
test('resolveAgentRunner with unknown name throws with registered list', () => {
registerAgentRunner('alpha', () => ({} as AgentRunner));
expect(() => resolveAgentRunner('unknown')).toThrow(/registered: alpha/);
});
});
describe('friction CLI integrates with harness run-id env', () => {
test('GBRAIN_FRICTION_RUN_ID populates harness-style run-ids', () => {
process.env.GBRAIN_FRICTION_RUN_ID = 'claw-test-20260428-fake-abcd1234';
try {
const code = runFriction(['log', '--phase', 'install', '--message', 'simulated harness write']);
expect(code).toBe(0);
const expectedFile = join(tmp, '.gbrain', 'friction', 'claw-test-20260428-fake-abcd1234.jsonl');
expect(existsSync(expectedFile)).toBe(true);
const raw = readFileSync(expectedFile, 'utf-8');
const entry = JSON.parse(raw.split('\n')[0]);
expect(entry.run_id).toBe('claw-test-20260428-fake-abcd1234');
expect(entry.message).toBe('simulated harness write');
} finally {
delete process.env.GBRAIN_FRICTION_RUN_ID;
}
});
});
describe('OpenClawRunner detection (reliable on box without openclaw)', () => {
test('detect returns unavailable when OPENCLAW_BIN missing', async () => {
const orig = process.env.OPENCLAW_BIN;
delete process.env.OPENCLAW_BIN;
try {
const { OpenClawRunner } = await import('../src/core/claw-test/runners/openclaw.ts');
const r = new OpenClawRunner();
const d = await r.detect();
// Either unavailable, or available if openclaw IS on PATH for the dev — both states are valid.
// We only assert the contract shape.
expect(typeof d.available).toBe('boolean');
if (!d.available) {
expect(typeof d.reason).toBe('string');
} else {
expect(d.binPath?.startsWith('/')).toBe(true);
}
} finally {
if (orig !== undefined) process.env.OPENCLAW_BIN = orig;
}
});
test('detect rejects relative OPENCLAW_BIN', async () => {
const orig = process.env.OPENCLAW_BIN;
process.env.OPENCLAW_BIN = 'relative/openclaw';
try {
const { OpenClawRunner } = await import('../src/core/claw-test/runners/openclaw.ts');
const r = new OpenClawRunner();
const d = await r.detect();
expect(d.available).toBe(false);
expect(d.reason).toMatch(/absolute/);
} finally {
if (orig !== undefined) process.env.OPENCLAW_BIN = orig;
else delete process.env.OPENCLAW_BIN;
}
});
test("detect rejects '..' segments in OPENCLAW_BIN", async () => {
const orig = process.env.OPENCLAW_BIN;
process.env.OPENCLAW_BIN = '/tmp/foo/../bar';
try {
const { OpenClawRunner } = await import('../src/core/claw-test/runners/openclaw.ts');
const r = new OpenClawRunner();
const d = await r.detect();
expect(d.available).toBe(false);
expect(d.reason).toMatch(/'\.\.' segments/);
} finally {
if (orig !== undefined) process.env.OPENCLAW_BIN = orig;
else delete process.env.OPENCLAW_BIN;
}
});
});
+134
View File
@@ -0,0 +1,134 @@
/**
* gbrain claw-test scripted-mode E2E.
*
* Invokes the harness via `bun run src/cli.ts` (NOT a compiled binary
* `bun build --compile` doesn't bundle PGLite's runtime assets like
* pglite.data, so a compiled gbrain can't init a fresh PGLite brain).
* Uses a tiny shim script that the harness can spawn as if it were the
* gbrain binary.
*
* Asserts:
* - exit code 0 on a clean tree
* - the friction JSONL has zero error/blocker entries
* - the harness recorded progress events for the expected phases
*
* Tagged-skip env: CLAW_TEST_SKIP_E2E=1 to opt out (e.g. when PGLite
* WASM is broken on the host the macOS 26.3 #223 bug class).
*/
import { describe, test, expect, beforeAll } from 'bun:test';
import { execFileSync, spawnSync } from 'child_process';
import { mkdirSync, existsSync, mkdtempSync, rmSync, readFileSync, readdirSync, writeFileSync, chmodSync } from 'fs';
import { tmpdir } from 'os';
import { join, resolve } from 'path';
const REPO_ROOT = resolve(import.meta.dir, '..', '..');
const BIN_CACHE = join(REPO_ROOT, 'test', '.cache');
const BIN_PATH = join(BIN_CACHE, 'gbrain.sh');
const SCENARIOS_DIR = join(REPO_ROOT, 'test', 'fixtures', 'claw-test-scenarios');
beforeAll(() => {
if (!existsSync(BIN_CACHE)) mkdirSync(BIN_CACHE, { recursive: true });
// Shim that delegates to `bun run src/cli.ts` so PGLite assets resolve from
// the source tree (bun --compile doesn't bundle them). Marked executable so
// child_process.spawn can run it directly.
const shim = `#!/bin/sh\nexec bun run "${join(REPO_ROOT, 'src', 'cli.ts')}" "$@"\n`;
writeFileSync(BIN_PATH, shim, 'utf-8');
chmodSync(BIN_PATH, 0o755);
}, 30_000);
describe('gbrain claw-test --scenario fresh-install (scripted)', () => {
test('runs end-to-end clean and produces zero error/blocker friction', () => {
const tmp = mkdtempSync(join(tmpdir(), 'claw-test-e2e-fresh-'));
try {
const result = spawnSync(BIN_PATH, ['claw-test', '--scenario', 'fresh-install', '--keep-tempdir'], {
cwd: REPO_ROOT,
env: {
...process.env,
GBRAIN_HOME: tmp,
GBRAIN_BIN_OVERRIDE: BIN_PATH,
GBRAIN_CLAW_SCENARIOS_DIR: join(REPO_ROOT, 'test', 'fixtures', 'claw-test-scenarios'),
},
encoding: 'utf-8',
timeout: 120_000,
});
if (result.status !== 0) {
console.error('STDOUT:', result.stdout);
console.error('STDERR:', result.stderr);
}
expect(result.status).toBe(0);
// Inspect the friction JSONL the harness wrote.
const frictionDir = join(tmp, '.gbrain', 'friction');
expect(existsSync(frictionDir)).toBe(true);
const files = readdirSync(frictionDir).filter(f => f.endsWith('.jsonl'));
expect(files.length).toBeGreaterThan(0);
const runFile = join(frictionDir, files[0]);
const lines = readFileSync(runFile, 'utf-8').split('\n').filter(l => l.trim());
const entries = lines.map(l => JSON.parse(l));
const blockers = entries.filter(e => e.kind === 'friction' && (e.severity === 'error' || e.severity === 'blocker'));
if (blockers.length > 0) {
console.error('unexpected friction entries:', blockers);
}
expect(blockers.length).toBe(0);
} finally {
rmSync(tmp, { recursive: true, force: true });
}
}, 180_000);
test('break path: an invented command produces an error friction entry and exits non-zero', () => {
// We do this by setting GBRAIN_BIN_OVERRIDE to a script that pretends to be gbrain
// and rejects the `import` subcommand specifically.
const tmp = mkdtempSync(join(tmpdir(), 'claw-test-e2e-break-'));
const fakeBin = join(tmp, 'fake-gbrain');
try {
// Write a shim that delegates to real gbrain but rejects 'import' to simulate breakage.
const shimContent = `#!/bin/sh\nif [ "$1" = "import" ]; then echo "fake import error" >&2; exit 17; fi\nexec "${BIN_PATH}" "$@"\n`;
const { writeFileSync, chmodSync } = require('fs');
writeFileSync(fakeBin, shimContent, 'utf-8');
chmodSync(fakeBin, 0o755);
const result = spawnSync(BIN_PATH, ['claw-test', '--scenario', 'fresh-install', '--keep-tempdir'], {
cwd: REPO_ROOT,
env: {
...process.env,
GBRAIN_HOME: tmp,
GBRAIN_BIN_OVERRIDE: fakeBin,
GBRAIN_CLAW_SCENARIOS_DIR: join(REPO_ROOT, 'test', 'fixtures', 'claw-test-scenarios'),
},
encoding: 'utf-8',
timeout: 60_000,
});
expect(result.status).not.toBe(0);
// The friction log should have an error-severity entry for the 'import' phase.
const frictionDir = join(tmp, '.gbrain', 'friction');
const files = readdirSync(frictionDir).filter(f => f.endsWith('.jsonl'));
const lines = readFileSync(join(frictionDir, files[0]), 'utf-8').split('\n').filter(l => l.trim());
const entries = lines.map(l => JSON.parse(l));
const importErrors = entries.filter(e => e.phase === 'import' && e.severity === 'error');
expect(importErrors.length).toBeGreaterThan(0);
} finally {
rmSync(tmp, { recursive: true, force: true });
}
}, 90_000);
});
describe('gbrain friction render integration', () => {
test('render produces a markdown report with the redact placeholder', () => {
const tmp = mkdtempSync(join(tmpdir(), 'claw-test-e2e-render-'));
try {
// Log a friction entry with $HOME embedded, then render --redact md
const home = process.env.HOME ?? '/tmp';
const env = { ...process.env, GBRAIN_HOME: tmp, GBRAIN_FRICTION_RUN_ID: 'render-e2e' };
execFileSync(BIN_PATH, ['friction', 'log', '--phase', 'p', '--message', `error at ${home}/.gbrain/x`], { env, encoding: 'utf-8' });
const out = execFileSync(BIN_PATH, ['friction', 'render', '--run-id', 'render-e2e'], { env, encoding: 'utf-8' });
expect(out).toContain('# Friction report');
expect(out).toContain('<HOME>');
// --redact is the default for md, so home itself should not appear.
expect(out).not.toContain(home + '/.gbrain');
} finally {
rmSync(tmp, { recursive: true, force: true });
}
}, 30_000);
});
@@ -0,0 +1,32 @@
# Claw-test brief — fresh-install
You are testing gbrain on a brand-new install. The user just ran `gbrain init` for the first time. Walk through the canonical first-day flow:
1. **Verify install:** confirm `gbrain --version` works and `gbrain doctor --json` returns a valid JSON object with a `status` field.
2. **Install skillpack:** run `gbrain skillpack install --workspace $PWD`. The workspace already has an `AGENTS.md` routing file.
3. **Import the brain:** run `gbrain import ./brain --no-embed --progress-json`. There are 3 small markdown pages already there.
4. **Query the brain:** run `gbrain query "alice"` and verify >0 results.
5. **Extract links:** run `gbrain extract --source fs --progress-json`.
6. **Verify health:** run `gbrain doctor --json`. The `status` field should be `"ok"`.
## Friction protocol
If anything is confusing, missing, surprising, or wrong, run:
```
gbrain friction log --severity {confused|error|blocker|nit} --phase <which-step> --message "<what-happened>" [--hint "<what-could-be-better>"]
```
Severity guide:
- `blocker` — couldn't proceed at all
- `error` — command failed unexpectedly
- `confused` — docs said one thing, the tool did another, or a step felt unclear
- `nit` — minor polish opportunity
If something *just worked* and was nicer than expected, log a delight too:
```
gbrain friction log --kind delight --phase <step> --message "<what-was-nice>"
```
We want to know what didn't work, not just whether commands exited zero. Be specific.
@@ -0,0 +1,15 @@
---
type: company
name: Acme Example
founded: 2024
founders:
- alice-example
---
# Acme Example
Fictional company used for claw-test fixtures. Founded 2024 by [Alice](people/alice-example).
## What they do
Acme builds an agentic-workflow product on top of [retrieval-augmented-generation](concepts/retrieval-augmented-generation). Early traction comes from a developer-tools wedge.
@@ -0,0 +1,10 @@
---
type: concept
name: Agentic Workflows
---
# Agentic Workflows
Workflows where an LLM-driven agent plans, executes, and revises a sequence of steps with minimal human supervision per step. Key constraints: cost, latency, and observability of the loop.
Companies building in this space include [acme-example](companies/acme-example).
@@ -0,0 +1,13 @@
---
type: person
name: Alice Example
x_handle: alice_example
---
# Alice Example
Alice is a fictional founder used for claw-test fixtures. She started [acme-example](companies/acme-example) in 2024.
## Background
Alice has spent 10 years in software and 2 years in AI tooling. She is exploring product-market fit for an [agentic-workflow](concepts/agentic-workflows) tool.
@@ -0,0 +1,6 @@
{
"min_pages_after_import": 3,
"min_query_results": 1,
"min_links_after_extract": 0,
"doctor_status": "ok"
}
@@ -0,0 +1,10 @@
{
"kind": "fresh-install",
"description": "Canonical 5-minute first-day flow: init → import → query → extract → verify",
"expected_phases": [
"import.files",
"extract.links_fs",
"doctor.db_checks"
],
"brain": "brain"
}
@@ -0,0 +1,25 @@
# Claw-test brief — upgrade-from-v0.18
You inherit a gbrain v0.18 brain (the harness has already replayed a seed SQL dump into a PGLite database). Walk through the upgrade path:
1. **Run `gbrain doctor --json`** first. Note any warnings or fix-hints.
2. **Run `gbrain init --pglite`** with the existing database path. The migration chain should detect the old `schema_version` and walk forward to the latest.
3. **Run `gbrain doctor --json` again.** The `status` field should be `"ok"`.
4. **Verify queries still work:** `gbrain query "alice"` should return results from the seeded brain.
## Friction protocol
If anything is confusing, missing, surprising, or wrong (especially around the migration steps — these are the highest-historical-pain regression points), run:
```
gbrain friction log --severity {confused|error|blocker|nit} --phase <which-step> --message "<what-happened>" [--hint "<what-could-be-better>"]
```
Common upgrade-flow friction patterns to watch for:
- The migration chain failed at a specific schema version (capture the version + error)
- Doctor flagged an issue but the fix-hint wasn't actionable
- `gbrain init --pglite` didn't recognize the existing brain
- Manual SQL was needed to unblock something
If something just worked, log a delight. We're tuning the upgrade flow toward zero-friction.
@@ -0,0 +1,8 @@
---
type: person
name: Alice Example
---
# Alice Example
Same brain content as the fresh-install scenario; this scenario tests upgrade flow rather than ingest. After the migration chain walks forward, agents query and the page must be findable.
@@ -0,0 +1,4 @@
{
"min_pages_after_migration": 1,
"doctor_status": "ok"
}
@@ -0,0 +1,10 @@
{
"kind": "upgrade",
"from_version": "0.18.0",
"description": "Pre-v0.18 brain shape replayed via PGLite SQL dump; migration chain walks forward to LATEST",
"expected_phases": [
"doctor.db_checks"
],
"seed": "seed",
"brain": "brain"
}
@@ -0,0 +1,24 @@
# v0.18 seed
This directory ships in v1 as **scaffolding only**`dump.sql` will contain a real v0.18-shape PGLite SQL dump in v1.1. Until then the harness treats the absent dump as a no-op seed and the upgrade scenario behaves like a fresh-install scenario for the test gate.
## Generating a real v0.18 seed
To produce an authentic seed:
1. Check out gbrain at the v0.18 release (`git checkout v0.18.0`).
2. Run `gbrain init --pglite --path /tmp/v0.18-seed.pglite` against a small fixture brain.
3. Run `gbrain import <fixture-brain>` to populate it.
4. Dump the PGLite as SQL: PGLite supports `pg_dump`-style export via the `executeRaw('SELECT * FROM pg_dump(...)')` extension or via direct file copy. If neither path works, run `pglite-tools dump /tmp/v0.18-seed.pglite > dump.sql`.
5. Place `dump.sql` here.
6. Update `expected.json::min_pages_after_migration` to match your dump's page count.
## What gets tested
When `dump.sql` exists, the harness:
- Runs `seedPgliteFromFile()` to replay the dump into a fresh `<tempdir>/.gbrain/brain.pglite`
- Then runs `gbrain init --pglite` so the migration chain detects the old schema_version and walks forward to LATEST
- Asserts `gbrain doctor --json` returns `status: 'ok'` after the walk
This is the regression gate for the upgrade-wedge bug class (#239/#243/#266/#357/#366/#374/#375/#378/#395/#396) — every gbrain release that adds a column-with-index in the embedded schema blob without a corresponding bootstrap retriggered the same wedge family.
+196
View File
@@ -0,0 +1,196 @@
/**
* Friction CLI dispatch tests. Exercises the thin command layer (each
* subcommand stays 30 LOC per the DRY contract from the eng review).
*/
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import { mkdtempSync, rmSync, readFileSync, existsSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { runFriction } from '../src/commands/friction.ts';
import { frictionFile, frictionDir } from '../src/core/friction.ts';
const ORIG_HOME = process.env.GBRAIN_HOME;
const ORIG_RUN_ID = process.env.GBRAIN_FRICTION_RUN_ID;
let tmp: string;
let stdoutLines: string[];
let stderrLines: string[];
let origStdoutWrite: typeof process.stdout.write;
let origConsoleLog: typeof console.log;
let origConsoleError: typeof console.error;
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), 'friction-cli-'));
process.env.GBRAIN_HOME = tmp;
delete process.env.GBRAIN_FRICTION_RUN_ID;
stdoutLines = [];
stderrLines = [];
origStdoutWrite = process.stdout.write.bind(process.stdout);
origConsoleLog = console.log;
origConsoleError = console.error;
process.stdout.write = ((chunk: string) => { stdoutLines.push(String(chunk)); return true; }) as any;
console.log = (...args: unknown[]) => { stdoutLines.push(args.join(' ') + '\n'); };
console.error = (...args: unknown[]) => { stderrLines.push(args.join(' ') + '\n'); };
});
afterEach(() => {
process.env.GBRAIN_HOME = ORIG_HOME;
if (ORIG_RUN_ID !== undefined) process.env.GBRAIN_FRICTION_RUN_ID = ORIG_RUN_ID;
rmSync(tmp, { recursive: true, force: true });
process.stdout.write = origStdoutWrite;
console.log = origConsoleLog;
console.error = origConsoleError;
});
describe('dispatch', () => {
test('--help returns 0 and prints subcommand list', () => {
const code = runFriction(['--help']);
expect(code).toBe(0);
expect(stdoutLines.join('')).toContain('Subcommands');
expect(stdoutLines.join('')).toContain('log');
expect(stdoutLines.join('')).toContain('render');
expect(stdoutLines.join('')).toContain('list');
expect(stdoutLines.join('')).toContain('summary');
});
test('unknown subcommand returns 2', () => {
const code = runFriction(['nonsense']);
expect(code).toBe(2);
expect(stderrLines.join('')).toContain('unknown subcommand');
});
});
describe('log subcommand', () => {
test('writes a friction entry under GBRAIN_HOME', () => {
const code = runFriction(['log', '--run-id', 'cli-1', '--phase', 'install', '--message', 'something broke', '--severity', 'error']);
expect(code).toBe(0);
const path = frictionFile('cli-1');
expect(existsSync(path)).toBe(true);
expect(path.startsWith(tmp)).toBe(true);
const raw = readFileSync(path, 'utf-8');
expect(raw).toContain('something broke');
});
test('missing --phase returns 2 with usage', () => {
const code = runFriction(['log', '--message', 'foo']);
expect(code).toBe(2);
expect(stderrLines.join('')).toContain('usage');
});
test('missing --message returns 2 with usage', () => {
const code = runFriction(['log', '--phase', 'p']);
expect(code).toBe(2);
expect(stderrLines.join('')).toContain('usage');
});
test('invalid --severity returns 2', () => {
const code = runFriction(['log', '--run-id', 'cli-2', '--phase', 'p', '--message', 'm', '--severity', 'panicking']);
expect(code).toBe(2);
expect(stderrLines.join('')).toContain('invalid --severity');
});
test('invalid --kind returns 2', () => {
const code = runFriction(['log', '--run-id', 'cli-3', '--phase', 'p', '--message', 'm', '--kind', 'bogus']);
expect(code).toBe(2);
expect(stderrLines.join('')).toContain('invalid --kind');
});
test('--kind delight is recorded', () => {
runFriction(['log', '--run-id', 'cli-4', '--phase', 'p', '--message', 'great', '--kind', 'delight']);
const raw = readFileSync(frictionFile('cli-4'), 'utf-8');
expect(raw).toContain('"kind":"delight"');
});
});
describe('render subcommand', () => {
test('renders markdown by default', () => {
runFriction(['log', '--run-id', 'cli-r', '--phase', 'install', '--message', 'beep', '--severity', 'error']);
stdoutLines.length = 0;
const code = runFriction(['render', '--run-id', 'cli-r']);
expect(code).toBe(0);
const out = stdoutLines.join('');
expect(out).toContain('# Friction report');
expect(out).toContain('## error');
});
test('--json emits parseable JSON', () => {
runFriction(['log', '--run-id', 'cli-r2', '--phase', 'p', '--message', 'beep']);
stdoutLines.length = 0;
const code = runFriction(['render', '--run-id', 'cli-r2', '--json']);
expect(code).toBe(0);
const out = stdoutLines.join('').trim();
const parsed = JSON.parse(out);
expect(parsed.run_id).toBe('cli-r2');
expect(parsed.entries.length).toBe(1);
});
test('missing run-id returns 1 with actionable error', () => {
const code = runFriction(['render', '--run-id', 'no-such-run']);
expect(code).toBe(1);
expect(stderrLines.join('')).toContain('not found');
});
});
describe('list subcommand', () => {
test('reports no runs initially', () => {
const code = runFriction(['list']);
expect(code).toBe(0);
expect(stdoutLines.join('')).toContain('no runs');
});
test('lists logged runs with counts', () => {
runFriction(['log', '--run-id', 'a', '--phase', 'p', '--message', 'm', '--severity', 'error']);
runFriction(['log', '--run-id', 'b', '--phase', 'p', '--message', 'm', '--kind', 'delight']);
stdoutLines.length = 0;
const code = runFriction(['list']);
expect(code).toBe(0);
const out = stdoutLines.join('');
expect(out).toContain('a');
expect(out).toContain('b');
});
test('--json emits parseable JSON array', () => {
runFriction(['log', '--run-id', 'jl', '--phase', 'p', '--message', 'm']);
stdoutLines.length = 0;
const code = runFriction(['list', '--json']);
expect(code).toBe(0);
const parsed = JSON.parse(stdoutLines.join('').trim());
expect(Array.isArray(parsed)).toBe(true);
expect(parsed[0].runId).toBe('jl');
});
});
describe('summary subcommand', () => {
test('renders friction + delight columns', () => {
runFriction(['log', '--run-id', 'sum-1', '--phase', 'p', '--message', 'broken thing']);
runFriction(['log', '--run-id', 'sum-1', '--phase', 'p', '--message', 'nice thing', '--kind', 'delight']);
stdoutLines.length = 0;
const code = runFriction(['summary', '--run-id', 'sum-1']);
expect(code).toBe(0);
const out = stdoutLines.join('');
expect(out).toContain('friction (1)');
expect(out).toContain('delight (1)');
expect(out).toContain('broken thing');
expect(out).toContain('nice thing');
});
});
describe('GBRAIN_FRICTION_RUN_ID fallback (D19)', () => {
test('log without --run-id uses standalone', () => {
const code = runFriction(['log', '--phase', 'p', '--message', 'fallback']);
expect(code).toBe(0);
const path = frictionFile('standalone');
expect(existsSync(path)).toBe(true);
expect(readFileSync(path, 'utf-8')).toContain('fallback');
});
test('log honors $GBRAIN_FRICTION_RUN_ID', () => {
process.env.GBRAIN_FRICTION_RUN_ID = 'env-run';
try {
runFriction(['log', '--phase', 'p', '--message', 'env']);
expect(existsSync(frictionFile('env-run'))).toBe(true);
} finally {
delete process.env.GBRAIN_FRICTION_RUN_ID;
}
});
});
+232
View File
@@ -0,0 +1,232 @@
/**
* Friction core: writer + reader + renderer + redactor.
*
* These tests are pure local-fs (no DB, no subprocess). They run under
* GBRAIN_HOME=<tmp> for hermeticity see test/gbrain-home-isolation.test.ts
* for the regression gate proving every consumer honors that env.
*/
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import { mkdtempSync, rmSync, existsSync, readFileSync, appendFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import {
logFriction, readFriction, listRuns, renderReport, renderSummary,
redactEntry, frictionFile, frictionDir, activeRunId,
type FrictionEntry,
} from '../src/core/friction.ts';
const ORIG_HOME = process.env.GBRAIN_HOME;
const ORIG_RUN_ID = process.env.GBRAIN_FRICTION_RUN_ID;
let tmp: string;
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), 'friction-test-'));
process.env.GBRAIN_HOME = tmp;
delete process.env.GBRAIN_FRICTION_RUN_ID;
});
afterEach(() => {
process.env.GBRAIN_HOME = ORIG_HOME;
if (ORIG_RUN_ID !== undefined) process.env.GBRAIN_FRICTION_RUN_ID = ORIG_RUN_ID;
rmSync(tmp, { recursive: true, force: true });
});
describe('writer', () => {
test('logFriction appends one JSONL line and roundtrips through reader', () => {
logFriction({ runId: 'run-a', phase: 'install', message: 'first', severity: 'error' });
const { entries, malformed } = readFriction('run-a');
expect(malformed).toBe(0);
expect(entries).toHaveLength(1);
expect(entries[0].message).toBe('first');
expect(entries[0].severity).toBe('error');
expect(entries[0].kind).toBe('friction');
expect(entries[0].schema_version).toBe('1');
expect(entries[0].run_id).toBe('run-a');
});
test('multiple entries append in order', () => {
logFriction({ runId: 'run-b', phase: 'p1', message: 'one', severity: 'nit' });
logFriction({ runId: 'run-b', phase: 'p2', message: 'two', severity: 'blocker' });
const { entries } = readFriction('run-b');
expect(entries.map(e => e.message)).toEqual(['one', 'two']);
});
test('long messages are truncated', () => {
const long = 'x'.repeat(5000);
logFriction({ runId: 'run-c', phase: 'p', message: long });
const { entries } = readFriction('run-c');
expect(entries[0].message.length).toBeLessThan(5000);
expect(entries[0].message.endsWith('[truncated]')).toBe(true);
});
test('kind: delight is recorded distinctly', () => {
logFriction({ runId: 'run-d', phase: 'verify', message: 'this just worked', kind: 'delight' });
const { entries } = readFriction('run-d');
expect(entries[0].kind).toBe('delight');
});
test('phase-marker entry roundtrips', () => {
logFriction({ runId: 'run-e', phase: 'extract', message: 'phase started', kind: 'phase-marker', marker: 'start' });
const { entries } = readFriction('run-e');
expect(entries[0].kind).toBe('phase-marker');
expect(entries[0].marker).toBe('start');
});
test('error envelope fields flatten in (D20)', () => {
logFriction({
runId: 'run-f',
phase: 'install',
message: 'spawn failed',
severity: 'blocker',
errorClass: 'AgentSpawnError',
errorCode: 'spawn_enoent',
docsUrl: 'https://example.test/docs',
});
const { entries } = readFriction('run-f');
expect(entries[0].class).toBe('AgentSpawnError');
expect(entries[0].code).toBe('spawn_enoent');
expect(entries[0].docs_url).toBe('https://example.test/docs');
});
test('rejects invalid run-id', () => {
expect(() => logFriction({ runId: 'has space', phase: 'p', message: 'm' })).toThrow(/invalid run-id/);
expect(() => logFriction({ runId: '../escape', phase: 'p', message: 'm' })).toThrow(/invalid run-id/);
});
});
describe('activeRunId', () => {
test('falls back to standalone when env unset (D19)', () => {
delete process.env.GBRAIN_FRICTION_RUN_ID;
expect(activeRunId()).toBe('standalone');
});
test('reads GBRAIN_FRICTION_RUN_ID', () => {
process.env.GBRAIN_FRICTION_RUN_ID = 'my-run';
try {
expect(activeRunId()).toBe('my-run');
} finally {
delete process.env.GBRAIN_FRICTION_RUN_ID;
}
});
});
describe('reader', () => {
test('skips malformed lines and counts them', () => {
logFriction({ runId: 'run-g', phase: 'p', message: 'good' });
appendFileSync(frictionFile('run-g'), 'this is not json\n', 'utf-8');
appendFileSync(frictionFile('run-g'), '{"ts":"only","kind":"friction"}\n', 'utf-8');
logFriction({ runId: 'run-g', phase: 'p', message: 'good2' });
const { entries, malformed } = readFriction('run-g');
expect(entries).toHaveLength(2);
expect(malformed).toBe(2);
});
test('throws on missing run-id', () => {
expect(() => readFriction('does-not-exist')).toThrow(/not found/);
});
});
describe('listRuns', () => {
test('lists runs sorted most-recent-first', () => {
logFriction({ runId: 'old-run', phase: 'p', message: 'a' });
// Sleep one millisecond worth via busy-wait so mtime differs reliably
const t0 = Date.now();
while (Date.now() - t0 < 10) { /* spin */ }
logFriction({ runId: 'new-run', phase: 'p', message: 'b' });
const runs = listRuns();
expect(runs.length).toBe(2);
expect(runs[0].runId).toBe('new-run');
expect(runs[1].runId).toBe('old-run');
});
test('reports per-run counts and interrupted flag', () => {
logFriction({ runId: 'run-h', phase: 'p', message: 'a', severity: 'error' });
logFriction({ runId: 'run-h', phase: 'p', message: 'b', severity: 'error' });
logFriction({ runId: 'run-h', phase: 'p', message: 'c', kind: 'delight' });
logFriction({ runId: 'run-h', phase: 'p', message: 'killed', kind: 'interrupted' });
const runs = listRuns();
const r = runs.find(x => x.runId === 'run-h')!;
expect(r.counts.friction).toBe(2);
expect(r.counts.delight).toBe(1);
expect(r.counts.interrupted).toBe(true);
expect(r.counts.bySeverity.error).toBe(2);
});
});
describe('renderer', () => {
test('markdown groups by severity then phase', () => {
logFriction({ runId: 'run-r', phase: 'install', message: 'a', severity: 'blocker' });
logFriction({ runId: 'run-r', phase: 'install', message: 'b', severity: 'error' });
logFriction({ runId: 'run-r', phase: 'verify', message: 'c', severity: 'error' });
logFriction({ runId: 'run-r', phase: 'verify', message: 'positive', kind: 'delight' });
const md = renderReport('run-r', { format: 'md', redact: false });
expect(md).toContain('# Friction report');
expect(md).toContain('## blocker');
expect(md).toContain('## error');
expect(md).toContain('### `install`');
expect(md).toContain('### `verify`');
// Blocker section comes before error section
expect(md.indexOf('## blocker')).toBeLessThan(md.indexOf('## error'));
});
test('json output is valid and includes entries', () => {
logFriction({ runId: 'run-j', phase: 'p', message: 'one' });
const out = renderReport('run-j', { format: 'json' });
const parsed = JSON.parse(out);
expect(parsed.run_id).toBe('run-j');
expect(parsed.entries).toHaveLength(1);
});
test('redact strips homedir and cwd from message + cwd field', () => {
const home = process.env.HOME ?? '';
const fakeCwd = process.cwd();
logFriction({
runId: 'run-red',
phase: 'p',
message: `error at ${home}/.gbrain/foo and ${fakeCwd}/bar.ts`,
});
const md = renderReport('run-red', { format: 'md', redact: true });
expect(md).not.toContain(home + '/.gbrain');
expect(md).toContain('<HOME>');
expect(md).toContain('<CWD>');
});
test('--no-redact path preserves homedir', () => {
const home = process.env.HOME ?? '/tmp/none';
logFriction({ runId: 'run-noredact', phase: 'p', message: `at ${home}/foo` });
const md = renderReport('run-noredact', { format: 'md', redact: false });
expect(md).toContain(home);
});
test('interrupted run shows banner', () => {
logFriction({ runId: 'run-i', phase: 'p', message: 'partial' });
logFriction({ runId: 'run-i', phase: 'p', message: 'killed', kind: 'interrupted' });
const md = renderReport('run-i', { format: 'md', redact: false });
expect(md).toContain('Run was interrupted');
});
});
describe('summary', () => {
test('two columns, friction + delight side-by-side', () => {
logFriction({ runId: 'run-s', phase: 'p', message: 'bad-thing' });
logFriction({ runId: 'run-s', phase: 'p', message: 'good-thing', kind: 'delight' });
const md = renderSummary('run-s', { format: 'md' });
expect(md).toContain('| friction (1) | delight (1) |');
expect(md).toContain('bad-thing');
expect(md).toContain('good-thing');
});
});
describe('redactEntry pure function', () => {
test('replaces homedir occurrences', () => {
const home = process.env.HOME ?? '/x';
const e: FrictionEntry = {
schema_version: '1', ts: 'now', run_id: 'r', phase: 'p', kind: 'friction',
message: `${home}/secret/file.txt`, source: 'claw', cwd: '/cwd', gbrain_version: 'test',
};
const r = redactEntry(e);
expect(r.message).toContain('<HOME>');
expect(r.cwd).toBe('<CWD>');
});
});
+283
View File
@@ -0,0 +1,283 @@
/**
* Tests for frontmatter-inference.ts the zero-friction ingest pipeline.
*
* Validates that files without frontmatter get correct type, title, date,
* source, and tags inferred from their filesystem path and content.
*/
import { describe, test, expect } from 'bun:test';
import {
inferFrontmatter,
extractDateFromFilename,
extractTitleFromFilename,
extractTitleFromHeading,
serializeFrontmatter,
applyInference,
DIRECTORY_RULES,
} from '../src/core/frontmatter-inference.ts';
// ── Date extraction ──────────────────────────────────────────────────
describe('extractDateFromFilename', () => {
test('extracts YYYY-MM-DD from date-prefixed filename', () => {
expect(extractDateFromFilename('2010-04-13 Apr 13 founders mtg.md')).toBe('2010-04-13');
});
test('extracts date with dash separator', () => {
expect(extractDateFromFilename('2024-01-30-therapy-session.md')).toBe('2024-01-30');
});
test('extracts date with underscore separator', () => {
expect(extractDateFromFilename('2023-06-15_meeting-notes.md')).toBe('2023-06-15');
});
test('returns null for no-date filename', () => {
expect(extractDateFromFilename('README.md')).toBe(null);
});
test('returns null for filename with numbers but no date', () => {
expect(extractDateFromFilename('chapter-1-intro.md')).toBe(null);
});
});
// ── Title extraction ─────────────────────────────────────────────────
describe('extractTitleFromFilename', () => {
test('strips date prefix and cleans up', () => {
expect(extractTitleFromFilename('2010-04-13 Apr 13 founders mtg.md')).toBe('Apr 13 founders mtg');
});
test('strips YYYY-MM-DD- prefix', () => {
expect(extractTitleFromFilename('2024-01-30-therapy-session.md')).toBe('Therapy Session');
});
test('handles filename without date', () => {
expect(extractTitleFromFilename('cognitive-distortions.md')).toBe('Cognitive Distortions');
});
test('preserves mixed case', () => {
expect(extractTitleFromFilename('YC presidency.md')).toBe('YC presidency');
});
test('returns Untitled for empty result', () => {
expect(extractTitleFromFilename('.md')).toBe('Untitled');
});
});
describe('extractTitleFromHeading', () => {
test('extracts first # heading', () => {
expect(extractTitleFromHeading('# Dhravya Shah\n\n> Founder of Supermemory')).toBe('Dhravya Shah');
});
test('ignores ## headings', () => {
expect(extractTitleFromHeading('Some text\n## Not this\n# This one')).toBe('This one');
});
test('returns null when no heading found', () => {
expect(extractTitleFromHeading('Just some text\nwithout headings')).toBe(null);
});
test('looks within first 20 lines only', () => {
const lines = Array(25).fill('text').join('\n') + '\n# Too Late';
expect(extractTitleFromHeading(lines)).toBe(null);
});
});
// ── Core inference ───────────────────────────────────────────────────
describe('inferFrontmatter', () => {
test('skips files that already have frontmatter', () => {
const result = inferFrontmatter('people/alice.md', '---\ntitle: Alice\n---\n# Alice');
expect(result.skipped).toBe(true);
});
test('Apple Notes: infers type, date, title, source', () => {
const result = inferFrontmatter(
'Apple Notes/2010-04-13 Apr 13 founders mtg.md',
'<span style="color:#000ff;">Top priority</span>',
);
expect(result.type).toBe('apple-note');
expect(result.date).toBe('2010-04-13');
expect(result.title).toBe('Apr 13 founders mtg');
expect(result.source).toBe('apple-notes');
});
test('Apple Notes/YC: adds yc tag', () => {
const result = inferFrontmatter(
'Apple Notes/YC/2022-08-04 Project 1783Y.md',
'Some content',
);
expect(result.type).toBe('apple-note');
expect(result.tags).toContain('yc');
expect(result.date).toBe('2022-08-04');
});
test('Apple Notes/Politics: adds politics tag', () => {
const result = inferFrontmatter(
'Apple Notes/Politics/2023-11-15 DA race notes.md',
'Some content',
);
expect(result.tags).toContain('politics');
});
test('people/ directory: type person, title from heading', () => {
const result = inferFrontmatter(
'people/dhravya-shah.md',
'# Dhravya Shah\n\n> Founder of Supermemory',
);
expect(result.type).toBe('person');
expect(result.title).toBe('Dhravya Shah');
});
test('people/ directory: falls back to filename when no heading', () => {
const result = inferFrontmatter(
'people/john-doe.md',
'Some text without a heading',
);
expect(result.type).toBe('person');
expect(result.title).toBe('John Doe');
});
test('personal/therapy: infers therapy-session type with date', () => {
const result = inferFrontmatter(
'personal/therapy/jan/2024-01-30.md',
'Session notes...',
);
expect(result.type).toBe('therapy-session');
expect(result.date).toBe('2024-01-30');
expect(result.source).toBe('therapy');
});
test('personal/reflections: infers reflection type, title from heading', () => {
const result = inferFrontmatter(
'personal/reflections/cognitive-distortions.md',
'# Cognitive Distortions\n\nA list of common...',
);
expect(result.type).toBe('reflection');
expect(result.title).toBe('Cognitive Distortions');
});
test('writing/essays: infers essay type', () => {
const result = inferFrontmatter(
'writing/essays/2024-03-15-on-being-remembered.md',
'# On Being Remembered Forever\n\nSome thoughts...',
);
expect(result.type).toBe('essay');
expect(result.title).toBe('On Being Remembered Forever');
expect(result.date).toBe('2024-03-15');
});
test('daily/calendar: infers calendar-index type', () => {
const result = inferFrontmatter(
'daily/calendar/2026-01-15-yc-office-hours.md',
'# Calendar Index\nSome calendar data',
);
expect(result.type).toBe('calendar-index');
expect(result.source).toBe('calendar');
});
test('companies/ directory: type company', () => {
const result = inferFrontmatter(
'companies/stripe.md',
'# Stripe\n\n> Online payments infrastructure',
);
expect(result.type).toBe('company');
expect(result.title).toBe('Stripe');
});
test('unknown directory: defaults to note type with heading title', () => {
const result = inferFrontmatter(
'random/some-file.md',
'# My Random Notes\n\nStuff here',
);
expect(result.type).toBe('note');
expect(result.title).toBe('My Random Notes');
});
test('handles empty content', () => {
const result = inferFrontmatter('notes/empty.md', '');
expect(result.type).toBe('note');
expect(result.title).toBe('Empty');
});
});
// ── Serialization ────────────────────────────────────────────────────
describe('serializeFrontmatter', () => {
test('generates valid YAML frontmatter', () => {
const fm = serializeFrontmatter({
title: 'Apr 13 founders mtg',
type: 'apple-note',
date: '2010-04-13',
source: 'apple-notes',
tags: ['yc'],
});
expect(fm).toContain('---');
expect(fm).toContain('title: Apr 13 founders mtg');
expect(fm).toContain('type: apple-note');
expect(fm).toContain('date: "2010-04-13"');
expect(fm).toContain('source: apple-notes');
expect(fm).toContain('tags: ["yc"]');
});
test('quotes title with special chars', () => {
const fm = serializeFrontmatter({
title: 'What\'s the deal: a "primer"',
type: 'note',
});
expect(fm).toContain('title: "What\'s the deal: a \\"primer\\""');
});
test('returns empty string for skipped files', () => {
expect(serializeFrontmatter({ title: '', type: '', skipped: true })).toBe('');
});
test('omits optional fields when absent', () => {
const fm = serializeFrontmatter({ title: 'Test', type: 'note' });
expect(fm).not.toContain('date');
expect(fm).not.toContain('source');
expect(fm).not.toContain('tags');
});
});
// ── Integration ──────────────────────────────────────────────────────
describe('applyInference', () => {
test('prepends frontmatter to content without it', () => {
const { content, inferred } = applyInference(
'people/alice-smith.md',
'# Alice Smith\n\n> Founder of FooBar',
);
expect(content).toMatch(/^---\n/);
expect(content).toContain('type: person');
expect(content).toContain('title: Alice Smith');
expect(content).toContain('# Alice Smith');
expect(inferred.skipped).toBeUndefined();
});
test('returns original content for files with frontmatter', () => {
const original = '---\ntitle: Bob\n---\n# Bob';
const { content, inferred } = applyInference('people/bob.md', original);
expect(content).toBe(original);
expect(inferred.skipped).toBe(true);
});
});
// ── Rules coverage ───────────────────────────────────────────────────
describe('DIRECTORY_RULES', () => {
test('has a catch-all rule with empty prefix', () => {
const catchAll = DIRECTORY_RULES.find(r => r.pathPrefix === '');
expect(catchAll).toBeDefined();
expect(catchAll!.type).toBe('note');
});
test('Apple Notes rules are more specific than the catch-all', () => {
const appleRules = DIRECTORY_RULES.filter(r => r.pathPrefix.startsWith('apple notes/'));
expect(appleRules.length).toBeGreaterThan(1); // subfolder rules + catch-all
// Subfolder rules should come before the generic apple notes/ rule
const ycIdx = DIRECTORY_RULES.findIndex(r => r.pathPrefix === 'apple notes/yc/');
const genericIdx = DIRECTORY_RULES.findIndex(r => r.pathPrefix === 'apple notes/');
expect(ycIdx).toBeLessThan(genericIdx);
});
});
+141
View File
@@ -0,0 +1,141 @@
/**
* Hermeticity test: every site that writes under `~/.gbrain` must honor
* `GBRAIN_HOME=<tmp>` and write under `<tmp>/.gbrain` instead of the developer's
* real home.
*
* Why this exists: `src/core/config.ts::configDir()` already supports
* `GBRAIN_HOME` as a parent-dir override (returns `<override>/.gbrain`), but
* historically many call sites built paths from `os.homedir()` directly,
* bypassing the override. The hermeticity migration migrated every write-side
* caller to `gbrainPath(...)`. This test is the regression gate.
*
* Scope: write-isolation only. Read-side host detection in
* `src/commands/init.ts` (reading `~/.claude`, `~/.openclaw`, etc. for module
* fingerprinting) is the documented v1 caveat and is NOT asserted here.
*/
import { describe, test, expect } from 'bun:test';
import { mkdtempSync, existsSync, readdirSync, statSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
// Save original env so we don't leak between tests.
const ORIG_GBRAIN_HOME = process.env.GBRAIN_HOME;
function fresh(): string {
return mkdtempSync(join(tmpdir(), 'gbrain-home-isolation-'));
}
describe('GBRAIN_HOME write-side isolation', () => {
test('configDir() returns <GBRAIN_HOME>/.gbrain when override is set', async () => {
const tmp = fresh();
process.env.GBRAIN_HOME = tmp;
try {
const { configDir, gbrainPath } = await import('../src/core/config.ts');
expect(configDir()).toBe(join(tmp, '.gbrain'));
expect(gbrainPath('foo', 'bar.json')).toBe(join(tmp, '.gbrain', 'foo', 'bar.json'));
} finally {
process.env.GBRAIN_HOME = ORIG_GBRAIN_HOME;
rmSync(tmp, { recursive: true, force: true });
}
});
test('configDir() falls back to homedir when GBRAIN_HOME unset', async () => {
delete process.env.GBRAIN_HOME;
try {
const { configDir } = await import('../src/core/config.ts');
const result = configDir();
// Should NOT contain the test tmpdir; should resolve to a real homedir path.
expect(result.endsWith('.gbrain')).toBe(true);
expect(result.startsWith('/tmp/')).toBe(false);
} finally {
if (ORIG_GBRAIN_HOME !== undefined) process.env.GBRAIN_HOME = ORIG_GBRAIN_HOME;
}
});
test('rejects relative GBRAIN_HOME', async () => {
process.env.GBRAIN_HOME = 'relative/path';
try {
const { configDir } = await import('../src/core/config.ts');
expect(() => configDir()).toThrow(/absolute path/);
} finally {
process.env.GBRAIN_HOME = ORIG_GBRAIN_HOME;
}
});
test("rejects GBRAIN_HOME containing '..' segments", async () => {
process.env.GBRAIN_HOME = '/tmp/foo/../bar';
try {
const { configDir } = await import('../src/core/config.ts');
expect(() => configDir()).toThrow(/'\.\.' segments/);
} finally {
process.env.GBRAIN_HOME = ORIG_GBRAIN_HOME;
}
});
test('saveConfig/loadConfig honor GBRAIN_HOME', async () => {
const tmp = fresh();
process.env.GBRAIN_HOME = tmp;
try {
const { saveConfig, loadConfig } = await import('../src/core/config.ts');
const cfg = { engine: 'pglite' as const, database_path: join(tmp, '.gbrain', 'brain.pglite') };
saveConfig(cfg);
// Config file should exist under the override, NOT under real ~/.gbrain.
expect(existsSync(join(tmp, '.gbrain', 'config.json'))).toBe(true);
// Round-trip: loadConfig() finds it back via the override.
const loaded = loadConfig();
expect(loaded?.engine).toBe('pglite');
expect(loaded?.database_path).toBe(cfg.database_path);
} finally {
process.env.GBRAIN_HOME = ORIG_GBRAIN_HOME;
rmSync(tmp, { recursive: true, force: true });
}
});
test('integrity, sync-failures, integrations heartbeat resolve under GBRAIN_HOME', async () => {
const tmp = fresh();
process.env.GBRAIN_HOME = tmp;
try {
const { gbrainPath } = await import('../src/core/config.ts');
// Spot-check a representative set of paths used across the migrated sites.
const paths = [
gbrainPath('integrity-review.md'), // src/commands/integrity.ts
gbrainPath('sync-failures.jsonl'), // src/core/sync.ts
gbrainPath('integrations', 'recipe-x'), // src/commands/integrations.ts
gbrainPath('migrate-manifest.json'), // src/commands/migrate-engine.ts
gbrainPath('import-checkpoint.json'), // src/commands/import.ts
gbrainPath('migrations', 'v0_13_1-rollback.jsonl'), // src/commands/migrations/v0_13_1.ts
gbrainPath('migrations', 'pending-host-work.jsonl'), // src/commands/migrations/v0_14_0.ts
gbrainPath('audit'), // shell-audit / backpressure-audit
gbrainPath('cycle.lock'), // src/core/cycle.ts
gbrainPath('fail-improve'), // src/core/fail-improve.ts
gbrainPath('validator-lint.jsonl'), // src/core/output/post-write.ts
gbrainPath('brain.pglite'), // init pglite default
];
for (const p of paths) {
expect(p.startsWith(join(tmp, '.gbrain'))).toBe(true);
}
} finally {
process.env.GBRAIN_HOME = ORIG_GBRAIN_HOME;
rmSync(tmp, { recursive: true, force: true });
}
});
test('GBRAIN_AUDIT_DIR override still wins over GBRAIN_HOME', async () => {
const tmp = fresh();
const auditTmp = fresh();
process.env.GBRAIN_HOME = tmp;
process.env.GBRAIN_AUDIT_DIR = auditTmp;
try {
const { resolveAuditDir } = await import('../src/core/minions/handlers/shell-audit.ts');
// Per the docstring: GBRAIN_AUDIT_DIR is the explicit override and wins.
expect(resolveAuditDir()).toBe(auditTmp);
} finally {
process.env.GBRAIN_HOME = ORIG_GBRAIN_HOME;
delete process.env.GBRAIN_AUDIT_DIR;
rmSync(tmp, { recursive: true, force: true });
rmSync(auditTmp, { recursive: true, force: true });
}
});
});
+5 -4
View File
@@ -16,16 +16,17 @@ import { join } from 'path';
import { tmpdir } from 'os';
let tmpHome: string;
const originalHome = process.env.HOME;
const originalGbrainHome = process.env.GBRAIN_HOME;
beforeEach(() => {
tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-v0_14_0-'));
process.env.HOME = tmpHome;
// GBRAIN_HOME is the parent dir; configDir() appends '.gbrain' itself.
process.env.GBRAIN_HOME = tmpHome;
});
afterEach(() => {
if (originalHome) process.env.HOME = originalHome;
else delete process.env.HOME;
if (originalGbrainHome !== undefined) process.env.GBRAIN_HOME = originalGbrainHome;
else delete process.env.GBRAIN_HOME;
try { rmSync(tmpHome, { recursive: true, force: true }); } catch { /* ignore */ }
});
+376
View File
@@ -2306,3 +2306,379 @@ describe('checkAborted (v0.20.5 cycle signal)', () => {
}).toThrow('aborted between phases: timeout');
});
});
// --- v0.22.14: Self-health-check for bare workers ---
describe('MinionWorker: self-health-check', () => {
test('health check is active when GBRAIN_SUPERVISED is not set', async () => {
// Save and clear the env var
const saved = process.env.GBRAIN_SUPERVISED;
delete process.env.GBRAIN_SUPERVISED;
try {
const worker = new MinionWorker(engine, {
queue: 'default',
concurrency: 1,
healthCheckInterval: 100, // fast for testing
pollInterval: 50,
stalledInterval: 10_000,
maxRssMb: 0,
});
worker.register('noop', async () => {});
await queue.add('noop', {});
const startPromise = worker.start();
// Let the health check fire at least once (100ms interval)
await new Promise(r => setTimeout(r, 300));
worker.stop();
await startPromise;
// Worker should have processed the job despite health check running
const completed = await queue.getJobs({ status: 'completed' });
expect(completed.length).toBeGreaterThanOrEqual(1);
} finally {
if (saved !== undefined) process.env.GBRAIN_SUPERVISED = saved;
else delete process.env.GBRAIN_SUPERVISED;
}
}, 10_000);
test('health check is skipped when GBRAIN_SUPERVISED=1', async () => {
const saved = process.env.GBRAIN_SUPERVISED;
process.env.GBRAIN_SUPERVISED = '1';
try {
const worker = new MinionWorker(engine, {
queue: 'default',
concurrency: 1,
healthCheckInterval: 100,
pollInterval: 50,
stalledInterval: 10_000,
maxRssMb: 0,
});
worker.register('noop', async () => {});
await queue.add('noop', {});
const startPromise = worker.start();
await new Promise(r => setTimeout(r, 300));
worker.stop();
await startPromise;
// Worker should still process jobs fine
const completed = await queue.getJobs({ status: 'completed' });
expect(completed.length).toBeGreaterThanOrEqual(1);
} finally {
if (saved !== undefined) process.env.GBRAIN_SUPERVISED = saved;
else delete process.env.GBRAIN_SUPERVISED;
}
}, 10_000);
test('healthCheckInterval=0 disables health check', async () => {
delete process.env.GBRAIN_SUPERVISED;
const worker = new MinionWorker(engine, {
queue: 'default',
concurrency: 1,
healthCheckInterval: 0,
pollInterval: 50,
stalledInterval: 10_000,
maxRssMb: 0,
});
worker.register('noop', async () => {});
await queue.add('noop', {});
const startPromise = worker.start();
await new Promise(r => setTimeout(r, 300));
worker.stop();
await startPromise;
const completed = await queue.getJobs({ status: 'completed' });
expect(completed.length).toBeGreaterThanOrEqual(1);
}, 10_000);
});
// --- v0.22.14: Self-health-check behavior tests (D7) ---
// These tests use a Proxy around the real engine so executeRaw can be
// intercepted by SQL pattern. SELECT 1 = liveness probe; the count(*) query
// = stall detection. Anything else passes through to the underlying engine.
interface ProbeOverrides {
/** When set, executeRaw('SELECT 1') uses this function instead of pass-through.
* Returning a thrown error simulates DB death; returning [{}] simulates success. */
selectOne?: () => Promise<unknown>;
/** When set, executeRaw of the stall-detection count(*) query returns this. */
countWaiting?: (handlers: string[]) => number;
/** Captures the last SQL string that matched the stall-count regex. Tests
* use this to assert the production SQL still contains `name = ANY(...)`
* so a future refactor that drops the predicate is caught. */
capturedStallSql?: { sql: string | null };
}
function makeProbeEngine(overrides: ProbeOverrides) {
return new Proxy(engine, {
get(target, prop, receiver) {
if (prop === 'executeRaw') {
return async (sql: string, params?: unknown[]): Promise<unknown[]> => {
if (overrides.selectOne && /^\s*SELECT\s+1\s*$/i.test(sql)) {
const r = await overrides.selectOne();
return Array.isArray(r) ? r : [r];
}
if (overrides.countWaiting && /count\(\*\).*minion_jobs.*WHERE\s+status\s*=\s*'waiting'/is.test(sql)) {
if (overrides.capturedStallSql) overrides.capturedStallSql.sql = sql;
const handlers = (params?.[1] as string[]) ?? [];
return [{ cnt: String(overrides.countWaiting(handlers)) }];
}
// Pass through to real engine for anything else (claim queries etc.)
return (target as unknown as { executeRaw: (s: string, p?: unknown[]) => Promise<unknown[]> })
.executeRaw(sql, params);
};
}
return Reflect.get(target, prop, receiver);
},
}) as unknown as PGLiteEngine;
}
describe('MinionWorker: self-health-check behavior (v0.22.14)', () => {
test('emits unhealthy{db_dead} after dbFailExitAfter consecutive DB probe failures', async () => {
delete process.env.GBRAIN_SUPERVISED;
let probeCount = 0;
const probeEngine = makeProbeEngine({
selectOne: async () => {
probeCount++;
throw new Error('connection terminated unexpectedly');
},
});
const worker = new MinionWorker(probeEngine, {
queue: 'default',
concurrency: 1,
healthCheckInterval: 30,
dbFailExitAfter: 3,
pollInterval: 50,
stalledInterval: 10_000,
maxRssMb: 0,
});
worker.register('noop', async () => {});
const events: Array<{ reason: string }> = [];
worker.on('unhealthy', (info) => { events.push(info); });
const startPromise = worker.start();
// 3 ticks at 30ms = 90ms; give extra slack.
await new Promise(r => setTimeout(r, 250));
worker.stop();
await startPromise;
expect(probeCount).toBeGreaterThanOrEqual(3);
expect(events.length).toBeGreaterThanOrEqual(1);
expect(events[0].reason).toBe('db_dead');
}, 10_000);
test('DB recovery resets the failure counter (no exit after intermittent failures)', async () => {
delete process.env.GBRAIN_SUPERVISED;
let probeCount = 0;
// Pattern: fail, fail, succeed (resets), fail, fail, then permanently succeed.
// No 3 consecutive failures, so dbFailExitAfter=3 must NOT trip.
const probeEngine = makeProbeEngine({
selectOne: async () => {
const idx = probeCount++;
if (idx === 0 || idx === 1 || idx === 3 || idx === 4) {
throw new Error('transient blip');
}
return [{ ok: 1 }];
},
});
const worker = new MinionWorker(probeEngine, {
queue: 'default',
concurrency: 1,
healthCheckInterval: 30,
dbFailExitAfter: 3,
pollInterval: 50,
stalledInterval: 10_000,
maxRssMb: 0,
});
worker.register('noop', async () => {});
const events: Array<{ reason: string }> = [];
worker.on('unhealthy', (info) => { events.push(info); });
const startPromise = worker.start();
await new Promise(r => setTimeout(r, 250));
worker.stop();
await startPromise;
// Counter should never have hit 3 consecutive — success at index 2 resets it.
const dbDeadEvents = events.filter(e => e.reason === 'db_dead');
expect(dbDeadEvents.length).toBe(0);
}, 10_000);
test('emits unhealthy{stalled} after stallExitAfterMs of continuous idle with waiting jobs', async () => {
delete process.env.GBRAIN_SUPERVISED;
const probeEngine = makeProbeEngine({
selectOne: async () => [{ ok: 1 }],
countWaiting: () => 5, // pretend 5 jobs are waiting for our handler names
});
const worker = new MinionWorker(probeEngine, {
queue: 'default',
concurrency: 1,
healthCheckInterval: 30,
stallWarnAfterMs: 50,
stallExitAfterMs: 100,
pollInterval: 50,
stalledInterval: 10_000,
maxRssMb: 0,
});
worker.register('noop', async () => {});
// Don't queue any real jobs — claim returns null, inFlight stays 0,
// jobsCompleted stays 0, idle clock advances.
const events: Array<{ reason: string; waitingCount?: number }> = [];
worker.on('unhealthy', (info) => { events.push(info); });
const startPromise = worker.start();
// Both thresholds measured from lastCompletionTime (corrected per codex r2):
// - tick @ +30ms: idle=30ms, < stallWarnAfterMs(50), no warn
// - tick @ +60ms: idle=60ms, > 50, warn fires (stallWarningSince set)
// - tick @ +90ms: idle=90ms, < stallExitAfterMs(100), no exit yet
// - tick @ +120ms: idle=120ms, > 100 → exit fires (unhealthy event)
// Wait 350ms which leaves comfortable slack for setTimeout drift.
await new Promise(r => setTimeout(r, 350));
worker.stop();
await startPromise;
const stalledEvents = events.filter(e => e.reason === 'stalled');
expect(stalledEvents.length).toBeGreaterThanOrEqual(1);
expect(stalledEvents[0].waitingCount).toBe(5);
// The idleMinutes payload should reflect total idle, not warn-since.
// With idle ~120ms at exit time, idleMinutes rounds to 0 — that's
// expected; the value is informative, not load-bearing.
}, 10_000);
test('inFlight > 0 blocks stall detection (long-running legitimate job)', async () => {
delete process.env.GBRAIN_SUPERVISED;
const probeEngine = makeProbeEngine({
selectOne: async () => [{ ok: 1 }],
countWaiting: () => 5,
});
const worker = new MinionWorker(probeEngine, {
queue: 'default',
concurrency: 1,
healthCheckInterval: 30,
stallWarnAfterMs: 50,
stallExitAfterMs: 100,
pollInterval: 50,
stalledInterval: 10_000,
maxRssMb: 0,
});
worker.register('noop', async () => {});
const events: Array<{ reason: string }> = [];
worker.on('unhealthy', (info) => { events.push(info); });
// Inject a fake in-flight entry directly. This bypasses the claim path
// (which goes through the proxy and complicates the cleanup race) and
// tests exactly what we want: the stall check's `inFlight.size === 0`
// gate when there's legitimate ongoing work.
const fakeInFlight = (worker as unknown as {
inFlight: Map<number, { lockTimer: NodeJS.Timeout; abort: AbortController; promise: Promise<void> }>
}).inFlight;
const fakeAbort = new AbortController();
const fakePromise = new Promise<void>(() => { /* never resolves */ });
const fakeTimer = setInterval(() => {}, 60_000); // dummy lock timer
fakeInFlight.set(99999, { lockTimer: fakeTimer, abort: fakeAbort, promise: fakePromise });
const startPromise = worker.start();
await new Promise(r => setTimeout(r, 350));
// Remove our fake entry before stop so the worker doesn't wait 30s for it.
clearInterval(fakeTimer);
fakeInFlight.delete(99999);
worker.stop();
await startPromise;
// No stall event should fire — inFlight.size > 0 gates the stall check.
const stalledEvents = events.filter(e => e.reason === 'stalled');
expect(stalledEvents.length).toBe(0);
}, 10_000);
test('regression (D1): waiting jobs of unregistered handler names do NOT trigger stall exit', async () => {
delete process.env.GBRAIN_SUPERVISED;
// The count(*) query is filtered by registered handler names. If handlers=['noop']
// and the queue has 5 'widget-fn' jobs, the SQL `name = ANY($2)` filter returns 0.
// The probe engine simulates this by checking handlers before returning a count;
// we ALSO capture the SQL to assert the predicate text is actually present (so a
// future refactor that silently drops `AND name = ANY(...)` is caught).
const capturedStallSql = { sql: null as string | null };
const probeEngine = makeProbeEngine({
selectOne: async () => [{ ok: 1 }],
countWaiting: (handlers) => handlers.includes('widget-fn') ? 5 : 0,
capturedStallSql,
});
const worker = new MinionWorker(probeEngine, {
queue: 'default',
concurrency: 1,
healthCheckInterval: 50,
stallWarnAfterMs: 100,
stallExitAfterMs: 200,
pollInterval: 50,
stalledInterval: 10_000,
maxRssMb: 0,
});
// Register 'noop' but pretend the queue is full of 'widget-fn' (unhandled).
worker.register('noop', async () => {});
const events: Array<{ reason: string }> = [];
worker.on('unhealthy', (info) => { events.push(info); });
const startPromise = worker.start();
// Window > stallExitAfterMs; if D1 fix wasn't applied, stall would fire.
await new Promise(r => setTimeout(r, 500));
worker.stop();
await startPromise;
// No stall event — the count for 'noop' handlers is 0, so worker is correctly idle.
const stalledEvents = events.filter(e => e.reason === 'stalled');
expect(stalledEvents.length).toBe(0);
// SQL shape assertion: the production query MUST filter by handler names.
// Without this assertion, a future change that drops the predicate would
// pass the no-event check above (the handler array would be irrelevant
// to the underlying DB but our probe just needs to return 0).
expect(capturedStallSql.sql).not.toBeNull();
expect(capturedStallSql.sql).toMatch(/name\s*=\s*ANY/i);
}, 10_000);
test('regression (R3): constructor throws when stallExitAfterMs <= stallWarnAfterMs', () => {
// The contract on MinionWorkerOpts.stallExitAfterMs says "Must be >
// stallWarnAfterMs". Without validation, an exit threshold equal to or
// less than the warn threshold made the configured exit time a lie
// (warn fires first, exit can't preempt). The constructor now throws
// loudly so misconfigurations fail at startup, not at idle-time.
expect(() => new MinionWorker(engine, {
stallWarnAfterMs: 200,
stallExitAfterMs: 100, // less than warn — invalid
})).toThrow(/stallExitAfterMs.*must be > stallWarnAfterMs/i);
expect(() => new MinionWorker(engine, {
stallWarnAfterMs: 100,
stallExitAfterMs: 100, // equal to warn — also invalid (must be strictly >)
})).toThrow(/stallExitAfterMs.*must be > stallWarnAfterMs/i);
// Sanity: defaults (5min warn / 10min exit) construct without throwing.
expect(() => new MinionWorker(engine, {})).not.toThrow();
});
});
+81
View File
@@ -0,0 +1,81 @@
/**
* progress-tail tests parse --progress-json events out of mixed stderr.
*/
import { describe, test, expect } from 'bun:test';
import { parseProgressEvents, eventsByPhase, verifyExpectedPhases } from '../src/core/claw-test/progress-tail.ts';
describe('parseProgressEvents', () => {
test('extracts JSON event lines from mixed stderr', () => {
const stderr = [
'starting up',
'{"phase":"import.files","event":"start"}',
'warning: deprecated flag X',
'{"phase":"import.files","event":"tick","done":3,"total":10}',
'random text',
'{"phase":"import.files","event":"finish"}',
].join('\n');
const events = parseProgressEvents(stderr);
expect(events).toHaveLength(3);
expect(events.map(e => e.event)).toEqual(['start', 'tick', 'finish']);
});
test('ignores malformed JSON lines silently', () => {
const stderr = [
'{"phase":"a","event":"start"}',
'{"phase":', // truncated JSON
'not json at all',
'{"phase":"b","event":"start"}',
].join('\n');
const events = parseProgressEvents(stderr);
expect(events).toHaveLength(2);
});
test('ignores objects without phase field', () => {
const stderr = [
'{"phase":"a","event":"start"}',
'{"foo":"bar"}',
'{"phase":"b","event":"start"}',
].join('\n');
const events = parseProgressEvents(stderr);
expect(events.map(e => e.phase)).toEqual(['a', 'b']);
});
});
describe('eventsByPhase', () => {
test('groups by phase name', () => {
const events = [
{ phase: 'import.files', event: 'start' },
{ phase: 'import.files', event: 'finish' },
{ phase: 'extract.links_fs', event: 'start' },
];
const grouped = eventsByPhase(events);
expect(grouped.get('import.files')).toHaveLength(2);
expect(grouped.get('extract.links_fs')).toHaveLength(1);
});
});
describe('verifyExpectedPhases', () => {
test('returns empty when all expected phases present', () => {
const events = [
{ phase: 'import.files' },
{ phase: 'extract.links_fs' },
{ phase: 'doctor.db_checks' },
];
const missing = verifyExpectedPhases(events, ['import.files', 'doctor.db_checks']);
expect(missing).toEqual([]);
});
test('returns missing phase names when some are absent', () => {
const events = [
{ phase: 'import.files' },
];
const missing = verifyExpectedPhases(events, ['import.files', 'extract.links_fs', 'doctor.db_checks']);
expect(missing).toEqual(['extract.links_fs', 'doctor.db_checks']);
});
test('returns full expected list when no events at all', () => {
const missing = verifyExpectedPhases([], ['a', 'b']);
expect(missing).toEqual(['a', 'b']);
});
});
+132
View File
@@ -0,0 +1,132 @@
/**
* Scenario loader tests proves scenario.json parsing + validation work.
*/
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { listScenarios, loadScenario, readBrief } from '../src/core/claw-test/scenarios.ts';
const ORIG_ROOT = process.env.GBRAIN_CLAW_SCENARIOS_DIR;
let root: string;
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'scenarios-'));
process.env.GBRAIN_CLAW_SCENARIOS_DIR = root;
});
afterEach(() => {
if (ORIG_ROOT !== undefined) process.env.GBRAIN_CLAW_SCENARIOS_DIR = ORIG_ROOT;
else delete process.env.GBRAIN_CLAW_SCENARIOS_DIR;
rmSync(root, { recursive: true, force: true });
});
function scaffoldScenario(name: string, scenarioJson: string, briefContent = '# Brief'): void {
const dir = join(root, name);
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, 'scenario.json'), scenarioJson);
writeFileSync(join(dir, 'BRIEF.md'), briefContent);
}
describe('listScenarios', () => {
test('returns empty when no scenarios exist', () => {
expect(listScenarios()).toEqual([]);
});
test('returns directories that contain scenario.json, sorted', () => {
scaffoldScenario('beta', '{"kind":"fresh-install","expected_phases":[]}');
scaffoldScenario('alpha', '{"kind":"fresh-install","expected_phases":[]}');
mkdirSync(join(root, 'incomplete'), { recursive: true }); // no scenario.json
expect(listScenarios()).toEqual(['alpha', 'beta']);
});
});
describe('loadScenario', () => {
test('parses a valid fresh-install scenario', () => {
scaffoldScenario('demo', JSON.stringify({
kind: 'fresh-install',
expected_phases: ['import.files', 'doctor.db_checks'],
description: 'demo',
brain: 'brain',
}));
const cfg = loadScenario('demo');
expect(cfg.name).toBe('demo');
expect(cfg.kind).toBe('fresh-install');
expect(cfg.expectedPhases).toEqual(['import.files', 'doctor.db_checks']);
expect(cfg.description).toBe('demo');
expect(cfg.brainRelative).toBe('brain');
});
test('parses an upgrade scenario with from_version + seed', () => {
scaffoldScenario('upgrade-x', JSON.stringify({
kind: 'upgrade',
from_version: '0.18.0',
expected_phases: ['doctor.db_checks'],
seed: 'seed',
}));
mkdirSync(join(root, 'upgrade-x', 'seed'), { recursive: true });
const cfg = loadScenario('upgrade-x');
expect(cfg.kind).toBe('upgrade');
expect(cfg.fromVersion).toBe('0.18.0');
expect(cfg.seedRelative).toBe('seed');
});
test('throws on missing scenario directory', () => {
expect(() => loadScenario('does-not-exist')).toThrow(/not found/);
});
test('throws on malformed JSON', () => {
scaffoldScenario('bad', 'not json {');
expect(() => loadScenario('bad')).toThrow(/malformed/);
});
test('throws on unknown kind', () => {
scaffoldScenario('weird', JSON.stringify({ kind: 'mystery', expected_phases: [] }));
expect(() => loadScenario('weird')).toThrow(/unknown kind/);
});
test('throws on non-array expected_phases', () => {
scaffoldScenario('bad-phases', JSON.stringify({ kind: 'fresh-install', expected_phases: 'oops' }));
expect(() => loadScenario('bad-phases')).toThrow(/expected_phases/);
});
test('throws when BRIEF.md missing', () => {
const dir = join(root, 'no-brief');
mkdirSync(dir);
writeFileSync(join(dir, 'scenario.json'), JSON.stringify({ kind: 'fresh-install', expected_phases: [] }));
expect(() => loadScenario('no-brief')).toThrow(/BRIEF\.md missing/);
});
});
describe('readBrief', () => {
test('returns BRIEF.md content', () => {
scaffoldScenario('reads-brief', '{"kind":"fresh-install","expected_phases":[]}', '# Hello world');
const cfg = loadScenario('reads-brief');
expect(readBrief(cfg)).toBe('# Hello world');
});
});
describe('shipped scenarios load cleanly', () => {
test('fresh-install loads from default fixtures root', () => {
delete process.env.GBRAIN_CLAW_SCENARIOS_DIR;
try {
const cfg = loadScenario('fresh-install');
expect(cfg.kind).toBe('fresh-install');
expect(cfg.expectedPhases.length).toBeGreaterThan(0);
} finally {
process.env.GBRAIN_CLAW_SCENARIOS_DIR = root;
}
});
test('upgrade-from-v0.18 loads from default fixtures root', () => {
delete process.env.GBRAIN_CLAW_SCENARIOS_DIR;
try {
const cfg = loadScenario('upgrade-from-v0.18');
expect(cfg.kind).toBe('upgrade');
expect(cfg.fromVersion).toBe('0.18.0');
} finally {
process.env.GBRAIN_CLAW_SCENARIOS_DIR = root;
}
});
});
+130
View File
@@ -0,0 +1,130 @@
/**
* seed-pglite tests exercises the SQL replay primitive that powers the
* upgrade-from-v0.18 scenario. Pure PGLite in-memory; no real DB needed.
*/
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { seedPglite, seedPgliteFromFile, _internal } from '../src/core/claw-test/seed-pglite.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
let tmp: string;
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), 'seed-'));
});
afterEach(() => {
rmSync(tmp, { recursive: true, force: true });
});
describe('splitStatements', () => {
const split = _internal.splitStatements;
test('splits on semicolons', () => {
expect(split('CREATE TABLE a(x int); INSERT INTO a VALUES (1);').length).toBe(2);
});
test('respects single-quoted strings', () => {
const sql = "INSERT INTO t VALUES ('a;b'); INSERT INTO t VALUES ('c');";
const stmts = split(sql);
expect(stmts.length).toBe(2);
expect(stmts[0]).toContain("'a;b'");
});
test('respects -- line comments', () => {
const sql = "-- a comment with ; semicolon\nCREATE TABLE x(id int);";
const stmts = split(sql);
expect(stmts.length).toBe(1);
});
test('handles escaped quotes (doubled apostrophe)', () => {
const sql = "INSERT INTO t VALUES ('it''s ok');";
const stmts = split(sql);
expect(stmts.length).toBe(1);
expect(stmts[0]).toContain("it''s ok");
});
test('returns empty list for empty input', () => {
expect(split('').length).toBe(0);
expect(split(' \n').length).toBe(0);
});
});
describe('seedPglite', () => {
test('replays a SQL dump into a fresh PGLite database', async () => {
const dbPath = join(tmp, 'brain.pglite');
const sql = `
CREATE TABLE seeded(id INT PRIMARY KEY, name TEXT);
INSERT INTO seeded(id, name) VALUES (1, 'alice');
INSERT INTO seeded(id, name) VALUES (2, 'bob');
`;
await seedPglite({ dbPath, sql });
// Re-open the seeded database and verify content survived.
const engine = new PGLiteEngine();
try {
await engine.connect({ engine: 'pglite', database_path: dbPath });
const rows: any = await (engine as any).db.query('SELECT id, name FROM seeded ORDER BY id');
expect(rows.rows).toEqual([
{ id: 1, name: 'alice' },
{ id: 2, name: 'bob' },
]);
} finally {
await engine.disconnect();
}
}, 30_000);
test('throws with a useful message when SQL is invalid', async () => {
const dbPath = join(tmp, 'bad.pglite');
const sql = 'INVALID SQL HERE;';
await expect(seedPglite({ dbPath, sql })).rejects.toThrow(/SQL execution failed/);
}, 30_000);
test('creates parent directories when needed', async () => {
const dbPath = join(tmp, 'nested', 'deeper', 'brain.pglite');
await seedPglite({ dbPath, sql: 'CREATE TABLE x(y int);' });
// No throw means the dir was created.
expect(true).toBe(true);
}, 30_000);
test('empty SQL is a no-op (just creates the .pglite)', async () => {
const dbPath = join(tmp, 'empty.pglite');
await seedPglite({ dbPath, sql: '' });
// Verify the database is openable but empty.
const engine = new PGLiteEngine();
try {
await engine.connect({ engine: 'pglite', database_path: dbPath });
const r: any = await (engine as any).db.query("SELECT COUNT(*)::int AS c FROM information_schema.tables WHERE table_schema='public'");
expect(r.rows[0].c).toBe(0);
} finally {
await engine.disconnect();
}
}, 30_000);
});
describe('seedPgliteFromFile', () => {
test('reads SQL from disk and replays', async () => {
const sqlPath = join(tmp, 'dump.sql');
const dbPath = join(tmp, 'brain.pglite');
writeFileSync(sqlPath, 'CREATE TABLE z(id int); INSERT INTO z VALUES (42);');
await seedPgliteFromFile({ dbPath, sqlPath });
const engine = new PGLiteEngine();
try {
await engine.connect({ engine: 'pglite', database_path: dbPath });
const r: any = await (engine as any).db.query('SELECT id FROM z');
expect(r.rows).toEqual([{ id: 42 }]);
} finally {
await engine.disconnect();
}
}, 30_000);
test('throws on missing SQL file', async () => {
await expect(seedPgliteFromFile({
dbPath: join(tmp, 'x.pglite'),
sqlPath: join(tmp, 'nope.sql'),
})).rejects.toThrow(/seed SQL not found/);
});
});
+73
View File
@@ -328,6 +328,79 @@ describe('MinionSupervisor', () => {
}, 15_000);
});
describe('integration: GBRAIN_SUPERVISED env var (v0.22.14)', () => {
it('sets GBRAIN_SUPERVISED=1 on spawned worker child', async () => {
const outFile = join(tmpdir(), `gbrain-sup-supervised-${process.pid}-${Date.now()}.txt`);
try { unlinkSync(outFile); } catch { /* may not exist */ }
const h = makeHarness('supervised-env', `printf '%s\n' "\${GBRAIN_SUPERVISED-UNSET}" > "$OUT_FILE" ; exit 0`);
try {
const sup = spawnSupervisor(h, {
OUT_FILE: outFile,
SUP_MAX_CRASHES: '1',
});
await sup.exited;
expect(existsSync(outFile)).toBe(true);
const childSawEnv = readFileSync(outFile, 'utf8').trim();
expect(childSawEnv).toBe('1');
} finally {
try { unlinkSync(outFile); } catch { /* noop */ }
h.cleanup();
}
}, 15_000);
});
describe('regression (R3): healthInterval=0 disables timer (v0.22.14)', () => {
// Pre-fix: supervisor unconditionally called setInterval(callback, 0),
// which schedules a tight loop on the next event-loop tick. The
// operator-facing CLI claim "Use 0 to disable" was a lie — passing 0
// produced a DB-probe loop that hammered Postgres.
//
// Post-fix: setInterval is gated on healthInterval > 0. With 0, the
// supervisor runs its supervise loop normally with the health timer
// entirely absent.
//
// Assertion strategy: spawn the supervisor with SUP_HEALTH_INTERVAL_MS=0,
// a fast worker that exits cleanly, and SUP_MAX_CRASHES=1. A working fix
// should produce a single worker spawn → exit → supervisor shutdown
// sequence. If the tight-loop bug returned, the supervisor would still
// exit (max-crashes path) but the audit trail would show the tell-tale
// signature of an extremely high health-check call rate during the brief
// window before max-crashes fires. We assert the basic completion path
// and let CI's wall-clock detect any pathological CPU spike.
it('completes a normal supervise lifecycle with healthInterval=0', async () => {
const h = makeHarness('health-interval-zero', 'exit 0');
try {
const sup = spawnSupervisor(h, {
SUP_HEALTH_INTERVAL_MS: '0',
SUP_MAX_CRASHES: '1',
});
const start = Date.now();
const { code } = await sup.exited;
const elapsedMs = Date.now() - start;
// Clean exit (max-crashes path returns 1; this is fine — we just
// want to confirm the supervisor reached its terminal state without
// hanging or runaway looping).
expect(code).toBe(1);
// Sanity: a tight loop on setInterval(0) plus the spawn-respawn
// loop would still terminate at max-crashes, but it would be
// measurably slower than a clean run because the event loop is
// saturated with health-check callbacks. Cap the upper bound at
// 10s — clean runs typically finish in 12s.
expect(elapsedMs).toBeLessThan(10_000);
} finally {
h.cleanup();
}
}, 15_000);
});
describe('integration: --max-rss spawn args (v0.21)', () => {
it('passes --max-rss 2048 to spawned worker by default', async () => {
const outFile = join(tmpdir(), `gbrain-sup-maxrss-${process.pid}-${Date.now()}.txt`);
+166
View File
@@ -0,0 +1,166 @@
/**
* Transcript capture tests async drain, byte offsets, multi-byte safety,
* spawn-with-capture happy + timeout paths.
*/
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import { mkdtempSync, rmSync, readFileSync, existsSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { createTranscriptSink, spawnWithCapture } from '../src/core/claw-test/transcript-capture.ts';
let tmp: string;
let path: string;
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), 'transcript-'));
path = join(tmp, 'transcript.jsonl');
});
afterEach(() => {
rmSync(tmp, { recursive: true, force: true });
});
describe('createTranscriptSink', () => {
test('writes events as JSONL lines with byte_offset', async () => {
const sink = createTranscriptSink(path);
sink.write({ ts: 1, channel: 'stdout', bytes: Buffer.from('hello') });
sink.write({ ts: 2, channel: 'stderr', bytes: Buffer.from('world') });
await sink.close();
const raw = readFileSync(path, 'utf-8');
const lines = raw.trim().split('\n').map(l => JSON.parse(l));
expect(lines).toHaveLength(2);
expect(lines[0].channel).toBe('stdout');
expect(lines[0].byte_offset).toBe(0);
expect(lines[1].channel).toBe('stderr');
expect(lines[1].byte_offset).toBeGreaterThan(0);
expect(Buffer.from(lines[0].bytes_b64, 'base64').toString('utf-8')).toBe('hello');
expect(Buffer.from(lines[1].bytes_b64, 'base64').toString('utf-8')).toBe('world');
});
test('preserves multi-byte UTF-8 (no chunk-boundary corruption)', async () => {
const sink = createTranscriptSink(path);
// Split a 4-byte emoji across two writes to simulate stdio chunk boundaries.
const emoji = '🌍';
const buf = Buffer.from(emoji, 'utf-8');
sink.write({ ts: 1, channel: 'stdout', bytes: buf.slice(0, 2) });
sink.write({ ts: 2, channel: 'stdout', bytes: buf.slice(2) });
await sink.close();
const lines = readFileSync(path, 'utf-8').trim().split('\n').map(l => JSON.parse(l));
const concatenated = Buffer.concat([
Buffer.from(lines[0].bytes_b64, 'base64'),
Buffer.from(lines[1].bytes_b64, 'base64'),
]).toString('utf-8');
expect(concatenated).toBe(emoji);
});
test('byte_offset is monotonic and matches the actual file position', async () => {
const sink = createTranscriptSink(path);
const before1 = sink.nextOffset();
sink.write({ ts: 1, channel: 'stdout', bytes: Buffer.from('a') });
const before2 = sink.nextOffset();
sink.write({ ts: 2, channel: 'stdout', bytes: Buffer.from('b') });
await sink.close();
expect(before1).toBe(0);
expect(before2).toBeGreaterThan(0);
// Verify the offsets recorded in lines match the actual file substring offsets.
const raw = readFileSync(path, 'utf-8');
const lines = raw.trim().split('\n').map(l => JSON.parse(l));
const expectedOffsets = [0, Buffer.byteLength(raw.split('\n')[0] + '\n')];
expect(lines[0].byte_offset).toBe(expectedOffsets[0]);
expect(lines[1].byte_offset).toBe(expectedOffsets[1]);
});
test('survives bursty writes (drain handling)', async () => {
const sink = createTranscriptSink(path);
// 256KB of payload across 256 1KB writes — exceeds default pipe buffer
const chunk = Buffer.alloc(1024, 0x61); // 'a' * 1024
for (let i = 0; i < 256; i++) {
sink.write({ ts: i, channel: 'stdout', bytes: chunk });
}
await sink.close();
const raw = readFileSync(path, 'utf-8');
const lines = raw.trim().split('\n');
expect(lines.length).toBe(256);
});
test('close is idempotent', async () => {
const sink = createTranscriptSink(path);
sink.write({ ts: 1, channel: 'stdout', bytes: Buffer.from('x') });
await sink.close();
// Second close should not throw — the writeStream's `end` won't fire 'close' a second time
// but we can call without error in our own wrapper.
// (Implementation note: we don't expose a closed flag; idempotent via stream's no-op behavior.)
expect(existsSync(path)).toBe(true);
});
});
describe('spawnWithCapture', () => {
test('captures stdout from a small command', async () => {
const sink = createTranscriptSink(path);
const result = await spawnWithCapture('/bin/sh', ['-c', 'printf hi'], {
cwd: tmp,
env: { PATH: process.env.PATH ?? '' },
timeoutMs: 5_000,
transcriptSink: sink,
});
await sink.close();
expect(result.exitCode).toBe(0);
expect(result.timedOut).toBe(false);
const raw = readFileSync(path, 'utf-8');
const captured = raw.split('\n').filter(Boolean).map(l => JSON.parse(l));
const stdoutBytes = captured.filter(e => e.channel === 'stdout')
.map(e => Buffer.from(e.bytes_b64, 'base64').toString('utf-8'))
.join('');
expect(stdoutBytes).toBe('hi');
});
test('non-zero exit propagates', async () => {
const sink = createTranscriptSink(path);
const result = await spawnWithCapture('/bin/sh', ['-c', 'exit 7'], {
cwd: tmp,
env: { PATH: process.env.PATH ?? '' },
timeoutMs: 5_000,
transcriptSink: sink,
});
await sink.close();
expect(result.exitCode).toBe(7);
expect(result.timedOut).toBe(false);
});
test('timeout fires SIGTERM/SIGKILL', async () => {
const sink = createTranscriptSink(path);
// `exec sleep` replaces sh with sleep so the child we spawn IS sleep —
// SIGTERM goes directly to it, no shell-vs-child process-group ambiguity.
// CI runners are slower than local, so the test cap is 30s with headroom
// even if SIGTERM is missed and SIGKILL has to run after the 5s grace.
const result = await spawnWithCapture('/bin/sh', ['-c', 'exec sleep 30'], {
cwd: tmp,
env: { PATH: process.env.PATH ?? '' },
timeoutMs: 200,
transcriptSink: sink,
});
await sink.close();
expect(result.timedOut).toBe(true);
expect(result.exitCode).not.toBe(0);
}, 30_000);
test('rejects when the binary does not exist', async () => {
const sink = createTranscriptSink(path);
await expect(
spawnWithCapture('/no/such/binary', [], {
cwd: tmp,
env: { PATH: process.env.PATH ?? '' },
timeoutMs: 1_000,
transcriptSink: sink,
})
).rejects.toThrow();
await sink.close();
});
});