Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(import): a code page carrying a facts/takes fence marker is never sealed safe (D-NEW-2)

time-attackbe9b5b030bb5
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index 57bc0d1128..c805edcba7 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -11,7 +11,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/return-policy.ts` (default OFF) — intent-aware adaptive return-sizing. Pure, dependency-light module that trims the final ranked candidate set to an intent-driven cap instead of returning the full top-K. `entity` intent gets a tight cap; `temporal`/`event`/`general` get a recall-preserving cap (`concept` is coerced to `general` by `hybrid.ts` before the call — concept queries want breadth). A `minKeep` failsafe (≥1) guarantees a human never gets a silent blank when candidates exist. WHY a cap, not a score-cliff detector: PrecisionMemBench instrumentation (gbrain-evals) measured the rank1→rank2 RRF gap is ~identical whether rank-1 is correct (0.602) or wrong (0.569) — mechanical decay, not a separatrix; rank-1 is right in 94% of single-answer cases, so "return a tight set" is the whole win and cliff-cutting just adds noise. Exports `AdaptiveReturnConfig`, `DEFAULT_ADAPTIVE_RETURN` (frozen: `enabled=false`, `entityMax=2`, `otherMax=6`, `minKeep=1`), `AdaptiveReturnDecision` (`{applied, intent, cap, kept, total}`), `AdaptiveReturnInput` (`boolean | Partial<AdaptiveReturnConfig> | undefined`), `adaptiveReturnFromConfig(cfg)`, `resolveAdaptiveReturn(perCall, fromConfig)` (defaults → config → per-call merge), `adaptiveReturnEnabled(...)` (cache-skip gate check), `applyAdaptiveReturn(results, intent, cfg)` (the trim). Config knobs (DB or file plane): `search.adaptive_return` (master switch), `search.adaptive_return_entity_max`, `search.adaptive_return_other_max`, `search.adaptive_return_min_keep` (each clamped ≥1). Wired into `hybridSearch` AFTER `applyReranker`, BEFORE the `limit` slice, and ONLY on the first page (`offset===0`) — paginating a confidence-gated set is incoherent, so paginated calls fall through to the fixed limit. Stamps the decision onto `HybridSearchMeta.adaptive_return` for `gbrain search --explain`. `hybridSearchCached` SKIPS the cache when the gate is on (a trimmed set must not be served to a gate-off lookup and vice versa). `SearchOpts.adaptiveReturn` + `HybridSearchMeta.adaptive_return` declared in `src/core/types.ts`. Agent-facing: the `query` op (`src/core/operations.ts`) exposes an `adaptive_return` boolean param whose description instructs the agent WHEN to set it (single-answer → on; breadth/exploration → off; pass `limit:1` for a hard single-answer cap), threaded into `hybridSearchCached` — end users never touch the config knob; their agent decides per query (same pattern as `salience`/`recency`). Pinned by `test/search/return-policy.test.ts` (mechanism) + `test/search/query-op-adaptive-return.test.ts` (agent surface: param exists + description teaches both directions + the never-empty contract).
-- `src/core/search/safe-chunks.ts` — shared current-revision and remote safe-chunk predicates. `currentTextProjectionFilter` emits `(text_projection_revision = knowledge_revision) IS TRUE`, preserving NULL exclusion while allowing expression statistics to guide the planner. Visibility and revision predicates stay inside candidate selection. Body/chunk changes invalidate the safe index until a guarded rebuild. `belowSafeChunkFence` is the page-level predicate shared by the importers' unchanged-content re-seal and the drain.
+- `src/core/search/safe-chunks.ts` — shared current-revision and remote safe-chunk predicates. `currentTextProjectionFilter` emits `(text_projection_revision = knowledge_revision) IS TRUE`, preserving NULL exclusion while allowing expression statistics to guide the planner. Visibility and revision predicates stay inside candidate selection. Body/chunk changes invalidate the safe index until a guarded rebuild. `belowSafeChunkFence` is the page-level predicate shared by the importers' unchanged-content re-seal and the drain. `protectedCodeFilter` marks code pages whose body carries a facts/takes fence marker: the code chunker keeps text verbatim, so code import and projection re-seal stamp them `-1` (never safe), and re-seal, `repair safe-chunks` and doctor's `safe_index_pending` leave them out of the re-sealable set (`test/code-import-protected-fence.test.ts`, both engines).
- `src/core/search/source-boost.ts` — Source-type boost map keyed by slug prefix. `DEFAULT_SOURCE_BOOSTS` (originals/ 1.5, concepts/ 1.3, writing/ 1.4, people/companies/deals/ 1.2, daily/ 0.8, media/x/ 0.7, <fork>/chat/ 0.5, archive/ 0.5, extracts/ 0.3) and `DEFAULT_HARD_EXCLUDES` (test/, attachments/, .raw/). `archive/` is DEMOTED (findable, ranked below curated), not hard-excluded — archive holds high-signal history users expect to retrieve; the demote is a prior at the SQL/fusion layer and the cross-encoder reranker can still promote a strongly-matching archive page. `parseSourceBoostEnv`/`parseHardExcludesEnv` parse comma-separated `prefix:factor` pairs from `GBRAIN_SOURCE_BOOST`/`GBRAIN_SEARCH_EXCLUDE`. `resolveBoostMap(env, config)` layers defaults (dropped by a `none` entry), the brain's `search.source_boosts` config and the env override; hybridSearch resolves it once from the mode config snapshot and passes it to the engines as `SearchOpts.source_boosts` (engines fall back to defaults + env when absent; the keyword-only `search` op branch reads the key itself). `resolveHardExcludes` merges defaults + env + caller `SearchOpts.exclude_slug_prefixes`/`include_slug_prefixes`. The surviving exclude policy is auditable via the `hidden_by_search_policy` doctor check (`src/commands/doctor/checks/calibration.ts`, local + remote paths) which counts chunked pages withheld per active exclude prefix, reusing `resolveHardExcludes` + `buildVisibilityClause` + the exported `escapeLikePattern`.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index f952f15980..40e1439d89 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -124,7 +124,7 @@ should also check `results[].complete`.
| `orphan-bindings` | `orphan_persistence_bindings` | Deletes persistence source bindings whose source was removed, or that belong to an earlier incarnation of a source re-added under the same id. `gbrain sources remove` and `gbrain sources purge` delete the binding; one an older gbrain left behind makes the re-added source read as claimed, so every `gbrain sync --source <id>` fails with `writer_coordinator_required`. Bookkeeping only: no journal admission, no page or file changes, and it runs brain-wide (`--source` does not narrow it). See [orphan bindings](#orphan-bindings). | A binding that a queued, running or recovering write request of the same source incarnation still references. |
| `embedding-effects` | `stale_embedding_effects` | Settles stale queued and failed embedding effects of committed writes, which block receipt compaction and activation: `reconciled` when current vectors pass the effect verifier, `superseded` when the page was deleted or a newer revision owns its own effect, `retry_queued` for the owner (paid; a used-up retry allowance gets one new bounded cycle per explicit apply). See [stale queued embedding effects](#stale-queued-embedding-effects). | `blocked` effects, counted by reason (`owner_unavailable`, `embedding_disabled`, `embedding_unconfigured`, `projection_pending`, `no_replacement_obligation`). |
| `attribution-backfill` | none | Fills write attribution (who wrote it) on pages, page versions and facts written before attribution was recorded, only where exactly one committed request in the write journal proves the writer: the page write whose recorded result is the row's revision, or the `remember` that inserted the fact. Fills NULLs only, in committed batches of 1,000 that resume after an interruption; no content, revision, page file or request ID changes. See [write attribution](../mcp/ADMIN.md#write-attribution). | `unrecorded_pages`, `unrecorded_page_versions`, `unrecorded_facts`: rows the journal cannot prove. They stay `unrecorded`; nothing is inferred. |
-| `safe-chunks` | `safe_index_pending` (also `contextual_retrieval_coverage`, `details.unsealed_pages`) | Rebuilds the chunks of markdown and code pages indexed before the safe-chunk fence, which remote and MCP search withhold. It rebuilds projections only: no page write, no new page version and no request ID. Vectors whose embedding input did not change are kept; the rest are embedded unless you pass `--no-embed` or no embedding model is configured. | `code_without_source_path`: code pages with no recorded file to re-chunk. `unsupported_page_kind`: other page kinds, such as images. Their importer re-seals them. |
+| `safe-chunks` | `safe_index_pending` (also `contextual_retrieval_coverage`, `details.unsealed_pages`) | Rebuilds the chunks of markdown and code pages indexed before the safe-chunk fence, which remote and MCP search withhold. It rebuilds projections only: no page write, no new page version and no request ID. Vectors whose embedding input did not change are kept; the rest are embedded unless you pass `--no-embed` or no embedding model is configured. | `code_without_source_path`: code pages with no recorded file to re-chunk. `code_with_fence_marker`: code pages whose text contains a facts/takes fence marker; remote reads always withhold them. `unsupported_page_kind`: other page kinds, such as images. Their importer re-seals them. |
| `orphan-children` | `child_table_orphans` (also a `storage_corrupt` error) | Explicit-only. Deletes rows of page child tables (chunks, versions, tags, takes, raw data, timeline, links) whose page row no longer exists, and clears dangling `links.origin_page_id` and `files.page_id` references, each in one statement that rechecks the orphan condition. See [orphan children](#orphan-children). | `torn_pages`: page rows whose stored body cannot be read (torn TOAST). The preview names them; the repair never changes them. |
| `planner-stats` | `planner_stats_stale` | Runs `ANALYZE` on the hot tables (pages, links, facts, takes, content_chunks, timeline_entries) whose planner statistics are stale, so search and graph reads stop planning as slow nested loops. PGLite also resets each table's pending row count; Postgres runs each `ANALYZE` with a 60 s statement timeout and a 2 s lock timeout. No journal admission, no user data changes, brain-wide. | none |
| `contextual-mode` | `contextual_retrieval_coverage` (pages with no recorded mode) | Stamps the contextual retrieval mode on markdown pages imported without one (for example by a large `--no-embed` sync, or by a connector source on an older gbrain), exactly as a fresh import of the page would: the page, source and brain settings decide, and the per-chunk synopsis tier lands at the free title tier. It rebuilds projections only: no page write, no new page version and no request ID. A page whose stored vectors already match the stamped convention keeps them and queues no re-embedding; a page whose embedding input changes has only those vectors cleared and is re-embedded once, unless you pass `--no-embed`. | `unsealed_projection`: pages whose chunks lag their text; `gbrain embed --stale` or `safe-chunks` seals them first, and the next run stamps them. `embed_skip`: pages marked to skip embedding keep their stored vectors and are not stamped. |
diff --git a/src/commands/doctor/checks/safe-index.ts b/src/commands/doctor/checks/safe-index.ts
index e7ab5bbb27..a2e5dfec64 100644
--- a/src/commands/doctor/checks/safe-index.ts
+++ b/src/commands/doctor/checks/safe-index.ts
@@ -7,20 +7,21 @@
*/
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
-import { SAFE_FENCE_CHUNKER_VERSION } from '../../../core/search/safe-chunks.ts';
+import { SAFE_FENCE_CHUNKER_VERSION, protectedCodeFilter } from '../../../core/search/safe-chunks.ts';
export async function safeIndexPendingCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {
const name = 'safe_index_pending';
try {
+ const rebuildablePage = `((p.page_kind='markdown' OR (p.page_kind='code' AND COALESCE(p.frontmatter->>'file',p.source_path) IS NOT NULL)) AND NOT ${protectedCodeFilter('p')})`;
const [row] = await engine.executeRaw<{ rebuildable: number; kept: number }>(`SELECT
- COUNT(*) FILTER (WHERE p.page_kind='markdown' OR (p.page_kind='code' AND COALESCE(p.frontmatter->>'file',p.source_path) IS NOT NULL))::int AS rebuildable,
- COUNT(*) FILTER (WHERE NOT (p.page_kind='markdown' OR (p.page_kind='code' AND COALESCE(p.frontmatter->>'file',p.source_path) IS NOT NULL)))::int AS kept
+ COUNT(*) FILTER (WHERE ${rebuildablePage})::int AS rebuildable,
+ COUNT(*) FILTER (WHERE NOT ${rebuildablePage})::int AS kept
FROM pages p JOIN sources s ON s.id=p.source_id AND s.archived IS NOT TRUE
WHERE p.deleted_at IS NULL AND p.chunker_version < ${SAFE_FENCE_CHUNKER_VERSION} ${sourceIds ? 'AND p.source_id=ANY($1::text[])' : ''}`,
sourceIds ? [sourceIds] : []);
const rebuildable = Number(row?.rebuildable ?? 0), kept = Number(row?.kept ?? 0);
const details = { pages_pending: rebuildable, kept_pages: kept, count: 'exact', truncated: false, repair: 'safe-chunks' };
- const keptNote = kept ? ` ${kept} other page(s) cannot be re-sealed here (code without a recorded source path, or image pages) and are left for their importer.` : '';
+ const keptNote = kept ? ` ${kept} other page(s) cannot be re-sealed here (code without a recorded source path, code containing a facts/takes fence marker, which remote reads always withhold, or image pages) and are left for their importer.` : '';
if (rebuildable === 0) return { name, status: 'ok', details, message: `Every re-sealable page is at the safe-chunk index version.${keptNote}` };
return { name, status: 'warn', details, message: `${rebuildable} page(s) are below the safe-chunk index version, so remote/MCP search withholds their chunks. `
+ `Preview: gbrain repair safe-chunks — apply: gbrain repair safe-chunks --apply.${keptNote}` };
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 0ecee0cbbc..23f00ca2f7 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -1485,7 +1485,7 @@ export async function importCodeFile(
await tx.deleteChunks(slug, txOpts);
}
await tx.executeRaw('UPDATE pages SET chunker_version = $1 WHERE source_id = $2 AND slug = $3',
- [MARKDOWN_CHUNKER_VERSION, txOpts.sourceId, slug]);
+ [hasProtectedBody(storageContent) ? -1 : MARKDOWN_CHUNKER_VERSION, txOpts.sourceId, slug]);
await sealPageTextProjection(tx, slug, txOpts.sourceId);
if (opts.prepare) await installCodeChunkEdges(tx, slug, txOpts.sourceId, code);
};
diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.ts
index 8a9dc9d0db..25cc2d4d71 100644
--- a/src/core/page-state/projections.ts
+++ b/src/core/page-state/projections.ts
@@ -12,7 +12,7 @@ import { quoteIdentifier, resolveWriteColumnFromConfigRows, vectorCastSuffix } f
import { getFtsLanguage } from '../fts-language.ts';
import { getEmbeddingModel } from '../ai/gateway.ts';
import { refreshProjectionStatistics } from '../search/projection-statistics.ts';
-import { belowSafeChunkFence } from '../search/safe-chunks.ts';
+import { belowSafeChunkFence, protectedCodeFilter } from '../search/safe-chunks.ts';
import { acceptedEmbeddingInputHashes, embeddingInputHash, isContextualMode, plainEmbeddingTier, synopsisBodyHash,
type EmbeddingInputContext, type EmbeddingTier } from '../embedding-input-hash.ts';
@@ -174,7 +174,7 @@ export async function installPageProjection(engine: BrainEngine, prepared: Proje
await tx.upsertChunks(slug, chunks, { sourceId, expectedRevision: snapshot.revision, embeddingColumn: context.column });
if (opts.code) await installCodeChunkEdges(tx, slug, sourceId, opts.code);
if (opts.seal) {
- await tx.executeRaw(`UPDATE pages SET chunker_version=$3
+ await tx.executeRaw(`UPDATE pages SET chunker_version=CASE WHEN ${protectedCodeFilter('pages')} THEN -1 ELSE $3 END
WHERE source_id=$1 AND slug=$2`, [sourceId, slug, MARKDOWN_CHUNKER_VERSION]);
await sealPageTextProjection(tx, slug, sourceId, current!);
await tx.executeRaw('DELETE FROM page_projection_jobs WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid', [snapshot.sourceIncarnation, slug, snapshot.revision]);
@@ -249,7 +249,7 @@ export async function queuePageProjection(engine: Pick<BrainEngine, 'executeRaw'
/** #5050/#5247: whether a live page's installed chunks predate the safe-chunk fence. */
export async function projectionBelowSafeFence(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number): Promise<boolean> {
const [row] = await engine.executeRaw<{ chunker_version: number | null }>(
- 'SELECT chunker_version FROM pages WHERE id=$1 AND deleted_at IS NULL', [pageId]) ?? [];
+ `SELECT chunker_version FROM pages WHERE id=$1 AND deleted_at IS NULL AND NOT ${protectedCodeFilter('pages')}`, [pageId]) ?? [];
return row !== undefined && belowSafeChunkFence(row.chunker_version === null ? null : Number(row.chunker_version));
}
diff --git a/src/core/repair/safe-chunks.ts b/src/core/repair/safe-chunks.ts
index d80e011374..18e0f24ae8 100644
--- a/src/core/repair/safe-chunks.ts
+++ b/src/core/repair/safe-chunks.ts
@@ -14,18 +14,20 @@
import type { BrainEngine } from '../engine.ts';
import { resealSafeChunks } from '../page-state/projections.ts';
import { PageRevisionConflictError } from '../page-state/types.ts';
-import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';
+import { SAFE_FENCE_CHUNKER_VERSION, protectedCodeFilter } from '../search/safe-chunks.ts';
import { embedStalePages } from '../embed-stale.ts';
import { afterCursor, type RepairCursor, type RepairHandler, type RepairItem, type RepairScope } from './core.ts';
-interface PendingRow { id: number; source_id: string; slug: string; page_kind: string; rebuildable: boolean; chars: number }
+interface PendingRow { id: number; source_id: string; slug: string; page_kind: string; rebuildable: boolean; protected_code: boolean; chars: number }
export const safeChunksRepair: RepairHandler = {
kind: 'safe-chunks',
publication: 'projection',
async plan(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null) {
const rows = await engine.executeRaw<PendingRow>(`SELECT p.id,p.source_id,p.slug,p.page_kind,
- (p.page_kind='markdown' OR (p.page_kind='code' AND COALESCE(p.frontmatter->>'file',p.source_path) IS NOT NULL)) AS rebuildable,
+ (p.page_kind='markdown' OR (p.page_kind='code' AND COALESCE(p.frontmatter->>'file',p.source_path) IS NOT NULL))
+ AND NOT ${protectedCodeFilter('p')} AS rebuildable,
+ ${protectedCodeFilter('p')} AS protected_code,
length(p.compiled_truth)+length(COALESCE(p.timeline,'')) AS chars
FROM pages p WHERE p.source_id=ANY($1::text[]) AND p.deleted_at IS NULL AND p.chunker_version < ${SAFE_FENCE_CHUNKER_VERSION}
ORDER BY p.id`, [scope.source_ids]);
@@ -35,7 +37,8 @@ export const safeChunksRepair: RepairHandler = {
.filter(item => afterCursor(item.cursor, after));
const kept = rows.filter(row => !row.rebuildable);
return { items, residuals: {
- code_without_source_path: kept.filter(row => row.page_kind === 'code').length,
+ code_without_source_path: kept.filter(row => row.page_kind === 'code' && !row.protected_code).length,
+ code_with_fence_marker: kept.filter(row => row.protected_code).length,
unsupported_page_kind: kept.filter(row => row.page_kind !== 'code').length,
} };
},
diff --git a/src/core/search/safe-chunks.ts b/src/core/search/safe-chunks.ts
index 8e96f4b6af..a2319d2b50 100644
--- a/src/core/search/safe-chunks.ts
+++ b/src/core/search/safe-chunks.ts
@@ -20,6 +20,15 @@ export function protectedBodyFilter(alias: string): string {
}
/** A body-only write cannot certify old fragments, even after fence removal. */
+/**
+ * A code page whose body carries a facts/takes fence marker. The code chunker
+ * keeps source text verbatim, so such a page is never sealed safe: remote
+ * reads withhold it, and re-seal, repair and doctor leave it alone.
+ */
+export function protectedCodeFilter(alias: string): string {
+ return `(${alias}.page_kind = 'code' AND ${protectedBodyFilter(alias)})`;
+}
+
export function bodyWriteChunkVersion(compiledTruth: string, timeline: string): string {
return `CASE WHEN pages.compiled_truth IS NOT DISTINCT FROM ${compiledTruth}
AND pages.timeline IS NOT DISTINCT FROM ${timeline} THEN pages.chunker_version
diff --git a/test/code-import-protected-fence.test.ts b/test/code-import-protected-fence.test.ts
new file mode 100644
index 0000000000..d9c2a1341e
--- /dev/null
+++ b/test/code-import-protected-fence.test.ts
@@ -0,0 +1,78 @@
+/**
+ * D-NEW-2: a code page whose body carries a facts/takes fence marker is never
+ * sealed safe. Authoring gate: (1) protects the code import stamp, the
+ * unchanged re-import re-seal path, `repair safe-chunks` and doctor's
+ * safe_index_pending; (2) fails when a protected code body is admitted to
+ * safe-chunk (remote) reads, or when re-seal stamps it safe again; (3)
+ * test/safe-chunk-reseal.test.ts covers code without markers only; (4) no
+ * production seam. Both engines: PGLite here, PostgreSQL through
+ * test/e2e/code-import-protected-fence-postgres.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importCodeFile } from '../src/core/import-file.ts';
+import { resealSafeChunks } from '../src/core/page-state/projections.ts';
+import { SAFE_FENCE_CHUNKER_VERSION } from '../src/core/search/safe-chunks.ts';
+import { safeChunksRepair } from '../src/core/repair/safe-chunks.ts';
+import { safeIndexPendingCheck } from '../src/commands/doctor/checks/safe-index.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const fenced = 'export const note = `\n<!--- gbrain:facts:begin -->\n| fact | private |\n<!--- gbrain:facts:end -->\n`;\n';
+const plain = 'export function add(a: number, b: number) {\n return a + b;\n}\n';
+
+for (const kind of testBackends()) {
+ describe(`code import with a fence marker (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let fencedSlug = '';
+ beforeAll(async () => {
+ if (kind === 'postgres') {
+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ } else {
+ const pglite = new PGLiteEngine();
+ await pglite.connect({});
+ await pglite.initSchema();
+ engine = pglite;
+ close = () => pglite.disconnect();
+ }
+ }, 120_000);
+ afterAll(async () => { await close?.(); });
+
+ const chunkerVersion = async (slug: string) => Number((await engine.executeRaw<{ v: number }>(
+ "SELECT chunker_version AS v FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0]!.v);
+
+ test('a protected code body stays below the safe fence through import, re-import and re-seal', async () => {
+ const imported = await importCodeFile(engine, 'lib/fenced-example.ts', fenced, { noEmbed: true });
+ expect(imported.status).toBe('imported');
+ fencedSlug = imported.slug;
+ expect(await chunkerVersion(imported.slug)).toBeLessThan(SAFE_FENCE_CHUNKER_VERSION);
+ expect((await engine.getChunks(imported.slug, { sourceId: 'default' })).length).toBeGreaterThan(0);
+ expect(await engine.getChunks(imported.slug, { sourceId: 'default', requireSafeChunks: true })).toEqual([]);
+
+ const again = await importCodeFile(engine, 'lib/fenced-example.ts', fenced, { noEmbed: true });
+ expect(again).toMatchObject({ status: 'skipped' });
+ expect(again.resealed).toBeUndefined();
+ expect(await resealSafeChunks(engine, imported.slug, 'default')).toBeNull();
+ expect(await chunkerVersion(imported.slug)).toBeLessThan(SAFE_FENCE_CHUNKER_VERSION);
+ expect(await engine.getChunks(imported.slug, { sourceId: 'default', requireSafeChunks: true })).toEqual([]);
+ }, 60_000);
+
+ test('plain code is still sealed and admitted', async () => {
+ const imported = await importCodeFile(engine, 'lib/plain-example.ts', plain, { noEmbed: true });
+ expect(await chunkerVersion(imported.slug)).toBeGreaterThanOrEqual(SAFE_FENCE_CHUNKER_VERSION);
+ expect((await engine.getChunks(imported.slug, { sourceId: 'default', requireSafeChunks: true })).length).toBeGreaterThan(0);
+ }, 60_000);
+
+ test('repair and doctor leave a protected code page out of the re-sealable count', async () => {
+ const plan = await safeChunksRepair.plan(engine, { brain_id: 'host', source_ids: ['default'] }, null);
+ expect(fencedSlug).not.toBe('');
+ expect(plan.items.map(item => item.slug)).not.toContain(fencedSlug);
+ expect(plan.residuals).toMatchObject({ code_with_fence_marker: 1, code_without_source_path: 0 });
+ const check = await safeIndexPendingCheck(engine, ['default']);
+ expect(check.status).toBe('ok');
+ expect(check.details).toMatchObject({ pages_pending: 0, kept_pages: 1 });
+ }, 60_000);
+ });
+}
diff --git a/test/e2e/code-import-protected-fence-postgres.test.ts b/test/e2e/code-import-protected-fence-postgres.test.ts
new file mode 100644
index 0000000000..8fb2acd53b
--- /dev/null
+++ b/test/e2e/code-import-protected-fence-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../code-import-protected-fence.test.ts'));