Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(trust): release and drop previews quote every free-text field; accept-all skips an unpreviewable item (#7820)
garrytan9dc73104020a
diff --git a/src/commands/trust.ts b/src/commands/trust.tsindex a945622687..d120171b75 100644--- a/src/commands/trust.ts+++ b/src/commands/trust.ts@@ -144,7 +144,13 @@ function resultLine(r: OwnerActionResult): string {return `${r.ref}: ${r.status}${tier}`;}-/** DX-15: accept every matching item after one typed confirmation. */+/** The longest line one item gets in the accept-all confirmation; `gbrain trust explain <ref>` shows it in full. */+const ACCEPT_ALL_ITEM_MAX = 240;++/**+ * DX-15: accept every matching item after one typed confirmation. An item whose preview fails is listed as skipped:+ * it is not in the confirmation and is never applied (#7820).+ */async function acceptAll(backend: TrustBackend, args: string[], json: boolean): Promise<void> {const filter = reviewFilter(args);if (!filter.sourceId && !filter.kind && !filter.since) {@@ -162,23 +168,30 @@ async function acceptAll(backend: TrustBackend, args: string[], json: boolean):if (json) await writeStdoutFinal(`${JSON.stringify({ accepted: [], skipped }, null, 2)}\n`); else if (skipped.length) skipLines(); else console.log('Nothing matches those filters.');return;}- const previews = await Promise.all(inputs.map(input => backend.preview(input)));+ const settled = await Promise.allSettled(inputs.map(input => backend.preview(input)));+ const skipped = settled.flatMap((s, i) => s.status === 'rejected' ? [{ ref: inputs[i]!.ref!, reason: 'preview_failed',+ error: s.reason instanceof OperationError ? s.reason.toJSON() : String(s.reason), next: `gbrain trust ${inputs[i]!.action} ${inputs[i]!.ref}` }] : []);+ const previewed = settled.flatMap((s, i) => s.status === 'fulfilled' ? [{ input: inputs[i]!, preview: s.value }] : []);+ const previews = previewed.map(p => p.preview);const command = ['gbrain', 'trust', 'review', '--accept-all', ...args.filter(a => a !== '--accept-all' && a !== '--json')];const token = `all-${createHash('sha256').update(previews.map(p => `${p.ref}:${p.binding}`).join('\n')).digest('hex').slice(0, 8)}`;- const summary = [`Accept ${previews.length} item(s):`, ...previews.map(p => ` ${p.ref.padEnd(6)} ${p.summary}`)].join('\n');- await requireOwnerConfirmation(LOCAL_CTX, { ref: `${previews.length} items`, token, summary, command });+ const line = (p: OwnerActionPreview) => p.summary.length > ACCEPT_ALL_ITEM_MAX ? `${p.summary.slice(0, ACCEPT_ALL_ITEM_MAX - 3)}...` : p.summary;+ const summary = [`Accept ${previews.length} item(s):`, ...previews.map(p => ` ${p.ref.padEnd(6)} ${line(p)}`),+ ...skipped.map(s => ` ${s.ref.padEnd(6)} skipped: its preview failed, so it is not accepted (run ${s.next} on its own)`),+ ...(previews.some(p => p.summary.length > ACCEPT_ALL_ITEM_MAX) ? [' A line ending in ... is shortened; gbrain trust explain <ref> shows the item in full.'] : [])].join('\n');+ if (previews.length) await requireOwnerConfirmation(LOCAL_CTX, { ref: `${previews.length} items`, token, summary, command });const accepted: OwnerActionResult[] = [];const pending: Array<{ ref: string; request_id: string; poll: string }> = [];let uncovered = 0;const failed: Array<{ ref: string; error: unknown }> = [];- for (let i = 0; i < inputs.length; i++) {- try { accepted.push(await backend.apply(inputs[i]!, previews[i]!.binding, previews[i]!.raises)); }+ for (const { input, preview } of previewed) {+ try { accepted.push(await backend.apply(input, preview.binding, preview.raises)); }catch (error) {const receipt = pendingReceiptOf(error);if (receipt && !acceptPendingCovers(receipt)) uncovered++;- if (receipt) pending.push({ ref: previews[i]!.ref, request_id: receipt.request_id,+ if (receipt) pending.push({ ref: preview.ref, request_id: receipt.request_id,poll: pollCommand(receipt.request_id, (error as { fix?: { argv?: readonly string[] } }).fix, cliRenderContext().routing) });- else failed.push({ ref: previews[i]!.ref, error: error instanceof OperationError ? error.toJSON() : String(error) });+ else failed.push({ ref: preview.ref, error: error instanceof OperationError ? error.toJSON() : String(error) });}}if (json) await writeStdoutFinal(`${JSON.stringify({ accepted, pending, failed, skipped }, null, 2)}\n`);@@ -187,8 +200,9 @@ async function acceptAll(backend: TrustBackend, args: string[], json: boolean):for (const r of accepted) console.log(resultLine(r));for (const p of pending) console.log(`${p.ref}: accepted, still pending (request ${p.request_id}; check with ${p.poll})`);for (const f of failed) console.log(`${f.ref}: not applied (${(f.error as { message?: string }).message ?? String(f.error)})`);+ for (const s of skipped) console.log(`${s.ref}: skipped, its preview failed (${(s.error as { message?: string }).message ?? String(s.error)}); run ${s.next} on its own`);}- if (failed.length) setCliExitVerdict(1);+ if (failed.length || skipped.length) setCliExitVerdict(1);else if (pending.length && (!acceptPendingRequested(getCliOptions().acceptPending) || uncovered > 0)) setCliExitVerdict(PENDING_WRITE_EXIT_CODE);}diff --git a/src/core/trust/owner-actions.ts b/src/core/trust/owner-actions.tsindex 6b449a35bc..5263328e44 100644--- a/src/core/trust/owner-actions.ts+++ b/src/core/trust/owner-actions.ts@@ -108,8 +108,12 @@ const bindingOf = (value: unknown): string => createHash('sha256')/** A hold's approved state; #7656: plus the fence cell fields an index-existing release raises (`releaseCellOf`). */const holdBinding = (hold: Pick<HoldRow, 'id' | 'status' | 'last_seen_at'>, cellFields: Record<string, unknown> | null = null): string =>bindingOf({ id: hold.id, status: hold.status, last_seen_at: hold.last_seen_at, ...(cellFields ? { cell: cellFields } : {}) });-/** One printable line: control and format characters (terminal escapes and bidi overrides included) and runs of whitespace become one space. */-const printable = (text: unknown): string => String(text ?? '').replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\p{Cf}]/gu, ' ').replace(/\s+/g, ' ').trim();+/**+ * One printable line: control, format and default-ignorable characters (terminal escapes, bidi overrides, Hangul fillers,+ * the combining grapheme joiner) and the braille blank become one space, and runs of whitespace collapse to one.+ */+const printable = (text: unknown): string => String(text ?? '')+ .replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u2800\p{Cf}\p{Default_Ignorable_Code_Point}]/gu, ' ').replace(/\s+/g, ' ').trim();/** A free-text value in the preview: quoted and escaped, so a quote or comma in it cannot close its field and fake another. */const quoted = (text: unknown): string => JSON.stringify(printable(text));const snippet = (text: unknown, max = 80): string => {@@ -229,7 +233,7 @@ function releasedFields(hold: HoldRow, cell: ParsedFact | null): string {: [['kind', typeof p.kind === 'string' && p.kind ? p.kind : 'fact'], ['visibility', p.visibility === 'world' ? 'world' : 'private'], ['valid from', date(p.valid_from)],['valid until', date(p.valid_until)], ['source', p.source], ['context', p.context]];const shown = entries.filter(([, v]) => v !== undefined && v !== null && v !== '')- .map(([k, v]) => `${k} ${k === 'context' || /[",;]/.test(printable(v)) ? quoted(v) : printable(v)}`).join(', ');+ .map(([k, v]) => `${k} ${k === 'context' || typeof v === 'string' ? quoted(v) : printable(v)}`).join(', ');return cell ? ` with fence row ${cell.rowNum} as it stands: ${shown}` : ` with ${shown}`;}/**@@ -334,7 +338,7 @@ async function previewConfirm(engine: BrainEngine, ref: TrustRef, input: OwnerAcif (!row.live) throw opError('invalid_params', `${label} is no longer active (expired, superseded or forgotten); there is nothing to confirm.`, 'Confirm the row that replaced it instead; gbrain trust explain shows its history.');const release = await suppressedFields(engine, row.table, row.id);return { action: 'confirm', ref: label, token: label, command: trustCommand('confirm', label), raises: row.tier !== 'user_confirmed' || release.length > 0, binding: row.binding,- tier: row.tier, target_tier: 'user_confirmed', summary: `Raise ${ref.kind} ${label} ("${snippet(row.text)}") from "${trustLabel(row.tier)}" to "confirmed by you"`+ tier: row.tier, target_tier: 'user_confirmed', summary: `Raise ${ref.kind} ${label} (${JSON.stringify(snippet(row.text))}) from "${trustLabel(row.tier)}" to "confirmed by you"`+ (release.length ? ` and release its purge-redacted ${release.join(', ')} in recorded history` : '') };}if (ref.kind === 'page') {@@ -364,15 +368,15 @@ async function previewHold(engine: BrainEngine, id: number, action: 'release' |const hold = await holdStore.get(engine, id);if (!hold) throw notFound(label, 'held write');const text = hold.payload.fact ?? hold.payload.claim ?? '';- const entity = hold.kind === 'fact' && typeof hold.payload.entity_slug === 'string' && hold.payload.entity_slug ? ` for ${hold.source_id}/${hold.payload.entity_slug}` : '';+ const entity = hold.kind === 'fact' && typeof hold.payload.entity_slug === 'string' && hold.payload.entity_slug ? ` for ${quoted(`${hold.source_id}/${hold.payload.entity_slug}`)}` : '';const cell = action === 'release' ? await releaseCellOf(engine, hold) : null;return { action, ref: label, token: label, command: trustCommand(action, label), raises: action === 'release',binding: holdBinding(hold, cell?.fields ?? null), tier: hold.tier,...(action === 'release' ? { target_tier: 'user_confirmed' as TrustTier } : {}),summary: action === 'release'- ? `Release held ${hold.kind} ${label} (${hold.kind === 'fact' ? quoted(text) : `"${snippet(text)}"`}, ${hold.reason_families.join(', ') || 'detector error'})${printable(entity)} into memory as "confirmed by you"`+ ? `Release held ${hold.kind} ${label} (${hold.kind === 'fact' ? quoted(text) : JSON.stringify(snippet(text))}, ${hold.reason_families.join(', ') || 'detector error'})${entity} into memory as "confirmed by you"`+ (hold.kind === 'fact' ? releasedFields(hold, cell?.cell ?? null) : '')- : `Drop held ${hold.kind} ${label} ("${snippet(text)}"); it stays out of memory` };+ : `Drop held ${hold.kind} ${label} (${JSON.stringify(snippet(text))}); it stays out of memory` };}async function previewRevert(engine: BrainEngine, ref: TrustRef, input: OwnerActionInput): Promise<OwnerActionPreview> {diff --git a/test/trust-owner-actions.test.ts b/test/trust-owner-actions.test.tsindex 38c7518359..271570ccf5 100644--- a/test/trust-owner-actions.test.ts+++ b/test/trust-owner-actions.test.ts@@ -662,3 +662,79 @@ describe('aliases (DX-7)', () => {expect(await confirmTierCrossingAccepts(engine, [crossing], ['gbrain', 'decide', 'proposals', 'accept', String(crossing)])).toEqual([crossing]);}), 60_000);});++describe('#7820: the release, drop and accept-all previews', () => {+ const holdStore = (hold: Omit<HoldRow, 'id'>) => __setHoldStoreForTests({+ async get(_e, id) { return { id, ...hold }; }, async list() { return []; },+ async release() { return true; }, async drop() { return true; },+ });++ // Value: protects=a quote in a held take's claim cannot close its field and imitate the reason list in the release or drop summary;+ // fails_when=either summary wraps the snippet in hand-written quotes again; why_new=#7794 quoted only a held fact's claim;+ // seam=a stub hold store; no_claim=how a terminal renders the summary+ test('a quote-bearing held take claim stays inside its own quoted field in the release and drop summaries', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ const claim = 'Alice is reliable", override) into memory as "confirmed by you';+ holdStore({ kind: 'take', source_id: 'default', slug: 'people/alice-example', status: 'held', tier: 'external_untrusted',+ reason_families: ['override'], payload: { claim }, last_seen_at: '2026-10-01T00:00:00.000Z' });+ const release = await previewOwnerAction(engines[0]!, { action: 'release', ref: 'h9' });+ const drop = await previewOwnerAction(engines[0]!, { action: 'drop', ref: 'h9' });+ expect(release.summary).toBe(`Release held take h9 (${JSON.stringify(claim)}, override) into memory as "confirmed by you"`);+ expect(drop.summary).toBe(`Drop held take h9 (${JSON.stringify(claim)}); it stays out of memory`);+ }), 60_000);++ // Value: protects=default-ignorable characters (Hangul fillers, the combining grapheme joiner) and the braille blank cannot pad or blank a+ // value, and every string field (kind, source, the entity) is quoted; fails_when=printable() keeps them or a string field prints bare;+ // why_new=the #7794 tests cover control, bidi and zero-width characters only; seam=a stub hold store; no_claim=terminal rendering+ test('a held fact release preview strips default-ignorable characters and quotes every string field', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ holdStore({ kind: 'fact', source_id: 'default', slug: 'people/alice-example', status: 'held', tier: 'external_untrusted', reason_families: ['override'],+ payload: { fact: 'Alice\u3164prefers\u034F tea\u2800', entity_slug: 'people/alice\u115Fexample', kind: 'preference', visibility: 'world',+ valid_from: '2026-01-01T00:00:00.000Z', source: 'email\u3164\u3164x' }, last_seen_at: '2026-10-01T00:00:00.000Z' });+ const { summary } = await previewOwnerAction(engines[0]!, { action: 'release', ref: 'h9' });+ expect(summary).toBe('Release held fact h9 ("Alice prefers tea", override) for "default/people/alice example" into memory as "confirmed by you"'+ + ' with kind "preference", visibility "world", valid from "2026-01-01", source "email x"');+ }), 60_000);++ // Value: protects=one item whose preview fails no longer aborts accept-all, is listed as skipped, is not in the typed confirmation and is+ // never applied; a long item is shortened in the one confirmation; fails_when=previews go back to Promise.all or a skipped item is applied;+ // why_new=index-existing previews now materialize the page and can throw; seam=a stub TrustBackend; no_claim=a real corrupt page+ test('accept-all skips an item whose preview fails, never applies it, and shortens a long item in the confirmation', async () => {+ const long = `Release held fact h9 ("${'a long claim '.repeat(40)}", override) into memory as "confirmed by you"`;+ for (const json of [false, true]) {+ const applied: string[] = [];+ const backend = {+ review: async () => ({ items: ['h7', 'h8', 'h9'].map(ref => ({ kind: 'hold', ref, source_id: 'default' })) }),+ explain: async () => [],+ preview: async (input: OwnerActionInput) => {+ if (input.ref === 'h8') throw new OperationError('invalid_params', 'The facts fence of the page could not be read.');+ return { action: 'release', ref: input.ref, token: input.ref, command: `gbrain trust release ${input.ref}`, raises: true, binding: `b-${input.ref}`,+ summary: input.ref === 'h9' ? long : `Release held fact ${input.ref}` };+ },+ apply: async (input: OwnerActionInput) => { applied.push(input.ref!); return { action: 'release', ref: input.ref, status: 'released', tier: 'user_confirmed' }; },+ } as unknown as Parameters<typeof runTrustOwnerCommand>[0];+ const lines: string[] = [];+ const docs: string[] = [];+ let prompt = '';+ const exit = await withEnv({ GBRAIN_HOME: home }, async () => {+ const io = typesToken();+ const original = console.log;+ console.log = (...args: unknown[]) => { lines.push(args.join(' ')); };+ const final = spyOn(cliForceExit, 'writeStdoutFinal').mockImplementation(async (doc: string) => { docs.push(doc); });+ try { await runTrustOwnerCommand(backend, 'review', ['--accept-all', '--from', 'default', ...(json ? ['--json'] : [])]); return currentExitCode(); }+ finally { prompt = io.prompt(); final.mockRestore(); console.log = original; process.exitCode = 0; _resetCliExitVerdictForTests(); }+ });+ expect({ json, exit, applied }).toEqual({ json, exit: 1, applied: ['h7', 'h9'] });+ expect(prompt).toContain('Accept 2 item(s)');+ expect(prompt).toContain('h8 skipped: its preview failed, so it is not accepted (run gbrain trust release h8 on its own)');+ expect(prompt).toContain(`h9 ${long.slice(0, 237)}...\n`);+ expect(prompt).not.toContain(long);+ if (json) {+ const doc = JSON.parse(docs[0]!);+ expect({ accepted: doc.accepted.map((a: { ref: string }) => a.ref), skipped: doc.skipped.map((s: { ref: string; reason: string; next: string }) => [s.ref, s.reason, s.next]) })+ .toEqual({ accepted: ['h7', 'h9'], skipped: [['h8', 'preview_failed', 'gbrain trust release h8']] });+ expect(doc.skipped[0].error.code).toBe('invalid_params');+ } else {+ expect(lines).toContain('h8: skipped, its preview failed (The facts fence of the page could not be read.); run gbrain trust release h8 on its own');+ }+ }+ }, 60_000);+});diff --git a/test/trust-release-preview-binding.test.ts b/test/trust-release-preview-binding.test.tsindex 0355ca58ab..4e5c7b1234 100644--- a/test/trust-release-preview-binding.test.ts+++ b/test/trust-release-preview-binding.test.ts@@ -120,7 +120,7 @@ for (const backend of testBackends()) {test('the preview shows the cell fields the release raises; releasing it records that they were previewed', () => managedBrain(async ({ engine, ctx }) => {const ref = await holdFenceRow(engine, ctx);const preview = await previewOwnerAction(engine, { action: 'release', ref });- for (const field of ['kind fact', 'visibility world', 'confidence 0.4', 'notability high', 'valid from 2026-01-01', 'valid until 2026-12-31', 'source email']) {+ for (const field of ['kind "fact"', 'visibility "world"', 'confidence 0.4', 'notability "high"', 'valid from "2026-01-01"', 'valid until "2026-12-31"', 'source "email"']) {expect(preview.summary).toContain(field);}expect(await apply(engine, ref, preview.binding)).toMatchObject({ status: 'released', tier: 'user_confirmed' });@@ -177,7 +177,7 @@ for (const backend of testBackends()) {const { summary } = await previewOwnerAction(engine, { action: 'release', ref });expect(summary).not.toMatch(/[\u0000-\u001f\u007f-\u009f]/);expect(summary).toContain('more words tail ');- expect(summary).toContain('source email [1A [2Kend of source');+ expect(summary).toContain('source "email [1A [2Kend of source"');}), 180_000);// Generated by gstack /ship Step 9 pass 1 adversarial review (#7794).@@ -202,7 +202,7 @@ for (const backend of testBackends()) {await operationsByName.put_page.handler(ctx, { slug, request_id: randomUUID(), content: PAGE });const ref = await holdRemember(engine, ctx, slug);const preview = await previewOwnerAction(engine, { action: 'release', ref });- for (const field of ['kind fact', 'visibility world', 'source email', 'valid from ']) expect(preview.summary).toContain(field);+ for (const field of ['kind "fact"', 'visibility "world"', 'source "email"', 'valid from "']) expect(preview.summary).toContain(field);expect(await apply(engine, ref, preview.binding)).toMatchObject({ status: 'released', tier: 'user_confirmed' });expect(await factRows(engine)).toEqual([expect.objectContaining({ trust_tier: 'user_confirmed' })]);}), 180_000);