Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Add gbrain guests init and gbrain sources writers to set up a guest source (GBRA-504)

garrytane7153b14ab1c
diff --git a/docs/architecture/key-files/commands-5-continued.md b/docs/architecture/key-files/commands-5-continued.md
index 7f618a7d74..4881e77c42 100644
--- a/docs/architecture/key-files/commands-5-continued.md
+++ b/docs/architecture/key-files/commands-5-continued.md
@@ -8,10 +8,12 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/sources-reset-upstream.ts` — `gbrain sources reset-upstream <id> --expect-local <sha> --expect-upstream <sha> [--dry-run] [--json]`, the fix for `upstream_rewritten` / `upstream_unknown` (`src/core/sync-upstream-rewrite.ts`). Refuses a managed canonical worktree (`writer_coordinator_required`) and an in-progress git operation (`git_operation_in_progress`); under the checkout's commit lock (none on `--dry-run`) refuses with `reset_upstream_refused` a HEAD or upstream other than the expected SHAs (`expect_mismatch`), no upstream (`no_upstream`), tracked edits (`dirty_tree`, names the paths) and local commits not reachable from the upstream, the recorded baseline or any old or new value of the tracking ref's reflog (`local_commits`, names them and the backup ref). Otherwise writes `refs/gbrain/backup/<UTC stamp>-<sha12>` (create-only), runs `git reset --keep <upstream>`, verifies HEAD, records the baseline and clears the divergence; never fetches. Pinned by `test/pathological/s-58-upstream-rewrite.test.ts`.
- `src/commands/sources-retry-held.ts` — `gbrain sources retry-held <id> [--dry-run] [--json]`: records a re-attempt request for a source's held connector items (and, on a managed brain, their retry-pointer rows) or a re-screen request (op `sync-hold-retry`) for its held Git files, which the next sync adds to its manifest; nothing runs now, the receipt prints the sync to run. #6278: on a managed brain that follow-up sync is built by `gitFollowUpSync`: the unfinished managed cursor's resume arguments (`readManagedSyncBacklog`, `managedSyncResumeArgs`), so `--no-embed` and the other processing options carry over instead of starting a second cursor, else the arguments a `preparation_stalled` hold recorded (`meta.stall.sync_argv`), else `--source <id> --no-pull`. `preparation_stalled` holds count under `stalled` in the repair route and need no file repair: the receipt and help point to `gbrain sources writer status --source <id> --json` first. #6865: `--unindexed` (`retryUnindexed`) runs one bounded pass of the unindexed-file detector (`persistence/unindexed-files.ts`, 60 s) for a managed Git source, schedules the found files through the same re-screen request, stores the result doctor `unindexed_files` reads (continuing an incomplete stored scan) and prints the follow-up sync with `gbrain doctor --only unindexed_files --json` as its verify; `--dry-run` lists them and writes nothing; connector and company-brain sources refuse `invalid_params`; a complete pass with nothing found prints `No unindexed files for <id>.`, an incomplete one says the scan continues. Both modes build the receipt through `receiptOf`. Tests: `test/held-files-walkthrough.test.ts`, `test/managed-sync-preparation-stalled-holds.test.ts`, `test/unindexed-files.test.ts`.
- `src/commands/sources-resolve-path.ts` — GBRA-150: `gbrain sources resolve-path <id> <path...> [--stdin] [--json]`, the CLI face of op `sources_resolve_path` (`core/ops/sources.ts`). Paths come from argv or `--stdin` (one per line, at most `RESOLVE_PATHS_MAX` = 200); the human print is one line per path (state, slug, why, fix), `--json` the op's result. Read-only. Tests: `test/sources-resolve-path.test.ts`. Harness guide: `docs/guides/resolve-paths.md`.
-- `src/commands/sources-set-path.ts` — `gbrain sources set-path <id> <path> [--force]`: unmanaged installations retain the legacy pointer repair and overlap check. Managed installations use the verified lifecycle rebind; force never bypasses ownership or manifest checks. Relative paths and MSYS spellings are normalized before routing. The `default_source_local_path` doctor check names this as the repair.
+- `src/commands/sources-set-path.ts` — `gbrain sources set-path <id> <path> [--force]`: unmanaged installations retain the legacy pointer repair and overlap check. Managed installations use the verified lifecycle rebind; force never bypasses ownership or manifest checks. Relative paths and MSYS spellings are normalized before routing. The `default_source_local_path` doctor check names this as the repair. A guest source is refused (database-only, GBRA-504).
- `src/commands/sources-strategy.ts` — `gbrain sources set-strategy <id> <markdown|code|auto>` (#4899, PR #5955): writes `sources.config.strategy` through `updateSourceConfig` (single-key merge; every other config key survives), the value `sync --all`, autopilot, the dream cycle and the MCP `sync` op pass to the per-source sync when the caller names no `--strategy`; unset means `markdown`. The one writer of that key (no `sources add --strategy`, no op param). Connector kinds refuse it. [R26]: refuses with `sync_run_unfinished` (exit 1) while the source has an unfinished `managed-sync` cursor, naming the resume and the orphan repair, because the frozen manifest was classified under the old strategy; re-stating the current value is allowed. `sources list --json` and `listSources` report `strategy` (`null` when unset). Pinned by `test/sources-strategy.test.ts`.
+- `src/commands/guests.ts` — `gbrain guests init [--source <id>] [--writer <kind>:<id>]... [--yes]` (GBRA-504): previews by default; `--yes` creates or marks the source database-only, federated, `guest: true` with `trust_ceiling`, and its `guest_sources` row in one transaction (`core/guests/sources.ts`). Refuses a source with a local_path.
+- `src/commands/sources-writers.ts` — `gbrain sources writers <id> [--add|--remove <w>] [--clear] [--json]`: lists or changes `guest_sources.writers`; refuses a source that is not a guest source.
- `src/commands/sources-add-next.ts` — GBRA-156: `noGrantFloorNext(engine, id)`, the federate step `sources add` prints when a new non-federated source leaves the no-grant floor (`localFederatedSourceIds(engine, 'default', 'seed_default')`, else `['default']`) holding no live page a remote read may show (private pages excluded when remote reads exclude them); returns `{ command, argv, why }` or null. One read, no write; `sources add` treats a failed read as no step.
- `src/commands/sources.ts` — `gbrain sources {list,add,remove,archive,restore,archived,purge,current,status,audit,refresh,set-calendar}`; `set-calendar` dispatches to `src/commands/sources-set-calendar.ts`, and `set-cr-mode` prints `contextualModeHint` after the write. `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`, where a fence lock timeout (55P03) becomes `refresh_lock_timeout` naming the open transactions holding the fenced tables, and any other untyped throw becomes an `internal_error` refusal whose `why` carries the stack and whose fix names the refresh row it left for the next run to resume, GBRA-250). `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. `add` without `--federated` or `--no-federated` stores the source non-federated and warns on stderr that a remote token or agent connection with no source grant cannot read it, naming `gbrain sources federate <id>` and `gbrain auth rescope --token <name> --sources <id>`; when the no-grant floor (the default source plus federated sources) then holds no live page it also prints `next: gbrain sources federate <id>` on stdout (`noGrantFloorNext` in `sources-add-next.ts`). `add --json` prints one object (`id`, `name`, `local_path`, `remote_url`, `federated`, and `next` with `command`/`argv`/`why` when that step applies) and moves the human lines to stderr (`test/sources-add-federation-warning.test.ts`). `federate <id> [--json]` and `restore <id>` print on stderr, after the change commits, the pages a remote credential wrote without readers that the change makes readable to no-grant connections (`core/access/federation-exposure.ts`); `federate --json` prints one object (`id`, `federated`, `pages_exposed`) and moves the human lines to stderr. Pinned by `test/content-sanity.test.ts`, `test/import-file-content-sanity.test.ts`, `test/source-health.test.ts`.
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 6a397a2e10..58efbf3cee 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -33,6 +33,8 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`
- `src/core/ops/attribution.ts` — write attribution reads (Foundations 1, F1b). `resolveWriteAttributions` turns stored (request id, principal kind, principal id) snapshots into `WriteAttributionView`s (`types.ts`), joining `persistence_requests` (operation, `completed_at`, `agent_label`), `oauth_clients.client_name`, `access_tokens.name` and the `persistence_local_writers` lane at read time, one query each; `origin` is `request`, `maintenance` (principal without request) or `unrecorded` (all NULL). `get_write_attribution` (scope `admin`, `localOnly: false`, CLI `gbrain attribution <slug> [--fact <id>] [--take <row>] [--timeline <id>] [--versions]`) returns `{ target, created, last, live_revision, versions? }`; a page's `created` is the origin of its oldest version snapshot. The page lookup uses `readPolicyOpts`, so remote admins stay inside their source grant; remote fact targets are `world` only and take targets follow `readHolders`. Tests: `test/write-attribution-read.test.ts` (PGLite) and `test/e2e/write-attribution-read-parity.test.ts` (Postgres and PgBouncer).
- `src/core/ops/trust.ts` — `confirm_memory` (#5575 A4, CEO-9, DX-20): the one MCP-visible owner action. Raises a fact, take or page to `user_confirmed` through `trust/owner-actions.ts` after `requireOwnerConfirmation` (a `memory_confirm` connection, or the local CLI's typed-token TTY prompt); agent tokens get `insufficient_scope` with a `tell_user_to_run` fix naming `gbrain trust confirm <ref>`. Trust proposals and holds are not reachable here; the other owner actions are CLI or resident-owner administration only (`trust/owner-ipc.ts`).
+- `src/core/guests/{schema,sources}.ts` — GBRA-504 guest sources. `schema.ts` is migration v312's DDL: `guest_sources` (the authority for which sources are guest sources, their writer list of `<kind>:<id>` attribution principals and their tier ceiling), `guest_marks` (immutable: `gbrain_guard_guest_records` refuses UPDATE; rows leave only with their page) and `guest_promotions`, RLS on, and the guard that keeps a guest source database-only (no `local_path`). The trust trigger (`trust/schema.ts` `GUEST_AWARE_STAMP_TIER_FUNCTION`, installed by v312; v226 keeps its own body) clamps a guest page to the ceiling on every exit, refuses a page INSERT or content change (any content column but `deleted_at`) unless `gbrain.write_principal_kind`:`gbrain.write_principal_id` is on the writer list, and refuses facts, takes and timeline rows there. `sources.ts` holds the reads and writes behind `gbrain guests init` and `gbrain sources writers`.
+
- `src/core/health-memo.ts` — in-process memo for the `get_health` op only (O-ENG-13). An entry is reused when engine object, scope key (`all`, `scalar:<id>`, `set:<sorted unique ids>`, `empty` for an empty or no-sources grant; derived from the exact scope handed to `engine.getHealth`, so no scope reads another's entry), config generation (hash of the orphan exclusions, embedding column registry keys and schema pack setting), page clock (`page_generation_clock_seq.last_value` plus the `persistence_brain` id) and TTL all match. TTL: `GBRAIN_HEALTH_CACHE_TTL_MS`, else config `health.cache_ttl_ms`, else 30000 ms; 0 disables. The TTL bounds staleness from writes that do not touch `pages` (links, timeline rows, chunks). A failed clock/config read computes uncached. `engine.getHealth` stays uncached, so doctor, remediation, maintain, embedding migration and repair verification always read fresh numbers; `gbrain repair --apply` and `gbrain doctor --remediate` call `clearHealthMemo`. Pinned by `test/health-memo.test.ts`.
- `src/core/ops/context.ts` (source-id confinement helpers) — `assertSourceInCallerScope(ctx, id)` is the READ-scope confinement for an explicitly named source id (`sources_status`): untrusted callers may only name an id inside the `sourceScopeOpts` ladder. `assertSourceInCallerWriteScope(ctx, id)` is its WRITE-authority twin for destructive source ops (`sources_remove`): federation (`ctx.auth.allowedSources`) is read authority and confers no removal right, so a bound untrusted caller (write source `ctx.auth.sourceId ?? ctx.sourceId`, and/or any federated grant) may name only its own write source; a bound caller with no write source (or the `__all__` sentinel) may name nothing; an unbound untrusted caller keeps full authority; trusted local passes. Both answer `OperationError('not_found', 'Unknown source: <id>')`. `resolveRequestedScope(ctx, sourceId, allSources, explicitReads?)` takes an optional explicit-read admission set (#5081) that only `federatedSearchScope` passes: a granted token admits nothing extra, a stdio connection bound by `GBRAIN_SOURCE`/`.gbrain-source` admits `ctx.explicitReadBinding.sourceIds`, and an unbound connection admits its own `localFederatedSourceIds`; its denial hint names why (token grant, binding, opted-out source) with `docs/guides/multi-source-brains.md#explicit-reads-from-a-bound-agent-connection`. Image, loops and code-intel pass nothing and keep the original denial (`test/explicit-read-admission-5081.test.ts`, `test/serve-stdio-bound-explicit-read.test.ts`). `enforceSubagentSlugFence` stays fail-closed on a missing `subagentId`; its one exception (#5994) is a failed-writes replay whose `replayAuthority` is restricted and whose allow-list equals the stored non-empty `delegatedPrefixes` exactly, and the slug must still match it. `isOpPageSlug` is the `validatePageSlug` grammar as a predicate; page-prepare's `prepareFileTarget` returns no file for a slug outside it, so an admitted legacy row publishes database-only and never removes a file its stale `source_uri`/`source_path` names (#6212).
diff --git a/docs/guides/guest-notes.md b/docs/guides/guest-notes.md
new file mode 100644
index 0000000000..13c70fb263
--- /dev/null
+++ b/docs/guides/guest-notes.md
@@ -0,0 +1,88 @@
+# Guest notes
+
+People in a group chat with your agent sometimes say things worth keeping ("the
+offsite moved to Friday"). Those people are outside guests: they aren't you, and
+their words shouldn't read as yours. A **guest source** is where gbrain keeps
+their notes, apart from your own pages, with a record of who said what.
+
+This page is the operator view: what a guest source is and how to set one up.
+Saving notes into it, the warning every read shows on a guest note, and keeping a
+guest note as your own page arrive in later releases. Until then a guest source
+holds nothing unless a listed writer puts pages there.
+
+## What a guest source is
+
+A guest source is a normal gbrain source with four rules the database itself
+enforces, whatever program writes to it:
+
+- **Only listed writers.** Creating a page there, or changing its text, title,
+ frontmatter, slug or source, needs a writer on the source's writer list. A
+ writer is named the way gbrain records who made a write: `oauth_client:<client
+ id>` for an OAuth client, `legacy_token:<token id>` for a legacy token. Your own
+ CLI is not on the list, so `gbrain put --source guests` is refused with
+ `source_writer_restricted`. Soft delete, restore, purge and maintenance that
+ touches no page text still work for you.
+- **Never above external, untrusted.** Every page there is stored at the
+ `external_untrusted` trust tier or lower ([memory trust](memory-trust.md)), even
+ when a write path would normally raise it (an owner rewrite, a backfill, a
+ trust confirmation).
+- **No facts, takes or timeline entries.** Those rows are refused in a guest
+ source (`guest_page_immutable`), so a guest's words never turn into facts about
+ people in your brain.
+- **Database-only.** A guest source has no local folder or git repository: the
+ database is the record, as on any repo-less brain. Attaching a path
+ (`gbrain sources set-path`, `gbrain sources add <id> --path`) is refused, and a
+ source that already has a path can't become a guest source.
+
+A guest source is also federated, so your own searches include it. Brains
+without a guest source are unchanged.
+
+## Set one up
+
+Preview first. Nothing is written without `--yes`:
+
+```bash
+gbrain guests init --writer oauth_client:client-a
+```
+
+```text
+Preview: gbrain guests init (nothing written; run again with --yes to apply)
+ Source "guests": will be created, database-only (no local path) and federated.
+ Trust ceiling: external_untrusted (no page there is ever stored above it).
+ Writers: oauth_client:client-a
+```
+
+Then apply it:
+
+```bash
+gbrain guests init --writer oauth_client:client-a --yes
+```
+
+The source is called `guests` unless you pass `--source <id>`. Running init
+again on a guest source adds the new writers and keeps the old ones. If the
+source exists already, it must have no local path; init then marks it as a guest
+source.
+
+## Change who may write
+
+```bash
+gbrain sources writers guests # list
+gbrain sources writers guests --add oauth_client:client-b # add
+gbrain sources writers guests --remove oauth_client:client-a # remove
+gbrain sources writers guests --clear # nobody
+gbrain sources writers guests --json
+```
+
+A source that isn't a guest source has no writer list, so the command refuses
+it. Changing the list is your decision on the brain host; nothing in gbrain
+widens it on its own.
+
+## What is stored
+
+Three database tables back a guest source. `guest_sources` names each guest
+source, its writer list and its trust ceiling. `guest_marks` will hold, for each
+guest note, who it was saved for, from which group (for example `group:team-a`),
+the sender's label (for example `bob-example`), when and by which writer; a mark
+can never be edited and is removed only when its page is purged.
+`guest_promotions` will record guest notes you keep as your own pages. In this
+release nothing writes the last two yet.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 32793931ce..7ec45de088 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -31,7 +31,7 @@ src/commands/import.ts 1507 ratchet new row: crossed the 1500 unlisted cap with
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 2165 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); +4 #8426/#8428: the user-scope MCP registration, its verify and the workspace and Codex SessionEnd hooks start gbrain through the hook launcher (logic in core/setup/hook-launcher.ts); +2 #8435: the user-global opencode entry starts serve through the hook launcher (logic in core/setup/hook-launcher.ts); +1 GBRA-224: INSTALL_PIN import (core/install-ref.ts; re-summed at the GBRA-346 merge: master 2153 + 1); +6 #8902: bootstrap prints an OperationError refusal with its code and next step; +5 GST-2456: bootstrap repo --scan-timeout parse and its help lines (the scan lives in core/bootstrap/repo.ts)
src/core/minions/worker.ts 1795 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts); +6 GBRA-133 2a.4 sync-queue wake: IdleWaiter import and field, claimStarted before each claim, the idle poll through it, and stop/requestShutdown ending its wait (logic in minions/idle-wait.ts); +1 GBRA-158 #7239: refusal.ts import (a deterministic refusal ends the job at once; classification in minions/refusal.ts); +3 #7242 lane reservation: lanes import and the longJobNames/shortJobReservedSlots defaults (the claim passes claimExclusions; policy in minions/lanes.ts); +2 #7242 terminal hook: onJobSettled default and the settle call (logic in terminal-hook.ts); #7252 x #7249 merge: both sides grew the file, re-summed (1794 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (1795 measured)
-src/commands/sources.ts 2145 ratchet +3 url_source_origin: sources record-origin dispatch and help rows (body in sources-record-origin.ts, logic in core/url-source-origin.ts); +3 PR B: sources guard dispatch and help rows (body in sources-guard.ts); +3 G7b-2: sources host-repo dispatch and help row (body in sources-host-repo.ts and core/persistence/hosted-repo.ts); +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts); +4 G1 git-canonical: sources git-gap dispatch, doc line and help rows (body in sources-git-gap.ts); +4 G3 git-canonical: sources reindex dispatch, doc line and help rows (body in sources-reindex.ts); +1 GBRA-156: the sources add non-federated warning line; re-summed at the master 33d73cb5 merge (2086 measured); +4 G8a git-canonical: sources canonical dispatch, doc line and help rows (body in sources-canonical.ts, plan and apply in persistence/git-conversion.ts); GBRA-156: sources add --json and its next step (logic in sources-add-next.ts); re-summed at the master ade6d638 merge (2100 measured); +2 GBRA-220 PR 2: the unmanaged sources add routes --kind meetings|slack to the shared lifecycle parser (body in sources-add-api.ts); re-summed at the master b85dd645 merge (2102 measured); +2 #7701: the archived field of SourceListEntry and its list entry (sources list now marks archived sources; an interface field cannot move): re-summed at the 0.60.583.0 merge: 2102 + 2; +1 GST-1113: sources federate refuses a QM scope source (one line; the check lives in core/access/attest-sources.ts), re-summed at the 0.60.594.0 gate-ahead: 2107 + 1; +5 GST-1113 /ship fix round: sources federate checks the scope mark and writes the config in one transaction under the source row lock (the check lives in core/access/attest-sources.ts); +7 #8982: sources federate and restore print the remote-written pages without readers they expose, federate --json, the prior federation read under the row lock (the read and the lines live in core/access/federation-exposure.ts); +6 sources git-reconcile dispatch, header and help rows (body in sources-git-reconcile.ts), re-summed at the master d25bd680 merge (2124 + 6); +3 GST-2250: sources status reads and prints the per-source automatic-publishing opt-out; +12 GST-2456: sources push --scan-timeout (parse, usage and help lines) and its blocked_history refusal case (logic in core/workspace-push.ts)
+src/commands/sources.ts 2147 ratchet +3 url_source_origin: sources record-origin dispatch and help rows (body in sources-record-origin.ts, logic in core/url-source-origin.ts); +3 PR B: sources guard dispatch and help rows (body in sources-guard.ts); +3 G7b-2: sources host-repo dispatch and help row (body in sources-host-repo.ts and core/persistence/hosted-repo.ts); +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts); +4 G1 git-canonical: sources git-gap dispatch, doc line and help rows (body in sources-git-gap.ts); +4 G3 git-canonical: sources reindex dispatch, doc line and help rows (body in sources-reindex.ts); +1 GBRA-156: the sources add non-federated warning line; re-summed at the master 33d73cb5 merge (2086 measured); +4 G8a git-canonical: sources canonical dispatch, doc line and help rows (body in sources-canonical.ts, plan and apply in persistence/git-conversion.ts); GBRA-156: sources add --json and its next step (logic in sources-add-next.ts); re-summed at the master ade6d638 merge (2100 measured); +2 GBRA-220 PR 2: the unmanaged sources add routes --kind meetings|slack to the shared lifecycle parser (body in sources-add-api.ts); re-summed at the master b85dd645 merge (2102 measured); +2 #7701: the archived field of SourceListEntry and its list entry (sources list now marks archived sources; an interface field cannot move): re-summed at the 0.60.583.0 merge: 2102 + 2; +1 GST-1113: sources federate refuses a QM scope source (one line; the check lives in core/access/attest-sources.ts), re-summed at the 0.60.594.0 gate-ahead: 2107 + 1; +5 GST-1113 /ship fix round: sources federate checks the scope mark and writes the config in one transaction under the source row lock (the check lives in core/access/attest-sources.ts); +7 #8982: sources federate and restore print the remote-written pages without readers they expose, federate --json, the prior federation read under the row lock (the read and the lines live in core/access/federation-exposure.ts); +6 sources git-reconcile dispatch, header and help rows (body in sources-git-reconcile.ts), re-summed at the master d25bd680 merge (2124 + 6); +3 GST-2250: sources status reads and prints the per-source automatic-publishing opt-out; +12 GST-2456: sources push --scan-timeout (parse, usage and help lines) and its blocked_history refusal case (logic in core/workspace-push.ts); +2 GBRA-504: sources writers dispatch and help row (body in sources-writers.ts, logic in core/guests/sources.ts)
src/core/link-extraction.ts 2462 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1); +3 G5 (GBRA-60): extractBodyLinks masks the ## Links fence (links-fence.ts), whose rows are projected as their own edges; +38 train C: #8921 #6983 DB link path resolves child-folder links on top of #9143's link-extraction edits
src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budget
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
diff --git a/src/cli/command-table.ts b/src/cli/command-table.ts
index fc5f4443f8..859f914d6c 100644
--- a/src/cli/command-table.ts
+++ b/src/cli/command-table.ts
@@ -424,6 +424,8 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// #5575: memory trust. Observational startup: `trust backfill --dry-run` runs with no migrations and no writes.
// W1 belief ledger coverage: enable, disable, status, reconcile, backfill (docs/designs/BELIEF_LEDGER.md section 7).
{ name: 'beliefs', phase: 'post-connect', thinClient: 'route-then-refuse', selfHelp: true, json: 'document', routes_source: true, load: () => import('./commands/beliefs.ts') },
+ // CLI_ONLY: guest notes (GBRA-504): sets up a database-only guest source; trusted local CLI only.
+ { name: 'guests', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/guests.ts') },
{ name: 'trust', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, json: 'document', skipStartupHooks: true, startup: 'observational', load: () => import('./commands/trust.ts') },
// selfHelp: v0.43 (#2095): watch ships WATCH_HELP (flags + the stdin-turn protocol).
// thin client: v0.43 (#2095): watch streams against a LOCAL engine; thin clients get the
diff --git a/src/cli/commands/guests.ts b/src/cli/commands/guests.ts
new file mode 100644
index 0000000000..5bef67683d
--- /dev/null
+++ b/src/cli/commands/guests.ts
@@ -0,0 +1,10 @@
+/**
+ * `gbrain guests`: post-connect dispatch, run by handleCliOnly with the engine
+ * connectEngine() opened. The record lives in src/cli/command-table.ts.
+ */
+import type { BrainEngine } from '../../core/engine.ts';
+
+export async function run(engine: BrainEngine, args: string[]): Promise<void> {
+ const { runGuests } = await import('../../commands/guests.ts');
+ await runGuests(engine, args);
+}
diff --git a/src/cli/enforced-member-classes.ts b/src/cli/enforced-member-classes.ts
index f15d49f520..6f6c87e652 100644
--- a/src/cli/enforced-member-classes.ts
+++ b/src/cli/enforced-member-classes.ts
@@ -115,7 +115,7 @@ export const CLI_COMMAND_CLASSES: Readonly<Record<string, EnforcedClass | Enforc
'advisor', 'conversation-parser', 'edges-backfill', 'whoknows', 'brainstorm', 'lsd', 'skillopt', 'calibration',
'transcripts', 'models', 'takes', 'onboard', 'founder', 'think', 'notability-eval', 'waiting', 'loops',
'questions', 'edge-proposals', 'memory-proposals', 'core', 'connectors', 'wakeshift', 'pages', 'quarantine', 'beliefs',
- 'trust', 'watch', 'storage', 'code-def', 'code-refs', 'reindex-code', 'reindex-search-vector', 'reindex-frontmatter',
+ 'trust', 'guests', 'watch', 'storage', 'code-def', 'code-refs', 'reindex-code', 'reindex-search-vector', 'reindex-frontmatter',
'backfill', 'code-callers', 'code-callees', 'repos',
].map(n => [n, 'refused' as const])),
};
diff --git a/src/cli/top-help.ts b/src/cli/top-help.ts
index bd68443524..369aa97aa5 100644
--- a/src/cli/top-help.ts
+++ b/src/cli/top-help.ts
@@ -158,6 +158,7 @@ SOURCES (multi-repo / multi-brain)
sources archived List soft-deleted sources and their purge expiry
sources purge [<id>] Permanently delete archived sources
sources status Per-source dashboard (sync lag, embed coverage)
+ guests init [--writer <w>] [--yes] Set up a guest source for outside guests' notes
sources --help Full subcommand list (rename, default, attach,
current, federate, set-cr-mode, webhook, harden, ...)
sync --all Sync all sources with a local_path
diff --git a/src/commands/guests.ts b/src/commands/guests.ts
new file mode 100644
index 0000000000..a27c5e1c63
--- /dev/null
+++ b/src/commands/guests.ts
@@ -0,0 +1,69 @@
+/**
+ * `gbrain guests init` (GBRA-504): sets up a guest source, the database-only,
+ * federated source an outside-guest broker saves notes into. Previews by
+ * default; `--yes` applies. Trusted local CLI only. Guide: docs/guides/guest-notes.md.
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import { isValidSourceId } from '../core/source-id.ts';
+import { GUEST_TRUST_CEILING, GUEST_WRITER_FORMAT, initGuestSource, isGuestWriter, planGuestSource } from '../core/guests/sources.ts';
+
+export const GUESTS_USAGE = `Usage: gbrain guests init [--source <id>] [--writer ${GUEST_WRITER_FORMAT}]... [--yes]
+
+ Sets up a guest source for notes saved by outside guests: database-only (no local
+ path or repository), federated, pages capped at ${GUEST_TRUST_CEILING}, and writable
+ only by the listed writers. The source defaults to "guests". Without --yes it
+ prints what it would do and writes nothing. Change writers later with
+ gbrain sources writers <id>.`;
+
+export async function runGuests(engine: BrainEngine, args: string[]): Promise<void> {
+ const [sub, ...rest] = args;
+ if (!sub || sub === '--help' || sub === '-h') { console.log(GUESTS_USAGE); return; }
+ if (sub !== 'init') {
+ console.error(`Unknown guests subcommand: ${sub}`);
+ console.error(GUESTS_USAGE);
+ process.exit(2);
+ }
+ let sourceId = 'guests';
+ const writers: string[] = [];
+ let yes = false;
+ for (let i = 0; i < rest.length; i++) {
+ const arg = rest[i]!;
+ if (arg === '--yes') yes = true;
+ else if ((arg === '--source' || arg === '--writer') && rest[i + 1] !== undefined) {
+ if (arg === '--source') sourceId = rest[++i]!; else writers.push(rest[++i]!);
+ } else if (arg === '--help' || arg === '-h') { console.log(GUESTS_USAGE); return; }
+ else {
+ console.error(`Unknown or incomplete argument: ${arg}`);
+ console.error(GUESTS_USAGE);
+ process.exit(2);
+ }
+ }
+ if (!isValidSourceId(sourceId)) {
+ console.error(`Invalid source id "${sourceId}". Must be 1-32 lowercase alnum chars with optional interior hyphens.`);
+ process.exit(2);
+ }
+ const malformed = writers.filter(w => !isGuestWriter(w));
+ if (malformed.length > 0) {
+ console.error(`Not a writer principal: ${malformed.join(', ')}. Name each writer as ${GUEST_WRITER_FORMAT}, for example oauth_client:<client id>.`);
+ process.exit(2);
+ }
+
+ const plan = await planGuestSource(engine, sourceId, writers);
+ if (plan.localPath) {
+ console.error(`Source "${sourceId}" has a local path (${plan.localPath}). A guest source is database-only, so gbrain will not make this one a guest source. Pick another name with --source.`);
+ process.exit(2);
+ }
+ const writerLine = (list: readonly string[]) => list.length > 0 ? list.join(', ')
+ : `none yet: nobody can save notes there until you add one (gbrain sources writers ${sourceId} --add ${GUEST_WRITER_FORMAT})`;
+ if (!yes) {
+ console.log('Preview: gbrain guests init (nothing written; run again with --yes to apply)');
+ console.log(` Source "${sourceId}": ${!plan.exists ? 'will be created, database-only (no local path) and federated'
+ : plan.guest ? 'is already a guest source' : 'exists with no local path; it becomes a guest source and is federated'}.`);
+ console.log(` Trust ceiling: ${GUEST_TRUST_CEILING} (no page there is ever stored above it).`);
+ console.log(` Writers: ${writerLine(plan.writers)}`);
+ return;
+ }
+ const guest = await initGuestSource(engine, sourceId, writers);
+ console.log(`Source "${sourceId}" is ${plan.exists ? 'now' : 'created as'} a guest source: database-only, federated, trust ceiling ${guest.trust_ceiling}.`);
+ console.log(` Writers: ${writerLine(guest.writers)}`);
+}
diff --git a/src/commands/sources-set-path.ts b/src/commands/sources-set-path.ts
index 4a36f32876..eb595fb637 100644
--- a/src/commands/sources-set-path.ts
+++ b/src/commands/sources-set-path.ts
@@ -21,6 +21,7 @@ import type { BrainEngine } from '../core/engine.ts';
import { assertNoOverlappingPath, SourceOpError } from '../core/sources-ops.ts';
import { OperationError } from '../core/ops/contract.ts';
import { clearConnectorLocalPath } from '../core/persistence/connector-path.ts';
+import { readGuestSource } from '../core/guests/sources.ts';
export async function runSetPath(engine: BrainEngine, rawArgs: string[]): Promise<void> {
if (rawArgs.includes('--clear')) return runClearPath(engine, rawArgs.filter(a => a !== '--clear'));
@@ -63,6 +64,11 @@ export async function runSetPath(engine: BrainEngine, rawArgs: string[]): Promis
const priorPath = existing[0]!.local_path;
+ if (await readGuestSource(engine, id)) {
+ console.error(`Error: source "${id}" is a guest source. A guest source is database-only, so it takes no local path or repository.`);
+ process.exit(2);
+ }
+
if (!existsSync(path) || !statSync(path).isDirectory()) {
console.error(`Error: path does not exist on disk (or is not a directory): ${path}`);
console.error(' This command only repairs the DB pointer — it never creates directories.');
diff --git a/src/commands/sources-writers.ts b/src/commands/sources-writers.ts
new file mode 100644
index 0000000000..be896540e5
--- /dev/null
+++ b/src/commands/sources-writers.ts
@@ -0,0 +1,48 @@
+/**
+ * `gbrain sources writers <id>` (GBRA-504): lists or changes who may write a
+ * guest source (guest_sources.writers, which the trust trigger enforces).
+ * Refuses a source that is not a guest source. Trusted local CLI only.
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import { GUEST_WRITER_FORMAT, changeGuestWriters, isGuestWriter, readGuestSource } from '../core/guests/sources.ts';
+
+export const SOURCES_WRITERS_USAGE = `Usage: gbrain sources writers <id> [--add ${GUEST_WRITER_FORMAT}]... [--remove <writer>]... [--clear] [--json]
+ Lists the writers of a guest source, or changes them. Only a listed writer can
+ create or change pages there.`;
+
+export async function runSourcesWriters(engine: BrainEngine, args: string[]): Promise<void> {
+ const add: string[] = [], remove: string[] = [];
+ let id: string | undefined, clear = false, json = false;
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i]!;
+ if (arg === '--clear') clear = true;
+ else if (arg === '--json') json = true;
+ else if ((arg === '--add' || arg === '--remove') && args[i + 1] !== undefined) (arg === '--add' ? add : remove).push(args[++i]!);
+ else if (arg === '--help' || arg === '-h') { console.log(SOURCES_WRITERS_USAGE); return; }
+ else if (!arg.startsWith('-') && id === undefined) id = arg;
+ else {
+ console.error(`Unknown or incomplete argument: ${arg}`);
+ console.error(SOURCES_WRITERS_USAGE);
+ process.exit(2);
+ }
+ }
+ if (!id) { console.error(SOURCES_WRITERS_USAGE); process.exit(2); }
+ const malformed = add.filter(w => !isGuestWriter(w));
+ if (malformed.length > 0) {
+ console.error(`Not a writer principal: ${malformed.join(', ')}. Name each writer as ${GUEST_WRITER_FORMAT}.`);
+ process.exit(2);
+ }
+ const [source] = await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE id = $1', [id]);
+ if (!source) {
+ console.error(`Source "${id}" not found. List sources with: gbrain sources list`);
+ process.exit(4);
+ }
+ const changing = clear || add.length > 0 || remove.length > 0;
+ const guest = changing ? await changeGuestWriters(engine, id, { clear, add, remove }) : await readGuestSource(engine, id);
+ if (!guest) {
+ console.error(`Source "${id}" is not a guest source, so it has no writer list. Set one up with: gbrain guests init --source <id>`);
+ process.exit(2);
+ }
+ if (json) { console.log(JSON.stringify({ source: guest.source_id, writers: guest.writers, trust_ceiling: guest.trust_ceiling })); return; }
+ console.log(`${changing ? 'Writers of' : 'Guest source'} "${id}"${changing ? ' are now' : ' writers'}: ${guest.writers.length > 0 ? guest.writers.join(', ') : 'none (nobody can create or change its pages)'}`);
+}
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index be38cdad07..86c3d68b3e 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -1975,6 +1975,7 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<v
case 'set-cr-mode': return runSetCrMode(engine, rest);
case 'set-calendar': return (await import('./sources-set-calendar.ts')).runSetCalendar(engine, rest);
case 'set-trust': { const { runSetTrust } = await import('./sources-trust.ts'); return runSetTrust(engine, rest); }
+ case 'writers': { const { runSourcesWriters } = await import('./sources-writers.ts'); return runSourcesWriters(engine, rest); }
// #4739 non-destructive local_path pointer repair
case 'set-path': { const { runSetPath } = await import('./sources-set-path.ts'); return runSetPath(engine, rest); }
case 'shared-skills': { const { runSourcesSharedSkills } = await import('./sources-shared-skills.ts'); return runSourcesSharedSkills(engine, rest); }
@@ -2084,6 +2085,7 @@ Subcommands:
to the global search.mode bundle).
set-calendar <id> <calendar-id> [--yes] Point a Google source at another calendar (ids: gbrain google calendars).
set-trust <id> <tier>|--clear Trust default for this source's sync and import (operator_curated or lower).
+ writers <id> [--add|--remove <w>] [--clear] [--json] Who may write a guest source (set one up: gbrain guests init).
set-path <id> <path> [--force] Repair a source's local_path pointer
(DB column only, never touches disk).
--force skips the overlapping-path guard.
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index b60e574bfa..7439efcebd 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -76,6 +76,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'git': ['--abbrev-ref', '--absolute-git-dir', '--add', '--aggressive', '--all', '--allow-outside-source-root', '--assume-unchanged', '--attr-source', '--autostash', '--base', '--batch', '--batch-check', '--before', '--brain', '--branch', '--cached', '--cacheinfo', '--cc', '--cherry-mark', '--combined', '--count', '--diff-filter', '--dry-run', '--dst-prefix', '--enable', '--end-of-options', '--error-unmatch', '--exclude-standard', '--exit-code', '--expect-remote', '--ff-only', '--file', '--force', '--force-remove', '--force-with-lease', '--format', '--from', '--full-index', '--get', '--get-all', '--get-regexp', '--get-url', '--git', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--help', '--ignore-unmatch', '--index-info', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-checkout', '--local', '--local-env-vars', '--max-count', '--merge-base', '--message', '--mode', '--name-only', '--name-status', '--no-assume-unchanged', '--no-autostash', '--no-color', '--no-commit-id', '--no-cron', '--no-ext-diff', '--no-follow-tags', '--no-gpg-sign', '--no-index', '--no-merges', '--no-optional-locks', '--no-recurse-submodules', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-textconv', '--no-verify', '--no-write-fetch-head', '--not', '--only', '--others', '--parents', '--pat-file', '--path', '--path-format', '--pending', '--porcelain', '--pull', '--push', '--push-only', '--quiet', '--rebase', '--recurse-submodules', '--repo', '--request-id', '--require-clean', '--resolve', '--reverse', '--right-only', '--root', '--scan-secrets', '--scan-timeout', '--short', '--show-prefix', '--show-toplevel', '--skip-worktree', '--source', '--source-id', '--src-prefix', '--staged', '--stat', '--stdin', '--to', '--topo-order', '--type', '--unified', '--uninstall', '--unset', '--unset-all', '--untrack', '--untracked-files', '--verify', '--worktree', '--write-tree'],
'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embed', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--plan', '--port', '--prefer-postgres', '--probe', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--search-mode', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],
+ 'guests': ['--add', '--brain', '--help', '--json', '--source', '--writer', '--yes'],
'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--catalog', '--count', '--diff-filter', '--dir', '--enable', '--end-of-options', '--env', '--force-with-lease', '--gbrain-bin', '--get', '--harness', '--heads', '--help', '--instructions', '--instructions-only', '--is-ancestor', '--jq', '--json', '--limit', '--name-only', '--no-follow-tags', '--no-instructions', '--no-tags', '--only', '--others', '--pat-file', '--path', '--porcelain', '--print', '--pure', '--quiet', '--recurse-submodules', '--remove', '--scope', '--sdk-url', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--source-ids', '--verify', '--workspace', '--yes'],
'import': ['--accept-pending', '--access-policy', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--as', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--room', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers', '--yes'],
'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--admin-intent', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--allow-without-owner', '--anchor', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--background', '--base', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--catch-up', '--channel', '--chat-model', '--check', '--check-downgrade', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--decisions', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--file', '--filter', '--first-parent', '--fix', '--force', '--force-retry', '--force-schema', '--format', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-failures', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--list-out', '--local', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-stdio-member', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--reason', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remote', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--safe', '--save', '--scan-secrets', '--scan-timeout', '--schedule', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--take', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--uninstall', '--unsettle', '--untrack', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],
@@ -116,7 +117,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--allow-without-owner', '--apply', '--as', '--audit', '--auto-additive', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--conflicts', '--cursor', '--cwd', '--day', '--diff', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--generation', '--held', '--help', '--id', '--include-ambiguous', '--include-cross-entity', '--include-failures', '--include-repairs', '--json', '--keep', '--key', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--mode', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--out', '--prefer', '--preview', '--principal', '--probe', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--readers', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--room', '--rules', '--run', '--scopes', '--seat', '--session', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],
'repair-jsonb': ['--accept-pending', '--as', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--room', '--source', '--supabase', '--timeout', '--timings', '--url', '--wait'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--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', '--approval-out', '--approved', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--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', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--force-with-lease', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--heads', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--list-out', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-edit', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-follow-tags', '--no-harden', '--no-lanes', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--readers', '--reads-unscoped', '--rebase', '--recurse-submodules', '--redirect-uri', '--refresh-operations', '--remote', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--sample', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--stat', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--uninstall', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
+ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--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', '--approval-out', '--approved', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--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', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--force-with-lease', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--heads', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--list-out', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-edit', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-follow-tags', '--no-harden', '--no-lanes', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--readers', '--reads-unscoped', '--rebase', '--recurse-submodules', '--redirect-uri', '--refresh-operations', '--remote', '--remove', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--sample', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--stat', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--uninstall', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],
'retrieval-upgrade': ['--accept-pending', '--all', '--as', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--plan', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--room', '--slugs', '--source', '--stale', '--status', '--timeout', '--timings', '--to', '--wait', '--yes'],
'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],
@@ -131,7 +132,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'skillpack': ['--accept-historical', '--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fail-on-skipped', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-diff', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--update-untouched', '--url', '--verify', '--version', '--workspace', '--yes'],
'skillpack-check': ['--accept-pending', '--as', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--room', '--source', '--strict', '--timeout', '--timings', '--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', '--approval-out', '--approved', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--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', '--channels', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-with-lease', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--heads', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--list-out', '--local', '--local-env-vars', '--lookback-days', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--max-requests', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-accept-pending', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-edit', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-follow-tags', '--no-harden', '--no-lanes', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--progress-interval', '--progress-json', '--provider', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--readers', '--reads-unscoped', '--rebase', '--record', '--recurse-submodules', '--redirect-uri', '--refresh-operations', '--remote', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--room', '--sample', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--skip', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--stat', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--sync-interval-min', '--takes-holders', '--timeout', '--timezone', '--timings', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--transcript', '--unindexed', '--uninstall', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--visibility', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
+ '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', '--approval-out', '--approved', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--background', '--backups', '--batch-check', '--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', '--channels', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-with-lease', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--heads', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--list-out', '--local', '--local-env-vars', '--lookback-days', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--max-requests', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-accept-pending', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-edit', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-follow-tags', '--no-harden', '--no-lanes', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--progress-interval', '--progress-json', '--provider', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--readers', '--reads-unscoped', '--rebase', '--record', '--recurse-submodules', '--redirect-uri', '--refresh-operations', '--remote', '--remove', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--room', '--sample', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--skip', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--stat', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--sync-interval-min', '--takes-holders', '--timeout', '--timezone', '--timings', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--transcript', '--unindexed', '--uninstall', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--visibility', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--check', '--code', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--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', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--reason', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--apply', '--as', '--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', '--retry-failed', '--room', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],
@@ -198,6 +199,7 @@ export const CLI_ROUTING_FLAGS: Record<string, readonly string[]> = {
'forget': ['--brain'],
'founder': ['--brain'],
'graph-query': ['--brain', '--source'],
+ 'guests': ['--brain'],
'import': ['--brain', '--source'],
'jobs': ['--brain'],
'loops': ['--brain', '--source'],
diff --git a/src/core/guests/sources.ts b/src/core/guests/sources.ts
new file mode 100644
index 0000000000..10ad1e9ed8
--- /dev/null
+++ b/src/core/guests/sources.ts
@@ -0,0 +1,75 @@
+/**
+ * Guest sources (GBRA-504): the reads and writes behind `gbrain guests init` and
+ * `gbrain sources writers`. guest_sources is the authority the trust trigger
+ * reads (guests/schema.ts); sources.config carries `guest: true` and
+ * `trust_ceiling` for people and `gbrain sources list`, and `federated: true`
+ * so owner reads that widen to federated sources include it.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { Principal } from '../persistence/model.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { addSource } from '../sources-ops.ts';
+import type { TrustTier } from '../trust/tier.ts';
+
+export const GUEST_TRUST_CEILING: TrustTier = 'external_untrusted';
+const PRINCIPAL_KINDS: readonly Principal['kind'][] = ['oauth_client', 'legacy_token', 'local_cli', 'local_stdio', 'application'];
+/** How a writer is named: the persistence attribution principal, `<kind>:<id>`. */
+export const GUEST_WRITER_FORMAT = `<${PRINCIPAL_KINDS.join('|')}>:<id>`;
+
+/** True when `value` names a principal the way the trust trigger compares it. */
+export function isGuestWriter(value: string): boolean {
+ const at = value.indexOf(':');
+ return at > 0 && (PRINCIPAL_KINDS as readonly string[]).includes(value.slice(0, at)) && /^[\x21-\x7e]{1,200}$/.test(value.slice(at + 1));
+}
+
+export interface GuestSource { source_id: string; writers: string[]; trust_ceiling: string }
+
+export async function readGuestSource(engine: BrainEngine, sourceId: string): Promise<GuestSource | null> {
+ const [row] = await engine.executeRaw<GuestSource>('SELECT source_id, writers, trust_ceiling FROM guest_sources WHERE source_id = $1', [sourceId]);
+ return row ?? null;
+}
+
+export interface GuestSourcePlan { sourceId: string; exists: boolean; localPath: string | null; guest: GuestSource | null; writers: string[] }
+
+/** What `guests init` would do, read without writing. `writers` is the list after the run (existing ones kept). */
+export async function planGuestSource(engine: BrainEngine, sourceId: string, writers: readonly string[]): Promise<GuestSourcePlan> {
+ const [source] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id = $1', [sourceId]);
+ const guest = source ? await readGuestSource(engine, sourceId) : null;
+ return { sourceId, exists: !!source, localPath: source?.local_path ?? null, guest, writers: [...new Set([...(guest?.writers ?? []), ...writers])].sort() };
+}
+
+/**
+ * Makes `sourceId` a guest source: creates it database-only and federated when
+ * missing, sets its guest config and writes its guest_sources row, in one
+ * transaction (a managed brain creates the source through its lifecycle first).
+ * The database refuses a source with a local_path (guest_source_database_only).
+ */
+export async function initGuestSource(engine: BrainEngine, sourceId: string, writers: readonly string[]): Promise<GuestSource> {
+ const managed = await managedPersistenceEnabled(engine);
+ if (managed && !(await planGuestSource(engine, sourceId, [])).exists) await addSource(engine, { id: sourceId, federated: true });
+ return engine.transaction(async tx => {
+ const [source] = await tx.executeRaw<{ id: string }>('SELECT id FROM sources WHERE id = $1 FOR UPDATE', [sourceId]);
+ if (!source) await addSource(tx, { id: sourceId, federated: true });
+ await tx.executeRaw(`UPDATE sources SET config = config || jsonb_build_object('federated', true, 'guest', true, 'trust_ceiling', $2::text) WHERE id = $1`,
+ [sourceId, GUEST_TRUST_CEILING]);
+ const [row] = await tx.executeRaw<GuestSource>(`INSERT INTO guest_sources (source_id, writers, trust_ceiling) VALUES ($1, $2::text[], $3)
+ ON CONFLICT (source_id) DO UPDATE SET writers = ARRAY(SELECT DISTINCT w FROM unnest(guest_sources.writers || EXCLUDED.writers) AS w ORDER BY w)
+ RETURNING source_id, writers, trust_ceiling`, [sourceId, [...new Set(writers)].sort(), GUEST_TRUST_CEILING]);
+ return row!;
+ });
+}
+
+export type WritersChange = { clear?: boolean; add?: readonly string[]; remove?: readonly string[] };
+
+/** Applies a writer-list change (clear first, then removals, then additions); null when the source is not a guest source. */
+export async function changeGuestWriters(engine: BrainEngine, sourceId: string, change: WritersChange): Promise<GuestSource | null> {
+ return engine.transaction(async tx => {
+ const [row] = await tx.executeRaw<GuestSource>('SELECT source_id, writers, trust_ceiling FROM guest_sources WHERE source_id = $1 FOR UPDATE', [sourceId]);
+ if (!row) return null;
+ const removed = new Set(change.remove ?? []);
+ const writers = [...new Set([...(change.clear ? [] : row.writers.filter(w => !removed.has(w))), ...(change.add ?? [])])].sort();
+ const [updated] = await tx.executeRaw<GuestSource>('UPDATE guest_sources SET writers = $2::text[] WHERE source_id = $1 RETURNING source_id, writers, trust_ceiling',
+ [sourceId, writers]);
+ return updated!;
+ });
+}
diff --git a/test/cli-dispatch-phase.test.ts b/test/cli-dispatch-phase.test.ts
index f3d9196b8d..a99de684d4 100644
--- a/test/cli-dispatch-phase.test.ts
+++ b/test/cli-dispatch-phase.test.ts
@@ -89,7 +89,7 @@ describe('CLI dispatch shape (master AST)', () => {
const shape = await expectNormalizerStable(extractCliDispatch, astNormalizer);
expect(shape.sets.CLI_ONLY).toEqual([...CLI_ONLY].sort());
expect(shape.sets.THIN_CLIENT_REFUSED_COMMANDS).toEqual([...THIN_CLIENT_REFUSED_COMMANDS].sort());
- expect(shape.switchCases.length).toBe(73);
+ expect(shape.switchCases.length).toBe(74);
expect(Object.keys(shape.commands).length).toBeGreaterThanOrEqual(shape.sets.CLI_ONLY.length);
});
diff --git a/test/fixtures/goldens/cli/dispatch-phase.json b/test/fixtures/goldens/cli/dispatch-phase.json
index b10c119d4e..f72297f790 100644
--- a/test/fixtures/goldens/cli/dispatch-phase.json
+++ b/test/fixtures/goldens/cli/dispatch-phase.json
@@ -1032,6 +1032,13 @@
"thinClient": "none",
"thinClientRoutedSubcommands": []
},
+ "guests": {
+ "hasSwitchCase": true,
+ "phase": "post-connect",
+ "preConnectRules": [],
+ "thinClient": "refuse",
+ "thinClientRoutedSubcommands": []
+ },
"hook": {
"hasSwitchCase": false,
"phase": "pre-connect",
diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.json
index 4d69db6bee..bf2ffa1c88 100644
--- a/test/fixtures/goldens/cli/help-and-errors.json
+++ b/test/fixtures/goldens/cli/help-and-errors.json
@@ -157,6 +157,7 @@
" sources archived List soft-deleted sources and their purge expiry",
" sources purge [<id>] Permanently delete archived sources",
" sources status Per-source dashboard (sync lag, embed coverage)",
+ " guests init [--writer <w>] [--yes] Set up a guest source for outside guests' notes",
" sources --help Full subcommand list (rename, default, attach,",
" current, federate, set-cr-mode, webhook, harden, ...)",
" sync --all Sync all sources with a local_path",
@@ -390,6 +391,7 @@
" sources archived List soft-deleted sources and their purge expiry",
" sources purge [<id>] Permanently delete archived sources",
" sources status Per-source dashboard (sync lag, embed coverage)",
+ " guests init [--writer <w>] [--yes] Set up a guest source for outside guests' notes",
" sources --help Full subcommand list (rename, default, attach,",
" current, federate, set-cr-mode, webhook, harden, ...)",
" sync --all Sync all sources with a local_path",
@@ -623,6 +625,7 @@
" sources archived List soft-deleted sources and their purge expiry",
" sources purge [<id>] Permanently delete archived sources",
" sources status Per-source dashboard (sync lag, embed coverage)",
+ " guests init [--writer <w>] [--yes] Set up a guest source for outside guests' notes",
" sources --help Full subcommand list (rename, default, attach,",
" current, federate, set-cr-mode, webhook, harden, ...)",
" sync --all Sync all sources with a local_path",
diff --git a/test/fixtures/goldens/cli/literal-imports.json b/test/fixtures/goldens/cli/literal-imports.json
index b4ffa27299..2c1109dca2 100644
--- a/test/fixtures/goldens/cli/literal-imports.json
+++ b/test/fixtures/goldens/cli/literal-imports.json
@@ -99,6 +99,9 @@
"graph-query": [
"./commands/graph-query.ts"
],
+ "guests": [
+ "./commands/guests.ts"
+ ],
"import": [
"./commands/import.ts",
"./core/agent-output.ts",
diff --git a/test/fixtures/goldens/cli/membership-sets.json b/test/fixtures/goldens/cli/membership-sets.json
index 6c21b738c7..d29512431c 100644
--- a/test/fixtures/goldens/cli/membership-sets.json
+++ b/test/fixtures/goldens/cli/membership-sets.json
@@ -73,6 +73,7 @@
"diag",
"edge-proposals",
"feedback",
+ "guests",
"memory-proposals",
"questions",
"trust",
@@ -155,6 +156,7 @@
"git",
"google",
"graph-query",
+ "guests",
"hook",
"import",
"init",
@@ -276,6 +278,7 @@
"git",
"google",
"graph-query",
+ "guests",
"hook",
"init",
"integrations",
@@ -415,6 +418,7 @@
"facts",
"feedback",
"files",
+ "guests",
"integrity",
"memory-proposals",
"migrate",
diff --git a/test/guests-cli.test.ts b/test/guests-cli.test.ts
new file mode 100644
index 0000000000..96ad5c221c
--- /dev/null
+++ b/test/guests-cli.test.ts
@@ -0,0 +1,139 @@
+/**
+ * gbrain guests init and gbrain sources writers (GBRA-504 slice 1).
+ *
+ * Protects: init previews by default and writes nothing; --yes creates the
+ * guest source database-only, federated and marked guest with its ceiling, and
+ * its guest_sources row with the writer list, in one go; init refuses a source
+ * that has a local_path and a malformed writer; sources writers lists, adds,
+ * removes and clears writers and refuses a source that is not a guest source;
+ * set-path refuses a guest source. PGLite, no repository, no embedding key.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import { mkdtempSync, rmSync } 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 { runGuests } from '../src/commands/guests.ts';
+import { runSources } from '../src/commands/sources.ts';
+
+let engine: PGLiteEngine;
+let origExit: typeof process.exit;
+let exitCode: number | null;
+let out: string[];
+let err: string[];
+let spies: Array<{ mockRestore: () => void }> = [];
+const tmpDirs: string[] = [];
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+ for (const d of tmpDirs) rmSync(d, { recursive: true, force: true });
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ exitCode = null; out = []; err = [];
+ origExit = process.exit;
+ (process as unknown as { exit: (n: number) => never }).exit = ((n: number) => {
+ exitCode = n;
+ throw new Error(`__test_exit_${n}__`);
+ }) as never;
+ spies = [
+ spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.join(' ')); }),
+ spyOn(console, 'error').mockImplementation((...a: unknown[]) => { err.push(a.join(' ')); }),
+ ];
+});
+
+afterEach(() => {
+ process.exit = origExit;
+ for (const spy of spies) spy.mockRestore();
+});
+
+const run = (fn: () => Promise<void>) => fn().catch((e: Error) => { if (!/^__test_exit_/.test(e.message)) throw e; });
+const sourceRow = async (id: string) => (await engine.executeRaw<{ local_path: string | null; config: unknown }>(
+ 'SELECT local_path, config FROM sources WHERE id=$1', [id]))[0];
+const guestRow = async (id: string) => (await engine.executeRaw<{ writers: string[]; trust_ceiling: string }>(
+ 'SELECT writers, trust_ceiling FROM guest_sources WHERE source_id=$1', [id]))[0];
+const configOf = (config: unknown) => (typeof config === 'string' ? JSON.parse(config) : config) as Record<string, unknown>;
+
+describe('gbrain guests init', () => {
+ test('previews by default and writes nothing', async () => {
+ await run(() => runGuests(engine, ['init', '--writer', 'oauth_client:client-a']));
+ expect(exitCode).toBeNull();
+ expect(out.join('\n')).toContain('guests');
+ expect(out.join('\n')).toContain('--yes');
+ expect(await sourceRow('guests')).toBeUndefined();
+ expect(await engine.executeRaw('SELECT 1 FROM guest_sources')).toEqual([]);
+ });
+
+ test('--yes creates a database-only, federated guest source and its writer list', async () => {
+ await run(() => runGuests(engine, ['init', '--writer', 'oauth_client:client-a', '--writer', 'legacy_token:token-a', '--yes']));
+ expect(exitCode).toBeNull();
+ const source = await sourceRow('guests');
+ expect(source?.local_path).toBeNull();
+ expect(configOf(source?.config)).toMatchObject({ federated: true, guest: true, trust_ceiling: 'external_untrusted' });
+ expect(await guestRow('guests')).toEqual({ writers: ['legacy_token:token-a', 'oauth_client:client-a'], trust_ceiling: 'external_untrusted' });
+ });
+
+ test('--source names the source, and a second run adds writers', async () => {
+ await run(() => runGuests(engine, ['init', '--source', 'source-a', '--writer', 'oauth_client:client-a', '--yes']));
+ await run(() => runGuests(engine, ['init', '--source', 'source-a', '--writer', 'oauth_client:client-b', '--yes']));
+ expect(exitCode).toBeNull();
+ expect((await guestRow('source-a'))?.writers).toEqual(['oauth_client:client-a', 'oauth_client:client-b']);
+ });
+
+ test('refuses a source that has a local_path', async () => {
+ await engine.executeRaw(`INSERT INTO sources(id,name,local_path) VALUES('source-a','source-a','/tmp/source-a')`);
+ await run(() => runGuests(engine, ['init', '--source', 'source-a', '--yes']));
+ expect(exitCode).toBe(2);
+ expect(err.join('\n')).toContain('database-only');
+ expect(await guestRow('source-a')).toBeUndefined();
+ });
+
+ test('refuses a malformed writer', async () => {
+ await run(() => runGuests(engine, ['init', '--writer', 'client-a', '--yes']));
+ expect(exitCode).toBe(2);
+ expect(await sourceRow('guests')).toBeUndefined();
+ });
+});
+
+describe('gbrain sources writers', () => {
+ test('lists, adds, removes and clears the writers of a guest source', async () => {
+ await run(() => runGuests(engine, ['init', '--writer', 'oauth_client:client-a', '--yes']));
+ await run(() => runSources(engine, ['writers', 'guests', '--add', 'oauth_client:client-b']));
+ expect((await guestRow('guests'))?.writers).toEqual(['oauth_client:client-a', 'oauth_client:client-b']);
+ await run(() => runSources(engine, ['writers', 'guests', '--remove', 'oauth_client:client-a']));
+ expect((await guestRow('guests'))?.writers).toEqual(['oauth_client:client-b']);
+ out = [];
+ await run(() => runSources(engine, ['writers', 'guests', '--json']));
+ expect(JSON.parse(out.join('\n'))).toEqual({ source: 'guests', writers: ['oauth_client:client-b'], trust_ceiling: 'external_untrusted' });
+ await run(() => runSources(engine, ['writers', 'guests', '--clear']));
+ expect((await guestRow('guests'))?.writers).toEqual([]);
+ expect(exitCode).toBeNull();
+ });
+
+ test('refuses a source that is not a guest source, and an unknown one', async () => {
+ await run(() => runSources(engine, ['writers', 'default', '--add', 'oauth_client:client-a']));
+ expect(exitCode).toBe(2);
+ expect(await engine.executeRaw('SELECT 1 FROM guest_sources')).toEqual([]);
+ exitCode = null;
+ await run(() => runSources(engine, ['writers', 'source-missing']));
+ expect(exitCode as number | null).toBe(4);
+ });
+
+ test('set-path refuses a guest source', async () => {
+ await run(() => runGuests(engine, ['init', '--yes']));
+ const dir = mkdtempSync(join(tmpdir(), 'gb-guests-'));
+ tmpDirs.push(dir);
+ await run(() => runSources(engine, ['set-path', 'guests', dir]));
+ expect(exitCode).toBe(2);
+ expect(err.join('\n')).toContain('database-only');
+ expect((await sourceRow('guests'))?.local_path).toBeNull();
+ });
+});