Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(trust): gbrain sources set-trust per-source default, never above operator_curated (#5575 A3)
garrytan45e18c0a3ac9
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex dd26a1a1c2..bb1220bc6e 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -30,7 +30,7 @@ src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connesrc/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)src/commands/bootstrap.ts 2134 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags)src/core/minions/worker.ts 1774 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler)-src/commands/sources.ts 2046 ratchet +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts)+src/commands/sources.ts 2048 ratchet +2 #5575: sources set-trust dispatch and help row (body in sources-trust.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts)src/core/link-extraction.ts 2205 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts)src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budgetsrc/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshdiff --git a/src/commands/sources-trust.ts b/src/commands/sources-trust.tsnew file mode 100644index 0000000000..68cdaa472a--- /dev/null+++ b/src/commands/sources-trust.ts@@ -0,0 +1,39 @@+/**+ * `gbrain sources set-trust <id> <tier>` / `--clear` (#5575 A3): the per-source+ * trust default (`sources.config.trust_tier`) that owner sync and import of+ * that source start from, for mirrors of third-party repositories. It can+ * only lower: the highest accepted value is operator_curated (the owner-sync+ * tier), and page frontmatter markers still lower further. Trusted local CLI+ * only (the sources command has no MCP surface). Applies to rows written by+ * the next sync or import; existing rows keep their tier.+ */+import type { BrainEngine } from '../core/engine.ts';+import { normalizeSourceConfig, parseSourceConfig } from '../core/sources-load.ts';+import { OWNER_TIER_FLOOR, TRUST_TIERS, compareTrust, isTrustTier, trustLabel } from '../core/trust/tier.ts';++const ACCEPTED = TRUST_TIERS.filter(tier => compareTrust(tier, OWNER_TIER_FLOOR) <= 0);+export const SOURCES_SET_TRUST_USAGE = `Usage: gbrain sources set-trust <id> <${ACCEPTED.join('|')}> | --clear`;++export async function runSetTrust(engine: BrainEngine, args: string[]): Promise<void> {+ const [id, value] = args;+ if (!id || id.startsWith('-') || !value) {+ console.error(SOURCES_SET_TRUST_USAGE);+ process.exit(2);+ }+ if (value !== '--clear' && (!isTrustTier(value) || compareTrust(value, OWNER_TIER_FLOOR) > 0)) {+ console.error(`${JSON.stringify(value)} is not a source trust default. Accepted: ${ACCEPTED.join(', ')} (user_confirmed is only ever set by the owner confirming a row: gbrain trust confirm).`);+ process.exit(2);+ }+ const [src] = await engine.executeRaw<{ config: unknown }>('SELECT config FROM sources WHERE id=$1', [id]);+ if (!src) {+ console.error(`Source "${id}" not found. List sources with: gbrain sources list`);+ process.exit(4);+ }+ const config = parseSourceConfig(src.config);+ if (value === '--clear') delete config.trust_tier;+ else config.trust_tier = value;+ await engine.executeRaw('UPDATE sources SET config = $1::text::jsonb WHERE id = $2', [JSON.stringify(normalizeSourceConfig(config)), id]);+ console.log(value === '--clear'+ ? `Source "${id}" syncs at the owner default again (${OWNER_TIER_FLOOR}: "${trustLabel(OWNER_TIER_FLOOR)}"), lowered by page markers. Existing rows keep their tier.`+ : `Source "${id}" now syncs at ${value} ("${trustLabel(value as never)}") or lower. It applies to pages the next sync or import writes; existing rows keep their tier.`);+}diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex add8e650fc..0b98e4db1e 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -1908,6 +1908,7 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<vcase 'tracked-branch': return runTrackedBranch(engine, rest);// v0.40.3.0 contextual retrieval (from master)case 'set-cr-mode': return runSetCrMode(engine, rest);+ case 'set-trust': { const { runSetTrust } = await import('./sources-trust.ts'); return runSetTrust(engine, rest); }// #4739 non-destructive local_path pointer repaircase 'set-path': { const { runSetPath } = await import('./sources-set-path.ts'); return runSetPath(engine, rest); }case 'shared-skills': { const { runSourcesSharedSkills } = await import('./sources-shared-skills.ts'); return runSourcesSharedSkills(engine, rest); }@@ -1991,6 +1992,7 @@ Subcommands:override (v0.40.3.0). Pass "unset" or"default" to clear (NULL falls throughto the global search.mode bundle).+ set-trust <id> <tier>|--clear Trust default for this source's sync and import (operator_curated or lower).set-path <id> <path> [--force] Repair a source's local_path pointer(DB column only, never touches disk).--force skips the overlapping-path guard.diff --git a/test/trust-channel-writes.test.ts b/test/trust-channel-writes.test.tsindex d0b7031869..b0f3683980 100644--- a/test/trust-channel-writes.test.ts+++ b/test/trust-channel-writes.test.ts@@ -39,6 +39,7 @@ import { listTrustProposals } from '../src/core/trust/proposals.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { renderFactsTable } from '../src/core/facts-fence.ts';+import { runSetTrust } from '../src/commands/sources-trust.ts';const engines: BrainEngine[] = [];const home = mkdtempSync(join(tmpdir(), 'gbrain-trust-channel-'));@@ -261,3 +262,29 @@ describe('owner-source sync tiers and the git round trip (CEO-21)', () => {}}), 120_000);});++describe('gbrain sources set-trust', () => {+ test('stores a default at or below operator_curated, refuses user_confirmed, clears', async () => {+ const engine = engines[0]!;+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw(`INSERT INTO sources(id,name,config) VALUES('mirror-example','mirror-example','{}') ON CONFLICT DO NOTHING`);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const config = async () => (await engine.executeRaw<{ t: string | null }>(`SELECT config->>'trust_tier' AS t FROM sources WHERE id='mirror-example'`))[0]?.t ?? null;+ const quietRun = async (args: string[]) => {+ const [log, err, exit] = [console.log, console.error, process.exit];+ let code: number | undefined;+ console.log = () => {}; console.error = () => {};+ process.exit = ((c?: number) => { code = c; throw new Error('exit'); }) as never;+ try { await runSetTrust(engine, args); } catch (e) { if ((e as Error).message !== 'exit') throw e; }+ finally { console.log = log; console.error = err; process.exit = exit; }+ return code;+ };+ expect(await quietRun(['mirror-example', 'external_untrusted'])).toBeUndefined();+ expect(await config()).toBe('external_untrusted');+ expect(await quietRun(['mirror-example', 'user_confirmed'])).toBe(2);+ expect(await config()).toBe('external_untrusted');+ expect(await quietRun(['mirror-example', '--clear'])).toBeUndefined();+ expect(await config()).toBeNull();+ expect(await quietRun(['missing-example', 'agent_written'])).toBe(4);+ });+});