Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(#7246): find_anomalies caps slugs at a fixed 20 per cohort (no new param), keeping the starter MCP schema budget
garrytan75b8e1dfcab0
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.mdindex 2051b17252..b1cc5e2ee7 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/agent.ts` — `gbrain agent run|logs|register` dispatcher. `run` submits `subagent` (or N children + 1 aggregator) under `{allowProtectedSubmit: true}`; single-entry `--fanout-manifest` short-circuits; children get `on_child_fail: 'continue'` + `max_stalled: 3`; `--follow` is the default on TTY (streams logs + polls `waitForCompletion` in parallel; Ctrl-C detaches, does not cancel). `logs` delegates to `agent-logs.ts`; `register` lazy-imports `agent-register.ts`. Subcommand-aware help is answered BEFORE any engine or queue work and STOPS at the `--` terminator (`agent run -- --help` submits the LITERAL prompt); on a brainless machine (null engine) help still prints while real `run`/`logs` invocations refuse with an init hint.-- `src/commands/anomalies.ts` — `gbrain anomalies [--since YYYY-MM-DD] [--lookback-days N] [--sigma N] [--json]`: cohort-level activity outliers. Calls `engine.findAnomalies(opts)`. Two cohort kinds: tag, type. `--json` (and MCP `find_anomalies`) lists at most 20 `page_slugs` per cohort and sets `page_slugs_complete: false` on a capped row; `count` covers the whole cohort. `--all` (CLI) or `slug_limit` (MCP, max 1000) lists more. Pinned by `test/anomalies-bounded-7246.test.ts`.+- `src/commands/anomalies.ts` — `gbrain anomalies [--since YYYY-MM-DD] [--lookback-days N] [--sigma N] [--json]`: cohort-level activity outliers. Calls `engine.findAnomalies(opts)`. Two cohort kinds: tag, type. `--json` (and MCP `find_anomalies`) lists at most 20 `page_slugs` per cohort and sets `page_slugs_complete: false` on a capped row; `count` covers the whole cohort. `--all` lists every slug on a local brain; MCP always caps. Pinned by `test/anomalies-bounded-7246.test.ts`.- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; clients without a `source_id` backfill to `'default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), federated reads (`federated_read`) and the operation snapshot — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `clientOperationsView` reports four distinct operation states (SQL NULL = `operations: "all"` with `includes_future_operations: true` and a re-pin `fix` naming `auth rescope --client <id> --operations <list>` or `--profile`; `[]` = deny-all; an explicit list; `unavailable` when the schema predates `allowed_operations`) and marks soft-revoked clients (`deleted_at`) `revoked` with no fix (`test/auth-clients-operations.test.ts`, both engines); `tokenLifetimeClampedClients` reads the migration's `clamp_token_ttl` / `shorten_access_tokens` audit rows so the listing marks clients whose access-token lifetime an upgrade brought inside 90 days (`token_lifetime_clamped` in `--json`); the `TOKEN_TTL_*` bounds are re-exported from `src/core/grants/model.ts`; `--usage` joins per-client op-call counts via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)`. Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`. F3: `gbrain auth rescope` (`runRescope`) is the one grant editor for tokens (`--token`/`--id`) and OAuth clients (`--client`), with a bare-name resolver, `--migrate-legacy [--dry-run]`, and refusals printed as JSON on stdout under `--json`; `rescope-token`, `rescope-client` and `permissions set-takes-holders` are aliases routed through it.diff --git a/src/commands/anomalies.ts b/src/commands/anomalies.tsindex 4c6979d8f9..4a62b44204 100644--- a/src/commands/anomalies.ts+++ b/src/commands/anomalies.ts@@ -19,7 +19,7 @@import type { BrainEngine } from '../core/engine.ts';import { loadConfig, isThinClient } from '../core/config.ts';import { callRemoteTool, unpackToolResult } from '../core/mcp-client.ts';-import { capRowList, LISTING_MAX_LIMIT } from '../core/bounded-listing.ts';+import { capRowList } from '../core/bounded-listing.ts';import { ANOMALY_SLUG_DEFAULT_LIMIT } from '../core/ops/salience.ts';interface RunOpts {@@ -66,7 +66,7 @@ Options:--sigma N Threshold multiplier (default 3.0)--json JSON output for agents (up to ${ANOMALY_SLUG_DEFAULT_LIMIT} slugs per cohort;page_slugs_complete is false when slugs were left out)- --all Every slug of each cohort (a remote brain caps at ${LISTING_MAX_LIMIT})+ --all Every slug of each cohort (local brain; a remote brain always caps)--help, -h Show this help`;@@ -84,7 +84,6 @@ export async function runAnomalies(engine: BrainEngine, args: string[]): Promisesince: parsed.since,lookback_days: parsed.lookbackDays,sigma: parsed.sigma,- slug_limit: parsed.all ? LISTING_MAX_LIMIT : ANOMALY_SLUG_DEFAULT_LIMIT,}, { timeoutMs: 30_000 });rows = unpackToolResult<Awaited<ReturnType<BrainEngine['findAnomalies']>>>(raw);} else {diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 7eb6bc0835..4cc32f0931 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1056,7 +1056,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.338.0', text: 'The title arm\'s any-word retry (after an all-words title match finds nothing) now matches page titles only, as remote callers already did, and drops repeated words (#7135): a date in a question no longer pulls every dated timeline into ranking, which cut a 3-5 s title arm to well under a second on a large brain. A local all-words title match is unchanged.' },// GBRA-151 (#7246 bounded whole-brain outputs). `since` is stamped at the merge slot.{ since: 'TBD', text: '`gbrain orphans` now prints at most 100 orphans per page (the totals still count every orphan). A paged `--json` result lists the totals and counts per domain first, then the page with `returned`, `limit`, `complete`, `next_cursor` and `next_command`; `--cursor <next_cursor>` prints the next page, `--limit <n>` sets the page size and `--all` prints every orphan in the earlier shape. A listing that fits in one page prints as before. MCP `find_orphans` adds `cursor`, `complete` and `next_cursor` beside offset paging.' },- { since: 'TBD', text: 'MCP `find_anomalies` and `gbrain anomalies --json` list at most 20 slugs per anomalous cohort; `count` still covers the whole cohort and `page_slugs_complete: false` marks a row that left slugs out. `slug_limit` (MCP, up to 1000) or `--all` (CLI) lists more.' },+ { since: 'TBD', text: 'MCP `find_anomalies` and `gbrain anomalies --json` list at most 20 slugs per anomalous cohort; `count` still covers the whole cohort and `page_slugs_complete: false` marks a row that left slugs out. `gbrain anomalies --json --all` lists every slug on a local brain.' },{ since: 'TBD', text: 'When `gbrain serve`\'s stdout or stderr is a regular file (the `gbrain mcp expose` service installs, or any `>>` redirect), serve rotates that file at 10 MiB, keeping 5 copies (`<log>.1` to `<log>.5`), and writes a line repeated within 10 minutes once, followed by one "[gbrain serve-log] repeated N more time(s)" line. `GBRAIN_SERVE_LOG_MAX_BYTES` (0 turns rotation off), `GBRAIN_SERVE_LOG_MAX_FILES` and `GBRAIN_SERVE_LOG_DEDUPE_SECONDS` (0 turns dedupe off) change it.' },];diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex c33f30fdb7..c2cbdceb0e 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -4644,10 +4644,6 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["sigma": {"type": "number","description": "Threshold (default 3)."- },- "slug_limit": {- "type": "number",- "description": "Slugs listed per cohort (default 20, max 1000); count covers the whole cohort and page_slugs_complete is false when slugs were left out."}},"cliHints": {diff --git a/src/core/ops/salience.ts b/src/core/ops/salience.tsindex 4504552e0c..6fb9e72a5a 100644--- a/src/core/ops/salience.ts+++ b/src/core/ops/salience.ts@@ -10,8 +10,7 @@import type { Operation } from './contract.ts';import { readPolicyOpts } from './context.ts';-import { invalidParam } from './op-fix.ts';-import { capRowList, LISTING_MAX_LIMIT } from '../bounded-listing.ts';+import { capRowList } from '../bounded-listing.ts';import {GET_RECENT_SALIENCE_DESCRIPTION,FIND_ANOMALIES_DESCRIPTION,@@ -19,7 +18,7 @@ import {// --- v0.29: Salience + Anomaly Detection ----/** #7246: slugs listed per anomalous cohort unless the caller asks for more (count always covers the whole cohort). */+/** #7246: slugs listed per anomalous cohort (count always covers the whole cohort; page_slugs_complete: false marks a capped row). */export const ANOMALY_SLUG_DEFAULT_LIMIT = 20;const get_recent_salience: Operation = {@@ -84,17 +83,8 @@ const find_anomalies: Operation = {type: 'number',description: 'Threshold (default 3).',},- slug_limit: {- type: 'number',- description: `Slugs listed per cohort (default ${ANOMALY_SLUG_DEFAULT_LIMIT}, max ${LISTING_MAX_LIMIT}); count covers the whole cohort and page_slugs_complete is false when slugs were left out.`,- },},handler: async (ctx, p) => {- const slugLimit = p.slug_limit === undefined ? ANOMALY_SLUG_DEFAULT_LIMIT : Number(p.slug_limit);- if (!Number.isInteger(slugLimit) || slugLimit < 1 || slugLimit > LISTING_MAX_LIMIT) {- throw invalidParam(ctx, 'find_anomalies', 'slug_limit', `find_anomalies: slug_limit must be 1-${LISTING_MAX_LIMIT}`,- { def: find_anomalies.params.slug_limit, example: ANOMALY_SLUG_DEFAULT_LIMIT });- }// Scope by the caller's source (same v0.34.1 #861 source-isolation class as// get_recent_salience above — the v0.29 batch missed both). Applied to the// baseline AND today windows inside the engine so the anomaly math stays@@ -107,7 +97,8 @@ const find_anomalies: Operation = {...await readPolicyOpts(ctx),});- return anomalies.map(row => capRowList(row, 'page_slugs', slugLimit));+ // #7246: a fixed per-cohort sample keeps the response bounded (count covers the whole cohort); the local CLI's --all lists every slug.+ return anomalies.map(row => capRowList(row, 'page_slugs', ANOMALY_SLUG_DEFAULT_LIMIT));},// hidden: 'anomalies' is in CLI_ONLY (src/cli.ts) — runAnomalies owns the// CLI surface; the non-hidden hint was dead (CLI_ONLY wins at dispatch).diff --git a/test/anomalies-bounded-7246.test.ts b/test/anomalies-bounded-7246.test.tsindex 78e406dca4..cb770a38a3 100644--- a/test/anomalies-bounded-7246.test.ts+++ b/test/anomalies-bounded-7246.test.ts@@ -1,13 +1,12 @@/*** #7246: find_anomalies (and `gbrain anomalies --json`) returned every slug* of an anomalous cohort, so a bulk-import day put tens of thousands of slugs- * in one response. Each row now carries at most `slug_limit` slugs (default- * 20, max 1000) and `page_slugs_complete: false` when it left some out; the- * count still covers the whole cohort. `--all` keeps every slug on the local CLI.+ * in one response. Each row now carries at most 20 slugs and+ * `page_slugs_complete: false` when it left some out; the count still covers+ * the whole cohort. `--all` keeps every slug on the local CLI.** Authoring gate: protects the output-size contract of a remote-reachable op;- * fails if the cap is dropped or a remote caller can lift it; no existing test- * covers the slug list size.+ * fails if the cap is dropped; no existing test covers the slug list size.*/import { describe, expect, test } from 'bun:test';import { operations } from '../src/core/operations.ts';@@ -40,11 +39,11 @@ describe('find_anomalies bounded slug lists (#7246)', () => {expect(out!.count).toBe(500);});- test('slug_limit raises the cap up to 1000, never unbounded for a remote caller', async () => {- const [out] = await op.handler(ctx(true), { slug_limit: 1000 }) as Array<Record<string, unknown>>;- expect(out!.page_slugs).toHaveLength(500);+ test('a cohort that fits the cap is returned whole with no completeness flag', async () => {+ const small = { kind: 'pglite', findAnomalies: async () => [{ ...row, count: 3, page_slugs: slugs.slice(0, 3) }] } as unknown as BrainEngine;+ const [out] = await op.handler({ ...(ctx(true) as object), engine: small } as never, {}) as Array<Record<string, unknown>>;+ expect(out!.page_slugs).toEqual(slugs.slice(0, 3));expect(out!.page_slugs_complete).toBeUndefined();- await expect(op.handler(ctx(true), { slug_limit: 1001 })).rejects.toThrow('slug_limit');});test('gbrain anomalies --json is capped by default and --all keeps every slug', async () => {diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex c9958be467..af000427cf 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 255279,- "stdoutSha256": "587625e601300f3576e9857ad6e27f3d26a951095fcb4303ee144ad4154a0fdc",+ "stdoutBytes": 255021,+ "stdoutSha256": "6523b1ba32215784707e0ae074471ee85990d277ef0691913900b4d6ad35f75d","toolNames": ["remember","entity",@@ -5570,8 +5570,7 @@"parameters": {"lookback_days": "number?","sigma": "number?",- "since": "string?",- "slug_limit": "number?"+ "since": "string?"},"required_scopes": [],"schema": {@@ -5587,10 +5586,6 @@"since": {"description": "YYYY-MM-DD (default today).","type": "string"- },- "slug_limit": {- "description": "Slugs listed per cohort (default 20, max 1000); count covers the whole cohort and page_slugs_complete is false when slugs were left out.",- "type": "number"}},"required": [],