Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

chore(w12-w1): keep embed.ts, importFromContent and the persistence layer inside their ratchets; env-scoped git test switch

time-attack36c5d34d6493
diff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.md
index d97e2c0a4f..a5f0026a33 100644
--- a/docs/architecture/key-files/commands-4-continued.md
+++ b/docs/architecture/key-files/commands-4-continued.md
@@ -9,7 +9,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/publish.ts` — Deterministic brain page publisher (code+skill pair, zero LLM calls)
-- `src/core/quarantine-override.ts` — #6259 (fix wave 12): the `quarantine_override` frontmatter key `gbrain quarantine clear --force` records: `{ binding, cleared_at }`, where `binding` is a sha256 over the classifier's inputs (title, type, body) as the gate canonicalizes them (`quarantineOverrideFor`). `assessImportSanity` (`import-screen.ts`) wraps its verdict in `withQuarantineOverride`, which removes the junk-pattern, literal and markup-flag outcomes while the binding is current (size outcomes stay). `importFromContent` calls `settleQuarantineOverride` at its gate-owned strip: remote input loses any override and keeps the stored one only while the binding still holds (so a remote tag edit does not re-hide the page); trusted input keeps its own only while current; a current override also drops classifier markers the content still carries. Company-brain inspection refuses files carrying it (`hidden_input`). Doctor's quarantine row names `clear <slug> --force` and `content_sanity.disabled_patterns`.
+- `src/core/quarantine-override.ts` — #6259 (fix wave 12): the `quarantine_override` frontmatter key `gbrain quarantine clear --force` records: `{ binding, cleared_at }`, where `binding` is a sha256 over the classifier's inputs (title, type, body) as the gate canonicalizes them (`quarantineOverrideFor`). `assessImportSanity` (`import-screen.ts`) wraps its verdict in `withQuarantineOverride`, which removes the junk-pattern, literal and markup-flag outcomes while the binding is current (size outcomes stay). `importFromContent` calls `settleGateOwnedMarkers` (which also owns the #1699 remote strip of `quarantine`, `content_flag`, `embed_skip` and `atoms_scan_hash`): remote input loses any override and keeps the stored one only while the binding still holds (so a remote tag edit does not re-hide the page); trusted input keeps its own only while current; a current override also drops classifier markers the content still carries. Company-brain inspection refuses files carrying it (`hidden_input`). Doctor's quarantine row names `clear <slug> --force` and `content_sanity.disabled_patterns`.
- `src/commands/quarantine.ts` — `gbrain quarantine <list|clear|scan>` operator surface for the content-quality gate. `list [--json] [--include-flagged]` paginates `listPages` and reports quarantined (HIDDEN) pages, optionally also `content_flag` (FLAGGED, searchable) pages. `clear <slug> [--force] [--no-embed] [--json]` drops both markers and re-imports through the normal pipeline so the page re-chunks + re-embeds and becomes searchable; the gate re-runs on import so genuinely-junk pages re-quarantine (exit 1) unless `--force` sets `GBRAIN_NO_SANITY=1` for that one import. `scan [--limit N] [--apply] [--no-embed] [--json]` re-assesses already-ingested pages so junk predating the gate gets marked (unchanged content short-circuits normal sync, so it never re-assesses otherwise); dry-run uses the SAME effective `content_sanity` config thresholds `--apply` will use, idempotent (skips already-marked pages), `--apply` re-imports with `forceRechunk` to set markers + (for quarantine) drop chunks. Dispatched in `cli.ts`. Pinned by `test/quarantine-cli.test.ts`. #6259: `clear` reads one snapshot (page, tags, revision) and, on a managed brain, publishes through `submitPageMutation` with that `expected_revision` (a concurrent edit is a `revision_conflict`, a pending receipt is reported as pending); `--force` writes a `quarantine_override` (see `src/core/quarantine-override.ts`) instead of disabling the gate, never mutation `force`. `scan --apply` refuses `writer_coordinator_required` on a managed brain. It is a router (`QUARANTINE_SUBCOMMANDS`, `printUsage`). Tests: `test/quarantine-override.serial.test.ts`, `test/quarantine-cli.test.ts`.
- `src/commands/recall.ts` — the `gbrain recall` CLI (facts-first by default; local engine or thin-client). A malformed `--limit` (not a positive safe integer, or missing) throws `invalid_params` from `parseFlags`, so the CLI exits 2 through `renderCliError`: the v1 envelope under `--json` with `why` and a `fix` that reruns the same argv with `--limit 50`, and the Error/Fix/Why lines otherwise (`test/recall-limit-envelope.test.ts`). Optional `--budget-policy facts_first|query_first` routes a one-shot read through the shared operation, forwarding fact filters and using remote recall on thin clients. Enum validation uses the shared operation definition; option order does not affect budget parsing. Only query-first with a nonblank query preserves numeric fractions until server packing; omitted/explicit facts-first keeps legacy integer parsing. The new option rejects watch/cursor/rollup/as-context combinations rather than silently ignoring them. Opt-in selector failures use stamped v1 errors; JSON mode emits structured local and remote errors on stdout with a nonzero exit, preserving remote read-error details without requiring a mutation receipt. Omitted-policy validation and fallback remain unchanged. Entity→text fallback: a bare positional without verb options is entity-first, but when the entity arm matches ZERO facts (and no `--grep`/`--supersessions`/`--session-id` narrows the read), the query retries as SQL-level fact-text grep with a stderr note. One predicate and note formatter are shared by the local path and thin-client mirror; explicit grep callers keep exact semantics. `--since` composes with entity and session in one query before LIMIT, on event time unless `--since-last-run`. Local `--grep` is passed to every engine arm (ILIKE with escaped metacharacters, before LIMIT); only `--supersessions` keeps the client-side filter. Pinned by `test/recall-grep-local-cli.test.ts`. Pinned by `test/facts-recall-since-composition.test.ts`, `test/recall-budget-policy-transports.test.ts`, `test/recall-budget-policy-thin-cli.test.ts`, and `test/recall-budget-policy-thin.serial.test.ts`.
diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.md
index 589058ce57..33abcf97db 100644
--- a/docs/architecture/key-files/providers.md
+++ b/docs/architecture/key-files/providers.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/embedding-readiness.ts` — bounded source-aware recovery through canonical projection snapshots, queued intent, preparation and guarded installation. Global readiness remains archive-visible. Plain stale repair selects active sources for recovery and separately reports archived stranded work, so live pages can progress without pretending the whole brain completed. `countArchivedEmbeddingWork` classifies archived NULL vectors, non-NULL hash drift, signature work, contentful chunkless pages and, for migration, pending projections before authorization. Repair queues and snapshots require a live source under the existing source-before-page guard; unsupported pages remain blocked, never revision-stamped. The invalidation SQL additionally excludes unsealed projections. #6223: repair walks a keyset cursor (each candidate once per call, ending on a short batch), so a batch of image/media pages only their importer can rebuild never hides repairable pages behind it; `listPendingProjectionPages` lists the first blocked pages for the caller's report. `embed --stale` and `embedStaleForSource` no longer stop when pages stay blocked: the guarded drain skips their unsealed snapshots (the CLI counts their chunks as failures and names them with `gbrain embed --stale --images`; the source drain adds them to `blocked` and stays incomplete).
+- `src/core/embedding-readiness.ts` — bounded source-aware recovery through canonical projection snapshots, queued intent, preparation and guarded installation. Global readiness remains archive-visible. Plain stale repair selects active sources for recovery and separately reports archived stranded work, so live pages can progress without pretending the whole brain completed. `countArchivedEmbeddingWork` classifies archived NULL vectors, non-NULL hash drift, signature work, contentful chunkless pages and, for migration, pending projections before authorization. Repair queues and snapshots require a live source under the existing source-before-page guard; unsupported pages remain blocked, never revision-stamped. The invalidation SQL additionally excludes unsealed projections. #6223: repair walks a keyset cursor (each candidate once per call, ending on a short batch), so a batch of image/media pages only their importer can rebuild never hides repairable pages behind it; `listPendingProjectionPages` lists the first blocked pages and `reportBlockedProjections` writes the CLI's failure sample. `embed --stale` and `embedStaleForSource` no longer stop when pages stay blocked: the guarded drain skips their unsealed snapshots (the CLI counts their chunks as failures and names them with `gbrain embed --stale --images`; the source drain adds them to `blocked` and stays incomplete).
- `src/core/embedding-migration-retention.ts` — fail-closed retained-vector rebuildability check shared by migration preflight, direct apply, schema transition, pinned-column repair and invalidation/config transactions. Transaction-local SHARE locks freeze source/page/vector/withdrawal/config eligibility during the census and mutation. Sealed importer text chunks can be embedded and oversized chunks healed without regenerating their source projection; unsealed unsupported media still refuses. Width changes protect archived, skipped, deleted and unrebuildable retained page vectors; same-width checks match the shared false-stamp predicate, signature gate and current-space test. Archived pending work, including same-target content drift, metadata-only restamping, NULL vectors and chunkless pages, refuses before authorization or provider work; correct target-stamped archived vectors, including grandfathered NULL hashes, are retained controls. Companion retention checks follow actual schema/pinned-width changes and the same-target persisted migration marker; the guard returns the locked companion-clear decision consumed by the writer, ignoring a different target's completed-clear flag. Schema-only work leaves takes untouched. Existing fact eligibility and deliberate expiry/supersession/audit/withdrawal policy remain unchanged. Unknown registry, width or census fails closed. The source census includes archive state, but embed leases are not archive coordination. Synthetic two-engine regressions cover preservation refusals, real imported-image migration, same-target companion preservation, retarget/first-clear refusal and fail-closed metadata. Completion counts remain archive-visible; refusal never restores a source automatically.
- `src/core/embedding-migration-budget.ts` — finite authorization in the existing migration marker. Each provider attempt reserves its maximum input price under the acquired leases and a `FOR UPDATE` on the marker row, and records a pending entry keyed by attempt id; `settle(usage)` takes the same lock and replaces the reservation with the reported usage (refund or overshoot). Idempotent per (`authorization_generation`, attempt id): a repeated or stale-generation settle is a no-op, so a crash before settlement keeps the maximum. Missing usage keeps the maximum. Usage above the reservation debits actual, adds `overshoot_usd` and sets `halted`, which refuses further dispatch until an explicit `--max-cost-usd` renewal. `authorizeMigrationBudget(..., worstCase)` throws `MigrationBudgetRefusal` (`embedding_budget_below_worst_case`, with cap, worst case, retained debits, the filled `--max-cost-usd` command and the `write-refusals.md` anchor) before writing any state when the cap is below debits + worst case. Refusal copy prints the operator's cap, never a remainder. Resume preserves every debit; unknown prices or missing input bounds refuse. Marker corruption cannot erase a versioned authorization. Only an explicitly reauthorized legacy marker without authorization fields can be replaced.
- `src/core/embedding-migration-worst-case.ts` — `planMigrationWorstCase(engine, plan, { rerankerModel })`: Σ per-request maximum input from `embed-batch-plan.ts` over what the run sends (target probe, the drain's two probes, stale chunks per page (including content drift: a stored text hash that no longer matches) split by `healOversizedChunks` at the target chunk size over the complete page (a split re-indexes siblings, so every healed chunk of that page counts) and wrapped with `wrapChunkTextsForStoredMode`, the chunks projection recovery and the chunkless heal will create — replayed through `readProjectionSnapshot` + `preparePageProjection` at the current chunk size then the target-size heal, and directly at the target size, keeping the larger ceiling, replacing those pages' existing chunks — stale facts in 100-row per-source batches, three smoke-check queries, the reranker probe when switching), priced with operator overrides. `usd` is null only when the embedding model is unpriced; an unpriced reranker lands in `unpriced_models` and the embedding bound is still enforced. Owns the migration and reranker probe texts. Computed at plan time for the printed estimate and again under the migration locks for the refusal.
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index 9fd6458f34..b38dcc7f60 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -1,5 +1,5 @@
import { sanitizeRemoteBody } from '../core/remote-body.ts';
-import { prepareEmbeddingProjections, countArchivedEmbeddingWork, listPendingProjectionPages } from '../core/embedding-readiness.ts';
+import { prepareEmbeddingProjections, countArchivedEmbeddingWork, reportBlockedProjections } from '../core/embedding-readiness.ts';
import { embedStaleFacts, type EmbedFactsResult } from '../core/embed-facts.ts';
import { embedTakesForStaleDrain, type EmbedTakesResult } from '../core/embed-takes.ts';
import { parseFactEmbedArgs } from './embed-facts-delegate.ts';
@@ -1646,21 +1646,8 @@ async function embedAllStale(
readiness = await prepareEmbeddingProjections(engine, { ...readinessOptions, repair: true, assertOwned: staleOpts?.assertOwned });
if (isAborted(externalSignal) || Date.now() >= (readinessOptions.deadline ?? Infinity)) return await noteBudgetStop();
}
- // #6223: pages still waiting for a projection after bounded recovery never
- // block the rest of the source. The guarded drain below refuses their
- // unsealed snapshots, counts their stale chunks as failures and installs no
- // vector for them; everything else embeds in this run.
- const blockedPages = readiness.blocked && !dryRun ? await listPendingProjectionPages(engine, readinessOptions) : [];
- const blockedProjections = new Set(blockedPages.map(page => `${page.source_id}::${page.slug}`));
- if (readiness.blocked && !dryRun) {
- const media = blockedPages.some(page => page.page_kind !== 'markdown' && page.page_kind !== 'code');
- const named = blockedPages.slice(0, 5);
- const more = readiness.blocked > named.length ? ` and ${readiness.blocked - named.length} more` : '';
- const sourceArg = sourceId ? ` --source ${sourceId}` : '';
- result.failure_samples.push(`${readiness.blocked} page(s) still need a text projection, so their chunks were not embedded (${named.map(page => `${page.source_id}:${page.slug}`).join(', ')}${more}); every other stale chunk was embedded. `
- + (media ? `Image and media pages are rebuilt only by their importer: run gbrain embed --stale --images${sourceArg} (needs GBRAIN_EMBEDDING_MULTIMODAL=true) or gbrain sync --full${sourceArg}. ` : '')
- + 'Rerun gbrain embed --stale to retry bounded projection recovery.');
- }
+ // #6223: pages still blocked after bounded recovery never stop the run; the guarded drain counts them.
+ const blockedProjections = readiness.blocked && !dryRun ? await reportBlockedProjections(engine, readinessOptions, readiness.blocked, result.failure_samples) : new Set<string>();
// Chunkless-page safety net: pre-flight count mirrors the countStaleChunks
// short-circuit just below — a healthy brain pays one extra SELECT
@@ -2035,7 +2022,6 @@ async function embedAllStale(
if (!prepared) {
// #5804: a page edited, deleted or unsealed mid-run is a counted failure, not a silent
// skip. An archived source is left to reportArchived, which already counts its pages.
- // #6223: a page already reported as waiting for its projection is counted, not renamed.
const [source] = await observed(pacer, () => engine.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id = $1', [keySourceId]));
if (!source?.archived) { result.failures += stale.length; if (!blockedProjections.has(key)) unavailablePages.set(key, slug); }
return;
diff --git a/src/commands/quarantine.ts b/src/commands/quarantine.ts
index 339139d1ff..8344fb6152 100644
--- a/src/commands/quarantine.ts
+++ b/src/commands/quarantine.ts
@@ -311,7 +311,7 @@ async function runScan(engine: BrainEngine, args: string[]): Promise<void> {
// brain publishes only through its canonical owner, so refuse up front.
if (apply && await managedPersistenceEnabled(engine)) {
const error = opError('writer_coordinator_required', 'quarantine scan --apply cannot rewrite pages on a managed brain.',
- 'It re-imports every page outside the canonical owner, so nothing was changed. Preview with gbrain quarantine scan (no --apply); new imports already pass the gate. Review hidden pages with gbrain quarantine list and clear a false positive with gbrain quarantine clear <slug> --force.',
+ 'It re-imports every page outside the canonical owner, so nothing was changed. Preview with gbrain quarantine scan (no --apply); new imports already pass the gate. Review hidden pages with gbrain quarantine list, then clear a false positive by passing its slug to gbrain quarantine clear with --force.',
{ fix: readFix('Previews what the gate would mark, read-only.', { argv: ['gbrain', 'quarantine', 'scan', '--json'] }) });
if (!await reportPersistenceCliError(error, json)) throw error;
return;
diff --git a/src/core/embedding-readiness.ts b/src/core/embedding-readiness.ts
index 334142fabf..8e3373912a 100644
--- a/src/core/embedding-readiness.ts
+++ b/src/core/embedding-readiness.ts
@@ -54,6 +54,25 @@ export async function listPendingProjectionPages(engine: BrainEngine, opts: Proj
JOIN sources s ON s.id=p.source_id WHERE ${where} AND NOT s.archived ORDER BY p.id LIMIT $${params.length + 1}`, [...params, limit]);
}
+/**
+ * #6223: `embed --stale` keeps going when bounded recovery leaves pages
+ * blocked; this adds one failure sample naming the first of them (and the
+ * importer route for image/media pages) and returns the keys
+ * (`source_id::slug`) of the pages it listed, so the drain counts their chunks
+ * without renaming them as pages that changed mid-run.
+ */
+export async function reportBlockedProjections(engine: BrainEngine, opts: ProjectionScope & { sourceId?: string }, blocked: number, samples: string[]): Promise<Set<string>> {
+ const pages = await listPendingProjectionPages(engine, opts);
+ const named = pages.slice(0, 5);
+ const more = blocked > named.length ? ` and ${blocked - named.length} more` : '';
+ const sourceArg = opts.sourceId ? ` --source ${opts.sourceId}` : '';
+ samples.push(`${blocked} page(s) still need a text projection, so their chunks were not embedded (${named.map(page => `${page.source_id}:${page.slug}`).join(', ')}${more}); every other stale chunk was embedded. `
+ + (pages.some(page => page.page_kind !== 'markdown' && page.page_kind !== 'code')
+ ? `Image and media pages are rebuilt only by their importer: run gbrain embed --stale --images${sourceArg} (needs GBRAIN_EMBEDDING_MULTIMODAL=true) or gbrain sync --full${sourceArg}. ` : '')
+ + 'Rerun gbrain embed --stale to retry bounded projection recovery.');
+ return new Set(pages.map(page => `${page.source_id}::${page.slug}`));
+}
+
export async function prepareEmbeddingProjections(engine: BrainEngine, opts: { sourceId?: string; limit?: number; repair?: boolean; existingChunksOnly?: boolean; activeSourcesOnly?: boolean; stale?: { signature?: string; includeNullSignature?: boolean }; signal?: AbortSignal; deadline?: number; assertOwned?: (tx?: BrainEngine) => Promise<void> } = {}) {
const limit = Math.max(1, Math.min(opts.limit ?? 100, 100));
const { where, params } = await pendingProjectionWhere(engine, opts);
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index ff62d2ddd1..eac0ec739b 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 { settleQuarantineOverride } 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';
@@ -353,26 +353,8 @@ export async function importFromContent(
parsed.compiled_truth = sanitizeText(parsed.compiled_truth);
parsed.timeline = sanitizeText(parsed.timeline);
- // v0.42 (#1699 trust boundary): strip gate-owned markers from UNTRUSTED
- // input. parseMarkdown preserves every frontmatter key except type/title/
- // tags/slug, so a remote MCP put_page (ctx.remote !== false, threaded as
- // opts.remote) could otherwise plant `quarantine` (hide a page from search +
- // suppress chunks) or `content_flag.detail` (inject text into the agent's
- // trusted "this looks odd" channel) on clean content. Only the content-
- // sanity gate (below) and trusted local CLIs may set these. Fail-closed:
- // strip whenever opts.remote === true.
- await settleQuarantineOverride(engine, parsed, slug, sourceId, opts.remote === true);
- if (opts.remote === true && parsed.frontmatter) {
- delete parsed.frontmatter[QUARANTINE_KEY];
- delete parsed.frontmatter[CONTENT_FLAG_KEY];
- delete parsed.frontmatter[EMBED_SKIP_KEY];
- // #1699 part 2: the extract_atoms completion marker is phase-owned. A
- // remote writer planting a matching marker would suppress atom mining
- // for the page (a silent extraction bypass); planting a stale one is
- // harmless but still not the caller's to set. Trusted local sync/export
- // round-trips (remote unset/false) preserve it.
- delete parsed.frontmatter[ATOMS_SCAN_HASH_KEY];
- }
+ // #1699 trust boundary: only the gate and trusted local callers set gate-owned markers (quarantine-override.ts).
+ await settleGateOwnedMarkers(engine, parsed, slug, sourceId, opts.remote === true);
// Vendor-neutral guardrail seam (observe-only, fail-open). Runs AFTER
// parseMarkdown and the size guard, BEFORE content-sanity, hash compute,
diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.ts
index a043355565..f5b84b2963 100644
--- a/src/core/persistence/facts-maintenance.ts
+++ b/src/core/persistence/facts-maintenance.ts
@@ -5,7 +5,7 @@ import type { FactsBackstopCtx } from '../facts/backstop.ts';
import { factEventTime } from '../facts/event-time.ts';
import { ENTITY_HINTS_CAP, type ExtractedFact, type FactEmbeddingSignature } from '../facts/extract.ts';
import { readFactsEmbeddingDim } from '../embedding-dim-check.ts';
-import { getEmbeddingModel } from '../ai/gateway.ts';
+import { currentEmbeddingSignature } from '../embedding.ts';
import type { OperationContext } from '../ops/contract.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { hostFix, opTransport, readFix } from '../ops/op-fix.ts';
@@ -120,8 +120,8 @@ export async function resolveManagedFactsEmbedding(engine: BrainEngine, config:
const dimensions = /^[1-9]\d*$/.test(values.embedding_dimensions ?? '') ? Number(values.embedding_dimensions) : null;
if (!/[:/]/.test(model) && /^[^\s]+$/.test(model) && dimensions) {
// #6113: a legacy row stores the model without its provider. Name the one supported rewrite (a preview first).
- let gateway: string | null = null;
- try { gateway = getEmbeddingModel(); } catch { /* unconfigured gateway: no provider to suggest */ }
+ const signature = currentEmbeddingSignature();
+ const gateway = signature ? signature.slice(0, signature.lastIndexOf(':')) : null;
const target = gateway?.endsWith(`:${model}`) ? gateway : null;
throw opError('embedding_configuration', 'The selected brain records its embedding model without a provider, so facts cannot be embedded.',
`The brain's embedding_model row is ${JSON.stringify(model)} with no provider prefix (a row from an older install), so fact extraction stopped before admission; gbrain config set cannot change it. `
diff --git a/src/core/quarantine-override.ts b/src/core/quarantine-override.ts
index a3756dd7c6..276438e41d 100644
--- a/src/core/quarantine-override.ts
+++ b/src/core/quarantine-override.ts
@@ -12,7 +12,7 @@
* are not overridden.
*
* Trust: only trusted local callers set it. Every untrusted ingress strips it
- * (the gate-owned strip in `import-file.ts`, which remote put_page,
+ * (`settleGateOwnedMarkers`, called by `importFromContent`, which remote put_page,
* put_pages, HTTP and ingest-capture all reach through `remote: true`); a
* remote edit that leaves title, type and body unchanged carries the stored
* override forward, so an unrelated tag edit does not re-hide the page.
@@ -24,6 +24,8 @@ import { parseMarkdown, type ParsedMarkdown } from './markdown.ts';
import { sanitizeText } from './batch-rows.ts';
import { sha256 } from './persistence/digest.ts';
import { CONTENT_FLAG_KEY, QUARANTINE_KEY } from './quarantine.ts';
+import { EMBED_SKIP_KEY } from './embed-skip.ts';
+import { ATOMS_SCAN_HASH_KEY } from './utils.ts';
export const QUARANTINE_OVERRIDE_KEY = 'quarantine_override';
@@ -56,15 +58,28 @@ export function hasCurrentQuarantineOverride(page: Bound & { frontmatter?: Recor
}
/**
- * Called by the import gate before it assesses `parsed` (already canonicalized).
- * Remote input loses any override it carries, then keeps the stored one only
- * when it still binds this content; trusted input keeps its own override only
- * while it binds. A stale or malformed override is dropped.
+ * Called by `importFromContent` before the gate assesses `parsed` (already canonicalized).
+ *
+ * v0.42 (#1699 trust boundary): gate-owned markers are stripped from
+ * UNTRUSTED input. parseMarkdown preserves every frontmatter key except
+ * type/title/tags/slug, so a remote MCP put_page (ctx.remote !== false,
+ * threaded as opts.remote) could otherwise plant `quarantine` (hide a page
+ * from search + suppress chunks), `content_flag.detail` (inject text into the
+ * agent's trusted "this looks odd" channel) or `embed_skip` on clean content.
+ * #1699 part 2: the extract_atoms completion marker is phase-owned; a remote
+ * writer planting a matching one would suppress atom mining for the page.
+ * Trusted local sync/export round-trips keep them. Fail-closed: strip
+ * whenever `remote` is true.
+ *
+ * #6259: remote input also loses any `quarantine_override`, then keeps the
+ * stored one only when it still binds this content; trusted input keeps its
+ * own override only while it binds. A stale or malformed override is dropped,
+ * and a current one drops classifier markers the content still carries.
*/
-export async function settleQuarantineOverride(engine: Pick<BrainEngine, 'executeRaw'>, parsed: ParsedMarkdown,
+export async function settleGateOwnedMarkers(engine: Pick<BrainEngine, 'executeRaw'>, parsed: ParsedMarkdown,
slug: string, sourceId: string | undefined, remote: boolean): Promise<void> {
if (remote) {
- delete parsed.frontmatter[QUARANTINE_OVERRIDE_KEY];
+ for (const key of [QUARANTINE_KEY, CONTENT_FLAG_KEY, EMBED_SKIP_KEY, ATOMS_SCAN_HASH_KEY, QUARANTINE_OVERRIDE_KEY]) delete parsed.frontmatter[key];
const [stored] = await engine.executeRaw<{ override: unknown }>(
`SELECT frontmatter->'${QUARANTINE_OVERRIDE_KEY}' AS override FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL`, [sourceId ?? 'default', slug]);
const carried = overrideOf(stored?.override);
diff --git a/test/persistence-git-coalescing-5530.slow.test.ts b/test/persistence-git-coalescing-5530.slow.test.ts
index 93ba2c18fd..4725a492b6 100644
--- a/test/persistence-git-coalescing-5530.slow.test.ts
+++ b/test/persistence-git-coalescing-5530.slow.test.ts
@@ -347,10 +347,11 @@ for (const kind of testBackends()) describe(`#6210 native Git durability probe f
}), 300_000);
test.each([
- ['damaged HEAD', (repo: Repo) => writeFileSync(join(repo.root, '.git', 'HEAD'), 'not a ref\n')],
- ['dubious ownership', () => { process.env.GIT_TEST_ASSUME_DIFFERENT_OWNER = '1'; }],
- ['a directory at the hook path', (repo: Repo) => { const hook = join(repo.root, '.git', 'custom-hooks', 'post-commit'); rmSync(hook); mkdirSync(hook); }],
- ])('%s keeps Git effects unfinished with git_unavailable', (_name, damage) => withBrain(kind, async ({ engine, home, ctx }) => {
+ ['damaged HEAD', (repo: Repo) => { writeFileSync(join(repo.root, '.git', 'HEAD'), 'not a ref\n'); return {}; }],
+ // Git's own switch for the "dubious ownership" refusal a checkout owned by another user gets.
+ ['dubious ownership', () => ({ GIT_TEST_ASSUME_DIFFERENT_OWNER: '1' })],
+ ['a directory at the hook path', (repo: Repo) => { const hook = join(repo.root, '.git', 'custom-hooks', 'post-commit'); rmSync(hook); mkdirSync(hook); return {}; }],
+ ] as Array<[string, (repo: Repo) => Record<string, string>]>)('%s keeps Git effects unfinished with git_unavailable', (_name, damage) => withBrain(kind, async ({ engine, home, ctx }) => {
const repo = makeRepo(home, 'content');
await bindSource(engine, 'default', repo);
await activateSharedSkillPersistence(engine, { confirmQuiesced: true });
@@ -358,9 +359,9 @@ for (const kind of testBackends()) describe(`#6210 native Git durability probe f
await pauseGitEffects(engine, () => seed(ctx('default'), 2));
const before = repo.commits();
try {
- damage(repo);
- await release(engine); await pass(engine);
- } finally { delete process.env.GIT_TEST_ASSUME_DIFFERENT_OWNER; writeFileSync(join(repo.root, '.git', 'HEAD'), 'ref: refs/heads/main\n'); }
+ const env = damage(repo);
+ await withEnv(env, async () => { await release(engine); await pass(engine); });
+ } finally { writeFileSync(join(repo.root, '.git', 'HEAD'), 'ref: refs/heads/main\n'); }
await expectUnfinished(engine, 2);
expect(repo.commits()).toBe(before); expect(repo.pushes()).toBe(0);
}), 300_000);
diff --git a/test/quarantine-override.serial.test.ts b/test/quarantine-override.serial.test.ts
index dfb9d2787c..0cecf65738 100644
--- a/test/quarantine-override.serial.test.ts
+++ b/test/quarantine-override.serial.test.ts
@@ -168,7 +168,7 @@ describe('quarantine clear on a managed brain (#6259)', () => {
const before = await engine.executeRaw('SELECT slug,knowledge_revision FROM pages ORDER BY id');
const { err } = await capture(() => runQuarantine(engine, ['scan', '--apply']));
expect(err).toContain('writer_coordinator_required');
- expect(err).toContain('gbrain quarantine clear <slug> --force');
+ expect(err).toContain('passing its slug to gbrain quarantine clear with --force');
expect(currentExitCode()).toBe(1);
expect(await engine.executeRaw('SELECT slug,knowledge_revision FROM pages ORDER BY id')).toEqual(before);
}), 120_000);