Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

status: --funnel, a local opt-in adoption funnel (D8): counts per stage, off by default, nothing leaves the machine

garrytan213e49961076
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.md
index 6ba2e3e41f..7999c73ee6 100644
--- a/docs/architecture/key-files/commands-5.md
+++ b/docs/architecture/key-files/commands-5.md
@@ -42,4 +42,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/sources.ts` — `gbrain sources {list,add,remove,archive,restore,archived,purge,current,status,audit,refresh}`. `refresh` dispatches to `src/commands/sources-refresh.ts` (argument parsing, stdout text or `--json` result/refusal objects, exit 1 on refusal or an unfinished sync; protocol in `src/core/persistence/worktree-refresh.ts`). `current [--json]` calls `resolveSourceWithTier()` and prints `source_id`, `tier` (`flag | env | dotfile | local_path | brain_default | seed_default`), and optional `detail` (decision table in `skills/conventions/brain-routing.md`). `status [--json]` — read-only per-source dashboard (last sync, staleness, page count, embedding coverage, unacked failures); thin wrapper around `buildSyncStatusReport` + `printSyncStatusReport` from `src/commands/sync.ts`; `--json` emits stable `{schema_version: 1, sources, ...}` on stdout; filters input to `local_path IS NOT NULL AND archived IS NOT TRUE`. `audit <id> [--json]` — read-only dry-run disk scan for size distribution + would-blocks + junk-pattern hits WITHOUT touching the DB; walks `sources.local_path`, reads each markdown file, runs `assessContent()` from `src/core/content-sanity.ts`, aggregates by verdict (`ok | warn_oversize | hard_block_junk_pattern`). The live `runStatus` health table gains a `BACKFILL` column between `EMBED` and `FAILS` (`active(N)` beats `queued(N)` beats `idle`, from `SourceMetrics.backfill_active` / `backfill_queued` in `src/core/source-health.ts`) so operators see deferred `embed-backfill` minion work after `sync --all` exits 0; `jobCountsBySource` in `source-health.ts` widens its `minion_jobs` SQL with two `COUNT(*) FILTER (WHERE name = 'embed-backfill' AND ...)` aggregates (best-effort, all-0 on pre-minions brains). `remove` pre-checks OAuth-client referents (guided refusal via `formatClientReferentsBlock` — the raw FK violation never reaches the operator), then commits the row DELETE atomically with an in-tx referents re-check (a registration racing the pre-check maps to the same guided refusal); durability-scaffolding teardown (`unhardenBrainRepo`: hook/cron/credential) runs only AFTER the commit, so a refused delete leaves the scaffolding intact. `purge` runs the same referents pre-check before its hard DELETE. Pinned by `test/content-sanity.test.ts`, `test/import-file-content-sanity.test.ts`, `test/source-health.test.ts`.
+- `src/commands/status-funnel.ts` — `gbrain status --funnel [--json] [--enable | --delete]` (D8 adoption funnel): engine-free, dispatched from `src/cli/main.ts` before any connect so it works before `gbrain init` and on a thin client; reads and writes only the local record through `src/core/funnel.ts`. Guide: `docs/guides/adoption-funnel.md`. Tests: `test/funnel.test.ts`, `test/funnel-cli.test.ts`.
+
- `src/commands/storage.ts` — `gbrain storage status [--repo P] [--json]`. Split into pure data (`getStorageStatus`) + JSON formatter + human formatter (ASCII-only) matching the `orphans.ts` pattern. `PageCountsByTier` and `DiskUsageByTier` are distinct nominal types so swaps fail at compile time. The repo and the counted source come from `resolveRestoreTarget` (`src/core/restore-target.ts`, the `export --restore-only` rule), and a page is listed missing exactly when that export would restore it (`isDbOnly`, then `restoreFilePath` in the page source's `scannerSlugRootMode` and `nativeFileTarget`: the recorded `source_path`, else `<slug>.md`, absent; the repo walk answers without a per-page syscall whenever it saw that exact file as a regular file under real directories, and a recorded path starting with the repo's path inside its git checkout, which export re-anchors, takes the full check), so the printed `Use: gbrain export --restore-only --source <id> --repo <path>` (the path passed through `shellQuote`, `src/core/shell-quote.ts`) writes exactly the listed files into `--dir` (default `./export`, not the repo). An unsafe recorded path or a symlinked/ambiguous file target (`OperationError` from `nativeFileTarget`) becomes one warning per reason (lowest slug plus a count of further pages) plus the refusal export would give, printed even when no file is missing; a repo whose own owner (`resolveSourceForRepoPath`: dotfile, then longest registered `local_path`) is archived is refused too (unless an active source is registered at the repo's exact path, which owns it outright), although export's exact-path rule would fall back to the only active source; a refused rule prints `Cannot suggest a restore command:` and falls back to the `--repo` / default-source path, counting the active repo owner's pages (dotfile, then longest registered `local_path`) or every source's pages when no active source owns it. `restoreSource` / `restoreRefusal` carry this in the JSON result. Pinned by `test/storage-restore-hint.test.ts`.
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.md
index dc0df7664a..35d2a6030d 100644
--- a/docs/architecture/key-files/core-utilities-1.md
+++ b/docs/architecture/key-files/core-utilities-1.md
@@ -45,6 +45,7 @@ The `src/core/cycle.ts` entry is on its own page: [Core Cycle primitive](core-cy
- `src/core/filing-audit.ts` + `skills/_brain-filing-rules.json` — Check 6 of `check-resolvable`. Parses `writes_pages:` / `writes_to:` frontmatter on skills and audits their filing claims against the filing-rules JSON (error severity). Internal `parseFrontmatter` is a thin wrapper over the shared `src/core/skill-frontmatter.ts` parser so both filing-audit and skill-brain-first read the same shape (`tools?`, `triggers?`, `brain_first?: 'exempt'`, typed `brain_first_typo`) from one source of truth.
- `src/core/fts-language.ts` — Single source for the FTS configuration name (write side, #6370: `engines-2.md`). `getFtsLanguage()` resolves `GBRAIN_FTS_LANGUAGE` (default `english`), validates against `/^[a-z][a-z0-9_]*$/` (tsvector config names can't be bound as parameters, so the value is interpolated into raw SQL — the allowlist regex is the injection guard; invalid values warn once and fall back to `english`), and caches on first read (`resetFtsLanguageCache()` is test-only). Consumed by both engines' `searchKeyword`/`searchKeywordChunks` (`websearch_to_tsquery` query side), the `configurable_fts_language` migration, and `reindex-search-vector` (write-side trigger functions). `factsFtsDocument`/`factsFtsIndexSql` build the facts keyword document and the `idx_facts_fts` definition (v237); `src/core/facts/fts-index.ts` `ensureFactsFtsIndex` builds it under `idx_facts_fts_next` (CONCURRENTLY on Postgres, via `buildIndexOnline`) and swaps it in with one rename transaction, dropping the old index last; every interrupted step converges on a rerun. Pinned by `test/fts-language.serial.test.ts` + `test/fts-language-migration.serial.test.ts` (includes the `'; DROP TABLE pages; --` injection cases).
+- `src/core/funnel.ts` — D8 adoption funnel, local and opt-in: recording happens only while `~/.gbrain/funnel.jsonl` exists (created by `gbrain status --funnel --enable`, removed by `--delete`); each line is `{event, at, session}` with no content, and `save`/`recall` are written once per process. Hooks: `remember` (`recordRememberOutcome`: superseded = correction), `forget`/`forget_fact` (withdrawal), `takes_supersede` (correction), `put_page` (save), search/query `searchOutput` and `recall` (`recordRecallOutcome`), `runImport` (import, imported > 0), `runInit` (clean install on a fresh home). `readFunnelReport` turns the record into counts per stage, never rates. No network, no DB table.
- `src/core/latin-fold.ts` — leaf text primitive (no engine/graph imports): `NON_DECOMPOSING_LATIN`, the lowercase-keyed table of the eleven Latin stroke/bar/ligature letters Unicode gives no decomposition (đ ð ø ł ħ ŧ ı ß æ œ þ), + `foldNonDecomposingLatin(s)`. Call it AFTER lowercasing and AFTER the combining-mark strip so composed forms reduce in one pass (ǿ → ø → o). Consumers: `entities/resolve.ts:slugify` (entity fallback slugs — pre-fold `Đăng Example` collided onto `ang-example` and an all-stroke name slugged to empty) and `link-extraction.ts:normalizeBasename` (basename-index keys + dir-hint candidates). Deliberately NOT applied to `sync.ts:slugifySegment` — the page-slug grammar keeps these letters (#3417) — so the dir-hint candidate step in `makeResolver` / the FS resolver tries both forms.
diff --git a/docs/guides/adoption-funnel.md b/docs/guides/adoption-funnel.md
new file mode 100644
index 0000000000..7139ead936
--- /dev/null
+++ b/docs/guides/adoption-funnel.md
@@ -0,0 +1,64 @@
+# Adoption funnel (`gbrain status --funnel`)
+
+gbrain can keep a local count of how far an install has got: installed, data
+imported, memory recalled in a later session, a correction applied, a
+withdrawal applied, and use a week or more after install. It is **off by
+default**, it never leaves your machine, and it records counts and dates only.
+You decide whether to share the numbers.
+
+## Turn it on
+
+```bash
+gbrain status --funnel --enable
+```
+
+This creates `~/.gbrain/funnel.jsonl` (under `GBRAIN_HOME` when that is set).
+Recording happens only while that file exists. To count the install itself,
+turn it on before `gbrain init`; the command needs no brain.
+
+## View it
+
+```bash
+gbrain status --funnel # one line per stage
+gbrain status --funnel --json # the same as one JSON document, to share if you choose
+```
+
+```json
+{"schema_version":1,"enabled":true,"enabled_on":"2026-10-14","stages":[
+ {"stage":"clean_install","count":1,"first_on":"2026-10-14"},
+ {"stage":"import_useful_data","count":1,"first_on":"2026-10-14"},
+ {"stage":"recall_new_session","count":3,"first_on":"2026-10-15"},
+ {"stage":"correction_applied","count":1,"first_on":"2026-10-16"},
+ {"stage":"withdrawal_applied","count":0,"first_on":null},
+ {"stage":"use_after_seven_days","count":2,"first_on":"2026-10-21"}]}
+```
+
+The report gives counts, never rates. With recording off it prints
+`"enabled":false` and zero counts, and writes nothing.
+
+| Stage | Counted when |
+|---|---|
+| `clean_install` | `gbrain init` creates a new brain (no earlier config) |
+| `import_useful_data` | an import (`gbrain import`, or a full sync) saves at least one page |
+| `recall_new_session` | a session's `search`, `query` or `recall` returns at least one row, and an earlier session had saved, imported or corrected memory; counted once per session. Whether the answer was right is not judged here |
+| `correction_applied` | a committed correction: `remember` superseding a fact (including `replaces`), or `takes_supersede` |
+| `withdrawal_applied` | a committed withdrawal: `forget` or `forget_fact` |
+| `use_after_seven_days` | distinct days with any of the above, seven or more days after the clean install (or after recording was turned on, without one) |
+
+A session is one gbrain process: one CLI command, or one `gbrain serve` run. Events are recorded where the operation runs: on a thin client, the brain host's funnel counts them (if its owner turned it on), not the client's.
+
+## What the file holds
+
+One line per event: `{"event":"recall","at":"<time>","session":"<when the process started>"}`.
+No page content, queries, slugs, fact ids or names, and no network request:
+nothing is uploaded. `save` and `recall` lines are written at most once per
+session, so the file grows with sessions, not with calls.
+
+## Delete it
+
+```bash
+gbrain status --funnel --delete
+```
+
+This removes the file, which also turns recording off. Deleting
+`~/.gbrain/funnel.jsonl` by hand does the same.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 60a7bb923b..e8eefaec96 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -25,7 +25,7 @@ src/core/postgres-engine.ts 3049 ratchet +1 System One v1 evals: search arms cla
src/core/search/hybrid.ts 1648 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook)
src/core/types.ts 2315 ratchet +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts)
src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)
-src/commands/init.ts 1882 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts)
+src/commands/init.ts 1884 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts); +2 D8 funnel: a fresh init counts one clean_install when the opt-in funnel is on (core/funnel.ts)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)
src/commands/bootstrap.ts 2147 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts)
@@ -40,7 +40,7 @@ src/core/config.ts 1971 ratchet +2 W5: search.page_rank_cut / page_rank_cut_fact
src/core/persistence/sync-run.ts 1684 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next
src/core/bootstrap/harness.ts 2615 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
-src/core/ops/pages.ts 704 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts)
+src/core/ops/pages.ts 705 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on
src/core/search/mode.ts 1669 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part)
src/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)
src/commands/doctor/checks/extraction-sync.ts 1523 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts
diff --git a/src/cli/help/status.ts b/src/cli/help/status.ts
index ccc2d39eba..33a0c3f936 100644
--- a/src/cli/help/status.ts
+++ b/src/cli/help/status.ts
@@ -3,16 +3,20 @@ import type { CliHelpSpec } from '../command-table.ts';
export const help: CliHelpSpec = {
summary: 'One-screen operational snapshot: sync, cycle, locks, workers, queue and autopilot.',
- usage: 'gbrain status [--json] [--section sync|cycle|locks|workers|queue|autopilot] [--fast | --deadline-ms <ms>]',
+ usage: 'gbrain status [--json] [--section sync|cycle|locks|workers|queue|autopilot] [--fast | --deadline-ms <ms>] | gbrain status --funnel [--json] [--enable | --delete]',
flags: [
{ name: '--json', type: 'boolean', desc: 'Print the snapshot as one JSON document.' },
{ name: '--section', type: 'enum', values: ['sync', 'cycle', 'locks', 'workers', 'queue', 'autopilot'], desc: 'Report only this section.' },
{ name: '--fast', type: 'boolean', desc: 'Bound the snapshot to 2000 ms; a section past the budget returns stale with a warning.' },
{ name: '--deadline-ms', type: 'number', desc: 'Bound the snapshot to this many milliseconds (positive).' },
+ { name: '--funnel', type: 'boolean', desc: 'Show the local, opt-in adoption funnel (counts per stage, never rates; nothing leaves this machine).' },
+ { name: '--enable', type: 'boolean', desc: 'With --funnel: start recording funnel counts in ~/.gbrain/funnel.jsonl (off by default).' },
+ { name: '--delete', type: 'boolean', desc: 'With --funnel: delete the funnel record, which stops recording.' },
],
examples: [
'gbrain status',
'gbrain status --json --fast',
'gbrain status --section queue --json',
+ 'gbrain status --funnel --json',
],
};
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 4b71f2810a..cf777c0cb8 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -2257,6 +2257,7 @@ async function routeEngineFreeSubcommands(command: string, args: string[]): Prom
// through to the engine-connected dispatch path below. (`args` here is the
// subArgs slice already — no need to re-slice past the command.)
if (command === 'status') {
+ if (args.includes('--funnel')) { setCliExitVerdict((await import('../commands/status-funnel.ts')).runStatusFunnel(args).exitCode); return true; }
const cfgPre = loadConfig();
if (cfgPre && isThinClient(cfgPre)) {
const { runStatus } = await import('../commands/status.ts');
diff --git a/src/commands/import.ts b/src/commands/import.ts
index f68f15a27f..dfa192f8d8 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -3,6 +3,7 @@ import { importFenceTally, type FencesNormalized } from '../core/fence-repair/re
import { opError } from '../core/ops/contract.ts';
import { hasSourceFilesystemLock, withSourceFilesystemLock, currentSourceFilesystemSignal } from '../core/minions/source-filesystem.ts';
import { readdirSync, lstatSync, existsSync, mkdirSync } from 'fs';
+import { recordFunnelEvent } from '../core/funnel.ts';
import { execFileSync } from 'child_process';
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'path';
import { cpus, totalmem } from 'os';
@@ -1207,6 +1208,7 @@ export async function runImport(
}
if (imported > 0 && !opts.managedBookmark) await refreshProjectionStatistics(engine, imported);
+ if (imported > 0) recordFunnelEvent('import');
return {
imported, skipped, errors, chunksCreated, failures,
...(resealSummary ? { resealed: resealSummary } : {}), ...fenceTally.fields(),
diff --git a/src/commands/init.ts b/src/commands/init.ts
index afddd9a0a7..14f59420f9 100644
--- a/src/commands/init.ts
+++ b/src/commands/init.ts
@@ -26,7 +26,9 @@ import type { McpSurface } from '../mcp/surface.ts';
/** D2: `--json` writes exactly one document, after whichever branch ran (see init-json.ts). */
export async function runInit(args: string[]) {
+ const fresh = !existsSync(configPath());
await runInitBranches(args);
+ if (fresh && existsSync(configPath())) (await import('../core/funnel.ts')).recordFunnelEvent('clean_install');
if (args.includes('--json')) await flushInitJsonResult();
}
diff --git a/src/commands/status-funnel.ts b/src/commands/status-funnel.ts
new file mode 100644
index 0000000000..f892794e2a
--- /dev/null
+++ b/src/commands/status-funnel.ts
@@ -0,0 +1,44 @@
+/**
+ * `gbrain status --funnel` (D8): the local, opt-in adoption funnel.
+ *
+ * gbrain status --funnel [--json] counts per stage (never rates)
+ * gbrain status --funnel --enable start recording (creates ~/.gbrain/funnel.jsonl; GBRAIN_HOME moves it)
+ * gbrain status --funnel --delete delete the record, which stops recording
+ *
+ * Engine-free: it reads and writes only the local funnel file, so it works
+ * before `gbrain init` and on a thin client. Nothing is sent anywhere.
+ */
+
+import { deleteFunnel, enableFunnel, funnelPath, readFunnelReport } from '../core/funnel.ts';
+
+export function runStatusFunnel(
+ args: string[],
+ opts: { stdout?: (s: string) => void; stderr?: (s: string) => void } = {},
+): { exitCode: 0 | 2 } {
+ const stdout = opts.stdout ?? ((s: string) => process.stdout.write(s));
+ const stderr = opts.stderr ?? ((s: string) => process.stderr.write(s));
+ const enable = args.includes('--enable');
+ const del = args.includes('--delete');
+ const other = args.filter(a => !['--funnel', '--enable', '--delete', '--json'].includes(a));
+ if ((enable && del) || other.length) {
+ stderr(`gbrain status --funnel: ${enable && del ? 'choose --enable or --delete, not both' : `unexpected argument ${other[0]}`}. Usage: gbrain status --funnel [--json] [--enable | --delete]\n`);
+ return { exitCode: 2 };
+ }
+ if (enable) enableFunnel();
+ const deleted = del ? deleteFunnel() : false;
+ const report = readFunnelReport();
+ if (args.includes('--json')) {
+ stdout(JSON.stringify(report) + '\n');
+ return { exitCode: 0 };
+ }
+ const lines: string[] = [];
+ if (del) lines.push(deleted ? `Deleted ${funnelPath()}; recording is off.` : 'No funnel record to delete; recording is off.');
+ else if (!report.enabled) lines.push('Adoption funnel: off (nothing is recorded).', 'Turn it on with `gbrain status --funnel --enable`. It stays on this machine.');
+ else {
+ lines.push(`Adoption funnel: on since ${report.enabled_on ?? 'unknown'}, recorded in ${funnelPath()} (counts and dates only; nothing leaves this machine).`);
+ for (const s of report.stages) lines.push(` ${s.stage.padEnd(22)} ${String(s.count).padStart(5)}${s.first_on ? ` first ${s.first_on}` : ''}`);
+ lines.push('Share it with `gbrain status --funnel --json` if you choose; delete it with `gbrain status --funnel --delete`.');
+ }
+ stdout(lines.join('\n') + '\n');
+ return { exitCode: 0 };
+}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 0399642285..a9fe8410c1 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -125,7 +125,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--wait', '--yes'],
'smoke-test': ['--brain', '--help', '--json', '--source'],
'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--origin', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
- 'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
+ 'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--delete', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--session', '--source', '--timeout', '--wait'],
'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
diff --git a/src/core/funnel.ts b/src/core/funnel.ts
new file mode 100644
index 0000000000..350bb6aefe
--- /dev/null
+++ b/src/core/funnel.ts
@@ -0,0 +1,178 @@
+/**
+ * Adoption funnel (D8): a local, opt-in record of how far one install got.
+ *
+ * Off by default. Recording happens only while `~/.gbrain/funnel.jsonl` (under GBRAIN_HOME when set)
+ * exists, and only `gbrain status --funnel --enable` creates it; with no file,
+ * every recorder below is a single `existsSync` and writes nothing.
+ * `gbrain status --funnel --delete` removes the file, which turns recording off.
+ *
+ * Each line is `{event, at, session}`: an event name, when it happened and
+ * when the recording process started. Never content, queries, slugs, ids or
+ * names. Nothing here touches the network; the user decides whether to share
+ * `gbrain status --funnel --json`, which reports counts, never rates.
+ *
+ * Appends are one short line each (POSIX O_APPEND keeps concurrent writers
+ * line-atomic); `save` and `recall` are written at most once per process, so
+ * the file grows by sessions, not by calls. A recorder never throws.
+ */
+
+import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
+import { dirname } from 'node:path';
+import { gbrainPath } from './config.ts';
+
+export const FUNNEL_SCHEMA_VERSION = 1 as const;
+
+export type FunnelEvent = 'enabled' | 'clean_install' | 'import' | 'save' | 'recall' | 'correction' | 'withdrawal';
+
+export const FUNNEL_STAGES = [
+ 'clean_install',
+ 'import_useful_data',
+ 'recall_new_session',
+ 'correction_applied',
+ 'withdrawal_applied',
+ 'use_after_seven_days',
+] as const;
+export type FunnelStage = (typeof FUNNEL_STAGES)[number];
+
+export interface FunnelLine { event: FunnelEvent; at: string; session: string }
+
+export interface FunnelReport {
+ schema_version: typeof FUNNEL_SCHEMA_VERSION;
+ enabled: boolean;
+ enabled_on: string | null;
+ stages: Array<{ stage: FunnelStage; count: number; first_on: string | null }>;
+}
+
+const ONCE_PER_SESSION: ReadonlySet<FunnelEvent> = new Set(['save', 'recall']);
+const WRITES: ReadonlySet<FunnelEvent> = new Set(['import', 'save', 'correction']);
+const USE: ReadonlySet<FunnelEvent> = new Set(['import', 'save', 'recall', 'correction', 'withdrawal']);
+const DAY_MS = 86_400_000;
+
+const sessionStarted = new Date(performance.timeOrigin).toISOString();
+const recordedThisSession = new Set<FunnelEvent>();
+let pathOverride: string | null = null;
+
+/** Test-only seam (the test-isolation lint forbids mutating GBRAIN_HOME). @internal */
+export function __setFunnelPathForTests(path: string | null): void {
+ pathOverride = path;
+ recordedThisSession.clear();
+}
+
+export function funnelPath(): string {
+ return pathOverride ?? gbrainPath('funnel.jsonl');
+}
+
+export function funnelEnabled(): boolean {
+ return existsSync(funnelPath());
+}
+
+export function recordFunnelEvent(event: FunnelEvent): void {
+ try {
+ const path = funnelPath();
+ if (!existsSync(path)) return;
+ if (ONCE_PER_SESSION.has(event)) {
+ if (recordedThisSession.has(event)) return;
+ recordedThisSession.add(event);
+ }
+ const line: FunnelLine = { event, at: new Date().toISOString(), session: sessionStarted };
+ appendFileSync(path, JSON.stringify(line) + '\n');
+ } catch {
+ /* the funnel is never fatal */
+ }
+}
+
+/** `promise.then(funnelPassThrough('save'))`: record the event once the write committed, pass the result on. */
+export function funnelPassThrough<T>(event: FunnelEvent): (result: T) => T {
+ return result => { recordFunnelEvent(event); return result; };
+}
+
+/** A remember result: `superseded` is a correction, anything else that committed is a save. */
+export function recordRememberOutcome(result: unknown): void {
+ const status = (result as { status?: unknown } | null)?.status;
+ if (status === 'superseded') recordFunnelEvent('correction');
+ else if (status === 'inserted' || status === 'duplicate') recordFunnelEvent('save');
+}
+
+/** A read that returned at least one fact or page counts as a recall. */
+export function recordRecallOutcome(result: unknown): void {
+ const r = result as { facts?: unknown; results?: unknown } | unknown[] | null;
+ const returned = Array.isArray(r) ? r.length
+ : (Array.isArray(r?.facts) ? r.facts.length : 0) + (Array.isArray(r?.results) ? r.results.length : 0);
+ if (returned > 0) recordFunnelEvent('recall');
+}
+
+/** Turn recording on. Idempotent: an existing file keeps its history. */
+export function enableFunnel(): void {
+ const path = funnelPath();
+ if (existsSync(path)) return;
+ mkdirSync(dirname(path), { recursive: true });
+ const line: FunnelLine = { event: 'enabled', at: new Date().toISOString(), session: sessionStarted };
+ appendFileSync(path, JSON.stringify(line) + '\n', { mode: 0o600 });
+}
+
+/** Delete the record, which also turns recording off. Returns whether a file was removed. */
+export function deleteFunnel(): boolean {
+ const path = funnelPath();
+ if (!existsSync(path)) return false;
+ rmSync(path, { force: true });
+ return true;
+}
+
+function readLines(path: string): FunnelLine[] {
+ const out: FunnelLine[] = [];
+ for (const raw of readFileSync(path, 'utf8').split('\n')) {
+ if (!raw.trim()) continue;
+ try {
+ const l = JSON.parse(raw) as FunnelLine;
+ if (typeof l.event === 'string' && typeof l.at === 'string' && typeof l.session === 'string' && !Number.isNaN(Date.parse(l.at))) out.push(l);
+ } catch { /* a torn line is skipped */ }
+ }
+ return out;
+}
+
+const day = (iso: string) => iso.slice(0, 10);
+
+/**
+ * Counts per stage:
+ * - clean_install: `gbrain init` runs that created a new brain;
+ * - import_useful_data: imports that saved at least one page;
+ * - recall_new_session: sessions whose read returned something, started after
+ * an earlier session saved, imported or corrected memory (correctness is
+ * Cat 41's `correct_then_recall`, not judged here);
+ * - correction_applied / withdrawal_applied: committed corrections (`remember`
+ * superseding a fact, `takes_supersede`) and withdrawals (`forget`, `forget_fact`);
+ * - use_after_seven_days: distinct days with any use, seven or more days after
+ * the clean install (or after recording was turned on, without one).
+ */
+export function readFunnelReport(): FunnelReport {
+ const path = funnelPath();
+ if (!existsSync(path)) {
+ return { schema_version: FUNNEL_SCHEMA_VERSION, enabled: false, enabled_on: null, stages: FUNNEL_STAGES.map(stage => ({ stage, count: 0, first_on: null })) };
+ }
+ const lines = readLines(path).sort((a, b) => a.at.localeCompare(b.at));
+ const of = (e: FunnelEvent) => lines.filter(l => l.event === e);
+ const enabled = of('enabled')[0] ?? null;
+ const install = of('clean_install')[0] ?? null;
+ const writes = lines.filter(l => WRITES.has(l.event));
+ const newSessionRecalls = of('recall').filter(r => writes.some(w => w.at < r.session));
+ const anchor = install ?? enabled ?? lines[0] ?? null;
+ const laterUse = new Map<string, string>();
+ if (anchor) {
+ const from = Date.parse(day(anchor.at)) + 7 * DAY_MS;
+ for (const l of lines) if (USE.has(l.event) && Date.parse(day(l.at)) >= from && !laterUse.has(day(l.at))) laterUse.set(day(l.at), l.at);
+ }
+ const stage = (s: FunnelStage, rows: Array<{ at: string }>) => ({ stage: s, count: rows.length, first_on: rows[0] ? day(rows[0].at) : null });
+ return {
+ schema_version: FUNNEL_SCHEMA_VERSION,
+ enabled: true,
+ enabled_on: enabled ? day(enabled.at) : null,
+ stages: [
+ stage('clean_install', of('clean_install')),
+ stage('import_useful_data', of('import')),
+ stage('recall_new_session', newSessionRecalls),
+ stage('correction_applied', of('correction')),
+ stage('withdrawal_applied', of('withdrawal')),
+ stage('use_after_seven_days', [...laterUse.values()].map(at => ({ at }))),
+ ],
+ };
+}
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 54ca263712..e29b060f64 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -1,4 +1,5 @@
import { searchAnswerFeedback } from '../feedback/record.ts';
+import { recordFunnelEvent, recordRecallOutcome } from '../funnel.ts';
import { parseRelationalPlan } from '../search/relational-plan.ts';
import { loadSearchModeConfig, resolveSearchMode } from '../search/mode.ts';
import { WRITE_REQUEST_PARAM } from '../persistence/params.ts';
@@ -570,7 +571,7 @@ const recall: Operation = {
const budgetPacking = recallBudgetPacking(p.budget_policy, queryText, budgetTokens, { rows, packedFacts, searchResults, packedResults }, recallResultCost(delivery));
- return {
+ const out = {
facts: await withFactDateHeaders(ctx.engine, await stampRowTrust(ctx.engine, 'facts', packedFacts.map(r => ({ // #5575 A6: + trust_tier, origin, unconfirmed
id: r.id,
fact: r.fact,
@@ -635,6 +636,8 @@ const recall: Operation = {
...(budgetPacking ? { budget_packing: budgetPacking } : {}),
...(delivery ? { delivery } : {}),
};
+ recordRecallOutcome(out);
+ return out;
},
};
@@ -1244,7 +1247,9 @@ const forget_fact: Operation = {
handler: async (ctx, p) => {
if (ctx.dryRun) return { dry_run: true, action: 'forget_fact', id: p.id };
const { submitForgetMutation } = await import('../persistence/memory-mutations.ts');
- return submitForgetMutation(ctx, 'forget_fact', p);
+ const out = await submitForgetMutation(ctx, 'forget_fact', p);
+ recordFunnelEvent('withdrawal');
+ return out;
},
};
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index 0d2554a722..fce30c0054 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -1,4 +1,5 @@
import { pageMutationSource, submitPageMutation, validateMutationSlug } from '../persistence/page-mutations.ts';
+import { funnelPassThrough } from '../funnel.ts';
import { suffixedSlugDryRun } from '../persistence/suffixed-slug.ts';
import { AGENT_CONTENT_PARAMS, PAGE_MUTATION_PARAMS, CAPTURE_EVENT_PARAMS, CAPTURE_CLI_PROVENANCE_PARAMS, WRITE_WAIT_PARAM } from '../persistence/params.ts';
import { assertPurgeParams } from '../persistence/purge-params.ts';
@@ -353,7 +354,7 @@ const put_page: Operation = {
return { dry_run: true, action: 'put_page', slug: p.slug };
}
if (ctx.remote !== false && typeof p.slug === 'string') await assertLargePageAdmission(ctx.engine, p.slug, sourceId, p);
- return submitPageMutation(ctx, { operation: 'put_page', params: p }).catch(error => rethrowNamingRevisionSource(ctx, sourceId, p, error));
+ return submitPageMutation(ctx, { operation: 'put_page', params: p }).then(funnelPassThrough('save')).catch(error => rethrowNamingRevisionSource(ctx, sourceId, p, error));
},
cliHints: { name: 'put', positional: ['slug'], stdin: 'content' },
};
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 8d03a51bbd..b592c8a6d3 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -1,4 +1,5 @@
import { searchAnswerFeedback } from '../feedback/record.ts';
+import { recordRecallOutcome } from '../funnel.ts';
import type { RelationalPlanMeta } from '../search/relational-recall.ts';
import type { Notice } from '../agent-output.ts';
import { readHolders } from './context.ts';
@@ -117,6 +118,7 @@ function searchOutput(ctx: OperationContext, p: Record<string, unknown>, results
const shown = ctx.remote !== false || p.fields !== undefined ? { rows } : {};
// Stage timings are read last, after the returned rows are assembled (meta only, never content).
const emit = (output: { meta: Record<string, unknown> }, returned: SearchResult[]) => {
+ recordRecallOutcome(returned);
ctx.emitResponseMeta?.('retrieval', { ...output.meta, timings: timings.snapshot() });
return returned;
};
diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.ts
index 1bdb2681ec..1a27537df9 100644
--- a/src/core/ops/takes.ts
+++ b/src/core/ops/takes.ts
@@ -1,4 +1,5 @@
import { submitPageMutation } from '../persistence/page-mutations.ts';
+import { recordFunnelEvent } from '../funnel.ts';
import { MERGE_PRECONDITION_PARAMS, WRITE_REQUEST_PARAM } from '../persistence/params.ts';
/**
* Takes + think operation cluster — pure move from operations.ts (v0.46.x
@@ -500,7 +501,9 @@ const takes_supersede: Operation = {
enforceClientSlugFence(ctx, slug, 'takes_supersede');
validatePageSlug(slug); // defense-in-depth, matching put_page
if (ctx.dryRun) return { dry_run: true, action: 'takes_supersede', slug, row_num: p.row_num };
- return submitPageMutation(ctx, { operation: 'takes_supersede', params: p });
+ const out = await submitPageMutation(ctx, { operation: 'takes_supersede', params: p });
+ recordFunnelEvent('correction');
+ return out;
},
};
diff --git a/src/core/verbs.ts b/src/core/verbs.ts
index ae64497bea..4e9c2442c3 100644
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@ -203,6 +203,7 @@ const remember: Operation = {
const { privateFactNotice } = await import('./interop-notices.ts');
ctx.emitNotice?.(privateFactNotice((result as { id?: string | number } | null)?.id));
}
+ (await import('./funnel.ts')).recordRememberOutcome(result);
return result;
},
cliHints: { name: 'remember', positional: ['fact'] },
@@ -456,7 +457,9 @@ const forget: Operation = {
const { submitForgetMutation } = await import('./persistence/memory-mutations.ts');
const { runMemoryWrite } = await import('./persistence/verb-errors.ts');
- return runMemoryWrite(() => submitForgetMutation(ctx, 'forget', { ...p, id: rawId, ...(reason ? { reason } : {}) }));
+ const out = await runMemoryWrite(() => submitForgetMutation(ctx, 'forget', { ...p, id: rawId, ...(reason ? { reason } : {}) }));
+ (await import('./funnel.ts')).recordFunnelEvent('withdrawal');
+ return out;
},
// NO cliHints: `gbrain forget` is a CLI_ONLY command (recall.ts runForget)
// that dispatches BEFORE cliOps — a cliHint here would be silently
diff --git a/test/funnel-cli.test.ts b/test/funnel-cli.test.ts
new file mode 100644
index 0000000000..6968d75b59
--- /dev/null
+++ b/test/funnel-cli.test.ts
@@ -0,0 +1,44 @@
+/**
+ * D8 adoption funnel from the real CLI: `gbrain status --funnel` runs before
+ * any brain exists, `gbrain init` on a fresh home counts one clean install once
+ * recording is on, and a home that never turned it on gets no funnel file.
+ */
+import { afterAll, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+
+const repo = resolve(import.meta.dir, '..');
+const root = mkdtempSync(join(tmpdir(), 'gbrain-funnel-cli-'));
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+function gbrain(home: string, ...args: string[]) {
+ const child = Bun.spawnSync([process.execPath, '--no-env-file', join(repo, 'src', 'cli.ts'), ...args], {
+ env: { ...process.env, GBRAIN_HOME: home, DATABASE_URL: '', GBRAIN_DATABASE_URL: '', OPENAI_API_KEY: '', VOYAGE_API_KEY: '' },
+ stdout: 'pipe', stderr: 'pipe',
+ });
+ return { code: child.exitCode, out: child.stdout.toString(), err: child.stderr.toString() };
+}
+const INIT = ['init', '--pglite', '--no-embedding', '--non-interactive'];
+
+test('enabled before init: status --funnel works with no brain, and init counts one clean install', () => {
+ const home = join(root, 'on');
+ const off = gbrain(home, 'status', '--funnel', '--json');
+ expect(off.code).toBe(0);
+ expect(JSON.parse(off.out).enabled).toBe(false);
+ expect(existsSync(join(home, '.gbrain', 'funnel.jsonl'))).toBe(false);
+ expect(gbrain(home, 'status', '--funnel', '--enable').code).toBe(0);
+ const init = gbrain(home, ...INIT);
+ expect(init.code).toBe(0);
+ expect(gbrain(home, ...INIT).code).toBe(0);
+ const report = JSON.parse(gbrain(home, 'status', '--funnel', '--json').out);
+ expect(report.enabled).toBe(true);
+ expect(report.stages[0]).toMatchObject({ stage: 'clean_install', count: 1 });
+}, 120_000);
+
+test('never enabled: init writes no funnel file', () => {
+ const home = join(root, 'off');
+ expect(gbrain(home, ...INIT).code).toBe(0);
+ expect(existsSync(join(home, '.gbrain', 'config.json'))).toBe(true);
+ expect(existsSync(join(home, '.gbrain', 'funnel.jsonl'))).toBe(false);
+}, 120_000);
diff --git a/test/funnel-ops.test.ts b/test/funnel-ops.test.ts
new file mode 100644
index 0000000000..5fe2ee6074
--- /dev/null
+++ b/test/funnel-ops.test.ts
@@ -0,0 +1,103 @@
+/**
+ * D8 adoption funnel through the real operations (PGLite, MCP dispatch) and
+ * `runImport`: each committed event is recorded once recording is on, nothing
+ * is written while it is off, and no content reaches the record.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { execSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { runImport } from '../src/commands/import.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { __setFunnelPathForTests, enableFunnel } from '../src/core/funnel.ts';
+
+const root = mkdtempSync(join(tmpdir(), 'gbrain-funnel-ops-'));
+let engine: PGLiteEngine;
+let path: string;
+let n = 0;
+
+async function call(name: string, params: Record<string, unknown>) {
+ const res = await dispatchToolCall(engine, name, params, { remote: false });
+ return { isError: res.isError === true, body: JSON.parse(res.content[0]!.text!) as Record<string, any> };
+}
+const events = () => existsSync(path) ? readFileSync(path, 'utf8').trim().split('\n').map(l => (JSON.parse(l) as { event: string }).event) : [];
+
+async function journey() {
+ expect((await call('put_page', { slug: 'people/alice-example', content: '---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n\nAlice Example works on the zephyrine project.\n' })).isError).toBe(false);
+ const first = await call('remember', { fact: 'Alice Example works at acme-example.', provenance: 'test', entity: 'people/alice-example' });
+ expect(first.body.status).toBe('inserted');
+ const replaced = await call('remember', { fact: 'Alice Example left acme-example in 2026.', provenance: 'test', entity: 'people/alice-example', replaces: first.body.id });
+ expect(replaced.body.status).toBe('superseded');
+ const searched = await call('search', { query: 'zephyrine' });
+ expect(searched.isError).toBe(false);
+ expect((searched.body as unknown as unknown[]).length).toBeGreaterThan(0);
+ const other = await call('remember', { fact: 'Alice Example prefers async standups.', provenance: 'test', entity: 'people/alice-example' });
+ expect((await call('forget', { id: other.body.id })).isError).toBe(false);
+ expect((await call('recall', { entity: 'people/alice-example' })).isError).toBe(false);
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+afterAll(async () => {
+ __setFunnelPathForTests(null);
+ resetGateway();
+ await engine.disconnect();
+ rmSync(root, { recursive: true, force: true });
+});
+beforeEach(async () => {
+ await disposePersistenceConsumer(engine);
+ await resetPgliteState(engine);
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });
+ const dir = join(root, `case-${n++}`);
+ path = join(dir, 'funnel.jsonl');
+ __setFunnelPathForTests(path);
+});
+
+describe('funnel through operations', () => {
+ test('off by default: a full save, correct, search, forget, recall journey writes nothing', async () => {
+ await journey();
+ expect(existsSync(path)).toBe(false);
+ });
+
+ test('on: one save and one recall for the session, the correction and the withdrawal; no content in the record', async () => {
+ enableFunnel();
+ await journey();
+ expect(events()).toEqual(['enabled', 'save', 'correction', 'recall', 'withdrawal']);
+ expect(readFileSync(path, 'utf8')).not.toMatch(/alice|acme|zephyrine|people\//i);
+ });
+
+ test('on: takes_supersede is a correction and forget_fact a withdrawal', async () => {
+ await call('put_page', { slug: 'companies/acme-example', content: '---\ntitle: Acme Example\ntype: company\n---\n# Acme Example\n\nA company.\n' });
+ expect((await call('takes_add', { slug: 'companies/acme-example', claim: 'Acme Example will ship in Q3.', kind: 'take', holder: 'world' })).isError).toBe(false);
+ const fact = await call('remember', { fact: 'Acme Example is based in Lisbon.', provenance: 'test', entity: 'companies/acme-example' });
+ enableFunnel();
+ const superseded = await call('takes_supersede', { slug: 'companies/acme-example', row_num: 1, claim: 'Acme Example will ship in Q4.' });
+ expect(superseded.isError).toBe(false);
+ expect((await call('forget_fact', { id: Number(fact.body.id) })).isError).toBe(false);
+ expect(events()).toEqual(['enabled', 'correction', 'withdrawal']);
+ });
+
+ test('on: an import that saved pages is recorded; an import that saved none is not', async () => {
+ enableFunnel();
+ const repo = join(root, `repo-${n}`);
+ mkdirSync(repo);
+ execSync('git init -q && git config user.email [email protected] && git config user.name T', { cwd: repo, stdio: 'pipe' });
+ writeFileSync(join(repo, 'note.md'), '---\ntype: note\n---\n# Note\n\nbody\n');
+ execSync('git add note.md && git commit -qm seed', { cwd: repo, stdio: 'pipe' });
+ await withEnv({ GBRAIN_HOME: join(root, `home-${n}`) }, async () => {
+ expect((await runImport(engine, [repo, '--no-embed', '--json'])).imported).toBe(1);
+ expect((await runImport(engine, [repo, '--no-embed', '--json'])).imported).toBe(0);
+ });
+ expect(events()).toEqual(['enabled', 'import']);
+ });
+});
diff --git a/test/funnel.test.ts b/test/funnel.test.ts
new file mode 100644
index 0000000000..7be0b72aa4
--- /dev/null
+++ b/test/funnel.test.ts
@@ -0,0 +1,187 @@
+/**
+ * D8 adoption funnel: off by default (nothing written), counts per stage from
+ * the local record, no content fields, and the pinned `--funnel --json` shape.
+ */
+import { afterAll, afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ __setFunnelPathForTests, deleteFunnel, enableFunnel, funnelEnabled, readFunnelReport, recordFunnelEvent,
+ recordRecallOutcome, recordRememberOutcome, type FunnelEvent,
+} from '../src/core/funnel.ts';
+import { runStatusFunnel } from '../src/commands/status-funnel.ts';
+
+const root = mkdtempSync(join(tmpdir(), 'gbrain-funnel-'));
+let dir: string;
+let path: string;
+let n = 0;
+
+beforeEach(() => {
+ dir = join(root, `case-${n++}`);
+ path = join(dir, 'funnel.jsonl');
+ __setFunnelPathForTests(path);
+});
+afterEach(() => __setFunnelPathForTests(null));
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+const lines = () => readFileSync(path, 'utf8').trim().split('\n').map(l => JSON.parse(l) as Record<string, string>);
+const events = () => lines().map(l => l.event);
+const ALL: FunnelEvent[] = ['clean_install', 'import', 'save', 'recall', 'correction', 'withdrawal'];
+
+describe('default off', () => {
+ test('no record file: every recorder writes nothing and creates no directory', () => {
+ for (const e of ALL) recordFunnelEvent(e);
+ recordRememberOutcome({ status: 'superseded' });
+ recordRememberOutcome({ status: 'inserted' });
+ recordRecallOutcome([{ slug: 'x' }]);
+ expect(funnelEnabled()).toBe(false);
+ expect(existsSync(dir)).toBe(false);
+ });
+
+ test('the report says off with zero counts', () => {
+ expect(readFunnelReport()).toEqual({
+ schema_version: 1, enabled: false, enabled_on: null,
+ stages: [
+ { stage: 'clean_install', count: 0, first_on: null },
+ { stage: 'import_useful_data', count: 0, first_on: null },
+ { stage: 'recall_new_session', count: 0, first_on: null },
+ { stage: 'correction_applied', count: 0, first_on: null },
+ { stage: 'withdrawal_applied', count: 0, first_on: null },
+ { stage: 'use_after_seven_days', count: 0, first_on: null },
+ ],
+ });
+ });
+});
+
+describe('recording', () => {
+ test('enable writes one line; delete removes the record and turns recording off', () => {
+ enableFunnel();
+ enableFunnel();
+ expect(events()).toEqual(['enabled']);
+ expect(deleteFunnel()).toBe(true);
+ recordFunnelEvent('correction');
+ expect(existsSync(path)).toBe(false);
+ expect(deleteFunnel()).toBe(false);
+ });
+
+ test('save and recall are recorded once per session; the other events every time', () => {
+ enableFunnel();
+ for (let i = 0; i < 3; i++) for (const e of ALL) recordFunnelEvent(e);
+ const counts = Object.fromEntries(ALL.map(e => [e, events().filter(x => x === e).length]));
+ expect(counts).toEqual({ clean_install: 3, import: 3, save: 1, recall: 1, correction: 3, withdrawal: 3 });
+ });
+
+ test('remember outcomes: superseded is a correction, inserted or duplicate a save, a refusal nothing', () => {
+ enableFunnel();
+ recordRememberOutcome({ status: 'superseded', id: '7' });
+ recordRememberOutcome({ status: 'inserted' });
+ recordRememberOutcome({ batch: true });
+ recordRememberOutcome(null);
+ expect(events()).toEqual(['enabled', 'correction', 'save']);
+ });
+
+ test('a recall counts only when it returned something (search rows, recall facts or results)', () => {
+ enableFunnel();
+ recordRecallOutcome([]);
+ recordRecallOutcome({ facts: [], results: [] });
+ expect(events()).toEqual(['enabled']);
+ recordRecallOutcome({ facts: [], results: [{}] });
+ expect(events()).toEqual(['enabled', 'recall']);
+ });
+
+ test('lines hold an event name and two timestamps, nothing else', () => {
+ enableFunnel();
+ for (const e of ALL) recordFunnelEvent(e);
+ recordRememberOutcome({ status: 'superseded', fact: 'Alice Example left acme-example.', entity_slug: 'people/alice-example' });
+ const iso = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
+ for (const l of lines()) {
+ expect(Object.keys(l).sort()).toEqual(['at', 'event', 'session']);
+ expect(l.at).toMatch(iso);
+ expect(l.session).toMatch(iso);
+ }
+ expect(readFileSync(path, 'utf8')).not.toMatch(/alice|acme|people\//i);
+ });
+});
+
+describe('counts per stage', () => {
+ const write = (rows: Array<[FunnelEvent, string, string]>) =>
+ writeFileSync(path, rows.map(([event, at, session]) => JSON.stringify({ event, at, session })).join('\n') + '\n{"torn":\n');
+
+ test('each stage counts from the record; a recall counts only in a later session than a write', () => {
+ mkdirSync(dir, { recursive: true });
+ const s1 = '2026-10-01T09:00:00.000Z', s2 = '2026-10-02T09:00:00.000Z', s3 = '2026-10-09T09:00:00.000Z', s4 = '2026-10-10T09:00:00.000Z';
+ write([
+ ['enabled', '2026-10-01T08:59:00.000Z', '2026-10-01T08:58:00.000Z'],
+ ['clean_install', '2026-10-01T09:00:01.000Z', s1],
+ ['recall', '2026-10-01T09:00:02.000Z', s1],
+ ['import', '2026-10-01T09:00:03.000Z', s1],
+ ['recall', '2026-10-01T09:30:00.000Z', '2026-10-01T09:29:00.000Z'],
+ ['recall', '2026-10-02T09:00:05.000Z', s2],
+ ['correction', '2026-10-02T09:00:06.000Z', s2],
+ ['withdrawal', '2026-10-02T09:00:07.000Z', s2],
+ ['recall', '2026-10-09T09:00:01.000Z', s3],
+ ['save', '2026-10-09T10:00:00.000Z', s3],
+ ['recall', '2026-10-10T09:00:01.000Z', s4],
+ ['withdrawal', '2026-10-10T09:00:02.000Z', s4],
+ ]);
+ expect(readFunnelReport()).toEqual({
+ schema_version: 1, enabled: true, enabled_on: '2026-10-01',
+ stages: [
+ { stage: 'clean_install', count: 1, first_on: '2026-10-01' },
+ { stage: 'import_useful_data', count: 1, first_on: '2026-10-01' },
+ { stage: 'recall_new_session', count: 4, first_on: '2026-10-01' },
+ { stage: 'correction_applied', count: 1, first_on: '2026-10-02' },
+ { stage: 'withdrawal_applied', count: 2, first_on: '2026-10-02' },
+ { stage: 'use_after_seven_days', count: 2, first_on: '2026-10-09' },
+ ],
+ });
+ });
+
+ test('without a clean install, seven days count from when recording was turned on', () => {
+ mkdirSync(dir, { recursive: true });
+ write([
+ ['enabled', '2026-10-03T08:00:00.000Z', '2026-10-03T08:00:00.000Z'],
+ ['recall', '2026-10-09T23:00:00.000Z', '2026-10-09T23:00:00.000Z'],
+ ['recall', '2026-10-10T00:30:00.000Z', '2026-10-10T00:30:00.000Z'],
+ ]);
+ const r = readFunnelReport();
+ expect(r.stages.find(s => s.stage === 'use_after_seven_days')).toEqual({ stage: 'use_after_seven_days', count: 1, first_on: '2026-10-10' });
+ expect(r.stages.find(s => s.stage === 'recall_new_session')!.count).toBe(0);
+ });
+});
+
+describe('gbrain status --funnel', () => {
+ const run = (args: string[]) => {
+ let out = '', err = '';
+ const { exitCode } = runStatusFunnel(['--funnel', ...args], { stdout: s => { out += s; }, stderr: s => { err += s; } });
+ return { exitCode, out, err };
+ };
+
+ test('off by default: --json reports enabled false and creates nothing', () => {
+ const r = run(['--json']);
+ expect(r.exitCode).toBe(0);
+ expect(JSON.parse(r.out)).toEqual(readFunnelReport());
+ expect(JSON.parse(r.out).enabled).toBe(false);
+ expect(existsSync(dir)).toBe(false);
+ expect(run([]).out).toContain('gbrain status --funnel --enable');
+ });
+
+ test('--enable, view, --delete', () => {
+ expect(run(['--enable', '--json']).exitCode).toBe(0);
+ expect(funnelEnabled()).toBe(true);
+ recordFunnelEvent('correction');
+ const json = JSON.parse(run(['--json']).out);
+ expect(json.stages.find((s: { stage: string }) => s.stage === 'correction_applied').count).toBe(1);
+ expect(JSON.stringify(json)).not.toContain(dir);
+ expect(run([]).out).toContain('correction_applied');
+ expect(run(['--delete']).out).toContain('recording is off');
+ expect(funnelEnabled()).toBe(false);
+ });
+
+ test('usage errors exit 2 and change nothing', () => {
+ expect(run(['--enable', '--delete']).exitCode).toBe(2);
+ expect(run(['--section', 'queue']).exitCode).toBe(2);
+ expect(existsSync(dir)).toBe(false);
+ });
+});