Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: pre-landing review fixes
garrytanac04e5266d17
diff --git a/src/commands/repair-propose.ts b/src/commands/repair-propose.tsindex a8421bc09c..f267981571 100644--- a/src/commands/repair-propose.ts+++ b/src/commands/repair-propose.ts@@ -15,11 +15,13 @@* one pinned to access.serves one, gets "nothing to propose" before any pages query (brainServes, the gate open-pages.ts* callers use). Everything it reads is database state, so a repo-less brain gets it unchanged.*/-import { chmodSync, mkdirSync, writeFileSync } from 'node:fs';+import { closeSync, fchmodSync, mkdirSync, openSync, renameSync, writeSync } from 'node:fs';+import { randomBytes } from 'node:crypto';import { join, resolve } from 'node:path';import type { BrainEngine } from '../core/engine.ts';import { configDir } from '../core/config.ts';import { opError } from '../core/ops/contract.ts';+import { shellQuote } from '../core/agent-output.ts';import { digest } from '../core/persistence/digest.ts';import { privacyPartSql } from '../core/search/private-visibility.ts';import { SENSITIVE_PAGE_TYPES } from '../core/grants/shared-exposure.ts';@@ -66,6 +68,19 @@ function entries(value: unknown): string[] {const canonical = (entry: string): string | null => { try { return assertMemberEmail(entry); } catch { return null; } };+/** Writes one slugs file (0600) through a new exclusive temp file renamed over the name, so a planted file or symlink there is replaced, never followed. */+function writeSlugs(file: string, slugs: string[]): void {+ const temp = `${file}.${randomBytes(6).toString('hex')}.tmp`;+ const fd = openSync(temp, 'wx', 0o600);+ try {+ fchmodSync(fd, 0o600);+ writeSync(fd, `${slugs.join('\n')}\n`);+ } finally {+ closeSync(fd);+ }+ renameSync(temp, file);+}+/** Refuses a proposals directory inside a git work tree, as member keys are refused (access-serves.ts). */function assertOutsideGit(dir: string): void {const root = gitRootAbove(dir);@@ -113,8 +128,8 @@ export async function proposeVisibility(engine: BrainEngine, opts: { source?: stconst folder = cut > 0 ? row.slug.slice(0, cut + 1) : '(root)';const key = JSON.stringify([row.source, folder]);const f = folders.get(key) ?? { source: row.source, folder, pages: 0, command: folder === '(root)'- ? `gbrain repair visibility --source ${row.source} --slug <slug> --readers ${ownerFirst}<list>`- : `gbrain access rule add --prefix ${folder} --readers ${ownerFirst}<list> --source ${row.source}` };+ ? shellQuote(['gbrain', 'repair', 'visibility', '--source', row.source, '--slug', '<slug>', '--readers', `${ownerFirst}<list>`])+ : shellQuote(['gbrain', 'access', 'rule', 'add', '--prefix', folder, '--readers', `${ownerFirst}<list>`, '--source', row.source]) };folders.set(key, f);f.pages++;continue;@@ -142,10 +157,9 @@ export async function proposeVisibility(engine: BrainEngine, opts: { source?: stfor (let i = 0; i < parts; i++) {const slugs = g.slugs.slice(i * READERS_MAX_PAGES, (i + 1) * READERS_MAX_PAGES);const file = join(dir, `${g.source}-${digest([g.source, g.readers]).slice(0, 12)}${parts > 1 ? `-${i + 1}` : ''}.txt`);- writeFileSync(file, `${slugs.join('\n')}\n`, { mode: 0o600 });- chmodSync(file, 0o600);+ writeSlugs(file, slugs);sets.push({ source: g.source, readers: g.readers, pages: slugs.length, file,- command: `gbrain repair visibility --source ${g.source} --slugs-file ${file} --readers ${g.readers.join(',')}` });+ command: shellQuote(['gbrain', 'repair', 'visibility', '--source', g.source, '--slugs-file', file, '--readers', g.readers.join(',')]) });}}const sorted = [...folders.values()].sort((a, b) => a.source.localeCompare(b.source) || b.pages - a.pages || a.folder.localeCompare(b.folder));diff --git a/test/repair-visibility-propose-gst2670.test.ts b/test/repair-visibility-propose-gst2670.test.tsindex 82849ee29b..7bc387160c 100644--- a/test/repair-visibility-propose-gst2670.test.ts+++ b/test/repair-visibility-propose-gst2670.test.ts@@ -15,7 +15,7 @@*/import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';import { execFileSync } from 'node:child_process';-import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs';+import { existsSync, lstatSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { basename, join } from 'node:path';import type { BrainEngine } from '../src/core/engine.ts';@@ -70,6 +70,9 @@ async function stateHash(engine: BrainEngine): Promise<string> {return JSON.stringify(rows);}+/** A printed command's argv as a POSIX shell reads it (printf, so nothing runs). */+const argv = (command: string): string[] => execFileSync('bash', ['-c', `printf '%s\\0' ${command}`], { encoding: 'utf8' }).split('\0').slice(0, -1);+async function capture(fn: () => Promise<unknown>): Promise<string> {const lines: string[] = [];const spy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { lines.push(a.map(String).join(' ')); });@@ -143,13 +146,13 @@ for (const kind of testBackends()) {expect(s.source).toBe(SRC);expect(statSync(s.file).mode & 0o777).toBe(0o600);expect(s.file.startsWith(join(home, '.gbrain', 'visibility-proposals') + '/')).toBe(true);- expect(s.command).toBe(`gbrain repair visibility --source ${SRC} --slugs-file ${s.file} --readers ${s.readers.join(',')}`);+ expect(argv(s.command)).toEqual(['gbrain', 'repair', 'visibility', '--source', SRC, '--slugs-file', s.file, '--readers', s.readers.join(',')]);}expect(readdirSync(join(home, '.gbrain', 'visibility-proposals')).sort()).toEqual(p.sets.map(s => basename(s.file)).sort());expect(Object.fromEntries(p.unmatched.map(u => [u.slug, u.addresses]))).toEqual({'emails/e2': ['[email protected]'], 'emails/e3': ['[email protected]'], 'meetings/m2': ['alice-example'] });- expect(p.folders).toEqual([{ source: SRC, folder: 'chats/team-a/', pages: 2,- command: `gbrain access rule add --prefix chats/team-a/ --readers owner-example,<list> --source ${SRC}` }]);+ expect(p.folders.map(f => ({ ...f, command: argv(f.command) }))).toEqual([{ source: SRC, folder: 'chats/team-a/', pages: 2,+ command: ['gbrain', 'access', 'rule', 'add', '--prefix', 'chats/team-a/', '--readers', 'owner-example,<list>', '--source', SRC] }]);expect(JSON.stringify(p)).not.toContain('notes/plain');const all = [...p.sets.flatMap(s => readFileSync(s.file, 'utf8').trim().split('\n')), ...p.unmatched.map(u => u.slug)];expect(all).not.toContain('labelled/m3');@@ -197,29 +200,60 @@ for (const kind of testBackends()) {test('each printed command parses with the real flag tables, previews, and applying one closes exactly its pages', async () => {const p = await propose(['--source', SRC]);for (const s of p.sets) {- const argv = s.command.split(' ');- expect(argv.slice(0, 3)).toEqual(['gbrain', 'repair', 'visibility']);- const parsed = parseRepairArgs(argv.slice(2));+ const args = argv(s.command);+ expect(args.slice(0, 3)).toEqual(['gbrain', 'repair', 'visibility']);+ const parsed = parseRepairArgs(args.slice(2));expect(parsed).toMatchObject({ kind: 'visibility', source: SRC, slugsFile: s.file, readers: s.readers.join(','), apply: false, propose: false });- for (const flag of argv.filter(a => a.startsWith('--'))) expect(CLI_FLAG_REGISTRY.repair).toContain(flag);+ for (const flag of args.filter(a => a.startsWith('--'))) expect(CLI_FLAG_REGISTRY.repair).toContain(flag);}for (const f of p.folders) {- const argv = f.command.replace('<list>', 'alice-example').split(' ');- expect(argv.slice(0, 4)).toEqual(['gbrain', 'access', 'rule', 'add']);- for (const flag of argv.filter(a => a.startsWith('--'))) expect(CLI_FLAG_REGISTRY.access).toContain(flag);+ const args = argv(f.command).map(a => a.replace('<list>', 'alice-example'));+ expect(args.slice(0, 4)).toEqual(['gbrain', 'access', 'rule', 'add']);+ for (const flag of args.filter(a => a.startsWith('--'))) expect(CLI_FLAG_REGISTRY.access).toContain(flag);const before = await stateHash(engine);- const preview = JSON.parse(await capture(() => runAccessRules(engine, 'rule', [...argv.slice(3), '--json'], true)));+ const preview = JSON.parse(await capture(() => runAccessRules(engine, 'rule', [...args.slice(3), '--json'], true)));expect(preview.applied).toBe(false);expect(await stateHash(engine)).toBe(before);}const set = p.sets.find(s => s.readers.length === 3)!;- const preview = JSON.parse(await repair([...set.command.split(' ').slice(2), '--json'])).results[0];+ const preview = JSON.parse(await repair([...argv(set.command).slice(2), '--json'])).results[0];expect(preview.affected).toBe(2);- await repair([...set.command.split(' ').slice(2), '--apply', '--expect', preview.preview_hash, '--json']);+ await repair([...argv(set.command).slice(2), '--apply', '--expect', preview.preview_hash, '--json']);const rows = await engine.executeRaw<{ slug: string; r: unknown }>("SELECT slug, frontmatter->'readable_by' AS r FROM pages WHERE source_id = $1 AND slug IN ('meetings/m1', 'meetings/m5') ORDER BY slug", [SRC]);for (const row of rows) expect(row.r).toEqual(['owner-example', 'alice-example', 'bob-example']);const again = await propose(['--source', SRC]);expect(again.sets.map(s => s.readers.join(',')).sort()).toEqual(['owner-example,alice-example', 'owner-example,bob-example']);}, 120_000);+ test('a slug with shell syntax stays one literal argument in every printed command, and nothing runs', async () => {+ const marker = join(tempDir('gbrain-propose-shell-'), 'ran');+ await importFromContent(engine, `chats/$(touch ${marker})/day-1`, fm('dm'), { sourceId: 'default', noEmbed: true });+ await importFromContent(engine, `meetings/$(touch ${marker})`, fm('meeting', 'attendees: [[email protected]]\n'), { sourceId: 'default', noEmbed: true });+ const out = join(tempDir('gbrain-propose-out $(x)-'), 'sets');+ const p = await propose(['--source', 'default', '--out', out]);+ const folder = p.folders.find(f => f.folder.includes('$('))!;+ expect(argv(folder.command)).toEqual(['gbrain', 'access', 'rule', 'add', '--prefix', folder.folder, '--readers', 'owner-example,<list>', '--source', 'default']);+ for (const s of p.sets) expect(argv(s.command)).toEqual(['gbrain', 'repair', 'visibility', '--source', 'default', '--slugs-file', s.file, '--readers', s.readers.join(',')]);+ expect(p.sets.some(s => readFileSync(s.file, 'utf8').includes('$('))).toBe(true);+ expect(existsSync(marker)).toBe(false);+ }, 60_000);++ test('a symlink planted at a slugs file name is replaced, never followed', async () => {+ const out = join(tempDir('gbrain-propose-link-'), 'sets');+ const first = await propose(['--source', SRC, '--out', out]);+ const target = first.sets[0]!.file;+ const victim = join(tempDir('gbrain-propose-victim-'), 'victim.txt');+ writeFileSync(victim, 'victim\n', { mode: 0o644 });+ const before = readFileSync(target, 'utf8');+ unlinkSync(target);+ symlinkSync(victim, target);+ const again = await propose(['--source', SRC, '--out', out]);+ expect(again.sets[0]!.file).toBe(target);+ expect(readFileSync(victim, 'utf8')).toBe('victim\n');+ expect(statSync(victim).mode & 0o777).toBe(0o644);+ expect(lstatSync(target).isSymbolicLink()).toBe(false);+ expect(lstatSync(target).mode & 0o777).toBe(0o600);+ expect(readFileSync(target, 'utf8')).toBe(before);+ expect(readdirSync(out).filter(n => n.endsWith('.tmp'))).toEqual([]);+ }, 60_000);});}