Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(persistence): G7b-2, sources host-repo hosts an empty source in a bare repository with a gbrain-owned linked worktree; a claim refuses a broken worktree link

garrytanf7a6a62f5e8d
diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.md
index c48ee82f3a..0cf6b662ab 100644
--- a/docs/architecture/key-files/core-persistence-request-indexes.md
+++ b/docs/architecture/key-files/core-persistence-request-indexes.md
@@ -14,3 +14,5 @@ The online-built request-table indexes (the managed sync checkpoint pair, the pa
- `src/core/persistence/{recovery-version,segmented-mirror-gate,segmented-gate-hold}.ts` — forward compatibility of recovery records. `recovery-version.ts` lists the record versions this binary reads (`EFFECT_RECOVERY_VERSIONS`, `REQUEST_RECOVERY_VERSIONS`); `assertRecoveryVersion` refuses any other `recovery_version_unsupported` (fix `gbrain upgrade`, `host_admin`) before a reader touches the record: `recoverEffectPublication`, `reserveEffectRecovery`, `rebaseStaleEffectRecovery` (the `--keep withdrawn` rebase), `upgradeRecoveryStaging` (both tables) and `model.ts` `recoveryFiles` (request recovery, clearing, stuck-recovery); the stuck-recovery preview (`recovery-resolve.ts` `scanStuckRecoveries`) lists such a record refused with that code and fix; `head-blocker.ts` reports such a record as an intervention with the same fix. `segmented-mirror-gate.ts`: `mirrorPage` calls `assertSegmentedMirrorGate` before streaming a segmented page's file; while `mirrorGateBlockers` sees a live writer below SEGMENTED_WRITER_FLOOR (the switch's TTL-cached `segmentedWriterBlockers`, filtered by `segmented-gate-hold.ts` `liveSegmentedBlockers`, the classification doctor `segmented_storage` uses: this host's own pre-upgrade writes superseded by the same kind of write from this build are not live; cached per gate read and host) it refuses `segmented_mirror_writer_gate` without reserving a record, and the target retries and parks as usual. `resumeGatedMirrors` (each effect pass, at most once per gate TTL per engine) requeues, via `retryParkedEffects`, requests whose parked targets all carry that code, or `withdrawal_mirror_failed` for the Git/embedding siblings parked behind the mirror (re-armed once it commits), once the gate is clear. No version 1 fallback: it would hold the file whole, and v0.60.290.0's recovery of it refuses to materialize a segmented page forever. Tests: `test/pathological/lp-d-recovery-version.test.ts`, `test/pathological/lp-d-segmented-mirror-gate.test.ts` (both engines).
- `src/core/persistence/effect-links.ts` — the `links` effect of a remote page write (`mcp.remote_auto_links`, link_source `mcp-remote-mention`). `runLinksEffect` reconciles a put_page/capture/edit_page page's plain mention edges against its whole compiled truth at the published revision (a later revision skips it as `superseded`), keeping targets that exist in the source, are visible to the writer (`writableTargets`) and sit inside its slug grant, and records missing targets as wanted pages. #7122: an effect with `data.range` (a remote append_page to the compiled truth) is `runAppendLinksEffect`: it reads only those stored truth bytes with the writer's audience (`readBodyRange` with the remote audience on a segmented page, loading only the segments the range overlaps; on an inline page the raw stored truth (`inlineRegions`) with its protected regions cut out of the range, then `sanitizeRemoteBody`), applies the same target filter and adds edges only, never removing one or replacing wanted rows. At a later revision it still runs when the range's trusted bytes hash to `data.range.sha256` (two appends whose effects run after both link both) and is skipped as `superseded` otherwise (an inline range is hash-checked at its own revision too); a write that lands between its read and its page lock is decided the same way under the lock, by reading the range again at the live revision, so a busy page never makes it retry. Tests: `test/persistence-links-effect.test.ts`, `test/large-pages/append-mention-links.test.ts` (both engines; readSegmentTexts spy).
- `src/core/persistence/pending-import.ts` `landedCommit` with `recoverPublication` (`coordinator.ts`) and `completeWrite` (`journal.ts`) — G7b: on a strict source, a request whose door commit landed before its row is requeued with `outcome.persistence = {git_state: committed, git_commit, landed_before_row: true}` (the newest commit in the record's `door.head..HEAD` that touched its path; none in that range stamps nothing). `completeWrite` keeps it on a receipt that ends without committing (a grant revoked before the replay, a charged interruption), so the caller sees the bytes are in Git and will be indexed; a committed replay writes the ordinary door receipt. Tests: `test/git-door-remote-g7b.test.ts` (both engines; remote OAuth and legacy-token callers, owner down, revoked grant, group commit).
+- `src/core/persistence/hosted-repo.ts` with `src/commands/sources-host-repo.ts` — G7b-2, `gbrain sources host-repo <id> --dir <path> [--push-remote <url>] [--dry-run | --expect <plan_hash>]`: a hosted brain gives an empty, unbound source a bare repository (`<dir>/repo.git`, branch `main`, one commit holding an empty `.gitignore`, repository-local identity `gbrain`) and checks it out as a linked worktree (`<dir>/worktree`) claimed through `runManagedSourceLifecycle` (`add` or `claim`, every physical-root and manifest check), with `config.canonical = "git"` and `config.hosted_repo` set in the claim's own transaction. The door then commits there unchanged. A pre-receive hook (`core.hooksPath` pinned to the repository's `hooks/`) refuses every push, since Git's checked-out-branch refusal ends once the worktree is pruned. The preview (the default without `--expect`) prints the plan in words and a `plan_hash` over the source incarnation, canonical setting, directory state, push remote and hook; the apply refuses `preview_changed` when it moved. Refuses `strict_requires_managed` on an unmanaged brain, `hosted_repo_refused` (`source_bound`, `source_has_path`, `source_has_pages`, `source_archived`, `dir_not_empty`) and `overlapping_path` (a directory in a checkout or a source's directory). On a hosted source the preview reports the hook (`ok`/`missing`/`changed`) and the worktree link, and the apply reinstalls the hook. Trusted local CLI only; no operation. Tests: `test/hosted-repo-g7b2.test.ts` (both engines).
+- `src/core/persistence/worktree-link.ts` `linkedWorktreeProblem` / `assertLinkedWorktreeIntact` — a claim (`localRoot` in `source-lifecycle.ts`) refuses `git_worktree_link_broken` for a linked worktree whose `.git` file names a repository entry that is gone (pruned) or whose entry names another path (the checkout moved); a submodule's `.git` file is checked for existence only. Tests: `test/hosted-repo-g7b2.test.ts`.
diff --git a/docs/designs/GIT_CANONICAL_MEMORY.md b/docs/designs/GIT_CANONICAL_MEMORY.md
index e3b746327c..1db570e34e 100644
--- a/docs/designs/GIT_CANONICAL_MEMORY.md
+++ b/docs/designs/GIT_CANONICAL_MEMORY.md
@@ -72,6 +72,8 @@ A write from a remote MCP caller or a thin client becomes a journal request that
The request carries the bytes, the expected revision, the idempotency key (`request_id`) and the caller's grant, and the owner re-authorizes it against the live grant inside the publication transaction, before the door commit. A grant revoked while the request waits is refused with no commit and no row. If a door commit landed and the transaction then failed, the request is replayed; should the replay end without committing (its grant revoked meanwhile), the receipt still names the landed commit (`outcome.persistence.landed_before_row`), because Git holds those bytes and the indexer will import them: they were authorized when they were committed, and a later revocation does not retract committed content.
+A hosted source (`gbrain sources host-repo`, G7b-2) keeps one bare repository per source and a gbrain-owned linked worktree of it, claimed with the same claim and physical-root checks as any canonical worktree, so the door, recovery, receipts and the push effect are unchanged: a door commit moves the branch the worktree shares with the bare repository. Only the door moves that branch. A pre-receive hook refuses every push, because Git's own refusal to update a checked-out branch ends once the worktree is removed and pruned; door commits are local ref updates and the push to the user's repository is outgoing, so neither passes the hook. A claim refuses a linked worktree whose link is broken (`git_worktree_link_broken`). The verb starts only from an empty source; adopting existing pages is conversion. A doctor check for a missing or changed hook is a G8 follow-up; until then the verb's preview reports it.
+
## Conversion
A source changes mode only through a preview-bound verb. The preview is the [git-gap census](#the-git-gap-census): every page whose row differs from its committed blob, every page with no file that is not in a declared class, held items and parked effects, by category. The operator chooses per category to commit the database content through the door, declare it, or let git win. The preview lists any database content that git-wins would discard, and the apply binds to that preview. A source can return to its previous mode.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index b4791a76de..862b0827b2 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1763,6 +1763,14 @@ More: [docs/guides/shared-checkout-git.md#stuck-rebase](../../docs/guides/shared
|---|---|---|---|---|---|---|
| A git command did not complete. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |
+### git_worktree_link_broken
+
+<a id="git_worktree_link_broken"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The directory is a linked Git worktree whose link to its repository is broken (the repository's entry was pruned, or the checkout moved), so it cannot be claimed as a canonical worktree; nothing was claimed. | A linked worktree reaches its commits through a .git file naming an entry in the repository, and the repository names the worktree back. With either link broken, Git commands in the directory fail or the next git worktree prune deletes the entry, so a door commit would go nowhere. | From the repository, run git worktree repair on the worktree when both still exist, or add the worktree again with git worktree add, then rerun the claim. | host_admin | `gbrain doctor --json` | 1 | no |
+
### gitlink_not_followed
<a id="gitlink_not_followed"></a>
@@ -2017,6 +2025,18 @@ More: [docs/guides/write-refusals.md#head-blocked](../../docs/guides/write-refus
More: [docs/guides/troubleshooting.md#host-identity-mismatch](../../docs/guides/troubleshooting.md#host-identity-mismatch)
+### hosted_repo_refused
+
+<a id="hosted_repo_refused"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| gbrain sources host-repo starts a hosted repository only for an empty, unbound source and an absent or empty directory; nothing was created. | The verb makes a new bare repository the source of truth for the source. Existing pages or an existing directory would need converting into it, which is a separate step, so it refuses instead of guessing. | Pick a new source ID and an empty directory, or keep this source as it is. | agent | `repeat the read that failed` | 1 | no |
+
+Reasons: `source_bound`, `source_has_pages`, `source_has_path`, `source_archived`, `dir_not_empty`.
+
+More: [docs/designs/GIT_CANONICAL_MEMORY.md#remote-and-hosted-writes](../../docs/designs/GIT_CANONICAL_MEMORY.md#remote-and-hosted-writes)
+
### idempotency_conflict
<a id="idempotency_conflict"></a>
diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.md
index 8b2b0c307a..a682158704 100644
--- a/docs/guides/multi-source-brains.md
+++ b/docs/guides/multi-source-brains.md
@@ -245,8 +245,33 @@ gbrain sources set-sync <id> <on|off> [--dry-run] [--expect <on|off>]
(config.syncEnabled; an explicit gbrain sync --source
still runs). --dry-run prints the apply command, which
carries --expect; a moved state refuses preview_changed.
+gbrain sources host-repo <id> --dir <path> [--push-remote <url>] [--dry-run | --expect <plan_hash>]
+ Managed brains: host a new, empty source in a bare
+ repository under <path> (see below). Previews without --expect.
```
+### Hosted repositories
+
+`gbrain sources host-repo` gives a new, empty source its own bare repository
+(`<path>/repo.git`) that people clone and fetch from, and checks it out once
+as a linked worktree gbrain owns (`<path>/worktree`), claimed as the source's
+canonical worktree like any other. The source becomes git-canonical
+(`canonical: git`), so every page write, remote ones included, commits there
+through the door before the database indexes it. A pre-receive hook refuses
+every push into the repository; `--push-remote` names a repository of your own
+that the push effect publishes to once Git durability is enabled
+(`gbrain sources writer git-durability <id> --enable`).
+
+It runs only from the trusted local CLI on the brain host. The preview says in
+words that the source becomes strict and prints the apply command with its
+`--expect <plan_hash>`; a plan that moved refuses `preview_changed`. It refuses
+a source that is bound or already has pages (moving existing pages into a
+hosted repository is conversion, a later wave), and a directory that is not
+empty or sits inside a checkout or another source's directory. On a hosted
+source the preview reports the hook and the worktree link, and the apply
+reinstalls a missing or changed hook. An agent runs it on a production brain
+only with the user's explicit yes, one source at a time.
+
### Read-only mirror sources
A source whose Git remote is the source of truth (a code or docs repository
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 2739b2d179..832747863a 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -30,7 +30,7 @@ src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 conne
src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)
src/commands/bootstrap.ts 2147 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts)
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 2085 ratchet +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)
+src/commands/sources.ts 2088 ratchet +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)
src/core/link-extraction.ts 2424 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
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/commands/sources-host-repo.ts b/src/commands/sources-host-repo.ts
new file mode 100644
index 0000000000..58d8234052
--- /dev/null
+++ b/src/commands/sources-host-repo.ts
@@ -0,0 +1,55 @@
+/**
+ * `gbrain sources host-repo <id> --dir <path> [--push-remote <url>] [--dry-run | --expect <plan_hash>] [--json]` (G7b-2):
+ * the CLI face of src/core/persistence/hosted-repo.ts. Without --expect it previews; the apply is the command the preview
+ * prints. Trusted local CLI only (no operation exposes it), and every run on a production source needs the user's yes.
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import { setCliExitVerdict } from '../core/cli-force-exit.ts';
+import { OperationError, opError } from '../core/ops/contract.ts';
+import { cliRenderContext, toAgentError } from '../core/agent-output.ts';
+import { hostRepo, type HostRepoOptions, type HostRepoPlan } from '../core/persistence/hosted-repo.ts';
+
+const USAGE = 'gbrain sources host-repo <id> --dir <path> [--push-remote <url>] [--dry-run | --expect <plan_hash>] [--json]';
+
+export function parseHostRepoArgs(args: string[]): HostRepoOptions {
+ const positional: string[] = [];
+ let dir: string | undefined, pushRemote: string | undefined, expect: string | undefined, dryRun = false;
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i]!;
+ if (arg === '--json') continue;
+ if (arg === '--dry-run') { dryRun = true; continue; }
+ if (arg === '--dir') { dir = args[++i]; continue; }
+ if (arg === '--push-remote') { pushRemote = args[++i]; continue; }
+ if (arg === '--expect') { expect = args[++i]; continue; }
+ if (arg.startsWith('-')) throw opError('invalid_params', `Unknown flag ${arg}.`, `Usage: ${USAGE}`);
+ positional.push(arg);
+ }
+ if (positional.length !== 1 || !dir) throw opError('invalid_params', 'Name one source and its --dir.', `Usage: ${USAGE}`);
+ if (expect !== undefined && !/^[a-f0-9]{64}$/.test(expect)) throw opError('invalid_params', '--expect takes the plan_hash the preview printed.', `Usage: ${USAGE}`);
+ if (dryRun && expect !== undefined) throw opError('invalid_params', 'Pass --dry-run or --expect, not both.', `Usage: ${USAGE}`);
+ return { sourceId: positional[0]!, dir, dryRun, ...(pushRemote !== undefined ? { pushRemote } : {}), ...(expect !== undefined ? { expect } : {}) };
+}
+
+function describe(plan: HostRepoPlan): string {
+ const lines = [...plan.summary];
+ if (plan.dry_run) {
+ lines.push(`Hook: ${plan.hook.state} (${plan.hook.path}); worktree link: ${plan.worktree_link}.`);
+ lines.push(plan.apply ? `Apply (after the user agrees): ${plan.apply.join(' ')}` : 'Nothing to apply.');
+ } else lines.push(plan.action === 'host' ? `Done: source ${plan.source_id} is hosted at ${plan.repository}.`
+ : plan.action === 'reinstall_hook' ? 'Done: the pre-receive hook is reinstalled.' : 'Nothing changed.');
+ for (const step of plan.next) lines.push(`Next: ${step.join(' ')}`);
+ return lines.join('\n');
+}
+
+export async function runHostRepo(engine: BrainEngine, args: string[]): Promise<void> {
+ const json = args.includes('--json');
+ try {
+ const plan = await hostRepo(engine, parseHostRepoArgs(args));
+ console.log(json ? JSON.stringify(plan) : describe(plan));
+ } catch (error) {
+ if (!(error instanceof OperationError)) throw error;
+ const env = toAgentError(error, { transport: 'cli', command: 'sources host-repo', render: cliRenderContext() });
+ console.log(json ? JSON.stringify(env) : `Refused (${error.code}): ${error.message}\nFix: ${error.suggestion ?? USAGE}`);
+ setCliExitVerdict(error.code === 'invalid_params' ? 2 : 1);
+ }
+}
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index 3a07aa5093..503b08fb6c 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -1910,6 +1910,7 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<v
case 'set-sync': return (await import('./sources-sync-enabled.ts')).runSetSync(engine, rest);
case 'refresh': return (await import('./sources-refresh.ts')).runSourcesRefresh(engine, rest);
case 'git-gap': return (await import('./sources-git-gap.ts')).runSourcesGitGap(engine, rest);
+ case 'host-repo': return (await import('./sources-host-repo.ts')).runHostRepo(engine, rest);
case 'reindex': return (await import('./sources-reindex.ts')).runSourcesReindex(engine, rest);
case 'archive': return runArchive(engine, rest);
case 'restore': return runRestore(engine, rest);
@@ -2011,6 +2012,8 @@ Subcommands:
set-strategy <id> <markdown|code|auto> Persist the sync strategy every sync of the source uses (PR #5955).
set-pull-strategy <id> <rebase|merge> How pulls reconcile local commits with origin (#5429); default rebase.
set-sync <id> <on|off> [--dry-run] [--expect <on|off>] Include or exclude the source from automatic sync (config.syncEnabled).
+ host-repo <id> --dir <path> [--push-remote <url>] [--dry-run | --expect <plan_hash>]
+ Managed brains: host an empty source in a new bare repository with a gbrain-owned worktree; it becomes git-canonical.
refresh <id> [--dry-run] [--wait-drain <s>] [--fetch-timeout-ms <ms>] [--resume|--abandon] [--json]
Managed brains: drain writes to the source's worktree, fast-forward
it to its upstream (git merge --ff-only) and sync every source bound
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index c32c720170..12f34e190d 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -113,7 +113,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--cursor', '--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', '--prefer', '--probe', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--run', '--scopes', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],
'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--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', '--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', '--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', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--sample', '--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', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--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', '--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', '--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', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--sample', '--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', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],
'retrieval-upgrade': ['--accept-pending', '--all', '--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', '--slugs', '--source', '--stale', '--status', '--timeout', '--timings', '--to', '--wait', '--yes'],
'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],
@@ -127,7 +127,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],
'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--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', '--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', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--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', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--sample', '--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', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--timeout', '--timings', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--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', '--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', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--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', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--sample', '--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', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--timeout', '--timings', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--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', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index c271095709..77e9c3ad6b 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -319,6 +319,8 @@ export const CODES = {
docs: 'docs/guides/concurrent-writes.md#git-durability-at-activation',
suggestion: 'Preview gbrain sources writer git-durability <source> --enable --dry-run on the owner host, then apply it with --admin-intent writer_git_durability; enabling re-queues the Git effects that were skipped while it was off.' },
git_checkout_required: { class: 'host_only', summary: "The canonical root is not inside a Git checkout, so its Git effects have nothing to commit to.", suggestion: 'Initialize the root as a Git repository with a first commit and a remote on the brain host, then rerun; a database-only source needs no Git durability.' },
+ git_worktree_link_broken: { class: 'host_only', summary: "The directory is a linked Git worktree whose link to its repository is broken (the repository's entry was pruned, or the checkout moved), so it cannot be claimed as a canonical worktree; nothing was claimed.", why: 'A linked worktree reaches its commits through a .git file naming an entry in the repository, and the repository names the worktree back. With either link broken, Git commands in the directory fail or the next git worktree prune deletes the entry, so a door commit would go nowhere.', suggestion: 'From the repository, run git worktree repair on the worktree when both still exist, or add the worktree again with git worktree add, then rerun the claim.' },
+ hosted_repo_refused: { class: 'caller', reasons: ['source_bound', 'source_has_pages', 'source_has_path', 'source_archived', 'dir_not_empty'], summary: "gbrain sources host-repo starts a hosted repository only for an empty, unbound source and an absent or empty directory; nothing was created.", why: 'The verb makes a new bare repository the source of truth for the source. Existing pages or an existing directory would need converting into it, which is a separate step, so it refuses instead of guessing.', docs: 'docs/designs/GIT_CANONICAL_MEMORY.md#remote-and-hosted-writes', suggestion: 'Pick a new source ID and an empty directory, or keep this source as it is.' },
git_detached_head: { class: 'host_only', summary: "The canonical checkout is on a detached HEAD, so a push would target the wrong ref.", suggestion: 'Check out the branch the remote should track (git switch <branch>) on the brain host, then rerun.' },
git_index_locked: { class: 'retryable', summary: "Another Git process holds the canonical checkout index lock." },
git_index_stale: { class: 'caller', summary: "Git index stale." },
diff --git a/src/core/persistence/hosted-repo.ts b/src/core/persistence/hosted-repo.ts
new file mode 100644
index 0000000000..a2785de721
--- /dev/null
+++ b/src/core/persistence/hosted-repo.ts
@@ -0,0 +1,218 @@
+/**
+ * `gbrain sources host-repo` (G7b-2, docs/designs/GIT_CANONICAL_MEMORY.md "Remote and hosted writes"): a hosted brain
+ * keeps one bare repository per source, which is what a user clones and what pushes to the user's own remote. gbrain
+ * checks it out once as a linked worktree it owns (`git worktree add`) and claims that worktree as the source's canonical
+ * worktree through the ordinary claim, with every physical-root and manifest check. From then on the one door applies
+ * unchanged: a door commit moves the branch the worktree shares with the bare repository; recovery, receipts, remote
+ * writes and the push effect are the ones every strict source has.
+ *
+ * Nothing but the door moves the hosted branch. Git already refuses a push to a branch a worktree has checked out, but
+ * that stops once the worktree is gone and pruned, so a pre-receive hook refuses every push itself. The door's commits
+ * are local ref updates and never pass through receive-pack, and the push effect is outgoing, so the hook stops neither.
+ *
+ * Preview first: the dry run (the default without --expect) prints the plan in words, including that the source becomes
+ * strict (`canonical: git`), and its plan_hash; the apply recomputes the plan and refuses `preview_changed` when it
+ * moved. It starts only from an empty, unbound source and an absent or empty directory (`hosted_repo_refused`); adopting
+ * existing pages is conversion (G8). On an already hosted source the preview reports the hook and the worktree link, and
+ * the apply reinstalls a missing or changed hook. Trusted local CLI only: no operation exposes it.
+ */
+import { createHash } from 'node:crypto';
+import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { dirname, isAbsolute, join, resolve } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import { GIT_ENV } from '../git-remote.ts';
+import { gitChildEnv } from '../git-env.ts';
+import { opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import { execFileSync } from '../spawn.ts';
+import { parseSourceConfig } from '../sources-load.ts';
+import { isValidSourceId } from '../source-id.ts';
+import { containsPath, managedPersistenceEnabled } from './ownership.ts';
+import { assertLinkedWorktreeIntact, linkedWorktreeProblem } from './worktree-link.ts';
+
+export const HOSTED_BRANCH = 'main';
+const HOOK_BANNER = '# gbrain hosted-repo pre-receive hook (G7b-2)';
+
+export interface HostRepoOptions { sourceId: string; dir: string; pushRemote?: string; dryRun: boolean; expect?: string }
+export type HookState = 'install' | 'ok' | 'missing' | 'changed';
+export interface HostRepoPlan {
+ source_id: string; dry_run: boolean; action: 'host' | 'reinstall_hook' | 'none';
+ source: { registered: boolean; canonical: { before: string | null; after: 'git' } };
+ repository: string; worktree: string; branch: string; push_remote: string | null;
+ hook: { path: string; state: HookState }; worktree_link: 'ok' | 'broken' | 'absent';
+ summary: string[]; next: string[][]; plan_hash: string; apply?: string[];
+ claim?: Record<string, unknown>;
+}
+interface SourceRow { incarnation: string; archived: boolean; local_path: string | null; config: unknown }
+
+const git = (cwd: string, args: string[], input?: string) => execFileSync('git', ['-C', cwd, ...args],
+ { encoding: 'utf8', input, stdio: ['pipe', 'pipe', 'pipe'], timeout: 60_000, env: gitChildEnv({ ...GIT_ENV }) }).trim();
+const sha256 = (text: string) => createHash('sha256').update(text).digest('hex');
+const real = (path: string) => { try { return realpathSync(path); } catch { return resolve(path); } };
+
+/** The hook every hosted repository carries: it refuses every push and names the way in. */
+export function hostedHookScript(sourceId: string): string {
+ return ['#!/bin/sh', HOOK_BANNER,
+ '# The branches of this repository move only through the gbrain door. Door commits are local ref updates and the',
+ '# push to the user remote is outgoing, so neither passes this hook; every incoming push is refused.',
+ `echo "gbrain: this repository holds source ${sourceId}; only the gbrain writer moves its branches, so this push was refused and nothing changed." >&2`,
+ `echo "gbrain: write pages through gbrain instead (gbrain put --source ${sourceId}, or put_page over MCP), then fetch from here." >&2`,
+ 'exit 1', ''].join('\n');
+}
+
+/** Whether the repository's pre-receive hook is the one host-repo installs, and Git runs it from where it was installed. */
+export function hostedHookState(repository: string, sourceId: string): Exclude<HookState, 'install'> {
+ const path = join(repository, 'hooks', 'pre-receive');
+ let stat;
+ try { stat = statSync(path); } catch { return 'missing'; }
+ if (!stat.isFile() || (stat.mode & 0o111) === 0) return 'missing';
+ if (readFileSync(path, 'utf8') !== hostedHookScript(sourceId)) return 'changed';
+ let hooks: string;
+ try { hooks = git(repository, ['rev-parse', '--git-path', 'hooks']); } catch { return 'changed'; }
+ return real(resolve(repository, hooks)) === real(join(repository, 'hooks')) ? 'ok' : 'changed';
+}
+
+function installHook(repository: string, sourceId: string): void {
+ mkdirSync(join(repository, 'hooks'), { recursive: true });
+ const path = join(repository, 'hooks', 'pre-receive');
+ writeFileSync(path, hostedHookScript(sourceId), { mode: 0o755 });
+ chmodSync(path, 0o755);
+ git(repository, ['config', 'core.hooksPath', join(repository, 'hooks')]);
+}
+
+function refused(reason: string, message: string, suggestion: string) {
+ return opError('hosted_repo_refused', message, suggestion, { reason,
+ fix: readFix('Lists the registered sources with their paths, read-only.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });
+}
+
+function hasPassword(url: string): boolean {
+ try { return !!new URL(url).password; } catch { return false; }
+}
+
+function hostedConfig(config: Record<string, unknown>): { repository: string; worktree: string; branch: string } | null {
+ const hosted = config.hosted_repo as Record<string, unknown> | undefined;
+ return hosted && typeof hosted.repository === 'string' && typeof hosted.worktree === 'string' && typeof hosted.branch === 'string'
+ ? { repository: hosted.repository, worktree: hosted.worktree, branch: hosted.branch } : null;
+}
+
+/** The plan for `opts`, with every refusal a preview and an apply share. */
+export async function planHostRepo(engine: BrainEngine, opts: HostRepoOptions): Promise<{ plan: HostRepoPlan; incarnation: string | null }> {
+ if (!isValidSourceId(opts.sourceId)) throw opError('invalid_params', 'A valid source ID is required.',
+ 'Name the source by its ID: lowercase letters, digits and inner hyphens, at most 32 characters.');
+ if (!isAbsolute(opts.dir) || opts.dir.includes('\0')) throw opError('invalid_params', '--dir must be an absolute path on this host.',
+ 'Pass the directory that will hold the hosted repository as an absolute path; nothing was created.');
+ if (opts.pushRemote !== undefined && (!opts.pushRemote.trim() || hasPassword(opts.pushRemote))) throw opError('invalid_params',
+ '--push-remote must be a repository URL without a password.',
+ `Pass the URL alone, and after hosting wire a credential with gbrain sources writer git-durability ${opts.sourceId} --pat-file and a token file; nothing was created.`);
+ if (!await managedPersistenceEnabled(engine)) throw opError('strict_requires_managed',
+ `host-repo makes source ${opts.sourceId} git-canonical, which needs managed persistence on this brain; nothing was created.`,
+ 'Ask the user whether to turn on managed persistence for this brain (gbrain sources writer activate) before hosting a repository.');
+ const dir = resolve(opts.dir);
+ const [source] = await engine.executeRaw<SourceRow>('SELECT incarnation::text AS incarnation, archived, local_path, config FROM sources WHERE id=$1', [opts.sourceId]);
+ const config = source ? parseSourceConfig(source.config) : {};
+ const [binding] = await engine.executeRaw<{ worktree_id: string }>('SELECT worktree_id::text AS worktree_id FROM persistence_source_bindings WHERE source_id=$1', [opts.sourceId]);
+ const hosted = hostedConfig(config);
+ const before = typeof config.canonical === 'string' ? config.canonical : null;
+
+ if (source?.archived) throw refused('source_archived', `Source ${opts.sourceId} is archived.`,
+ `Restore it first (gbrain sources restore ${opts.sourceId}) or pick a new source ID; nothing was created.`);
+ if (hosted && binding) {
+ if (real(join(dir, 'repo.git')) !== real(hosted.repository)) throw refused('source_bound', `Source ${opts.sourceId} is already hosted at ${dirname(hosted.repository)}.`,
+ `Preview it at its own directory with gbrain sources host-repo ${opts.sourceId} --dir ${dirname(hosted.repository)} --dry-run; nothing was changed.`);
+ const state = hostedHookState(hosted.repository, opts.sourceId);
+ const link = !existsSync(hosted.worktree) ? 'absent' : linkedWorktreeProblem(hosted.worktree) ? 'broken' : 'ok';
+ const action = state === 'ok' ? 'none' : 'reinstall_hook';
+ const plan_hash = sha256(JSON.stringify({ v: 1, action, source_id: opts.sourceId, incarnation: source!.incarnation, repository: hosted.repository, state }));
+ return { incarnation: source!.incarnation, plan: {
+ source_id: opts.sourceId, dry_run: opts.dryRun, action, source: { registered: true, canonical: { before, after: 'git' } },
+ repository: hosted.repository, worktree: hosted.worktree, branch: hosted.branch, push_remote: null,
+ hook: { path: join(hosted.repository, 'hooks', 'pre-receive'), state }, worktree_link: link,
+ summary: [
+ `Source ${opts.sourceId} is hosted at ${hosted.repository} and is git-canonical (strict).`,
+ state === 'ok' ? 'The pre-receive hook that refuses every push is in place.'
+ : `The pre-receive hook that refuses every push is ${state}; the apply reinstalls it.`,
+ link === 'ok' ? 'The worktree gbrain commits through is linked to the repository.'
+ : `The worktree gbrain commits through is ${link === 'absent' ? 'missing' : 'no longer linked to the repository'}; writes to this source cannot commit until it is restored (git worktree repair, or git worktree add).`,
+ ], next: [], plan_hash } };
+ }
+ if (binding || hosted) throw refused('source_bound', `Source ${opts.sourceId} already has a canonical worktree.`,
+ 'host-repo starts a new hosted repository for an unbound source, and a bound source keeps its checkout; nothing was created.');
+ if (source?.local_path) throw refused('source_has_path', `Source ${opts.sourceId} already has a directory (${source.local_path}).`,
+ 'host-repo gives a source a new repository; pick a new source ID, or keep this source on its directory. Nothing was created.');
+ const [pages] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id=$1', [opts.sourceId]);
+ if (Number(pages?.n ?? 0) > 0) throw refused('source_has_pages', `Source ${opts.sourceId} already has ${pages!.n} page(s).`,
+ 'Moving existing pages into a hosted repository is conversion, which is not available yet (git-canonical wave G8); host a new, empty source instead. Nothing was created.');
+ let dirState: 'absent' | 'empty' = 'absent';
+ if (existsSync(dir)) {
+ if (!lstatSync(dir).isDirectory() || readdirSync(dir).length) throw refused('dir_not_empty', `${dir} exists and is not an empty directory.`,
+ 'Pass a directory that does not exist yet, or an empty one; nothing was created.');
+ dirState = 'empty';
+ }
+ let ancestor = dir; while (!existsSync(ancestor)) ancestor = dirname(ancestor);
+ let checkout: string | null = null;
+ try { checkout = git(ancestor, ['rev-parse', '--show-toplevel']) || null; } catch { checkout = null; }
+ if (checkout || linkedWorktreeProblem(ancestor)) throw opError('overlapping_path', `${dir} is inside the Git checkout ${checkout ?? ancestor}.`,
+ "A hosted repository needs a directory outside every checkout, the brain's own and other sources' worktrees included; nothing was created.");
+ const roots = await engine.executeRaw<{ id: string; path: string }>(
+ `SELECT id, local_path AS path FROM sources WHERE local_path IS NOT NULL UNION ALL SELECT b.source_id AS id, h.local_path AS path
+ FROM persistence_host_bindings h JOIN persistence_source_bindings b ON b.worktree_id=h.worktree_id WHERE h.local_path IS NOT NULL`);
+ const target = join(real(ancestor), dir.slice(ancestor.length));
+ const overlap = roots.find(row => containsPath(real(row.path), target) || containsPath(target, real(row.path)));
+ if (overlap) throw opError('overlapping_path', `${dir} overlaps the directory of source ${overlap.id} (${overlap.path}).`,
+ "Pick a directory outside every source's worktree; nothing was created.");
+
+ const repository = join(dir, 'repo.git'), worktree = join(dir, 'worktree');
+ const plan_hash = sha256(JSON.stringify({ v: 1, action: 'host', source_id: opts.sourceId, incarnation: source?.incarnation ?? null, canonical: before,
+ dir, dir_state: dirState, branch: HOSTED_BRANCH, push: opts.pushRemote ? sha256(opts.pushRemote) : null, hook: sha256(hostedHookScript(opts.sourceId)) }));
+ return { incarnation: source?.incarnation ?? null, plan: {
+ source_id: opts.sourceId, dry_run: opts.dryRun, action: 'host', source: { registered: !!source, canonical: { before, after: 'git' } },
+ repository, worktree, branch: HOSTED_BRANCH, push_remote: opts.pushRemote ?? null,
+ hook: { path: join(repository, 'hooks', 'pre-receive'), state: 'install' }, worktree_link: 'absent',
+ summary: [
+ `Source ${opts.sourceId} becomes git-canonical (strict, canonical: git${before ? `, was ${before}` : ''}): every page write commits to Git through the door before the database indexes it, and the database is derived from the commits.`,
+ `${source ? 'The source' : `A new source ${opts.sourceId}`} gets a bare repository at ${repository} on branch ${HOSTED_BRANCH} with one commit (an empty .gitignore); users clone it and fetch from it.`,
+ `gbrain checks it out at ${worktree} as a linked worktree and claims it as the source's canonical worktree on this host.`,
+ 'A pre-receive hook refuses every push into the repository, so only the door moves its branch.',
+ opts.pushRemote ? `Commits are pushed to ${opts.pushRemote} by the push effect once Git durability is enabled (the next step).` : 'No push remote: commits stay in the hosted repository.',
+ ], next: opts.pushRemote ? [['gbrain', 'sources', 'writer', 'git-durability', opts.sourceId, '--enable', '--dry-run']] : [], plan_hash } };
+}
+
+/** Preview or apply the plan; the apply needs the plan_hash its preview printed. */
+export async function hostRepo(engine: BrainEngine, opts: HostRepoOptions): Promise<HostRepoPlan> {
+ const { plan, incarnation } = await planHostRepo(engine, opts);
+ const preview = ['gbrain', 'sources', 'host-repo', opts.sourceId, '--dir', resolve(opts.dir), ...(opts.pushRemote ? ['--push-remote', opts.pushRemote] : [])];
+ if (opts.dryRun || opts.expect === undefined) return { ...plan, dry_run: true, ...(plan.action === 'none' ? {} : { apply: [...preview, '--expect', plan.plan_hash] }) };
+ if (opts.expect !== plan.plan_hash) throw opError('preview_changed', `The host-repo plan for source ${opts.sourceId} changed since its preview; nothing was changed.`,
+ 'Preview again and apply the plan_hash it prints.', { fix: readFix('Prints the current plan and its plan_hash; changes nothing.', { argv: [...preview, '--dry-run', '--json'] }) });
+ if (plan.action === 'none') return plan;
+ if (plan.action === 'reinstall_hook') { installHook(plan.repository, opts.sourceId); return { ...plan, hook: { ...plan.hook, state: 'ok' } }; }
+
+ const dir = resolve(opts.dir), created = !existsSync(dir);
+ mkdirSync(dir, { recursive: true });
+ try {
+ git(dir, ['init', '-q', '--bare', `--initial-branch=${plan.branch}`, plan.repository]);
+ for (const [key, value] of [['receive.denyCurrentBranch', 'refuse'], ['receive.denyDeletes', 'true'], ['receive.denyNonFastForwards', 'true'],
+ ['user.name', 'gbrain'], ['user.email', 'gbrain@localhost']] as const) git(plan.repository, ['config', key, value]);
+ installHook(plan.repository, opts.sourceId);
+ const blob = git(plan.repository, ['hash-object', '-w', '--stdin'], '');
+ const tree = git(plan.repository, ['mktree'], `100644 blob ${blob}\t.gitignore\n`);
+ const commit = git(plan.repository, ['commit-tree', tree, '-m', `gbrain: host source ${opts.sourceId}`]);
+ git(plan.repository, ['update-ref', `refs/heads/${plan.branch}`, commit, '']);
+ if (opts.pushRemote) {
+ git(plan.repository, ['remote', 'add', 'origin', opts.pushRemote]);
+ git(plan.repository, ['config', `branch.${plan.branch}.remote`, 'origin']);
+ git(plan.repository, ['config', `branch.${plan.branch}.merge`, `refs/heads/${plan.branch}`]);
+ }
+ git(plan.repository, ['worktree', 'add', '-q', plan.worktree, plan.branch]);
+ assertLinkedWorktreeIntact(plan.worktree);
+ const { runManagedSourceLifecycle } = await import('./source-lifecycle.ts');
+ const claim = await runManagedSourceLifecycle(engine, { operation: plan.source.registered ? 'claim' : 'add', sourceId: opts.sourceId, path: plan.worktree,
+ ...(incarnation ? { expectedIncarnation: incarnation } : {}),
+ config: { canonical: 'git', hosted_repo: { repository: plan.repository, worktree: plan.worktree, branch: plan.branch } } });
+ return { ...plan, dry_run: false, hook: { ...plan.hook, state: 'ok' }, worktree_link: 'ok', claim };
+ } catch (error) {
+ if (created) rmSync(dir, { recursive: true, force: true });
+ else for (const entry of readdirSync(dir)) rmSync(join(dir, entry), { recursive: true, force: true });
+ throw error;
+ }
+}
diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.ts
index 7ed5e926b6..4189db3106 100644
--- a/src/core/persistence/source-lifecycle.ts
+++ b/src/core/persistence/source-lifecycle.ts
@@ -29,6 +29,7 @@ import { inspectRelocatedPhysicalRoot, relocatePhysicalRoot } from './physical-r
import { assertWriterAdminState, WRITER_INSPECTION_HINT } from './admin-intent.ts';
import { assertWriterAdminUnlocked } from './admin-lock.ts';
import { rebindContentReceipts } from '../shared-skills/receipt-root.ts';
+import { assertLinkedWorktreeIntact } from './worktree-link.ts';
export interface SourceLifecycleInput {
operation:'add'|'claim'|'archive'|'restore'|'remove'|'purge'|'rebind'|'reclone';
@@ -59,6 +60,7 @@ function localRoot(path:string,create=false):{source:string;worktree:string}{
'The path names a file. Pass the directory that holds the source content, then rerun the command; nothing was changed.');
let worktree=source;
let ancestor=source;while(!existsSync(ancestor))ancestor=dirname(ancestor);
+ assertLinkedWorktreeIntact(ancestor);
try{worktree=realpathSync(discoverGitRoot(ancestor));}catch{/* directory source */}
return {source,worktree};
}
diff --git a/src/core/persistence/worktree-link.ts b/src/core/persistence/worktree-link.ts
new file mode 100644
index 0000000000..463881d9ed
--- /dev/null
+++ b/src/core/persistence/worktree-link.ts
@@ -0,0 +1,39 @@
+/**
+ * The link check for a linked Git worktree (G7b-2; GBRA-133's review of the hosted layout). A linked worktree reaches its
+ * repository through a `.git` file naming an entry under the repository's `worktrees/`, and that entry's `gitdir` file
+ * names the worktree back. `git worktree prune` deletes an entry whose worktree it cannot see, and a checkout moved to
+ * another path leaves the entry naming the old one, so the next prune deletes it. Either way a canonical worktree would
+ * commit through a link that is gone or about to go, so a claim refuses it with `git_worktree_link_broken`.
+ * A submodule's `.git` file names a module directory with no back link; only its existence is checked.
+ */
+import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { opError } from '../ops/contract.ts';
+
+const real = (path: string) => { try { return realpathSync(path); } catch { return resolve(path); } };
+
+/** Why the nearest `.git` at or above `root` is a broken worktree link, or null when it is intact or not a link. */
+export function linkedWorktreeProblem(root: string): string | null {
+ for (let dir = root; ; dir = dirname(dir)) {
+ const marker = join(dir, '.git');
+ let isFile: boolean;
+ try { isFile = lstatSync(marker).isFile(); } catch { if (dir === dirname(dir)) return null; continue; }
+ if (!isFile) return null;
+ const named = /^gitdir:\s*(.+)$/m.exec(readFileSync(marker, 'utf8'))?.[1]?.trim();
+ if (!named) return `${marker} names no repository entry`;
+ const entry = resolve(dir, named);
+ if (!existsSync(entry)) return `the repository entry ${entry} that ${marker} names is gone (git worktree prune removes the entry of a worktree it cannot see)`;
+ if (!existsSync(join(entry, 'commondir'))) return null;
+ let back: string;
+ try { back = readFileSync(join(entry, 'gitdir'), 'utf8').trim(); } catch { return `the repository entry ${entry} has no gitdir file naming its worktree`; }
+ if (real(resolve(entry, back)) !== real(marker)) return `the repository entry ${entry} names ${back}, not ${marker} (the checkout moved)`;
+ return null;
+ }
+}
+
+export function assertLinkedWorktreeIntact(root: string): void {
+ const problem = linkedWorktreeProblem(root);
+ if (!problem) return;
+ throw opError('git_worktree_link_broken', `${root} is a linked Git worktree whose link to its repository is broken: ${problem}.`,
+ `Nothing was claimed. From the repository, run git worktree repair ${root} when both still exist, or add the worktree again with git worktree add, then rerun.`);
+}
diff --git a/test/hosted-repo-g7b2.test.ts b/test/hosted-repo-g7b2.test.ts
new file mode 100644
index 0000000000..576c0e62b4
--- /dev/null
+++ b/test/hosted-repo-g7b2.test.ts
@@ -0,0 +1,257 @@
+/**
+ * G7b-2, hosted writes (docs/designs/GIT_CANONICAL_MEMORY.md "Remote and hosted writes"): `gbrain sources host-repo` gives an
+ * empty source a bare repository plus a gbrain-owned linked worktree, claimed through the ordinary claim, and makes the
+ * source git-canonical. Protects:
+ * - the preview says the source becomes strict and binds the apply: a stale plan_hash refuses `preview_changed` and
+ * creates nothing; the apply leaves the worktree claimed on the repository's branch, and a second preview has nothing to do;
+ * - every remote write (OAuth client and legacy token) lands as exactly one commit on the bare repository's branch, its
+ * receipt names that commit, and a G3 pass over the source afterwards changes no page;
+ * - a door commit that landed before its grant was revoked keeps the landed commit on the receipt in this layout too;
+ * - a push into the repository is refused with the worktree and, once the worktree is removed and pruned, by the
+ * pre-receive hook alone; the preview reports a missing or changed hook and the apply reinstalls it;
+ * - the push effect carries door commits to the user's remote;
+ * - the refusals: a bound source, a source with pages, a directory that is not empty or sits in a checkout or a
+ * source's directory, an unmanaged brain (with a remote extract_entities on a strict source refused the same way);
+ * - a claim refuses a linked worktree whose link is broken (the checkout moved, or its entry was pruned).
+ * PGLite here; with DATABASE_URL also Postgres (test/postgres-unit-arms.txt).
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { hostRepo, hostedHookScript, type HostRepoOptions } from '../src/core/persistence/hosted-repo.ts';
+import { runManagedSourceLifecycle } from '../src/core/persistence/source-lifecycle.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { durableGitRepo, git } from './helpers/git-publication.ts';
+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+
+const SOURCE = 'source-a';
+const page = (title: string, body: string) => `---\ntype: note\ntitle: ${title}\n---\n\n${body}\n`;
+const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };
+const hostedDir = (root: string) => join(dirname(root), 'hosted');
+const code = (promise: Promise<unknown>) => promise.then(() => null, (error: { code?: string; reason?: string }) => ({ code: error.code, reason: error.reason ?? null }));
+
+async function host(engine: BrainEngine, dir: string, extra: Partial<HostRepoOptions> = {}) {
+ const preview = await hostRepo(engine, { sourceId: SOURCE, dir, dryRun: true, ...extra });
+ return hostRepo(engine, { sourceId: SOURCE, dir, dryRun: false, expect: preview.plan_hash, ...extra });
+}
+
+/** A remote OAuth client and a remote legacy token, both granted read and write on the hosted source. */
+async function remoteCallers(engine: BrainEngine, ctx: OperationContext) {
+ const clientId = `client-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_secret_hash,client_name,scope,source_id) VALUES($1,'fixture-hash','example-client','read write',$2)`, [clientId, SOURCE]);
+ const minted = await mintLegacyToken(engine, { name: `token-${clientId}`, scopes: ['read', 'write'], sourceGrant: [SOURCE], takesHolders: ['world'] });
+ return {
+ tokenId: minted.id,
+ oauth: { ...ctx, sourceId: SOURCE, remote: true, transport: 'http', auth: { token: 'fixture', clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['read', 'write'], sourceId: SOURCE } } as OperationContext,
+ token: { ...ctx, sourceId: SOURCE, remote: true, transport: 'http', takesHoldersAllowList: ['world'],
+ auth: { token: '', clientId: minted.id, principal: { kind: 'legacy_token', id: minted.id }, sourceId: SOURCE, allowedSources: [SOURCE], scopes: ['read', 'write'] } } as OperationContext,
+ };
+}
+
+const call = (ctx: OperationContext, name: string, params: Record<string, unknown>) =>
+ (operationsByName[name]!.handler(ctx, { request_id: randomUUID(), wait_ms: 30_000, ...params }) as Promise<Record<string, any>>)
+ .catch((error: Error & { code?: string }) => { throw Object.assign(error, { message: `${name}: ${error.message}` }); });
+const revision = async (engine: BrainEngine, slug: string) => (await engine.readPageSnapshot(slug, { sourceId: SOURCE }))!.revision;
+const commitsTouching = (repository: string, rel: string) => git(repository, 'log', '--format=%H', 'main', '--', rel).split('\n').filter(Boolean);
+/** A push from a clone of the repository: its exit code and stderr. */
+function foreignPush(repository: string, clone: string): { exitCode: number | null; stderr: string } {
+ if (!existsSync(clone)) git(dirname(clone), 'clone', '-q', repository, clone);
+ writeFileSync(join(clone, 'foreign.md'), page('Foreign', `Pushed around the door at ${Date.now()}.`));
+ git(clone, 'add', 'foreign.md');
+ git(clone, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-q', '-m', 'foreign');
+ const result = Bun.spawnSync(['git', '-C', clone, 'push', 'origin', 'HEAD:main'], { env: process.env });
+ return { exitCode: result.exitCode, stderr: result.stderr.toString() };
+}
+
+for (const backend of testBackends()) describe(`[${backend}] G7b-2: a hosted source commits every write in its bare repository through the door`, () => {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ afterEach(() => installFaultHook(undefined));
+
+ test('the preview says the source becomes strict and binds the apply; a stale plan refuses and creates nothing; the apply claims the worktree', () => managedBrain(async ({ engine, root }) => {
+ const dir = hostedDir(root);
+ const preview = await hostRepo(engine, { sourceId: SOURCE, dir, dryRun: true });
+ expect(preview).toMatchObject({ action: 'host', dry_run: true, source: { registered: false, canonical: { before: null, after: 'git' } },
+ repository: join(dir, 'repo.git'), worktree: join(dir, 'worktree'), branch: 'main', hook: { state: 'install' } });
+ expect(preview.summary[0]).toContain(`Source ${SOURCE} becomes git-canonical (strict, canonical: git)`);
+ expect(preview.apply).toEqual(['gbrain', 'sources', 'host-repo', SOURCE, '--dir', dir, '--expect', preview.plan_hash]);
+ expect(existsSync(dir)).toBe(false);
+
+ await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: SOURCE });
+ expect(await code(hostRepo(engine, { sourceId: SOURCE, dir, dryRun: false, expect: preview.plan_hash }))).toEqual({ code: 'preview_changed', reason: null });
+ expect(existsSync(dir)).toBe(false);
+
+ const hosted = await host(engine, dir);
+ expect(hosted).toMatchObject({ action: 'host', dry_run: false, source: { registered: true }, hook: { state: 'ok' }, worktree_link: 'ok' });
+ const [row] = await engine.executeRaw<{ config: Record<string, any>; local_path: string }>('SELECT config, local_path FROM sources WHERE id=$1', [SOURCE]);
+ expect(row!.config).toMatchObject({ canonical: 'git', hosted_repo: { repository: hosted.repository, worktree: hosted.worktree, branch: 'main' } });
+ const [binding] = await engine.executeRaw<{ local_path: string }>(
+ 'SELECT h.local_path FROM persistence_source_bindings b JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id WHERE b.source_id=$1', [SOURCE]);
+ expect(binding!.local_path).toBe(hosted.worktree);
+ expect(git(hosted.worktree, 'rev-parse', 'HEAD').trim()).toBe(git(hosted.repository, 'rev-parse', 'main').trim());
+ expect(git(hosted.repository, 'ls-tree', '--name-only', 'main').trim()).toBe('.gitignore');
+ expect(readFileSync(hosted.hook.path, 'utf8')).toBe(hostedHookScript(SOURCE));
+ const again = await hostRepo(engine, { sourceId: SOURCE, dir, dryRun: true });
+ expect(again).toMatchObject({ action: 'none', hook: { state: 'ok' }, worktree_link: 'ok' });
+ expect(again.apply).toBeUndefined();
+ }, { databaseUrl, setup }), 120_000);
+
+ test('every remote write lands as exactly one commit on the bare branch, its receipt names it, and a G3 pass changes nothing', () => managedBrain(async ({ engine, ctx, root }) => {
+ const hosted = await host(engine, hostedDir(root));
+ const { oauth, token } = await remoteCallers(engine, ctx);
+ const start = Number((await engine.executeRaw<{ s: number }>('SELECT COALESCE(max(sequence),0) AS s FROM persistence_requests'))[0]!.s);
+ await call(oauth, 'put_page', { slug: 'notes/a', content: page('A', 'First body.') });
+ await call(token, 'put_page', { slug: 'notes/b', content: page('B', 'Bee.') });
+ await call(oauth, 'edit_page', { slug: 'notes/a', expected_revision: await revision(engine, 'notes/a'), edits: [{ old_text: 'First body.', new_text: 'Edited body.' }] });
+ expect(await call(token, 'put_pages', { pages: [{ slug: 'notes/c', content: page('C', 'Cee.') }, { slug: 'notes/d', content: page('D', 'Dee.') }] }))
+ .toMatchObject({ state: 'committed', counts: { committed: 2, failed: 0 } });
+ await call(oauth, 'delete_page', { slug: 'notes/b', expected_revision: await revision(engine, 'notes/b') });
+
+ const rows = await engine.executeRaw<{ slug: string; state: string; outcome: Record<string, any> | null }>(
+ 'SELECT slug, state, outcome FROM persistence_requests WHERE sequence > $1 AND source_id=$2 AND slug IS NOT NULL ORDER BY sequence', [start, SOURCE]);
+ expect(rows.map(r => ({ slug: r.slug, state: r.state, git_state: r.outcome?.persistence?.git_state })))
+ .toEqual(['notes/a', 'notes/b', 'notes/a', 'notes/c', 'notes/d', 'notes/b'].map(slug => ({ slug, state: 'committed', git_state: 'committed' })));
+ const byCommit = new Map<string, string[]>();
+ for (const r of rows) byCommit.set(r.outcome!.persistence.git_commit, [...(byCommit.get(r.outcome!.persistence.git_commit) ?? []), `${r.slug}.md`]);
+ const doorCommits = git(hosted.repository, 'rev-list', 'main').split('\n').filter(Boolean).slice(0, -1);
+ expect(new Set(doorCommits)).toEqual(new Set(byCommit.keys()));
+ for (const [commit, paths] of byCommit)
+ expect({ commit, touched: git(hosted.repository, 'diff-tree', '--no-commit-id', '--name-only', '-r', commit).split('\n').filter(Boolean).sort() })
+ .toEqual({ commit, touched: [...paths].sort() });
+ expect(git(hosted.worktree, 'status', '--porcelain')).toBe('');
+ expect(git(hosted.repository, 'show', 'main:notes/a.md')).toContain('Edited body.');
+
+ const pages = () => engine.executeRaw<{ slug: string; revision: string; deleted: boolean }>(
+ 'SELECT slug, knowledge_revision::text AS revision, deleted_at IS NOT NULL AS deleted FROM pages WHERE source_id=$1 ORDER BY slug', [SOURCE]);
+ const before = await pages();
+ expect(before.map(p => p.slug)).toEqual(['notes/a', 'notes/b', 'notes/c', 'notes/d']);
+ await performManagedSync(engine, { sourceId: SOURCE, noPull: true, noEmbed: true, noExtract: true });
+ expect(await pages()).toEqual(before);
+ expect((await performManagedSync(engine, { sourceId: SOURCE, noPull: true, noEmbed: true, noExtract: true })).status).toBe('up_to_date');
+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='sync-hold' AND completed_keys::text LIKE '%notes/%'")).toHaveLength(0);
+ }, { databaseUrl, setup }), 240_000);
+
+ test('a door commit that landed before its grant was revoked: the replay refuses, and its receipt names the landed commit in the bare repository', () => managedBrain(async ({ engine, ctx, root }) => {
+ const hosted = await host(engine, hostedDir(root));
+ const { token, tokenId } = await remoteCallers(engine, ctx);
+ const requestId = randomUUID();
+ let landed = '';
+ installFaultHook(async (point, detail) => {
+ if (detail.requestId !== requestId) return;
+ if (point === 'publication:before_commit' && !landed) { landed = git(hosted.repository, 'rev-parse', 'main').trim(); throw Object.assign(new Error('database interruption'), { code: 'CONNECTION_CLOSED' }); }
+ if (point === 'publication:prepared' && landed) await engine.executeRaw('UPDATE access_tokens SET revoked_at=now() WHERE id=$1 AND revoked_at IS NULL', [tokenId]);
+ });
+ await expect(call(token, 'put_page', { request_id: requestId, slug: 'notes/landed', content: page('Landed', 'Committed, then revoked.') }))
+ .rejects.toMatchObject({ code: 'permission_denied' });
+ const holder = commitsTouching(hosted.repository, 'notes/landed.md');
+ expect(holder).toEqual([landed]);
+ const [done] = await engine.executeRaw<{ state: string; error_code: string; outcome: Record<string, any> }>('SELECT state, error_code, outcome FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);
+ expect(done).toEqual({ state: 'failed', error_code: 'permission_denied', outcome: { persistence: { git_state: 'committed', git_commit: landed, landed_before_row: true } } });
+ expect(await engine.executeRaw('SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2', [SOURCE, 'notes/landed'])).toHaveLength(0);
+ }, { databaseUrl, setup }), 120_000);
+
+ test('a push into the repository is refused with the worktree and by the hook alone once it is pruned; the preview reports the hook and the apply reinstalls it', () => managedBrain(async ({ engine, root }) => {
+ const dir = hostedDir(root);
+ const hosted = await host(engine, dir);
+ const head = git(hosted.repository, 'rev-parse', 'main').trim();
+ const clone = join(dirname(root), 'clone');
+ const first = foreignPush(hosted.repository, clone);
+ expect({ exitCode: first.exitCode, named: first.stderr.includes(`gbrain put --source ${SOURCE}`) }).toEqual({ exitCode: 1, named: true });
+ expect(git(hosted.repository, 'rev-parse', 'main').trim()).toBe(head);
+
+ rmSync(hosted.worktree, { recursive: true, force: true });
+ git(hosted.repository, 'worktree', 'prune');
+ expect(git(hosted.repository, 'worktree', 'list', '--porcelain')).not.toContain(hosted.worktree);
+ const second = foreignPush(hosted.repository, clone);
+ expect({ exitCode: second.exitCode, named: second.stderr.includes(`gbrain put --source ${SOURCE}`) }).toEqual({ exitCode: 1, named: true });
+ expect(git(hosted.repository, 'rev-parse', 'main').trim()).toBe(head);
+ expect(await hostRepo(engine, { sourceId: SOURCE, dir, dryRun: true })).toMatchObject({ action: 'none', hook: { state: 'ok' }, worktree_link: 'absent' });
+
+ writeFileSync(hosted.hook.path, '#!/bin/sh\nexit 0\n');
+ const changed = await hostRepo(engine, { sourceId: SOURCE, dir, dryRun: true });
+ expect(changed).toMatchObject({ action: 'reinstall_hook', hook: { state: 'changed' } });
+ rmSync(hosted.hook.path);
+ const missing = await hostRepo(engine, { sourceId: SOURCE, dir, dryRun: true });
+ expect(missing).toMatchObject({ action: 'reinstall_hook', hook: { state: 'missing' } });
+ expect(await code(hostRepo(engine, { sourceId: SOURCE, dir, dryRun: false, expect: changed.plan_hash }))).toEqual({ code: 'preview_changed', reason: null });
+ expect(await hostRepo(engine, { sourceId: SOURCE, dir, dryRun: false, expect: missing.plan_hash })).toMatchObject({ action: 'reinstall_hook', hook: { state: 'ok' } });
+ expect(foreignPush(hosted.repository, clone).exitCode).toBe(1);
+ expect(git(hosted.repository, 'rev-parse', 'main').trim()).toBe(head);
+ }, { databaseUrl, setup }), 120_000);
+
+ test('the push effect carries door commits to the user remote', () => managedBrain(async ({ engine, ctx, root }) => {
+ const remote = join(dirname(root), 'user-remote.git');
+ git(dirname(root), 'init', '-q', '--bare', '--initial-branch=main', remote);
+ const preview = await hostRepo(engine, { sourceId: SOURCE, dir: hostedDir(root), dryRun: true, pushRemote: remote });
+ expect(preview.next).toEqual([['gbrain', 'sources', 'writer', 'git-durability', SOURCE, '--enable', '--dry-run']]);
+ const hosted = await host(engine, hostedDir(root), { pushRemote: remote });
+ await engine.executeRaw(`UPDATE persistence_host_bindings SET git_durability='enabled' WHERE worktree_id=(SELECT worktree_id FROM persistence_source_bindings WHERE source_id=$1)`, [SOURCE]);
+ const { oauth } = await remoteCallers(engine, ctx);
+ await call(oauth, 'put_page', { slug: 'notes/pushed', content: page('Pushed', 'Reaches the user remote.') });
+ await settleManagedGitEffects(engine, SOURCE);
+ expect(git(remote, 'rev-parse', 'main').trim()).toBe(git(hosted.repository, 'rev-parse', 'main').trim());
+ expect(git(remote, 'show', 'main:notes/pushed.md')).toContain('Reaches the user remote.');
+ }, { databaseUrl, setup }), 120_000);
+
+ test('refuses a bound source, a source with pages, and a directory that is not empty or sits in a checkout or a source directory, and creates nothing', () => managedBrain(async ({ engine, root }) => {
+ const dir = join(dirname(root), 'elsewhere');
+ expect(await code(hostRepo(engine, { sourceId: 'default', dir, dryRun: true }))).toEqual({ code: 'hosted_repo_refused', reason: 'source_bound' });
+ await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: 'source-p' });
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['source-p'], () => tx.executeRaw(
+ `INSERT INTO pages(source_id, slug, type, title, compiled_truth) VALUES('source-p','notes/existing','note','Existing','Existing body.')`), TEST_WRITE_ATTRIBUTION));
+ expect(await code(hostRepo(engine, { sourceId: 'source-p', dir, dryRun: true }))).toEqual({ code: 'hosted_repo_refused', reason: 'source_has_pages' });
+ const plain = join(dirname(root), 'plain'); mkdirSync(plain);
+ await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: 'source-d', path: plain });
+ expect(await code(hostRepo(engine, { sourceId: 'source-d', dir, dryRun: true }))).toEqual({ code: 'hosted_repo_refused', reason: 'source_bound' });
+ mkdirSync(dir); writeFileSync(join(dir, 'stray.txt'), 'x');
+ expect(await code(hostRepo(engine, { sourceId: SOURCE, dir, dryRun: true }))).toEqual({ code: 'hosted_repo_refused', reason: 'dir_not_empty' });
+ expect(await code(hostRepo(engine, { sourceId: SOURCE, dir: join(root, 'hosted'), dryRun: true }))).toEqual({ code: 'overlapping_path', reason: null });
+ expect(await code(hostRepo(engine, { sourceId: SOURCE, dir: join(plain, 'hosted'), dryRun: true }))).toEqual({ code: 'overlapping_path', reason: null });
+ expect(existsSync(join(root, 'hosted')) || existsSync(join(plain, 'hosted'))).toBe(false);
+ expect(await engine.executeRaw('SELECT 1 FROM sources WHERE id=$1', [SOURCE])).toHaveLength(0);
+ expect(Object.keys(operationsByName).filter(name => name.includes('host'))).toEqual([]);
+ }, { databaseUrl, setup }), 120_000);
+
+ test('a claim refuses a linked worktree whose checkout moved or whose entry was pruned', () => managedBrain(async ({ engine, root }) => {
+ const home = dirname(root), repository = join(home, 'linked.git'), worktree = join(home, 'linked-worktree'), moved = join(home, 'moved-worktree');
+ git(home, 'init', '-q', '--bare', '--initial-branch=main', repository);
+ git(repository, 'worktree', 'add', '-q', '--orphan', '-b', 'main', worktree);
+ git(worktree, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-q', '--allow-empty', '-m', 'Initial');
+ renameSync(worktree, moved);
+ expect(await code(runManagedSourceLifecycle(engine, { operation: 'add', sourceId: 'source-l', path: moved }))).toEqual({ code: 'git_worktree_link_broken', reason: null });
+ git(repository, 'worktree', 'prune');
+ expect(await code(runManagedSourceLifecycle(engine, { operation: 'add', sourceId: 'source-l', path: moved }))).toEqual({ code: 'git_worktree_link_broken', reason: null });
+ expect(await engine.executeRaw("SELECT 1 FROM sources WHERE id='source-l'")).toHaveLength(0);
+ }, { databaseUrl, setup }), 120_000);
+});
+
+const unmanaged: { backend: string; engine: BrainEngine; close: () => Promise<void> }[] = [];
+beforeAll(async () => {
+ for (const backend of testBackends()) {
+ if (backend === 'postgres') { const pg = await isolatedPersistencePostgres(requirePostgresTestDatabase()); unmanaged.push({ backend, engine: pg.engine, close: pg.close }); continue; }
+ const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ unmanaged.push({ backend, engine, close: () => engine.disconnect() });
+ }
+}, 120_000);
+afterAll(async () => { for (const { close } of unmanaged) await close(); });
+
+for (const backend of testBackends()) test(`[${backend}] G7b-2: an unmanaged brain refuses host-repo and a remote extract_entities on a strict source with strict_requires_managed`, async () => {
+ const { engine } = unmanaged.find(entry => entry.backend === backend)!;
+ expect(await code(hostRepo(engine, { sourceId: SOURCE, dir: '/nonexistent/hosted', dryRun: true }))).toEqual({ code: 'strict_requires_managed', reason: null });
+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ($1, $1, '{"canonical":"git"}'::jsonb) ON CONFLICT (id) DO UPDATE SET config = EXCLUDED.config`, [SOURCE]);
+ const ctx = { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId: SOURCE, remote: true, transport: 'http', dryRun: false,
+ logger: { info() {}, warn() {}, error() {} }, auth: { token: 'fixture', clientId: 'client-x', principal: { kind: 'oauth_client', id: 'client-x' }, scopes: ['read', 'write'], sourceId: SOURCE } } as unknown as OperationContext;
+ expect(await code(operationsByName.extract_entities!.handler(ctx, { text: 'Met Alice Example at the offsite.', source_slug: 'notes/offsite' })))
+ .toEqual({ code: 'strict_requires_managed', reason: null });
+ expect(await engine.executeRaw('SELECT 1 FROM pages WHERE source_id=$1', [SOURCE])).toHaveLength(0);
+}, 60_000);
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 9725d71ca3..5fd04dd42b 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -99,6 +99,7 @@ test/harness-skills-epoch.test.ts
test/held-read-signals.test.ts
test/hermes-clarify-transcripts-7396.test.ts
test/hold-action-chain-6712.test.ts
+test/hosted-repo-g7b2.test.ts
test/import-file-result-callback-gbra130.test.ts
test/import-frontmatter-key-order-5158.test.ts
test/import-inline-chunk-keep.test.ts