Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
large pages: managed sync streams Markdown files over 24 MiB
garrytana53c0906b50e
diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex 1e730bf55a..82e688cc29 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -10,5 +10,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/sync.ts` — Pure sync functions (manifest parsing, filtering, slug conversion). Exported `pruneDir(name: string): boolean` is the single source of truth for descent-time directory exclusion across walkers — blocks `node_modules` (no leading dot, so a naive walker would descend into it and inflate MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (the bundled daily-task-manager stores `ops/tasks` there); `isSyncable` applies it per path segment, and `walkMarkdownFiles` in `src/commands/extract.ts` + `listTextFiles` in `src/core/cycle/transcript-discovery.ts` consult it BEFORE recursing to save the IO of walking thousands of vendor files. `manageGitignore` worktree discriminator matches the gitdir path segment (`/modules/<name>` = submodule, `/worktrees/<name>` = worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get `.gitignore` management for storage-tiering. The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives in `src/core/sync-failure-ledger.ts`; `sync.ts` re-exports `classifyErrorCode`, `summarizeFailuresByCode`, `loadSyncFailures`, `unacknowledgedSyncFailures`, `acknowledgeSyncFailures`, `recordSyncFailures`, `decideSyncFailureSeverity`, `applySyncFailureGate`, and the `SyncFailure` type for backward-compatible imports — see its entry below. `isSyncable` factored through private `classifySync(path, opts): SyncableReason | null`; exported companion `unsyncableReason(path, opts)` returns the same tagged reason or null when syncable. `SYNC_SKIP_FILES` is a named export (the canonical metafile basenames `schema.md`, `index.md`, `log.md`, `README.md`, `RESOLVER.md`, skipped at any depth); `SYNC_ROOT_SKIP_FILES` (#5186, W14 P1.5b) adds the bootstrap scaffolding `AGENTS.md` / `CLAUDE.md` at depth 0 only, and `isSyncMetafile(path)` is the one predicate `classifySync` and the bulk-import collector (`commands/import.ts`) share (the managed effect scan's `isMetafilePage` in `persistence/effects.ts` still reads `SYNC_SKIP_FILES` directly), so an earlier-indexed root `agents` page survives under the #1433 guard (`test/sync-root-agents-metafile.test.ts`). `SyncableReason` union: `'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit' | 'malformed-path'`. Malformed filenames are TWO-TIER: `hasMalformedPathSegment` (ADMISSION — control chars on any path; square brackets on `.md`/`.mdx` paths only, so code-strategy lanes keep indexing `app/[id]/page.tsx` framework layouts) vs `isPoisonedPath` (DESTRUCTION — only the injection signature `](` or control chars; sync's row-DELETING lanes gate on this so a bare-bracket markdown row already in the DB survives reconcile while its file exists). `sanitizePathForDisplay` scrubs control bytes + caps length before echoing such paths. The un-syncable cleanup loop (`sweepUnsyncableModified` in `src/commands/sync/deletes.ts`) guards on `unsyncableReason(path)` being `'metafile'` OR `'pruned-dir'` so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT cover `manifest.deleted` (the upstream filter already strips metafiles). Pinned by `test/sync-isSyncable-shape.test.ts` (15 cases, duality contract) + `test/sync-metafile-skip.test.ts` (3 PGLite cases incl. the renamed `.md → .txt` negative). `pruneDir`: `pruneDir(name, parentDir?)` extended with optional `parentDir`. When provided, additionally rejects directories containing `.git` as a FILE — the git submodule gitfile pattern (regular repos have `.git` as a DIRECTORY; submodules as a file pointing into the parent's `.git/modules/`). Sync + extract walkers thread `parentDir` so the gitfile-as-FILE check fires per descend step. Best-effort: `statSync` failures fall through and treat as a normal dir. Prevents phantom imports from a worktree-with-submodules sync walking into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`. The legacy failure ledger re-export is distinct from managed cursor-keyed mirrors: repeat managed observation does not inflate attempts, success clears only the matching cursor, and managed failures cannot be acknowledged or auto-skipped. `isMultimodalEnabled(env)` (`GBRAIN_EMBEDDING_MULTIMODAL=true`) is the one predicate managed discovery, the hold re-screen, `embed --stale`, the blocked-projection hint and doctor `image_embedding_coverage` read for whether images are imported and embedded.- `src/core/persistence/sync-image.ts` — #6529: managed sync's image branch. With multimodal embedding on, `freezeEntry` (`sync-run.ts`) freezes an image entry as its bytes in base64 (`frozenImageIntent`; `rawHash` stays the file sha256, so the working-tree check and the hash no-op are unchanged) and `prepareManagedSyncMutation` (`sync-prepare.ts`) hands it to `prepareManagedSyncImage`, which runs `importImageFile` with `prepare` (the coordinated path `gbrain import` uses in `import-prepare.ts`): the importer decides the hash no-op, OCRs and embeds the image at preparation inside the sync budget (`--no-embed` skips both; the caption chunk's text vector is deferred to `embed --stale`), and the apply records `source_path`, releases the path's hold and re-reads the snapshot. A company plan refuses (`profile_incompatible`), a screening preparation (`sameContentAtOrigin`, the no-op waiver in `sync-waivers.ts` and `unchangedManagedImport` in `import-mutations.ts` return early for images) is refused rather than paid for, newer working-tree bytes or a vanished file refuse `source_changed`, and a Git rename publishes the new slug and soft-deletes the old page. `import-file.ts` records `source_path` on the legacy importer's hash-skip path too (`refreshSourcePath`), so no image import leaves it NULL. Tests: `test/managed-sync-images-5493.test.ts` (both engines), `test/embed-stale-images-managed-6529.test.ts`.+- `src/core/persistence/sync-streamed.ts` — Wave B PR 2: managed sync of a Markdown file over the 24 MiB single-string ceiling. With `pages.segmented_storage` on, `freezeEntry` (`sync-run.ts`) freezes such a file by reference instead of holding it by its size: `streamedSyncBodyRef` hashes the sha256 and the Git blob id as a stream (sha1 or sha256 by the pinned commit's length) into `intent.body_ref` (`git_blob`, or `input_file` for an uncommitted working-tree file); the journal carries no content, and a committed entry whose working tree does not hold its pinned blob, a file over `pages.max_bytes` or a non-Markdown file is held as before. `prepareManagedSyncMutation` (`sync-prepare.ts`) hands it to `prepareManagedSyncStreamed`, which streams it through `importStreamedMarkdownFile` (`page-body/streamed-import.ts`, `coordinated`; `moved` on a rename keeps an implicit type following the new path) and publishes database-only; a rename moves the page first and re-seals an unchanged body (`sealSegmentedPage`). A file the streamed path refuses (a facts fence) fails its request with the refusal's code and the run holds it (`streamedRefusalHold` in `sync-screen.ts`); a dry run lists it in `screen_skipped` as `page_body_segmented`; `groupableIntent` (`sync-group.ts`) keeps it out of bulk groups. Tests: `test/large-pages/managed-sync-streamed.test.ts` (both engines), `managed-sync-streamed-crash.test.ts` (owner killed at `consumer:prepared`), `managed-sync-streamed-memory.slow.test.ts` (VmHWM).- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? })` (active rows by default; `includeDeleted: true` resolves a tombstone's recorded `source_path` for the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`); the page's recorded `source_path` (or a contained absolute `file://` `source_uri`; a relative or host-only `file://` names no local file and is read as absent) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention for the source's pinned `slug_root_mode` (or the mode its first sync would pin, via `scannerSlugRootMode`): GIT-ROOT-relative under `git-root` when the scan root sits inside a git repo, scan-root-relative under `source-root` and for non-git or git-root scan roots, so a put-born page binds the same form managed sync and delete-reconcile key on. Every recorded-path reader (write targets, takes, reconcile, audit, export restore, doctor) decodes with the same mode (`resolveSourceLocalFilePath(..., slugRootMode)`): under `source-root` the scope prefix is removed only from the legacy Git-root form whose remainder names the page slug, and basename rows resolve under the unstripped slug directory. The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, logger?, expectedFileBytes?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders it via `serializePageToMarkdown`, and writes the `.md` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed `atomicWriteFileSync` stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. `put_page` holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns `WriteThroughResult { written, path?, skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed', warning?, error? }` (`file_changed`: the caller's `expectedFileBytes` preimage, null for absent, no longer matches the file under the source filesystem lock, so the file is left untouched) so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error` inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 3d9c56dc28..950e3aa9fe 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -37,7 +37,7 @@ src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap insrc/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeoutsrc/core/config.ts 1981 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981-src/core/persistence/sync-run.ts 1690 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts)+src/core/persistence/sync-run.ts 1704 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHoldsrc/core/bootstrap/harness.ts 2615 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent blocksrc/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 707 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707diff --git a/src/core/page-body/streamed-import.ts b/src/core/page-body/streamed-import.tsindex e381830bf5..ed6c7e9ecc 100644--- a/src/core/page-body/streamed-import.ts+++ b/src/core/page-body/streamed-import.ts@@ -89,6 +89,8 @@ type StreamedImportOptions = {* runs in the coordinator's publication transaction.*/coordinated?: { snapshot: PageSnapshot | null; owner: SegmentedStagingOwner; sha256: string;+ /** A managed sync rename: `snapshot` is the page at its old slug, which the publication moves here first; an implicit type follows the new path. */+ moved?: boolean;prepare(prepared: StreamedPreparedImport): Promise<ImportResult> };};@@ -265,7 +267,7 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bomprocess.stderr.write(`[import] slug collision: ${relativePath} and ${collisionOwner} both map to ${slug} in source ${sourceId}; keeping ${collisionOwner}. Rename one file to import both.\n`);return { slug, status: 'skipped', chunks: 0, skip_reason: 'slug_collision' };}- if (parsed.typeExplicit !== true && existing) parsed.type = existing.type;+ if (parsed.typeExplicit !== true && existing && !opts.coordinated?.moved) parsed.type = existing.type;resolveParsedSubtype(parsed, existing);const typeClass = parsed.typeExplicit === true && opts.activePack ? classifyStoredType(parsed.type, opts.activePack) : null;const typeWarning = typeClass?.kind === 'alias_of' ? { kind: 'alias_of' as const, type: parsed.type, canonical: typeClass.canonical, directory: typeClass.directory }@@ -315,7 +317,8 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bomreturn opts.coordinated ? opts.coordinated.prepare({ slug, observedRevision: opts.coordinated.snapshot?.revision ?? null, noop: true, result: skipped, frontmatter: parsed.frontmatter,validate: async () => {}, apply: async () => {} }) : skipped;}- const identity = await decideImportIdentity(engine, { sourceId, slug, hash, frontmatterId: null, sourcePath: relativePath, sourceRoot, body: { title: parsed.title, compiled_truth: '', timeline: '' } });+ const identity = opts.coordinated?.moved ? { kind: 'none' as const }+ : await decideImportIdentity(engine, { sourceId, slug, hash, frontmatterId: null, sourcePath: relativePath, sourceRoot, body: { title: parsed.title, compiled_truth: '', timeline: '' } });if (identity.kind === 'shared_hash') process.stderr.write(`[import] WARNING: ${relativePath} shares content_hash with ${identity.dupSlug} in source ${sourceId}. Indexing both.\n`);const nowDate = new Date();const { loadBrainTimeZone } = await import('../import-file.ts');diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex 07272a5493..275a82132a 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -86,7 +86,11 @@ function managedSyncFix(sourceId: string, why: string): Action {return { argv: ['gbrain', 'sync', '--no-pull', '--source', sourceId], consent: [], actor: 'agent', requires_exclusive: false, why,verify: { argv: ['gbrain', 'sources', 'status', sourceId] } };}-export function readSyncFile(root: string, path: string): Buffer | null {+/**+ * The checked absolute path of a sync file: inside its registered root, no symlink component, a regular file of at+ * most `maxBytes`; null when it is gone. Wave B: a streamed import (sync-streamed.ts) passes the page ceiling.+ */+export function syncFilePath(root: string, path: string, maxBytes = SYNC_READ_BOUND): string | null {if (realpathSync(root) !== resolve(root)) throw syncTargetRefusal('source_changed', 'The registered source root was replaced by a symlink.',`The registered root holding ${path} is now a symlink.`);const absolute = resolve(root, path);@@ -102,11 +106,15 @@ export function readSyncFile(root: string, path: string): Buffer | null {}if (!lstatSync(absolute).isFile()) throw syncTargetRefusal('source_changed', 'Sync target is not a regular file.',`${path} is not a regular file.`);- if (lstatSync(absolute).size > SYNC_READ_BOUND) throw opError('request_too_large', 'Sync file exceeds the bounded import size.',+ if (lstatSync(absolute).size > maxBytes) throw opError('request_too_large', 'Sync file exceeds the bounded import size.',`${path} is larger than the ${SYNC_READ_BOUND}-byte (24 MiB) page ceiling, so nothing was imported from it. Pages up to that size are chunked and searchable; above it, add the file to the sync.exclude config (or keep it outside the brain repo), then sync its source again. See docs/guides/memory-boundaries.md#large-pages.`);- return readFileSync(absolute);+ return absolute;} catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }}+export function readSyncFile(root: string, path: string): Buffer | null {+ const absolute = syncFilePath(root, path);+ try { return absolute === null ? null : readFileSync(absolute); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }+}/** Whether a file backs `path` in the working tree; a file that exists but cannot be read as a sync target (a symlink, oversized) still counts as present. */function workingTreeFilePresent(root: string, path: string): boolean {try { return readSyncFile(root, path) !== null; } catch { return true; }diff --git a/src/core/persistence/sync-group.ts b/src/core/persistence/sync-group.tsindex a4a372f90b..d645381616 100644--- a/src/core/persistence/sync-group.ts+++ b/src/core/persistence/sync-group.ts@@ -78,9 +78,9 @@ async function whole(engine: BrainEngine, env: string, key: string, fallback: nureturn Math.floor(raw);}-/** Entries a group may carry: plain page imports and deletes; renames, company plans and the checkpoint stay single. */+/** Entries a group may carry: plain page imports and deletes; renames, company plans, streamed pages (Wave B) and the checkpoint stay single. */export function groupableIntent(intent: SyncIntent): boolean {- return (intent.kind === 'managed_sync_import' || intent.kind === 'managed_sync_delete') && !intent.renameFrom && !intent.companyApproval;+ return (intent.kind === 'managed_sync_import' || intent.kind === 'managed_sync_delete') && !intent.renameFrom && !intent.companyApproval && !intent.body_ref;}/** Apply budgets for a lane group: normally, and while a foreground write on the worktree is queued or just committed. */diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex c5a3988bd4..5ca4be0f88 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -22,6 +22,7 @@ import { sameCanonicalImport } from '../page-state/import-guard.ts';import { assertPageRevision } from '../page-state/types.ts';import { sealImportedPage, sealPageTextProjection } from '../page-state/projections.ts';import { abortSegmentedStaging, materializedSnapshot, sealSegmentedPage } from './segmented-apply.ts';+import { prepareManagedSyncStreamed, type SyncBodyRef } from './sync-streamed.ts';import { fenceBody, withoutBody } from '../page-body/page-shape.ts';import { pipelined, transactionMemo } from '../page-state/transactions.ts';import { prepareCanonicalProjections } from './canonical-projections.ts';@@ -65,6 +66,8 @@ export interface SyncIntent extends Record<string, unknown> {kind: 'managed_sync_import' | 'managed_sync_delete' | 'managed_sync_checkpoint';expected_revision: string | null; sourcePath: string | null; path: string | null;rawHash: string | null; content: string | null; ownerEpoch: string;+ /** Wave B: a Markdown file over the single-string ceiling, frozen by reference (`content` is null); the owner streams it. */+ body_ref?: SyncBodyRef;lineEndingOnly?: boolean;/** #5565: the deleted file is no page's origin; publication only re-proves that and commits a no-op. */unownedDeletion?: boolean;@@ -220,7 +223,8 @@ export function cursorFenceRefusal(row: WriteRequest, p: SyncIntent, cursor: Syn* stays `invalid_params` (what older receipts stored), so the stored code and* message keep matching `isContentRefusal`; `code` is the typed one.*/-function syncContentRefusal(refusal: ContentRefusal, row: WriteRequest, p: SyncIntent): OperationError {+/** `legacy`: the wire `error` stays `invalid_params` for refusals older clients knew by it; a streamed (Wave B) refusal keeps its own code, which the run holds by. */+function syncContentRefusal(refusal: ContentRefusal, row: WriteRequest, p: SyncIntent, legacy = true): OperationError {const where = refusal.line !== undefined ? `line ${refusal.line}${refusal.key ? ` (key "${refusal.key}")` : ''} of ${p.sourcePath}` : p.sourcePath;const cause = refusal.code === 'invalid_fence' ? `Edit ${fenceWhere(refusal.fence)} in ${p.sourcePath} as the message says and commit the change${p.companyApproval ? ' to the repository (a company-brain source never rewrites repository files and never holds a file)' : ''}.`: refusal.code === 'frontmatter_slug_conflict' ? 'Correct the frontmatter `slug:` in the file and commit the change.'@@ -230,7 +234,7 @@ function syncContentRefusal(refusal: ContentRefusal, row: WriteRequest, p: SyncI: refusal.code === 'write_gate_rejected' ? `The write gate refuses ${p.sourcePath}: external instruction-like content under write_gate.external_mode=reject. Tell the user; changing that setting or the file is their decision.`: `Fix ${where} (one line per key, the whole value quoted) and commit the change; gbrain repair frontmatter --source ${row.source_id} previews the exact line fix and writes it only after the preview hash is approved.`;const error = syncPublicationRefusal(refusal.code, refusal.message, row, p, cause, false, {- ...(refusal.code === 'content_rejected' || refusal.code === 'write_gate_rejected' ? {} : { legacy_error: 'invalid_params' }),+ ...(!legacy || refusal.code === 'content_rejected' || refusal.code === 'write_gate_rejected' ? {} : { legacy_error: 'invalid_params' }),...(refusal.reason ? { reason: refusal.reason } : {}),...(refusal.key || refusal.line !== undefined ? { detail: [refusal.key ? `key ${refusal.key}` : '', refusal.line !== undefined ? `line ${refusal.line}` : ''].filter(Boolean).join(', ') } : {}),});@@ -539,7 +543,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr},async () => { if (p.kind !== 'managed_sync_checkpoint') await assertKnowledgePublicationAllowed(tx, row, p.path === null ? undefined : { root, path: join(root, p.path) }); },async () => {- if (p.path !== null && syncRawHash(root, p.path) !== p.rawHash) throw syncPublicationRefusal('source_changed', 'The imported file changed after sync admission.', row, p,+ if (p.path !== null && !p.body_ref && syncRawHash(root, p.path) !== p.rawHash) throw syncPublicationRefusal('source_changed', 'The imported file changed after sync admission.', row, p,`The file of ${row.slug} changed on disk after this sync was admitted; review the change and commit it.`);},async () => {@@ -565,7 +569,8 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrif (p.kind === 'managed_sync_checkpoint') return { sourceExclusive: true, observedRevision: null, validate, apply: tx => applyManagedSyncCheckpoint(tx, row, p, root, releaseHold) };const source = { sourceId: row.source_id };enterClaimStep(clock, 'page_snapshot', undefined, 'db');- const snapshot = await materializedSnapshot(engine, await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true }));+ const read = await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });+ const snapshot = p.body_ref ? read : await materializedSnapshot(engine, read);assertPageRevision(snapshot, { expectedRevision: p.expected_revision }); // null asserts the admitted-absent page is still absent (#5385)const recordedOrigin = moved?.slug === row.slug ? moved.sourcePath : p.sourcePath!;const foreignOrigin = snapshot?.page.source_path != null && !sameSyncOrigin(snapshot.page.source_path, recordedOrigin, originScope, snapshot.page.slug);@@ -586,6 +591,22 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrawait releaseHold(tx);return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop: !snapshot || snapshot.page.deleted_at != null };} };+ // Wave B: a Markdown file over the single-string ceiling (never a company-brain or image entry) streams; its body is never read here.+ if (p.body_ref && typeof p.sourcePath === 'string' && typeof p.path === 'string') {+ enterClaimStep(clock, 'schema_pack', undefined, 'db');+ const pack = p.processingOptions?.noSchemaPack ? undefined : await loadActivePackForEngine(engine, { remote: row.authority.remote, sourceId: row.source_id }).catch(() => null);+ const renamed = moved && moved.slug !== row.slug ? moved : undefined;+ const base = renamed ? await engine.readPageSnapshot(renamed.slug, { ...source, includeDeleted: true }) : snapshot;+ if (renamed && (base?.page.id !== renamed.pageId || base.revision !== renamed.revision || base.page.deleted_at != null)) {+ throw syncPublicationRefusal('revision_conflict', 'The renamed page changed after sync admission.', row, p,+ `Page ${renamed.slug}, which this file was renamed from, changed or was deleted after the sync was admitted.`);+ }+ return prepareManagedSyncStreamed(engine, row, { ...p, body_ref: p.body_ref, sourcePath: p.sourcePath, path: p.path }, { root, snapshot, base, ...(renamed ? { renamed } : {}),+ ...(pack?.manifest ? { activePack: pack.manifest } : {}), validate, releaseHold, clock, screening: !!screening,+ importProvenance: { source_id: row.source_id, incarnation: row.source_incarnation, origin: p.sourcePath, raw_sha256: p.body_ref.sha256,+ ...(p.blobOid ? { blob_oid: p.blobOid } : {}), working: p.working === true, gbrain_version: VERSION, parser: syncImportParser(pack?.identity ?? null) },+ refuse: (code, message, cause) => syncPublicationRefusal(code, message, row, p, cause), contentRefusal: refusal => syncContentRefusal(refusal, row, p, false) });+ }if (typeof p.content !== 'string' || typeof p.sourcePath !== 'string' || typeof p.path !== 'string') throw syncPublicationRefusal('storage_error', 'The frozen import content is missing.', row, p,'The stored intent has no frozen file content to import.');// #6529: an image entry (frozen as base64 bytes) takes the coordinated image importer; its text embedding waits for embed --stale.diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 3e886c07c1..3fe41a56eb 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -21,6 +21,7 @@ import { isImageFilePath, isMultimodalEnabled } from '../sync.ts';import { assertSyncPageOrigin, sameSyncOrigin, syncOriginScope } from './sync-origin.ts';import { assertManagedSyncActive, assertSyncDispatchActive, managedSyncAuthority, validateSyncAuthority, validateManagedSyncOptions, syncProcessingOptions, SYNC_PROCESSING_KEYS, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';import { prepareManagedSyncMutation, type SyncCursorOptions, type SyncIntent } from './sync-prepare.ts';+import { streamedSyncBodyRef, type SyncBodyRef } from './sync-streamed.ts';import { startClaimPhase } from './claim-phase.ts';import { screeningRequest } from './noop-kernel.ts';import { FINISH_BUDGET_MS, stampDrainStep } from './drain-step.ts';@@ -47,7 +48,7 @@ import { laneApplyMsPerMember, lanePolicy, openLanes } from './sync-lanes.ts';import { isContentRefusal } from '../import-screen.ts';import { isRetryableConnError, isStatementTimeoutError } from '../retry-matcher.ts';import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';-import { dryRunScreen, heldImageEntry, isSyncReadBound, loadSyncScreenRun, oversizeHold, pinnedBlob, pinnedContent, pinnedImageBytes, preparationStalledHold, prepareTimeFenceHold, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';+import { dryRunScreen, heldImageEntry, isSyncReadBound, loadSyncScreenRun, oversizeHold, pinnedBlob, pinnedContent, pinnedImageBytes, preparationStalledHold, prepareTimeFenceHold, screenFrozenImport, streamedRefusalHold, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';import { frozenImageIntent, sameImageBytes } from './sync-image.ts';import { fenceReceiptLocation } from '../fence-repair/refusal.ts';import { managedSyncWriteDiagnostic, writeWaitOf } from './sync-write-diagnostic.ts';@@ -343,7 +344,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, asslet frozenSnapshot: PageSnapshot | null | undefined;// #5988: company-profile sources never hold; their approved manifest keeps refusing.const screening = entry?.action === 'import' && !cursor.companyPlan ? run.screen ?? null : null;- let blob: TreeBlob | null = null, oversize: { size: number | null } | undefined;+ let blob: TreeBlob | null = null, oversize: { size: number | null } | undefined, bodyRef: SyncBodyRef | null = null;// #6529: an image entry is frozen as its bytes (base64) for the coordinated image importer when multimodal embedding is on.const image = !!entry && entry.action === 'import' && !cursor.companyPlan && isImageFilePath(entry.path);let imageBytes: Buffer | null = null;@@ -366,13 +367,23 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass}let bytes: Buffer | null = null;try { bytes = readSyncFile(cursor.root, entry.path); }- catch (error) { if (!screening || !isSyncReadBound(error)) throw error; oversize = { size: null }; }- if ((screening || image) && !entry.working) {+ catch (error) {+ if (!isSyncReadBound(error)) throw error;+ // Wave B: with segmented storage on, a Markdown file over the read bound is frozen by reference and streamed by its owner.+ if (entry.action === 'import' && !cursor.companyPlan && !image) {+ bodyRef = await streamedSyncBodyRef(engine, { root: cursor.root, path: entry.path, target: cursor.target, working: entry.working,+ blob: () => (blob = pinnedBlob(cursor, entry.path)) });+ assertActive();+ }+ if (!bodyRef && !screening) throw error;+ if (!bodyRef) oversize = { size: null };+ }+ if ((screening || image) && !entry.working && !bodyRef) {// #5988: an over-bound pinned blob is held by its size before its content is loaded.blob = pinnedBlob(cursor, entry.path);if (blob && blob.size > SYNC_READ_BOUND) oversize = { size: blob.size };}- rawHash = bytes === null ? null : sha256(bytes);+ rawHash = bodyRef ? bodyRef.sha256 : bytes === null ? null : sha256(bytes);if (image && oversize) return { hold: oversizeHold(entry, entry.slug!, entry.pageId ?? null, oversize.size, blob) };if (image) imageBytes = pinnedImageBytes(cursor, entry);if (entry.action === 'import' && cursor.companyPlan) {@@ -383,7 +394,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass`Source ${cursor.sourceId}'s approved company-brain content manifest no longer includes ${entry.path} for this run (its approval changed, or the file is no longer an included path), so nothing was imported for it. If the approval changed, inspect and approve the repository again first (gbrain sources inspect --help).`);content = (await readCommittedBlob(cursor.companyPlan.revision!, blob, cursor.companyPlan.limits)).toString('utf8');assertActive();- } else content = imageBytes ? frozenImageIntent(imageBytes).content : entry.action === 'import' && !oversize ? pinnedContent(cursor, entry) : null;+ } else content = imageBytes ? frozenImageIntent(imageBytes).content : entry.action === 'import' && !oversize && !bodyRef ? pinnedContent(cursor, entry) : null;// #6340: working-tree bytes that differ from the pinned blob but are committed at HEAD (a commit past the pin on a// live checkout) are imported as HEAD has them; the pin..HEAD diff later re-imports the same bytes as a no-op.// Uncommitted bytes keep the pinned content and reach the publication screen (idea from PR #6323).@@ -439,7 +450,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass}}if (screening && !image) {- const hold = await screenFrozenImport(engine, { cursor, entry, slug, pageId, snapshot, content, rawHash, lineEndingOnly, blob, oversize,+ const hold = await screenFrozenImport(engine, { cursor, entry, slug, pageId, snapshot, content, rawHash, lineEndingOnly, blob, oversize, streamed: !!bodyRef,retryCommand: checkpointRetryCommand(retry) }, screening);assertActive();if (hold) return { hold };@@ -449,7 +460,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, assassertActive();if (entry?.action === 'import') await faultPoint('sync:after_freeze', { sourceId: cursor.sourceId, slug, path: entry.path });return remember(frozenSnapshot, { requestId: randomUUID(), slug, pageId, ...(occupantRebound ? { rebound: true as const } : {}), intent: { kind: !entry ? 'managed_sync_checkpoint' : entry.action === 'import' ? 'managed_sync_import' : 'managed_sync_delete',- expected_revision: revision, sourcePath: entry?.sourcePath ?? null, path: entry?.path ?? null, rawHash, content, lineEndingOnly,+ expected_revision: revision, sourcePath: entry?.sourcePath ?? null, path: entry?.path ?? null, rawHash, content, lineEndingOnly, ...(bodyRef ? { body_ref: bodyRef } : {}),...(entry?.unownedDeletion ? { unownedDeletion: true } : {}),...(entry?.renameFrom ? { renameFrom: entry.renameFrom } : {}),...(run.observedAt ? { holdObservedAt: run.observedAt } : {}), ...(blob ? { blobOid: blob.oid } : {}), ...(entry && run.embedDeferred ? { embedDeferred: true } : {}),@@ -711,7 +722,7 @@ async function holdFailedFenceRequest(engine: BrainEngine, cursor: Cursor, key:const entry = cursor.entries[cursor.index];if (!entry || entry.path !== pending.intent.path) return null;const stalled = preparationStalled(done);- const page = pending.intent.kind === 'managed_sync_import' && typeof pending.intent.content === 'string';+ const page = pending.intent.kind === 'managed_sync_import' && (typeof pending.intent.content === 'string' || !!pending.intent.body_ref);if (!stalled && !page && pending.intent.kind !== 'managed_sync_delete') return null;let base: Cursor | undefined;if (stalled) {@@ -736,9 +747,12 @@ async function holdFailedFenceRequest(engine: BrainEngine, cursor: Cursor, key:if (pending.converted) return holdUnderGate(engine, { cursor, key, pending, hold: worktreeDirtyHold(entry, pending.slug, pending.pageId, { ...pending.intent, rawHash: refrozen.intent.rawHash }), assertActive, observedAt: run.observedAt!, waitMs, failedId: done.id, base });return holdUnderGate(engine, { cursor, key, pending, refrozen, assertActive, observedAt: run.observedAt!, waitMs, failedId: done.id, base });}- if (!stalled && !fence && !fault) return null;+ // Wave B: a file the streamed preparation refuses (a fence, a frontmatter problem) is held with the refusal's code.+ const streamed = !stalled && !fence && !fault && pending.intent.body_ref && isContentRefusal(done.error_code, null)+ ? streamedRefusalHold(entry, pending.slug, pending.pageId, done, pending.intent.blobOid) : null;+ if (!stalled && !fence && !fault && !streamed) return null;const hold = stalled ? preparationStalledHold(entry, pending.slug, pending.pageId, done, pending.intent.content ?? null, pending.intent.blobOid, resumeArgsOf(cursor, run))- : fence ? prepareTimeFenceHold(entry, pending.slug, pending.pageId, fence, pending.intent.content!, pending.intent.blobOid) : fault!;+ : fence ? prepareTimeFenceHold(entry, pending.slug, pending.pageId, fence, pending.intent.content!, pending.intent.blobOid) : fault ?? streamed!;return holdUnderGate(engine, { cursor, key, pending, hold, assertActive, observedAt: run.observedAt!, waitMs, failedId: done.id, base });}diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.tsindex 6b0a4c5c21..ac8500ddcf 100644--- a/src/core/persistence/sync-screen.ts+++ b/src/core/persistence/sync-screen.ts@@ -11,11 +11,11 @@* normalized file; a dry run lists it in `would_normalize`), and a residual* fence is held as `invalid_fence`.*/-import { realpathSync } from 'node:fs';-import { relative, resolve, sep } from 'node:path';+import { realpathSync, statSync } from 'node:fs';+import { join, relative, resolve, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';import { OperationError, opError } from '../ops/contract.ts';-import { loadImportSanityConfig, screenNormalized, type ImportSanityConfig, type ImportScreenResult } from '../import-screen.ts';+import { loadImportSanityConfig, screenNormalized, type ContentRefusal, type ImportSanityConfig, type ImportScreenResult } from '../import-screen.ts';import { fencesNormalizeEnabled } from '../fence-repair/config.ts';import type { FenceFix } from '../fence-repair/types.ts';import { parseMarkdown, RECOVERY_VERSION } from '../markdown.ts';@@ -27,6 +27,7 @@ import { isImageFilePath, isMultimodalEnabled, resolveSlugForPath } from '../synimport { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';import { VERSION } from '../../version.ts';import { sha256 } from './digest.ts';+import { readPageBodyPolicy, type PageBodyPolicy } from '../page-body/limits.ts';import { readPagePurgeTombstones } from './page-purge.ts';import { readSyncContent, readSyncFile, syncGitPath, type SyncDiscovery, type SyncEntry } from './sync-discovery.ts';import { PINNED_WINDOW, readBlobBytes, readBlobContents, readPinnedBlob, readPinnedBytes, readPinnedContent, readTreeBlobs, SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';@@ -175,6 +176,13 @@ export function managedImageHold(entry: Pick<SyncEntry, 'path' | 'sourcePath' |}/** #5988: the hold of a file over the sync read bound, whose content is never read (#6529: shared with the image freeze). */+/** Wave B: the hold for a file its streamed preparation refused, by the receipt's content-refusal code and message. */+export function streamedRefusalHold(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld'>, slug: string, pageId: number | null,+ done: Pick<WriteRequest, 'error_code' | 'error_message'>, blobOid: string | null | undefined): HeldEntry {+ return heldEntry(entry, slug, pageId, { code: done.error_code as ContentRefusal['code'], message: done.error_message ?? 'The streamed import refused this file.' },+ null, blobOid ? { oid: blobOid } : null);+}+export function oversizeHold(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld'>, slug: string, pageId: number | null, size: number | null, blob: TreeBlob | null | undefined): HeldEntry {return heldEntry(entry, slug, pageId, { code: 'file_too_large',message: `File too large (${size ?? `over ${SYNC_READ_BOUND}`} bytes; the sync read bound is the ${SYNC_READ_BOUND}-byte (24 MiB) page ceiling). Pages up to the ceiling are chunked and searchable; leave this file out of the source (sync.exclude) or keep it outside the brain repo. See docs/guides/memory-boundaries.md#large-pages.` }, null, blob);@@ -194,6 +202,8 @@ export interface FrozenImportScreen {/** null only for an over-size file, whose content is never read. */content: string | null; rawHash: string | null; lineEndingOnly: boolean;blob?: TreeBlob | null; oversize?: { size: number | null };+ /** Wave B: frozen by reference (`content` is null); its owner's streamed preparation screens it, and a refusal there is held. */+ streamed?: boolean;/** The `--retry-failed` command that resumes after a parser-regression fix. */retryCommand: string;/** #6188 dry run: told the fixes when Tier 1 admits the file by rewriting a fence. */@@ -228,10 +238,11 @@ export async function screenFrozenContent(screenInput: SyncImportScreenInput, ru*/export async function screenFrozenImport(engine: BrainEngine, input: FrozenImportScreen, run: SyncScreenRun): Promise<HeldEntry | null> {const { entry, slug, pageId, snapshot, content, blob } = input;- if (input.oversize || content === null) return oversizeHold(entry, slug, pageId, input.oversize?.size ?? blob?.size ?? null, blob);+ if (input.oversize || (content === null && !input.streamed)) return oversizeHold(entry, slug, pageId, input.oversize?.size ?? blob?.size ?? null, blob);if (entry.renameHeld) {return heldEntry(entry, slug, pageId, { code: 'rename_held', reason: 'rename_source_changed', message: `${entry.path} is a rename of page ${entry.renameHeld.slug}, which changed after the rename was recorded, so the page was not moved.` }, content, blob);}+ if (content === null) return null;// #6188: a fence Tier 1 rewrites is admitted (publication writes the normalized file back); with fences.normalize=false it is held.const screen = await screenFrozenContent(await frozenImportScreenInput(engine, { ...input, content }, run), run);if (screen.status === 'importable' && screen.fences?.fixes.length) input.onNormalized?.(screen.fences.fixes);@@ -270,6 +281,7 @@ export async function dryRunScreen(engine: BrainEngine, discovery: SyncDiscoveryconst held: GitHoldItem[] = [];const normalized: Array<{ path: string; classes: string[] }> = [];const skipped: Array<{ path: string; code: string }> = [];+ let policy: PageBodyPolicy | undefined;const observed = new Date().toISOString();for (const entry of entries) {try {@@ -286,6 +298,9 @@ export async function dryRunScreen(engine: BrainEngine, discovery: SyncDiscoverylet bytes: Buffer | null = null, oversize: { size: number | null } | undefined;try { bytes = readSyncFile(discovery.root, entry.path); } catch (error) { if (!isSyncReadBound(error)) throw error; oversize = { size: null }; }if (blob && blob.size > SYNC_READ_BOUND) oversize = { size: blob.size };+ // Wave B: a Markdown file the real run streams (sync-streamed.ts) is screened only by its owner's preparation.+ if (oversize && /\.mdx?$/i.test(entry.path) && (policy ??= await readPageBodyPolicy(engine)).segmented+ && (oversize.size ?? statSync(join(discovery.root, entry.path)).size) <= policy.maxBytes) { skipped.push({ path: entry.path, code: 'page_body_segmented' }); continue; }const content = oversize ? null : entry.working ? bytes?.toString('utf8') ?? null : blob ? contents.get(blob.oid) ?? null : null;if (!oversize && content === null) { skipped.push({ path: entry.path, code: 'source_changed' }); continue; }const snapshot = await engine.readPageSnapshot(entry.slug!, { sourceId: discovery.sourceId, includeDeleted: true });diff --git a/src/core/persistence/sync-streamed.ts b/src/core/persistence/sync-streamed.tsnew file mode 100644index 0000000000..c3c29f8efb--- /dev/null+++ b/src/core/persistence/sync-streamed.ts@@ -0,0 +1,142 @@+/**+ * Wave B: managed sync of a Markdown file over the single-string ceiling+ * (spec 3.1, 3.2). With `pages.segmented_storage` on, `freezeEntry`+ * (`sync-run.ts`) freezes such a file by reference (`body_ref`: its sha256,+ * size and Git blob id, hashed as a stream; no content in the journal) instead+ * of holding it by its size. A committed entry streams only when the working+ * tree holds exactly its pinned blob; otherwise it is held as before. The+ * owner's preparation streams the file through the segmented import+ * (`importStreamedMarkdownFile`), which verifies the sha256 on its first pass,+ * and the publication is database-only (the canonical file is never+ * rewritten). A file the streamed path refuses fails its request with the+ * refusal's code, and the run holds it (`holdFailedFenceRequest`). A rename+ * moves the page in the publication and applies the preparation made at the+ * new path.+ */+import { createReadStream } from 'node:fs';+import { lstat } from 'node:fs/promises';+import { createHash } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import { OperationError } from '../ops/contract.ts';+import type { RegistryCode } from '../error-registry.ts';+import type { ContentRefusal } from '../import-screen.ts';+import type { PageSnapshot } from '../page-state/types.ts';+import { sizeStateField } from '../page-embedding-budget.ts';+import { readPageBodyPolicy } from '../page-body/limits.ts';+import { importStreamedMarkdownFile, type StreamedPreparedImport } from '../page-body/streamed-import.ts';+import { ownerImportTrust } from '../trust/channel.ts';+import { pipelined } from '../page-state/transactions.ts';+import { sealSegmentedPage } from './segmented-apply.ts';+import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';+import { syncFilePath, type SyncRename } from './sync-discovery.ts';+import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';+import { recordSyncImportProvenance, type SyncImportProvenanceBase } from './sync-holds.ts';+import type { WriteRequest } from './model.ts';+import type { SyncIntent, SyncPreparedMutation } from './sync-prepare.ts';++/** A frozen Markdown file over the single-string ceiling: the bytes the owner streams and verifies. */+export interface SyncBodyRef { kind: 'git_blob' | 'input_file'; sha256: string; bytes: number; blob_oid: string }++/**+ * The reference a Markdown import over the sync read bound is frozen by, or+ * null when it is held by its size as before: the switch is off, the file is+ * over `pages.max_bytes`, or (a committed entry) the working tree does not hold+ * the pinned blob. `target` is the pinned commit id (its length names the+ * object format).+ */+export async function streamedSyncBodyRef(engine: BrainEngine, input: { root: string; path: string; target: string; working: boolean; blob: () => TreeBlob | null }): Promise<SyncBodyRef | null> {+ if (!/\.mdx?$/i.test(input.path)) return null;+ const policy = await readPageBodyPolicy(engine);+ if (!policy.segmented) return null;+ let absolute: string | null;+ try { absolute = syncFilePath(input.root, input.path, policy.maxBytes); }+ catch (error) { if (error instanceof OperationError && error.code === 'request_too_large') return null; throw error; }+ if (absolute === null) return null;+ const bytes = (await lstat(absolute)).size;+ const blob = input.working ? null : input.blob();+ if (bytes <= SYNC_READ_BOUND || (!input.working && blob?.size !== bytes)) return null;+ const sha256 = createHash('sha256'), oid = createHash(input.target.length === 64 ? 'sha256' : 'sha1').update(`blob ${bytes}\0`);+ let read = 0;+ for await (const part of createReadStream(absolute) as AsyncIterable<Buffer>) { sha256.update(part); oid.update(part); read += part.length; }+ const ref: SyncBodyRef = { kind: input.working ? 'input_file' : 'git_blob', sha256: sha256.digest('hex'), bytes, blob_oid: oid.digest('hex') };+ return read === bytes && (input.working || ref.blob_oid === blob?.oid) ? ref : null;+}++export interface StreamedSyncContext {+ root: string;+ /** The page at the admitted slug, and the page the import is prepared against (the rename source for a rename). */+ snapshot: PageSnapshot | null; base: PageSnapshot | null;+ renamed?: SyncRename;+ activePack?: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string> }> };+ importProvenance: SyncImportProvenanceBase;+ validate: (tx: BrainEngine) => Promise<void>;+ releaseHold: (tx: BrainEngine) => Promise<void>;+ refuse: (code: RegistryCode, message: string, cause: string) => OperationError;+ contentRefusal: (refusal: ContentRefusal) => OperationError;+ clock?: ClaimPhaseClock;+ screening?: boolean;+}++const CHANGED = 'The imported file changed after sync admission.';++export async function prepareManagedSyncStreamed(engine: BrainEngine, row: WriteRequest, p: SyncIntent & { body_ref: SyncBodyRef; sourcePath: string; path: string },+ ctx: StreamedSyncContext): Promise<SyncPreparedMutation> {+ const { refuse, snapshot, base, renamed } = ctx;+ const ref = p.body_ref;+ const changed = () => refuse('source_changed', CHANGED, `The file of ${row.slug} changed on disk after this sync was admitted; review the change and commit it.`);+ // A screen without admission (an origin occupant, a waiver) never streams a page this size.+ if (ctx.screening) throw refuse('invalid_params', 'A streamed import is prepared only under its admitted request.',+ `${p.sourcePath} is over the single-string ceiling, so it is prepared only under its admitted request.`);+ const policy = await readPageBodyPolicy(engine);+ if (!policy.segmented || ref.bytes > policy.maxBytes) throw ctx.contentRefusal({ code: 'file_too_large',+ message: `File too large (${ref.bytes} bytes): segmented page storage (pages.segmented_storage) is off or the file is over pages.max_bytes (${policy.maxBytes}).` });+ const filePath = syncFilePath(ctx.root, p.path, policy.maxBytes);+ const stat = filePath === null ? null : await lstat(filePath);+ if (!filePath || !stat || stat.size !== ref.bytes) throw changed();+ let ready: StreamedPreparedImport | undefined;+ enterClaimStep(ctx.clock, 'import_content', undefined, 'fs');+ const result = await importStreamedMarkdownFile(engine, filePath, p.sourcePath, { sourceId: row.source_id, noEmbed: true, ...(ctx.activePack ? { activePack: ctx.activePack } : {}),+ coordinated: { snapshot: base, sha256: ref.sha256, moved: !!renamed, prepare: async value => { ready = value; return value.result; },+ owner: { kind: 'sync', principalKind: row.principal_kind, principalId: row.principal_id, baseRevision: base?.revision ?? null } } }, stat, policy)+ .catch(error => { throw error instanceof OperationError && error.code === 'source_changed' ? changed() : error; });+ if (!ready) throw result.refusal ? ctx.contentRefusal(result.refusal) : refuse('invalid_params', result.error ?? 'The sync file could not be prepared.',+ `The file could not be prepared as page ${row.slug}.`);+ const prepared: StreamedPreparedImport = ready;+ if (prepared.slug !== row.slug) throw refuse('revision_conflict', 'A different page already owns this file identity; resolve the duplicate before syncing.',+ `Page ${prepared.slug} already holds the content identity of ${row.slug}; resolve the duplicate pages first.`);+ if (prepared.observedRevision !== (base?.revision ?? null)) throw refuse('revision_conflict', 'The page changed during sync preparation.',+ `Page ${renamed?.slug ?? row.slug} changed while this sync was being prepared.`);+ const source = { sourceId: row.source_id };+ const mutation: SyncPreparedMutation = { observedRevision: snapshot?.revision ?? null, importProvenance: ctx.importProvenance,+ trust: await ownerImportTrust(engine, row, prepared.frontmatter, p.sourcePath),+ contentUnchanged: prepared.noop && !renamed,+ ...(renamed ? { additionalPageKeys: [{ sourceId: row.source_id, slug: renamed.slug }] } : {}),+ validate: async tx => {+ await ctx.validate(tx);+ await prepared.validate(tx).catch(error => { throw error instanceof OperationError && error.code === 'source_changed' ? changed() : error; });+ },+ deferEmbedding: p.processingOptions?.noEmbed || p.embedDeferred === true,+ ...(prepared.afterCommit ? { afterCommit: prepared.afterCommit } : {}),+ apply: async tx => {+ // The page moves first, keeping its id, links and history; the import prepared at the new path then applies to it.+ if (renamed && await tx.updateSlug(renamed.slug, row.slug, source) !== 1) throw refuse('page_identity_changed', 'The renamed page could not move to its new slug.',+ `Page ${renamed.slug} could not move to ${row.slug}.`);+ await prepared.apply(tx);+ // An unchanged body keeps its chunks (the no-op required a sealed page), so the move's new revision is sealed here.+ if (renamed && prepared.noop) await sealSegmentedPage(tx, renamed.pageId);+ await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);+ await tx.executeRaw("UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND database_only_reason='unbound_source'", [row.source_id, row.slug]);+ const final = await tx.readPageSnapshot(row.slug, { ...source, includeDeleted: true });+ await pipelined(tx, [+ () => ctx.releaseHold(tx),+ async () => { if (final) await recordSyncImportProvenance(tx, { ...ctx.importProvenance, page_id: Number(final.page.id), revision: final.revision,+ disk_sha256: ref.sha256, disk_blob_oid: ref.blob_oid }); },+ ]);+ mutation.postimage = final;+ const live = final && final.page.deleted_at == null ? final.page : null;+ return { status: renamed ? 'renamed' : prepared.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,+ chunks: prepared.result.chunks, noop: prepared.noop && !renamed, imported_file: true, ...(renamed ? { renamed_from: renamed.slug } : {}),+ ...(prepared.noop ? {} : await sizeStateField(tx, row.source_id, row.slug, live)) };+ } };+ return mutation;+}diff --git a/test/large-pages/managed-sync-streamed-crash.test.ts b/test/large-pages/managed-sync-streamed-crash.test.tsnew file mode 100644index 0000000000..93ead4ccae--- /dev/null+++ b/test/large-pages/managed-sync-streamed-crash.test.ts@@ -0,0 +1,105 @@+/**+ * Wave B: the crash window of a managed sync that streams a page over the+ * single-string ceiling (spec 3.2, 3.3).+ *+ * 1. Protects: an owner killed between its preparation and the publication+ * (`consumer:prepared`, SIGKILL in a child process) leaves the request+ * running with a reference-only intent and its staging prepared; once the+ * dead claim lapses, the next run's owner prepares the request again from+ * its `body_ref` (re-streaming and re-verifying the file) and publishes the+ * page byte-identical, and segment GC collects the dead staging.+ * 2. Fails when: the journal needs the body to re-prepare, the dead staging+ * blocks the re-preparation, or GC keeps it.+ * Seams: test/fixtures/convergence-fault-kill.ts preloaded into the child (the+ * persistence gate's fault hook); no mocks.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync, spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { parseMarkdown } from '../../src/core/markdown.ts';+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';+import { BODY_STAGING_HARD_MS } from '../../src/core/page-body/limits.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { performManagedSync } from '../../src/core/persistence/sync-run.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { withEnv } from '../helpers/with-env.ts';+import { conversationPage } from '../helpers/conversation-page.ts';+import { reconstructedPage } from '../helpers/segmented-page-checks.ts';++const REPO = resolve(import.meta.dir, '../..');+const home = mkdtempSync(join(tmpdir(), 'gbrain-sync-streamed-crash-'));+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+const huge = conversationPage(PAGE_MAX_BYTES + 1024 * 1024, { seed: 72 });+const sourceId = `streamed-crash-${randomUUID().slice(0, 8)}`;+const brain = join(home, 'brain');+const root = join(home, sourceId);+const marker = join(home, 'fault.marker');+const CHILD = `+import { createEngine } from ${JSON.stringify(join(REPO, 'src/core/engine-factory.ts'))};+import { performManagedSync } from ${JSON.stringify(join(REPO, 'src/core/persistence/sync-run.ts'))};+const [brain, sourceId] = process.argv.slice(-2);+const engine = await createEngine({ engine: 'pglite', database_path: brain });+await engine.connect({ engine: 'pglite', database_path: brain });+for (let pass = 0; pass < 30; pass++) await performManagedSync(engine, { sourceId, noPull: true, noEmbed: true });+`;+let engine: PGLiteEngine;+let child: ReturnType<typeof spawnSync>;++function git(...args: string[]): void { execFileSync('git', ['-C', root, ...args], { stdio: ['ignore', 'pipe', 'pipe'] }); }++beforeAll(async () => withEnv(env, async () => {+ const setup = new PGLiteEngine(); await setup.connect({ database_path: brain }); await setup.initSchema();+ await setup.setConfig('pages.segmented_storage', 'on');+ mkdirSync(join(root, 'notes'), { recursive: true });+ writeFileSync(join(root, 'notes/huge.md'), huge);+ git('init', '-q'); git('add', '-A'); git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'huge');+ await setup.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await setup.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);+ await claimWorktree(setup, sourceId, root);+ await setup.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await disposePersistenceConsumer(setup); await setup.disconnect();+ child = spawnSync(process.execPath, ['--no-env-file', '--preload', join(REPO, 'test/fixtures/convergence-fault-kill.ts'), '-e', CHILD, brain, sourceId],+ { cwd: REPO, encoding: 'utf8', timeout: 300_000,+ env: { ...process.env, GBRAIN_HOME: home, OPENAI_API_KEY: '', VOYAGE_API_KEY: '', ANTHROPIC_API_KEY: '',+ GBRAIN_TEST_CONVERGENCE_FAULT: JSON.stringify({ point: 'consumer:prepared', nth: 1, marker, operation: 'submit_job' }) } });+ engine = new PGLiteEngine(); await engine.connect({ database_path: brain });+}), 600_000);++afterAll(async () => {+ await withEnv(env, async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });+ rmSync(home, { recursive: true, force: true });+});++test('an owner killed between preparation and publication: the next run re-prepares from the reference and publishes', async () => withEnv(env, async () => {+ expect(child.signal).toBe('SIGKILL');+ expect(JSON.parse(readFileSync(marker, 'utf8'))).toMatchObject({ point: 'consumer:prepared', operation: 'submit_job' });+ const [running] = await engine.executeRaw<{ state: string; intent: Record<string, unknown> }>(+ "SELECT state, intent FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import'", [sourceId]);+ expect(running!.state).toBe('running');+ expect(running!.intent.content).toBeNull();+ expect(running!.intent.body_ref).toMatchObject({ kind: 'git_blob', bytes: Buffer.byteLength(huge) });+ const dead = await engine.executeRaw<{ id: string }>("SELECT id::text AS id FROM page_body_stagings WHERE source_id=$1 AND state='prepared'", [sourceId]);+ expect(dead.length).toBe(1);++ // The dead owner's claim lapses, as its lease would; the next run's owner reclaims the request and prepares it again.+ await engine.executeRaw("UPDATE persistence_requests SET claim_expires_at=now()-interval '1 second' WHERE source_id=$1 AND state='running'", [sourceId]);+ let result = await performManagedSync(engine, { sourceId, noPull: true, noEmbed: true });+ for (let pass = 0; result.status === 'partial' && pass < 30; pass++) result = await performManagedSync(engine, { sourceId, noPull: true, noEmbed: true });+ expect(result.status).toBe('first_sync');+ const { page, body, hash } = await reconstructedPage(engine, 'notes/huge', sourceId);+ expect(page.body_storage).toBe('segmented');+ expect(body.compiled_truth).toBe(parseMarkdown(huge, 'notes/huge.md').compiled_truth);+ expect(page.content_hash).toBe(hash);+ expect(page.text_projection_revision).toBe(page.knowledge_revision);+ const states = await engine.executeRaw<{ state: string }>("SELECT state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import'", [sourceId]);+ expect(states.map(row => row.state)).toEqual(['committed']);++ await engine.sweepSegments({ sourceId, expireStagings: true, now: new Date(Date.now() + BODY_STAGING_HARD_MS + 60_000) });+ expect((await engine.executeRaw<{ state: string }>('SELECT state FROM page_body_stagings WHERE id=$1::uuid', [dead[0]!.id]))[0]?.state).not.toBe('prepared');+ expect(await engine.executeRaw('SELECT 1 FROM page_body_manifest WHERE page_id=$1 AND staging_id IS NOT NULL', [page.id])).toEqual([]);+ expect((await reconstructedPage(engine, 'notes/huge', sourceId)).body).toEqual(body);+}), 600_000);diff --git a/test/large-pages/managed-sync-streamed-memory.slow.test.ts b/test/large-pages/managed-sync-streamed-memory.slow.test.tsnew file mode 100644index 0000000000..2f4669a2e4--- /dev/null+++ b/test/large-pages/managed-sync-streamed-memory.slow.test.ts@@ -0,0 +1,79 @@+/**+ * Wave B (spec 3.1): managed sync of a page over the single-string ceiling+ * streams it, so its memory does not follow the page.+ *+ * Protects: `performManagedSync` of a committed 32 MiB conversation page on+ * PGLite (frozen by reference, streamed by its owner in the same process), in+ * a fresh child process, peaks (VmHWM, reset after setup) under 450 MiB above+ * the same child syncing a 1 MiB page (the single-string path), as the+ * streamed import does (segmented-ingest-memory.slow.test.ts).+ * Fails when: the freeze or the preparation reads the file as one buffer or+ * string (the journal, the screen, the pinned-blob window), or the page is+ * held instead of published.+ * Seams: a child process per sync (VmHWM is per process); no mocks.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { execFileSync, spawnSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { conversationPage } from '../helpers/conversation-page.ts';++const REPO = resolve(import.meta.dir, '../..');+const PEAK_DELTA_LIMIT_MIB = 450;+const dir = mkdtempSync(join(tmpdir(), 'managed-sync-streamed-memory-'));+afterAll(() => rmSync(dir, { recursive: true, force: true }));++const CHILD = `+import { readFileSync, writeFileSync } from 'node:fs';+import { createEngine } from ${JSON.stringify(join(REPO, 'src/core/engine-factory.ts'))};+import { claimWorktree } from ${JSON.stringify(join(REPO, 'src/core/persistence/ownership.ts'))};+import { performManagedSync } from ${JSON.stringify(join(REPO, 'src/core/persistence/sync-run.ts'))};+import { disposePersistenceConsumer } from ${JSON.stringify(join(REPO, 'src/core/persistence/service.ts'))};+const [root, brain] = process.argv.slice(-2);+const engine = await createEngine({ engine: 'pglite', database_path: brain });+await engine.connect({ engine: 'pglite', database_path: brain });+await engine.initSchema();+await engine.setConfig('pages.segmented_storage', 'on');+await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES('memory','memory',$1,'{}')", [root]);+await claimWorktree(engine, 'memory', root);+await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+Bun.gc(true);+writeFileSync('/proc/self/clear_refs', '5');+let result;+for (let pass = 0; pass < 30; pass++) {+ result = await performManagedSync(engine, { sourceId: 'memory', noPull: true, noEmbed: true });+ if (result.status !== 'partial') break;+}+const peak = Number(/^VmHWM:\\s+(\\d+) kB$/m.exec(readFileSync('/proc/self/status', 'utf8'))[1]) / 1024;+const [page] = await engine.executeRaw("SELECT body_storage FROM pages WHERE source_id='memory' AND slug='notes/memory-example'");+await disposePersistenceConsumer(engine);+await engine.disconnect();+console.log(JSON.stringify({ status: result.status, storage: page?.body_storage ?? null, peak }));+`;++function syncInChild(mib: number): { status: string; storage: string | null; peak: number } {+ const root = join(dir, `repo-${mib}`);+ mkdirSync(join(root, 'notes'), { recursive: true });+ writeFileSync(join(root, 'notes/memory-example.md'), conversationPage(mib * 2 ** 20, { seed: 1 }));+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { stdio: ['ignore', 'pipe', 'pipe'] });+ git('init', '-q'); git('add', '-A'); git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'memory');+ const run = spawnSync(process.execPath, ['--no-env-file', '-e', CHILD, root, join(dir, `brain-${mib}`)],+ { cwd: REPO, encoding: 'utf8', timeout: 300_000, maxBuffer: 1 << 22,+ env: { ...process.env, GBRAIN_HOME: join(dir, `home-${mib}`), OPENAI_API_KEY: '', VOYAGE_API_KEY: '', ANTHROPIC_API_KEY: '' } });+ const line = run.stdout.trim().split('\n').pop() ?? '';+ if (run.status !== 0 || !line.startsWith('{')) throw new Error(`child sync of ${mib} MiB failed (${run.status}):\n${run.stderr.slice(-2000)}`);+ return JSON.parse(line);+}++describe.skipIf(!existsSync('/proc/self/status'))('managed sync streamed memory', () => {+ test(`a 32 MiB page syncs segmented and peaks under ${PEAK_DELTA_LIMIT_MIB} MiB above a 1 MiB one`, () => {+ const small = syncInChild(1);+ const large = syncInChild(32);+ expect(small.status).toBe('first_sync');+ expect(large).toMatchObject({ status: 'first_sync', storage: 'segmented' });+ process.stderr.write(`managed sync peak: 1 MiB ${small.peak.toFixed(0)} MiB, 32 MiB ${large.peak.toFixed(0)} MiB\n`);+ expect(large.peak - small.peak).toBeLessThan(PEAK_DELTA_LIMIT_MIB);+ }, 600_000);+});diff --git a/test/large-pages/managed-sync-streamed.test.ts b/test/large-pages/managed-sync-streamed.test.tsnew file mode 100644index 0000000000..191e2c3a6f--- /dev/null+++ b/test/large-pages/managed-sync-streamed.test.ts@@ -0,0 +1,204 @@+/**+ * Wave B managed sync of a Markdown file over the single-string ceiling.+ *+ * 1. Protects: with `pages.segmented_storage` on, `performManagedSync` freezes+ * a committed file over PAGE_MAX_BYTES by reference (`body_ref`: its+ * sha256, size and pinned blob; no content in the journal) and its owner+ * streams it into a segmented page that round-trips byte-identical, with+ * the canonical file untouched; on a source at a repository subdirectory+ * (git-root slugs), on an edit, on a full walk and on a rename. A file the+ * streamed path refuses (a facts fence) is held `file_too_large` and the+ * run checkpoints, as before. A dry run lists the file as screened only by+ * its owner (`page_body_segmented`), not as a hold. With the switch off the+ * hold is unchanged. The crash window: managed-sync-streamed-crash.test.ts.+ * 2. Fails when: managed sync holds such a file, the journal carries its body,+ * a rename leaves the page at its old slug, or a streamed refusal blocks+ * the run instead of holding the file.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { parseMarkdown } from '../../src/core/markdown.ts';+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { performManagedSync } from '../../src/core/persistence/sync-run.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { readGitSourceHolds } from '../../src/core/persistence/sync-holds.ts';+import { sha256 } from '../../src/core/persistence/digest.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { withEnv } from '../helpers/with-env.ts';+import { conversationPage } from '../helpers/conversation-page.ts';+import { reconstructedPage } from '../helpers/segmented-page-checks.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-sync-streamed-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+const huge = conversationPage(PAGE_MAX_BYTES + 1024 * 1024, { seed: 71 });++function git(root: string, ...args: string[]): string { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }+function commit(root: string): void { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'test content'); }++beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);++afterAll(async () => {+ await withEnv(env, async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.();+ });+ rmSync(home, { recursive: true, force: true });+});++/** A managed source over a Git repository; `scope` puts the source at a subdirectory of it, pinned to git-root slugs (origins include the scope). */+async function fixture(engine: BrainEngine, files: Record<string, string>, scope = '') {+ await disposePersistenceConsumer(engine);+ const sourceId = `streamed-sync-${randomUUID().slice(0, 8)}`;+ const repo = join(home, sourceId), root = join(repo, scope);+ mkdirSync(join(root, 'notes'), { recursive: true });+ git(repo, 'init', '-q');+ for (const [path, body] of Object.entries(files)) writeFileSync(join(root, path), body);+ commit(repo);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [sourceId, root, JSON.stringify(scope ? { slug_root_mode: 'git-root' } : {})]);+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return { sourceId, repo, root };+}++/** One managed sync to a settled result: a streamed page outlasts a pass's bounded wait (`partial` / `writer_pending`), as the drain's next pass picks it up. */+async function sync(engine: BrainEngine, opts: { sourceId: string; full?: boolean; workingTree?: boolean }) {+ for (let pass = 0; ; pass++) {+ const result = await performManagedSync(engine, { ...opts, noPull: true, noEmbed: true });+ if (result.status !== 'partial' || result.reason !== 'writer_pending' || pass === 30) return result;+ }+}++async function syncRequest(engine: BrainEngine, sourceId: string, slug: string) {+ const [row] = await engine.executeRaw<{ intent_bytes: string; intent: Record<string, unknown>; state: string }>(+ `SELECT intent_bytes::text AS intent_bytes, intent, state FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND intent->>'kind'='managed_sync_import'+ ORDER BY sequence DESC LIMIT 1`, [sourceId, slug]);+ return row;+}++async function expectStreamed(engine: BrainEngine, sourceId: string, slug: string, content: string, path: string) {+ const parsed = parseMarkdown(content, path);+ const { page, body, hash } = await reconstructedPage(engine, slug, sourceId);+ expect(page.body_storage).toBe('segmented');+ expect(body.compiled_truth).toBe(parsed.compiled_truth);+ expect(body.timeline).toBe(parsed.timeline);+ expect(page.content_hash).toBe(hash);+ expect(page.text_projection_revision).toBe(page.knowledge_revision);+ const request = (await syncRequest(engine, sourceId, slug))!;+ expect(request.state).toBe('committed');+ expect(Number(request.intent_bytes)).toBeLessThan(16 * 1024);+ expect(request.intent.content).toBeNull();+ expect(request.intent.body_ref).toMatchObject({ sha256: sha256(Buffer.from(content)), bytes: Buffer.byteLength(content) });+ expect(await engine.executeRaw(`SELECT 1 FROM page_body_stagings WHERE page_id=$1 AND state IN ('open','prepared')`, [page.id])).toEqual([]);+ return page;+}++describe('managed sync over the single-string ceiling', () => {+ test('switch on: a committed file streams in by reference, then an edit, a full walk and a rename follow it', async () => withEnv(env, async () => {+ for (const engine of engines) {+ await engine.setConfig('pages.segmented_storage', 'on');+ const f = await fixture(engine, { 'notes/huge.md': huge, 'notes/small.md': '---\ntitle: Small\n---\nA small note.\n' });+ const file = join(f.root, 'notes/huge.md');+ const before = statSync(file);+ const preview = await performManagedSync(engine, { sourceId: f.sourceId, noPull: true, noEmbed: true, dryRun: true });+ expect(preview.would_hold).toBeUndefined();+ expect(preview.screen_skipped).toEqual([{ path: 'notes/huge.md', code: 'page_body_segmented' }]);+ expect(await sync(engine, { sourceId: f.sourceId })).toMatchObject({ status: 'first_sync', filesImported: 2 });+ await expectStreamed(engine, f.sourceId, 'notes/huge', huge, 'notes/huge.md');+ expect(statSync(file).mtimeMs).toBe(before.mtimeMs);+ expect(sha256(readFileSync(file))).toBe(sha256(Buffer.from(huge)));+ expect((await readGitSourceHolds(engine, { sourceIds: [f.sourceId] }))[0]?.holds ?? []).toEqual([]);++ const edited = `${huge.trimEnd()}\n\n**alice-example**: a closing streamed remark.\n`;+ writeFileSync(file, edited);+ commit(f.repo);+ expect(await sync(engine, { sourceId: f.sourceId })).toMatchObject({ status: 'synced' });+ const updated = await expectStreamed(engine, f.sourceId, 'notes/huge', edited, 'notes/huge.md');+ expect((await sync(engine, { sourceId: f.sourceId, full: true })).status).not.toBe('failed');+ expect((await reconstructedPage(engine, 'notes/huge', f.sourceId)).page.body_generation).toBe(updated.body_generation);++ git(f.repo, 'mv', 'notes/huge.md', 'notes/moved.md');+ commit(f.repo);+ expect(await sync(engine, { sourceId: f.sourceId })).toMatchObject({ status: 'synced', renamed: 1 });+ const moved = await expectStreamed(engine, f.sourceId, 'notes/moved', edited, 'notes/moved.md');+ expect(moved.id).toBe(updated.id);+ expect(await engine.getPage('notes/huge', { sourceId: f.sourceId })).toBeNull();+ const [origin] = await engine.executeRaw<{ source_path: string }>('SELECT source_path FROM pages WHERE id=$1', [moved.id]);+ expect(origin!.source_path).toBe('notes/moved.md');++ git(f.repo, 'mv', 'notes/moved.md', 'notes/again.md');+ const renamedEdit = `${edited.trimEnd()}\n\n**bob-example**: one more remark after the move.\n`;+ writeFileSync(join(f.root, 'notes/again.md'), renamedEdit);+ commit(f.repo);+ expect(await sync(engine, { sourceId: f.sourceId })).toMatchObject({ status: 'synced', renamed: 1 });+ const again = await expectStreamed(engine, f.sourceId, 'notes/again', renamedEdit, 'notes/again.md');+ expect(again.id).toBe(updated.id);+ expect(again.body_generation).toBe(moved.body_generation + 1);+ expect(await engine.getPage('notes/moved', { sourceId: f.sourceId })).toBeNull();+ await disposePersistenceConsumer(engine);+ }+ }), 900_000);++ test('a source at a repository subdirectory streams with git-root slugs', async () => withEnv(env, async () => {+ for (const engine of engines) {+ await engine.setConfig('pages.segmented_storage', 'on');+ const f = await fixture(engine, { 'notes/huge.md': huge }, 'brain');+ expect(await sync(engine, { sourceId: f.sourceId })).toMatchObject({ status: 'first_sync', filesImported: 1 });+ const page = await expectStreamed(engine, f.sourceId, 'brain/notes/huge', huge, 'brain/notes/huge.md');+ expect((await engine.executeRaw<{ source_path: string }>('SELECT source_path FROM pages WHERE id=$1', [page.id]))[0]!.source_path).toBe('brain/notes/huge.md');+ await disposePersistenceConsumer(engine);+ }+ }), 600_000);++ test('an uncommitted file synced from the working tree streams by reference', async () => withEnv(env, async () => {+ for (const engine of engines) {+ await engine.setConfig('pages.segmented_storage', 'on');+ const f = await fixture(engine, { 'notes/small.md': '---\ntitle: Small\n---\nA small note.\n' });+ writeFileSync(join(f.root, 'notes/huge.md'), huge);+ expect((await sync(engine, { sourceId: f.sourceId, workingTree: true })).status).not.toBe('failed');+ await expectStreamed(engine, f.sourceId, 'notes/huge', huge, 'notes/huge.md');+ expect((await syncRequest(engine, f.sourceId, 'notes/huge'))!.intent.body_ref).toMatchObject({ kind: 'input_file' });+ await disposePersistenceConsumer(engine);+ }+ }), 600_000);++ test('a file the streamed path refuses (a facts fence) is held file_too_large and the run checkpoints', async () => withEnv(env, async () => {+ for (const engine of engines) {+ await engine.setConfig('pages.segmented_storage', 'on');+ const fenced = `${huge.trimEnd()}\n\n## Facts\n\n<!--- gbrain:facts:begin -->\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|\n| 1 | Example fact | fact | 1.0 | world | high | | | test | |\n<!--- gbrain:facts:end -->\n`;+ const f = await fixture(engine, { 'notes/fenced.md': fenced, 'notes/small.md': '---\ntitle: Small\n---\nA small note.\n' });+ const result = await sync(engine, { sourceId: f.sourceId });+ expect(result.status).toBe('first_sync');+ const holds = (await readGitSourceHolds(engine, { sourceIds: [f.sourceId] }))[0]?.holds ?? [];+ expect(holds.map(hold => [hold.path, hold.code])).toEqual([['notes/fenced.md', 'file_too_large']]);+ expect(holds[0]!.message).toContain('facts and takes fences');+ expect(await engine.getPage('notes/fenced', { sourceId: f.sourceId })).toBeNull();+ expect(await engine.getPage('notes/small', { sourceId: f.sourceId })).not.toBeNull();+ await disposePersistenceConsumer(engine);+ }+ }), 600_000);++ test('switch off: the file is held by its size, as before', async () => withEnv(env, async () => {+ for (const engine of engines) {+ await engine.setConfig('pages.segmented_storage', 'off');+ const f = await fixture(engine, { 'notes/huge.md': huge });+ expect((await sync(engine, { sourceId: f.sourceId })).status).toBe('first_sync');+ const holds = (await readGitSourceHolds(engine, { sourceIds: [f.sourceId] }))[0]?.holds ?? [];+ expect(holds.map(hold => [hold.path, hold.code])).toEqual([['notes/huge.md', 'file_too_large']]);+ expect(await syncRequest(engine, f.sourceId, 'notes/huge')).toBeUndefined();+ await disposePersistenceConsumer(engine);+ }+ }), 600_000);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex ff4adda669..49a2c82646 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -67,6 +67,7 @@ test/large-pages/chunk-visibility.test.tstest/large-pages/contextual-reembed-segmented.test.tstest/large-pages/managed-streamed-import.test.tstest/large-pages/managed-sync-segmented-rename.test.ts+test/large-pages/managed-sync-streamed.test.tstest/large-pages/oversized-backfill-segmented.test.tstest/large-pages/segment-vector-reuse.test.tstest/large-pages/segmented-body-unreachable.test.ts