Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(export): GBRA-130 B-5 escape unportable slugs, collect every collision, suffix reserved entity names
garrytan8e876b24be27
diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.mdindex e134c4e6d9..d0ba9758f8 100644--- a/docs/architecture/key-files/commands-3.md+++ b/docs/architecture/key-files/commands-3.md@@ -27,7 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/eval.ts` — `gbrain eval` command: single-run table + A/B config comparison. Sub-subcommand dispatch on `args[0]` routes `gbrain eval export` + `gbrain eval prune` + `gbrain eval replay` into session-capture handlers; bare `gbrain eval --qrels …` fall-through preserves the legacy IR-metrics flow. `gbrain eval cross-modal` is in the dispatch (the user-facing path is the cli.ts no-DB branch — `src/commands/eval.ts:cross-modal` only fires when callers re-enter with an existing engine).-- `src/commands/export.ts` + `src/core/export-snapshot.ts` + `src/core/export-stage.ts` + `src/core/export-publish.ts` — local Markdown export collects source/page/canonical-withdrawal/tag/raw state in one export-scoped repeatable-read read-only transaction, using 256-key ID batches and private disk-backed SQLite staging. Primary-key page reads reuse the canonical withdrawal overlay without source-wide slug scans under stale planner statistics. Each 256-key batch groups by source and retains only one capacity-checked withdrawal ledger at a time; bodies with no literal `gbrain:facts:` marker skip normalization, while malformed/orphan markers still use canonical SQL fingerprinting. No engine defaults or shared migration iterators change. Explicit source selection is validated; restore-only selects one source through `resolveRestoreTarget` (`src/core/restore-target.ts`, shared with `gbrain storage status`) and checks its recorded file path through the existing native path resolver. The manifest rejects unsafe paths, same/cross-source aliases, case/Unicode and file-prefix collisions before destination output, preserving the `<slug>.md` and `.raw/<name>.json` layout. Existing planned paths refuse rather than overwrite. The portable first-party native addon anchors no-follow directories and publishes leaves with atomic no-replace operations, retaining an exclusive persistent `.gbrain-export-status` marker; success requires flushed data and a final COMPLETE line. Unsupported native capabilities fail closed without a pathname fallback. A fresh destination is the retry path; unrelated files are never pruned. Fixed capacity/time limits fail visibly, never truncate. This is a historical snapshot, not a database backup or a sandbox against another same-user process renaming directories. See [safe export](../../storage-tiering.md#safe-export). Engine-free `export --help` documents scope, no-overwrite publication and incomplete-output recovery. Wave B PR 2: a segmented page streams (`segmentedExportMarkdown`: serializeMarkdown's head, the trusted stored body through `readBodyRange` under a body ledger, here `exportBodyLedger`, the same withdrawal overlay; `restore_page` of a page over the single-string ceiling passes its snapshot's ledger; the timeline separator before the first timeline byte) into its own stage file (`ExportStage.addStream`, a full collection per 1 MiB read), published with the native path API; its payload estimate is `body_bytes`, the per-page limit is `exportPayloadLimit(pages.max_bytes)` (32 MiB while segmented storage is off), a streamed page adds 1 ms per KiB to the 10-minute snapshot deadline and stage files must leave 512 MiB free on the staging filesystem (`test/e2e/large-pages-export.test.ts`: inline vs segmented same bytes at 2 and 20 MiB, export(import(F)) == F, a gated 128 MiB memory arm). Pinned by both-engine export safety/independent-roundtrip/snapshot/failure-release suites, the 100001-page scale fixture with staging bytes and full export SQL statement accounting, the native publication/compiled-wrapper suite, actual CLI help tests, and the PostgreSQL export E2E wrapper.+- `src/commands/export.ts` + `src/core/export-snapshot.ts` + `src/core/export-stage.ts` + `src/core/export-publish.ts` — local Markdown export collects source/page/canonical-withdrawal/tag/raw state in one export-scoped repeatable-read read-only transaction, using 256-key ID batches and private disk-backed SQLite staging. Primary-key page reads reuse the canonical withdrawal overlay without source-wide slug scans under stale planner statistics. Each 256-key batch groups by source and retains only one capacity-checked withdrawal ledger at a time; bodies with no literal `gbrain:facts:` marker skip normalization, while malformed/orphan markers still use canonical SQL fingerprinting. No engine defaults or shared migration iterators change. Explicit source selection is validated; restore-only selects one source through `resolveRestoreTarget` (`src/core/restore-target.ts`, shared with `gbrain storage status`) and checks its recorded file path through the existing native path resolver. The manifest rejects unsafe paths, same/cross-source aliases, case/Unicode and file-prefix collisions before destination output, preserving the `<slug>.md` and `.raw/<name>.json` layout. Existing planned paths refuse rather than overwrite. The portable first-party native addon anchors no-follow directories and publishes leaves with atomic no-replace operations, retaining an exclusive persistent `.gbrain-export-status` marker; success requires flushed data and a final COMPLETE line. Unsupported native capabilities fail closed without a pathname fallback. A fresh destination is the retry path; unrelated files are never pruned. Fixed capacity/time limits fail visibly, never truncate. This is a historical snapshot, not a database backup or a sandbox against another same-user process renaming directories. See [safe export](../../storage-tiering.md#safe-export). Engine-free `export --help` documents scope, no-overwrite publication and incomplete-output recovery. Wave B PR 2: a segmented page streams (`segmentedExportMarkdown`: serializeMarkdown's head, the trusted stored body through `readBodyRange` under a body ledger, here `exportBodyLedger`, the same withdrawal overlay; `restore_page` of a page over the single-string ceiling passes its snapshot's ledger; the timeline separator before the first timeline byte) into its own stage file (`ExportStage.addStream`, a full collection per 1 MiB read), published with the native path API; its payload estimate is `body_bytes`, the per-page limit is `exportPayloadLimit(pages.max_bytes)` (32 MiB while segmented storage is off), a streamed page adds 1 ms per KiB to the 10-minute snapshot deadline and stage files must leave 512 MiB free on the staging filesystem (`test/e2e/large-pages-export.test.ts`: inline vs segmented same bytes at 2 and 20 MiB, export(import(F)) == F, a gated 128 MiB memory arm). `exportPagePath` writes a page whose slug is not a portable file name under an escaped name with its `slug:` line (`:` and other Windows-unsafe characters become `~`, a reserved device name or trailing dot/space gets `~` appended, an over-budget segment is cut with a `~<8 hex>` hash and marked not restorable); `runExport` returns an `ExportReport`, prints the escaped pages, and collects every `ExportPathCollision` into one refusal whose lines name each fix (`test/pathological/b5-export-unsafe-slugs.test.ts`). Pinned by both-engine export safety/independent-roundtrip/snapshot/failure-release suites, the 100001-page scale fixture with staging bytes and full export SQL statement accounting, the native publication/compiled-wrapper suite, actual CLI help tests, and the PostgreSQL export E2E wrapper.- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into bounded windows via `src/core/facts/conversation-windows.ts` (#6267: eligibility per 30-min gap group of ≥2 messages decided before windowing; windows close at 30 messages or when the rendered text with its header would exceed 6,500 chars; oversized turns split at sentence boundaries with the speaker prefix repeated; a trailing single reply of an eligible group is its own window, never glued across a gap; nothing is clipped and an unrepresentable header fails the page before prior-fact cleanup; a page's frontmatter `conversation_segment_gap_minutes`, an integer from 1 to 10080, overrides the gap for that page, and any other value is ignored with a stderr warning naming the accepted range), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES` = `CONVERSATION_BODY_MAX_BYTES` in `conversation-parser/body.ts`, `PAGE_MAX_BYTES` + 1 MiB = 25 MiB, measured on the parser input; `readConversationBodyForParsing` stats a `raw_transcript` sidecar and throws `ConversationBodyTooLargeError` over the cap before any read, the snapshot carries `oversizedSidecarBytes`, and a size skip writes a `skipped_too_large` receipt to `page_extraction_state` (doctor `extraction_input_truncated`) that a later run under the cap clears; test `test/conversation-facts-oversized-sidecar.test.ts`; a segmented page is read in ranges; one over `CONVERSATION_WINDOW_BYTES` with no conversation facts is extracted from its newest window (day-header date, `tail_window` receipt, `window_rule: no_prior_facts`); one with facts is skipped with nothing cleared (`skipped_too_large`, `window_rule: prior_facts_kept`), since the run clears prior facts the window may not see, until PR 4's window anchors (test `test/large-pages/segmented-conversation-facts.test.ts`)); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd` (a DEFAULT cap is dropped with a warning when the extraction or parser chat model is unpriced, via `src/core/facts/conversation-budget.ts` `conversationFactsCostCap` (#5823); explicit CLI/caller/cycle caps stay fail-closed and a `no_pricing` stop reports `budget_reason`/`budget_model`, exits 1 and names `pricing.overrides`); **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, so a terminal audit row can never certify a partial insertFacts failure. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Additive `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` explain the unchanged `pages_skipped` aggregate across core, CLI, workers, and cycle sources; durable completion remains separate. `--dry-run` stops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrow `python-dict-utterance` registry format and its quoted/nested-example rejection are documented in [conversation parser patterns](../conversation-parser-patterns.md). Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-diagnostics.serial.test.ts` (pool workers, per-page lock skip + exit 3, delete-orphans-first replay, D15 preflight, `--workers` round-trip). `src/commands/doctor.ts` reads the same outcomes, which survive checkpoint GC. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Explicit `slugs` batches contain page failures like the pool (cancellation and budget stops halt); logs carry only the closed reason and a retry command. Completion requires every in-scope segment (exactly `--segment-limit` counts). Extracted rows take `facts.default_visibility` (resolved once per run); audit rows stay private. Each page's own entities go to the extractor as `entityHints` (slugs, `src/core/facts/conversation-entity-hints.ts`, computed once per page, cap `CONVERSATION_ENTITY_HINTS_CAP` = 40 through `ExtractInput.entityHintsCap`): authored edges only (the page's frontmatter edges with the page as origin, then outgoing markdown, wikilink-resolved and manual links), same source, live fact-entity pages, and a private entity only when the run's facts are private; the `extract_facts` op keeps its 5-hint cap and prompt. Pinned by `test/conversation-entity-hints.test.ts`. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives, bar `facts/conversation-skip.ts` (prose meetings, single emails, undated turns). Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. On a managed brain the core runs `managedDerivedFactsPreflight` (local writer, active source) before any provider work, and a page's facts and terminal (or non-extractable) audit row are buffered, then replace the prior extractor batch in one `replaceDerivedFactsForPage` transaction after source activity, page id, revision and parser-input snapshot are rechecked under the page lock, so a failed or raced re-extraction keeps the prior batch; the CLI no longer refuses up front and receipt pages are skipped. Tests: `test/managed-facts-writers.test.ts`, `test/managed-unsupported-preflight.serial.test.ts` (refusal before spend for an unaccepted writer).diff --git a/src/commands/export.ts b/src/commands/export.tsindex 6d275b88b5..05b2c930cb 100644--- a/src/commands/export.ts+++ b/src/commands/export.ts@@ -8,7 +8,8 @@ import { loadStorageConfig, isDbOnly } from '../core/storage-config.ts';import { resolveSourceId } from '../core/source-resolver.ts';import { ALL_SOURCES, assertValidSourceId } from '../core/source-id.ts';import { resolveRestoreTarget, restoreFilePath } from '../core/restore-target.ts';-import { ExportStage, EXPORT_PAYLOAD_LIMIT, EXPORT_SNAPSHOT_MS, EXPORT_STREAM_BYTES_PER_MS, exportPathKey, exportPayloadLimit } from '../core/export-stage.ts';+import { ExportPathCollision, ExportStage, EXPORT_PAYLOAD_LIMIT, EXPORT_SNAPSHOT_MS, EXPORT_STREAM_BYTES_PER_MS, exportPagePath, exportPayloadLimit } from '../core/export-stage.ts';+import { slugPortabilityProblem } from '../core/portable-slug.ts';import { publishExport } from '../core/export-publish.ts';import { nativeFileTarget } from '../core/persistence/native-file-target.ts';import { exportBodyLedger, readExportPage, readExportWithdrawals, segmentedExportMarkdown } from '../core/export-snapshot.ts';@@ -25,7 +26,49 @@ function option(args: string[], name: string): string | undefined {return value;}-export async function runExport(engine: BrainEngine, args: string[]): Promise<void> {+/** A page exported under an escaped file name (GBRA-130 B-5): its slug is not a portable file name. */+export interface EscapedExportPage {+ source_id: string;+ slug: string;+ /** The file written, relative to --dir; its `slug:` stamp names the slug. */+ path: string;+ /** `unportable_slug`: import restores the slug from the escaped name. `segment_too_long`: the name was shortened and import refuses the file. */+ reason: 'unportable_slug' | 'segment_too_long';+ restorable: boolean;+ /** For a shortened page, how to move it to a portable slug; null when import restores it. */+ fix: { argv: string[] } | null;+}++export interface ExportReport { pages: number; escaped: EscapedExportPage[] }++interface ExportCollision { key: string; path: string; prior: string; source_id: string; slug: string }++/** One refusal naming every collision with its fix: separate exports per source, or a move when both pages share a source. */+function collisionRefusal(collisions: ExportCollision[], owners: Map<string, { source_id: string; label: string }>, outDir: string): Error {+ const lines = collisions.map(collision => {+ const owner = owners.get(collision.prior) ?? [...owners].find(([path]) => path.startsWith(collision.prior + '/'))?.[1];+ const fix = owner && owner.source_id !== collision.source_id+ ? `gbrain export --source ${collision.source_id} --dir ${outDir.replace(/\/+$/, '')}-${collision.source_id}`+ : `move one of the pages: put_page its content under a new slug, then delete_page ${collision.slug}`;+ return ` - ${collision.key} -> ${collision.path} collides with ${owner?.label ?? collision.prior} (export_path_collision); fix: ${fix}`;+ });+ return new Error(`Export path collision (including case, Unicode, page/sidecar or file-prefix aliases). Nothing was published. ${collisions.length} page path(s) collide:\n${lines.join('\n')}\nExport one source at a time with --source <id> into separate fresh directories.`);+}++function printEscaped(escaped: EscapedExportPage[]): void {+ const restorable = escaped.filter(page => page.restorable);+ const shortened = escaped.filter(page => !page.restorable);+ if (restorable.length) {+ console.log(`${restorable.length} page(s) have slugs that are not portable file names and were exported under escaped names; each file's slug: line keeps the slug, and import restores it:`);+ for (const page of restorable) console.log(` - ${page.source_id}:${page.slug} -> ${page.path}`);+ }+ if (shortened.length) {+ console.log(`${shortened.length} page(s) have a slug segment longer than a file name may be and were exported under a shortened name; import refuses those files until the page moves to a shorter slug:`);+ for (const page of shortened) console.log(` - ${page.source_id}:${page.slug} -> ${page.path}; fix: ${page.fix!.argv.join(' ')}, then delete_page ${page.slug}`);+ }+}++export async function runExport(engine: BrainEngine, args: string[]): Promise<ExportReport | undefined> {if (args.includes('--help') || args.includes('-h')) {console.log(`Usage: gbrain export [--dir <path>] [--source <id>] [--type <type>] [--slug-prefix <prefix>]gbrain export --restore-only [--source <id>] [--repo <path>] [--dir <path>] [--slug-prefix <prefix>]@@ -38,7 +81,10 @@ Export a coherent point-in-time Markdown snapshot; this is not a database backup--restore-only Export missing db_only files for one source.--repo <path> Restore source's repository and storage config; output still goes to --dir.-Colliding planned paths and occupied output paths refuse; nothing is overwritten.+Colliding planned paths and occupied output paths refuse (every collision is+listed); nothing is overwritten. A page whose slug is not a portable file name+(a ':', a Windows reserved name such as aux) is written under an escaped name+with a slug: line, and import restores its slug.Existing empty directories and unrelated files are preserved. There is no force option.The reserved .gbrain-export-status starts incomplete and ends with COMPLETE onlyafter successful publication. On failure, preserve partial output and retry into@@ -55,6 +101,9 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);const restoreOnly = args.includes('--restore-only');stage = new ExportStage();const staged = stage;+ const escaped: EscapedExportPage[] = [];+ const collisions: ExportCollision[] = [];+ const owners = new Map<string, { source_id: string; label: string }>();const started = Date.now();let streamedBytes = 0;const checkDeadline = () => {@@ -91,7 +140,7 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);for (const key of batch.filter(key => key.source_id === batchSource)) {checkDeadline();assertValidSourceId(key.source_id);- exportPathKey(key.slug + '.md');+ const target = exportPagePath(key.slug, Number(key.raw_count) > 0);if (restoreOnly && storage && repo) {if (!isDbOnly(key.slug, storage)) continue;if (existsSync(nativeFileTarget(repo, restoreFilePath(repo, key.slug, key.source_path, Number(key.source_path_bytes), await scannerSlugRootMode(tx, batchSource, repo))))) continue;@@ -99,19 +148,32 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);if (Number(key.bytes) > (key.segmented ? segmentedLimit : EXPORT_PAYLOAD_LIMIT)) throw new Error('Export page payload limit exceeded. No destination output was published.');const snapshot = await readExportPage(tx, key, withdrawals);const page = snapshot.page;- // #5966: the slug stamp rule lives in slugStampedFrontmatter (markdown.ts), shared with every render.- const frontmatter = slugStampedFrontmatter(page.slug, page.frontmatter ?? {});+ // #5966: the slug stamp rule lives in slugStampedFrontmatter (markdown.ts), shared with every render; an+ // escaped file always carries its slug.+ const frontmatter = target.escaped ? { ...(page.frontmatter ?? {}), slug: page.slug } : slugStampedFrontmatter(page.slug, page.frontmatter ?? {});const meta = { type: page.type, title: page.title, tags: snapshot.tags };- if (isSegmentedPage(page)) {- streamedBytes += Number(key.bytes);- const head = serializeMarkdown(frontmatter, '', '', meta).slice(0, -1);- await staged.addStream(page.slug + '.md', Number(key.bytes), segmentedLimit, segmentedExportMarkdown(tx, page, exportBodyLedger(page.slug, withdrawals), head));- } else staged.add(page.slug + '.md', 'file', serializeMarkdown(frontmatter, page.compiled_truth, page.timeline, meta));+ const label = `${page.source_id}:${page.slug}`;const raw = Number(key.raw_count) ? await tx.getRawData(page.slug, undefined, { sourceId: page.source_id, includeDeleted: true }) : [];- if (raw.length) {- const parts = page.slug.split('/');- const name = parts.pop()!;- staged.add([...parts, '.raw', name + '.json'].join('/'), 'file', JSON.stringify(Object.fromEntries(raw.map(row => [row.source, row.data])), null, 2) + '\n');+ try {+ if (isSegmentedPage(page)) {+ streamedBytes += Number(key.bytes);+ const head = serializeMarkdown(frontmatter, '', '', meta).slice(0, -1);+ await staged.addStream(target.path, Number(key.bytes), segmentedLimit, segmentedExportMarkdown(tx, page, exportBodyLedger(page.slug, withdrawals), head));+ } else staged.add(target.path, 'file', serializeMarkdown(frontmatter, page.compiled_truth, page.timeline, meta));+ owners.set(target.path, { source_id: page.source_id, label });+ if (raw.length) {+ staged.add(target.rawPath, 'file', JSON.stringify(Object.fromEntries(raw.map(row => [row.source, row.data])), null, 2) + '\n');+ owners.set(target.rawPath, { source_id: page.source_id, label });+ }+ } catch (error) {+ if (!(error instanceof ExportPathCollision)) throw error;+ collisions.push({ key: label, path: error.path, prior: error.prior, source_id: page.source_id, slug: page.slug });+ continue;+ }+ if (target.escaped) {+ const suggestion = target.restorable ? null : slugPortabilityProblem(page.slug)?.suggestion ?? null;+ escaped.push({ source_id: page.source_id, slug: page.slug, path: target.path, reason: target.restorable ? 'unportable_slug' : 'segment_too_long',+ restorable: target.restorable, fix: suggestion ? { argv: ['gbrain', 'put', suggestion] } : null });}staged.pages++;}@@ -119,6 +181,7 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);cursor = batch[batch.length - 1].id;}checkDeadline();+ if (collisions.length) throw collisionRefusal(collisions, owners, outDir);});console.log(`${restoreOnly ? 'Restoring' : 'Exporting'} ${stage.pages}${restoreOnly ? ' db_only' : ''} pages to ${outDir}/`);const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));@@ -126,6 +189,8 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);await publishExport(stage, outDir, path => { if (path.endsWith('.md')) progress.tick(); });progress.finish();console.log(`${restoreOnly ? 'Restored' : 'Exported'} ${stage.pages} pages to ${outDir}/`);+ printEscaped(escaped);+ return { pages: stage.pages, escaped };} catch (error) {console.error(`Error: Export failed: ${(error as Error).message}\nNo complete export was produced. If ${'.gbrain-export-status'} exists without a final COMPLETE line, the destination is incomplete. Preserve its files and retry into a fresh directory. See docs/storage-tiering.md#safe-export.`);if (stage) { stage.close(); stage = undefined; }diff --git a/src/core/enrichment-service.ts b/src/core/enrichment-service.tsindex 6bb76eac01..e4305dc6b6 100644--- a/src/core/enrichment-service.ts+++ b/src/core/enrichment-service.ts@@ -19,6 +19,7 @@ import { OperationError } from './ops/contract.ts';import { waitForCapacity } from './backoff.ts';import { quarantineMarkers } from './extraction-review.ts';import { SLUG_WORD_CHARS, SLUG_VARIATION_SELECTORS_RE } from './cjk.ts';+import { portableSegment } from './portable-slug.ts';// #3994: created stubs route through serializeMarkdown + importFromContent// (the same parse→chunk→embed pipeline put_page uses) instead of a bare// engine.putPage, so fresh entity pages land in the retrieval surface@@ -101,7 +102,12 @@ const SLUGIFY_ENTITY_KEEP_RE = new RegExp(`[^${SLUG_WORD_CHARS}]`, 'gu');* '-', producing empty or colliding people/companies slugs. Now mirrors* sync.ts:slugifySegment's Unicode-aware keep-set: strip Latin accents to* their base letter (fold, don't drop), keep every script's own letters- * as-is (Cyrillic, CJK, Devanagari, …).+ * as-is (Cyrillic, CJK, Devanagari, …). A name that slugifies to a Windows+ * reserved device name gets the entity type as a suffix (`Con` →+ * `people/con-person`) and an over-long one is cut to the file-name budget+ * (portable-slug.ts), so a stub is always a page export and write-through can+ * store; a page an older brain created as `people/con` is still found through+ * the legacy-slug lookup in enrichEntity.*/export function slugifyEntity(name: string, type: 'person' | 'company'): string {const slug = name@@ -116,7 +122,7 @@ export function slugifyEntity(name: string, type: 'person' | 'company'): string.replace(/^-+|-+$/g, '');const prefix = type === 'person' ? 'people' : 'companies';- return `${prefix}/${slug}`;+ return `${prefix}/${portableSegment(slug, true, type)}`;}/**diff --git a/src/core/export-stage.ts b/src/core/export-stage.tsindex 6d51ac0585..8de435fa03 100644--- a/src/core/export-stage.ts+++ b/src/core/export-stage.ts@@ -1,8 +1,10 @@import { Database } from 'bun:sqlite';+import { createHash } from 'node:crypto';import { closeSync, mkdirSync, mkdtempSync, openSync, rmSync, statfsSync, writeSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { PAGE_MAX_BYTES } from './page-size-policy.ts';+import { FILE_NAME_MAX_BYTES, RESERVED_DEVICE_NAME, truncateUtf8 } from './portable-slug.ts';export const EXPORT_MARKER = '.gbrain-export-status';export const EXPORT_PAYLOAD_LIMIT = 32 * 1024 * 1024;@@ -24,16 +26,73 @@ export function exportPayloadLimit(maxBytes: number): number {return Math.max(maxBytes, PAGE_MAX_BYTES) + EXPORT_PAYLOAD_LIMIT - PAGE_MAX_BYTES;}+/** A character no exported file name may hold. */+const UNSAFE_NAME_CHAR = /[\\\x00-\x1f\x7f:<>"|?*]|[\uD800-\uDFFF]/u;++function unsafeExportPart(part: string): boolean {+ return !part || part === '.' || part === '..' || UNSAFE_NAME_CHAR.test(part) || /[. ]$/.test(part)+ || RESERVED_DEVICE_NAME.test(part) || Buffer.byteLength(part) > FILE_NAME_MAX_BYTES;+}+export function exportPathKey(path: string): string {const parts = path.split('/');- if (Buffer.byteLength(path) > 4096 || parts.length > 256 || parts.some(part => !part || part === '.' || part === '..'- || /[\\\x00-\x1f\x7f:<>"|?*]/.test(part) || /[\uD800-\uDFFF]/u.test(part) || /[. ]$/.test(part)- || /^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/i.test(part) || Buffer.byteLength(part) > 240)) {+ if (Buffer.byteLength(path) > 4096 || parts.length > 256 || parts.some(unsafeExportPart)) {throw new Error('Unsafe export path. Correct the stored slug before exporting.');}return path.normalize('NFC').toUpperCase().toLowerCase().normalize('NFC');}+export interface ExportPagePath {+ /** The page's file, relative to the export root. */+ path: string;+ /** Its raw-data sidecar (`<dirs>/.raw/<leaf>.json`). */+ rawPath: string;+ /** True when a part was escaped: the file is not `<slug>.md`, and the page's `slug:` stamp names its slug. */+ escaped: boolean;+ /** False when a part was too long and was shortened: import refuses the file until the page moves to a shorter slug. */+ restorable: boolean;+}++/**+ * Where export writes a page: `<slug>.md` when every part is a portable file+ * name. A part an older gbrain admitted that is not (GBRA-130 B-5) is escaped+ * so the importer still derives the stored slug from the path (import-file.ts+ * accepts a stamped slug whose slugified form is the path's): a `:` or any+ * other character no file name may hold becomes `~`, and a reserved device+ * name or a trailing dot or space gets a `~` after it; slugifyPath drops+ * `~`. A part over the file-name budget (with its `.md`, or `.json` when the+ * page has raw data) is cut and suffixed with a hash of the slug: that file+ * keeps the slug in its stamp, but is not restorable.+ */+export function exportPagePath(slug: string, hasRaw: boolean): ExportPagePath {+ const parts = slug.split('/');+ let escaped = false;+ let restorable = true;+ const names = parts.map((part, i) => {+ const leaf = i === parts.length - 1;+ const extensions = leaf ? (hasRaw ? ['.md', '.json'] : ['.md']) : [''];+ if (extensions.every(ext => !unsafeExportPart(part + ext))) return part;+ escaped = true;+ let name = part.replace(new RegExp(UNSAFE_NAME_CHAR.source, 'gu'), '~').replace(RESERVED_DEVICE_NAME, '$1~');+ if (/[. ]$/.test(name)) name += '~';+ const budget = FILE_NAME_MAX_BYTES - Math.max(...extensions.map(ext => Buffer.byteLength(ext)));+ if (Buffer.byteLength(name) > budget) {+ restorable = false;+ name = `${truncateUtf8(name, budget - 9)}~${createHash('sha256').update(slug).digest('hex').slice(0, 8)}`;+ }+ return name;+ });+ const leaf = names.pop()!;+ return { path: [...names, leaf + '.md'].join('/'), rawPath: [...names, '.raw', leaf + '.json'].join('/'), escaped, restorable };+}++/** A staged path whose key another staged path already holds (case, Unicode, page/sidecar or file-prefix aliases). */+export class ExportPathCollision extends Error {+ constructor(readonly path: string, readonly prior: string) {+ super('Export path collision (including case, Unicode, page/sidecar or file-prefix aliases). Nothing was published. Export one source at a time with --source <id> into separate fresh directories.');+ }+}+export class ExportStage {readonly directory = mkdtempSync(join(tmpdir(), 'gbrain-export-'));readonly db = new Database(join(this.directory, 'manifest.sqlite'));@@ -99,7 +158,7 @@ export class ExportStage {const prior = this.db.query<{ path: string; kind: string }, [string]>('SELECT path, kind FROM paths WHERE key=?').get(key);if (prior) {if (prior.kind === 'directory' && currentKind === 'directory' && prior.path === current) continue;- throw new Error('Export path collision (including case, Unicode, page/sidecar or file-prefix aliases). Nothing was published. Export one source at a time with --source <id> into separate fresh directories.');+ throw new ExportPathCollision(current, prior.path);}this.db.query('INSERT INTO paths VALUES (?, ?, ?, ?, ?)').run(key, current, currentKind, i === parts.length ? payload : null, i === parts.length ? file : null);}diff --git a/test/pathological/b5-export-unsafe-slugs.test.ts b/test/pathological/b5-export-unsafe-slugs.test.tsnew file mode 100644index 0000000000..8884ac0950--- /dev/null+++ b/test/pathological/b5-export-unsafe-slugs.test.ts@@ -0,0 +1,241 @@+/**+ * B-5 (GBRA-130): a slug put_page or an entity stub accepted never wedges+ * `gbrain export`, and new identities that cannot be file names are refused+ * at admission.+ *+ * Protects (export): pages an older gbrain stored under slugs no portable file+ * name can hold (`ns:foo`, `meetings/2026-01-01:standup`, `companies/aux`,+ * `people/con`, `people/nul.x`, an 81-CJK-character segment) export under+ * escaped names with a `slug:` stamp instead of aborting the whole export;+ * import restores each exact slug from its escaped file (the over-long one is+ * reported as shortened, with the move as its fix); path collisions are all+ * collected and refused once, each with its typed code and fix, and the+ * per-source exports that fix names publish. A run-scoped failure still+ * aborts the export with nothing published.+ * Protects (write side): put_page, its dry run and put_pages refuse a NEW+ * identity whose segment is a Windows reserved name (invalid_params, detail+ * slug_not_portable, with a portable slug), also when another source holds+ * the same slug; colon slugs stay writable; an existing page keeps accepting+ * put_page and edit_page with an advisory; a replayed request returns its+ * receipt; slugifyEntity suffixes reserved names.+ * Fails when: export.ts calls exportPathKey on the raw slug (one unsafe page+ * throws inside the snapshot transaction: "Nothing was published"), stops at+ * the first collision, or admission ignores reserved names.+ * Seams: none; the run cases patch the engine instance. PGLite always,+ * Postgres when DATABASE_URL is set.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { runExport } from '../../src/commands/export.ts';+import { importFromFile } from '../../src/core/import-file.ts';+import { parseMarkdown, serializePageToMarkdown } from '../../src/core/markdown.ts';+import { slugifyEntity } from '../../src/core/enrichment-service.ts';+import { operations, OperationError, type OperationContext } from '../../src/core/operations.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, managedBrain, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';++const op = (name: string) => operations.find(o => o.name === name)!;+const CJK81 = 'notes/' + '漢'.repeat(81);+const UNSAFE = ['ns:foo', 'meetings/2026-01-01:standup', 'companies/aux', 'people/con', 'people/nul.x', CJK81];+const ESCAPED: Record<string, string> = {+ 'ns:foo': 'ns~foo.md', 'meetings/2026-01-01:standup': 'meetings/2026-01-01~standup.md', 'companies/aux': 'companies/aux~.md',+ 'people/con': 'people/con~.md', 'people/nul.x': 'people/nul~.x.md',+};+const body = (title: string) => `---\ntitle: ${title}\ntype: note\n---\n# ${title}\n\nBody of ${title}.\n`;++async function refusal(run: unknown): Promise<OperationError> {+ try { await run; } catch (error) { if (error instanceof OperationError) return error; throw error; }+ throw new Error('expected a refusal');+}++function walk(dir: string, prefix = ''): string[] {+ return readdirSync(dir, { withFileTypes: true }).flatMap(entry => entry.isDirectory()+ ? walk(join(dir, entry.name), prefix + entry.name + '/') : [prefix + entry.name]).sort();+}++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`B-5 export of unportable slugs (${backend})`, () => {+ let engine: BrainEngine;+ let target: BrainEngine;+ const closers: Array<() => Promise<void>> = [];+ let dir: string;+ let messages: string[];+ let restore: () => void;++ beforeAll(async () => {+ for (const assign of [(e: BrainEngine) => { engine = e; }, (e: BrainEngine) => { target = e; }]) {+ if (databaseUrl) { const isolated = await isolatedPersistencePostgres(databaseUrl); assign(isolated.engine); closers.push(isolated.close); }+ else { const e = new PGLiteEngine(); await e.connect({}); await e.initSchema(); assign(e); closers.push(() => e.disconnect()); }+ }+ await engine.executeRaw("INSERT INTO sources (id,name) VALUES ('other','Other') ON CONFLICT DO NOTHING");+ }, 180_000);+ afterAll(async () => { for (const close of closers) await close(); });+ beforeEach(async () => {+ dir = realpathSync(mkdtempSync(join(tmpdir(), 'b5-export-')));+ await engine.executeRaw('DELETE FROM pages');+ await target.executeRaw('DELETE FROM pages');+ messages = [];+ const [exit, log, error] = [process.exit, console.log, console.error];+ process.exit = ((code: number) => { throw new Error(`EXIT:${code}`); }) as never;+ console.log = console.error = (...args: unknown[]) => { messages.push(args.join(' ')); };+ restore = () => { process.exit = exit; console.log = log; console.error = error; };+ });+ afterEach(() => { restore(); rmSync(dir, { recursive: true, force: true }); });++ async function page(slug: string, sourceId = 'default') {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `body of ${slug}`, timeline: '' }, { sourceId });+ await engine.putRawData(slug, 'feed', { owner: slug }, { sourceId });+ }++ test('B-5 item: unportable slugs export under escaped names with a slug stamp and import restores each slug', async () => {+ for (const slug of [...UNSAFE, 'notes/healthy']) await page(slug);+ const before = await snapshotItems(engine, 'default');+ const report = await expectUnitNotAborted(() => runExport(engine, ['--dir', join(dir, 'out')]));+ const out = join(dir, 'out');+ expect(readFileSync(join(out, '.gbrain-export-status'), 'utf8')).toBe('GBRAIN EXPORT INCOMPLETE\nCOMPLETE\n');+ expect(report!.pages).toBe(UNSAFE.length + 1);+ const files = walk(out);+ for (const [slug, path] of Object.entries(ESCAPED)) {+ expect({ slug, file: files.includes(path) }).toEqual({ slug, file: true });+ expect(parseMarkdown(readFileSync(join(out, path), 'utf8'), path).frontmatter.slug ?? parseMarkdown(readFileSync(join(out, path), 'utf8'), path).slug).toBe(slug);+ const imported = await importFromFile(target, join(out, path), path, { sourceId: 'default', noEmbed: true });+ expect({ slug, imported: imported.slug, error: imported.error }).toEqual({ slug, imported: slug, error: undefined });+ }+ expect(files).toContain('companies/.raw/aux~.json');+ expect(files).toContain('notes/healthy.md');+ const long = report!.escaped.find(e => e.slug === CJK81)!;+ expect(long).toMatchObject({ source_id: 'default', restorable: false });+ expect(files).toContain(long.path);+ expectItemFailure({ key: long.slug, code: long.reason, fix: long.fix }, { key: CJK81, code: 'segment_too_long', fix: new RegExp(`^gbrain put notes/漢{78}`) });+ expect(report!.escaped.filter(e => e.restorable).map(e => e.slug).sort()).toEqual(Object.keys(ESCAPED).sort());+ expect(messages.join('\n')).toContain('companies/aux -> companies/aux~.md');+ expectOthersUnchanged(before, await snapshotItems(engine, 'default'));+ }, 120_000);++ test('B-5 item: every path collision is collected and refused once with its code and fix; the per-source exports publish', async () => {+ await page('notes/shared'); await page('notes/shared', 'other');+ await page('one'); await page('one.md/two');+ await page('companies/aux');+ const out = join(dir, 'out');+ await expect(runExport(engine, ['--dir', out])).rejects.toThrow('EXIT:1');+ expect(existsSync(out) ? readdirSync(out) : []).toEqual([]);+ const text = messages.join('\n');+ const lines = text.split('\n').filter(line => line.includes('(export_path_collision)'));+ const parsed = lines.map(line => /^ {2}- (\S+) -> (\S+) collides with (\S+) \((\w+)\); fix: (.*)$/.exec(line)!).map(m => ({ key: m[1], code: m[4], fix: m[5] }));+ expect(parsed.map(p => p.key).sort()).toEqual(['default:one.md/two', 'other:notes/shared']);+ expectItemFailure(parsed.find(p => p.key === 'other:notes/shared'), { key: 'other:notes/shared', code: 'export_path_collision', fix: new RegExp(`^gbrain export --source other --dir ${out}-other$`) });+ expectItemFailure(parsed.find(p => p.key === 'default:one.md/two'), { key: 'default:one.md/two', code: 'export_path_collision', fix: /delete_page one\.md\/two/ });+ for (const source of ['default', 'other']) {+ await engine.executeRaw('DELETE FROM pages WHERE slug = $1', ['one.md/two']);+ await expectUnitNotAborted(() => runExport(engine, ['--dir', `${out}-${source}`, '--source', source]));+ expect(readFileSync(join(`${out}-${source}`, 'notes/shared.md'), 'utf8')).toContain('body of notes/shared');+ }+ }, 120_000);++ for (const injected of runScopedErrors().filter(e => e.name === 'connection lost' || e.name === 'failed transaction (25P02)')) {+ test(`B-5 run: a run-scoped error (${injected.name}) reading an unportable page aborts the export and publishes nothing`, async () => {+ for (const slug of [...UNSAFE, 'notes/healthy']) await page(slug);+ const query = engine.executeRaw;+ engine.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[], options?: unknown) {+ if (sql.includes('AS export_tags')) throw injected.error();+ return (query as Function).call(this, sql, params, options);+ } as typeof engine.executeRaw;+ try {+ await expect(runExport(engine, ['--dir', join(dir, 'out')])).rejects.toThrow('EXIT:1');+ } finally { engine.executeRaw = query; }+ expect(existsSync(join(dir, 'out')) ? readdirSync(join(dir, 'out')) : []).toEqual([]);+ expect(messages.join('\n')).not.toContain('escaped');+ }, 120_000);+ }+ });++ describe(`B-5 new unportable identities (${backend})`, () => {+ const putPage = op('put_page');+ test('B-5 item: put_page, its dry run and put_pages refuse a new reserved-name slug with a portable one; colon slugs and siblings land', async () => {+ await managedBrain(async ({ engine, ctx }) => {+ await putPage.handler(ctx, { slug: 'notes/kept', content: body('Kept') });+ const before = await snapshotItems(engine, 'default');+ for (const [slug, suggestion] of [['companies/aux', 'companies/aux-page'], ['people/nul.x', 'people/nul-page.x'], ['people/con', 'people/con-page']]) {+ const error = await refusal(putPage.handler(ctx, { slug, content: body(slug) }));+ expectItemFailure({ key: slug, code: String(error.code), fix: error.fix }, { key: slug, code: 'invalid_params', fix: new RegExp(`^gbrain get ${suggestion.replace('.', '\\.')}$`) });+ expect(error.detail).toBe('slug_not_portable');+ const dry = await refusal(putPage.handler({ ...ctx, dryRun: true }, { slug, content: body(slug) }));+ expect(dry.detail).toBe('slug_not_portable');+ }+ const batch = await op('put_pages').handler(ctx, { request_id: randomUUID(), pages: [+ { slug: 'companies/lpt1', content: body('Lpt') }, { slug: 'notes/batch-sibling', content: body('Batch sibling') }] }) as { pages?: Array<Record<string, unknown>> };+ const refused = JSON.stringify(batch);+ expect(refused).toContain('slug_not_portable');+ for (const slug of ['ns:foo', 'meetings/2026-01-01:standup']) await expectUnitNotAborted(() => Promise.resolve(putPage.handler(ctx, { slug, content: body(slug) })));+ expect(await engine.getPage('companies/aux', { sourceId: 'default' })).toBeNull();+ expect(await engine.getPage('companies/lpt1', { sourceId: 'default' })).toBeNull();+ expect(await engine.getPage('notes/batch-sibling', { sourceId: 'default' })).not.toBeNull();+ expectOthersUnchanged(before, await snapshotItems(engine, 'default'), { changed: ['notes/batch-sibling', 'ns:foo', 'meetings/2026-01-01:standup'] });+ await expectUnitNotAborted(() => Promise.resolve(putPage.handler(ctx, { slug: 'companies/aux-page', content: body('Aux') })));+ }, { databaseUrl });+ }, 120_000);++ test('B-5 item: an existing reserved-name page keeps updating (put_page, edit_page, replay); another source holding the slug does not make it existing here', async () => {+ await managedBrain(async ({ engine, ctx }) => {+ const write = async (slug: string, content: string, extra: Record<string, unknown> = {}, sourceId = 'default') => {+ const prior = await engine.readPageSnapshot(slug, { sourceId });+ return putPage.handler({ ...ctx, sourceId }, { slug, content, ...(prior ? { expected_revision: prior.revision } : {}), ...extra }) as Promise<Record<string, unknown>>;+ };+ const updated = await expectUnitNotAborted(() => write('companies/aux', body('Aux updated')));+ expect(String(updated.slug_advisory)).toContain('companies/aux-page');+ expect((await engine.getPage('companies/aux', { sourceId: 'default' }))!.compiled_truth).toContain('Aux updated');+ const snapshot = (await engine.readPageSnapshot('companies/aux', { sourceId: 'default' }))!;+ await expectUnitNotAborted(() => Promise.resolve(op('edit_page').handler(ctx, { slug: 'companies/aux', expected_revision: snapshot.revision,+ edits: [{ old_text: 'Body of Aux updated.', new_text: 'Body of Aux edited.' }] })));+ expect((await engine.getPage('companies/aux', { sourceId: 'default' }))!.compiled_truth).toContain('Aux edited');+ const requestId = randomUUID();+ const params = { slug: 'companies/aux', content: body('Aux replayed'), expected_revision: (await engine.readPageSnapshot('companies/aux', { sourceId: 'default' }))!.revision, request_id: requestId };+ await putPage.handler(ctx, params);+ await op('delete_page').handler(ctx, { slug: 'companies/aux', expected_revision: (await engine.readPageSnapshot('companies/aux', { sourceId: 'default' }))!.revision });+ expect(await engine.getPage('companies/aux', { sourceId: 'default' })).toBeNull();+ await expectUnitNotAborted(() => Promise.resolve(putPage.handler(ctx, params)));+ const other = await refusal(write('companies/con', body('Con'), {}, 'default'));+ expect(other.detail).toBe('slug_not_portable');+ const inOther = await expectUnitNotAborted(() => write('companies/con', body('Con other'), {}, 'other'));+ expect(String(inOther.slug_advisory)).toContain('companies/con-page');+ }, { databaseUrl, setup: async ({ engine, root }) => {+ await engine.executeRaw("INSERT INTO sources (id,name,local_path) VALUES ('other','Other',NULL) ON CONFLICT DO NOTHING");+ await engine.putPage('companies/aux', { type: 'note', title: 'Aux', compiled_truth: 'Body of Aux.', timeline: '' }, { sourceId: 'default' });+ const stored = (await engine.readPageSnapshot('companies/aux', { sourceId: 'default' }))!;+ mkdirSync(join(root, 'companies'));+ writeFileSync(join(root, 'companies/aux.md'), serializePageToMarkdown(stored.page, stored.tags));+ await engine.putPage('companies/con', { type: 'note', title: 'Con', compiled_truth: 'Body of Con.', timeline: '' }, { sourceId: 'other' });+ } });+ }, 120_000);++ test('B-5 item: slugifyEntity suffixes reserved names with the entity type', () => {+ expect(slugifyEntity('Con', 'person')).toBe('people/con-person');+ expect(slugifyEntity('Aux', 'company')).toBe('companies/aux-company');+ expect(slugifyEntity('COM1', 'company')).toBe('companies/com1-company');+ expect(slugifyEntity('Nul.x', 'person')).toBe('people/nul-x');+ expect(slugifyEntity('Connor Example', 'person')).toBe('people/connor-example');+ });++ for (const injected of runScopedErrors().filter(e => e.name === 'connection lost' || e.name === 'failed transaction (25P02)')) {+ test(`B-5 run: a run-scoped error (${injected.name}) while checking a reserved-name identity is not a slug refusal`, async () => {+ await managedBrain(async ({ engine, ctx }) => {+ const error = injected.error();+ const failing = new Proxy(engine, { get(t, prop) {+ if (prop === 'readPageSnapshot') return () => Promise.reject(error);+ const value = Reflect.get(t, prop, t);+ return typeof value === 'function' ? value.bind(t) : value;+ } });+ const dryCtx: OperationContext = { ...ctx, dryRun: true, engine: failing };+ let thrown: unknown;+ try { await putPage.handler(dryCtx, { slug: 'companies/aux', content: body('Aux') }); } catch (e) { thrown = e; }+ expect(thrown).toBe(error);+ }, { databaseUrl });+ }, 120_000);+ }+ });+}