Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: pre-landing review fixes

garrytane85621a010bb
diff --git a/src/core/trust/owner-actions.ts b/src/core/trust/owner-actions.ts
index e103c0a97e..cec70d8da7 100644
--- a/src/core/trust/owner-actions.ts
+++ b/src/core/trust/owner-actions.ts
@@ -107,8 +107,10 @@ 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 characters (terminal escapes included) and runs of whitespace become one space. */
-const printable = (text: unknown): string => String(text ?? '').replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ').replace(/\s+/g, ' ').trim();
+/** 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();
+/** 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 => {
const flat = printable(text);
return flat.length > max ? `${flat.slice(0, max - 3)}...` : flat;
@@ -218,15 +220,15 @@ async function releaseCellOf(engine: BrainEngine, hold: HoldRow): Promise<{ cell
/** #7656: what a fact release raises besides its text, for the preview: the fence cell an index-existing release indexes, else the held payload. */
function releasedFields(hold: HoldRow, cell: ParsedFact | null): string {
const p = hold.payload;
- const quoted = (v: unknown) => typeof v === 'string' && v ? `"${printable(v)}"` : null;
const date = (v: unknown) => typeof v === 'string' && v ? v.slice(0, 10) : null;
const entries: Array<[string, unknown]> = cell
? [['kind', cell.kind], ['visibility', cell.visibility], ['confidence', cell.confidence], ['notability', cell.notability], ['valid from', cell.validFrom],
['valid until', cell.validUntil], ['metric', cell.claimMetric], ['value', cell.claimValue], ['unit', cell.claimUnit], ['period', cell.claimPeriod],
- ['attributed to', cell.attributedTo], ['source', cell.source], ['context', quoted(cell.context)]]
+ ['attributed to', cell.attributedTo], ['source', cell.source], ['context', cell.context]]
: [['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', quoted(p.context)]];
- const shown = entries.filter(([, v]) => v !== undefined && v !== null && v !== '').map(([k, v]) => `${k} ${printable(v)}`).join(', ');
+ ['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(', ');
return cell ? ` with fence row ${cell.rowNum} as it stands: ${shown}` : ` with ${shown}`;
}
/**
@@ -367,7 +369,7 @@ async function previewHold(engine: BrainEngine, id: number, 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' ? printable(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) : `"${snippet(text)}"`}, ${hold.reason_families.join(', ') || 'detector error'})${printable(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` };
}
diff --git a/test/doctor-trust-release-unpreviewed-fields.test.ts b/test/doctor-trust-release-unpreviewed-fields.test.ts
index f123e3b38a..55e68bbfc8 100644
--- a/test/doctor-trust-release-unpreviewed-fields.test.ts
+++ b/test/doctor-trust-release-unpreviewed-fields.test.ts
@@ -27,4 +27,30 @@ describe('trust_release_unpreviewed_fields doctor check', () => {
expect(check).toMatchObject({ name: 'trust_release_unpreviewed_fields', status: 'ok', details: { total: 0, items: [] } });
expect(categorizeCheck('trust_release_unpreviewed_fields')).toBe('brain');
}, 60_000);
+
+ // Generated by gstack /ship Step 7 coverage audit (#7794).
+ // Value: protects=the check lists at most five facts in its message, reports the full total, and names its first row as the read-only fix target;
+ // fails_when=the five-row message cap or the "and N more" count is dropped, or total reads the page of rows instead of the window count;
+ // seam=none; no_claim=the SQL itself (a stub engine returns the rows; the listing is exercised against real releases in trust-release-preview-binding.test.ts)
+ test('a listing past five rows names five, counts the rest, and points the fix at the first row', async () => {
+ const rows = Array.from({ length: 7 }, (_, i) => ({ id: i + 1, source_id: 'default', slug: 'people/alice-example', row_num: i + 1, hold_id: 10 + i, total: 52 }));
+ const [check] = await trustReleaseUnpreviewedEntry.run({ engine: { executeRaw: async () => rows } } as unknown as DoctorContext) as Check[];
+ expect(check).toMatchObject({ name: 'trust_release_unpreviewed_fields', status: 'warn', details: { total: 52 } });
+ expect(check!.message).toContain('f5 (default/people/alice-example row 5, released h14)');
+ expect(check!.message).not.toContain('f6 ');
+ expect(check!.message).toContain('; and 47 more.');
+ expect(check!.fix).toMatchObject({ argv: ['gbrain', 'trust', 'explain', 'f1'] });
+ });
+
+ // Value: protects=a schema that predates trust releases reports ok, while any other read failure surfaces as a warn with its error instead of a silent ok;
+ // fails_when=the missing-schema classification swallows every error, or a pre-trust schema reports a failure; why_new=only the empty-brain path was covered;
+ // seam=none; no_claim=real pre-trust schemas (the errors are the exact Postgres wording, thrown by a stub engine)
+ test('a missing trust table is ok (pre_trust); any other error is reported, never swallowed', async () => {
+ const run = (error: unknown) => trustReleaseUnpreviewedEntry.run({ engine: { executeRaw: async () => { throw error; } } } as unknown as DoctorContext) as Promise<Check[]>;
+ const [preTrust] = await run(Object.assign(new Error('relation "write_gate_holds" does not exist'), { code: '42P01' }));
+ expect(preTrust).toMatchObject({ status: 'ok', details: { schema: 'pre_trust' } });
+ const [failed] = await run(new Error('connection reset by peer'));
+ expect(failed).toMatchObject({ name: 'trust_release_unpreviewed_fields', status: 'warn' });
+ expect(failed!.message).toContain('connection reset by peer');
+ });
});
diff --git a/test/trust-release-fence.test.ts b/test/trust-release-fence.test.ts
index 6b09044db2..d274ef4e8a 100644
--- a/test/trust-release-fence.test.ts
+++ b/test/trust-release-fence.test.ts
@@ -665,7 +665,7 @@ for (const backend of testBackends()) {
// Generated by gstack /ship Step 7 coverage audit (#7511).
// Value: protects=the trust_release preparer refuses confirmation_required for a remote-authority or malformed request before reading any state;
-// fails_when=the authority.remote or intent-shape guard in prepareTrustReleaseMutation is dropped; why_new=no test reaches the preparer with a remote row;
+// fails_when=the authority.remote or intent-shape guard (including the index-existing cell_fields digest, #7656) in prepareTrustReleaseMutation is dropped; why_new=no test reaches the preparer with a remote row;
// seam=none; no_claim=how a remote row could be journaled (no remote op admits trust_release; the row is hand-built and the engine is a stub)
describe('the trust_release preparer refuses a request the owner did not confirm', () => {
test('a remote or malformed trust_release request refuses confirmation_required and touches no engine', async () => {
@@ -673,7 +673,8 @@ describe('the trust_release preparer refuses a request the owner did not confirm
const engine = new Proxy({}, { get: (_t, key) => { throw new Error(`engine.${String(key)} read`); } }) as BrainEngine;
const intent = { hold_id: 1, last_seen_at: '2026-01-01T00:00:00Z', by: 'owner:owner-example', mode: 'append' };
const row = (over: Record<string, unknown>) => ({ operation: 'trust_release', source_id: 'default', slug, page_id: 1, intent, authority: { remote: false }, ...over }) as never;
- for (const bad of [{ authority: { remote: true } }, { intent: null }, { intent: { ...intent, mode: 'rewrite' } }, { intent: { ...intent, hold_id: 'h1' } }, { intent: { ...intent, mode: 'index-existing' } }, { operation: 'remember' }]) {
+ for (const bad of [{ authority: { remote: true } }, { intent: null }, { intent: { ...intent, mode: 'rewrite' } }, { intent: { ...intent, hold_id: 'h1' } }, { intent: { ...intent, mode: 'index-existing' } },
+ { intent: { ...intent, mode: 'index-existing', row_num: 1 } }, { intent: { ...intent, mode: 'index-existing', row_num: 1, cell_fields: 7 } }, { operation: 'remember' }]) {
const error = await prepareTrustReleaseMutation(engine, row(bad), { engine: 'pglite' } as never).then(() => null, (e: { code?: string }) => e);
expect({ bad, code: error?.code }).toEqual({ bad, code: 'confirmation_required' });
}
diff --git a/test/trust-release-preview-binding.test.ts b/test/trust-release-preview-binding.test.ts
index 78af8563c3..0355ca58ab 100644
--- a/test/trust-release-preview-binding.test.ts
+++ b/test/trust-release-preview-binding.test.ts
@@ -137,6 +137,20 @@ for (const backend of testBackends()) {
expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE operation='trust_release'")).toEqual([]);
}, { setup, databaseUrl }), 180_000);
+ // Generated by gstack /ship Step 7 coverage audit (#7794).
+ // Value: protects=a fence row deleted after the owner approved its release refuses preview_changed: the hold stays held and no fact is indexed;
+ // fails_when=the approved-cell comparison treats a missing cell as unchanged or releases the held payload instead; why_new=existing cases only edit valid_until;
+ // seam=none; no_claim=a row deleted between admission and preparation (the preparer's missing-cell digest is the same comparison)
+ test('a fence row deleted after the approval refuses preview_changed: nothing is confirmed', () => managedBrain(async ({ engine, ctx }) => {
+ const ref = await holdFenceRow(engine, ctx);
+ const preview = await previewOwnerAction(engine, { action: 'release', ref });
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(
+ "UPDATE pages SET compiled_truth = split_part(compiled_truth, '## Facts', 1) WHERE source_id='default' AND slug=$1", [slug]), TEST_WRITE_ATTRIBUTION));
+ expect((await failure(apply(engine, ref, preview.binding)))?.code).toBe('preview_changed');
+ expect(await holdStatus(engine, ref)).toBe('held');
+ expect(await factRows(engine)).toEqual([]);
+ }, { setup, databaseUrl }), 180_000);
+
test('a cell field edited after the release was admitted, before it is prepared, refuses preview_changed at preparation', () => managedBrain(async ({ engine, ctx }) => {
const ref = await holdFenceRow(engine, ctx);
const preview = await previewOwnerAction(engine, { action: 'release', ref });
@@ -166,6 +180,24 @@ for (const backend of testBackends()) {
expect(summary).toContain('source email [1A [2Kend of source');
}), 180_000);
+ // Generated by gstack /ship Step 9 pass 1 adversarial review (#7794).
+ // Value: protects=the release preview cannot be made to show a field the held row lacks: bidi and format characters are stripped, and a quote or comma in the claim or source cannot close its field;
+ // fails_when=printable() stops stripping format characters or the claim and source are printed without escaping; why_new=the control-character test uses no quote, comma or bidi character;
+ // seam=none; no_claim=how a terminal renders the preview (asserts the summary text only)
+ test('the preview neutralizes bidi characters and a quote or comma that would fake another field', () => repoLessBrain(databaseUrl, async (engine, ctx) => {
+ await enableTrustProtections(engine);
+ let ref = '';
+ try { await operationsByName.remember.handler(ctx, { fact: `${CLAIM} \u202Eend", valid until 2099-01-01, "x`, provenance: 'email, valid until 2098-01-01\u200B',
+ content_origin: 'tool_output', request_id: randomUUID() }); }
+ catch (e) { ref = JSON.parse((e as { detail: string }).detail).hold_ref; }
+ expect(ref).toMatch(/^h\d+$/);
+ const { summary } = await previewOwnerAction(engine, { action: 'release', ref });
+ expect(summary).not.toMatch(/[\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/);
+ expect(summary).toContain('end\\", valid until 2099-01-01, \\"x"');
+ expect(summary).toContain('source "email, valid until 2098-01-01"');
+ expect(summary).not.toMatch(/, valid until 2098-01-01(?!")/);
+ }), 180_000);
+
test('on a repo-less brain the preview shows the held payload fields the database-only release raises', () => repoLessBrain(databaseUrl, async (engine, ctx) => {
await operationsByName.put_page.handler(ctx, { slug, request_id: randomUUID(), content: PAGE });
const ref = await holdRemember(engine, ctx, slug);