Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(takes): gbrain takes rebuild works while gbrain serve owns a PGLite brain (W9F item 8)
time-attackfa39cccaab4e
diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.mdindex c312aa3d90..9cda423d27 100644--- a/docs/architecture/key-files/commands-6.md+++ b/docs/architecture/key-files/commands-6.md@@ -8,7 +8,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/sync/` — the `gbrain sync` implementation behind the `sync.ts` façade (refactor wave 1, W4 sync). `perform.ts` is `performSync` (dispatch, filesystem lock, writer lock). `incremental.ts` is `performSyncInner`, a short orchestrator that runs the phases in order and returns the first `partial` a drain produces: `preflight.ts` (repo, git root and scope, pull and HEAD — an abort of the sync signal or a process cleanup pass (SIGTERM/SIGHUP) stops the pull and returns partial `pull_timeout`, persisted `sync.exclude` / `sync.include_hidden` unions, gc'd-bookmark / first-sync / `--include-gitignored` full-sync fallbacks, checkpoint pin, working-tree scope and drift, the filtered delta, dry run — every exit before the checkpoint opens is `{ done }`, otherwise an immutable `SyncPlan`), `deletes.ts` (un-syncable-modified sweep, batched removed-file drain), `renames.ts` (rename drain, per-rename apply, reconcile fallback), `imports.ts` (concurrency and connection clamp, pacer, stall watchdog, `importOnePath`, serial / worker-pool drain whose pools connect with `retryConnectTimeout`, #5946; the #132 rule — never wrap the drain or its call in `engine.transaction()` — is pinned in `test/sync.test.ts` for both files) and `finalize.ts` (zero-change exit, final flush, pin-reachability gate, failure-ledger bookmark gate, ingest log, extract / facts / embed). `sync-run.ts` defines `SyncRun`, the state the phases share across awaits, and `SyncPlan`; mutable fields are accessed only as `run.<field>` and `@checkpoint` fields are written only by `sync-run.ts` (`createSyncRun`, `flushCheckpoint`, `markCompleted`, `maybeYield`, `registerCheckpointCleanup`, `partial`, `abortUnpersistedPin`) — enforced by `scripts/check-sync-run-state.ts` (docs/TESTING.md#syncrun-state-guard). `full.ts` is `performFullSync` (dry run, import, shared failure gate, reconcile of deleted files, stale embed); the hold settle and the delete reconcile reuse runImport's walk only when `reusableWalk` accepts it (complete, same root, identical strategy / include-gitignored / --include-hidden / --exclude), and a reconcile whose reused walk names any page stale decides deletions on a fresh walk, because the import walk can miss a file restored since. `run.ts` is the CLI body `runSyncInner` (break-lock, source resolution, `--skip-failed` pre-ack, `runSyncAll` fan-out, `runSingleSourceSync` / watch), with flag parsing and usage text in `args.ts` (`parseSyncFlags` before the `--break-lock` branch, `parseSyncFanoutFlags` after it, `printSyncHelp`). Helpers: `checkpoint.ts` (checkpoint keys, cadence env knobs), `rename-reconcile.ts` (tracked-slug liveness index, orphaned `<rename:…>` sentinel sweep), `connector.ts`, `trigger.ts` (`gbrain sync trigger`), `report.ts` (`printSyncResult`, nudges), `missing-path.ts`, `gitignore.ts`. Controlled-order interleavings (watchdog, caller abort, SIGTERM cleanup, checkpoint write, mid-run commit, gc'd bookmark) with durable state checked after a restart: `test/sync-run-ordering.serial.test.ts`; parallel worker completion on Postgres: `test/e2e/sync-run-workers-postgres.test.ts`. Adding a sync phase: add a module that takes `(run, Pick<SyncPlan, ...>, ...)` and returns `SyncResult | undefined`, and call it from `performSyncInner` in order.-- `src/commands/takes-mutation.ts` — one parser and operation adapter for local, resident PGLite, and HTTP take mutations. Allocates a request UUID before delivery; retries retain that UUID and caller intent. `--source` remains claim provenance, `--source-id` selects the logical source, and `--dir` becomes a trusted local canonical-root assertion. Default owner/resolver choices remain unset until admission freezes them. The CLI and thin-client router share this parser for all four mutations before connecting; queued/error responses never print completed-mutation text. Remote failures use the shared typed reporter directly, retaining UUIDs, unknown delivery status and original receipt fields in JSON. `test/persistence-cli-delegation.test.ts` drives the real CLI through a held PGLite owner's socket, checks all four parameter mappings and pending receipts, and rejects malformed numeric/precondition input.+- `src/commands/takes-mutation.ts` — one parser and operation adapter for local, resident PGLite, and HTTP take mutations. Allocates a request UUID before delivery; retries retain that UUID and caller intent. `--source` remains claim provenance, `--source-id` selects the logical source, and `--dir` becomes a trusted local canonical-root assertion. Default owner/resolver choices remain unset until admission freezes them. The CLI and thin-client router share this parser for all four mutations before connecting; `runTakesRebuild` (W9F item 8) is `gbrain takes rebuild`'s parser and renderer, running `takes_rebuild` through a resident owner or the local engine (thin clients refused); queued/error responses never print completed-mutation text. Remote failures use the shared typed reporter directly, retaining UUIDs, unknown delivery status and original receipt fields in JSON. `test/persistence-cli-delegation.test.ts` drives the real CLI through a held PGLite owner's socket, checks all four parameter mappings and pending receipts, and rejects malformed numeric/precondition input.- `src/commands/transcripts.ts` — the transcripts command family, all local-only (`ctx.remote=false` by construction). `recent`: raw `.txt` corpus reads via `listRecentTranscripts` (same library as the gated `get_recent_transcripts` op). `ingest <path-or-glob>`: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phase `transcripts.ingest`), and calls `runTranscriptsIngest` with the CLI's `makeContext` context, so on a writer-claimed brain each rendered part is submitted as a `put_page` write request naming the page's current revision (unmanaged brains and dry runs keep the direct importer; `recover codex --apply` passes the same context; pinned by `test/transcripts-managed-ingest.test.ts`); embedding is OFF by default (embed backfill is the catch-up lane; the embed flag opts in); the max-bytes flag (validated size string, e.g. `4gb`) overrides the per-format file/store byte caps for oversized stores while omission preserves each adapter's native default; the since-last watermark is an op-checkpoint (op `transcripts-ingest`, fingerprint = source + pathspec + format + adapter version + any explicit byte cap via `ingestCheckpointFingerprintInput` — a checkpoint written under one cap is never silently reused under another, so a capped run's skipped tail can't read as scanned; the pathspec binds the user-stated paths resolved + sorted, and the no-arg/all lane substitutes hostname + sorted harness roots so DB-backed checkpoints shared across a brain's machines never let one machine inherit another's watermark and skip sessions it never scanned) advanced ONLY after a clean, untruncated, non-dry scan; no-arg = confined discovery table, the all flag imports the discovered set. `status`: found-vs-imported gap table (disk scan vs ONE conversation-pages frontmatter query — `executeRaw`, both engines — in `src/core/transcripts/discover.ts`) — the correctness surface that catches late-arriving sessions no watermark can. The facts flag hands EVERY touched slug (including hash-skipped) to `src/core/transcripts/ingest-facts.ts`; a page that fails extraction counts in `facts.pagesFailed`, stays unfinished, and makes the command exit 1. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help). `expandTilde(raw)` (bare `~`, leading `~/` or `~\\` → home dir; `~user` forms and a mid-string `~` stay literal) is the one tilde expansion `expandPaths` applies to every path spec. `recover codex` (`src/commands/transcripts-recover.ts`, logic `src/core/transcripts/recover.ts`; D15 for #5163): finds codex conversation pages in one source with no `**User**` anchor, re-parses the retained rollouts (discovery root + archived store, or given paths) and classifies each session recoverable / still userless / unrecoverable (rollout gone); preview by default, `--apply` re-imports only the recoverable rollouts through `runTranscriptsIngest` (content-hash dedup, no facts, no watermark write). Pinned by `test/transcripts-recover-codex.test.ts`.diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex d82622755a..8c7f7e94f0 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -49,7 +49,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct. #5032: `isWindowsColonTarget(rel)` and `colonSlugWindowsRefusal(slug, sourceId)` name the one Windows-only refusal (`colon_slug_windows_write_through`: `:` names an NTFS alternate data stream); `submitPageMutation` raises it before admission when this host publishes the file, `prepareFileTarget` at publication, and managed (`fileRefusals`) and unmanaged (`failedFiles`) sync skip each such path by name (`test/colon-slug-windows-5032.test.ts`).-- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection. A lock holder that is not a serve and answers no owner socket (a concurrent CLI call) is not a resident owner: `maybeDelegateLocalOperation` returns unhandled and the engine path waits for the PGLite lock instead of answering `owner_unavailable`; a serve holder or an answering socket keeps every failure final. Owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. For an op that owns a `source` param (`opOwnsSource`, `src/core/ops/contract.ts`), `params.source` stays on the wire as the op's own value (provenance) and routing comes from the ambient tiers, as on the direct and thin-client CLI routes (`test/cli-op-owned-source.test.ts`). The production provider dispatches the trusted `local_cli` principal's allow-listed skill-administration ops with the `'stdio'` locality marker, so the four `localOnly` ones (`get_skill_retention`, `prune_skill_revisions`, `retain_skill_revision`, `import_skill_proposal`) work while a serve owns the brain, as does `takes_remove` for the `local_cli` principal (its write scope still checked; `gbrain takes remove` defers its engine like the other takes verbs); other local calls keep no marker (`test/persistence-local-only-ops.test.ts`). `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. `residentPersistenceConfig` resolves a resident serve's brain the same way (`--brain`, `GBRAIN_BRAIN_ID`, `.gbrain-mount`, mount path), so the owner socket and the provider's consumer config follow a mounted brain instead of the host config (#5237); hook IPC stays keyed off the host config. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`, `test/serve-mounted-owner.test.ts`. A credential-free, read-only `projection_status` request (like `capabilities`) returns the resident's projection backlog counts (`PersistenceProjectionStatus`, no identifiers) so doctor's `text_projection_readiness` can report it while the resident holds a PGLite datastore (#5401, `test/projection-resident-doctor.test.ts`).+- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection. A lock holder that is not a serve and answers no owner socket (a concurrent CLI call) is not a resident owner: `maybeDelegateLocalOperation` returns unhandled and the engine path waits for the PGLite lock instead of answering `owner_unavailable`; a serve holder or an answering socket keeps every failure final. Owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. For an op that owns a `source` param (`opOwnsSource`, `src/core/ops/contract.ts`), `params.source` stays on the wire as the op's own value (provenance) and routing comes from the ambient tiers, as on the direct and thin-client CLI routes (`test/cli-op-owned-source.test.ts`). The production provider dispatches the trusted `local_cli` principal's allow-listed skill-administration ops with the `'stdio'` locality marker, so the four `localOnly` ones (`get_skill_retention`, `prune_skill_revisions`, `retain_skill_revision`, `import_skill_proposal`) work while a serve owns the brain, as do `takes_remove` and `takes_rebuild` (`LOCAL_CLI_LOCAL_ONLY_OPS`) for the `local_cli` principal (write scope still checked; `gbrain takes remove` and `gbrain takes rebuild` defer their engine like the other takes verbs); other local calls keep no marker (`test/persistence-local-only-ops.test.ts`). `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. `residentPersistenceConfig` resolves a resident serve's brain the same way (`--brain`, `GBRAIN_BRAIN_ID`, `.gbrain-mount`, mount path), so the owner socket and the provider's consumer config follow a mounted brain instead of the host config (#5237); hook IPC stays keyed off the host config. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`, `test/serve-mounted-owner.test.ts`. A credential-free, read-only `projection_status` request (like `capabilities`) returns the resident's projection backlog counts (`PersistenceProjectionStatus`, no identifiers) so doctor's `text_projection_readiness` can report it while the resident holds a PGLite datastore (#5401, `test/projection-resident-doctor.test.ts`).- `src/core/persistence/{schema,model,journal,authority,identity,ownership,coordinator,consumer,service,page-mutations,page-prepare,source-storage,control,context,digest,prepared-import}.ts` — dedicated durable mutation admission and permanent principal-scoped replay IDs, atomic quota reservations, registered canonical worktree ownership, native lock publication, conditional file recovery, and coherent receipt completion. Recovery presence blocks its whole worktree even when the receipt is terminal; admission and publication both enforce the fence. A file write is not claimed while a queued or running withdrawal mirror targets its page (any page, for an untargeted mirror), so the mirror cannot rewrite the file under an accepted request; when file bytes differ from preparation and the page revision also moved, publication reprepares (`revision_conflict`) instead of refusing as `raw_file_changed`, which stays the outcome for changed bytes at an unchanged revision (`test/withdrawal-followup-writes.test.ts`). Migration 159 adds a partial worktree/sequence recovery index so permanent receipt retention does not turn the fence into a history scan. Canonical file preparation honors a recorded source path or contained absolute capture file URI within the registered owner root (relative or host-only `file://` URIs are absent); symlink confinement and coherent snapshot checks still apply. A slug under a `storage.db_only` dir declared in `gbrain.yml` (matched case-insensitively, derive-phase defaults excluded) publishes database-only when a live page's file is absent (the case that otherwise refuses as an uncoordinated removal), with receipt `write_through.skipped: db_only`; new pages, tombstones, missing-file-tolerant callers and present cache files keep the full file treatment and never read `gbrain.yml`. `gbrain.yml` is read from the source root, like doctor, export and backup, not the git root `manageGitignore` uses, which differs for a monorepo-subdir source. `source-storage.ts` caches the parsed file per version and logs an invalid one (unreadable, overlapping tiers, db_only declared in syntax that resolves nothing) once; that missing-file refusal then reports `storage_error`, and the Git effect treats the page as not db_only. The drift guard applies the import rule for a file without an explicit `type:` (the stored type stands) and compares titles trimmed, as the parser reads them; a real drift refuses with `detail: file_database_drift` and a filled `sources reconcile` command; when sync holds the page's file (`sync-holds.ts`), the drift and occupied-path refusals name the hold instead (location-free message from `verb-errors.ts` `heldFileMessage`, mapped back by `heldFileDiagnostic` in receipts and `service.ts`) and its repair, and the page stays read-only for put_page until the file is repaired. The first write that binds an origin in a Git-subdirectory source with no slug-root pin pins the inferred mode in its publication transaction (a concurrent different pin refuses with `revision_conflict`), so later pages cannot flip the inference. A new page captured from a file inside the source (`capture_path`, resolved from the trusted CLI `local_file` in `page-mutations`, only when sync would give that file the capture slug under the source's slug-root mode) publishes to that file when its bytes are exactly the captured input; otherwise capture records `source_uri: cli-file`, never a host path. `acquireWorktree(binding, waitMs, signal, engine)` re-stamps a device-only physical-root change under the native lock (see `physical-root.ts`); without an engine, or when birth time is zero, it refuses with `detail: physical_root_device_changed` and the filled self-transfer commands. Version snapshots retain nullable `is_deleted`: new snapshots restore recorded deletion state atomically with content, tags, files and receipts; legacy NULL preserves current deletion state. Canonical no-op detection compares deletion state as well as content. Page replacement preconditions are checked before no-op detection; providers prepare outside publication transactions; recovery never restores unexpected bytes. Local registrations retain immutable CLI/stdio trust lanes and hashed credentials; accepted authority is intersected with current grants. `limits.ts` reads every `persistence.limits.*` cap and `persistence.receipt_retention_days` (default 30) from the database config table (`JOURNAL_CONFIG_KEYS`, registered for `gbrain config set`; malformed values are rejected at set time). Cumulative defaults (250,000 lifetime IDs and 1.5 GiB receipt bytes per principal, 8 GiB brain receipt bytes) cover 600 admissions a day for a year; each admission reserves at least 16 KiB and a compacted receipt keeps about 4 KiB. A cumulative `queue_capacity` refusal names its key in `detail` and suggests a `gbrain config set` value covering one more year at the recent admission rate (`oneYearCapacity`). Compaction filters out receipts with unfinished effects before its batch limit. `test/persistence-journal.test.ts` exercises real PGLite and optional guarded Postgres admission, cancellation, compaction, conflict and publication recovery; `test/persistence-capacity.test.ts` covers retention, the compaction filter, capacity hints and default sizing. `service.ts` also dispatches operation `decide_proposal` (S9 proposal accept/undo) to `facts/proposal-supersede.ts`. GOOGLE PUBLISH MODE: a page target is a `PageMutationFile` (`MutationFile` plus optional `publishMode`). The Google callers set `publishMode: 0o600` at prepare time from the stored connector (`prepareConnectorMutation` in `connector-sync.ts` when `p.connector === 'google'`, and `prepareGoogleReceiptPatch`); it is never part of the submitted intent, so request ids are unchanged. `publishFile` then creates missing directories with `mkdirPrivate(dirname(path), root)` (0700) instead of `mkdirSync` and opens the stage with `mode ?? publishMode` through `AtomicWriteOpts.mode`, so a rewrite of a legacy 0644 page lands 0600. Restoration keeps restoring the journaled before-mode and opens its stage with it (the post-flush chmod stays), so a restored private page is never staged wider than its mode.- `src/core/persistence/protocol.ts` — the persistence protocol declaration and the global row-lock order: the `persistence_brain` row, then worktree rows (id order), then source rows (id order), then `persistence_counters`, request rows and page keys. The request and effect protocol triggers (`shared-skills/persistence-schema.ts`) read the brain row FOR SHARE, and worktree claims, topology changes (`lockTopologyRows`, then `settleTopologyRequests` locks the `brain` counter) and activation hold it FOR UPDATE before their worktrees, sources and counters. So `declarePersistenceProtocol` and `declareDurablePersistence` take the brain row FOR SHARE in the same statement as their settings (after `lock_timeout`, a missing row still declares), and every journal transaction declares before any other row lock: admission, publication, recovery, completion, cancellation (`control.ts`), `forget` (`memory-mutations.ts`), connector retry approval, embedding effect retry and settlement, and withdrawal-target upgrades (`effect-targets.ts`). A transaction that needs the brain row FOR UPDATE takes it first and declares after it (`skill-activation.ts`). Before this order, an ordinary write that locked its source and counters before the trigger's brain read inverted against a concurrent claim or topology change and ended in a 1 s `lock_timeout` (or a deadlock), a retry, and writes left pending. Tests: `test/e2e/persistence-publish-lock-order-postgres.test.ts` (paused topology change and a claim/topology race, direct and through PgBouncer), the crash robot's `brain_before_rows` rule (`scripts/persistence/lock-order.ts`, `test/persistence-crash-robot.test.ts`).diff --git a/docs/architecture/key-files/hindsight.md b/docs/architecture/key-files/hindsight.mdindex 355c9e74b9..4872d4ba89 100644--- a/docs/architecture/key-files/hindsight.md+++ b/docs/architecture/key-files/hindsight.md@@ -33,7 +33,7 @@ unresolvable+true|false, pre-v80 NULL/NULL rows survive).- `src/core/think/prompt.ts` — anti-bias prompt shaping. `withCalibration` option on `buildThinkSystemPrompt` adds anti-bias rules. `buildCalibrationBlock()` emits the `<calibration>` XML. `buildThinkUserMessage` has TWO shapes: default (question first), and with-calibration (retrieval → calibration → question) when opt-in. Wired into `runThink` via `opts.withCalibration` + `opts.calibrationHolder`.- `src/commands/calibration.ts` — CLI: `gbrain calibration` (read + print), `--regenerate`, `--undo-wave <ver>`, `ab-report`. MCP op `get_calibration_profile` (scope: read) backs the same data path. Source-scoped via `sourceScopeOpts(ctx)`.- `src/core/owner-holder.ts` — single source of truth for "the brain owner" holder string. `DEFAULT_OWNER_HOLDER = 'self'` (matches the consolidate facts→takes writer + `docs/takes-vs-facts.md`); `resolveOwnerHolder({override, configValue})` returns override > `emotional_weight.user_holder` config > `'self'`. Consumed by the calibration_profile cycle phase, `gbrain calibration` CLI, the `get_calibration_profile` op, `think`'s calibration block, `emotional-weight`'s `DEFAULT_USER_HOLDER`, and doctor's `calibration_freshness`. Pure; unit-tested in `test/owner-holder.test.ts`. Does NOT unify owner-identity fragmentation (`self`/`brain`/`people-<owner>`) — tracked separately.-- `src/commands/takes.ts` — the full `gbrain takes` subcommand dispatcher (list/search/embed/add/update/supersede/resolve/propose/scorecard/calibration/extract/revisit). `takes list --limit N --offset N` validates integers at the CLI; the engine clamps limit (default 100, cap 500) and floors offset at 0. `takes revisit <slug>` opens $EDITOR on the source page with a `<!-- gbrain:revisit -->` cursor marker. #5167: `takes remove <slug> --row N` goes through `takes-mutation.ts` to the local-only `takes_remove` op (persistence `takes-prepare.ts`): the row leaves the fence and the takes table in one coordinated publication, other row numbers stay, and a resolved row, a row another row cites as "superseded by" it, or a row whose DB claim disagrees with the fence is refused (the last names `takes rebuild`); thin clients are refused. `takes rebuild <slug> [--source-id]` runs `extractTakes({source:"db", slugs:[slug], sourceId, rebuild:true})`, whose rebuild now deletes only indexed rows whose (row_num, claim) left the fence, so matching rows keep resolutions and vectors. The v0_28_0 hint names `gbrain reindex --markdown` instead of the nonexistent `extract takes --rebuild`.+- `src/commands/takes.ts` — the full `gbrain takes` subcommand dispatcher (list/search/embed/add/update/supersede/resolve/propose/scorecard/calibration/extract/revisit). `takes list --limit N --offset N` validates integers at the CLI; the engine clamps limit (default 100, cap 500) and floors offset at 0. `takes revisit <slug>` opens $EDITOR on the source page with a `<!-- gbrain:revisit -->` cursor marker. #5167: `takes remove <slug> --row N` goes through `takes-mutation.ts` to the local-only `takes_remove` op (persistence `takes-prepare.ts`): the row leaves the fence and the takes table in one coordinated publication, other row numbers stay, and a resolved row, a row another row cites as "superseded by" it, or a row whose DB claim disagrees with the fence is refused (the last names `takes rebuild`); thin clients are refused. `takes rebuild <slug> [--source-id]` runs the local-only `takes_rebuild` op (W9F item 8; `runTakesRebuild` in `takes-mutation.ts`, delegated to a resident `gbrain serve` owner over persistence IPC, else the local engine, with the same JSON, warnings and exit 1 on a missing page or a warning), which calls `extractTakes({source:"db", slugs:[slug], sourceId, rebuild:true})`, whose rebuild now deletes only indexed rows whose (row_num, claim) left the fence, so matching rows keep resolutions and vectors. The v0_28_0 hint names `gbrain reindex --markdown` instead of the nonexistent `extract takes --rebuild`.- `src/core/extract-takes-from-pages.ts` — bootstrap extraction selects uncovered pages newest first. Managed pages capture their revision before classification and publish the complete appended takes fence through coordinated `put_page`, whose canonical projection commits the takes rows with the page; conflicts skip that page. Unmanaged pages retain the md-first writer. Pinned by `test/persistence-managed-takes-extract.test.ts` and `test/extract-takes-md-first.test.ts`. `takes extract --before <updated_at>,<id>` (CLI-only) continues strictly below a prior run's `next_before`, an `(updated_at, id)` keyset with exact timestamptz text, so zero-claim pages no longer starve older ones; a budget stop resumes at the first unclassified page, a failed page stays uncovered for the next run without `--before`, and a malformed cursor is an exit-2 `invalid_params` refusal before any page is read. Pinned by `test/extract-takes-from-pages-progression.test.ts`, `test/takes-extract-json.test.ts` and `test/e2e/takes-extract-cursor-postgres.test.ts`.- `src/core/take-proposals.ts` — owns the `take_proposals` queue's row contract. `normalizeTakeProposalRow` coerces Postgres driver BigInt/string values (`id`, `weight`, `promoted_row_num`) to numbers at the query boundary so both engines return the same numeric row shape. `acceptProposal` promotes through a coordinated `takes_add` mutation (`submitPageMutation`, the same path `gbrain takes add` uses), so accept works on a managed brain where a direct fence write is refused with `writer_coordinator_required` (`test/takes-propose-accept-managed.test.ts`). #5214: an accepted proposal's take records `take_proposals#<id>` as its source; `acceptProposal(target, id, edits)` (`takes propose --accept <id> --claim/--weight/--who/--kind`) applies the edits as a plain takes_add with source `take_proposals#<id> (edited)` while the queue row keeps the original claim text.- `admin/src/pages/Calibration.tsx` — Calibration tab. Single-column layout. `<TrustedSVG>` wrapper handles `dangerouslySetInnerHTML` for the server-rendered SVG.diff --git a/docs/architecture/managed-mutating-writers.tsv b/docs/architecture/managed-mutating-writers.tsvindex 453851fcd7..f56506f5da 100644--- a/docs/architecture/managed-mutating-writers.tsv+++ b/docs/architecture/managed-mutating-writers.tsv@@ -46,6 +46,7 @@ op takes_update coordinator submitPageMutation takes intent.op takes_resolve coordinator submitPageMutation takes intent.op takes_remove coordinator submitPageMutation takes intent; local-only removal of one fence row and its takes row.op takes_supersede coordinator submitPageMutation takes intent.+op takes_rebuild coordinator Local-only rebuild of one page's takes index from its fence (W9F item 8); on a managed brain reextractCoordinated publishes it inside a withCoordinatedWrite transaction (receipted takes intent: Lane R).op sources_add early_refusal Deliberate administrative refusal on managed brains; source topology changes through writer administration.op sources_remove early_refusal Deliberate administrative refusal on managed brains; source topology changes through writer administration.op request_tools no_canonical_write Persists the calling client's MCP tool surface on oauth_clients.diff --git a/src/cli.ts b/src/cli.tsindex 4e762bf167..e73621a51b 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -2014,7 +2014,7 @@ async function routeCliOnlyBeforeTable(command: string, args: string[]): Promise}// Local deferred connections must not bypass the remote installation route.- if (command === 'capture' || command === 'forget' || command === 'call' || command === 'sources' && ['writer', 'reconcile', 'add', 'remove', 'archive', 'restore', 'purge', 'set-path', 'reclone'].includes(args[0]) || command === 'takes' && ['add', 'update', 'supersede', 'resolve', 'remove'].includes(args[0]) && !hasHelpFlag(args)) {+ if (command === 'capture' || command === 'forget' || command === 'call' || command === 'sources' && ['writer', 'reconcile', 'add', 'remove', 'archive', 'restore', 'purge', 'set-path', 'reclone'].includes(args[0]) || command === 'takes' && ['add', 'update', 'supersede', 'resolve', 'remove', 'rebuild'].includes(args[0]) && !hasHelpFlag(args)) {const { runDeferredPersistenceCommand } = await import('./commands/persistence-delegate.ts');await runDeferredPersistenceCommand(command, args, connectEngine);return true;diff --git a/src/commands/persistence-delegate.ts b/src/commands/persistence-delegate.tsindex b5e0e2cd6e..8534a6ade4 100644--- a/src/commands/persistence-delegate.ts+++ b/src/commands/persistence-delegate.ts@@ -84,8 +84,9 @@ export async function runDeferredPersistenceCommand(const getEngine = async () => connected ??= await connect();try {if (command === 'takes') {- const { runTakesMutation } = await import('./takes-mutation.ts');- await runTakesMutation(getEngine, args);+ const { runTakesMutation, runTakesRebuild } = await import('./takes-mutation.ts');+ if (args[0] === 'rebuild') await runTakesRebuild(getEngine, args.slice(1));+ else await runTakesMutation(getEngine, args);} else if (command === 'sources') {if (args[0] === 'reconcile') {const { runReconcileCli } = await import('./source-reconcile.ts');diff --git a/src/commands/takes-mutation.ts b/src/commands/takes-mutation.tsindex d8a103b47b..5e53ac6f7a 100644--- a/src/commands/takes-mutation.ts+++ b/src/commands/takes-mutation.ts@@ -1,4 +1,4 @@-/** One parser and one operation path for local, resident, and remote takes mutations. */+/** One parser and one operation path for local, resident, and remote takes mutations (and `takes rebuild`). */import { randomUUID } from 'node:crypto';import { resolve } from 'node:path';import type { BrainEngine } from '../core/engine.ts';@@ -153,3 +153,53 @@ export async function runTakesMutation(engine: BrainEngine | (() => Promise<Braiif (requestId) console.error(`Retry the same takes ${args[0]} arguments with --request-id ${requestId}.`);}}++/**+ * W9F item 8: `gbrain takes rebuild <slug> [--source-id <id>] [--json]`. A+ * resident owner (`gbrain serve` holding PGLite) runs the `takes_rebuild`+ * operation; otherwise it runs here on the local engine. Both render the same+ * operation result, so JSON, warnings and exit codes match: exit 1 when the+ * page is missing or the rebuild warned.+ */+export async function runTakesRebuild(engine: BrainEngine | (() => Promise<BrainEngine>), args: string[], configOverride?: GBrainConfig): Promise<void> {+ const [slug, ...rest] = args;+ const json = rest.includes('--json');+ if (!slug || slug.startsWith('-')) {+ console.error('Usage: gbrain takes rebuild <slug> [--source-id <id>] [--json]');+ setCliExitVerdict(1);+ return;+ }+ const sourceFlag = rest.indexOf('--source-id');+ const sourceId = sourceFlag >= 0 ? rest[sourceFlag + 1] : undefined;+ try {+ const config = configOverride ?? loadConfig(), cli = getCliOptions();+ if (isThinClient(config)) throw invalid('takes rebuild runs only on the brain host.',+ 'Run gbrain takes rebuild on the brain host; a remote connection cannot rebuild the takes index.');+ const params: Record<string, unknown> = { slug, request_id: randomUUID() };+ const delegated = await maybeDelegateLocalOperation('takes_rebuild', params, config, {+ brain: cli.brain, source: sourceId ?? null, timeoutMs: cli.timeoutMs ?? undefined,+ });+ let result: { source_id: string; pagesScanned: number; takesUpserted: number; warnings: string[] };+ if (delegated.handled) result = delegated.result as typeof result;+ else {+ const connected = typeof engine === 'function' ? await engine() : engine;+ const { operations } = await import('../core/operations.ts');+ const op = operations.find(candidate => candidate.name === 'takes_rebuild')!;+ result = await op.handler({ engine: connected, config: config ?? { engine: 'pglite' }, remote: false,+ sourceId: await resolveSourceId(connected, sourceId ?? null), dryRun: false,+ logger: { info: message => console.error(message), warn: message => console.error(message), error: message => console.error(message) },+ }, params) as typeof result;+ }+ if (json) await writeStdoutFinal(`${JSON.stringify(result, null, 2)}\n`);+ else if (result.pagesScanned === 0) console.error(`No page ${slug} in source ${result.source_id}.`);+ else {+ for (const warning of result.warnings) console.error(`[takes rebuild] ${warning}`);+ console.log(`Rebuilt ${result.takesUpserted} take row(s) on ${slug} from its takes fence.`);+ }+ if (result.pagesScanned === 0 || result.warnings.length) setCliExitVerdict(1);+ } catch (error) {+ if (!await reportPersistenceCliError(error, json)) {+ console.error(error instanceof Error ? error.message : String(error)); setCliExitVerdict(1);+ }+ }+}diff --git a/src/commands/takes.ts b/src/commands/takes.tsindex 01d83f428a..c795297235 100644--- a/src/commands/takes.ts+++ b/src/commands/takes.ts@@ -522,7 +522,7 @@ Common flags:case 'supersede':case 'resolve':case 'remove': { const { runTakesMutation } = await import('./takes-mutation.ts'); return runTakesMutation(engine, args); }- case 'rebuild': return cmdRebuild(engine, rest);+ case 'rebuild': { const { runTakesRebuild } = await import('./takes-mutation.ts'); return runTakesRebuild(engine, rest); }// #2411: `takes propose` used to fall through to the slug path and print// "No takes on propose." — the LLM proposal queue had no drain surface.case 'propose': return cmdPropose(engine, rest, await resolveTakesSourceId(engine));@@ -536,32 +536,6 @@ Common flags:}}-/**- * #5167: `gbrain takes rebuild <slug> [--source-id <id>]` rebuilds one page's- * takes index from the canonical fence its page holds (trusted local CLI).- * Rows whose number and claim still match keep their resolution and vector;- * rows the index and the fence disagree on are re-inserted from the fence.- */-async function cmdRebuild(engine: BrainEngine, rest: string[]): Promise<void> {- const slug = rest[0];- if (!slug || slug.startsWith('-')) {- process.stderr.write('Usage: gbrain takes rebuild <slug> [--source-id <id>] [--json]\n');- process.exit(1);- }- const sourceId = await resolveSourceId(engine, flagValue(rest, '--source-id') ?? null);- const { extractTakes } = await import('../core/cycle/extract-takes.ts');- const result = await extractTakes(engine, { source: 'db', slugs: [slug], sourceId, rebuild: true });- if (flagPresent(rest, '--json')) {- process.stdout.write(`${JSON.stringify({ slug, source_id: sourceId, ...result }, null, 2)}\n`);- } else if (result.pagesScanned === 0) {- process.stderr.write(`No page ${slug} in source ${sourceId}.\n`);- } else {- for (const warning of result.warnings) process.stderr.write(`[takes rebuild] ${warning}\n`);- console.log(`Rebuilt ${result.takesUpserted} take row(s) on ${slug} from its takes fence.`);- }- if (result.pagesScanned === 0 || result.warnings.length) process.exit(1);-}-/*** v0.41.18.0 (A12, A24, T9) — `gbrain takes extract --from-pages` runs* Haiku over concept/atom/lore/briefing/writing/originals pages anddiff --git a/src/core/ops/takes.ts b/src/core/ops/takes.tsindex fb44e00c9f..1b2036f9ee 100644--- a/src/core/ops/takes.ts+++ b/src/core/ops/takes.ts@@ -516,11 +516,45 @@ const takes_remove: Operation = {},};+/**+ * W9F item 8: `gbrain takes rebuild <slug>` as an operation, so the CLI can+ * delegate it to a resident owner (`gbrain serve` holding PGLite) instead of+ * waiting on the owner's lock. Same work as the local rebuild: the page's+ * takes index is rebuilt from its canonical fence (`extractTakes` rebuild;+ * on a managed brain `reextractCoordinated` publishes it, the integration+ * point for Lane R's receipted takes intent).+ */+const takes_rebuild: Operation = {+ name: 'takes_rebuild',+ idempotent: true,+ outputRedaction: { exempt: 'local-only: rebuild warnings quote malformed takes fence rows to the trusted local CLI owner, as the local rebuild always printed them' },+ description:+ 'Rebuild one page\'s takes index from the takes fence the page holds. Local-only. ' ++ 'Rows whose number and claim still match keep their resolution; rows the index and the fence disagree on are re-inserted from the fence. ' ++ 'CLI: `gbrain takes rebuild <slug>`.',+ params: {+ request_id: WRITE_REQUEST_PARAM,+ slug: { type: 'string', required: true, description: 'Page slug.' },+ },+ scope: 'write',+ mutating: true,+ localOnly: true,+ area: 'takes',+ handler: async (ctx, p) => {+ const slug = p.slug as string;+ validatePageSlug(slug);+ const sourceId = ctx.sourceId ?? 'default';+ if (ctx.dryRun) return { dry_run: true, action: 'takes_rebuild', slug, source_id: sourceId };+ const { extractTakes } = await import('../cycle/extract-takes.ts');+ return { slug, source_id: sourceId, ...await extractTakes(ctx.engine, { source: 'db', slugs: [slug], sourceId, rebuild: true }) };+ },+};+// Ops in EXACTLY the canonical `operations` array order: the v0.28 trio// (takes_list, takes_search, think), the v0.30 calibration aggregates, then// the gap-closure write verbs.export const takesOperations: Operation[] = [takes_list, takes_search, think,takes_scorecard, takes_calibration,- takes_add, takes_update, takes_resolve, takes_supersede, takes_remove,+ takes_add, takes_update, takes_resolve, takes_supersede, takes_remove, takes_rebuild,];diff --git a/src/core/persistence/ipc.ts b/src/core/persistence/ipc.tsindex 3ddf613dfe..d3fe48d6a8 100644--- a/src/core/persistence/ipc.ts+++ b/src/core/persistence/ipc.ts@@ -23,14 +23,14 @@ export const PERSISTENCE_IPC_OPERATIONS = ['put_skill', 'delete_skill', 'join_brain', 'sync_brain_skills', 'leave_brain','get_skill_policy', 'set_skill_policy', 'get_skill_retention', 'prune_skill_revisions','retain_skill_revision', 'import_skill_proposal',- 'add_tag', 'remove_tag', 'add_timeline_entry', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve', 'takes_remove',+ 'add_tag', 'remove_tag', 'add_timeline_entry', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve', 'takes_remove', 'takes_rebuild',] as const;export type PersistenceIpcOperation = typeof PERSISTENCE_IPC_OPERATIONS[number];const OPERATIONS = new Set<string>(PERSISTENCE_IPC_OPERATIONS);const MUTATIONS = new Set<string>(['put_page', 'put_pages', 'capture', 'delete_page', 'restore_page', 'revert_version', 'edit_page', 'remember', 'forget', 'extract_facts','put_skill', 'delete_skill', 'import_skill_proposal',- 'add_tag', 'remove_tag', 'add_timeline_entry', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve', 'takes_remove',+ 'add_tag', 'remove_tag', 'add_timeline_entry', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve', 'takes_remove', 'takes_rebuild',]);export interface PersistenceIpcRegistration {diff --git a/src/core/persistence/provider.ts b/src/core/persistence/provider.tsindex 24141acd7f..b8ba3f06e5 100644--- a/src/core/persistence/provider.ts+++ b/src/core/persistence/provider.ts@@ -19,6 +19,13 @@ import type { Action } from '../agent-output.ts';const localWritersFix: Action = { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'], consent: [], actor: 'agent',why: 'Shows this brain\'s local writer registrations with their grants, read-only.', requires_exclusive: false };+/**+ * localOnly operations the verified local CLI may run through the resident+ * owner: dispatched with the `stdio` locality marker so the localOnly+ * backstop admits them; remote principals never get it.+ */+const LOCAL_CLI_LOCAL_ONLY_OPS = new Set(['takes_remove', 'takes_rebuild']);+/** Resident lifecycle owns the consumer; each connection proves its own durable registration. */export async function createPersistenceIpcProvider(engine: BrainEngine, config: GBrainConfig): Promise<PersistenceIpcProvider> {for (const lane of ['cli', 'stdio'] as const) {@@ -70,7 +77,7 @@ export async function createPersistenceIpcProvider(engine: BrainEngine, config:return (await import('../transcripts.ts')).listRecentTranscripts(engine, { days: typeof p.days === 'number' ? p.days : undefined,summary: typeof p.summary === 'boolean' ? p.summary : undefined, limit: typeof p.limit === 'number' ? p.limit : undefined });}- const localCliLocalOnly = !verified.remote && verified.principal.kind === 'local_cli' && request.operation === 'takes_remove';+ const localCliLocalOnly = !verified.remote && verified.principal.kind === 'local_cli' && LOCAL_CLI_LOCAL_ONLY_OPS.has(request.operation);const writeWaitMs = boundedWriteWaitMs(request.write_wait_ms);const result = await dispatchToolCall(engine, request.operation, params, {config, remote: verified.remote, transport: verified.remote || localSkillAdministration || localCliLocalOnly ? 'stdio' : undefined, sourceId, auth,diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 13de54f1f9..9b13a10e99 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 207549,- "stdoutSha256": "ba03674e7846f4d445030acf6a2bb53cd5544abdff7f8d28e480903f1e852586",+ "stdoutBytes": 208397,+ "stdoutSha256": "daa48a3e341a9686dc20d0d57b1d6e7ee16afc01a53b4248fef6b1c7e3ee587b","toolNames": ["remember","entity",@@ -104,6 +104,7 @@"takes_resolve","takes_supersede","takes_remove",+ "takes_rebuild","whoami","sources_add","sources_list",@@ -4321,6 +4322,35 @@},"scope": "write"},+ {+ "description": "Rebuild one page's takes index from the takes fence the page holds. Local-only. Rows whose number and claim still match keep their resolution; rows the index and the fence disagree on are re-inserted from the fence. CLI: `gbrain takes rebuild <slug>`.",+ "idempotent": true,+ "local_only": true,+ "mutating": true,+ "name": "takes_rebuild",+ "parameters": {+ "request_id": "string?",+ "slug": "string"+ },+ "required_scopes": [],+ "schema": {+ "properties": {+ "request_id": {+ "description": "UUID; retry with it on timeout.",+ "type": "string"+ },+ "slug": {+ "description": "Page slug.",+ "type": "string"+ }+ },+ "required": [+ "slug"+ ],+ "type": "object"+ },+ "scope": "write"+ },{"description": "Your identity: transport, scopes and, over OAuth, client, source_id and federated_read.","idempotent": true,diff --git a/test/operations-coverage-ledger.test.ts b/test/operations-coverage-ledger.test.tsindex 70c4c9c3b2..645ec48b79 100644--- a/test/operations-coverage-ledger.test.ts+++ b/test/operations-coverage-ledger.test.ts@@ -122,6 +122,7 @@ const LEDGER: Record<string, string> = {takes_resolve: 'test/takes-write-ops.test.ts',takes_supersede: 'test/takes-write-ops.test.ts',takes_remove: 'test/takes-verbs-5167-5214.test.ts',+ takes_rebuild: 'test/persistence-local-only-ops.test.ts',whoami: 'test/whoami.test.ts',sources_add: 'test/sources-mcp.test.ts',sources_list: 'test/sources-mcp.test.ts',diff --git a/test/operations-trust-boundary.test.ts b/test/operations-trust-boundary.test.tsindex e41062428a..f1b7f35a3c 100644--- a/test/operations-trust-boundary.test.ts+++ b/test/operations-trust-boundary.test.ts@@ -246,6 +246,8 @@ describe('mcpOperations filter — localOnly ops are excluded from the HTTP-expo'retain_skill_revision','sources_inspect','sync_brain',+ // W9F item 8: the CLI delegates rebuild to a resident owner over IPC.+ 'takes_rebuild','takes_remove',];const derived = operations.filter(o => o.localOnly).map(o => o.name).sort();diff --git a/test/persistence-local-only-ops.test.ts b/test/persistence-local-only-ops.test.tsindex ff39318d13..51c43f3657 100644--- a/test/persistence-local-only-ops.test.ts+++ b/test/persistence-local-only-ops.test.ts@@ -1,7 +1,8 @@/*** #5864: the trusted local CLI reaches the four localOnly skill-administration- * operations, and `gbrain takes remove` (#5167), while a serve owns the PGLite- * brain. Authoring gate: (1) protects+ * operations, `gbrain takes remove` (#5167) and `gbrain takes rebuild` (W9F+ * item 8: it hung on the owner's lock until killed), while a serve owns the+ * PGLite brain. Authoring gate: (1) protects* the delegated route for get_skill_retention, prune_skill_revisions,* retain_skill_revision and import_skill_proposal, and keeps remote callers* refused; (2) fails when the resident owner answers `unknown_tool` to the@@ -28,9 +29,9 @@ import { withEnv } from './helpers/with-env.ts';const LOCAL_ONLY_IPC = ['get_skill_retention', 'import_skill_proposal', 'prune_skill_revisions', 'retain_skill_revision'];-test('the localOnly operations on persistence IPC are the four skill-admin ops, takes_remove and the provider-served transcript read', () => {+test('the localOnly operations on persistence IPC are the four skill-admin ops, takes_remove, takes_rebuild and the provider-served transcript read', () => {const ipc = new Set<string>(PERSISTENCE_IPC_OPERATIONS);- expect(operations.filter(op => op.localOnly && ipc.has(op.name)).map(op => op.name).sort()).toEqual([...LOCAL_ONLY_IPC, 'takes_remove', 'get_recent_transcripts'].sort());+ expect(operations.filter(op => op.localOnly && ipc.has(op.name)).map(op => op.name).sort()).toEqual([...LOCAL_ONLY_IPC, 'takes_remove', 'takes_rebuild', 'get_recent_transcripts'].sort());});describe('localOnly skill administration through a resident owner', () => {@@ -121,8 +122,28 @@ describe('localOnly skill administration through a resident owner', () => {expect(indexed.map(row => [row.row_num, row.claim])).toEqual([[1, 'Keep one']]);}, 120_000);+ test('gbrain takes rebuild (W9F item 8) runs through the resident owner and prints what a local rebuild returns', async () => {+ const slug = 'notes/ipc-takes-rebuild';+ expect((await call('put_page', { slug, content: '---\ntitle: IPC takes rebuild\ntype: note\n---\nAbout the rebuild path.\n' })).code).toBe(0);+ for (const claim of ['First claim', 'Second claim']) {+ expect((await call('takes_add', { slug, claim, kind: 'take', holder: 'world' })).code).toBe(0);+ }+ const started = Date.now();+ const rebuilt = await cli(['takes', 'rebuild', slug, '--json']);+ expect(Date.now() - started).toBeLessThan(30_000);+ expect(rebuilt.output).not.toContain('unknown_tool');+ expect(rebuilt.code, rebuilt.output).toBe(0);+ const { extractTakes } = await import('../src/core/cycle/extract-takes.ts');+ const local = { slug, source_id: 'default', ...await extractTakes(engine, { source: 'db', slugs: [slug], sourceId: 'default', rebuild: true }) };+ expect(JSON.parse(rebuilt.stdout)).toEqual(JSON.parse(JSON.stringify(local)));+ expect(local.takesUpserted).toBe(2);+ const missing = await cli(['takes', 'rebuild', 'notes/ipc-no-such-page', '--json']);+ expect(missing.code).toBe(1);+ expect(JSON.parse(missing.stdout)).toMatchObject({ pagesScanned: 0 });+ }, 120_000);+test('remote callers are still refused', async () => {- for (const operation of [...LOCAL_ONLY_IPC, 'takes_remove']) {+ for (const operation of [...LOCAL_ONLY_IPC, 'takes_remove', 'takes_rebuild']) {const http = await dispatchToolCall(engine, operation, {}, { remote: true, transport: 'http' });expect(http.isError).toBe(true);expect(http.content[0]!.text).toContain('unknown_tool');@@ -132,3 +153,37 @@ describe('localOnly skill administration through a resident owner', () => {}});});++describe('gbrain takes rebuild without a resident owner (W9F item 8)', () => {+ test('runs on the local engine and prints the rebuild result', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-takes-rebuild-local-'));+ try {+ const config = { engine: 'pglite' as const, database_path: join(dir, 'db') };+ const slug = 'notes/local-takes-rebuild';+ await withEnv({ GBRAIN_HOME: dir, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const local = new PGLiteEngine();+ await local.connect(config);+ await local.initSchema();+ await local.putPage(slug, { type: 'note', title: 'Local takes rebuild', compiled_truth: [+ 'About the local rebuild path.', '', '## Takes', '', '<!--- gbrain:takes:begin -->',+ '| # | claim | kind | who | weight | since | source |', '|---|-------|------|-----|--------|-------|--------|',+ '| 1 | Local claim | take | world | 0.5 | 2026-10 | test |', '<!--- gbrain:takes:end -->',+ ].join('\n') }, { sourceId: 'default' });+ await local.disconnect();+ });+ mkdirSync(join(dir, '.gbrain'), { recursive: true });+ writeFileSync(join(dir, '.gbrain', 'config.json'), JSON.stringify(config));+ const child = Bun.spawn([process.execPath, join(import.meta.dir, '../src/cli.ts'), 'takes', 'rebuild', slug, '--json'], {+ cwd: dir,+ env: { ...process.env, GBRAIN_HOME: dir, GBRAIN_BRAIN_ID: 'host', GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0', GBRAIN_SKIP_UPGRADE_CHECK: '1',+ GBRAIN_SOURCE: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined },+ stdout: 'pipe', stderr: 'pipe',+ });+ const timeout = setTimeout(() => child.kill('SIGKILL'), 60_000);+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);+ clearTimeout(timeout);+ expect(code, stdout + stderr).toBe(0);+ expect(JSON.parse(stdout)).toMatchObject({ slug, source_id: 'default', pagesScanned: 1, takesUpserted: 1, warnings: [] });+ } finally { rmSync(dir, { recursive: true, force: true }); }+ }, 120_000);+});