Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(write-gate): page gate joins the content-sanity disposition in import-screen (#5575 B3, CEO-19)

garrytan91b79d638b63
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index d87909b956..6a3d44c597 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -39,7 +39,7 @@ src/core/cycle/propose-takes.ts ProposeTakesPhase.process 429 seed: W5 baseline,
src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 490 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it; +13 fix wave 9 lane P (D-N3): fence-stripped member hash with legacy-hash grandfathering, and the classic write moved to publishClassicConcept (concept-publication.ts); +3 (#5041): opt-in concept write-through hook and the import callback publishClassicConcept runs under the page lock; +6 #4907 (issue #4906): configured budget read, budget-capped counter, summary clause and details.warnings (message text in budgetWarnings); +4 fix wave 11 #6161: concept redirects in grouping and the skipped_deleted pre-check (logic in cycle/concept-redirects.ts); +13 fix wave 12 #6260: a narrative stopped before the end is a counted failure, and the per-member-hash retry bound (state in cycle/concept-retry-bound.ts)
src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1047 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phase; +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data
src/core/facts/backstop.ts runPipelineBodyInner 358 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/import-file.ts importFromContent 812 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal; +1 #5333: embed-skip transition defeats the unchanged fast paths (the stale-marker clear stays inside the sanity block); +3 #6188: Tier 1 fence step in place before the hidden-row merge (logic in fence-repair/import-step.ts)
+src/core/import-file.ts importFromContent 666 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal; +1 #5333: embed-skip transition defeats the unchanged fast paths (the stale-marker clear stays inside the sanity block); +3 #6188: Tier 1 fence step in place before the hidden-row merge (logic in fence-repair/import-step.ts); -146 #5575: content-sanity/write-gate disposition moved to import-screen.ts settleContentDisposition
src/core/minions/handlers/subagent-oneshot.ts runSubagentOneshot 378 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 fix wave 9 lane B #4921: the oneshot sub-budget is passed as the call timeoutMs so the 300 s gateway backstop cannot cut it
src/core/minions/handlers/subagent.ts makeSubagentHandler 887 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 9 lane B #4921: per-turn timeout read once, passed to oneshot and gateway loop
src/core/minions/handlers/subagent.ts makeSubagentHandler>subagentHandlerInner 817 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 9 lane B #4921: per-turn timeout read once, passed to oneshot and gateway loop
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index f9faaafbd3..d1f5748bf3 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -17,7 +17,7 @@ src/core/cycle.ts 3283 ratchet +2 System One v1 S9: extract_facts phase tail run
src/core/cycle/synthesize.ts 3227 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import)
src/core/cycle/extract-atoms.ts 1650 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt
src/core/engine.ts 2721 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract
-src/core/import-file.ts 2200 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts)
+src/core/import-file.ts 2046 ratchet -136 #5575 write gate: the content-sanity disposition block moved to import-screen.ts settleContentDisposition (one call, write gate joined there); +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts)
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 340 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row
src/core/pglite-engine.ts 2996 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows)
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1926 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
src/core/chunkers/code.ts 1588 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)
-src/core/config.ts 1921 ratchet +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)
+src/core/config.ts 1924 ratchet +3 #5575: write_gate.external_mode / write_gate.agent_mode registered in KNOWN_CONFIG_KEYS; +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)
src/core/bootstrap/harness.ts 2610 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)
src/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 option
src/core/ops/pages.ts 673 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)
diff --git a/src/commands/quarantine.ts b/src/commands/quarantine.ts
index 8344fb6152..513b3990ee 100644
--- a/src/commands/quarantine.ts
+++ b/src/commands/quarantine.ts
@@ -1,7 +1,7 @@
/**
* gbrain quarantine — operator surface for the content-quality gate (issue #1699).
*
- * gbrain quarantine list [--json] [--include-flagged]
+ * gbrain quarantine list [--json] [--include-flagged] (also write-gate fact/take holds)
* gbrain quarantine clear <slug> [--force] [--no-embed] [--json]
* gbrain quarantine scan [--limit N] [--apply] [--no-embed] [--json]
*
@@ -23,6 +23,7 @@ import { resolveCliWriteWaitMs } from '../core/persistence/write-wait.ts';
import { QUARANTINE_OVERRIDE_KEY, quarantineOverrideFor } from '../core/quarantine-override.ts';
import { reportPersistenceCliError } from './persistence-delegate.ts';
import type { PageType } from '../core/types.ts';
+import { listWriteGateHolds, type WriteGateHold } from '../core/write-gate-store.ts';
export interface QuarantineRow {
slug: string;
@@ -141,15 +142,28 @@ export async function collectQuarantineRows(
return { rows, scanned, truncated };
}
+/** One-line, inert preview of a held row's text for the owner's review. */
+function holdPreview(hold: WriteGateHold): string {
+ const text = String(hold.payload.fact ?? hold.payload.claim ?? '').replace(/\s+/g, ' ').trim();
+ return text.length > 120 ? `${text.slice(0, 117)}...` : text;
+}
+
async function runList(engine: BrainEngine, args: string[]): Promise<void> {
const json = args.includes('--json');
const includeFlagged = args.includes('--include-flagged');
const { rows } = await collectQuarantineRows(engine, { includeFlagged });
+ // #5575: facts and takes the write gate held (never inserted); release or drop with gbrain trust release|drop <ref>.
+ const holds = await listWriteGateHolds(engine, { status: 'held', limit: 1000 });
if (json) {
- console.log(JSON.stringify({ schema_version: 1, count: rows.length, rows }, null, 2));
+ console.log(JSON.stringify({ schema_version: 1, count: rows.length, rows, hold_count: holds.length, holds }, null, 2));
return;
}
+ for (const h of holds) {
+ const src = h.source_id === 'default' ? '' : ` [${h.source_id}]`;
+ console.log(` HELD ${h.kind} ${h.ref}${src}${h.slug ? ` ${h.slug}` : ''} reasons=${h.reason_families.join(',') || 'detector_error'} tier=${h.tier} at=${h.last_seen_at}\n ${holdPreview(h)}`);
+ }
+ if (holds.length) console.log(`\n${holds.length} held fact/take row(s): review, then gbrain trust release <ref> or gbrain trust drop <ref>.\n`);
if (rows.length === 0) {
console.log(
includeFlagged
@@ -388,6 +402,7 @@ export const QUARANTINE_HELP = `Usage: gbrain quarantine <list|clear|scan> [opti
list [--json] [--include-flagged]
Pages the content-quality gate hid as junk (quarantine), and with
--include-flagged the searchable pages it flagged (content_flag).
+ Also lists facts and takes the write gate held for review (h<id>).
clear <slug> [--source-id <id>] [--force] [--no-embed] [--json]
Remove the markers and write the page again; the gate re-checks it.
--force records that the page is not junk (quarantine_override, bound
diff --git a/src/commands/sync/holds.ts b/src/commands/sync/holds.ts
index 8cb83df1f4..b0bb153692 100644
--- a/src/commands/sync/holds.ts
+++ b/src/commands/sync/holds.ts
@@ -154,6 +154,7 @@ export function legacyRefusal(result: Pick<ImportResult, 'status' | 'error' | 'r
if (result.refusal) return result.refusal.code === 'invalid_fence' ? null : result.refusal;
const error = result.error ?? '';
if (/^Content rejected by sanity gate: /.test(error)) return { code: 'content_rejected', message: error };
+ if (/^Refused by the write gate: /.test(error)) return { code: 'write_gate_rejected', message: error };
const typed = isContentRefusal('invalid_params', error) ? contentRefusalFromReceipt('invalid_params', error) : null;
if (!typed || typed.code === 'invalid_fence') return null;
const { suggestion: _suggestion, ...refusal } = typed;
diff --git a/src/core/config.ts b/src/core/config.ts
index 5e22326290..66c816d81d 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1580,6 +1580,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// #4702: per-pattern opt-out (JSON array or comma-separated names) —
// finer than junk_patterns_enabled (all patterns) / disabled (kill-switch).
'content_sanity.disabled_patterns',
+ // #5575 write gate (local-only): quarantine|flag|reject|off and flag|off; read by import-screen.ts.
+ 'write_gate.external_mode',
+ 'write_gate.agent_mode',
// MCP skill-catalog publishing (PR1)
'mcp.publish_skills',
'mcp.publish_skills_prompted',
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 120670006c..b86acc9856 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -3,7 +3,7 @@ import { suffixedFrontmatterSlugHold } from './persistence/suffixed-slug.ts';
import { maintenanceTransaction } from './persistence/attribution.ts';
import { assertImportBase, sameCanonicalImport, sameContentAnyKeyOrder } from './page-state/import-guard.ts';
import { stabilizeSafetyAssessments } from './persistence/reconcile-safety.ts';
-import { carryStoredQuarantineOverride, settleGateOwnedMarkers } from './quarantine-override.ts';
+import { settleGateOwnedMarkers } from './quarantine-override.ts';
import { decideImportIdentity, collidingSlugOwner, fileOriginUri } from './import-identity.ts';
import { readSourceFileSync } from './minions/source-filesystem.ts';
import { readFileSync, statSync, lstatSync } from 'fs';
@@ -11,7 +11,8 @@ import { basename, extname, resolve } from 'path';
import { createHash } from 'crypto';
import type { BrainEngine, FileSpec } from './engine.ts';
import { classifyImportHold, parseMarkdown, resolveParsedSubtype, type ParseOpts, type ParsedMarkdown } from './markdown.ts';
-import { assessImportSanity, loadImportSanityConfig, MAX_FILE_SIZE, screenImportContent, type ContentRefusal, type FenceScreen } from './import-screen.ts';
+import { MAX_FILE_SIZE, screenImportContent, settleContentDisposition, type ContentRefusal, type FenceScreen } from './import-screen.ts';
+import type { WriteGateInput } from './write-gate.ts';
import { applyImportFences } from './fence-repair/import-step.ts';
import type { FenceIssueWire } from './fence-repair/tier1.ts';
import type { FenceFix } from './fence-repair/types.ts';
@@ -40,15 +41,7 @@ import type { PageSnapshot } from './page-state/types.ts';
import { computeEffectiveDate, fallbackCreatedAt, isValidTimeZone } from './effective-date.ts';
import { MARKDOWN_CHUNKER_VERSION } from './chunkers/recursive.ts';
import { logSlugFallback } from './audit-slug-fallback.ts';
-import { ContentSanityBlockError } from './content-sanity.ts';
-import { logContentSanityAssessment } from './audit/content-sanity-audit.ts';
-import { buildEmbedSkipMarker, EMBED_SKIP_KEY, isEmbedSkipped } from './embed-skip.ts';
-import {
- QUARANTINE_KEY,
- CONTENT_FLAG_KEY,
- buildQuarantineMarker,
- buildContentFlagMarker,
-} from './quarantine.ts';
+import { isEmbedSkipped } from './embed-skip.ts';
import {
buildContextualPrefix,
modeRequiresSynopsis,
@@ -142,8 +135,8 @@ export interface ImportResult {
/** True when the page landed with a `content_flag` marker (fuzzy
* markup-heavy or oversize — stays searchable, agent warned). */
flagged?: boolean;
- /** Which flag tier fired, when `flagged`. */
- flag_reason?: 'markup_heavy' | 'oversized';
+ /** Which flag tier fired, when `flagged` (`instruction_like`: the #5575 write gate). */
+ flag_reason?: 'markup_heavy' | 'oversized' | 'instruction_like';
/** #5050: unchanged content below the safe-chunk fence was re-sealed; chunks left to embed. */
resealed?: { pendingChunks: number; pendingChars: number };
/**
@@ -322,6 +315,8 @@ export async function importFromContent(
* and reindex leave it unset so the guard stays armed.
*/
allowEmptyOverwrite?: boolean;
+ /** #5575: the caller's trust tier and origin for this write; absent skips the write gate (owner paths). */
+ writeGate?: WriteGateInput;
beforeCommit?: (tx: BrainEngine, slug: string) => Promise<void>;
onPostCommitEmbedding?: (complete: () => Promise<ImportEmbeddingResult>) => void;
} & ImportFenceOptions = {},
@@ -376,141 +371,9 @@ export async function importFromContent(
},
});
- // v0.41 content-sanity gate. Runs AFTER parseMarkdown so the assessor
- // sees the parsed body (compiled_truth + timeline), title, and
- // frontmatter; runs BEFORE the hash compute so a soft-block that
- // mutates frontmatter (sets `embed_skip`) reaches the existing hash
- // calculation and the page write doesn't short-circuit on hash equality.
- //
- // Three outcomes:
- // - kill-switch active (`content_sanity.disabled === true` /
- // `GBRAIN_NO_SANITY=1`) → assess + audit with bypass flag, emit
- // loud stderr per offending ingest, but let everything through.
- // - hard-block (junk pattern OR operator literal) → THROW
- // ContentSanityBlockError. Existing exception flow at every
- // wrapper site (import.ts errors counter, put_page MCP envelope,
- // sync.ts:929 failure record) fires correctly through this single
- // throw point. classifyErrorCode picks up the PAGE_JUNK_PATTERN
- // prefix in the error message and groups in sync-failures.jsonl.
- // - soft-block (oversize WITHOUT junk-pattern hit) → mutate
- // frontmatter to embed `embed_skip` marker. Existing chunking
- // block guards on `isEmbedSkipped(frontmatter)` so chunks stays
- // empty; the existing `tx.deleteChunks` at the empty-chunks
- // branch fires to purge old chunks (D9 transition invariant).
- //
- // Effective config: env > file > DB > defaults. The DB-plane lift
- // adds ~4 SQL round-trips per import (one per content_sanity.* key);
- // acceptable for the per-page cost since the gate runs at most once
- // per ingest. Power-users with 10K-file syncs who care about this
- // overhead can set the keys via env vars instead and skip the DB read.
- // Content-quality gate disposition flags (issue #1699), threaded onto
- // the ImportResult so callers (sync reporting, tests) see what happened.
- let pageQuarantined = false;
- let pageFlagged = false;
- let pageFlagReason: 'markup_heavy' | 'oversized' | undefined;
- {
- const sanityCfg = await loadImportSanityConfig(engine);
- const sanityDisabled = sanityCfg.disabled;
- // Disposition for the high-confidence junk path: quarantine (hide) by
- // default, or reject (throw → sync-failure) when the operator opts in.
- const junkDisposition = sanityCfg.junkDisposition;
- const sanityResult = await carryStoredQuarantineOverride(engine, parsed, assessImportSanity(parsed, sanityCfg), { slug, sourceId, remote: opts.remote === true });
- if (!sanityDisabled && !sanityResult.shouldQuarantine && sanityResult.flag_reason !== 'oversized' && (parsed.frontmatter[EMBED_SKIP_KEY] as { reason?: unknown } | undefined)?.reason === 'oversized') {
- delete parsed.frontmatter[EMBED_SKIP_KEY];
- if ((parsed.frontmatter[CONTENT_FLAG_KEY] as { reason?: unknown } | undefined)?.reason === 'oversized') delete parsed.frontmatter[CONTENT_FLAG_KEY];
- }
-
- if (sanityDisabled) {
- // Kill-switch active: loud stderr per offending ingest. Operator
- // explicitly opted into the bypass and gets noisy feedback every
- // time it fires so they remember the gate is off. Audit as a
- // bypass (page lands regardless).
- logContentSanityAssessment(slug, sourceId ?? 'default', sanityResult, {
- bypass: true,
- });
- if (sanityResult.shouldQuarantine || sanityResult.shouldFlag) {
- process.stderr.write(
- `[gbrain] content-sanity bypass (GBRAIN_NO_SANITY=1): ${slug} — ${sanityResult.reason_messages.join('; ')}\n`,
- );
- }
- } else if (sanityResult.shouldQuarantine) {
- // High-confidence junk (Cloudflare/CAPTCHA pattern or operator
- // literal). The detail names which fired.
- const detail = [
- ...sanityResult.junk_pattern_matches,
- ...sanityResult.literal_substring_matches,
- ].join(', ');
- const reason = sanityResult.junk_pattern_matches.length > 0
- ? 'junk_pattern'
- : 'literal_substring';
- if (junkDisposition === 'reject') {
- // Operator opted into hard-block. Throw with PAGE_QUARANTINE so
- // classifyErrorCode bins it. Existing exception flow at every
- // wrapper site (import errors counter, put_page MCP envelope,
- // sync failure record) fires through this single throw point.
- logContentSanityAssessment(slug, sourceId ?? 'default', sanityResult, {
- disposition: 'reject',
- });
- throw new ContentSanityBlockError(sanityResult);
- }
- // Default: quarantine (hide). Page lands with the marker, writes
- // zero chunks (chunking guard below widens to isQuarantined), is
- // excluded from search via QUARANTINE_FILTER_FRAGMENT, reviewable
- // via get_page / `gbrain quarantine list`.
- parsed.frontmatter[QUARANTINE_KEY] = buildQuarantineMarker(reason, detail, {
- bytes: sanityResult.bytes,
- });
- pageQuarantined = true;
- logContentSanityAssessment(slug, sourceId ?? 'default', sanityResult, {
- disposition: 'quarantine',
- });
- process.stderr.write(
- `[gbrain] content-sanity quarantine: ${slug} — ${detail} (hidden from search, reviewable via 'gbrain quarantine list')\n`,
- );
- } else if (sanityResult.shouldFlag) {
- // Fuzzy markup-heavy OR oversize. The page stays usable; the agent
- // gets warned (Garry's paradigm — "this is odd, you decide").
- const flagReason = sanityResult.flag_reason!; // non-null when shouldFlag
- const flagDetail = sanityResult.reason_messages.join('; ');
- parsed.frontmatter[CONTENT_FLAG_KEY] = buildContentFlagMarker(flagReason, flagDetail, {
- ...(sanityResult.markup_ratio !== null ? { markup_ratio: sanityResult.markup_ratio } : {}),
- bytes: sanityResult.bytes,
- });
- pageFlagged = true;
- pageFlagReason = flagReason;
- if (flagReason === 'oversized') {
- // Oversize also skips embedding (existing embed_skip marker). The
- // chunking guard below honors it; tx.deleteChunks purges old chunks.
- parsed.frontmatter[EMBED_SKIP_KEY] = buildEmbedSkipMarker(sanityResult.bytes);
- logContentSanityAssessment(slug, sourceId ?? 'default', sanityResult, {
- disposition: 'soft_block',
- });
- // #3893 (reimplemented from @y2688): console.warn, not bare stderr —
- // soft_block silently drops embedding, and console-level warns are
- // what operator log hooks and collectors can observe.
- console.warn(
- `[gbrain] content-sanity flag (oversized): ${slug} (${sanityResult.bytes} bytes) — page lands, embedding skipped, agent warned`,
- );
- } else {
- // markup_heavy: page ingests NORMALLY (keeps chunks, embeds). The
- // content_flag marker rides along for the agent warning.
- logContentSanityAssessment(slug, sourceId ?? 'default', sanityResult, {
- disposition: 'flag',
- });
- process.stderr.write(
- `[gbrain] content-sanity flag (markup_heavy): ${slug} (ratio ${sanityResult.markup_ratio?.toFixed(2)}) — stays searchable, agent warned\n`,
- );
- }
- } else if (sanityResult.reasons.includes('oversize_warn')) {
- // Warn tier: page lands normally; lint surface picks up too.
- logContentSanityAssessment(slug, sourceId ?? 'default', sanityResult, {
- disposition: 'warn',
- });
- process.stderr.write(
- `[gbrain] content-sanity warn: ${slug} (${sanityResult.bytes} bytes) — exceeds warn threshold, consider splitting\n`,
- );
- }
- }
+ // Content-sanity (#1699) and write-gate (#5575) disposition before the hash (import-screen.ts).
+ const disposition = await settleContentDisposition(engine, parsed, { slug, sourceId, remote: opts.remote === true, ...(opts.writeGate ? { writeGate: opts.writeGate } : {}) });
+ const { quarantined: pageQuarantined, flagged: pageFlagged, flagReason: pageFlagReason } = disposition;
// v0.39.3.0 CV8 — DB content_hash excludes timestamp-bearing frontmatter
// keys so identical body content from `gbrain capture` (which stamps
@@ -972,6 +835,7 @@ export async function importFromContent(
await writePageAliases(tx, slug, sourceId ?? 'default', parsed, opts.activePack, mentionPolicy);
if (!opts.coordinated) await verifyPageReadable(tx, slug, hash, sourceId, 'importFromContent');
await opts.beforeCommit?.(tx, slug);
+ await disposition.persistReceipt(tx);
if (opts.onPostCommitEmbedding && !opts.noEmbed && chunks.length > 0) {
// Capture the complete installed projection before releasing the page
// guard. Deferred provider results cannot replace newer text or chunks.
diff --git a/src/core/import-screen.ts b/src/core/import-screen.ts
index 0dcd5ec7fe..67bf45373e 100644
--- a/src/core/import-screen.ts
+++ b/src/core/import-screen.ts
@@ -10,8 +10,16 @@
*/
import type { BrainEngine } from './engine.ts';
import { loadConfig, loadConfigWithEngine } from './config.ts';
-import { assessContentSanity, type ContentSanityResult } from './content-sanity.ts';
-import { withQuarantineOverride } from './quarantine-override.ts';
+import { assessContentSanity, ContentSanityBlockError, type ContentSanityResult } from './content-sanity.ts';
+import { carryStoredQuarantineOverride, withQuarantineOverride } from './quarantine-override.ts';
+import { logContentSanityAssessment } from './audit/content-sanity-audit.ts';
+import { buildEmbedSkipMarker, EMBED_SKIP_KEY } from './embed-skip.ts';
+import { buildContentFlagMarker, buildQuarantineMarker, CONTENT_FLAG_KEY, QUARANTINE_KEY } from './quarantine.ts';
+import {
+ assessPageForGate, DEFAULT_WRITE_GATE_CONFIG, parseWriteGateConfig, writeGateDetail, writeGateRejectedError,
+ type WriteGateAssessment, type WriteGateConfig, type WriteGateInput,
+} from './write-gate.ts';
+import { recordPageGateReceipt } from './write-gate-store.ts';
import { loadOperatorLiterals } from './content-sanity-literals.ts';
import { classifyImportHold, contentSizeHold, parseMarkdown, type ContentHold, type ParseOpts, type ParsedMarkdown } from './markdown.ts';
import { isCodeFilePath } from './sync.ts';
@@ -32,28 +40,213 @@ export interface ImportSanityConfig {
disabled: boolean;
extraLiterals: ReturnType<typeof loadOperatorLiterals>;
junkDisposition: 'quarantine' | 'reject';
+ /** #5575 `write_gate.external_mode` / `write_gate.agent_mode` (DB plane, local-only); absent = defaults. */
+ writeGate?: WriteGateConfig;
}
/**
* Effective content-sanity config: env > file > DB > defaults. A transient
* engine error falls back to file/env values. `GBRAIN_NO_SANITY=1` is read
- * directly because loadConfig() is null on config-less PGLite setups.
+ * directly because loadConfig() is null on config-less PGLite setups. The
+ * write-gate keys ride the same lift; an unreadable value falls back to the
+ * defaults (external quarantine, agent flag), never to `off`.
*/
export async function loadImportSanityConfig(engine: BrainEngine): Promise<ImportSanityConfig> {
const baseCfg = loadConfig();
let effectiveCfg = baseCfg;
+ const readKey = (key: string) => engine.getConfig(key).catch(() => null);
+ const gateKeys = Promise.all([readKey('write_gate.external_mode'), readKey('write_gate.agent_mode')]);
try {
effectiveCfg = await loadConfigWithEngine(engine, baseCfg);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
process.stderr.write(`[gbrain] content-sanity: DB config lift failed (${msg}); falling back to file/env\n`);
}
+ const [externalMode, agentMode] = await gateKeys;
const cs = effectiveCfg?.content_sanity ?? {};
const disabled = cs.disabled === true || process.env.GBRAIN_NO_SANITY === '1';
return {
cs, disabled,
extraLiterals: cs.junk_patterns_enabled !== false && !disabled ? loadOperatorLiterals() : [],
junkDisposition: cs.junk_disposition === 'reject' ? 'reject' : 'quarantine',
+ writeGate: parseWriteGateConfig({ external_mode: externalMode, agent_mode: agentMode }),
+ };
+}
+
+export interface ContentDispositionContext {
+ slug: string;
+ sourceId?: string;
+ /** Untrusted caller: a stored quarantine override is not carried (quarantine-override.ts). */
+ remote: boolean;
+ /** #5575: tier and origin of this write; absent skips the write gate. */
+ writeGate?: WriteGateInput;
+}
+
+export interface ContentDisposition {
+ quarantined: boolean;
+ flagged: boolean;
+ flagReason?: 'markup_heavy' | 'oversized' | 'instruction_like';
+ /** The write-gate assessment, when the caller passed `writeGate`. */
+ gate: WriteGateAssessment | null;
+ /** Records the gate's flag/quarantine receipt for the written page inside the publication transaction. */
+ persistReceipt: (tx: BrainEngine) => Promise<void>;
+}
+
+/**
+ * The page disposition `importFromContent` applies before hashing: the v0.41
+ * content-sanity gate (#1699) and the #5575 write gate, most severe wins.
+ * Runs after parseMarkdown and the guardrail seam, before the hash compute,
+ * so a marker it sets (`embed_skip`, `quarantine`, `content_flag`) reaches
+ * the hash and the page write never short-circuits on hash equality.
+ *
+ * Content sanity:
+ * - kill-switch (`content_sanity.disabled` / `GBRAIN_NO_SANITY=1`): assess
+ * and audit as a bypass, loud stderr per offending ingest, write anyway.
+ * - hard-block (junk pattern or operator literal) under
+ * `junk_disposition: reject`: throw ContentSanityBlockError, the single
+ * throw point every wrapper (import errors, put_page envelope, sync
+ * failure record) already handles; otherwise quarantine (hidden, zero
+ * chunks, reviewable via `gbrain quarantine list`).
+ * - soft-block (oversize without a junk hit): `embed_skip` plus a
+ * `content_flag`, so chunks stay empty and old chunks are purged.
+ * - markup-heavy: `content_flag`, page stays searchable.
+ * Write gate (only with `ctx.writeGate`; its own `write_gate.*` switches):
+ * - reject: throw `write_gate_rejected`.
+ * - quarantine: `quarantine` marker (reason `instruction_like`) unless
+ * content sanity already quarantined the page.
+ * - flag: `content_flag` (reason `instruction_like`) unless quarantined.
+ * - a write the gate allows drops a stale `instruction_like` marker.
+ * Effective config: env > file > DB > defaults, read once per import with the
+ * write-gate keys in the same lift (`loadImportSanityConfig`).
+ */
+export async function settleContentDisposition(engine: BrainEngine, parsed: ParsedMarkdown, ctx: ContentDispositionContext): Promise<ContentDisposition> {
+ const { slug, sourceId } = ctx;
+ let pageQuarantined = false;
+ let pageFlagged = false;
+ let pageFlagReason: ContentDisposition['flagReason'];
+ const sanityCfg = await loadImportSanityConfig(engine);
+ const sanityDisabled = sanityCfg.disabled;
+ // Disposition for the high-confidence junk path: quarantine (hide) by
+ // default, or reject (throw → sync-failure) when the operator opts in.
+ const junkDisposition = sanityCfg.junkDisposition;
+ const sanityResult = await carryStoredQuarantineOverride(engine, parsed, assessImportSanity(parsed, sanityCfg), { slug, sourceId, remote: ctx.remote });
+ if (!sanityDisabled && !sanityResult.shouldQuarantine && sanityResult.flag_reason !== 'oversized' && (parsed.frontmatter[EMBED_SKIP_KEY] as { reason?: unknown } | undefined)?.reason === 'oversized') {
+ delete parsed.frontmatter[EMBED_SKIP_KEY];
+ if ((parsed.frontmatter[CONTENT_FLAG_KEY] as { reason?: unknown } | undefined)?.reason === 'oversized') delete parsed.frontmatter[CONTENT_FLAG_KEY];
+ }
+
+ if (sanityDisabled) {
+ // Kill-switch active: loud stderr per offending ingest. Operator
+ // explicitly opted into the bypass and gets noisy feedback every
+ // time it fires so they remember the gate is off. Audit as a
+ // bypass (page lands regardless).
+ logContentSanityAssessment(slug, sourceId ?? 'default', sanityResult, {
+ bypass: true,
+ });
+ if (sanityResult.shouldQuarantine || sanityResult.shouldFlag) {
+ process.stderr.write(
+ `[gbrain] content-sanity bypass (GBRAIN_NO_SANITY=1): ${slug} — ${sanityResult.reason_messages.join('; ')}\n`,
+ );
+ }
+ } else if (sanityResult.shouldQuarantine) {
+ // High-confidence junk (Cloudflare/CAPTCHA pattern or operator
+ // literal). The detail names which fired.
+ const detail = [
+ ...sanityResult.junk_pattern_matches,
+ ...sanityResult.literal_substring_matches,
+ ].join(', ');
+ const reason = sanityResult.junk_pattern_matches.length > 0
+ ? 'junk_pattern'
+ : 'literal_substring';
+ if (junkDisposition === 'reject') {
+ // Operator opted into hard-block. Throw with PAGE_QUARANTINE so
+ // classifyErrorCode bins it. Existing exception flow at every
+ // wrapper site (import errors counter, put_page MCP envelope,
+ // sync failure record) fires through this single throw point.
+ logContentSanityAssessment(slug, sourceId ?? 'default', sanityResult, {
+ disposition: 'reject',
+ });
+ throw new ContentSanityBlockError(sanityResult);
+ }
+ // Default: quarantine (hide). Page lands with the marker, writes
+ // zero chunks (chunking guard below widens to isQuarantined), is
+ // excluded from search via QUARANTINE_FILTER_FRAGMENT, reviewable
+ // via get_page / `gbrain quarantine list`.
+ parsed.frontmatter[QUARANTINE_KEY] = buildQuarantineMarker(reason, detail, {
+ bytes: sanityResult.bytes,
+ });
+ pageQuarantined = true;
+ logContentSanityAssessment(slug, sourceId ?? 'default', sanityResult, {
+ disposition: 'quarantine',
+ });
+ process.stderr.write(
+ `[gbrain] content-sanity quarantine: ${slug} — ${detail} (hidden from search, reviewable via 'gbrain quarantine list')\n`,
+ );
+ } else if (sanityResult.shouldFlag) {
+ // Fuzzy markup-heavy OR oversize. The page stays usable; the agent
+ // gets warned (Garry's paradigm — "this is odd, you decide").
+ const flagReason = sanityResult.flag_reason!; // non-null when shouldFlag
+ const flagDetail = sanityResult.reason_messages.join('; ');
+ parsed.frontmatter[CONTENT_FLAG_KEY] = buildContentFlagMarker(flagReason, flagDetail, {
+ ...(sanityResult.markup_ratio !== null ? { markup_ratio: sanityResult.markup_ratio } : {}),
+ bytes: sanityResult.bytes,
+ });
+ pageFlagged = true;
+ pageFlagReason = flagReason;
+ if (flagReason === 'oversized') {
+ // Oversize also skips embedding (existing embed_skip marker). The
+ // chunking guard below honors it; tx.deleteChunks purges old chunks.
+ parsed.frontmatter[EMBED_SKIP_KEY] = buildEmbedSkipMarker(sanityResult.bytes);
+ logContentSanityAssessment(slug, sourceId ?? 'default', sanityResult, {
+ disposition: 'soft_block',
+ });
+ // #3893 (reimplemented from @y2688): console.warn, not bare stderr —
+ // soft_block silently drops embedding, and console-level warns are
+ // what operator log hooks and collectors can observe.
+ console.warn(
+ `[gbrain] content-sanity flag (oversized): ${slug} (${sanityResult.bytes} bytes) — page lands, embedding skipped, agent warned`,
+ );
+ } else {
+ // markup_heavy: page ingests NORMALLY (keeps chunks, embeds). The
+ // content_flag marker rides along for the agent warning.
+ logContentSanityAssessment(slug, sourceId ?? 'default', sanityResult, {
+ disposition: 'flag',
+ });
+ process.stderr.write(
+ `[gbrain] content-sanity flag (markup_heavy): ${slug} (ratio ${sanityResult.markup_ratio?.toFixed(2)}) — stays searchable, agent warned\n`,
+ );
+ }
+ } else if (sanityResult.reasons.includes('oversize_warn')) {
+ // Warn tier: page lands normally; lint surface picks up too.
+ logContentSanityAssessment(slug, sourceId ?? 'default', sanityResult, {
+ disposition: 'warn',
+ });
+ process.stderr.write(
+ `[gbrain] content-sanity warn: ${slug} (${sanityResult.bytes} bytes) — exceeds warn threshold, consider splitting\n`,
+ );
+ }
+ const gate = ctx.writeGate ? assessPageForGate(parsed, ctx.writeGate, sanityCfg.writeGate ?? DEFAULT_WRITE_GATE_CONFIG) : null;
+ if (gate) {
+ if (gate.verdict === 'reject') throw writeGateRejectedError(gate);
+ const detail = writeGateDetail(gate);
+ for (const key of [QUARANTINE_KEY, CONTENT_FLAG_KEY]) {
+ if ((parsed.frontmatter[key] as { reason?: unknown } | undefined)?.reason === 'instruction_like') delete parsed.frontmatter[key];
+ }
+ if (gate.verdict === 'quarantine' && !pageQuarantined) {
+ parsed.frontmatter[QUARANTINE_KEY] = buildQuarantineMarker('instruction_like', detail);
+ pageQuarantined = true;
+ process.stderr.write(`[gbrain] ${detail}: ${slug} quarantined (hidden from search, reviewable via 'gbrain quarantine list')\n`);
+ } else if (gate.verdict === 'flag' && !pageQuarantined) {
+ parsed.frontmatter[CONTENT_FLAG_KEY] = buildContentFlagMarker('instruction_like', detail);
+ pageFlagged = true;
+ pageFlagReason = 'instruction_like';
+ }
+ }
+ return {
+ quarantined: pageQuarantined, flagged: pageFlagged, ...(pageFlagReason ? { flagReason: pageFlagReason } : {}), gate,
+ persistReceipt: async tx => {
+ if (gate) await recordPageGateReceipt(tx, { slug, sourceId: sourceId ?? 'default', assessment: gate, requestId: ctx.writeGate?.requestId ?? null });
+ },
};
}
@@ -80,7 +273,7 @@ export function assessImportSanity(page: Pick<ParsedMarkdown, 'compiled_truth' |
* with its location-only `fence`.
*/
export interface ContentRefusal extends Omit<ContentHold, 'code' | 'reason'> {
- code: ContentHold['code'] | 'content_rejected' | 'invalid_fence';
+ code: ContentHold['code'] | 'content_rejected' | 'invalid_fence' | 'write_gate_rejected';
reason?: ContentHold['reason'] | FenceReason;
fence?: FenceMessageLocation;
/** #6188 (D18): every issue that blocks the write, location and class only. */
@@ -137,6 +330,8 @@ export interface ImportScreenInput {
fences?: 'coordinated' | 'lenient';
/** #6188: `fences.normalize`; false treats a fixable fence as residual. Default true. */
normalize?: boolean;
+ /** #5575: tier and origin of this write; under `write_gate.external_mode: reject` (from `sanity`) a gate reject refuses `write_gate_rejected`. */
+ writeGate?: WriteGateInput;
}
export type ImportScreenResult =
@@ -174,6 +369,10 @@ export function screenImportContent(input: ImportScreenInput): ImportScreenResul
const result = assessImportSanity(parsed, input.sanity);
if (result.shouldQuarantine) return { status: 'refused', refusal: { code: 'content_rejected', message: `Content rejected by sanity gate: ${result.reason_messages.join('; ')}` } };
}
+ if (input.writeGate?.tier === 'external_untrusted' && input.sanity?.writeGate?.externalMode === 'reject') {
+ const gate = assessPageForGate(parsed, input.writeGate, input.sanity.writeGate);
+ if (gate.verdict === 'reject') return { status: 'refused', refusal: { code: 'write_gate_rejected', message: writeGateRejectedError(gate).message } };
+ }
return { status: 'importable', parsed, ...(fences ? { fences } : {}) };
}
@@ -218,11 +417,12 @@ export function contentRefusalFromReceipt(code: string | null | undefined, messa
const suggestion = typed === 'invalid_frontmatter' ? `The content itself was refused, so resubmitting it unchanged refuses again. Correct ${where}: one line per key with its whole value quoted, then submit the corrected content with a new request_id.`
: typed === 'frontmatter_slug_conflict' ? 'The content declares a slug that conflicts with its path. Remove the `slug:` line or make it match, then submit with a new request_id.'
: typed === 'content_rejected' ? 'The content-sanity gate rejects this content under the operator\'s junk_disposition=reject setting. Remove the matched junk, then submit with a new request_id.'
+ : typed === 'write_gate_rejected' ? 'The write gate refuses this external instruction-like content under the operator\'s write_gate.external_mode=reject setting, so it refuses on every retry. Tell the user; changing that setting is their decision.'
: 'The content is over the import size limit. Split it into smaller pages, then submit each with its own request_id.';
return { code: typed, ...(reason ? { reason } : {}), ...(key ? { key } : {}), ...(line !== undefined ? { line } : {}), suggestion };
}
-const CONTENT_REFUSAL_CODES = new Set(['invalid_frontmatter', 'frontmatter_slug_conflict', 'file_too_large', 'content_rejected']);
+const CONTENT_REFUSAL_CODES = new Set(['invalid_frontmatter', 'frontmatter_slug_conflict', 'file_too_large', 'content_rejected', 'write_gate_rejected']);
const LEGACY_CONTENT_MESSAGES: Array<[code: string, pattern: RegExp]> = [
['invalid_params', /^Invalid YAML frontmatter(?::| at line \d| in )/],
['invalid_params', /^The frontmatter slug "[^"\n]*" in [^\n]+ conflicts with its path, which expects slug "[^"\n]*"\./],
diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.ts
index 564d98f657..55d00198df 100644
--- a/src/core/persistence/import-prepare.ts
+++ b/src/core/persistence/import-prepare.ts
@@ -62,6 +62,7 @@ function managedImportRefusal(refusal: ContentRefusal, sourcePath: string): Oper
? `In ${sourcePath}, remove the frontmatter slug or set it to the path-derived slug (the path decides the slug), or move the file to the path that matches its slug, then import again.`
: refusal.code === 'file_too_large' ? `${sourcePath} is over the import size limit and was not imported. Split it into smaller files or leave it out of the import.`
: refusal.code === 'content_rejected' ? `Remove the matched junk from ${sourcePath}, then import it again.`
+ : refusal.code === 'write_gate_rejected' ? `The write gate refuses ${sourcePath} (external instruction-like content under write_gate.external_mode=reject); tell the user, the decision is theirs.`
: `Fix line ${refusal.line ?? '?'} of ${sourcePath}${refusal.key ? ` (key "${refusal.key}")` : ''}: one line per key with its whole value quoted. Run gbrain frontmatter validate on the file to see every problem, then import it again.`;
return contentRefusalError(refusal, suggestion, { legacy_error: 'invalid_params' });
}
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index d22772cdc6..5a2dc69570 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -377,6 +377,10 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'c
return { argv: ['gbrain', 'config', 'get', 'content_sanity'], consent: [], actor: 'user', requires_exclusive: false,
user_message: `${record.path} was rejected by the content-sanity gate because junk_disposition is reject. Remove the matched junk from the file, or decide whether to switch junk_disposition back to quarantine.`,
why: 'The operator chose to reject junk; changing that setting is a user decision. Editing the file and committing clears the hold on the next sync.' };
+ case 'write_gate_rejected':
+ return { argv: ['gbrain', 'config', 'get', 'write_gate.external_mode'], consent: [], actor: 'user', requires_exclusive: false,
+ user_message: `${record.path} was refused by the write gate: its source is untrusted and it reads like an instruction to an agent, and write_gate.external_mode is reject. Decide whether to edit the file or switch the setting back to quarantine.`,
+ why: 'The operator chose to reject external instruction-like content; changing that setting is a user decision. Editing the file and committing clears the hold on the next sync.' };
case 'managed_image_sync_unsupported':
return { argv: ['gbrain', 'config', 'get', 'sync.exclude'], consent: [], actor: 'user', requires_exclusive: false,
user_message: `Managed sync does not import images yet, so ${record.path} is held and the rest of source ${source} keeps syncing. Keeping images held is fine; to stop holding them, leave images out of the source with sync.exclude or turn off multimodal embedding.`,
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index ef6da2f984..86c8d7c1f3 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -136,9 +136,10 @@ function syncContentRefusal(refusal: ContentRefusal, row: WriteRequest, p: SyncI
: refusal.code === 'frontmatter_slug_conflict' ? 'Correct the frontmatter `slug:` in the file and commit the change.'
: refusal.code === 'file_too_large' ? `${p.sourcePath} is over the import size limit; split it into smaller files or add it to sync.exclude, then commit.`
: refusal.code === 'content_rejected' ? `The content-sanity gate rejects ${p.sourcePath} under junk_disposition=reject; remove the matched junk and commit.`
+ : 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' ? {} : { legacy_error: 'invalid_params' }),
+ ...(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(', ') } : {}),
});
diff --git a/src/core/quarantine.ts b/src/core/quarantine.ts
index 0d5a4f8b35..06309c54ed 100644
--- a/src/core/quarantine.ts
+++ b/src/core/quarantine.ts
@@ -56,8 +56,8 @@ export function quarantineFilterFragment(pageAlias: string): string {
export const QUARANTINE_FILTER_FRAGMENT = quarantineFilterFragment('p');
export interface QuarantineMarker {
- /** Why the page was quarantined. The high-confidence junk reasons. */
- reason: 'junk_pattern' | 'literal_substring';
+ /** Why the page was quarantined: high-confidence junk, or (#5575) instruction-like content the write gate held. */
+ reason: 'junk_pattern' | 'literal_substring' | 'instruction_like';
/** Human-readable detail (which pattern/literal names fired). */
detail: string;
/** ISO 8601 timestamp at assessment time. */
@@ -113,8 +113,8 @@ export async function quarantinedSlugs(engine: Pick<BrainEngine, 'executeRaw'>,
export const CONTENT_FLAG_KEY = 'content_flag';
export interface ContentFlagMarker {
- /** Which fuzzy/oversize tier fired. */
- reason: 'markup_heavy' | 'oversized';
+ /** Which fuzzy/oversize tier fired, or (#5575) the write gate flagged instruction-like content. */
+ reason: 'markup_heavy' | 'oversized' | 'instruction_like';
/** Human-readable detail surfaced to the agent on retrieval. */
detail: string;
/** ISO 8601 timestamp at assessment time. */
diff --git a/src/core/repair/frontmatter.ts b/src/core/repair/frontmatter.ts
index 6fb8945ebc..b3776369e2 100644
--- a/src/core/repair/frontmatter.ts
+++ b/src/core/repair/frontmatter.ts
@@ -174,6 +174,7 @@ function resolution(hold: Pick<ContentRefusal, 'code' | 'reason' | 'key' | 'line
case 'file_too_large': return `Split ${path} into files under ${MAX_FILE_SIZE} bytes and commit, or leave it out of the source with sync.exclude.`;
case 'frontmatter_slug_conflict': return `Remove the slug: line of ${path} (the path decides the slug), or move the file to the path its slug names.`;
case 'content_rejected': return `Remove the junk the content-sanity gate matched in ${path}, or ask the user whether junk_disposition should stay reject.`;
+ case 'write_gate_rejected': return `The write gate refused ${path} as external instruction-like content; ask the user whether to edit it or whether write_gate.external_mode should stay reject.`;
case 'rename_held': return `Re-run the preview with --include-ambiguous to re-bind the rename of ${path} to the current page, or restore the old file name.`;
case 'parser_regression': return `This is a gbrain bug: report the gbrain version, ${path} and the code; upgrade or pin the last good version.`;
default: return hold.reason === 'ambiguous_protected_key' ? `Write ${where} on one line with one quoted value; gbrain never guesses who may read a page or where it came from.`