Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Wave B follow-ups F3: remote append_page mention links (#7122), append_page stays out of OWNER_EDIT_OPERATIONS (#7123)

garrytan226c7acdcc7e
diff --git a/docs/architecture/key-files/belief-ledger.md b/docs/architecture/key-files/belief-ledger.md
index d9c0dd3d9b..0d5da3b5b2 100644
--- a/docs/architecture/key-files/belief-ledger.md
+++ b/docs/architecture/key-files/belief-ledger.md
@@ -8,7 +8,7 @@ Design: [BELIEF_LEDGER.md](../../designs/BELIEF_LEDGER.md). Operator surface: `g
- `src/core/belief/keys.ts` — subject keys and hashes. A key never holds a row id: page slugs serialize as the lifetime (`L:<uuid>`), a slug with no page as `S:<incarnation>:<slug>`. Append, replay, lookup and `state_hash` share this one serialization.
- `src/core/belief/lifetimes.ts` — page lifetimes, the ledger's page identity: minted at first need, kept across a rename, ended by a hard delete or a recreate; `page_id` is a hint only.
- `src/core/belief/state.ts` / `subjects.ts` — raw stream state (a page, its fence and DB-only facts, takes, and links whose origin, else from, page it is) and its keyed subjects; row ids are payload, never keys. The post read reuses the pre read's rows for tables the transaction did not write (`pg_stat_xact` counters; a full read with `track_counts` off). The process-local fingerprint cache maps claim-text SHA-256 to `gbrain_fact_fingerprint` only (no text, bounded); `__fingerprintCacheForTests` and `__suppressBeliefTouchedSignalForTests` are the test seams.
-- `src/core/belief/ledger.ts` — the finalization contract. `withBeliefBatch` reads the state of the held page keys before and after the transaction's projections and appends the canonical diff (origin `live` on a managed brain, `unmanaged` otherwise, or the caller's override). `beliefBatchCovers` and `insideBeliefBatch` let a nested writer skip its own batch. Managed mode comes from `readManagedMode`, never a direct `persistence_brain` read.
+- `src/core/belief/ledger.ts` — the finalization contract. `withBeliefBatch` reads the state of the held page keys before and after the transaction's projections and appends the canonical diff (origin `live` on a managed brain, `unmanaged` otherwise, or the caller's override). `beliefBatchCovers` and `insideBeliefBatch` let a nested writer skip its own batch. Managed mode comes from `readManagedMode`, never a direct `persistence_brain` read. `publicationBeliefOptions` sets `ownerEdit` (the only input to the redaction release) for a local `OWNER_EDIT_OPERATIONS` publication with no intent `kind`; `append_page` is deliberately not in the list (#7123): an append cannot set a fact or take field, so as an owner edit it could only release a redaction on a field its publication re-derives, and its events are attributed `cause.op: 'append_page'` regardless (`test/belief-ledger-append-owner.test.ts`).
- `src/core/belief/append.ts` — the one insert (`appendBeliefEvents`): tombstones and the redaction register first, then deterministic `event_key`s. `markBeliefCommits` writes the post-commit observation (`observed_at >= recorded_at`); `__setBeliefEmitterFaultForTests` is the forced-probe seam.
- `src/core/belief/coverage.ts` — `enableBeliefLedger` (`coverage.started`, a resumable per-page baseline, `coverage.complete` whose recorded_at is the watermark; certified only on a managed brain) and `disableBeliefLedger` (`coverage.stopped`). Start, complete and stop are decided under the source row FOR UPDATE: a second enable resumes the open run, a disable mid-walk ends it with no `complete`, and the completion re-checks the pending set (a page renamed behind the cursor). A slug no page key can name is skipped and listed (`unkeyable_slugs`). The coverage state is the newest event other than `coverage.restored`, so a restore never restarts a stopped ledger.
- `src/core/belief/coverage-report.ts` — readers: `coverageIntervals` (restore marks carry purge-mirror's `archived_at`, `purge_replay`, `replays`), `coverageAt` (refuses `coverage_from` before the slug's cut, found under the slug or its page lifetime, and `coverage_gap` in a stopped span or a restore gap; an interval holding a purge whose derivation walk was truncated is not certified, `uncertified_reason: 'truncated_walk'`, its requests in `truncated_walks`), `beliefEventVisibility` (an unmarked publication is `unproven` until a commit mark or a later event of the page proves it). Drift: `scanBeliefDrift` (sampled, or deep; read-only, it mints no lifetime) compares each slug's current `state_hash` with its newest non-backfill event; `reconcileBeliefDrift` appends `reconcile` events (the slug interval stays uncertified). `orphanLifetimes` and `unmarkedPublications`/`fillCommitMarks` read a recent window unless `deep`; `cycleBeliefReconcile` for the extract phase.
diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.md
index 1584deb5b1..6b8026b10f 100644
--- a/docs/architecture/key-files/core-persistence-request-indexes.md
+++ b/docs/architecture/key-files/core-persistence-request-indexes.md
@@ -12,3 +12,4 @@ The online-built request-table indexes (the managed sync checkpoint pair, the pa
- `src/core/persistence/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. `decideUnboundWrite` is the one rule page writers and fact writers (`remember`, loop-fact retirement and relink through `fact-write-target.ts`, #6608) apply to a rooted source with no binding: connector → `connector_database`; PGLite not activation-listed database-only (#6449) → automatic claim; otherwise a page with a recorded canonical file, or the key unset, refuses and the rest is database-only. `remember` keeps its frozen `unavailable` code and carries the refusal's detail, docs and fix (`verb-errors.ts`). On a classic brain (managed persistence not activated) the hint leads with the classic write path: write `<checkout>/<slug>.md`, commit it, `gbrain sync --source <id>` (a remote caller is told to ask the user to). The refusal is `retryable: false` with a `fix` of `next: ask_user` and a `user_message` (classic or managed wording), because every way out is the user's choice (`test/unbound-source-hint.test.ts`). Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`. See [persistence stalls](persistence-stalls.md).
- Segmented withdrawal mirror (`src/core/persistence/{effects,effect-recovery,effect-model,staging}.ts`, flip lane A) — a withdrawal's mirror and Git scans treat a page stored in segments as an inline page (older binaries skipped it with `page_body_segmented`). `mirrorPage` renders its file from the segments (`page-prepare.ts` `unreadPageFile`, a `StreamedFileContent`) and reserves a version 2 `EffectRecovery` (`after: null`; `staging.publication` names the streamed file by path and SHA-256; the reservation counts the file once). `recoverEffectPublication` writes that stage before its transaction (`stageStreamedMirror`: from the measured file, or after a crash from the segments at the recorded revision, first discarding a stream a crash cut short under its in-progress name; seams `effect_recovery:before_stage` / `effect_recovery:staged`), then renames the verified stage (`staging.ts` `publishStreamedStage`). A segmented page's withdrawal is not materialized again: its rows were struck in its segments when the withdrawal committed. v0.60.290.0 reads a version 2 record as version 1 (`Buffer.from(null)`, untyped `effect_unavailable` on every attempt, never parks) but never deletes it or its stage, so `mirrorPage` writes none while that binary could claim it (next entry). Test: `test/large-pages/segmented-withdrawal-mirror.test.ts` (purge and forget twins, Git commits, two interruption seams, both engines).
- `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; a revision that moves between its read and its transaction retries as `revision_conflict`. Tests: `test/persistence-links-effect.test.ts`, `test/large-pages/append-mention-links.test.ts` (both engines; readSegmentTexts spy).
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index 0cbd6801a1..7efcf2ffa3 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -42,7 +42,7 @@ The page-state concurrency foundation under `src/core/page-state/` and the share
Writes that change part of a page in time proportional to the change (Wave B spec 6.1, 6.3): `append_page`, segmented `edit_page` and the splice engine both use. Tests: `test/large-pages/append-cost.test.ts`, `test/large-pages/append-concurrency.test.ts` and `test/large-pages/edit-segmented.test.ts`, PGLite and Postgres (helper `test/helpers/append-brain.ts`).
- `src/core/page-body/splice.ts` + `tail-digest.ts` — byte-range splices of a segmented body. `spliceSegmentedBody` replaces stored byte ranges of the live generation (`BodyReplacement`) and stages the next one from the touched segments only: segmentation resumes at the last clean entry point before the first replaced byte and stops at the first old boundary whose entry state the new run reproduces, so later segments keep their bytes, text and chunks and only move (new manifest rows under the same occurrence; content_hash midstate recomputed). An append is an insertion at its region's end: it re-segments the old tail plus the text and moves nothing; an insertion at the truth/timeline boundary belongs to truth (`replacementRegion`), so exactly one row owns it. New segments equal to a replaced one keep its occurrence; the rest are chunked with vectors reused by chunk text. A change that flips a region's fence trust restages the whole body (`rescanned`). `splicePage` reads the page row a splice needs (generation, region sizes, cr tier, corpus generation, kind); `spliceWork` counts segments segmented, bytes read and manifest rows (the cost tests' work counters). `tail-digest.ts` is the append precondition's digest for inline pages, sha256 of a region's last min(4096, region bytes) raw stored bytes (`inlineTailDigest`; segmented pages use `page-window/segmented.ts` `tailDigest`); a tail holding facts or takes text is withheld from a remote caller, since a hash of hidden text is a guessing oracle. The cost test pins that a 10 KB append to a 4 MB and a 16 MB page segments only the tail plus the text, and a forced full-rewrite probe (`appendProbe.fullRewrite`) fails the bound.
-- `src/core/persistence/page-append.ts` — `append_page`: text added to the end of a region (`region` auto/truth/timeline, `separator` auto/none), idempotent by `request_id`. `admitPageAppend` (also the upload lane's `commit_page_upload` append entry, with a staged `body_ref`) journals the text or the reference, never the body; text is capped at `APPEND_TEXT_MAX_BYTES` (4 MiB), a fence marker in it refuses `invalid_params`, and a missing or deleted page refuses `page_not_found`. `prepareAppendMutation` checks the optional preconditions on the locked snapshot (`expected_revision` gives `revision_changed`; `expected_tail_sha256` gives `tail_changed`, whose fix carries the current tail digest). A segmented page splices onto its region's tail through `prepareSegmentedSpliceMutation`, which segmented edit_page and append-mode upload commits share. It refuses a result over `pages.max_bytes` as a streamed import does (`file_too_large`, nothing written), and runs put_page's write gate over the new text only (title, frontmatter and the replacement bytes, O(text)): a flag verdict sets `content_flag` (`instruction_like`), records the page gate receipt and returns put_page's `gate` field; an allowed append never clears an existing flag, since the stored text was not re-read; it declines (null, whole-body path) for an always-loaded core page, an external_untrusted write the write gate scans whole, a change that creates or empties a region, or a file a withdrawal ledger rewrites. An inline page composes the new body on put_page's path, which promotes it past the segmented threshold. Chunks and embeddings of the appended text follow commit as for any segmented write; links, timeline rows and fence projections of appended text wait for PR 4's incremental derivation. A file-backed segmented page's canonical file gains the appended bytes, its frontmatter rendered in stored key order as inline edit_page and append write-through render it.
+- `src/core/persistence/page-append.ts` — `append_page`: text added to the end of a region (`region` auto/truth/timeline, `separator` auto/none), idempotent by `request_id`. `admitPageAppend` (also the upload lane's `commit_page_upload` append entry, with a staged `body_ref`) journals the text or the reference, never the body; text is capped at `APPEND_TEXT_MAX_BYTES` (4 MiB), a fence marker in it refuses `invalid_params`, and a missing or deleted page refuses `page_not_found`. `prepareAppendMutation` checks the optional preconditions on the locked snapshot (`expected_revision` gives `revision_changed`; `expected_tail_sha256` gives `tail_changed`, whose fix carries the current tail digest). A segmented page splices onto its region's tail through `prepareSegmentedSpliceMutation`, which segmented edit_page and append-mode upload commits share. It refuses a result over `pages.max_bytes` as a streamed import does (`file_too_large`, nothing written), and runs put_page's write gate over the new text only (title, frontmatter and the replacement bytes, O(text)): a flag verdict sets `content_flag` (`instruction_like`), records the page gate receipt and returns put_page's `gate` field; an allowed append never clears an existing flag, since the stored text was not re-read; it declines (null, whole-body path) for an always-loaded core page, an external_untrusted write the write gate scans whole, a change that creates or empties a region, or a file a withdrawal ledger rewrites. An inline page composes the new body on put_page's path, which promotes it past the segmented threshold. Chunks and embeddings of the appended text follow commit as for any segmented write. A remote append to the compiled truth records the bytes it added (`PreparedMutation.mentionRange`: stored truth offsets and their SHA-256, from the splice or, inline, from the parsed new truth) and queues a `links` effect carrying them (`data.range`, #7122; see `effect-links.ts`); timeline rows and fence projections of appended text wait for PR 4's incremental derivation. A file-backed segmented page's canonical file gains the appended bytes, its frontmatter rendered in stored key order as inline edit_page and append write-through render it.
- `src/core/ops/page-append.ts` — the `append_page` operation (write scope, client slug-fence allowlist, `outputRedaction: 'no_stored_text'`): params `{slug, source_id?, text, request_id, expected_revision?, expected_tail_sha256?, region?, separator?}`, returns `{slug, revision, body_bytes, appended_bytes, chunks_new, size_state, receipt}`. get_page's `body: 'none'` returns `tail_sha256` and `tail_region` for inline and segmented pages, and its window reads return `edit_target: {revision, byte_start, byte_end}` in stored coordinates (`ops/get-page-body.ts` `editTarget`), withheld from a remote caller when hidden text precedes the window end (`read-range.ts` `hiddenBefore`).
Segmented edit_page (`persistence/page-edit.ts`, entry in [Core Persistence](core-persistence.md)): optional `within: {byte_start, byte_end}` (stored coordinates, as `edit_target` returns them; `parseEditWithin`, `edit_invalid`) limits matching to one range, and a range the page no longer holds refuses `revision_conflict`. A remote caller's `within` refuses `edit_invalid` (one refusal for every range and edit, before any match or fence check) when hidden text starts before `byte_end`: on a segmented page the read projection's hidden units (`read-range.ts` `hiddenBefore`, the predicate `editTarget` withholds `edit_target` by), on an inline page a fence whose remote view differs from its stored text; such a range would measure the hidden text. A segmented page is never materialized: `prepareSegmentedEditMutation` (called first by `page-prepare.ts` `preparePageMutation`) finds each old_text by a streaming scan across segment boundaries (`locateSegmentedEdits`, with applyPageEdits' exactly-once, protected-span and remote-view rules; the scan keeps at most two matches per edit and refuses `edit_ambiguous_match` at the second, counted in `spliceWork.matches`) and splices the touched range; the receipt diff covers the touched range plus 2 KB of context, and only the first replacement past 256 KB (`diff_truncated`); its context never starts at or inside hidden facts or takes text, nor ends inside it, and its hunk lines count the caller's view (`viewNewlinesBefore`: row line counts plus, for a remote caller, each hidden run before the diff rendered as `sanitizeRemoteBody` renders it). With a withdrawal ledger that applies, the scan, the diff and those line counts read the page through its withdrawal overlay (`storedPieces` over `trustedSegments`, rows widened to whole fence blocks), on every path; a match into a block the overlay rewrote is never kept. A segmented page's remote edit view hides withdrawn rows as its remote windows do (`SEGMENTED_REMOTE_VIEW`, also on the whole-body path). A stored fence that does not compile refuses as applyPageEdits refuses it (typed `target_fence_malformed`, same location), at submission (`assertSegmentedEditFences`) and again at preparation: `scanCanonicalFences` runs over the stored fence text alone, each piece at its own line, so only segments holding fence text are read; with `within`, only the fences in the touched segments and those crossing into them. It declines to the whole-body path for an old_text naming the timeline sentinel or also found in the frontmatter head, or a miss without `within` on a page within the single-string ceiling.
diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.md
index a2c9feda4e..3e3be710db 100644
--- a/docs/guides/memory-boundaries.md
+++ b/docs/guides/memory-boundaries.md
@@ -56,7 +56,7 @@ prompt or response text).
|---|---|
| Trusted local `put_page` / capture | Extracts supported page references without an LLM when auto-linking is enabled. |
| MCP `put_page` / capture / `edit_page`, including stdio | Saves body references as text; no inline graph extraction. The receipt reports `auto_links.skipped: remote`. |
-| Post-commit `links` effect of an MCP page write | Adds untyped `mentions` edges (`link_source: mcp-remote-mention`) for the body's markdown links, `[[wikilinks]]` and page-path mentions whose target already exists in the same source, is not deleted, is visible to the writer and is inside its slug grant. No typed, frontmatter, timeline or cross-source edges and no new pages. The receipt reports `auto_links.mention_links: queued`; `get_write_request` lists the effect with `added`/`removed` counts, plus `invalid_targets` (reason `invalid_slug`) for any target that is not a valid slug (`[[../x]]`, a backslash, an encoded separator): those are skipped and the page's other edges still land (#7008). `gbrain config set mcp.remote_auto_links off` (or `auto_link off`) disables it. |
+| Post-commit `links` effect of an MCP page write | Adds untyped `mentions` edges (`link_source: mcp-remote-mention`) for the body's markdown links, `[[wikilinks]]` and page-path mentions whose target already exists in the same source, is not deleted, is visible to the writer and is inside its slug grant. No typed, frontmatter, timeline or cross-source edges and no new pages. The receipt reports `auto_links.mention_links: queued`; `get_write_request` lists the effect with `added`/`removed` counts, plus `invalid_targets` (reason `invalid_slug`) for any target that is not a valid slug (`[[../x]]`, a backslash, an encoded separator): those are skipped and the page's other edges still land (#7008). A remote `append_page` to the page body queues the same effect over the appended text only: it adds edges for what that text mentions and never removes one (#7122). `gbrain config set mcp.remote_auto_links off` (or `auto_link off`) disables it. |
| Stdio `gbrain serve` | Has bounded, best-effort startup and idle maintenance sweeps, unless disabled. This is eventual maintenance, not a guarantee that a remote write immediately has edges. |
| `gbrain serve --http` | Does not self-sweep. The host must run maintenance explicitly. |
diff --git a/docs/guides/remote-mcp.md b/docs/guides/remote-mcp.md
index dcca4b7071..e20ceae449 100644
--- a/docs/guides/remote-mcp.md
+++ b/docs/guides/remote-mcp.md
@@ -409,6 +409,8 @@ put_pages with one request_id per batch and wait_ms 25000."*
- **Links.** For remote writes, `[[wikilinks]]` in a page body that point at
pages already in the same source become plain `mentions` links after the
commit, and a batch links pages to each other once its last page commits.
+ `append_page` links what the appended text mentions the same way, without
+ re-reading the rest of the page.
The batch receipt's `links` field shows when they have landed; agents do
not add them by hand. Typed links still need `add_link`. Turn this off with
`gbrain config set mcp.remote_auto_links false`.
diff --git a/llms-full.txt b/llms-full.txt
index 8844e977f3..2f6829f378 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -422,6 +422,8 @@ put_pages with one request_id per batch and wait_ms 25000."*
- **Links.** For remote writes, `[[wikilinks]]` in a page body that point at
pages already in the same source become plain `mentions` links after the
commit, and a batch links pages to each other once its last page commits.
+ `append_page` links what the appended text mentions the same way, without
+ re-reading the rest of the page.
The batch receipt's `links` field shows when they have landed; agents do
not add them by hand. Typed links still need `add_link`. Turn this off with
`gbrain config set mcp.remote_auto_links false`.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 0e71e7f8e2..660f4f11f3 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1016,6 +1016,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.324.0', text: 'New `append_page` adds text to the end of a page in time proportional to the text added, idempotent by `request_id`; use it for conversation logs instead of re-putting the page. `expected_tail_sha256` (the `tail_sha256` that `get_page` with `body: \'none\'` returns) refuses `tail_changed` when another writer appended first. `gbrain append <slug> [--file f | stdin]` calls it.' },
{ since: '0.60.324.0', text: 'New upload sessions (`begin_page_upload`, `upload_page_part`, `get_page_upload`, `commit_page_upload`, `abort_page_upload`) let remote and thin clients write pages larger than one request, up to the page ceiling; `gbrain put --file` and `gbrain capture --file` use them on remote brains. A session is bound to the principal, source and page that began it (any other caller gets `upload_not_found`), staged bytes count against `persistence.limits` upload quotas (`write_quota_exhausted`), and an idle session expires after an hour. Locally, `gbrain put --file` and `gbrain capture --file` stream a file over 24 MiB straight in.' },
{ since: '0.60.324.0', text: '`edit_page` accepts `within` to restrict a match to a range returned by a window read (`edit_target`), and edits a page stored in segments by rewriting only the segments the match touches instead of reading the whole page back.' },
+ // Wave B follow-ups lane F3 (#7122 remote append_page mention links). `since` is stamped at the merge slot.
+ { since: 'TBD', text: 'A remote `append_page` to the body of a page now adds plain `mentions` links (link source `mcp-remote-mention`) for the `[[wikilinks]]`, markdown links and page paths in the appended text, to existing pages the writer can see inside its grant, as a remote `put_page` does. The post-commit pass reads only the appended text, never the rest of a large page, and never removes a link. `gbrain config set mcp.remote_auto_links off` turns it off.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/belief/ledger.ts b/src/core/belief/ledger.ts
index 6942ccf144..0c48d0f9c5 100644
--- a/src/core/belief/ledger.ts
+++ b/src/core/belief/ledger.ts
@@ -518,6 +518,12 @@ export { stateHashOf };
* redaction; sync (`submit_job`), gate release, held accept, backfill, revert, restore and retention never do.
* append.ts still requires the writer tier at or above OWNER_TIER_FLOOR, and the trust channel records these verbs
* as agent_written even from the local CLI, so today `trust confirm` is the release that reaches it.
+ *
+ * append_page stays out (#7123). The redaction release is this list's only consumer (`ownerEdit` reaches nothing else;
+ * the ledger attributes every publication by its `op`, so an append's events say `append_page` either way). An append
+ * cannot set a fact or take field (its text refuses fence markers), so as an owner edit it could only release a
+ * redaction on a field its publication re-derives from text the owner did not edit. Its intent's `kind` keeps it out
+ * a second time. Pinned by test/belief-ledger-append-owner.test.ts.
*/
const OWNER_EDIT_OPERATIONS: ReadonlySet<string> = new Set(['put_page', 'edit_page', 'takes_update', 'takes_resolve']);
let allowlistDropped = false;
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 8322ef91a2..d6895b4a71 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -30,7 +30,7 @@ import { mayReprepare } from './semantic.ts';
import { tryAcquirePublicationCapacity } from './pool-capacity.ts';
import { queuePublicationEffects } from './effect-journal.ts';
import { timePublicationStep } from './publication-timing.ts';
-import type { GitCommitNote } from './effect-model.ts';
+import type { AppendedRange, GitCommitNote } from './effect-model.ts';
import { authorizePageVisibility } from './page-visibility.ts';
import { withNoRepoWriteThroughWarning } from '../write-through.ts';
import { assertUnboundPublication, classifyUnboundPage, unboundWriteWarning } from './unbound-source.ts';
@@ -92,6 +92,8 @@ interface PreparedMutationBase {
* deferred projection and segment GC). Best effort: the projection queue and GC converge after a failure.
*/
afterCommit?(engine: BrainEngine): Promise<void>;
+ /** #7122: the truth bytes an append_page added; a remote append's `links` effect reads only these. Absent for every other write. */
+ mentionRange?: AppendedRange;
}
/**
* A page file target; `publishMode` (Google pages) is the exact mode it publishes with, and its created directories get 0700.
diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.ts
index f52b7576be..fcd955bd74 100644
--- a/src/core/persistence/effect-journal.ts
+++ b/src/core/persistence/effect-journal.ts
@@ -20,8 +20,8 @@ import { EFFECT_FAULT_POINTS, faultPoint } from './fault-points.ts';
/**
* `snapshot` is the publication's final read of the page, including deleted rows, in this transaction.
- * A remote put_page/capture/edit_page also queues a `links` effect, in one statement that inserts
- * nothing while `auto_link` or `mcp.remote_auto_links` is off (unset is on).
+ * A remote put_page/capture/edit_page also queues a `links` effect (an append_page to the compiled truth, one scoped
+ * to its appended bytes), in one statement that inserts nothing while `auto_link` or `mcp.remote_auto_links` is off (unset is on).
*/
export async function queuePublicationEffects(tx: BrainEngine, row: EffectRequest & Partial<Pick<WriteRequest, 'operation' | 'intent' | 'authority' | 'principal_kind' | 'principal_id'>>, snapshot: PageSnapshot | null,
outcome: Record<string, unknown>, prepared?: PreparedMutation,
@@ -54,7 +54,7 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques
else queue('facts-backstop', { visibility: await resolveDefaultVisibility(tx) });
}
// The links effect is inserted with the others, gated in SQL on auto_link and mcp.remote_auto_links.
- if (queuesMentionLinks(row)) queued.push({ kind: 'links', data: { ...data }, gated: true });
+ if (queuesMentionLinks(row, prepared)) queued.push({ kind: 'links', data: { ...data, ...(prepared?.mentionRange ? { range: prepared.mentionRange } : {}) }, gated: true });
// #5876: the Life Chronicle decision is a ledger row, not an effect; the `chronicle` cycle phase executes it.
await recordChronicleDecision(tx, row, snapshot, outcome);
}
@@ -70,10 +70,13 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques
}
}
-/** Whether a publication of this request queues a mention `links` effect: a remote page write without trusted auto-linking. */
-export function queuesMentionLinks(row: Partial<Pick<WriteRequest, 'operation' | 'authority'>>): boolean {
- return !!row.authority && !!row.operation && REMOTE_MENTION_OPERATIONS.includes(row.operation)
- && !(row.authority.autoLinkTrusted ?? !row.authority.remote);
+/**
+ * Whether a publication of this request queues a mention `links` effect: a remote page write without trusted
+ * auto-linking. #7122: an append_page queues one only when it appended to the compiled truth (`mentionRange`).
+ */
+export function queuesMentionLinks(row: Partial<Pick<WriteRequest, 'operation' | 'authority'>>, prepared?: Pick<PreparedMutation, 'mentionRange'>): boolean {
+ if (!row.authority || !row.operation || (row.authority.autoLinkTrusted ?? !row.authority.remote)) return false;
+ return REMOTE_MENTION_OPERATIONS.includes(row.operation) || (row.operation === 'append_page' && !!prepared?.mentionRange);
}
/**
diff --git a/src/core/persistence/effect-links.ts b/src/core/persistence/effect-links.ts
index ab0baf199a..cf5f0b1e2f 100644
--- a/src/core/persistence/effect-links.ts
+++ b/src/core/persistence/effect-links.ts
@@ -1,18 +1,23 @@
+import { createHash } from 'node:crypto';
import type { BrainEngine, LinkBatchInput } from '../engine.ts';
import { unmanagedBeliefPoint } from '../belief/projection-point.ts';
import type { PageSnapshot } from '../page-state/types.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
import { matchesSlugAllowList, slugUnderBoundPrefixes } from '../ops/context.ts';
-import { extractPageLinks, isAutoLinkEnabled, isGlobalBasenameEnabled, makeResolver } from '../link-extraction.ts';
+import { extractPageLinks, isAutoLinkEnabled, isGlobalBasenameEnabled, makeResolver, type PageLinksResult } from '../link-extraction.ts';
+import { protectedRegions } from '../fence-scan.ts';
+import { PROTECTED_PAIRS, sanitizeRemoteBody } from '../remote-body.ts';
+import { confirmBodyPin, openSegmentedBody, readBodyRange, type BodyAudience } from '../page-body/read-range.ts';
import { privatePagesFilterFragment } from '../search/private-visibility.ts';
import { authorizeStoredRequest } from './authority.ts';
import { completeEffect } from './effect-journal.ts';
-import { REMOTE_AUTO_LINKS_KEY, REMOTE_MENTION_LINK_SOURCE, type PersistenceEffect } from './effect-model.ts';
+import { REMOTE_AUTO_LINKS_KEY, REMOTE_MENTION_LINK_SOURCE, type AppendedRange, type PersistenceEffect } from './effect-model.ts';
import { guardEffectSource } from './effect-recovery.ts';
import type { SqlEngine, WriteAuthority, WriteRequest } from './model.ts';
import { excludesPrivateWrites } from './page-visibility.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
import { extractSegmentedPageLinks } from '../page-body/segment-links.ts';
+import { inlineRegions } from '../page-body/tail-digest.ts';
import { validateSlug } from '../utils.ts';
import { isRemoteWantedPagesEnabled, replaceWantedLinks } from '../wanted-links.ts';
@@ -39,15 +44,22 @@ const SKIPPED_TARGET_LIMIT = 50;
async function mentionTargets(engine: BrainEngine, snapshot: PageSnapshot, sourceId: string) {
const { page } = snapshot;
const resolver = makeResolver(engine, { mode: 'live', sourceId });
- const opts = { skipFrontmatter: true, pack: null, globalBasename: await isGlobalBasenameEnabled(engine) };
+ const opts = await mentionOptions(engine);
const { candidates } = isSegmentedPage(page)
? await extractSegmentedPageLinks(engine, { id: Number(page.id), slug: page.slug, source_id: sourceId, type: page.type, frontmatter: {} }, resolver,
{ ...opts, regions: ['truth'] })
: await extractPageLinks(page.slug, page.compiled_truth, {}, page.type, resolver, opts);
+ return mentionCandidates(candidates, page.slug, sourceId);
+}
+
+const mentionOptions = async (engine: BrainEngine) => ({ skipFrontmatter: true, pack: null, globalBasename: await isGlobalBasenameEnabled(engine) });
+
+/** The plain mention targets among extracted candidates (no frontmatter edge, never the page itself), each with its first context. */
+function mentionCandidates(candidates: PageLinksResult['candidates'], pageSlug: string, sourceId: string) {
const targets = new Map<string, string>();
const skipped: SkippedLinkTarget[] = [];
for (const candidate of candidates) {
- if (candidate.fromSlug || candidate.targetSlug === page.slug) continue;
+ if (candidate.fromSlug || candidate.targetSlug === pageSlug) continue;
if (!validSlug(candidate.targetSlug)) {
const slug = candidate.targetSlug.replace(/[\x00-\x1f\x7f-\x9f]/g, c => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
if (!skipped.some(target => target.slug === slug)) skipped.push({ slug, reason: 'invalid_slug' });
@@ -96,6 +108,7 @@ export async function runLinksEffect(engine: BrainEngine, effect: PersistenceEff
const skip = (tx: SqlEngine, reason: string) => completeEffect(tx, effect, { links: 'skipped', reason });
const [row] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid', [effect.request_id]);
if (!row || row.state !== 'committed' || !effect.data.slug) return skip(engine, 'invalid_write_request');
+ if (effect.data.range) return runAppendLinksEffect(engine, effect, row, effect.data.range, hostId);
const sourceId = effect.source_id;
const snapshot = await engine.readPageSnapshot(effect.data.slug, { sourceId });
if (!snapshot || snapshot.page.id !== effect.data.page_id || snapshot.revision !== effect.revision) return skip(engine, 'superseded');
@@ -103,36 +116,13 @@ export async function runLinksEffect(engine: BrainEngine, effect: PersistenceEff
const { targets, skipped } = await mentionTargets(engine, snapshot, sourceId);
const beliefs = unmanagedBeliefPoint(sourceId, [snapshot.page.slug], 'remote_auto_links');
await engine.transaction(async tx => {
- await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");
- await guardEffectSource(tx, effect, hostId);
- try { await authorizeStoredRequest(tx, row, true); }
- catch (error) {
- if (error instanceof OperationError && ['permission_denied', 'source_changed', 'page_not_found'].includes(error.code)) { await skip(tx, error.code); return; }
- throw error;
- }
- await tx.lockPageKeys([{ sourceId, slug: snapshot.page.slug }, ...[...targets.keys()].map(slug => ({ sourceId, slug }))]);
- const [current] = await tx.executeRaw<PersistenceEffect>('SELECT * FROM persistence_effects WHERE id=$1 FOR UPDATE', [effect.id]);
- if (!current || current.state !== 'running' || current.execution_token !== effect.execution_token) return;
- const live = await tx.readPageSnapshot(snapshot.page.slug, { sourceId });
- if (!live || live.page.id !== snapshot.page.id || live.revision !== snapshot.revision) { await skip(tx, 'superseded'); return; }
- const hidePrivate = row.authority.remote && ((row.authority.excludePrivate ?? true) || await excludesPrivateWrites(tx, true));
- const existing = targets.size ? await tx.executeRaw<{ slug: string; visible: boolean }>(`SELECT p.slug,(${privatePagesFilterFragment('p')}) AS visible
- FROM pages p WHERE p.source_id=$1 AND p.slug=ANY($2::text[]) AND p.deleted_at IS NULL`, [sourceId, [...targets.keys()]]) : [];
- const visible = new Map(existing.map(page => [page.slug, page.visible]));
- const granted = await targetGrant(tx, row.authority);
- const wanted = new Map<string, string>();
- for (const [slug, context] of targets) {
- const reason = !visible.has(slug) ? 'missing' : hidePrivate && !visible.get(slug) ? 'not_visible' : !granted(slug) ? 'outside_grant' : null;
- if (reason) skipped.push({ slug, reason });
- else wanted.set(slug, context);
- }
- const owned = await tx.executeRaw<{ id: number; slug: string }>(`SELECT l.id,t.slug FROM links l JOIN pages t ON t.id=l.to_page_id
- WHERE l.link_source=$1 AND l.origin_page_id=$2`, [REMOTE_MENTION_LINK_SOURCE, live.page.id]);
+ const live = await lockedPage(tx, effect, row, snapshot, targets, hostId);
+ if (!live) return;
+ if (live.revision !== snapshot.revision) { await skip(tx, 'superseded'); return; }
+ const { wanted, owned } = await writableTargets(tx, row, live, targets, skipped);
const obsolete = owned.filter(link => !wanted.has(link.slug)).map(link => link.id);
const kept = new Set(owned.map(link => link.slug));
- const additions: LinkBatchInput[] = [...wanted].filter(([slug]) => !kept.has(slug)).map(([slug, context]) => ({
- from_slug: live.page.slug, to_slug: slug, from_source_id: sourceId, to_source_id: sourceId, link_type: 'mentions', context,
- link_source: REMOTE_MENTION_LINK_SOURCE, link_kind: 'plain', origin_slug: live.page.slug, origin_source_id: sourceId }));
+ const additions = mentionEdges(live.page.slug, sourceId, wanted, kept);
const added = await beliefs.run(tx, async () => {
if (obsolete.length) await tx.executeRaw('DELETE FROM links WHERE id=ANY($1::bigint[])', [obsolete]);
return additions.length ? await tx.addLinksBatch(additions, { auditSite: 'addLinksBatch' }) : 0;
@@ -144,8 +134,141 @@ export async function runLinksEffect(engine: BrainEngine, effect: PersistenceEff
.map(target => ({ producer: 'body', ref_kind: 'slug', target_source_id: sourceId, target_ref: target.slug,
link_type: 'mentions', context: (targets.get(target.slug) ?? '').slice(0, 240) })) });
}
- await completeEffect(tx, effect, { links: 'committed', added, removed: obsolete.length, skipped_targets: skipped.slice(0, SKIPPED_TARGET_LIMIT),
- ...(skipped.length > SKIPPED_TARGET_LIMIT ? { skipped_target_count: skipped.length } : {}) });
+ await completeEffect(tx, effect, linksOutcome(added, obsolete.length, skipped));
+ });
+ await beliefs.commit(engine);
+}
+
+/**
+ * #7122: the `links` effect of a remote append_page reads only the truth bytes the append added (`data.range`), as
+ * the writer may read them, and adds plain mention edges to the pages that exist, are visible to the writer and are
+ * inside its grant, exactly as runLinksEffect does. It never removes an edge or replaces wanted rows: the rest of the
+ * page was not read. A later write moves the revision but leaves the appended bytes in place unless it rewrote them, so
+ * at a later revision the effect still runs when those bytes hash as appended, and is skipped as superseded otherwise
+ * (a remote rewrite's own effect reconciles the whole page).
+ */
+async function runAppendLinksEffect(engine: BrainEngine, effect: PersistenceEffect, row: WriteRequest, range: AppendedRange, hostId: string): Promise<void> {
+ const skip = (tx: SqlEngine, reason: string) => completeEffect(tx, effect, { links: 'skipped', reason });
+ const sourceId = effect.source_id;
+ const snapshot = await engine.readPageSnapshot(effect.data.slug!, { sourceId });
+ if (!snapshot || snapshot.page.id !== effect.data.page_id) return skip(engine, 'superseded');
+ if (!await isAutoLinkEnabled(engine) || !await isRemoteAutoLinksEnabled(engine)) return skip(engine, 'disabled');
+ const text = await appendedText(engine, snapshot, range, snapshot.revision !== effect.revision, row.authority.remote ? 'remote' : 'trusted');
+ if (text === null) return skip(engine, 'superseded');
+ const { page } = snapshot;
+ const { candidates } = await extractPageLinks(page.slug, text, {}, page.type, makeResolver(engine, { mode: 'live', sourceId }), await mentionOptions(engine));
+ const { targets, skipped } = mentionCandidates(candidates, page.slug, sourceId);
+ const beliefs = unmanagedBeliefPoint(sourceId, [page.slug], 'remote_auto_links');
+ await engine.transaction(async tx => {
+ const live = await lockedPage(tx, effect, row, snapshot, targets, hostId);
+ if (!live) return;
+ if (live.revision !== snapshot.revision) {
+ throw opError('revision_conflict', `Page ${page.slug} changed while its appended mentions were read.`, 'The links effect retries against the current revision.');
+ }
+ const { wanted, owned } = await writableTargets(tx, row, live, targets, skipped);
+ const additions = mentionEdges(live.page.slug, sourceId, wanted, new Set(owned.map(link => link.slug)));
+ const added = await beliefs.run(tx, async () => additions.length ? await tx.addLinksBatch(additions, { auditSite: 'addLinksBatch' }) : 0);
+ await completeEffect(tx, effect, linksOutcome(added, 0, skipped));
});
await beliefs.commit(engine);
}
+
+/**
+ * The appended truth bytes [start, end) as `audience` reads them; null when `verify` (the page moved since the append)
+ * finds the stored bytes there no longer hash as appended. A segmented page is read through readBodyRange, which loads
+ * only the segments the range overlaps (the remote audience gets the read projection: protected, private and withdrawn
+ * text never reaches it). An inline truth (bounded by the inline threshold) is read raw, as the append stored it; its
+ * protected regions are found over the whole truth and cut out of the range before the remote sanitizer.
+ */
+async function appendedText(engine: BrainEngine, snapshot: PageSnapshot, range: AppendedRange, verify: boolean, audience: BodyAudience): Promise<string | null> {
+ const { page } = snapshot;
+ if (isSegmentedPage(page)) {
+ const body = await openSegmentedBody(engine, { pageId: Number(page.id), pin: { revision: snapshot.revision } });
+ const read = async (as: BodyAudience) => {
+ const parts: Buffer[] = [];
+ for await (const piece of readBodyRange(engine, { pageId: body.pageId, space: 'stored', start: range.start, end: range.end, audience: as, region: 'truth', body })) parts.push(piece.bytes);
+ return Buffer.concat(parts);
+ };
+ if (verify && sha256Hex(await read('trusted')) !== range.sha256) return null;
+ const text = (await read(audience)).toString('utf8');
+ await confirmBodyPin(engine, body);
+ return text;
+ }
+ const truth = Buffer.from((await inlineRegions(engine, Number(page.id))).truth, 'utf8');
+ if (verify && sha256Hex(truth.subarray(range.start, range.end)) !== range.sha256) return null;
+ if (audience === 'trusted') return truth.subarray(range.start, range.end).toString('utf8');
+ const text = truth.toString('utf8');
+ const from = truth.subarray(0, range.start).toString('utf8').length;
+ const { regions, truncatedAt } = protectedRegions(text, PROTECTED_PAIRS);
+ const to = Math.min(truth.subarray(0, range.end).toString('utf8').length, truncatedAt === -1 ? Infinity : truncatedAt);
+ let visible = '';
+ let at = from;
+ for (const region of regions) {
+ if (region.end <= at) continue;
+ if (region.start >= to) break;
+ if (region.start > at) visible += text.slice(at, region.start);
+ at = region.end;
+ }
+ if (at < to) visible += text.slice(at, to);
+ return sanitizeRemoteBody(visible);
+}
+
+const sha256Hex = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex');
+
+/**
+ * The effect's transaction up to its page check: source guard, the stored request's authority (a revoked grant
+ * finishes the effect as skipped), the page keys of the page and its targets, and the claim. Returns the live page,
+ * or null when the effect finished or lost its claim.
+ */
+async function lockedPage(tx: BrainEngine, effect: PersistenceEffect, row: WriteRequest, snapshot: PageSnapshot, targets: Map<string, string>, hostId: string): Promise<PageSnapshot | null> {
+ const skip = (reason: string) => completeEffect(tx, effect, { links: 'skipped', reason });
+ const sourceId = effect.source_id;
+ await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");
+ await guardEffectSource(tx, effect, hostId);
+ try { await authorizeStoredRequest(tx, row, true); }
+ catch (error) {
+ if (error instanceof OperationError && ['permission_denied', 'source_changed', 'page_not_found'].includes(error.code)) { await skip(error.code); return null; }
+ throw error;
+ }
+ await tx.lockPageKeys([{ sourceId, slug: snapshot.page.slug }, ...[...targets.keys()].map(slug => ({ sourceId, slug }))]);
+ const [current] = await tx.executeRaw<PersistenceEffect>('SELECT * FROM persistence_effects WHERE id=$1 FOR UPDATE', [effect.id]);
+ if (!current || current.state !== 'running' || current.execution_token !== effect.execution_token) return null;
+ const live = await tx.readPageSnapshot(snapshot.page.slug, { sourceId });
+ if (!live || live.page.id !== snapshot.page.id) { await skip('superseded'); return null; }
+ return live;
+}
+
+/**
+ * The targets that get an edge: existing pages of the source, visible to the writer (a remote writer that excludes
+ * private pages never links one) and inside its slug grant; the rest are added to `skipped` with the reason. Also
+ * the edges this producer already owns from the page.
+ */
+async function writableTargets(tx: BrainEngine, row: WriteRequest, live: PageSnapshot, targets: Map<string, string>, skipped: SkippedLinkTarget[]) {
+ const sourceId = live.page.source_id;
+ const hidePrivate = row.authority.remote && ((row.authority.excludePrivate ?? true) || await excludesPrivateWrites(tx, true));
+ const existing = targets.size ? await tx.executeRaw<{ slug: string; visible: boolean }>(`SELECT p.slug,(${privatePagesFilterFragment('p')}) AS visible
+ FROM pages p WHERE p.source_id=$1 AND p.slug=ANY($2::text[]) AND p.deleted_at IS NULL`, [sourceId, [...targets.keys()]]) : [];
+ const visible = new Map(existing.map(page => [page.slug, page.visible]));
+ const granted = await targetGrant(tx, row.authority);
+ const wanted = new Map<string, string>();
+ for (const [slug, context] of targets) {
+ const reason = !visible.has(slug) ? 'missing' : hidePrivate && !visible.get(slug) ? 'not_visible' : !granted(slug) ? 'outside_grant' : null;
+ if (reason) skipped.push({ slug, reason });
+ else wanted.set(slug, context);
+ }
+ const owned = await tx.executeRaw<{ id: number; slug: string }>(`SELECT l.id,t.slug FROM links l JOIN pages t ON t.id=l.to_page_id
+ WHERE l.link_source=$1 AND l.origin_page_id=$2`, [REMOTE_MENTION_LINK_SOURCE, live.page.id]);
+ return { wanted, owned };
+}
+
+/** Plain `mentions` edges from the page to each wanted target it does not already have from this producer. */
+function mentionEdges(slug: string, sourceId: string, wanted: Map<string, string>, kept: Set<string>): LinkBatchInput[] {
+ return [...wanted].filter(([target]) => !kept.has(target)).map(([target, context]) => ({
+ from_slug: slug, to_slug: target, from_source_id: sourceId, to_source_id: sourceId, link_type: 'mentions', context,
+ link_source: REMOTE_MENTION_LINK_SOURCE, link_kind: 'plain', origin_slug: slug, origin_source_id: sourceId }));
+}
+
+function linksOutcome(added: number, removed: number, skipped: SkippedLinkTarget[]): Record<string, unknown> {
+ return { links: 'committed', added, removed, skipped_targets: skipped.slice(0, SKIPPED_TARGET_LIMIT),
+ ...(skipped.length > SKIPPED_TARGET_LIMIT ? { skipped_target_count: skipped.length } : {}) };
+}
diff --git a/src/core/persistence/effect-model.ts b/src/core/persistence/effect-model.ts
index 5e4cdee6af..26f0866a52 100644
--- a/src/core/persistence/effect-model.ts
+++ b/src/core/persistence/effect-model.ts
@@ -8,8 +8,13 @@ export type EffectKind = 'git' | 'embedding' | 'withdrawal-mirror' | 'facts-back
export const REMOTE_AUTO_LINKS_KEY = 'mcp.remote_auto_links';
/** link_source owned by the `links` effect; reconciliation of this producer never touches other producers' edges. */
export const REMOTE_MENTION_LINK_SOURCE = 'mcp-remote-mention';
-/** Operations whose remote publications queue a `links` effect. */
+/**
+ * Operations whose remote publications queue a whole-page `links` effect. #7122: a remote append_page queues one
+ * scoped to the truth bytes it appended (`data.range`, effect-links.ts), so it never re-reads the page.
+ */
export const REMOTE_MENTION_OPERATIONS: readonly string[] = ['put_page', 'capture', 'edit_page'];
+/** #7122: the stored truth-region bytes [start, end) an append added and their SHA-256, the only text its `links` effect reads. */
+export interface AppendedRange { start: number; end: number; sha256: string }
/**
* Commit metadata a trusted local preparer attaches to a page file target
* (a fence or content repair): the subject when the file commits alone, its
@@ -68,6 +73,8 @@ export interface PersistenceEffect {
data: { version?: 2; targets?: WithdrawalTarget[]; slug?: string; page_id?: number; relative_path?: string; expected_hash?: string | null; after_slug?: string; source_id?: string; source_scan?: boolean; visibility?: 'private' | 'world'; embedding_attempt_base?: number; embedding_retry_base?: number;
/** Wave B: the occurrences a segmented write added; its embedding effect embeds only their chunk rows. */
occurrence_ids?: number[];
+ /** #7122: an append's `links` effect mines only these appended truth bytes and never removes an edge. */
+ range?: AppendedRange;
/** A single-file Git target's GitCommitNote, when its preparer gave one. */
commit_subject?: string;
commit_line?: string;
diff --git a/src/core/persistence/page-append.ts b/src/core/persistence/page-append.ts
index 71fd905c7f..4b8b200492 100644
--- a/src/core/persistence/page-append.ts
+++ b/src/core/persistence/page-append.ts
@@ -16,7 +16,9 @@
* guessing oracle), as get_page withholds it.
*
* The segmented path writes its derived rows for the appended text after commit as any segmented write does (chunks,
- * embeddings); links, timeline rows and fence projections of the appended text follow PR 4's incremental derivation.
+ * embeddings). A remote append to the compiled truth records the bytes it added (`mentionRange`) for its `links` effect,
+ * which mines those bytes alone (#7122, effect-links.ts); timeline rows and fence projections of the appended text follow
+ * PR 4's incremental derivation.
*/
import { createHash } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
@@ -27,7 +29,7 @@ import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../facts-fence.ts';
import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../takes-fence.ts';
-import { serializePageToMarkdown, timelineSentinelKind } from '../markdown.ts';
+import { parseMarkdown, serializePageToMarkdown, timelineSentinelKind } from '../markdown.ts';
import { buildContentFlagMarker, CONTENT_FLAG_KEY, isQuarantined } from '../quarantine.ts';
import { sizeStateField } from '../page-embedding-budget.ts';
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
@@ -384,6 +386,7 @@ export async function prepareAppendMutation(engine: BrainEngine, row: WriteReque
const separatorFor = (tail: RegionTail) => intent.separator === 'auto' && tail.bytes.length > 0 && tail.bytes[tail.bytes.length - 1] !== 0x0a ? '\n' : '';
if (isSegmentedPage(stored.page)) {
+ let mentionRange: PreparedMutation['mentionRange'];
const prepared = await prepareSegmentedSpliceMutation(engine, row, stored, { full: appendProbe.fullRewrite, replacements: async page => {
const region = targetRegion(intent.region, page.bodyBytes > page.truthBytes);
const tail = await segmentedRegionTail(engine, row.source_id, page, region);
@@ -391,9 +394,13 @@ export async function prepareAppendMutation(engine: BrainEngine, row: WriteReque
if (region === 'timeline' && page.bodyBytes === page.truthBytes) return null;
const bytes = Buffer.from(separatorFor(tail) + text, 'utf8');
const at = region === 'truth' ? page.truthBytes : page.bodyBytes;
+ mentionRange = region === 'truth' ? { start: at, end: at + bytes.length, sha256: sha256Hex(bytes) } : undefined;
return { replacements: [{ start: at, end: at, bytes }], appendTo: region, outcome: { appended_bytes: bytes.length, region } };
} });
- if (prepared) return prepared;
+ if (prepared) {
+ if (mentionRange) prepared.mentionRange = mentionRange;
+ return prepared;
+ }
if (Number((stored.page as { body_bytes?: number | null }).body_bytes ?? 0) + Buffer.byteLength(text, 'utf8') + 1 > PAGE_MAX_BYTES) {
throw opError('page_body_segmented', `Page ${row.slug} cannot take this append in segments (an external_untrusted write the gate scans whole, an always-loaded core page, or an append that starts a region), and it is over the ${PAGE_MAX_BYTES}-byte limit of a whole-body write. Nothing was appended.`,
'Append to the last non-empty region (omit region), or write from a trusted caller.', { fix: pageFix(row.source_id, row.slug) });
@@ -410,7 +417,12 @@ export async function prepareAppendMutation(engine: BrainEngine, row: WriteReque
const beforeBytes = Buffer.byteLength(page.compiled_truth ?? '', 'utf8') + Buffer.byteLength(page.timeline ?? '', 'utf8');
const prepared = await preparePageMutation(engine, row, config, { content, expectedRevision: stored.revision }, signal, { clock });
const apply = prepared.apply.bind(prepared);
- return { ...prepared, apply: async (tx, preimage) => {
+ // The stored truth is the parsed one (trimmed); the append's bytes are what it adds after the old truth.
+ const truth = region === 'truth' ? Buffer.from(parseMarkdown(content, row.slug).compiled_truth, 'utf8') : null;
+ const start = Buffer.byteLength(before, 'utf8');
+ const mentionRange = truth && truth.length > start && truth.subarray(0, start).equals(Buffer.from(before, 'utf8'))
+ ? { start, end: truth.length, sha256: sha256Hex(truth.subarray(start)) } : undefined;
+ return { ...prepared, ...(mentionRange ? { mentionRange } : {}), apply: async (tx, preimage) => {
const outcome = await apply(tx, preimage);
const [row2] = await tx.executeRaw<{ bytes: string | null }>(`SELECT COALESCE(body_bytes, octet_length(COALESCE(compiled_truth,'')) + octet_length(COALESCE(timeline,'')))::text AS bytes
FROM pages WHERE id=$1`, [stored.page.id]);
diff --git a/test/append-page-operation-lists.test.ts b/test/append-page-operation-lists.test.ts
index 5d66ca519f..09d2439912 100644
--- a/test/append-page-operation-lists.test.ts
+++ b/test/append-page-operation-lists.test.ts
@@ -42,12 +42,17 @@ describe('append_page in operation lists', () => {
}
});
- test('append_page stays out of the owner-edit and remote-mention lists', () => {
+ test('append_page stays out of the owner-edit and whole-page remote-mention lists', () => {
// Owner edits can release a purge redaction: an append cannot write facts or takes (fence markers are refused).
expect(list('src/core/belief/ledger.ts', 'const OWNER_EDIT_OPERATIONS')).not.toContain("'append_page'");
- // A remote mention links effect re-reads the whole page; an append's links follow the incremental derivation instead.
+ // #7122: the whole-page links effect re-reads the page; a remote append queues one scoped to the truth bytes it added,
+ // and none when it added none there (a timeline append).
const remote = { remote: true, autoLinkTrusted: false } as WriteRequest['authority'];
+ const mentionRange = { start: 10, end: 20, sha256: '0'.repeat(64) };
+ expect(list('src/core/persistence/effect-model.ts', 'export const REMOTE_MENTION_OPERATIONS')).not.toContain("'append_page'");
expect(queuesMentionLinks({ operation: 'edit_page', authority: remote })).toBe(true);
expect(queuesMentionLinks({ operation: 'append_page', authority: remote })).toBe(false);
+ expect(queuesMentionLinks({ operation: 'append_page', authority: remote }, { mentionRange })).toBe(true);
+ expect(queuesMentionLinks({ operation: 'append_page', authority: { remote: false } as WriteRequest['authority'] }, { mentionRange })).toBe(false);
});
});
diff --git a/test/belief-ledger-append-owner.test.ts b/test/belief-ledger-append-owner.test.ts
new file mode 100644
index 0000000000..0769dc6ba1
--- /dev/null
+++ b/test/belief-ledger-append-owner.test.ts
@@ -0,0 +1,106 @@
+/**
+ * #7123: append_page is not an owner edit of the belief ledger (`OWNER_EDIT_OPERATIONS`, belief/ledger.ts), so an
+ * owner's append never releases a purge redaction, and the ledger attributes it as an append.
+ *
+ * 1. Protects: a local append to a page whose fact context is under a purge redaction commits, appends no
+ * `redaction.released` event, leaves the register unreleased, and every event of its publication carries
+ * `cause.op: 'append_page'` and its request. An owner-tier append publication (the append intent, and the same row
+ * with the intent's kind stripped) gets no `ownerEdit`, so a carrying field it rewrites stays the redaction marker.
+ * 2. Fails when: append_page joins OWNER_EDIT_OPERATIONS (the kind-less publication releases the redaction), or the
+ * allowlist is dropped (the forced probe below: the append publication releases it and writes the new value).
+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set (test/postgres-unit-arms.txt).
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { REDACTION_MARKER } from '../src/core/belief/keys.ts';
+import { __dropOwnerEditAllowlistForTests, publicationBeliefOptions, withBeliefBatch } from '../src/core/belief/ledger.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { operations } from '../src/core/operations.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { beliefBrain, beliefEngineCase, beliefPage, type BeliefBrain } from './helpers/belief-ledger.ts';
+
+afterEach(() => { __dropOwnerEditAllowlistForTests(false); });
+
+const X = 'Door code is 4417';
+const SLUG = 'companies/acme-example';
+const purgeOp = operations.find(o => o.name === 'purge_fact')!;
+
+async function purgeFact(b: BeliefBrain, claim: string): Promise<string> {
+ const [row] = await b.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id = $1 AND fact = $2 AND expired_at IS NULL ORDER BY id LIMIT 1', [b.sourceId, claim]);
+ const dry = await purgeOp.handler(b.ctx, { id: Number(row!.id), dry_run: true }) as Record<string, any>;
+ const done = await purgeOp.handler(b.ctx, { id: Number(row!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID() }) as Record<string, any>;
+ return await requestOf(b, String(done.request_id));
+}
+
+const requestOf = async (b: BeliefBrain, clientRequestId: string) =>
+ (await b.engine.executeRaw<{ id: string }>('SELECT id::text AS id FROM persistence_requests WHERE request_id = $1::uuid', [clientRequestId]))[0]!.id;
+const releasedCount = async (b: BeliefBrain) =>
+ (await b.engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM belief_redactions WHERE source_id = $1 AND released_hash IS NOT NULL', [b.sourceId]))[0]!.n;
+
+/** Runs a brain scenario to completion (teardown included) and returns what it reported. */
+async function collect<T>(run: (report: (value: T) => void) => Promise<void>): Promise<T> {
+ let out: T | undefined;
+ await run(value => { out = value; });
+ return out as T;
+}
+
+/** A page whose second fact's context quotes the claim the scenario purges, so that context is under a redaction. */
+const seeded = async (b: BeliefBrain) => {
+ await b.put(SLUG, beliefPage({ facts: [X, { claim: 'Acme sells widgets', context: `notes say ${X}` }] }));
+ return purgeFact(b, X);
+};
+
+for (const engineCase of testBackends().map(beliefEngineCase)) {
+ describe(`append_page and the belief ledger owner edit (${engineCase.name})`, () => {
+ const brain = (run: (b: BeliefBrain) => Promise<void>) => beliefBrain(run, { managed: true, databaseUrl: engineCase.databaseUrl });
+
+ test('an owner\'s append next to a purged claim releases nothing and is attributed to append_page', async () => {
+ const r = await collect<Record<string, unknown>>(report => brain(async b => {
+ await seeded(b);
+ const mark = await b.lastId();
+ const clientRequest = randomUUID();
+ await b.op('append_page', { slug: SLUG, text: 'Later note about the widget plan.', request_id: clientRequest });
+ const request = await requestOf(b, clientRequest);
+ const [state] = await b.engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE id = $1::uuid', [request]);
+ const events = await b.events(mark);
+ const own = events.filter(e => e.publication_id === request);
+ report({ state: state!.state, appended: (await b.engine.executeRaw<{ t: string }>('SELECT compiled_truth AS t FROM pages WHERE source_id = $1 AND slug = $2', [b.sourceId, SLUG]))[0]!.t.includes('Later note'),
+ released: await releasedCount(b), releaseEvents: events.filter(e => e.event_type === 'redaction.released').length,
+ published: own.map(e => [e.subject_kind, e.event_type, e.writer_tier]), causes: [...new Set(own.map(e => JSON.stringify(e.cause)))].map(c => JSON.parse(c)),
+ leaks: events.filter(e => JSON.stringify(e.value ?? {}).includes(X)).length, request });
+ }));
+ expect(r).toEqual({ state: 'committed', appended: true, released: 0, releaseEvents: 0, published: [['page', 'page.published', null]],
+ causes: [{ op: 'append_page', request: r.request }], leaks: 0, request: r.request });
+ }, 240_000);
+
+ test('an owner-tier append publication gets no ownerEdit, so a field it rewrites stays redacted (forced probe: dropping the allowlist releases it)', async () => {
+ const run = (forced: boolean) => collect<Record<string, unknown>>(report => brain(async b => {
+ const purge = await seeded(b);
+ __dropOwnerEditAllowlistForTests(forced);
+ const fact = `source_id = $1 AND fact = 'Acme sells widgets' AND expired_at IS NULL`;
+ const intent = { kind: 'append_page', text: 'Later note.', region: 'auto', separator: 'auto', preconditions: {} };
+ const out: Record<string, unknown> = { marker: REDACTION_MARKER(purge) };
+ for (const [name, shape] of [['append', intent], ['kindless', {}]] as const) {
+ const options = publicationBeliefOptions({ id: randomUUID(), source_id: b.sourceId, slug: SLUG, operation: 'append_page', authority: { remote: false }, intent: shape });
+ const mark = await b.lastId();
+ await b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], async () => {
+ await tx.lockPageKeys([{ sourceId: b.sourceId, slug: SLUG }]);
+ await withBeliefBatch(tx, options, () => tx.executeRaw(`UPDATE facts SET context = '${name} rewrote it' WHERE ${fact}`, [b.sourceId]));
+ }, { ...TEST_WRITE_ATTRIBUTION, trust: { tier: 'operator_curated', origin: { channel: 'append_page' } } }));
+ const events = await b.events(mark);
+ out[name] = { ownerEdit: options.ownerEdit === true, contexts: events.filter(e => e.event_type.startsWith('fact.')).map(e => e.value?.context),
+ causes: [...new Set(events.filter(e => e.event_type.startsWith('fact.')).map(e => e.cause.op))] };
+ if (forced) break;
+ }
+ out.released = await releasedCount(b);
+ report(out);
+ }));
+ const r = await run(false);
+ const m = r.marker;
+ expect(r).toEqual({ marker: m, append: { ownerEdit: false, contexts: [m], causes: ['append_page'] }, kindless: { ownerEdit: false, contexts: [m], causes: ['append_page'] }, released: 0 });
+ const forced = await run(true);
+ expect(forced).toEqual({ marker: forced.marker, append: { ownerEdit: true, contexts: ['append rewrote it'], causes: ['append_page'] }, released: 1 });
+ }, 240_000);
+ });
+}
diff --git a/test/large-pages/append-mention-links.test.ts b/test/large-pages/append-mention-links.test.ts
new file mode 100644
index 0000000000..cc2eb48ea0
--- /dev/null
+++ b/test/large-pages/append-mention-links.test.ts
@@ -0,0 +1,168 @@
+/**
+ * #7122: a remote append_page links the existing pages its appended text mentions, reading only that text.
+ *
+ * 1. Protects: a remote append to the compiled truth queues a `links` effect scoped to the bytes it added
+ * (`data.range`); the effect reads those bytes alone through the segmented reader with the writer's audience
+ * (readSegmentTexts spy: the same bounded segment text after a 10 KB append to a 1.5 MB and a 6 MB page), and adds
+ * a plain `mentions` edge (link_source mcp-remote-mention) to each mentioned page that exists and the writer can
+ * see inside its grant. It never removes an edge an earlier write made, and two appends whose effects run after
+ * both still link both. A mention of a private page or a page outside the grant makes no edge, and appended text
+ * that lands in a takes fence left open at the tail is not mined, on segmented and inline pages.
+ * 2. Fails when: append_page queues no links effect (the base: no edge at all), the effect re-reads the whole page
+ * (the segment bound fails), reads the trusted text for a remote writer (the takes mention links), or reconciles
+ * the page against the appended text alone (the earlier edge is removed).
+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set (test/postgres-unit-arms.txt). Work is counted, never timed.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { conversationBody, conversationPage } from '../helpers/conversation-page.ts';
+import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { waitFor } from '../helpers/wait-for.ts';
+import { SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';
+
+const SMALL = 'notes/mention-log-small';
+const BIG = 'notes/mention-log-big';
+const INLINE = 'notes/mention-log-inline';
+const TAKES_SEGMENTED = 'notes/mention-log-takes';
+const TAKES_INLINE = 'notes/mention-log-takes-inline';
+const FENCED_LATER = 'notes/mention-log-fenced-later';
+/** About 10 KB of conversation turns, then the mentions. */
+const filler = conversationBody(10_000, { seed: 7 });
+const mentions = (...slugs: string[]) => `${filler}\n\nFollow-up with ${slugs.map(slug => `[[${slug}]]`).join(', ')}.`;
+const TAKES_BEGIN = '<!--- gbrain:takes:begin -->';
+/** A takes block whose first begin marker never pairs (a second begin follows): the tail is protected to the end of the truth. */
+const OPEN_TAKES = `\n\n${TAKES_BEGIN}\nPrivate musing.\n\n${TAKES_BEGIN}\n| # | claim | kind | who | weight | since | source |\n|---|-------|------|-----|--------|-------|--------|\n| 1 | Widgets will sell | take | brain | 0.5 | 2026-07 | notes |\n<!--- gbrain:takes:end -->\n\nMore private musing.\n`;
+/** A line as long as the takes begin marker, which a later trusted edit turns into one without moving any byte after it. */
+const PLACEHOLDER = 'x'.repeat(TAKES_BEGIN.length);
+
+for (const kind of testBackends()) {
+ describe(`remote append_page mention links (${kind})`, () => {
+ let brain: AppendBrain;
+ const edges = async (slug: string) => (await brain.engine.executeRaw<{ to_slug: string; link_type: string; link_source: string }>(
+ `SELECT t.slug AS to_slug, l.link_type, l.link_source FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id
+ WHERE f.source_id='default' AND f.slug=$1 ORDER BY t.slug, l.link_source`, [slug]));
+ /** This producer's edges only: a trusted local write links its own text through the markdown producer. */
+ const remoteEdges = async (slug: string) => (await edges(slug)).filter(e => e.link_source === 'mcp-remote-mention');
+ const mention = (to_slug: string) => ({ to_slug, link_type: 'mentions', link_source: 'mcp-remote-mention' });
+ const linksEffects = (slug: string) => brain.engine.executeRaw<{ request_id: string; state: string; outcome: Record<string, any> | null; data: Record<string, any> }>(
+ `SELECT request_id::text AS request_id, state, outcome, data FROM persistence_effects WHERE kind='links' AND data->>'slug'=$1 ORDER BY id`, [slug]);
+ /** Effects queued while `fn` runs wait until released, so the test decides when the links effects run. */
+ const deferred = async <T>(fn: () => Promise<T>): Promise<T> => {
+ await brain.engine.executeRaw("ALTER TABLE persistence_effects ALTER COLUMN next_attempt_at SET DEFAULT (now()+interval '1 hour')");
+ try { return await fn(); } finally { await brain.engine.executeRaw('ALTER TABLE persistence_effects ALTER COLUMN next_attempt_at SET DEFAULT now()'); }
+ };
+ /** Release the page's links effects (and only those) and wait until each settles; returns the segment text loaded meanwhile. */
+ const runLinks = async (slug: string) => {
+ const original = brain.engine.readSegmentTexts.bind(brain.engine);
+ const loaded = { segments: 0, bytes: 0 };
+ brain.engine.readSegmentTexts = (async (sourceId: string, hashes: Uint8Array[]) => {
+ const texts = await original(sourceId, hashes);
+ loaded.segments += texts.size;
+ for (const text of texts.values()) loaded.bytes += text.length;
+ return texts;
+ }) as typeof brain.engine.readSegmentTexts;
+ try {
+ await brain.engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE kind='links' AND data->>'slug'=$1 AND state='queued'", [slug]);
+ await waitFor(async () => (await linksEffects(slug)).every(e => e.state === 'committed'), { timeoutMs: 60_000, intervalMs: 50, label: `links effects of ${slug} settled` });
+ } finally { brain.engine.readSegmentTexts = original; }
+ return loaded;
+ };
+ const append = async (slug: string, text: string, extra: Record<string, unknown> = {}) => {
+ const res = await brain.call('append_page', { slug, text, request_id: randomUUID(), ...extra }, { remote: true });
+ expect(res).toMatchObject({ isError: false });
+ return res.body;
+ };
+
+ beforeAll(async () => {
+ brain = await openAppendBrain(kind);
+ for (const slug of ['notes/alice-example', 'notes/bob-example', 'notes/carol-example']) await brain.seed(slug, `---\ntitle: ${slug}\ntype: person\n---\n\n${slug} fixture.\n`);
+ await brain.seed('notes/secret-example', '---\ntitle: Secret\ntype: person\nvisibility: private\n---\n\nPrivate fixture.\n');
+ await brain.seed('people/outside-example', '---\ntitle: Outside\ntype: person\n---\n\nOutside the grant.\n');
+ await brain.seed(SMALL, conversationPage(1_500_000, { seed: 1 }));
+ await brain.seed(BIG, conversationPage(6_000_000, { seed: 2 }));
+ await brain.seed(INLINE, conversationPage(20_000, { seed: 3 }));
+ await brain.seed(TAKES_SEGMENTED, `${conversationPage(1_500_000, { seed: 4 }).trimEnd()}${OPEN_TAKES}`);
+ await brain.seed(TAKES_INLINE, `${conversationPage(20_000, { seed: 5 }).trimEnd()}${OPEN_TAKES}`);
+ await brain.seed(FENCED_LATER, `${conversationPage(20_000, { seed: 6 }).trimEnd()}\n\n${PLACEHOLDER}\n`);
+ for (const slug of [SMALL, BIG, TAKES_SEGMENTED]) expect((await brain.body(slug)).storage).toBe('segmented');
+ for (const slug of [INLINE, TAKES_INLINE, FENCED_LATER]) expect((await brain.body(slug)).storage).toBe('inline');
+ }, 600_000);
+ afterAll(() => brain.close(), 120_000);
+
+ test('a remote append links the pages it mentions and reads only the appended bytes, at 1.5 MB and 6 MB', async () => {
+ for (const slug of [SMALL, BIG]) {
+ const text = mentions('notes/alice-example', 'notes/secret-example', 'notes/ghost-example', 'people/outside-example');
+ const res = await deferred(() => append(slug, text));
+ const [queued] = await linksEffects(slug);
+ expect(queued!.state).toBe('queued');
+ expect(queued!.data.range.end - queued!.data.range.start).toBe(res.appended_bytes);
+ const work = await runLinks(slug);
+ // Exactly the live segments the appended bytes overlap (the new tail: old tail text plus the append), at either page size.
+ const { start, end } = queued!.data.range;
+ const [page] = await brain.engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [slug]);
+ const overlapped = (await brain.engine.readManifest(Number(page!.id), { region: 'truth' })).filter(row => row.byteStart < end && row.byteStart + row.byteLen > start);
+ expect(overlapped.length).toBeGreaterThan(0);
+ expect(overlapped.length).toBeLessThanOrEqual(2);
+ expect(work).toEqual({ segments: overlapped.length, bytes: overlapped.reduce((n, row) => n + row.byteLen, 0) });
+ expect(work.bytes).toBeLessThanOrEqual(SEGMENT_MAX_BYTES + res.appended_bytes);
+ expect(await edges(slug)).toEqual([mention('notes/alice-example')]);
+ const [settled] = await linksEffects(slug);
+ expect(settled!.outcome).toMatchObject({ links: 'committed', added: 1, removed: 0 });
+ expect(new Map(settled!.outcome!.skipped_targets.map((t: { slug: string; reason: string }) => [t.slug, t.reason]))).toEqual(new Map([
+ ['notes/secret-example', 'not_visible'], ['notes/ghost-example', 'missing'], ['people/outside-example', 'outside_grant']]));
+ }
+ }, 300_000);
+
+ test('appends never remove an edge, and two appends whose effects run after both link both', async () => {
+ await deferred(async () => {
+ await append(SMALL, mentions('notes/bob-example'));
+ await append(SMALL, mentions('notes/carol-example'));
+ });
+ await runLinks(SMALL);
+ expect(await edges(SMALL)).toEqual([mention('notes/alice-example'), mention('notes/bob-example'), mention('notes/carol-example')]);
+ expect((await linksEffects(SMALL)).slice(-2).map(e => e.outcome)).toEqual([
+ { links: 'committed', added: 1, removed: 0, skipped_targets: [] }, { links: 'committed', added: 1, removed: 0, skipped_targets: [] }]);
+ }, 300_000);
+
+ test('an inline page: the visible mention links, a private one does not, and a rewrite of the appended text supersedes its effect', async () => {
+ await deferred(() => append(INLINE, mentions('notes/alice-example', 'notes/secret-example')));
+ await runLinks(INLINE);
+ expect(await edges(INLINE)).toEqual([mention('notes/alice-example')]);
+ expect((await linksEffects(INLINE)).at(-1)!.outcome).toMatchObject({ added: 1, skipped_targets: [{ slug: 'notes/secret-example', reason: 'not_visible' }] });
+ const page = await brain.body(INLINE);
+ await deferred(() => append(INLINE, mentions('notes/bob-example')));
+ const rewritten = await brain.call('put_page', { slug: INLINE, content: `---\ntitle: Conversation log\ntype: note\n---\n\n${page.truth}\n\nRewritten tail.\n`, request_id: randomUUID(), force: true });
+ expect(rewritten).toMatchObject({ isError: false });
+ await runLinks(INLINE);
+ expect((await linksEffects(INLINE)).at(-1)!.outcome).toEqual({ links: 'skipped', reason: 'superseded' });
+ expect(await remoteEdges(INLINE)).toEqual([mention('notes/alice-example')]);
+ }, 300_000);
+
+ test('appended text inside a takes fence left open at the tail of a segmented page is not mined', async () => {
+ await deferred(() => append(TAKES_SEGMENTED, mentions('notes/alice-example')));
+ expect((await brain.body(TAKES_SEGMENTED)).truth.endsWith('[[notes/alice-example]].')).toBe(true);
+ await runLinks(TAKES_SEGMENTED);
+ expect(await edges(TAKES_SEGMENTED)).toEqual([]);
+ expect((await linksEffects(TAKES_SEGMENTED)).at(-1)!.outcome).toEqual({ links: 'committed', added: 0, removed: 0, skipped_targets: [] });
+ }, 300_000);
+
+ test('an inline page: a remote append onto an open takes fence is refused; appended text a later edit fences is not mined', async () => {
+ const refused = await brain.call('append_page', { slug: TAKES_INLINE, text: mentions('notes/alice-example'), request_id: randomUUID() }, { remote: true });
+ expect(refused).toMatchObject({ isError: true, body: { code: 'invalid_params' } });
+ expect(await linksEffects(TAKES_INLINE)).toEqual([]);
+ // The trusted edit turns the line before the appended text into a takes begin marker and closes the fence after it; the
+ // appended bytes keep their offsets and hash, so the effect runs at the later revision and reads them as the remote writer may: hidden.
+ await deferred(() => append(FENCED_LATER, mentions('notes/alice-example')));
+ const before = await brain.body(FENCED_LATER);
+ const edited = await brain.call('put_page', { slug: FENCED_LATER, force: true, request_id: randomUUID(),
+ content: `---\ntitle: Conversation log\ntype: note\n---\n\n${before.truth.replace(PLACEHOLDER, TAKES_BEGIN)}\n<!--- gbrain:takes:end -->\n` });
+ expect(edited).toMatchObject({ isError: false });
+ const after = await brain.body(FENCED_LATER);
+ expect(after.truth.startsWith(before.truth.replace(PLACEHOLDER, TAKES_BEGIN))).toBe(true);
+ await runLinks(FENCED_LATER);
+ expect(await remoteEdges(FENCED_LATER)).toEqual([]);
+ expect((await linksEffects(FENCED_LATER)).at(-1)!.outcome).toEqual({ links: 'committed', added: 0, removed: 0, skipped_targets: [] });
+ }, 300_000);
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 15d79af331..623936cb5a 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -16,6 +16,7 @@ test/alias-source-cascade-5094.test.ts
test/attribution-backfill-history.test.ts
test/backstop-same-page-shadow-managed-6333.test.ts
test/behavior-change-notice.test.ts
+test/belief-ledger-append-owner.test.ts
test/belief-ledger-coverage.test.ts
test/belief-ledger-group.test.ts
test/belief-ledger-identity.test.ts
@@ -90,6 +91,7 @@ test/keyword-timeout-negative-cache-6495.test.ts
test/lane-apply-pipelining.test.ts
test/large-pages/append-concurrency.test.ts
test/large-pages/append-cost.test.ts
+test/large-pages/append-mention-links.test.ts
test/large-pages/chunk-retirement-plan.test.ts
test/large-pages/chunk-visibility.test.ts
test/large-pages/contextual-reembed-segmented.test.ts