Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(slugs): GBRA-130 B-12 refuse unportable new slugs and map ENAMETOOLONG to file_name_too_long

garrytan93175bab3e23
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 170b1a263d..306d9bc274 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -41,7 +41,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa
- `src/core/persistence/page-edit.ts` — `edit_page` (#5616): splits the canonical serialization into editable text and protected takes/facts segments whose remote view matches get_page's sanitized `content` byte for byte; `applyPageEdits` applies ordered exact-once replacements inside editable text only (typed `edit_no_match`/`edit_ambiguous_match`/`edit_protected_span`/`edit_invalid`), so canonical fences never move; `editDiff` caps the caller-view diff at 8 KB; `boundedUnifiedDiff` keeps its LCS table under `EDIT_PAGE_DIFF_CELL_BUDGET` (4M cells) by diffing only the window between common leading/trailing lines, and a window still over budget becomes one coarse hunk flagged `diff_coarse` (pinned by `test/large-pages/edit-diff-bounded.test.ts`). Called at submission (`page-mutations.ts`, before admission) and again on the locked snapshot in `page-prepare.ts`, which gives edit_page put_page's revision-bound `editing` timeline semantics. Pinned by `test/edit-page.test.ts`.
- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A page file target's optional `commit` note (`GitCommitNote`, set only by trusted local preparers: a fence repair's `fenceRepairCommit`) is queued as `commit_subject`/`commit_line` in the Git effect's data and passed by the runner to `commitGitTargets`/`publishGitEffect`: a noted path committing alone takes its subject; a group keeps `gbrain: persist N canonical memory updates` and lists the noted paths' lines in the body, in path order; control characters are stripped, and targets without a note commit exactly as before (`test/fence-repair-receipts.test.ts`). A group yields to publications still queued or running for its worktree (one update requeues it with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group, and a write admitted behind a backlog of full groups takes the worktree lock after the group already committing (wave 9; on master it waited out the backlog and its 5 s write wait); the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. `claimCoalescedGitEffects` checks the worktree-wide conditions (owner, refresh fence, recovery blocks) once as an InitPlan, so the claim walks `persistence_effects_pending` in order and stops at its limit (351 → 25 ms per claim with 22k ready effects). A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once. In a root without the durability hook a group runs no git command: it takes each root's lock once, guards each source incarnation once, validates every path as before and records the `durability_not_enabled` outcomes in one update (a 50k import's ~30k queued effects drain inside a minute of serve) (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits) and transient database failures do not count): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. A mirror or Git scan never parks on a sync-skip metafile page (`RESOLVER.md` carries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (`file_database_drift`): the mirror materializes the withdrawal in the database without touching the file, both scans record the page in `data.skipped` (at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); tests: `persistence-effect-parking.test.ts`. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated; the lock is never removed, because no timestamp proves its holder is gone.
-- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct. #5032: `isWindowsColonTarget(rel)` and `colonSlugWindowsRefusal(slug, sourceId)` name the one Windows-only refusal (`colon_slug_windows_write_through`: `:` names an NTFS alternate data stream); `submitPageMutation` raises it before admission when this host publishes the file, `prepareFileTarget` at publication, and managed (`fileRefusals`) and unmanaged (`failedFiles`) sync skip each such path by name (`test/colon-slug-windows-5032.test.ts`).
+- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct. #5032: `isWindowsColonTarget(rel)` and `colonSlugWindowsRefusal(slug, sourceId)` name the one Windows-only refusal (`colon_slug_windows_write_through`: `:` names an NTFS alternate data stream); `submitPageMutation` raises it before admission when this host publishes the file, `prepareFileTarget` at publication, and managed (`fileRefusals`) and unmanaged (`failedFiles`) sync skip each such path by name (`test/colon-slug-windows-5032.test.ts`). A path segment over 255 bytes, or `ENAMETOOLONG` from the lookup, refuses `invalid_params` with detail `file_name_too_long` and a fix naming a slug whose segments fit 240 bytes (`test/pathological/b12-slug-segment-bytes.test.ts`).
- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection. A lock holder that is not a serve and answers no owner socket (a concurrent CLI call) is not a resident owner: `maybeDelegateLocalOperation` returns unhandled and the engine path waits for the PGLite lock instead of answering `owner_unavailable`; a serve holder or an answering socket keeps every failure final. Owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. For an op that owns a `source` param (`opOwnsSource`, `src/core/ops/contract.ts`), `params.source` stays on the wire as the op's own value (provenance) and routing comes from the ambient tiers, as on the direct and thin-client CLI routes (`test/cli-op-owned-source.test.ts`). The production provider dispatches the trusted `local_cli` principal's allow-listed skill-administration ops with the `'stdio'` locality marker, so the four `localOnly` ones (`get_skill_retention`, `prune_skill_revisions`, `retain_skill_revision`, `import_skill_proposal`) work while a serve owns the brain, as do `takes_remove` and `takes_rebuild` (`LOCAL_CLI_LOCAL_ONLY_OPS`) for the `local_cli` principal (write scope still checked; `gbrain takes remove` and `gbrain takes rebuild` defer their engine like the other takes verbs); other local calls keep no marker (`test/persistence-local-only-ops.test.ts`). `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. `residentPersistenceConfig` resolves a resident serve's brain the same way (`--brain`, `GBRAIN_BRAIN_ID`, `.gbrain-mount`, mount path), so the owner socket and the provider's consumer config follow a mounted brain instead of the host config (#5237); hook IPC stays keyed off the host config. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`, `test/serve-mounted-owner.test.ts`. A credential-free, read-only `projection_status` request (like `capabilities`) returns the resident's projection backlog counts (`PersistenceProjectionStatus`, no identifiers) so doctor's `text_projection_readiness` can report it while the resident holds a PGLite datastore (#5401, `test/projection-resident-doctor.test.ts`).
diff --git a/docs/architecture/key-files/page-identity-and-administration.md b/docs/architecture/key-files/page-identity-and-administration.md
index 64f57c4b2b..17fd64d73f 100644
--- a/docs/architecture/key-files/page-identity-and-administration.md
+++ b/docs/architecture/key-files/page-identity-and-administration.md
@@ -79,4 +79,6 @@ upgrade consequence and engine parity respectively.
## Suffixed slugs
-- `src/core/persistence/suffixed-slug.ts` — `.md`/`.mdx`-suffixed slugs (#4807). `preparePageAdmission` refuses a new put_page/put_pages slug ending in `.md`/`.mdx` before any journal row (`invalid_params`, why, suggestion naming the bare slug, read-only `get_page` fix and verify); a live page with that exact (source_id, slug) still updates and the put_page response carries `slug_advisory` (put under the bare slug, then delete_page). `suffixedSlugDryRun` serves put_page dry runs; `suffixedFrontmatterSlugHold` holds a file import whose frontmatter `slug:` identity ends in `.md` as `frontmatter_slug_conflict`. `validateSlug` and path-derived import slugs are unchanged. Test: `test/ingestion/put-page-write-through.test.ts`.
+- `src/core/persistence/suffixed-slug.ts` — `.md`/`.mdx`-suffixed slugs (#4807). `preparePageAdmission` refuses a new put_page/put_pages slug ending in `.md`/`.mdx` before any journal row (`invalid_params`, why, suggestion naming the bare slug, read-only `get_page` fix and verify); a live page with that exact (source_id, slug) still updates and the put_page response carries `slug_advisory` (put under the bare slug, then delete_page). `suffixedSlugDryRun` serves put_page dry runs; `suffixedFrontmatterSlugHold` holds a file import whose frontmatter `slug:` identity ends in `.md` as `frontmatter_slug_conflict`. The same admission refuses a NEW slug with a Windows reserved device segment or a segment over 240 bytes (`slug_not_portable`, suggestion from `portable-slug.ts`); a live page with that slug still updates and gets a `slug_advisory` naming the move. `:` stays valid slug grammar. `validateSlug` and path-derived import slugs are unchanged. Tests: `test/ingestion/put-page-write-through.test.ts`, `test/pathological/b5-export-unsafe-slugs.test.ts`, `test/pathological/b12-slug-segment-bytes.test.ts`.
+
+- `src/core/portable-slug.ts` — the one slug portability rule (GBRA-130 B-5/B-12): `FILE_NAME_MAX_BYTES` (240, a name's byte budget; a leaf also reserves `.json`), `RESERVED_DEVICE_NAME` (con, prn, aux, nul, com1-9, lpt1-9, alone or before an extension), `truncateUtf8`, `portableSegment` (a reserved name gets `-<suffix>`, an over-budget segment is cut at a code point boundary) and `slugPortabilityProblem` (reason, first segment, suggested slug). Used by `persistence/suffixed-slug.ts` admission and `enrichment-service.ts` `slugifyEntity`, so a reserved entity name mints `people/con-person` or `companies/com1-company`.
diff --git a/src/core/persistence/native-file-target.ts b/src/core/persistence/native-file-target.ts
index 21f5679faa..42c99646fa 100644
--- a/src/core/persistence/native-file-target.ts
+++ b/src/core/persistence/native-file-target.ts
@@ -1,8 +1,22 @@
import { lstatSync, readdirSync, realpathSync, statSync, type BigIntStats } from 'node:fs';
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
import { catalogueError } from '../error-catalogue.ts';
+/** The longest file or directory name, in bytes, the supported file systems store (NAME_MAX). */
+const NATIVE_NAME_MAX_BYTES = 255;
+
+/**
+ * A name the file system cannot store (over NAME_MAX bytes, or ENAMETOOLONG):
+ * the slug is the problem, so it is a caller error with the move as its fix,
+ * never a storage failure an agent retries.
+ */
+function fileNameTooLong(): OperationError {
+ return opError('invalid_params', 'The canonical file name is longer than the file system allows.',
+ 'Write the page under a slug whose segments are at most 240 bytes each (put_page refuses new longer ones and names one), then delete_page the old slug.',
+ { detail: 'file_name_too_long', why: `A slug segment becomes a file or directory name, and file systems store at most ${NATIVE_NAME_MAX_BYTES} bytes per name.` });
+}
+
export function nativeFileTarget(root: string, target: string, code?: string): string {
const unsafe = () => new OperationError(code ?? 'source_changed', 'The canonical file target has no unambiguous native identity.',
'Reconcile the recorded file path with the registered worktree before retrying publication.');
@@ -16,6 +30,7 @@ export function nativeFileTarget(root: string, target: string, code?: string): s
const rootInfo = statSync(physicalRoot, { bigint: true });
if (!rootInfo.isDirectory()) throw unsafe();
const segments = path.split(sep);
+ if (segments.some(segment => Buffer.byteLength(segment) > NATIVE_NAME_MAX_BYTES)) throw fileNameTooLong();
const names: string[] = [];
let parent = physicalRoot;
for (let i = 0; i < segments.length; i++) {
@@ -23,6 +38,7 @@ export function nativeFileTarget(root: string, target: string, code?: string): s
let info: BigIntStats;
try { info = lstatSync(join(parent, name), { bigint: true }); }
catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENAMETOOLONG') throw fileNameTooLong();
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
names.push(...segments.slice(i));
break;
diff --git a/src/core/persistence/suffixed-slug.ts b/src/core/persistence/suffixed-slug.ts
index 2a9776742c..0535d588f1 100644
--- a/src/core/persistence/suffixed-slug.ts
+++ b/src/core/persistence/suffixed-slug.ts
@@ -12,11 +12,19 @@
* its identity from a frontmatter `slug:` follows the same rule through the
* held-file path; path-derived import slugs, `validateSlug` and every internal
* stored-identity reader are unchanged.
+ *
+ * The same admission refuses a new identity whose file name no supported
+ * platform can store (GBRA-130 B-5, B-12: a Windows reserved device name such
+ * as `companies/aux`, or a segment over the 240-byte file-name budget;
+ * portable-slug.ts), naming the portable slug to write instead. A live page
+ * already holding such a slug keeps accepting updates with an advisory, and a
+ * replayed request never reaches this check.
*/
import type { BrainEngine } from '../engine.ts';
import type { ContentRefusal } from '../import-screen.ts';
import { opError, type OperationContext, type OperationError } from '../ops/contract.ts';
import { opTransport, readFix } from '../ops/op-fix.ts';
+import { slugPortabilityProblem, type SlugPortabilityProblem } from '../portable-slug.ts';
const MARKDOWN_SUFFIX = /(\.mdx?)+$/i;
@@ -39,15 +47,35 @@ function refusal(ctx: OperationContext, bare: string): OperationError {
});
}
+function portabilityRefusal(ctx: OperationContext, slug: string, problem: SlugPortabilityProblem): OperationError {
+ const cli = opTransport(ctx) === 'cli';
+ const what = problem.reason === 'reserved_name' ? `"${problem.segment}" is a name Windows reserves for a device`
+ : `"${problem.segment.slice(0, 24)}…" is longer than the 240-byte file-name budget`;
+ return opError('invalid_params', `New page slugs must be portable file names: ${what}.`,
+ cli ? `Write the page as ${problem.suggestion}: gbrain put ${problem.suggestion}`
+ : `Call put_page again with slug "${problem.suggestion}" and the same content.`, {
+ detail: 'slug_not_portable',
+ why: 'Each slug segment becomes a file or directory name on disk and in exports, and that name cannot be stored on every supported platform.',
+ fix: {
+ ...readFix('Checks whether the portable slug already holds a page before writing it there.',
+ { argv: ['gbrain', 'get', problem.suggestion], mcp: { tool: 'get_page', arguments: { slug: problem.suggestion } } }),
+ verify: { argv: ['gbrain', 'get', problem.suggestion], mcp: { tool: 'get_page', arguments: { slug: problem.suggestion } } },
+ },
+ });
+}
+
/**
- * Refuses a new suffixed slug; for a live exact-identity page returns the
- * advisory to attach to the response. Null for every other slug.
+ * Refuses a new suffixed or unportable slug; for a live exact-identity page
+ * returns the advisory to attach to the response. Null for every other slug.
*/
export function suffixedSlugAdmission(ctx: OperationContext, slug: string, liveExactRow: boolean): string | null {
const bare = bareSlugOf(slug);
- if (bare === null) return null;
- if (!liveExactRow) throw refusal(ctx, bare);
- return `This page's slug ends in .md, which new pages cannot use. To move it, put_page its content under "${bare}", then delete_page "${slug}".`;
+ const problem = slugPortabilityProblem(bare ?? slug);
+ if (bare === null && problem === null) return null;
+ if (!liveExactRow) throw bare !== null ? refusal(ctx, bare) : portabilityRefusal(ctx, slug, problem!);
+ const target = problem?.suggestion ?? bare!;
+ const why = bare !== null ? 'ends in .md, which new pages cannot use' : 'is not a portable file name, which new pages need';
+ return `This page's slug ${why}. To move it, put_page its content under "${target}", then delete_page "${slug}".`;
}
@@ -58,7 +86,8 @@ async function liveExactRow(engine: BrainEngine, sourceId: string, slug: string)
/** Dry-run form: reads the exact `(source_id, slug)` row itself. */
export async function suffixedSlugDryRun(ctx: OperationContext, sourceId: string, slug: string): Promise<void> {
- if (bareSlugOf(slug) === null) return;
+ const bare = bareSlugOf(slug);
+ if (bare === null && slugPortabilityProblem(slug) === null) return;
suffixedSlugAdmission(ctx, slug, await liveExactRow(ctx.engine, sourceId, slug.toLowerCase()));
}
diff --git a/src/core/portable-slug.ts b/src/core/portable-slug.ts
new file mode 100644
index 0000000000..e1fef0a0aa
--- /dev/null
+++ b/src/core/portable-slug.ts
@@ -0,0 +1,69 @@
+/**
+ * Page slugs whose file names every supported platform can store (GBRA-130
+ * B-5, B-12). A page lives at `<slug>.md` (its raw sidecar at
+ * `.raw/<leaf>.json`), so each slug segment becomes a file or directory name:
+ * Windows refuses its reserved device names (`con`, `aux`, `nul.x`, `com1`,
+ * ...) and file systems cap a name at 255 bytes, which a 255-character
+ * segment in a multi-byte script passes in UTF-16 units but not in bytes.
+ *
+ * `slugPortabilityProblem` is the rule new page identities are admitted under
+ * (put_page, put_pages; persistence/suffixed-slug.ts), entity stubs mint
+ * around (enrichment-service.ts slugifyEntity), and export escapes for pages
+ * an older gbrain admitted (export-stage.ts exportPagePath). Existing pages
+ * keep accepting updates; the colon namespace (`ns:foo`) is slug grammar and
+ * is not a portability problem here (export escapes it).
+ */
+
+/** Longest file name, in UTF-8 bytes, a page's files may use: the export and write-through budget. */
+export const FILE_NAME_MAX_BYTES = 240;
+/** The longest extension a slug's leaf segment gets on disk (`.raw/<leaf>.json`; the page itself is `<leaf>.md`). */
+const LEAF_EXTENSION_BYTES = '.json'.length;
+/** A Windows reserved device name, alone or before an extension (`aux`, `nul.x`). */
+export const RESERVED_DEVICE_NAME = /^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?=\.|$)/i;
+
+export interface SlugPortabilityProblem {
+ reason: 'reserved_name' | 'segment_too_long';
+ /** The first offending segment. */
+ segment: string;
+ /** The slug with every offending segment made portable: the slug to write instead. */
+ suggestion: string;
+}
+
+/** The byte budget of one segment's name: a leaf also carries its extension. */
+export function segmentByteBudget(leaf: boolean): number {
+ return FILE_NAME_MAX_BYTES - (leaf ? LEAF_EXTENSION_BYTES : 0);
+}
+
+/** The longest prefix of `text` within `bytes` UTF-8 bytes, cut at a code point boundary. */
+export function truncateUtf8(text: string, bytes: number): string {
+ let used = 0;
+ let out = '';
+ for (const char of text) {
+ const size = Buffer.byteLength(char);
+ if (used + size > bytes) break;
+ used += size;
+ out += char;
+ }
+ return out;
+}
+
+/** One segment made portable: a reserved device name gets `-<suffix>`, an over-long name is cut to its budget. */
+export function portableSegment(segment: string, leaf: boolean, suffix = 'page'): string {
+ const renamed = segment.replace(RESERVED_DEVICE_NAME, name => `${name}-${suffix}`);
+ const budget = segmentByteBudget(leaf);
+ return Buffer.byteLength(renamed) <= budget ? renamed : truncateUtf8(renamed, budget).replace(/[-._:]+$/, '');
+}
+
+/** Null when every segment of `slug` is a portable file name; otherwise the first problem and the portable slug to use. */
+export function slugPortabilityProblem(slug: string, suffix = 'page'): SlugPortabilityProblem | null {
+ const segments = slug.split('/');
+ let first: Omit<SlugPortabilityProblem, 'suggestion'> | null = null;
+ const fixed = segments.map((segment, i) => {
+ const leaf = i === segments.length - 1;
+ const reserved = RESERVED_DEVICE_NAME.test(segment);
+ if (!reserved && Buffer.byteLength(segment) <= segmentByteBudget(leaf)) return segment;
+ first ??= { reason: reserved ? 'reserved_name' : 'segment_too_long', segment };
+ return portableSegment(segment, leaf, suffix);
+ });
+ return first === null ? null : { ...(first as Omit<SlugPortabilityProblem, 'suggestion'>), suggestion: fixed.join('/') };
+}
diff --git a/test/pathological/b12-slug-segment-bytes.test.ts b/test/pathological/b12-slug-segment-bytes.test.ts
new file mode 100644
index 0000000000..f1e66786b4
--- /dev/null
+++ b/test/pathological/b12-slug-segment-bytes.test.ts
@@ -0,0 +1,111 @@
+/**
+ * B-12 (GBRA-130): a slug segment longer than a file name may be (bytes, not
+ * UTF-16 units) is refused as a caller error before admission, never retried
+ * as a storage failure.
+ *
+ * Protects: put_page and its dry run refuse a NEW page whose segment is over
+ * the 240-byte file-name budget (90 CJK characters: 270 bytes, 90 UTF-16
+ * units) with invalid_params, detail slug_not_portable and the shortened slug
+ * to write instead, while a healthy sibling write lands and nothing else
+ * changes; a page an older gbrain stored under such a slug keeps its row, and
+ * publishing its file ends its write failed with invalid_params (nativeFileTarget
+ * refuses a name over NAME_MAX and maps ENAMETOOLONG to detail file_name_too_long) instead of storage_error with a
+ * "repair the filesystem" fix agents retry. A run-scoped error while checking
+ * the existing identity is not turned into a slug refusal.
+ * Fails when: validatePageSlug's 255-unit check is the only gate (the write is
+ * admitted and its publication fails storage_error), or ENAMETOOLONG falls into
+ * nativeFileTarget's generic inaccessible branch.
+ * Seams: none; the run case wraps the engine in a Proxy. PGLite always,
+ * Postgres when DATABASE_URL is set.
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync } 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 { operations, OperationError, type OperationContext } from '../../src/core/operations.ts';
+import { nativeFileTarget } from '../../src/core/persistence/native-file-target.ts';
+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, managedBrain, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';
+
+const putPage = operations.find(op => op.name === 'put_page')!;
+const LONG = 'notes/' + '漢'.repeat(90);
+const body = (title: string) => `---\ntitle: ${title}\ntype: note\n---\n# ${title}\n\nBody of ${title}.\n`;
+
+async function refusal(run: Promise<unknown>): Promise<OperationError> {
+ try { await run; } catch (error) { if (error instanceof OperationError) return error; throw error; }
+ throw new Error('expected a refusal');
+}
+const asFailure = (key: string, error: OperationError) => ({ key, code: String(error.code), detail: error.detail, fix: error.fix });
+
+function failingReads(engine: BrainEngine, injected: unknown): BrainEngine {
+ return new Proxy(engine, { get(target, prop) {
+ if (prop === 'readPageSnapshot') return () => Promise.reject(injected);
+ const value = Reflect.get(target, prop, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+}
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`B-12 slug segment bytes (${backend})`, () => {
+ test('B-12 item: a new 90-CJK-character segment is refused invalid_params with a shorter slug; a sibling lands', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ await putPage.handler(ctx, { slug: 'notes/kept', content: body('Kept') });
+ const before = await snapshotItems(engine, 'default');
+ const error = await refusal(Promise.resolve(putPage.handler(ctx, { slug: LONG, content: body('Long') })));
+ expect({ code: error.code, detail: error.detail }).toEqual({ code: 'invalid_params', detail: 'slug_not_portable' });
+ const suggestion = 'notes/' + '漢'.repeat(78);
+ expectItemFailure(asFailure(LONG, error), { key: LONG, code: 'invalid_params', fix: new RegExp(`^gbrain get ${suggestion}$`) });
+ expect(error.suggestion).toContain(`gbrain put ${suggestion}`);
+ const dry = await refusal(Promise.resolve(putPage.handler({ ...ctx, dryRun: true }, { slug: LONG, content: body('Long') })));
+ expect({ code: dry.code, detail: dry.detail }).toEqual({ code: 'invalid_params', detail: 'slug_not_portable' });
+ await expectUnitNotAborted(() => Promise.resolve(putPage.handler(ctx, { slug: 'notes/sibling', content: body('Sibling') })));
+ expect(await engine.getPage(LONG, { sourceId: 'default' })).toBeNull();
+ expectOthersUnchanged(before, await snapshotItems(engine, 'default'), { changed: ['notes/sibling'] });
+ expect(await engine.getPage('notes/sibling', { sourceId: 'default' })).not.toBeNull();
+ await expectUnitNotAborted(() => Promise.resolve(putPage.handler(ctx, { slug: suggestion, content: body('Long') })));
+ }, { databaseUrl });
+ }, 120_000);
+
+ test('B-12 item: a stored long-segment page publishes as a failed invalid_params write, not storage_error', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ await putPage.handler(ctx, { slug: 'notes/kept', content: body('Kept') });
+ const before = await snapshotItems(engine, 'default');
+ const snapshot = (await engine.readPageSnapshot(LONG, { sourceId: 'default' }))!;
+ const error = await refusal(Promise.resolve(putPage.handler(ctx, { slug: LONG, content: body('Legacy'), expected_revision: snapshot.revision, request_id: randomUUID() })));
+ expect({ code: error.code, writeError: error.writeError, message: error.message })
+ .toEqual({ code: 'invalid_params', writeError: 'invalid_params', message: 'The canonical file name is longer than the file system allows.' });
+ expect(error.suggestion).toContain('will not publish');
+ expectOthersUnchanged(before, await snapshotItems(engine, 'default'));
+ }, { databaseUrl, setup: async ({ engine, root }) => {
+ mkdirSync(join(root, 'notes'));
+ await engine.putPage(LONG, { type: 'note', title: 'Legacy', compiled_truth: 'stored body', timeline: '' }, { sourceId: 'default' });
+ } });
+ }, 120_000);
+
+ test('B-12 item: nativeFileTarget maps ENAMETOOLONG to invalid_params file_name_too_long', () => {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-b12-'));
+ try {
+ let thrown: unknown;
+ try { nativeFileTarget(root, join(root, 'notes', '漢'.repeat(90) + '.md')); } catch (error) { thrown = error; }
+ expect(thrown).toBeInstanceOf(OperationError);
+ expect({ code: (thrown as OperationError).code, detail: (thrown as OperationError).detail }).toEqual({ code: 'invalid_params', detail: 'file_name_too_long' });
+ expect(nativeFileTarget(root, join(root, 'notes', '漢'.repeat(70) + '.md'))).toBe(join(root, 'notes', '漢'.repeat(70) + '.md'));
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ });
+
+ for (const injected of runScopedErrors().filter(e => e.name === 'connection lost' || e.name === 'failed transaction (25P02)')) {
+ test(`B-12 run: a run-scoped error (${injected.name}) while checking the identity is not a slug refusal`, async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ const before = await snapshotItems(engine, 'default');
+ const error = injected.error();
+ const dryCtx: OperationContext = { ...ctx, dryRun: true, engine: failingReads(engine, error) };
+ let thrown: unknown;
+ try { await putPage.handler(dryCtx, { slug: LONG, content: body('Long') }); } catch (e) { thrown = e; }
+ expect(thrown).toBe(error);
+ expectOthersUnchanged(before, await snapshotItems(engine, 'default'));
+ }, { databaseUrl });
+ }, 120_000);
+ }
+ });
+}