Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(pathological): GBRA-133 lane B probe fixture and cases (from gbra133-blockers 53a31e9f)
garrytan58c35da71c1a
diff --git a/test/pathological/s-blockers-cases.ts b/test/pathological/s-blockers-cases.tsnew file mode 100644index 0000000000..33751fd218--- /dev/null+++ b/test/pathological/s-blockers-cases.ts@@ -0,0 +1,268 @@+/**+ * GBRA-133 lane B: the odd inputs each probe commits next to a healthy sibling.+ * Row ids (S-n) match ~/.capy/work/gbra133/blockers.md. A case's mutate writes+ * the odd input (the runner has already written ok/healthy-1.md) and commits,+ * unless it needs another order. custom cases run their own flow.+ */+import { execFileSync } from 'node:child_process';+import { chmodSync, mkdirSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { gitIn, md, type ProbeRepo, type SyncMode } from './s-blockers-fixture.ts';+import { performManagedSync } from '../../src/core/persistence/sync-run.ts';+import { readSyncStatus } from '../../src/core/persistence/sync-status.ts';++export interface BlockerCase {+ id: string;+ name: string;+ /** Repo-relative odd path(s) (string) used to find a ledger row, refusal or hold that names it. */+ odd: string[];+ /** Slug the odd file would import as, when importing it is the right outcome. */+ oddSlug?: string;+ /** Runs after the first sync with ok/healthy-1.md already on disk; must leave HEAD with healthy-1 committed. */+ mutate(r: ProbeRepo): void | Promise<void>;+ /** Before the first sync (after the seed commit). */+ prepare?(r: ProbeRepo): void | Promise<void>;+ /** Build the repo root yourself (it must already hold a seed commit); the runner skips init and seed. */+ makeRoot?(home: string): string;+ skip?(mode: SyncMode): string | false;+ /** Sync with git pull (noPull false). */+ pull?: boolean;+ /** For pull cases: the upstream repo the healthy-2 commit must reach before the third sync. */+ upstream?(r: ProbeRepo): string;+ /** Skipping or refusing the odd file is the right outcome only when it is reported; importing it is not required. */+ importNotRequired?: boolean;+}++const BIN_PNG = Buffer.from('89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d4944415478da63fcffff3f0300050001ffa1e3d40000000049454e44ae426082', 'hex');+const sh = (cwd: string, cmd: string) => execFileSync('bash', ['-c', cmd], { cwd, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] });+const commit = (r: ProbeRepo, msg = 'odd') => r.commitAll(msg);+const looseObjectPath = (r: ProbeRepo, sha: string) => join(r.root, '.git', 'objects', sha.slice(0, 2), sha.slice(2));++export const CASES: BlockerCase[] = [+ // ---- filenames --------------------------------------------------------------------------------+ { id: 'S-1', name: 'filename with double quotes', odd: ['notes/say "hi".md'], oddSlug: undefined,+ mutate: r => { r.write('notes/say "hi".md', md('quoted')); commit(r); } },+ { id: 'S-2', name: 'filename with a newline', odd: ['notes/line\nbreak.md'],+ mutate: r => { r.write('notes/line\nbreak.md', md('newline')); commit(r); } },+ { id: 'S-3', name: 'filename with a tab', odd: ['notes/tab\there.md'],+ mutate: r => { r.write('notes/tab\there.md', md('tab')); commit(r); } },+ { id: 'S-4', name: 'filename with a backslash', odd: ['notes/back\\slash.md'],+ mutate: r => { r.write('notes/back\\slash.md', md('backslash')); commit(r); } },+ { id: 'S-5', name: 'filename with a leading dash', odd: ['-dash.md', 'notes/--help.md'], oddSlug: 'notes/help',+ mutate: r => { r.write('-dash.md', md('dash')); r.write('notes/--help.md', md('help')); commit(r); } },+ { id: 'S-6', name: 'filename with a colon (POSIX)', odd: ['notes/a:b.md'], oddSlug: 'notes/a:b',+ mutate: r => { r.write('notes/a:b.md', md('colon')); commit(r); } },+ { id: 'S-7', name: 'non-UTF-8 filename (latin-1 byte 0xE9)', odd: ['notes/caf'],+ mutate: r => { r.write(Buffer.concat([Buffer.from('notes/caf'), Buffer.from([0xe9]), Buffer.from('.md')]), md('latin1')); commit(r); } },+ { id: 'S-8', name: 'NFD unicode filename', odd: ['notes/jose\u0301.md'], oddSlug: 'notes/jos\u00e9',+ mutate: r => { r.write('notes/jose\u0301.md', md('nfd')); commit(r); } },+ { id: 'S-9', name: 'NFC and NFD twins of one name', odd: ['notes/jos\u00e9.md', 'notes/jose\u0301.md'], importNotRequired: true,+ mutate: r => { r.write('notes/jos\u00e9.md', md('nfc')); r.write('notes/jose\u0301.md', md('nfd')); commit(r); } },+ { id: 'S-10', name: '255-byte filename component', odd: ['notes/' + 'a'.repeat(252) + '.md'], oddSlug: 'notes/' + 'a'.repeat(252),+ mutate: r => { r.write('notes/' + 'a'.repeat(252) + '.md', md('long')); commit(r); } },+ { id: 'S-11', name: 'very deep path (40 levels, ~3 KB)', odd: ['deep/'], oddSlug: undefined, importNotRequired: true,+ mutate: r => { r.write('deep/' + Array.from({ length: 40 }, (_, i) => 'level-' + String(i).padStart(2, '0') + '-' + 'x'.repeat(60)).join('/') + '/leaf.md', md('deep')); commit(r); } },+ { id: 'S-12', name: 'a directory named x.md', odd: ['notes/dir.md'], oddSlug: 'notes/dir.md/inner',+ mutate: r => { r.write('notes/dir.md/inner.md', md('inner')); commit(r); } },+ { id: 'S-13', name: 'filename with leading space and trailing-space directory', odd: ['notes/ lead.md', 'trail /x.md'],+ mutate: r => { r.write('notes/ lead.md', md('lead')); r.write('trail /x.md', md('trail')); commit(r); } },+ { id: 'S-14', name: 'case-only rename with core.ignorecase=true', odd: ['notes/case.md', 'notes/Case.md'], oddSlug: 'notes/case',+ prepare: r => { r.write('notes/Case.md', md('Case')); commit(r, 'case'); },+ mutate: r => { r.git('config', 'core.ignorecase', 'true'); r.git('mv', 'notes/Case.md', 'notes/case.md'); r.write('notes/case.md', md('case renamed')); commit(r); } },+ { id: 'S-15', name: 'two files differing only by case', odd: ['notes/Dup.md', 'notes/dup.md'], importNotRequired: true,+ mutate: r => { r.write('notes/Dup.md', md('Dup')); r.write('notes/dup.md', md('dup')); commit(r); } },++ // ---- symlinks ---------------------------------------------------------------------------------+ { id: 'S-16', name: 'symlink to a file inside the repo', odd: ['notes/link.md'], importNotRequired: true,+ mutate: r => { r.write('notes/real.md', md('real')); symlinkSync('real.md', join(r.root, 'notes/link.md')); commit(r); } },+ { id: 'S-17', name: 'symlink pointing outside the repo', odd: ['notes/out.md'], importNotRequired: true,+ mutate: r => { writeFileSync(join(r.home, 'outside-secret.md'), md('outside')); mkdirSync(join(r.root, 'notes'), { recursive: true }); symlinkSync(join(r.home, 'outside-secret.md'), join(r.root, 'notes/out.md')); commit(r); } },+ { id: 'S-18', name: 'dangling symlink', odd: ['notes/dangling.md'], importNotRequired: true,+ mutate: r => { mkdirSync(join(r.root, 'notes'), { recursive: true }); symlinkSync('nowhere.md', join(r.root, 'notes/dangling.md')); commit(r); } },+ { id: 'S-19', name: 'symlinked directory holding markdown', odd: ['linked'], importNotRequired: true,+ mutate: r => { r.write('real-dir/inside.md', md('inside')); symlinkSync('real-dir', join(r.root, 'linked')); commit(r); } },+ { id: 'S-20', name: 'symlink loop', odd: ['loop1.md', 'loop2.md'], importNotRequired: true,+ mutate: r => { symlinkSync('loop2.md', join(r.root, 'loop1.md')); symlinkSync('loop1.md', join(r.root, 'loop2.md')); commit(r); } },+ { id: 'S-21', name: 'typechange: imported file becomes a symlink', odd: ['notes/t.md'], importNotRequired: true,+ prepare: r => { r.write('notes/t.md', md('t')); r.write('notes/target.md', md('target')); commit(r, 't'); },+ mutate: r => { unlinkSync(join(r.root, 'notes/t.md')); symlinkSync('target.md', join(r.root, 'notes/t.md')); commit(r); } },+ { id: 'S-22', name: 'typechange: imported file becomes a directory', odd: ['notes/fd.md'], oddSlug: 'notes/fd.md/x',+ prepare: r => { r.write('notes/fd.md', md('fd')); commit(r, 'fd'); },+ mutate: r => { unlinkSync(join(r.root, 'notes/fd.md')); r.write('notes/fd.md/x.md', md('fdx')); commit(r); } },++ // ---- repository structure ---------------------------------------------------------------------+ { id: 'S-23', name: 'nested git repo committed as a gitlink (embedded repo)', odd: ['nested'], importNotRequired: true,+ mutate: r => {+ const nested = join(r.root, 'nested'); mkdirSync(nested);+ gitIn(nested, 'init', '-q'); writeFileSync(join(nested, 'n.md'), md('n'));+ gitIn(nested, '-c', 'user.name=E', '-c', '[email protected]', 'add', '-A');+ gitIn(nested, '-c', 'user.name=E', '-c', '[email protected]', 'commit', '-qm', 'n');+ commit(r);+ } },+ { id: 'S-24', name: 'submodule declared in .gitmodules but not initialized', odd: ['sub'], importNotRequired: true,+ mutate: r => {+ const up = join(r.home, 'sub-upstream-' + r.sourceId); mkdirSync(up); gitIn(up, 'init', '-q', '-b', 'main');+ writeFileSync(join(up, 's.md'), md('s')); gitIn(up, 'add', '-A'); gitIn(up, '-c', 'user.name=E', '-c', '[email protected]', 'commit', '-qm', 's');+ r.git('-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', up, 'sub');+ commit(r);+ rmSync(join(r.root, 'sub'), { recursive: true, force: true }); mkdirSync(join(r.root, 'sub'));+ } },+ { id: 'S-25', name: '.gitattributes filter=lfs on one markdown file (LFS pointer content, no lfs installed)', odd: ['notes/lfs.md'], oddSlug: 'notes/lfs',+ mutate: r => {+ r.write('.gitattributes', 'notes/lfs.md filter=lfs diff=lfs merge=lfs -text\n');+ r.write('notes/lfs.md', 'version https://git-lfs.github.com/spec/v1\noid sha256:' + 'a'.repeat(64) + '\nsize 12345\n');+ commit(r);+ } },+ { id: 'S-26', name: '.gitattributes with a working-tree-encoding on one markdown file', odd: ['notes/utf16.md'], oddSlug: 'notes/utf16',+ mutate: r => {+ r.write('.gitattributes', 'notes/utf16.md working-tree-encoding=UTF-16 text\n');+ r.write('notes/utf16.md', Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(md('utf16'), 'utf16le')]));+ commit(r);+ } },+ { id: 'S-27', name: 'sparse checkout leaves a committed file off disk', odd: ['hidden/h.md'], importNotRequired: true,+ mutate: r => {+ r.write('hidden/h.md', md('hidden')); commit(r);+ r.git('sparse-checkout', 'set', '--no-cone', '/*', '!/hidden/');+ } },+ { id: 'S-28', name: 'committed file deleted from the working tree (not committed)', odd: ['notes/gone.md'], importNotRequired: true,+ mutate: r => { r.write('notes/gone.md', md('gone')); commit(r); unlinkSync(join(r.root, 'notes/gone.md')); } },+ { id: 'S-29', name: 'working-tree edit of a committed file that differs from HEAD', odd: ['notes/dirty.md'], importNotRequired: true,+ mutate: r => { r.write('notes/dirty.md', md('committed')); commit(r); r.write('notes/dirty.md', md('uncommitted edit')); } },+ { id: 'S-30', name: 'unreadable file (mode 000)', odd: ['notes/locked.md'], importNotRequired: true,+ skip: () => (process.getuid?.() === 0 ? 'running as root: chmod 000 does not block reads' : false),+ mutate: r => { r.write('notes/locked.md', md('locked')); commit(r); chmodSync(join(r.root, 'notes/locked.md'), 0o000); } },+ { id: 'S-31', name: 'stale .git/index.lock (0 bytes)', odd: [], importNotRequired: true,+ mutate: r => { commit(r); writeFileSync(join(r.root, '.git/index.lock'), ''); } },+ { id: 'S-32', name: 'stale HEAD.lock and refs/heads/main.lock', odd: [], importNotRequired: true,+ mutate: r => { commit(r); writeFileSync(join(r.root, '.git/HEAD.lock'), ''); writeFileSync(join(r.root, '.git/refs/heads/main.lock'), ''); } },+ { id: 'S-33', name: 'missing blob object for a committed file (working tree intact)', odd: ['notes/corrupt.md'], oddSlug: 'notes/corrupt',+ mutate: r => {+ r.write('notes/corrupt.md', md('corrupt unique ' + r.sourceId)); commit(r);+ const sha = r.git('rev-parse', 'HEAD:notes/corrupt.md'); chmodSync(looseObjectPath(r, sha), 0o644); unlinkSync(looseObjectPath(r, sha));+ } },+ { id: 'S-34', name: 'detached HEAD with a new commit', odd: [], importNotRequired: true,+ mutate: r => { r.git('checkout', '-q', '--detach'); commit(r); } },+ { id: 'S-35', name: 'history rewrite: last_commit amended away and garbage-collected', odd: [], importNotRequired: true,+ mutate: r => {+ r.write('seed.md', md('seed rewritten')); r.git('add', '-A'); r.git('commit', '-q', '--amend', '-m', 'seed rewritten');+ r.git('reflog', 'expire', '--expire=now', '--all'); r.git('gc', '-q', '--prune=now');+ } },+ { id: 'S-36', name: 'history rewrite: last_commit still present but no longer an ancestor', odd: [], importNotRequired: true,+ mutate: r => { r.write('seed.md', md('seed amended')); r.git('add', '-A'); r.git('commit', '-q', '--amend', '-m', 'seed amended'); } },+ { id: 'S-37', name: 'orphan branch switch (unrelated history)', odd: [], importNotRequired: true,+ mutate: r => { r.git('checkout', '-q', '--orphan', 'other'); r.write('seed.md', md('orphan seed')); commit(r); } },+ { id: 'S-38', name: 'shallow clone refetched at depth 1 past last_commit', odd: [], importNotRequired: true,+ makeRoot: home => {+ const up = join(home, 'shallow-up-' + Math.random().toString(36).slice(2, 8)); mkdirSync(up);+ gitIn(up, 'init', '-q', '-b', 'main'); writeFileSync(join(up, 'seed.md'), md('seed')); gitIn(up, 'add', '-A');+ gitIn(up, '-c', 'user.name=E', '-c', '[email protected]', 'commit', '-qm', 'seed');+ const root = up + '-clone';+ execFileSync('git', ['-c', 'protocol.file.allow=always', 'clone', '-q', '--depth', '1', 'file://' + up, root]);+ gitIn(root, 'config', 'user.name', 'Example'); gitIn(root, 'config', 'user.email', '[email protected]');+ return root;+ },+ mutate: r => {+ const up = r.root.replace(/-clone$/, '');+ writeFileSync(join(up, 'mid.md'), md('mid')); gitIn(up, 'add', '-A'); gitIn(up, '-c', 'user.name=E', '-c', '[email protected]', 'commit', '-qm', 'mid');+ renameSync(join(r.root, 'ok/healthy-1.md'), join(up, 'healthy-tmp.md'));+ mkdirSync(join(up, 'ok'), { recursive: true }); renameSync(join(up, 'healthy-tmp.md'), join(up, 'ok/healthy-1.md'));+ gitIn(up, 'add', '-A'); gitIn(up, '-c', 'user.name=E', '-c', '[email protected]', 'commit', '-qm', 'healthy');+ r.git('fetch', '-q', '--depth', '1', 'origin', 'main'); r.git('reset', '-q', '--hard', 'FETCH_HEAD');+ r.git('reflog', 'expire', '--expire=now', '--all'); r.git('gc', '-q', '--prune=now');+ } },++ // ---- content ----------------------------------------------------------------------------------+ { id: 'S-39', name: 'NUL bytes in body', odd: ['notes/nul.md'], oddSlug: 'notes/nul',+ mutate: r => { r.write('notes/nul.md', md('nul') + 'before\u0000after\n'); commit(r); } },+ { id: 'S-40', name: 'invalid UTF-8 bytes in body', odd: ['notes/badutf8.md'], oddSlug: 'notes/badutf8',+ mutate: r => { r.write('notes/badutf8.md', Buffer.concat([Buffer.from(md('badutf8')), Buffer.from([0xc3, 0x28, 0xff, 0xfe, 0x0a])])); commit(r); } },+ { id: 'S-41', name: 'UTF-8 BOM before frontmatter', odd: ['notes/bom.md'], oddSlug: 'notes/bom',+ mutate: r => { r.write('notes/bom.md', Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), Buffer.from(md('bom'))])); commit(r); } },+ { id: 'S-42', name: 'CRLF line endings', odd: ['notes/crlf.md'], oddSlug: 'notes/crlf',+ mutate: r => { r.write('notes/crlf.md', md('crlf').replace(/\n/g, '\r\n')); commit(r); } },+ { id: 'S-43', name: 'zero-byte markdown file', odd: ['notes/empty.md'], importNotRequired: true,+ mutate: r => { r.write('notes/empty.md', ''); commit(r); } },+ { id: 'S-44', name: 'binary PNG bytes with a .md extension', odd: ['notes/binary.md'], importNotRequired: true,+ mutate: r => { r.write('notes/binary.md', BIN_PNG); commit(r); } },+ { id: 'S-45', name: 'frontmatter that parses to a YAML list (not a mapping)', odd: ['notes/yaml-list.md'], importNotRequired: true,+ mutate: r => { r.write('notes/yaml-list.md', '---\n- a\n- b\n---\nBody.\n'); commit(r); } },+ { id: 'S-46', name: 'frontmatter that parses to a scalar', odd: ['notes/yaml-scalar.md'], importNotRequired: true,+ mutate: r => { r.write('notes/yaml-scalar.md', '---\njust a string\n---\nBody.\n'); commit(r); } },+ { id: 'S-47', name: 'YAML alias bomb in frontmatter (7 levels: 280 bytes of YAML expand to 22.8 MB of JSON; 9 levels OOM-killed every arm at 15.5 GB RSS)', odd: ['notes/yaml-bomb.md'], importNotRequired: true,+ mutate: r => {+ const lines = ['a: &a ["x","x","x","x","x","x","x","x","x"]'];+ for (let i = 1; i < 7; i++) lines.push(String.fromCharCode(97 + i) + ': &' + String.fromCharCode(97 + i) + ' [' + Array(9).fill('*' + String.fromCharCode(96 + i)).join(',') + ']');+ r.write('notes/yaml-bomb.md', '---\ntitle: bomb\n' + lines.join('\n') + '\n---\nBody.\n'); commit(r);+ } },+ { id: 'S-48', name: 'frontmatter with odd typed values (title is a mapping, tags a number, date invalid)', odd: ['notes/yaml-types.md'], importNotRequired: true,+ mutate: r => { r.write('notes/yaml-types.md', '---\ntitle: {a: 1}\ntags: 42\ndate: 2026-13-45\ntype: [note]\nslug: 7\n---\nBody.\n'); commit(r); } },+ { id: 'S-49', name: 'single 4 MB line with no newline', odd: ['notes/oneline.md'], importNotRequired: true,+ mutate: r => { r.write('notes/oneline.md', '---\ntitle: oneline\n---\n' + 'word '.repeat(800_000)); commit(r); } },+ { id: 'S-50', name: 'lone UTF-16 surrogate escaped in frontmatter', odd: ['notes/surrogate.md'], importNotRequired: true,+ mutate: r => { r.write('notes/surrogate.md', '---\ntitle: "bad \\ud800 surrogate"\n---\nBody.\n'); commit(r); } },+ { id: 'S-56', name: 'managed cursor left unfinished on a target commit that is then rewritten away and garbage-collected', odd: [], importNotRequired: true,+ skip: mode => (mode === 'classic' ? 'managed cursor only' : false),+ mutate: async r => {+ for (let i = 0; i < 6; i++) r.write('batch/b' + i + '.md', md('batch ' + i));+ commit(r, 'batch');+ const partial = await performManagedSync(r.engine, { sourceId: r.sourceId, noPull: true, noEmbed: true, noExtract: true } as never, { maxPages: 1, maxMs: 60_000 });+ const st = await readSyncStatus(r.engine, r.sourceId) as unknown as { state?: string; reason?: string };+ if (partial.status !== 'partial' || st.state !== 'resumable') throw new Error('precondition: expected an unfinished cursor, got ' + partial.status + ' ' + st.state + '/' + st.reason);+ r.write('seed.md', md('seed rewritten under an open cursor')); r.git('add', '-A'); r.git('commit', '-q', '--amend', '-m', 'batch rewritten');+ r.git('reflog', 'expire', '--expire=now', '--all'); r.git('gc', '-q', '--prune=now');+ } },+ { id: 'S-57', name: 'classic pin left by a blocked run, then history rewritten away and garbage-collected', odd: [], importNotRequired: true,+ skip: mode => (mode === 'managed' ? 'classic pin only (the managed twin is S-56)' : process.getuid?.() === 0 ? 'root ignores mode 000' : false),+ mutate: async r => {+ r.write('notes/locked.md', md('locked')); commit(r, 'locked');+ chmodSync(join(r.root, 'notes/locked.md'), 0o000);+ await r.sync().catch(() => undefined);+ chmodSync(join(r.root, 'notes/locked.md'), 0o644);+ r.write('seed.md', md('seed rewritten under a pin')); r.git('add', '-A'); r.git('commit', '-q', '--amend', '-m', 'locked rewritten');+ r.git('reflog', 'expire', '--expire=now', '--all'); r.git('gc', '-q', '--prune=now');+ } },+ { id: 'S-58', name: 'upstream force-push rewrites history under a clone that syncs with pull', odd: [], importNotRequired: true, pull: true,+ skip: mode => (mode === 'managed' ? 'managed sync refuses git pull (writer_coordinator_required); it always runs --no-pull' : false),+ makeRoot: home => {+ const up = join(home, 'fp-up-' + Math.random().toString(36).slice(2, 8)); mkdirSync(up);+ gitIn(up, 'init', '-q', '-b', 'main'); gitIn(up, 'config', 'receive.denyCurrentBranch', 'ignore');+ writeFileSync(join(up, 'seed.md'), md('seed')); gitIn(up, 'add', '-A'); gitIn(up, '-c', 'user.name=E', '-c', '[email protected]', 'commit', '-qm', 'seed');+ const root = up + '-clone';+ execFileSync('git', ['-c', 'protocol.file.allow=always', 'clone', '-q', 'file://' + up, root]);+ gitIn(root, 'config', 'user.name', 'Example'); gitIn(root, 'config', 'user.email', '[email protected]');+ return root;+ },+ upstream: r => r.root.replace(/-clone$/, ''),+ mutate: r => {+ const up = r.root.replace(/-clone$/, '');+ mkdirSync(join(up, 'ok'), { recursive: true }); renameSync(join(r.root, 'ok/healthy-1.md'), join(up, 'ok/healthy-1.md'));+ writeFileSync(join(up, 'seed.md'), md('seed rewritten upstream'));+ gitIn(up, 'add', '-A'); gitIn(up, '-c', 'user.name=E', '-c', '[email protected]', 'commit', '-q', '--amend', '-m', 'seed rewritten upstream');+ } },+ { id: 'S-59', name: 'upstream force-push of a non-root commit (diverged, not unrelated) under a clone that syncs with pull', odd: [], importNotRequired: true, pull: true,+ skip: mode => (mode === 'managed' ? 'managed sync refuses git pull (writer_coordinator_required); it always runs --no-pull' : false),+ makeRoot: home => {+ const up = join(home, 'fp-up-' + Math.random().toString(36).slice(2, 8)); mkdirSync(up);+ gitIn(up, 'init', '-q', '-b', 'main'); gitIn(up, 'config', 'receive.denyCurrentBranch', 'ignore');+ writeFileSync(join(up, 'seed.md'), md('seed')); gitIn(up, 'add', '-A'); gitIn(up, '-c', 'user.name=E', '-c', '[email protected]', 'commit', '-qm', 'seed');+ writeFileSync(join(up, 'second.md'), md('second')); gitIn(up, 'add', '-A'); gitIn(up, '-c', 'user.name=E', '-c', '[email protected]', 'commit', '-qm', 'second');+ const root = up + '-clone';+ execFileSync('git', ['-c', 'protocol.file.allow=always', 'clone', '-q', 'file://' + up, root]);+ gitIn(root, 'config', 'user.name', 'Example'); gitIn(root, 'config', 'user.email', '[email protected]');+ return root;+ },+ upstream: r => r.root.replace(/-clone$/, ''),+ mutate: r => {+ const up = r.root.replace(/-clone$/, '');+ mkdirSync(join(up, 'ok'), { recursive: true }); renameSync(join(r.root, 'ok/healthy-1.md'), join(up, 'ok/healthy-1.md'));+ writeFileSync(join(up, 'second.md'), md('second rewritten upstream'));+ gitIn(up, 'add', '-A'); gitIn(up, '-c', 'user.name=E', '-c', '[email protected]', 'commit', '-q', '--amend', '-m', 'second rewritten upstream');+ } },+ { id: 'S-51', name: 'NUL in a title committed together with a markdown delete (rename-identity confirmation)', odd: ['notes/nul-title.md'], importNotRequired: true,+ prepare: r => { r.write('notes/old.md', md('old')); commit(r, 'old'); },+ mutate: r => { unlinkSync(join(r.root, 'notes/old.md')); r.write('notes/nul-title.md', '# Meeting notes\u0000\u0000\u0000'); commit(r); } },+ { id: 'S-52', name: 'filename with trailing whitespace', odd: ['notes/trail.md '], oddSlug: undefined,+ mutate: r => { r.write('notes/trail.md ', md('trail')); commit(r); } },+ { id: 'S-53', name: 'UTF-16LE note with a BOM and no attributes (NULs once read as UTF-8)', odd: ['notes/utf16-raw.md'], importNotRequired: true,+ mutate: r => { r.write('notes/utf16-raw.md', Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(md('utf16 raw'), 'utf16le')])); commit(r); } },+];diff --git a/test/pathological/s-blockers-fixture.ts b/test/pathological/s-blockers-fixture.tsnew file mode 100644index 0000000000..a9e8cec3c1--- /dev/null+++ b/test/pathological/s-blockers-fixture.ts@@ -0,0 +1,165 @@+/**+ * GBRA-133 lane B (strange-error blockers): one git-backed source per case, synced+ * classic (persistence off, performSync) or managed (claimed worktree,+ * drainManagedSync), on PGLite and on Postgres when DATABASE_URL is set.+ *+ * A case seeds seed.md, takes a first sync, then commits one odd input next to+ * one healthy file (ok/healthy-1.md) and syncs again. The observation records+ * whether the run threw, whether the healthy sibling landed, whether the cursor+ * reached HEAD, and how the odd item was accounted for (imported, ledger row,+ * managed refusal or hold, or nothing). A follow-up commit of ok/healthy-2.md+ * and a third sync shows whether a block is permanent.+ */+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { appendFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { SyncResult } from '../../src/commands/sync.ts';+import { performSync } from '../../src/commands/sync/perform.ts';+import { drainManagedSync } from '../../src/core/persistence/sync-drain.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { readSyncStatus } from '../../src/core/persistence/sync-status.ts';+import { loadSyncFailures } from '../../src/core/sync-failure-ledger.ts';+import { readGitSourceHolds } from '../../src/core/persistence/sync-holds.ts';+import { readBlockedManagedSyncs } from '../../src/core/persistence/sync-blocked.ts';+import { checkSyncFailures } from '../../src/commands/doctor/checks/sync-failures.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { withEnv } from '../helpers/with-env.ts';++export type SyncMode = 'classic' | 'managed';++export const md = (title: string) => '---\ntitle: ' + title + '\ntype: note\n---\nThe ' + title + ' note.\n';++export interface ProbeRepo {+ mode: SyncMode; engine: BrainEngine; root: string; home: string; sourceId: string;+ git(...args: string[]): string;+ write(path: string | Buffer, body: string | Buffer): void;+ commitAll(msg: string): void;+ sync(opts?: { skipFailed?: boolean; timeoutMs?: number; pull?: boolean }): Promise<SyncResult>;+ lastCommit(): Promise<string | null>;+ head(): string;+}++export interface Observation {+ thrown: string | null;+ status?: string; reason?: string;+ cursorAtHead: boolean;+ healthy: boolean;+ ms: number;+ ledger: Array<{ path: string; code?: string; state?: string; error?: string }>;+ gitHolds: Array<{ path: string; code?: string }>;+ malformedSkipped?: number;+ refusals: Array<{ path: string; code: string }>;+ failures: Array<{ path?: string; slug?: string; code?: string }>;+ status_state?: string; status_reason?: string; status_next?: string; holds?: Array<{ path?: string; code?: string }>;+ doctor?: { sync_failures?: string; managed_blocked?: string };+}++export function errText(e: unknown): string {+ if (!(e instanceof Error)) return 'non-Error: ' + String(e).slice(0, 200);+ const code = (e as { code?: unknown }).code;+ return e.name + (code ? '[' + String(code) + ']' : '') + ': ' + e.message.split('\n')[0]!.slice(0, 300);+}++export function gitIn(root: string, ...args: string[]): string {+ return execFileSync('git', ['-c', 'protocol.file.allow=always', '-C', root, ...args], { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();+}++/** One repo per case on a shared engine. */+export async function withProbeRepo(engine: BrainEngine, mode: SyncMode, home: string,+ run: (r: ProbeRepo) => Promise<void>, opts: { seed?: boolean; root?: string; initRepo?: boolean } = {}): Promise<void> {+ const root = opts.root ?? join(home, 'repo-' + randomUUID().slice(0, 8));+ mkdirSync(root, { recursive: true });+ const git = (...args: string[]) => gitIn(root, ...args);+ if (opts.initRepo !== false) {+ git('init', '-q', '-b', 'main'); git('config', 'user.name', 'Example'); git('config', 'user.email', '[email protected]');+ }+ const write = (path: string | Buffer, body: string | Buffer) => {+ const full = typeof path === 'string' ? join(root, path) : Buffer.concat([Buffer.from(root + '/'), path]);+ mkdirSync(dirname(full.toString('latin1' as never)), { recursive: true });+ writeFileSync(full, body);+ };+ const commitAll = (msg: string) => { git('add', '-A'); git('commit', '-qm', msg, '--allow-empty'); };+ const sourceId = 's' + randomUUID().replace(/-/g, '').slice(0, 14);+ if (opts.seed !== false) { write('seed.md', md('seed')); commitAll('seed'); }+ if (mode === 'managed') await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);+ if (mode === 'managed') {+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ }+ const sync = async (o: { skipFailed?: boolean; timeoutMs?: number; pull?: boolean } = {}) => {+ const p = mode === 'classic'+ ? performSync(engine, { repoPath: root, sourceId, noPull: !o.pull, noEmbed: true, noExtract: true, concurrency: 1, skipFailed: o.skipFailed })+ : drainManagedSync(engine, { sourceId, noPull: !o.pull, noEmbed: true, noExtract: true, skipFailed: o.skipFailed } as never, false);+ const limit = o.timeoutMs ?? 90_000;+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ return await Promise.race([p, new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error('probe timeout: sync did not return in ' + limit + ' ms')), limit); })]);+ } finally { clearTimeout(timer); }+ };+ const lastCommit = async () => (await engine.executeRaw<{ c: string | null }>('SELECT last_commit AS c FROM sources WHERE id=$1', [sourceId]))[0]?.c ?? null;+ const head = () => { try { return git('rev-parse', 'HEAD'); } catch { return ''; } };+ await run({ mode, engine, root, home, sourceId, git, write, commitAll, sync, lastCommit, head });+}++/** Run one sync and observe it; healthySlug is the sibling that must land for the source to count as moving. */+export async function observe(r: ProbeRepo, healthySlug: string, opts: { skipFailed?: boolean; timeoutMs?: number; pull?: boolean } = {}): Promise<Observation> {+ const started = performance.now();+ let result: SyncResult | undefined; let thrown: string | null = null;+ try { result = await r.sync(opts); } catch (e) { thrown = errText(e); }+ const ms = Math.round(performance.now() - started);+ const healthy = (await r.engine.executeRaw('SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [r.sourceId, healthySlug])).length > 0;+ const head = r.head();+ const obs: Observation = {+ thrown, status: result?.status, reason: (result as { reason?: string } | undefined)?.reason,+ cursorAtHead: head !== '' && (await r.lastCommit()) === head, healthy, ms,+ ledger: loadSyncFailures().filter(f => f.source_id === r.sourceId).map(f => ({ path: f.path, code: f.code, state: f.state, error: String((f as { error?: unknown }).error ?? '').slice(0, 200) })),+ gitHolds: await readGitSourceHolds(r.engine, { sourceIds: [r.sourceId] }).then(s => (s[0]?.holds ?? []).map(h => ({ path: h.path, code: (h as { code?: string }).code ?? (h as { refusal?: { code?: string } }).refusal?.code })), (e: unknown) => [{ path: '<read failed>', code: errText(e) }]),+ malformedSkipped: (result as { malformedSkipped?: number } | undefined)?.malformedSkipped,+ refusals: (result?.fileRefusals ?? []).map(f => ({ path: f.path, code: f.code })),+ failures: (result?.failures ?? []).map(f => ({ path: (f as { path?: string }).path, slug: (f as { slug?: string }).slug, code: (f as { code?: string }).code })),+ };+ if (r.mode === 'managed') {+ try {+ const status = await readSyncStatus(r.engine, r.sourceId) as unknown as { state?: string; reason?: string; holds?: Array<{ path?: string; code?: string }> };+ obs.status_state = status.state; obs.status_reason = status.reason;+ obs.status_next = JSON.stringify((status as { next?: unknown }).next ?? null).slice(0, 300);+ obs.holds = (status.holds ?? []).map(h => ({ path: h.path, code: h.code }));+ } catch (e) { obs.status_state = 'status threw: ' + errText(e); }+ }+ const doctor: Observation['doctor'] = {};+ try {+ const check = await checkSyncFailures(r.engine, { sourceIds: [r.sourceId], remote: false });+ doctor.sync_failures = check ? check.status + ': ' + String(check.message).slice(0, 200) : 'null';+ } catch (e) { doctor.sync_failures = 'threw: ' + errText(e); }+ try {+ const blocked = await readBlockedManagedSyncs(r.engine, [r.sourceId]);+ doctor.managed_blocked = blocked.length ? blocked.map(b => b.code).join(',') : 'none';+ } catch (e) { doctor.managed_blocked = 'threw: ' + errText(e); }+ obs.doctor = doctor;+ return obs;+}++/** The engine arm (one engine per mode and backend) with a temp GBRAIN_HOME and ledger dir. */+export async function withProbeEngine(databaseUrl: string | undefined, run: (engine: BrainEngine, home: string) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-s-blockers-'));+ try {+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_AUDIT_DIR: join(home, 'audit'), GBRAIN_SYNC_AUTOSKIP_AFTER: '3', GBRAIN_GIT_ALLOW_FILE_TRANSPORT: '1',+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try { await run(engine, home); } finally { await disposePersistenceConsumer(engine); await close(); }+ });+ } finally {+ try { execFileSync('chmod', ['-R', 'u+rwX', home]); } catch { /* best effort */ }+ rmSync(home, { recursive: true, force: true });+ }+}++export function record(row: Record<string, unknown>): void {+ const out = process.env.GBRAIN_TEST_S_PROBE_OUT;+ if (out) appendFileSync(out, JSON.stringify(row) + '\n');+}