Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.45.19.0 chore(test): consolidate the PTY layer — delete dead harness, real-PTY init picker test (#4139)
Garry Tan1a06fc100aa9
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 9bf7299b20..d7125bdca7 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.45.18.0 -->+<!-- gbrain-runbook-stamp: 0.45.19.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 533b8c6409..3978d8791a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,22 @@All notable changes to GBrain will be documented in this file.+## [0.45.19.0] - 2026-08-15++**The interactive `gbrain init` pickers are now tested on a real terminal — and the repo carries one PTY layer instead of two.** The first thing every new user touches (the embedding provider picker and the search-mode picker) previously had no true-TTY coverage; the comments that claimed otherwise pointed at a harness nothing ever called.++### Added+- A real-PTY test for the interactive init flow (`test/init-picker-pty.serial.test.ts`). It drives both pickers under a true pseudo-terminal, proves typed input actually lands (non-default selections plus bounded response times, so dead input can never pass through the pickers' silent defaults), covers the Ctrl-D/EOF fallback, and runs in the required serial CI lane. Fully hermetic: temp-root home, no provider keys visible, child process reaped even on failed assertions.++### Removed+- The unused second PTY harness (`test/helpers/cli-pty-runner.ts` plus its self-test, ~657 lines). Its spawn path never gained a caller across ~20 minor versions. The real-terminal layer is consolidated on `test/helpers/tty-harness.ts` (Bun's built-in `terminal:` spawn — no native modules).++### Fixed+- Three test-file comments that claimed interactive-picker coverage existed where it didn't — two deferred to each other in a circle, one described a piped-stdin test as PTY-based. All three now point at the real coverage.++### Changed+- `docs/TESTING.md` gains a four-tier decision table for TTY and interactive-CLI testing (injected `isTTY` → piped stdin → real-PTY serial test → DX-exploration instrument), including the rule that CI-required interactive tests live in the serial lane. `docs/architecture/KEY_FILES.md` now describes the surviving harness accurately, and related project docs and the stale shard-weight entry were trued up to match.+## [0.45.18.0] - 2026-08-15**Today's agent spend now reads correctly at every hour, in every timezone.** The admin spend endpoint computed "today" against a naive timestamp that each database session reinterpreted in its own timezone — on any non-UTC session (a PGLite brain following the host clock, a timezone-configured Postgres role), the day boundary shifted by the offset and every evening's spend silently underreported as 0. The boundary is now a UTC instant, independent of session timezone, pinned by a regression test that exercises sessions 12 hours either side of UTC at any wall-clock hour.diff --git a/TODOS.md b/TODOS.mdindex 19482b6a52..a5d95d69cd 100644--- a/TODOS.md+++ b/TODOS.md@@ -4267,7 +4267,7 @@ purpose; needs baseline-governance care per the BrainBench gate rules.### 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.+**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 so live-mode transcripts capture the full agent UX. Do NOT add node-pty for this: Bun's built-in `terminal:` spawn option (Bun 1.3.10+, already pinned in engines) is the dependency-free path, proven by `test/helpers/tty-harness.ts` — reuse `launchTty` or its spawn shape.**Why:** Faithful transcripts make the friction → reasoning link more useful. v1 accepts that some agent UI is lost.@@ -4275,6 +4275,28 @@ purpose; needs baseline-governance care per the BrainBench gate rules.---+### Non-tier-1 e2e files run in no required CI lane+**Priority:** P2++**What:** Unit shards exclude `test/e2e/*` (`scripts/test-shard.sh`), and `.github/workflows/e2e.yml` runs only explicitly named files (a handful across its jobs — e.g. `test/e2e/mechanical.test.ts`, `test/e2e/mcp.test.ts`, the jsonb-parity pair); there is no glob. Every other `test/e2e/*.test.ts` — including PGLite-only files that need no `DATABASE_URL`, like `init-fresh-pglite.test.ts` — executes only when someone runs `bun run test:e2e` by hand. Decide per file: wire into a required workflow, re-home PGLite-only files to the serial lane (the pattern `test/init-picker-pty.serial.test.ts` uses), or explicitly document them as manual-only.++**Why:** Tests that never run in required CI are silent coverage loss — they rot without failing. Surfaced by the TTY-harness cleanup review when the new PTY picker test almost landed in the same dead lane.++**Effort:** S-M (CC ~30-60m for the audit + re-homing; workflow wiring adds CI-minutes cost per file).++---++### Ctrl-D during `gbrain init` stalls 60s at the next prompt (readLineSafe does not latch EOF)+**Priority:** P2++**What:** Pressing Ctrl-D at the interactive provider picker is detected immediately (keyless fallback in ~200ms), but Bun's stdin never yields another line after EOF while `isTTY` stays true — so the SUBSEQUENT search-mode picker sits its full 60s `readLineSafe` fallback before init completes (probed under a real PTY: keyless notice at 0.2s, mode prompt rendered at 1.2s, exit at 61.1s). Fix: `readLineSafe` (src/commands/init.ts) should latch EOF — once stdin has ended, later calls return their default immediately instead of waiting out the timer. Regression test: extend the EOF case in `test/init-picker-pty.serial.test.ts` to run init to completion and assert exit well under the fallback window (the case currently closes early on purpose to keep the 60s stall out of required CI — see the comment there).++**Why:** A user who hits Ctrl-D at the first prompt stares at a frozen screen for a full minute before init finishes. Cross-model adversarial review finding (Codex), confirmed by a real-PTY probe.++**Effort:** S (CC ~20m: EOF latch + regression-test extension).++---+### Read-side host-isolation (`$GBRAIN_HOST_HOME`)**Priority:** P3diff --git a/VERSION b/VERSIONindex 1beb3028af..b370446273 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.45.18.0\ No newline at end of file+0.45.19.0diff --git a/docs/TESTING.md b/docs/TESTING.mdindex ef8139305c..9f0b6b832e 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -136,6 +136,28 @@ Triage rule: a `warn-pass` EXIT-HANG line in `.context/test-summary.txt` is NOT- `tests/heavy/*.sh` → ops-shape shell scripts. Cost minutes per run; NOT in default `bun test`. Run via `bun run test:heavy` or scheduled nightly via `.github/workflows/heavy-tests.yml`. Examples: pg_upgrade matrix (boot legacy brain → walk to head), RSS budget gate (measure peak worker RSS vs committed baseline), read-latency-under-sync (p50/p95/p99 under concurrent writer load), sync lock regression (N concurrent syncs assert 1 winner + N-1 lock-busy + zero leaked `gbrain_cycle_locks` rows). See `tests/heavy/README.md` for when to add a script here vs `*.slow.test.ts`. Files prefixed with `_` (e.g. `tests/heavy/_build_legacy_fixtures.sh`) are helpers/libs invoked by sibling tests — the runner skips them.- `test/fuzz/*.test.ts` → property-based fuzz harness. Pure-validator targets in `pure-validators.test.ts` are guarded by `scripts/check-fuzz-purity.sh` (in `bun run verify`), which `bun build --target=bun` bundles each target and greps the resulting bundle for banned transitive imports (`node:fs`, `node:child_process`, engine modules). Anything that fails the guard moves to `mixed-validators.test.ts` (still property-tested, but no purity guarantee) or `filesystem-validators.test.ts` (fs-backed, uses temp dirs). Fuzz tests run in the default `bun test` loop because they're fast (~3s for ~12 properties × 1000 runs each).+### TTY and interactive-CLI testing++Four escalating tools; reach for the cheapest one that answers the question:++| Question | Tool | Example |+|---|---|---|+| Does the TTY/non-TTY branch logic pick right? | Inject `isTTY` into the pure function — no subprocess | `test/init-provider-picker.test.ts`, `test/jobs-watch-mode.test.ts` |+| Does the real CLI behave right when stdin is NOT a terminal? | Spawn the CLI with piped/ignored stdio | `test/cli-stdin-hang.test.ts` (fast loop); `test/e2e/init-fresh-pglite.test.ts` (manual `test:e2e` lane — see the TODOS e2e CI-lane entry) |+| Does the real CLI render menus and read typed input under a REAL terminal? | `launchTty` from `test/helpers/tty-harness.ts` in a `*.serial.test.ts` file | `test/init-picker-pty.serial.test.ts` |+| How does the install FEEL (stalls, copy, silence windows)? | `scripts/dx-explore.ts` — instrument, not a test; nothing asserts | transcripts under `.context/dx-runs/` (see `docs/guides/bootstrap.md`) |++Real-PTY test rules: put the file in the serial lane (`*.serial.test.ts` — that+lane runs in required CI; a new `test/e2e/*` file does NOT, since unit shards+exclude the directory and the e2e workflow runs only explicitly named files,+no glob);+assert NON-default picker values (bare Enter and each prompt's 60s+`readLineSafe` timeout both resolve to the default, so a defaults-asserting+test passes with dead input); always `await session.close()` in a `finally`+(only `close()` clears the harness wall timer); and point `HOME` plus+`GBRAIN_HOME` at a temp root with pass-through auth keys stripped via+`dropEnv` so picker state is machine-independent.+### Skills-manifest freshness guard`skills/skills.lock.json` is a committed sha256 inventory of every bundled file under@@ -263,6 +285,8 @@ Unit tests and what they cover:- `test/volunteer-context.test.ts` — push-based context core (#2095), hermetic in-memory PGLite: `parseWindow` lenient `user:`/`assistant:` parsing, multi-turn window extraction, confidence-gated volunteering (arm confidences, multi-turn/newest-turn boosts, `min_confidence` gate, max-pages cap), slug-only suppression, privacy (rationales are deterministic templates; synopses pass the takes/facts fence), and the approximate usage-stats join.- `test/watch-command.test.ts` — `gbrain watch` push transport (#2095): streaming loop, rolling window, session dedupe, `--json` JSONL shape, `channel: 'watch'` event logging, clean EOF return. Hermetic PGLite + injected line/write deps (no subprocess, no real stdin).- `test/watch-sigint.serial.test.ts` — `gbrain watch` SIGINT lifecycle against a real spawned CLI subprocess with a tmpdir brain. SERIAL: parallel unit shards flake on concurrent subprocess spawns (same rationale as `apply-migrations-pglite-spawn.serial.test.ts`).+- `test/init-picker-pty.serial.test.ts` — the interactive `gbrain init` pickers (embedding-provider + search-mode) driven under a REAL pseudo-terminal via `launchTty`: typed input lands (a NON-default mode choice verified by a follow-up non-TTY config read — bare Enter and the `readLineSafe` timeout both resolve to defaults, so a defaults-asserting test would pass with dead input), prompt-to-acknowledgement gaps bounded well under the fallback window, plus the Ctrl-D/EOF keyless fallback. On CI, missing PTY support fails loud instead of skipping. Hermetic: HOME + GBRAIN_HOME at a temp root, pass-through auth keys stripped via `dropEnv`; `session.close()` in `finally`. Serial: PTY spawn + full PGLite bootstrap, and the serial lane is what runs in required CI.+- `test/tty-harness.test.ts` — the real-PTY harness's pure helpers (`stripAnsi`, `computeStalls`, `renderStallsReport`, `parseDriveCommand`, `buildClaudeTuiSeed`) with zero subprocesses; the file's live-PTY smokes are `describe.skipIf(!ptySupported())`-gated.- `test/autopilot-launchd-lifecycle.serial.test.ts` — autopilot lifecycle behavior, not generated-string assertions: the full install → self-disable → status → reinstall → uninstall arc with `launchctl` replaced by an argv recorder and the generated wrapper executed by a REAL bash against a genuinely deleted repo (every platform), plus a darwin-only fail-SKIP describe against the real launchd under a per-run unique label (`GBRAIN_AUTOPILOT_LABEL`) so it can never collide with — or tear down — a real install on the host. Serial: spawns subprocesses and pins HOME/GBRAIN_HOME for the whole file.- `test/autopilot-fanout.test.ts` — Autopilot fan-out and #4046 policy regression: targeted idempotency keys reopen per dispatch interval while stable doctor/remediate keys remain unchanged; the 60-minute full-cycle floor wins with a remaining small plan, and an all-fresh restart check advances the process-local clock without masking failed stale-source submissions.- `test/agent-scheduler-contract.serial.test.ts` — the documented external agent-scheduler shell chain (`gbrain sync --repo X && gbrain embed --stale`, live-sync.md / INSTALL_FOR_AGENTS.md Step 7) driven end-to-end through a real `/bin/sh` against a keyless PGLite brain: the `&&` short-circuit IS the contract (argv arrays can't exercise it), the keyless bare stale embed exits 0, and the pull-failure case that must break the chain does. Anti-vacuity: the fixture commits a real page and every read-back asserts pages >= 1. Serial: real spawned CLI + tmpdir HOME.diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex c8d6b4946d..2e20e7249c 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -162,7 +162,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/skillpack.ts` + `src/core/skillpack/{bundle,scaffold,reference,migrate-fence,scrub-legacy,harvest,harvest-lint,copy,apply-hunks,diff-text,installer}.ts` — managed-block install model retired; `install`/`uninstall` removed (exit non-zero with a hint to the replacement). Surface: `scaffold` (one-time additive copy via `copyArtifacts` in `copy.ts`; refuses to overwrite; partial-state fills missing paired sources declared in SKILL.md frontmatter `sources:`), `reference` (read-only diff lens + `--apply-clean-hunks` two-way auto-apply via pure-JS unified-diff parser/applier in `apply-hunks.ts` + `diff-text.ts`), `migrate-fence` (one-shot strip of legacy fence; cumulative-slugs receipt → row-parsing fallback; preserves rows verbatim as user-owned routing), `scrub-legacy-fence-rows` (opt-in row cleanup with skill-present + non-empty-triggers gate), `harvest` (host→gbrain inverse with symlink-reject + canonical-path containment via a `validateUploadPath`-style gate + default-on privacy linter in `harvest-lint.ts` against `~/.gbrain/harvest-private-patterns.txt` plus built-in a built-in fork-name pattern + email + Slack-channel patterns; rollback on match). Paired-source declarations live in each SKILL.md's frontmatter `sources:` array (validated by `loadSkillSources` in `bundle.ts`). `autoDetectSkillsDir` (in `src/core/repo-root.ts`) has a `cwd_walk_up` tier ahead of `~/.openclaw/workspace` (`$OPENCLAW_WORKSPACE` precedence preserved). `gbrain skillpack check --strict` exits non-zero on drift (CI gate); top-level `gbrain skillpack-check` keeps exit-1-on-issues for cron. Companion editorial skill `skills/skillpack-harvest/SKILL.md` drives the genericization checklist. Doc: `docs/guides/skillpacks-as-scaffolding.md`. Test coverage across `test/skillpack-{copy,scaffold,reference,reference-apply,apply-hunks,migrate-fence,scrub-legacy,harvest,harvest-lint,frontmatter-sources}.test.ts` + 9-case E2E in `test/e2e/skillpack-flow.test.ts`. `installer.ts` + `test/skillpack-install.test.ts` survive — `gbrain skillpack diff` still uses `diffSkill` from there.- `src/core/skillpack/{manifest-v1,tarball,state,remote-source,trust-prompt,bootstrap-display,scaffold-third-party,registry-schema,registry-client,rubric,doctor,init-scaffold,pack-publish,endorse,audit}.ts` + `examples/skillpack-reference/` + `docs/skillpack-anatomy.md` + `scripts/build-skillpack-anatomy.ts` — third-party skillpack ecosystem. `gbrain skillpack scaffold <owner/repo|https-url|./tgz|./local-dir>` resolves the spec via `classifySpec`, fetches through SSRF-hardened `git-remote.ts` (git) or extracts the tarball into `~/.gbrain/skillpack-cache/<host>/<owner>/<repo>/<sha>/`, validates `skillpack.json` (api_version `gbrain-skillpack-v1`), checks `gbrain_min_version`, surfaces a TOFU first-install identity-confirm prompt (author + source + pinned commit + tarball SHA + tier; non-TTY requires `--trust`), records the pin in machine-owned `~/.gbrain/skillpack-state.json` (schema `gbrain-skillpack-state-v1`, atomic `.tmp + rename`, `isAlreadyTrusted` skips re-prompt on author+pin match), runs through `enumerateScaffoldEntries` → `copyArtifacts` (one-time additive, refuses to overwrite), then DISPLAYS `runbooks/bootstrap.md` WITHOUT executing (deliberately does not auto-execute). Registry catalog at `garrytan/gbrain-skillpack-registry` split into `registry.json` (PR-able, `gbrain-registry-v1`) + `endorsements.json` (maintainer-only overlay, `gbrain-endorsements-v1`); `effectiveTier` merges. `registry-client.ts` fetches both via `If-None-Match` etag with 1h soft-TTL + stale-fallback (origins `fresh_fetch | cache_warm | cache_soft_stale | cache_hard_stale`); hard-fail only on no-cache + no-network. CLI: `gbrain skillpack {search,info,registry,doctor,init,pack,endorse}`. Doctor walks `SKILLPACK_RUBRIC_V1` (10 binary dimensions: 5 required CORE — manifest_valid, skills_have_skill_md, routing_evals_present ≥5 intents, skills_have_unique_triggers MECE, changelog_present_and_current — and 5 quality BADGES — unit_tests_present, e2e_tests_present, llm_eval_present ≥3 cases, bootstrap_runbook_present, license_present); tier eligibility: `endorsed` needs all 10, `community` needs core + ≥3 badges, `experimental` needs core only, `blocked` when any core fails. `--quick` ~5s structural sweep; `--fix --yes` auto-scaffolds `auto_fixable: true` dimensions and refuses to overwrite files whose mtime is newer than `skillpack.json`. `gbrain skillpack init <name>` lands 11 files (skillpack.json, SKILL.md, routing-eval.jsonl, test/example.test.ts, e2e/example.e2e.test.ts, evals/example.judge.json, runbooks/{bootstrap,uninstall,upgrade-template}.md, CHANGELOG, README, LICENSE); freshly-init'd scores 10/10; `--minimal` skips test/e2e/evals. `gbrain skillpack pack` packs a deterministic tarball via GNU tar (`--sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner` + `GZIP=-n` + `TZ=UTC`); refuses on `tier_eligibility === 'blocked'`. Extract caps (5000 files / 100MB total / 1MB per file / 255-char paths / 100:1 compression ratio); rejects symlinks/hardlinks/devices/FIFOs. `gbrain skillpack endorse <name> [--tier ...] [--push] [--dry-run]` runs in a clone of the registry repo: validates the pack in `registry.json`, mutates `endorsements.json` via pure `applyEndorsement`, stable-key-orders the write, commits `endorse: <name> -> <tier>`, optionally pushes. JSONL audit at `~/.gbrain/audit/skillpack-YYYY-Www.jsonl` (ISO-week rotated, honors `GBRAIN_AUDIT_DIR`). `examples/skillpack-reference/` is a 10/10 reference pack pinned by `test/e2e/skillpack-third-party.test.ts`. `docs/skillpack-anatomy.md` auto-generated via `scripts/build-skillpack-anatomy.ts` (`--check` for CI drift). CLI dispatch in `src/commands/skillpack.ts` disambiguates third-party (contains `/`, `://`, `.tgz`) from bundled-skill kebab; kebab routes bundled-first, registry-fallback. Tests: `test/skillpack-{manifest-v1,tarball,state,remote-source,trust-prompt,registry-schema,registry-client,rubric,doctor,init-scaffold,pack-publish,endorse,audit,scaffold-third-party}.test.ts` + `test/e2e/skillpack-third-party.test.ts`. Spec at `docs/designs/SKILLPACK_REGISTRY_V1_SPEC.md`.- `src/core/archive-crawler-config.ts` — safety gate for the `archive-crawler` skill. Refuses to run unless `archive-crawler.scan_paths:` is explicitly set in the brain repo's `gbrain.yml`. Mirrors the storage-config.ts parsing pattern (sibling file, separate concern from storage tiering). `loadArchiveCrawlerConfig(repoPath)` throws `ArchiveCrawlerConfigError(missing_section | empty_scan_paths | invalid_path | parse_error)`. `normalizeAndValidateArchiveCrawlerConfig` rejects relative paths and `..` traversal; `~` is expanded; paths are stored resolved and terminated with the PLATFORM separator (`path.sep`) so error output reads natively on each OS. `isPathAllowed(candidate, config)` is the runtime per-file gate (scan_paths prefix-match with directory-boundary correctness; deny_paths overrides). Candidate, scan_paths and deny_paths all funnel through the private `toComparablePrefix()` before the prefix test — on Windows it folds `\`→`/` and lowercases (NTFS is case-insensitive, so a deny_path spelled `Private` must still match `private`, else the gate fails OPEN); on POSIX it is identity apart from the trailing separator, deliberately NOT folding, since `\` is a legal filename character and paths are case-sensitive. Storing a native separator while appending a hardcoded `/` is the mixed-separator bug that made `isPathAllowed` deny every real path on Windows; the two functions must stay symmetric or the prefix test is meaningless. Pinned by `test/archive-crawler-config.test.ts` (26 cases, platform-selected fixtures + `it.if`-gated win32/POSIX comparison semantics).-- `test/helpers/cli-pty-runner.ts` — generic real-PTY harness (~470 lines) using pure `Bun.spawn({terminal:})` (Bun 1.3.10+; engines.bun pin in package.json). Generic primitives only, no plan-mode orchestrators. Exports `launchPty`, `resolveBinary`, `stripAnsi`, `parseNumberedOptions`, `optionsSignature`, `isNumberedOptionListVisible`, `isTrustDialogVisible`. Self-tests in `test/cli-pty-runner.test.ts` (24 cases).+- `test/helpers/tty-harness.ts` + `scripts/dx-explore.ts` — the repo's single real-PTY layer, on pure `Bun.spawn({terminal:})` (Bun 1.3.10+; engines.bun pin in package.json; no node-pty). `launchTty` spawns any CLI under a true pseudo-terminal with the hermetic env contract from `test/helpers/agent-harness.ts` (`hermeticChildEnv`; `dropEnv` strips pass-through auth keys), records timestamped output frames, and exposes `waitFor`/`waitForAny`/`mark`/`sendKey`/`waitForQuiet`/`waitForExit`/`close`. Lifecycle rule: only `close()` clears the wall-clock kill timer — always call it in a `finally`. Pure helpers (`stripAnsi`, `computeStalls`, `renderStallsReport`, `parseDriveCommand`, `buildClaudeTuiSeed`) are unit-tested in `test/tty-harness.test.ts`; that file's live-PTY smokes are `describe.skipIf(!ptySupported())`-gated. `scripts/dx-explore.ts` is the DX-exploration driver built on it — a developer instrument, not a test: nothing asserts, transcripts land gitignored under `.context/dx-runs/` (doc: `docs/guides/bootstrap.md`). The interactive `gbrain init` pickers are asserted for real in `test/init-picker-pty.serial.test.ts` (serial lane, so it runs in required CI).- `src/core/skillpack/{init-brain-pack,brain-pack-advisory,brain-pack-lint,brain-resident-locate,nag-state}.ts` (#2180) — brain-resident skillpacks. `manifest-v1.ts` gains optional `brain_resident` + `schema_pack` (additive). `runInitBrainPack` scaffolds a pack beside brain content (`brain_resident:true`, exact `gbrain_min_version`, 5-section machine-parseable README); `applyWritePlan` is factored out of `init-scaffold.ts` for the shared refuse-overwrite loop. `brain-pack-lint.lintBrainPackTools` validates each skill's `tools:` against the serving op set (E6 version-skew). Topology A: `src/commands/sources.ts` `runAdd` prints `brain-pack-advisory` to stderr after `opsAddSource`, fail-open; `nag-state.ts` (`~/.gbrain/skillpack-nag-state.json`) keys declines by `(source-repo brain_id, source_id, pack_name)` with pure `decideNagAction` (first/reminder/version-bump/ceiling) — declines count ONLY on CLI-interactive displays. Topology B: `brain-resident-locate.loadResidentPacksForServer` (source-scoped via `sourceScopeOpts`) backs the `list_brain_skillpack` op; `getResidentSkillDetail` backs `get_skill` `source_id`; `scaffold_spec` is the git source, never a server FS path. Tests: `test/skillpack-{init-brain-pack,nag-state,brain-resident-locate}.test.ts` + the brain-resident cases in `test/skillpack-manifest-v1.test.ts`.- `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` + `src/commands/advisor.ts` (#2180) — `gbrain advisor`: read-only ranked actions from brain state. `run.runAdvisor` executes the hardcoded COLLECTORS array (version [cache-only], migration, schema-pack, stalled-jobs [absent-table tolerant], usage-shape, setup-smells, uninstalled-brain-pack, uninstalled-bundled, chronicle, mcp-client-fit), each in its own try/catch; `collect-mcp-client-fit.ts` (E3) flags full-surface MCP clients whose 30d usage fits STARTER_OPS (exact `rescope-client --surface starter` fix; ≥10-call threshold; automation-shaped clients excluded per D12) plus STARTER_OPS drift (top-used ops missing; starter members unused 90d) via the shared `src/core/mcp-usage.ts` reader — starter membership is judged against the exported `ALWAYS_INCLUDED_STARTER_OPS` (surface.ts) so the always-included lane never reads as unused, and the missing-from-starter arm excludes `localOnly` ops (never proposable for a network surface, mirroring derive-starter-ops) — REMOTE runs redact client identifiers to aggregate counts (amendment 29), and its dismiss/snooze rides the nag-state engine with its own `~/.gbrain/advisor-usage-nag-state.json` (local runs only); `rankFindings` orders critical>warn>info then collector order, caps the info tail, and drops `workspace_dependent` findings when `remote` (A1). `render.ts` is the shared `=`-bar renderer used by the advisor AND `post-install-advisory.ts` (generalized to a single current-state `recommended-set.RECOMMENDED`, `install`→`scaffold`). `history.ts` appends bounded `~/.gbrain/advisor-history.jsonl` (no DB migration) for since-last-run deltas; local-only. `apply.resolveApplyTarget` is the allowlist+injection guard for `commands/advisor.ts --apply <id>` (structured argv, never a shell; local-only). The `advisor` op (`operations.ts`) is read-scoped, NOT localOnly, gated by `mcp.publish_advisor` (config.ts; default off) and strictly read-only on remote. CLI wired in `cli.ts` (`CLI_ONLY` + dispatch). Bundled skill `skills/gbrain-advisor/` + weekly cron recipe. Tests: `test/advisor-{core,apply,op-gate,ranking-eval}.test.ts`.- `src/core/chronicle/{eligibility,config,backstop,extract-events,ontology,narrative}.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` (#2390) — Life Chronicle: the temporal spine. `eligibility.isChronicleEligible` decides which pages auto-emit events (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop). `backstop.runChronicleBackstop` is the put_page hook body (fires ONLY on `status==='imported'` + the auto-link trust gate + the default-OFF `auto_chronicle` flag; enqueues a `chronicle_extract` minion job — LLM never runs on the write path). `extract-events.runChronicleExtract` is the job body: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date — a malformed batch writes NOTHING), then content-addressed `life/events/` pages + a `timeline_entries` projection via `engine.upsertEventProjection` (dedup `(event_page_id, date)`; idempotent re-runs). An unusable judge response is never recorded as `no_events` (#2606): a `stopReason: 'length'` truncation or a no-JSON-array response (`parseJudgeJson` returns `null` on parse failure; `[]` only for a legitimate empty array) surfaces as `status: 'skipped'` with reason `judge_truncated` / `judge_parse_failed`. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free → crash-retry idempotent), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value, forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly). Diary privacy: diary-sourced ontology + conflict values redacted for `ctx.remote !== false` callers. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts + coverage gap); doctor `chronicle_projection_health` (BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts`, `test/eval-chronicle.test.ts`.diff --git a/docs/guides/bootstrap.md b/docs/guides/bootstrap.mdindex 5462e59fad..7c912363ec 100644--- a/docs/guides/bootstrap.md+++ b/docs/guides/bootstrap.md@@ -300,6 +300,10 @@ burst with a millisecond timestamp, so unnecessary pauses become a measurableartifact (`computeStalls` → `stalls.md`) instead of a vibe. Same hermetic env as`agent-harness.ts`; pure helpers are unit-tested in `test/tty-harness.test.ts`(zero subprocesses, PTY smokes self-skip where `terminal:` is unavailable).+The harness itself also backs one required-CI test: `test/init-picker-pty.serial.test.ts`+asserts the interactive `gbrain init` pickers under a real PTY (see the+TTY decision table in `docs/TESTING.md`). The DX-exploration layer below stays+an instrument — nothing in it asserts.`scripts/dx-explore.ts` drives it to capture the fresh-user funnel as timestampedtranscripts under `.context/dx-runs/` (gitignored — nothing asserts, no CI):diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 3ff3f0622a..a430be24e2 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.45.18.0",+ "version": "0.45.19.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","configSchema": {diff --git a/package.json b/package.jsonindex af7d875747..12da1ed24b 100644--- a/package.json+++ b/package.json@@ -156,7 +156,7 @@"bun": ">=1.3.10"},"license": "MIT",- "version": "0.45.18.0",+ "version": "0.45.19.0","overrides": {"@hono/node-server": "^2.0.5","fast-uri": "^3.1.5",diff --git a/scripts/test-weights.json b/scripts/test-weights.jsonindex 2ba74a3ef3..dfbdca1a66 100644--- a/scripts/test-weights.json+++ b/scripts/test-weights.json@@ -103,7 +103,6 @@"test/cli-help-discoverability.test.ts": 1670,"test/cli-multimodal-integration.test.ts": 26677,"test/cli-options.test.ts": 1658,- "test/cli-pty-runner.test.ts": 16,"test/cli-query-image.test.ts": 56,"test/cli.test.ts": 2633,"test/code-callers-cli.test.ts": 2,diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 77a94cd130..c5520e4281 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.45.18.0 -->+<!-- gbrain-template-stamp: 0.45.19.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/cli-pty-runner.test.ts b/test/cli-pty-runner.test.tsdeleted file mode 100644index 98afacd778..0000000000--- a/test/cli-pty-runner.test.ts+++ /dev/null@@ -1,184 +0,0 @@-/**- * Tests for test/helpers/cli-pty-runner.ts (D14/C-prime PTY harness).- *- * Pure-function tests. The launchPty subprocess path is exercised by- * the E2E suite (test/e2e/skill-smoke-openclaw.test.ts), not here.- */--import { describe, expect, it } from 'bun:test';-import {- stripAnsi,- isNumberedOptionListVisible,- parseNumberedOptions,- optionsSignature,- isTrustDialogVisible,- resolveBinary,-} from './helpers/cli-pty-runner.ts';--describe('stripAnsi', () => {- it('strips standard CSI sequences', () => {- expect(stripAnsi('\x1b[31mred\x1b[0m')).toBe('red');- expect(stripAnsi('\x1b[1;33;42mfoo\x1b[m')).toBe('foo');- });-- it('strips OSC sequences (terminator BEL)', () => {- expect(stripAnsi('\x1b]0;title\x07rest')).toBe('rest');- });-- it('strips OSC sequences (terminator ST)', () => {- expect(stripAnsi('\x1b]1;icon\x1b\\rest')).toBe('rest');- });-- it('strips charset designators', () => {- expect(stripAnsi('\x1b(Bplain')).toBe('plain');- });-- it('strips DEC special functions (\\x1b7 / \\x1b8 / \\x1b=)', () => {- expect(stripAnsi('\x1b7save\x1b8restore\x1b=app')).toBe('saverestoreapp');- });-- it('passes through plain text unchanged', () => {- expect(stripAnsi('hello world')).toBe('hello world');- expect(stripAnsi('1. Option\n2. Option')).toBe('1. Option\n2. Option');- });-});--describe('isNumberedOptionListVisible', () => {- it('matches a cursor + numbered list', () => {- expect(isNumberedOptionListVisible('❯ 1. Yes\n 2. No')).toBe(true);- });-- it('rejects when no cursor', () => {- expect(isNumberedOptionListVisible('1. Yes\n2. No')).toBe(false);- });-- it('rejects when only one option', () => {- expect(isNumberedOptionListVisible('❯ 1. Only')).toBe(false);- });-- it('handles cursor + collapsed-whitespace cases (TTY artifacts)', () => {- // After stripAnsi, cursor-positioning escapes that visually rendered- // as spaces are gone — `text 2.` becomes `text2.`.- expect(isNumberedOptionListVisible('❯ 1.Yestext2.No')).toBe(true);- });-});--describe('parseNumberedOptions', () => {- it('extracts a clean 3-option list', () => {- const visible = `Question text-❯ 1. First option- 2. Second option- 3. Third option-`;- const opts = parseNumberedOptions(visible);- expect(opts).toEqual([- { index: 1, label: 'First option' },- { index: 2, label: 'Second option' },- { index: 3, label: 'Third option' },- ]);- });-- it('returns [] when no list rendered', () => {- expect(parseNumberedOptions('just prose, no list')).toEqual([]);- });-- it('returns [] when only one option (not a real list)', () => {- expect(parseNumberedOptions('❯ 1. Only')).toEqual([]);- });-- it('caller pattern: gate on isNumberedOptionListVisible to skip prose', () => {- // parseNumberedOptions itself has a fallback for cursor-on-non-1- // (user pressed Down) which means it WILL match prose numbering- // when no cursor is present. The contract is that consumers gate- // on `isNumberedOptionListVisible` first — it requires `❯`.- const prose = `Steps to take:-1. Read the file-2. Edit the line-3. Run the test`;- expect(isNumberedOptionListVisible(prose)).toBe(false);- // Defense-in-depth: even if parseNumberedOptions returns options- // here, the caller would not act on them because the gate is false.- });-- it('truncates at the first gap (sequential block only)', () => {- const visible = `❯ 1. A- 2. B- 4. D`;- expect(parseNumberedOptions(visible)).toEqual([- { index: 1, label: 'A' },- { index: 2, label: 'B' },- ]);- });-- it('handles cursor on a non-1 option (user pressed Down)', () => {- const visible = `Question- 1. First-❯ 2. Second- 3. Third`;- const opts = parseNumberedOptions(visible);- expect(opts.length).toBe(3);- expect(opts[0]).toEqual({ index: 1, label: 'First' });- });-- it('reads only the last 4KB to avoid stale option lists', () => {- const noise = 'old ❯ 1. STALE\n 2. STALE\n'.padEnd(5000, ' ');- const fresh = '❯ 1. Fresh\n 2. New\n';- const opts = parseNumberedOptions(noise + fresh);- expect(opts).toEqual([- { index: 1, label: 'Fresh' },- { index: 2, label: 'New' },- ]);- });-});--describe('optionsSignature', () => {- it('produces a stable signature regardless of input order', () => {- const a = optionsSignature([- { index: 2, label: 'B' },- { index: 1, label: 'A' },- ]);- const b = optionsSignature([- { index: 1, label: 'A' },- { index: 2, label: 'B' },- ]);- expect(a).toBe(b);- expect(a).toBe('1:A|2:B');- });-- it('includes label in the signature so same indices with different labels differ', () => {- expect(optionsSignature([{ index: 1, label: 'Yes' }])).not.toBe(- optionsSignature([{ index: 1, label: 'No' }]),- );- });-});--describe('isTrustDialogVisible', () => {- it('matches the canonical phrasing', () => {- expect(- isTrustDialogVisible('Do you want to trust this folder?'),- ).toBe(true);- });-- it('does not match other prompts', () => {- expect(isTrustDialogVisible('Do you want to proceed?')).toBe(false);- expect(isTrustDialogVisible('')).toBe(false);- });-});--describe('resolveBinary', () => {- it('honors override when the file exists', () => {- // /bin/sh exists everywhere unix-y this test runs.- expect(resolveBinary('any-name', '/bin/sh')).toBe('/bin/sh');- });-- it('returns null for a definitely-missing binary', () => {- expect(resolveBinary('definitely-not-a-real-binary-xyzzy123')).toBeNull();- });-- it('finds common binaries by name (sh)', () => {- const sh = resolveBinary('sh');- // bun.which finds /bin/sh on macOS/linux. Either /bin/sh or /usr/bin/sh- // is acceptable — just confirm SOMETHING was found.- expect(sh).toBeTruthy();- });-});diff --git a/test/e2e/init-fresh-pglite.test.ts b/test/e2e/init-fresh-pglite.test.tsindex b6e8f4da6f..d6ffe22276 100644--- a/test/e2e/init-fresh-pglite.test.ts+++ b/test/e2e/init-fresh-pglite.test.ts@@ -13,10 +13,10 @@* - `--no-embedding` D9 opt-in: init succeeds with sentinel; gbrain import refuses* - D11 preflight: explicit bad --embedding-dimensions refuses BEFORE touching disk*- * Picker interactive flow (multi-key TTY) needs the real-PTY harness from- * test/helpers/cli-pty-runner.ts — that path is exercised by the unit tests- * for `init-provider-picker.ts` (T4) plus the env-detection helpers (T5).- * Adding PTY here is mostly orthogonal scope.+ * Picker interactive flow (real TTY) is covered by the real-PTY serial test+ * at test/init-picker-pty.serial.test.ts (keyless provider choice plus a+ * non-default search mode, driven through a true pseudo-terminal). This file+ * stays piped-stdin on purpose: it exercises the NON-TTY branches.*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';diff --git a/test/helpers/cli-pty-runner.ts b/test/helpers/cli-pty-runner.tsdeleted file mode 100644index b68df1548f..0000000000--- a/test/helpers/cli-pty-runner.ts+++ /dev/null@@ -1,473 +0,0 @@-/**- * cli-pty-runner.ts — generic real-PTY runner for CLI E2E tests.- *- * Ported from gstack's claude-pty-runner.ts (D14/C-prime in the v0.25.1- * plan). Generalized to drive any CLI binary (gbrain, openclaw, claude)- * — the gstack-specific plan-mode orchestrators (runPlanSkillObservation,- * runPlanSkillCounting, invokeAndObserve, the per-skill Step-0 boundary- * predicates) are dropped because they assume Claude Code's plan-mode- * UI specifics that don't apply here.- *- * Architecture: pure Bun.spawn — no node-pty, no native modules. Bun- * 1.3.10+ has built-in PTY support via the `terminal:` spawn option.- *- * What gbrain uses this for in v0.25.1:- * - test/e2e/skill-smoke-openclaw.test.ts: drive an openclaw session- * interactively after `gbrain skillpack install book-mirror`,- * verifying real numbered-menu routing.- * - Future: any CLI command that grows interactive prompts (e.g.,- * book-mirror's cost-estimate "Continue? [y/N]") becomes testable- * without a refactor.- *- * For non-interactive CLI tests (skillpack install/uninstall stdout- * grep), use Bun.spawnSync directly — that's lighter and matches the- * existing test/cli.test.ts pattern.- */--import * as fs from 'fs';--// ── ANSI / TTY helpers ──────────────────────────────────────--/** Strip ANSI escapes for pattern-matching against visible text. */-export function stripAnsi(s: string): string {- return s- .replace(/\x1b\[[\d;]*[a-zA-Z]/g, '')- .replace(/\x1b\][^\x07\x1b]*(\x07|\x1b\\)/g, '')- .replace(/\x1b[()][AB012]/g, '')- .replace(/\x1b[78=>]/g, '');-}--/** Detect a numbered AskUserQuestion-shaped option list with cursor. */-export function isNumberedOptionListVisible(visible: string): boolean {- // ❯ cursor + at least two numbered options 1-9.- // The `[^0-9]2\.` pattern handles the case where stripAnsi removes- // TTY cursor-positioning escapes that visually rendered as spaces,- // collapsing `text 2.` to `text2.`.- return /❯\s*1\./.test(visible) && /(^|[^0-9])2\./.test(visible);-}--/**- * Parse a rendered numbered-option list out of the visible TTY text.- *- * Looks for lines like `❯ 1. label` (cursor) or ` 2. label` (no cursor)- * and returns them in order. Used by tests that need to ROUTE on a- * specific option label without hard-coding positional indexes that- * drift when option order changes.- *- * Reads only the LAST 4KB of visible text to avoid matching stale- * option lists from earlier prompts.- *- * Returns [] when no list is rendered (or when the list isn't a- * sequential 1.., 2.., ... block — to avoid matching `1. Read the- * file` prose). Otherwise returns indices in ascending order.- */-export function parseNumberedOptions(- visible: string,-): Array<{ index: number; label: string }> {- const tail = visible.length > 4096 ? visible.slice(-4096) : visible;- // `\s*` after `.` (not `\s+`) because stripAnsi removes TTY cursor-- // positioning escapes that render as spaces — `1. Option` may come- // through as `1.Option`.- const optionRe = /^[\s❯]*([1-9])\.\s*(\S.*?)\s*$/;- const lines = tail.split('\n');-- // Anchor on the LAST `❯<spaces>1.` line. Box-layout AUQs render- // cursor mid-line after dividers + headers + prompt text on the same- // logical line — the unanchored pattern catches those.- let cursorLineIdx = -1;- for (let i = lines.length - 1; i >= 0; i--) {- if (/❯\s*1\./.test(lines[i] ?? '')) {- cursorLineIdx = i;- break;- }- }- // Fallback: if cursor isn't on option 1 (user pressed Down), find- // the last `1.` line.- if (cursorLineIdx < 0) {- for (let i = lines.length - 1; i >= 0; i--) {- if (/^(?:\s*|\s*❯\s+)1\./.test(lines[i] ?? '')) {- cursorLineIdx = i;- break;- }- }- }- if (cursorLineIdx < 0) return [];-- const found: Array<{ index: number; label: string }> = [];- const seenIndices = new Set<number>();-- // Cursor line: option 1 may be inline after box dividers + header.- const cursorLine = lines[cursorLineIdx] ?? '';- const cursorInlineRe = /❯\s*([1-9])\.\s*(\S.*?)\s*$/;- const inlineMatch = cursorInlineRe.exec(cursorLine);- if (inlineMatch) {- const idx = Number(inlineMatch[1]);- const label = (inlineMatch[2] ?? '').trim();- if (label.length > 0 && !seenIndices.has(idx)) {- seenIndices.add(idx);- found.push({ index: idx, label });- }- } else {- const startMatch = optionRe.exec(cursorLine);- if (startMatch) {- const idx = Number(startMatch[1]);- const label = (startMatch[2] ?? '').trim();- if (label.length > 0 && !seenIndices.has(idx)) {- seenIndices.add(idx);- found.push({ index: idx, label });- }- }- }-- // Subsequent lines: standard start-of-line option parsing.- for (let i = cursorLineIdx + 1; i < lines.length; i++) {- const m = optionRe.exec(lines[i] ?? '');- if (!m) continue;- const idx = Number(m[1]);- const label = (m[2] ?? '').trim();- if (seenIndices.has(idx)) continue;- if (label.length === 0) continue;- seenIndices.add(idx);- found.push({ index: idx, label });- }-- // Only return if we found a sequential 1.., 2.., ... block (at least- // 2 consecutive options starting at 1). Otherwise it's prose noise.- found.sort((a, b) => a.index - b.index);- if (found.length < 2) return [];- if (found[0]!.index !== 1) return [];- for (let i = 1; i < found.length; i++) {- if (found[i]!.index !== found[i - 1]!.index + 1) {- return found.slice(0, i);- }- }- return found;-}--/**- * Stable signature for a parsed numbered-option list. Used by tests- * to detect "is this AUQ the same as the last poll, or has the agent- * advanced to a new one?"- */-export function optionsSignature(- opts: Array<{ index: number; label: string }>,-): string {- return [...opts]- .sort((a, b) => a.index - b.index)- .map((o) => `${o.index}:${o.label}`)- .join('|');-}--/** Detect a workspace-trust dialog (claude / openclaw render this on first- * use of a new directory). */-export function isTrustDialogVisible(visible: string): boolean {- return visible.includes('trust this folder');-}--// ── binary resolution ──────────────────────────────────────--/**- * Resolve a CLI binary on PATH, with common fallback locations. Used- * to find `claude`, `openclaw`, `gbrain`, etc. without forcing tests- * to hard-code paths.- */-export function resolveBinary(name: string, override?: string): string | null {- if (override && fs.existsSync(override)) return override;- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const which = (Bun as any).which?.(name);- if (which) return which;- const home = process.env.HOME ?? '';- const candidates = [- `/opt/homebrew/bin/${name}`,- `/usr/local/bin/${name}`,- `${home}/.local/bin/${name}`,- `${home}/.bun/bin/${name}`,- `${home}/.npm-global/bin/${name}`,- ];- for (const c of candidates) {- try {- fs.accessSync(c, fs.constants.X_OK);- return c;- } catch {- /* keep searching */- }- }- return null;-}--// ── PTY session ────────────────────────────────────────────--export interface PtyOptions {- /** Absolute path to the binary. If omitted, uses the first arg of- * `args` as a binary name and tries resolveBinary on it. */- binary?: string;- /** Command + args, OR (when binary is omitted) [binaryName, ...args]. */- args: string[];- /** Terminal size. Default 120x40. */- cols?: number;- rows?: number;- /** Working directory. Default: process.cwd(). */- cwd?: string;- /** Env override on top of process.env. */- env?: Record<string, string>;- /** Total run timeout (ms). Default 240_000 (4 min). */- timeoutMs?: number;- /** Auto-handle the workspace-trust dialog by sending "1\r". Default- * true since most claude/openclaw test runs see it on fresh tempdirs. */- autoTrust?: boolean;-}--export interface PtySession {- /** Send raw bytes to PTY stdin. Newlines = `\r` in TTY world. */- send(data: string): void;- /** Send a key by name. */- sendKey(key: 'Enter' | 'Up' | 'Down' | 'Esc' | 'Tab' | 'ShiftTab' | 'CtrlC'): void;- /** Raw accumulated stdout (with ANSI). For forensics. */- rawOutput(): string;- /** ANSI-stripped session output for pattern matching. */- visibleText(): string;- /**- * Mark the current buffer position. Subsequent waitForAny /- * visibleSince calls only look at output AFTER this mark. Useful- * for scoping assertions to "after I sent the command" — avoids- * matching against boot-banner residue.- */- mark(): number;- /** Visible text since the most recent (or specific) mark. */- visibleSince(marker?: number): string;- /**- * Wait for any of the supplied patterns to appear. Resolves with- * the first match. Throws on timeout (last 2KB of visible included- * in the error for forensics). If `since` is supplied, only matches- * text after that mark.- */- waitForAny(- patterns: Array<RegExp | string>,- opts?: { timeoutMs?: number; pollMs?: number; since?: number },- ): Promise<{ matched: RegExp | string; index: number }>;- /** Convenience: single-pattern wait. */- waitFor(- pattern: RegExp | string,- opts?: { timeoutMs?: number; pollMs?: number; since?: number },- ): Promise<void>;- /** Subprocess pid (for debug). */- pid(): number | undefined;- /** True if the underlying process has exited. */- exited(): boolean;- /** Exit code, if known. */- exitCode(): number | null;- /**- * Send SIGINT, then SIGKILL after 1s. Always safe to call- * multiple times. Awaits process exit before resolving.- */- close(): Promise<void>;-}--/**- * launchPty — spawn a CLI binary in a real PTY and return a session.- *- * Caller is responsible for `await session.close()` to release the- * subprocess + timers.- */-export async function launchPty(opts: PtyOptions): Promise<PtySession> {- const args = [...opts.args];- let binary = opts.binary;- if (!binary) {- if (args.length === 0) {- throw new Error(- 'launchPty: pass a `binary` option, or `args[0]` as the binary name.',- );- }- const resolved = resolveBinary(args[0]!);- if (!resolved) {- throw new Error(- `launchPty: could not resolve "${args[0]}" on PATH. Set the binary location explicitly via the \`binary\` option, or install it.`,- );- }- binary = resolved;- args.shift();- }-- const cwd = opts.cwd ?? process.cwd();- const cols = opts.cols ?? 120;- const rows = opts.rows ?? 40;- const timeoutMs = opts.timeoutMs ?? 240_000;- const autoTrust = opts.autoTrust ?? true;-- let buffer = '';- let exited = false;- let exitCodeCaptured: number | null = null;-- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const proc = (Bun as any).spawn([binary, ...args], {- terminal: {- cols,- rows,- data(_t: unknown, chunk: Buffer) {- buffer += chunk.toString('utf-8');- },- },- cwd,- env: { ...process.env, ...(opts.env ?? {}) },- });-- // Track exit so waitForAny can fail fast if the subprocess crashes.- let exitedPromise: Promise<void> = Promise.resolve();- if (proc.exited && typeof proc.exited.then === 'function') {- exitedPromise = proc.exited- .then((code: number | null) => {- exitCodeCaptured = code;- exited = true;- })- .catch(() => {- exited = true;- });- }-- // Top-level wall-clock timeout. If a test forgets to close, this- // kills the subprocess eventually so CI doesn't hang forever.- const wallTimer = setTimeout(() => {- try {- proc.kill?.('SIGKILL');- } catch {- /* ignore */- }- }, timeoutMs);-- // Auto-handle the workspace-trust dialog. Polls during boot;- // idempotent (only fires while the phrase is on screen).- let trustHandled = false;- let trustWatcher: ReturnType<typeof setInterval> | null = null;- let trustWatcherStop: ReturnType<typeof setTimeout> | null = null;- if (autoTrust) {- trustWatcher = setInterval(() => {- if (trustHandled || exited) return;- const visible = stripAnsi(buffer);- if (isTrustDialogVisible(visible)) {- trustHandled = true;- try {- proc.terminal?.write?.('1\r');- } catch {- /* ignore */- }- }- }, 200);- trustWatcherStop = setTimeout(() => {- if (trustWatcher) clearInterval(trustWatcher);- }, 15_000);- }-- function send(data: string): void {- if (exited) return;- try {- proc.terminal?.write?.(data);- } catch {- /* ignore */- }- }-- type Key = Parameters<PtySession['sendKey']>[0];- function sendKey(key: Key): void {- const map: Record<string, string> = {- Enter: '\r',- Up: '\x1b[A',- Down: '\x1b[B',- Esc: '\x1b',- Tab: '\t',- ShiftTab: '\x1b[Z',- CtrlC: '\x03',- };- send(map[key] ?? '');- }-- let lastMark = 0;- function mark(): number {- lastMark = buffer.length;- return lastMark;- }- function visibleSince(marker?: number): string {- const offset = marker ?? lastMark;- return stripAnsi(buffer.slice(offset));- }-- async function waitForAny(- patterns: Array<RegExp | string>,- waitOpts?: { timeoutMs?: number; pollMs?: number; since?: number },- ): Promise<{ matched: RegExp | string; index: number }> {- const wTimeout = waitOpts?.timeoutMs ?? 60_000;- const poll = waitOpts?.pollMs ?? 250;- const since = waitOpts?.since;- const start = Date.now();- while (Date.now() - start < wTimeout) {- if (exited) {- throw new Error(- `subprocess exited (code=${exitCodeCaptured}) before any pattern matched. ` +- `Last visible:\n${stripAnsi(buffer).slice(-2000)}`,- );- }- const visible =- since !== undefined ? stripAnsi(buffer.slice(since)) : stripAnsi(buffer);- for (let i = 0; i < patterns.length; i++) {- const p = patterns[i]!;- const matchIdx =- typeof p === 'string' ? visible.indexOf(p) : visible.search(p);- if (matchIdx >= 0) {- return { matched: p, index: matchIdx };- }- }- await Bun.sleep(poll);- }- throw new Error(- `Timed out after ${wTimeout}ms waiting for any of: ${patterns- .map((p) => (typeof p === 'string' ? JSON.stringify(p) : p.source))- .join(', ')}\nLast visible (since=${since ?? 'all'}):\n${- since !== undefined- ? stripAnsi(buffer.slice(since)).slice(-2000)- : stripAnsi(buffer).slice(-2000)- }`,- );- }-- async function waitFor(- pattern: RegExp | string,- waitOpts?: { timeoutMs?: number; pollMs?: number; since?: number },- ): Promise<void> {- await waitForAny([pattern], waitOpts);- }-- async function close(): Promise<void> {- clearTimeout(wallTimer);- if (trustWatcherStop) clearTimeout(trustWatcherStop);- if (trustWatcher) clearInterval(trustWatcher);- if (exited) return;- try {- proc.kill?.('SIGINT');- } catch {- /* ignore */- }- await Promise.race([exitedPromise, Bun.sleep(2000)]);- if (!exited) {- try {- proc.kill?.('SIGKILL');- } catch {- /* ignore */- }- await Promise.race([exitedPromise, Bun.sleep(1000)]);- }- }-- return {- send,- sendKey,- rawOutput: () => buffer,- visibleText: () => stripAnsi(buffer),- mark,- visibleSince,- waitForAny,- waitFor,- pid: () => proc.pid as number | undefined,- exited: () => exited,- exitCode: () => exitCodeCaptured,- close,- };-}diff --git a/test/helpers/tty-harness.ts b/test/helpers/tty-harness.tsindex cfc68edd19..a108e0e46c 100644--- a/test/helpers/tty-harness.ts+++ b/test/helpers/tty-harness.ts@@ -15,9 +15,10 @@* 1. DX-exploration runs (`scripts/dx-explore.ts`) — capture the fresh-user* install funnel as timestamped transcripts for Don't-Make-Me-Think* audits (stall report + verbatim rendered copy per step).- * 2. Future PTY e2e tests — the same waitFor/sendKey primitives the gstack- * plan-mode PTY suite uses (pattern adapted from gstack's- * test/helpers/claude-pty-runner.ts; no node-pty, no native modules).+ * 2. PTY e2e tests — test/init-picker-pty.serial.test.ts and future+ * siblings use the same waitFor/sendKey primitives (pattern adapted from+ * gstack's test/helpers/claude-pty-runner.ts; no node-pty, no native+ * modules).** Hermeticity matches agent-harness.ts: every spawn goes through* hermeticChildEnv, so a DX run can NEVER see (or mutate) the operator's real@@ -25,8 +26,9 @@* temp-dir override in.** Pure helpers (stripAnsi, computeStalls, parseDriveCommand,- * renderStallsReport, buildClaudeTuiSeed) are exported for the zero-subprocess- * unit suite (test/tty-harness.test.ts).+ * renderStallsReport, buildClaudeTuiSeed) are exported for the unit suite+ * (test/tty-harness.test.ts) — mostly pure describes, plus a+ * ptySupported()-gated live block that spawns real sh children.*/import * as fs from 'node:fs';diff --git a/test/init-env-detection.test.ts b/test/init-env-detection.test.tsindex 8b4359a890..41d5ac54f4 100644--- a/test/init-env-detection.test.ts+++ b/test/init-env-detection.test.ts@@ -4,7 +4,9 @@* These tests exercise the exported pure helpers (groupReadyByProvider,* findEnvKeyTypos) with hermetic env injections. The resolveAIOptions* orchestration itself is exercised end-to-end via T12's- * test/e2e/init-fresh-pglite.test.ts (PTY-based, real CLI).+ * test/e2e/init-fresh-pglite.test.ts (piped-stdin, real CLI — non-TTY+ * branches) and test/init-picker-pty.serial.test.ts (real PTY — the+ * interactive picker branches).** Per CLAUDE.md test isolation rules: env mutations would normally need* `withEnv`, but these helpers accept env as an argument — purer DI, nodiff --git a/test/init-picker-pty.serial.test.ts b/test/init-picker-pty.serial.test.tsnew file mode 100644index 0000000000..b74b471136--- /dev/null+++ b/test/init-picker-pty.serial.test.ts@@ -0,0 +1,179 @@+/**+ * Real-PTY test for the interactive `gbrain init` pickers — the one flow that+ * needs a true TTY. Both pickers branch on stdin TTY-ness: the embedding+ * provider picker (fires BEFORE schema init, src/commands/init.ts) and the+ * search-mode picker (fires AFTER initSchema, src/commands/init-mode-picker.ts).+ * Injected-isTTY unit tests cover the pure logic; this test proves the real+ * CLI under a real pseudo-terminal renders both menus and reads typed input.+ *+ * Why serial: PTY spawns plus a full PGLite bootstrap are too heavy for the+ * concurrent fast loop — and the serial runner is the lane that actually+ * executes in required CI (unit shards exclude the e2e directory, and the+ * e2e workflow runs only explicitly named files — no glob).+ *+ * Input-liveness discipline: bare Enter AND the 60s readLineSafe timeout both+ * resolve each prompt to its default, so a test asserting defaults would pass+ * with dead input. This test therefore (a) picks a NON-default search mode+ * (tokenmax; the keyless-env recommendation is conservative) and asserts its+ * DB-plane value via a follow-up non-TTY config read, and (b) bounds each+ * prompt-to-acknowledgement gap well under the 60s fallback.+ *+ * Hermeticity: HOME and GBRAIN_HOME both point at the temp root — init probes+ * host paths under the real home (gstack discovery via homedir()) — and the+ * Anthropic credentials are dropped (the auth vars hermeticChildEnv passes+ * through), so zero providers are env-ready and picker state is+ * machine-independent.+ *+ * Lifecycle: session.close() in finally, BEFORE temp-dir removal. waitForExit+ * does not clear the harness wall timer; only close() does — skipping it+ * leaks the child and its PGLite lock on any failed assertion.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { mkdtempSync, mkdirSync, rmSync, existsSync, readFileSync } from 'fs';+import { spawnSync } from 'child_process';+import { tmpdir } from 'os';+import { join } from 'path';++import { launchTty, ptySupported } from './helpers/tty-harness.ts';++const REPO_ROOT = join(import.meta.dir, '..');+const CLI_TS = join(REPO_ROOT, 'src', 'cli.ts');++// A prompt answered by a live send resolves fast; a dead send means+// readLineSafe sits its full fallback window (60s at both call sites this+// test drives: src/commands/init-provider-picker.ts and+// src/commands/init-mode-picker.ts) and proceeds with the default. The+// liveness bound is a FIXED interaction budget, deliberately independent of+// the fallback constant — generous enough for a loaded CI runner, strictly+// below any plausible future fallback value, so dead input can never pass+// even if the production fallback is shortened.+const PROMPT_LIVENESS_MS = 20_000;++// On CI the pinned Bun (engines >= 1.3.10) has PTY support — a skip here+// would be silent coverage loss, so fail loud instead. Locally a missing+// PTY (exotic sandbox) downgrades to skip.+if (process.env.CI) {+ test('PTY support is mandatory on CI', () => {+ expect(ptySupported()).toBe(true);+ });+}+const describePty = ptySupported() ? describe : describe.skip;++describePty('gbrain init interactive pickers under a real PTY (keyless)', () => {+ let tmpRoot: string;+ let homeDir: string;+ let workDir: string;++ beforeAll(() => {+ tmpRoot = mkdtempSync(join(tmpdir(), 'gbrain-pty-init-'));+ homeDir = join(tmpRoot, 'home');+ workDir = join(tmpRoot, 'work');+ mkdirSync(homeDir, { recursive: true });+ mkdirSync(workDir, { recursive: true });+ });+ afterAll(() => {+ rmSync(tmpRoot, { recursive: true, force: true });+ });++ test('provider picker keyless choice + NON-default mode land in config', async () => {+ const session = launchTty(['bun', 'run', CLI_TS, 'init', '--pglite'], {+ cwd: workDir,+ env: { HOME: homeDir, GBRAIN_HOME: homeDir },+ dropEnv: ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN'],+ timeoutMs: 240_000,+ });++ try {+ // ── Prompt 1: embedding provider picker (pre-schema). Zero env-ready+ // providers → the menu still renders the keyless row for the embedding+ // touchpoint. Answer 0 (keyless).+ await session.waitFor('0) none', { timeoutMs: 60_000 });+ const afterMenu = session.mark();+ const tProvider = Date.now();+ session.send('0\r');++ // The keyless-continue notice prints immediately after the picker+ // returns (still pre-schema), so this gap measures prompt liveness,+ // not PGLite bootstrap time.+ await session.waitFor(/keyless mode/i, { timeoutMs: 60_000, since: afterMenu });+ expect(Date.now() - tProvider).toBeLessThan(PROMPT_LIVENESS_MS);++ // ── Prompt 2: search-mode picker (post-initSchema — allow PGLite+ // bootstrap time before it appears). Recommendation in a keyless env+ // is conservative; pick tokenmax (option 3) to prove input landed.+ await session.waitFor('Mode [', { timeoutMs: 120_000, since: afterMenu });+ const afterModePrompt = session.mark();+ const tMode = Date.now();+ session.send('3\r');++ await session.waitFor('Search mode set to: tokenmax', {+ timeoutMs: 60_000,+ since: afterModePrompt,+ });+ expect(Date.now() - tMode).toBeLessThan(PROMPT_LIVENESS_MS);++ const exitCode = await session.waitForExit(120_000);+ expect(exitCode).toBe(0);+ } finally {+ await session.close();+ }++ // ── Persistence: file plane carries the keyless sentinel...+ const cfgPath = join(homeDir, '.gbrain', 'config.json');+ expect(existsSync(cfgPath)).toBe(true);+ const cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));+ expect(cfg.engine).toBe('pglite');+ expect(cfg.embedding_disabled).toBe(true);++ // ── ...and the DB plane carries the NON-default mode. Read it back the+ // way a script would: non-TTY CLI, bare value on stdout. The init child+ // has exited, so the PGLite single-writer lock is free.+ const readBack = spawnSync('bun', ['run', CLI_TS, 'config', 'get', 'search.mode'], {+ env: {+ PATH: process.env.PATH,+ HOME: homeDir,+ GBRAIN_HOME: homeDir,+ TMPDIR: process.env.TMPDIR,+ },+ cwd: REPO_ROOT,+ encoding: 'utf-8',+ timeout: 120_000,+ });+ expect(readBack.status).toBe(0);+ expect((readBack.stdout ?? '').trim()).toBe('tokenmax');+ }, 300_000);++ test('Ctrl-D at the provider prompt falls back to keyless via EOF detection', async () => {+ const homeDir2 = join(tmpRoot, 'home-eof');+ const workDir2 = join(tmpRoot, 'work-eof');+ mkdirSync(homeDir2, { recursive: true });+ mkdirSync(workDir2, { recursive: true });++ const session = launchTty(['bun', 'run', CLI_TS, 'init', '--pglite'], {+ cwd: workDir2,+ env: { HOME: homeDir2, GBRAIN_HOME: homeDir2 },+ dropEnv: ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN'],+ timeoutMs: 240_000,+ });+ try {+ await session.waitFor('0) none', { timeoutMs: 60_000 });+ const afterMenu = session.mark();+ const tEof = Date.now();+ session.sendKey('CtrlD');+ // EOF must be DETECTED (immediate keyless fallback), not absorbed until+ // the readLineSafe fallback timer fires — this is the shared branch the+ // deleted harness's comments falsely claimed to cover.+ await session.waitFor(/keyless mode/i, { timeoutMs: 60_000, since: afterMenu });+ expect(Date.now() - tEof).toBeLessThan(PROMPT_LIVENESS_MS);+ // Deliberate early close: after EOF, Bun's stdin never yields another+ // line while isTTY stays true, so the LATER mode picker sits its full+ // 60s fallback before init completes (probed: exit at ~61s). That is a+ // pre-existing product stall (readLineSafe does not latch EOF), filed+ // in TODOS.md — running init to completion here would bake that 60s+ // stall into every required-CI serial run.+ } finally {+ await session.close();+ }+ }, 300_000);+});diff --git a/test/init-provider-picker.test.ts b/test/init-provider-picker.test.tsindex 0e56f923b5..6fbbc7483d 100644--- a/test/init-provider-picker.test.ts+++ b/test/init-provider-picker.test.ts@@ -1,10 +1,10 @@/*** Picker unit tests — exercise the pure paths (env filtering, caveat- * messaging, null returns on bad input). TTY-input flows (numbered- * selection happy path, Ctrl-D, timeout) are covered E2E via- * cli-pty-runner.ts because mocking readLineSafe at the unit boundary- * leaks across files in the shard process per CLAUDE.md test-isolation- * rules.+ * messaging, null returns on bad input). The real TTY-input flow (menu+ * rendering, typed selection, persistence) is covered by the real-PTY+ * serial test at test/init-picker-pty.serial.test.ts; mocking readLineSafe+ * at the unit boundary would leak across files in the shard process per+ * CLAUDE.md test-isolation rules.*/import { describe, test, expect } from 'bun:test';