Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(serve): --access=read-only sets the read-only ceiling instead of starting a full-access serve (security)
garrytan573a421a2599
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e10f4d3a4e..900e2a4b07 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,14 +14,19 @@ identifiers and attribution are available in the pre-removal Git revision**A sync pass killed by an out-of-memory guard or a timeout now shows up in `gbrain sync status` and `gbrain doctor` instead of looking healthy. A read-only stdio serve no longer holds session-lane connections or runs the long-lived processes' write duties, so per-session serves can't starve them.**-A killed pass used to read `resumable` / `pass_unfinished`, the same as one that stopped cleanly at its deadline, and `live` still named the dead PID because its lock row outlives it. Now an open pass that no process is still renewing reads `pass_interrupted`, a second killed pass reads `pass_abandoned` at once, and doctor's `managed_sync_blocked` lists both. This is the visibility half of #7596; the memory growth itself is still being traced on real data.+A killed pass used to read `resumable` / `pass_unfinished`, the same as one that stopped cleanly at its deadline, and `live` still named the dead PID because its lock row outlives it. Now an open pass that no process is still renewing reads `pass_interrupted`, a second killed pass reads `pass_abandoned` at once, and doctor's `managed_sync_blocked` lists both. This is the visibility half of #7596; the memory growth itself is still being traced on real data. `gbrain sync status` also stays interactive after such a pass: it read the freshness of tens of thousands of receipts one at a time (#7604).Harnesses run one `gbrain serve --access read-only` per session. Each one opened the 3-connection resident direct pool, started a persistence consumer, took the on-commit notifier lease and ran sweeps, so a few sessions could exhaust the session lane (`EMAXCONNSESSION`). On Postgres a read-only serve now holds 0 session-lane connections and runs none of those duties. On PGLite it keeps them, because the CLI's reads and writes go through the one process that owns the database file. Search latency is unchanged: warm p50 about 0.8 s on both lanes at 50 ms RTT, on 3,000 synthetic pages.+Security: `gbrain serve --access=read-only`, the `=` form, passed flag validation but started the serve with full write access, because only the bare `--access read-only` form was read. A harness configured that way had every mutating tool. Both forms now set the read-only ceiling, a repeated flag never widens a read-only value, and an invalid value in either form refuses.+### Itemized changes- `src/core/persistence/sync-lease.ts`, `sync-pass-status.ts`, `sync-status.ts`, `sync-blocked.ts`, `src/commands/sync/operator.ts`, `src/commands/doctor/checks/managed-sync-blocked.ts`: `readDrainLease` and `drainLeaseLive` (one liveness rule for status, doctor and the autopilot's live-job check), the `pass_interrupted` reason and `interrupted` block, and the doctor listing. Test: `test/sync-pass-interrupted-7596.test.ts`.- `src/core/direct-pool-profile.ts`, `src/commands/serve.ts`, `src/mcp/server.ts`, `src/mcp/resolve-ipc-binding.ts`: a read-only stdio serve takes the one-shot profile and, on Postgres, skips the consumer, the delegated sync, nudge and sweep kinds, the resident tickers and the sweeps. Tests: `test/direct-pool-profile.test.ts` and `test/e2e/serve-read-only-session-lane-postgres.test.ts` (3 direct connections on the previous release, 0 now), `test/serve-read-only-pglite-owner-7599.test.ts` (CLI writes beside a read-only PGLite serve).+- `src/core/direct-pool-profile.ts` (`accessFlagValues`), `src/mcp/surface.ts` (`parseAccessFlag`): one `--access` parse for both forms, behind the MCP access ceiling and the pool profile. Tests: `test/serve-stdio-read-only.test.ts` (a real stdio session with `--access=read-only` lists only read-only tools and refuses `put_page`), `test/direct-pool-profile.test.ts`.+- `src/core/persistence/sync-freshness.ts`: the freshness check reads the newest committed revision per page once (a materialized join) instead of one correlated subquery per sampled receipt, so `gbrain sync status` stays interactive after a killed pass leaves tens of thousands of receipts (#7604; 5 min to 1.9 s on a 30,000-page repro). Test: `test/sync-freshness-6858.test.ts`.+- `scripts/generate-flag-registry.ts`: the scan skips `direct-pool-profile.ts`, whose `sync --watch` literal had made `gbrain serve --watch` pass validation once serve imported it. Test: `test/cli-flag-validation.test.ts`.## [0.60.461.0] - 2026-10-25diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex 50c69f5124..bc78a5084b 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -582,6 +582,8 @@ drives `tools/list`, the `gbrain://capabilities` resource (`access:`unknown_tool` before any handler runs. It denies agent-requestedmutations; owner maintenance on the same process (startup migrations, hookIPC banking) is a separate control. The default is `--access full`.+`--access=read-only` is the same flag; a repeated `--access` never widens a+read-only value.On Postgres a read-only serve is also not a resident owner, because harnessesstart one per session. It holds no session-lane (direct pool) connection, starts nodiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 5e87ce43b3..2d81d435a8 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1733 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move)src/commands/config.ts 1523 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts)src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)-src/core/behavior-change-notice.ts 1502 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change; +2 v0.60.462.0 rows (#7596 pass_interrupted, #7599 read-only serve)+src/core/behavior-change-notice.ts 1503 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change; +3 v0.60.462.0 rows (#7596 pass_interrupted, #7599 read-only serve, the --access=read-only ceiling)diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 35e72b6ce7..889b9927d1 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1303,6 +1303,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.460.0', text: '`gbrain repair duplicate-facts` keeps the copy that is a row of a page\'s `## Facts` table over an older database-only copy of the same fact, so the legacy copy is superseded onto the fence row instead of holding it (which left the legacy row unfenced and its page out of fact reconciliation). With no fenced copy it still keeps the oldest row. It stays preview-first and explicit.' },{ since: '0.60.460.0', text: 'Dream consolidation on a managed brain now closes a fenced fact in its page: the closing `valid_until` is written into the fact\'s row in the entity page\'s `## Facts` fence, published with the take, and the database row takes its value from that cell, so a later sync or re-import keeps the fact closed. Before, only the database row was closed and the next re-import of the page reopened it. A fact with no fence row is still closed in the database. A fenced fact whose fence row is on another page is left open. Facts an earlier release closed in the database only are not changed (GBRA-190).' },{ since: '0.60.462.0', text: 'On Postgres, `gbrain serve --access read-only` (stdio) no longer acts as a resident owner: it holds no session-lane (direct pool) connection, starts no persistence consumer, takes no on-commit notifier lease, runs no startup or idle sweep or facts drain, and refuses delegated sync and sweep requests (the CLI then runs them itself). Resolve, turn_context and context_pack still answer. A read-write serve, `gbrain jobs work` or the autopilot owns those duties; `gbrain doctor` reports when no process on the host holds the notifier (`commit_notifier`) or a consumer (`two_consumers_on_host`). Read-write and HTTP serves, and any serve on PGLite (the process that owns the database file), are unchanged.' },+ { since: '0.60.462.0', text: 'Security: `gbrain serve --access=read-only` (the `=` form) now sets the read-only ceiling. It passed flag validation before but started the serve with full write access, because only `--access read-only` was read. A config that used the `=` form now gets the read-only tool set and refused mutations it asked for; a repeated `--access` never widens a read-only value, and an invalid value in either form refuses.' },{ since: '0.60.462.0', text: 'A managed sync pass whose process was killed or crashed now reads `resumable` / `pass_interrupted` in `gbrain sync status` (with an `interrupted` block naming the pass and the dead holder) instead of `pass_unfinished`, and a second killed pass reads `blocked` / `pass_abandoned` at once. `gbrain doctor` `managed_sync_blocked` lists both (warn, fail after an hour). A live pass still committing is no longer counted abandoned because its row is old.' },];diff --git a/src/core/direct-pool-profile.ts b/src/core/direct-pool-profile.tsindex 5ec826ef4e..c4ca80fb97 100644--- a/src/core/direct-pool-profile.ts+++ b/src/core/direct-pool-profile.ts@@ -21,10 +21,18 @@ const SHORT_LIVED_COMMANDS = new Set(['sync', 'mcp', 'dream', 'cycle', 'sources'let processProfile: DirectPoolProfile = 'resident';+/**+ * Every `--access` value in `args`, in either form (`--access read-only`, `--access=read-only`; a bare flag at the end reads+ * ''). The one parse behind the MCP access ceiling (`parseAccessFlag`, src/mcp/surface.ts) and the pool profile: reading only+ * the bare form let `--access=read-only` pass flag validation and start a serve with full access.+ */+export function accessFlagValues(args: readonly string[]): string[] {+ return args.flatMap((arg, i) => arg === '--access' ? [args[i + 1] ?? ''] : arg.startsWith('--access=') ? [arg.slice('--access='.length)] : []);+}+/** `serve ... --access read-only`: a stdio serve that runs no resident write duty on Postgres (#7599). */export function isReadOnlyServeArgs(args: readonly string[]): boolean {- const at = args.indexOf('--access');- return at >= 0 && args[at + 1] === 'read-only';+ return accessFlagValues(args).includes('read-only');}/**diff --git a/src/mcp/surface.ts b/src/mcp/surface.tsindex cacde3cf64..ad41af8382 100644--- a/src/mcp/surface.ts+++ b/src/mcp/surface.ts@@ -39,6 +39,7 @@ import type { BrainEngine } from '../core/engine.ts';import { VERB_NAMES } from '../core/verbs.ts';import { opError } from '../core/ops/contract.ts';import { BRAIN_TOOL_ALLOWLIST } from '../core/minions/tools/brain-tool-allowlist.ts';+import { accessFlagValues } from '../core/direct-pool-profile.ts';export type McpSurface = 'verbs' | 'starter' | 'full';@@ -156,18 +157,18 @@ export function parseSurfaceFlag(args: string[]): McpSurface | null {* mutating, so discovery cannot widen it). It denies agent-requested* mutations; owner maintenance (startup migrations, hook IPC banking) is a* separate control. HTTP enforces per-token operation grants instead.+ * `--access=read-only` is the same flag (`accessFlagValues`); any read-only+ * value wins, so a repeated flag never widens the ceiling.*/export type McpAccess = 'full' | 'read-only';export function parseAccessFlag(args: string[]): McpAccess {- const idx = args.indexOf('--access');- if (idx < 0) return 'full';- const raw = args[idx + 1];- if (raw !== 'full' && raw !== 'read-only') {+ const values = accessFlagValues(args);+ if (values.some(raw => raw !== 'full' && raw !== 'read-only')) {throw opError('invalid_params', '--access takes read-only or full (default full); see docs/mcp/ADMIN.md#read-only-stdio-serve','Pass --access read-only or --access full (default full).', { docs: 'docs/mcp/ADMIN.md#read-only-stdio-serve' });}- return raw;+ return values.includes('read-only') ? 'read-only' : 'full';}export function isReadOnlyOperation(op: Pick<OperationMeta, 'scope' | 'mutating' | 'requiredScopes'>): boolean {diff --git a/test/direct-pool-profile.test.ts b/test/direct-pool-profile.test.tsindex 1acd68d069..0b7b30f5a7 100644--- a/test/direct-pool-profile.test.ts+++ b/test/direct-pool-profile.test.ts@@ -45,7 +45,8 @@ describe('directPoolProfileForCommand', () => {test('#7599: a read-only stdio serve is one-shot; a read-write serve stays resident', () => {expect(directPoolProfileForCommand('serve', ['--access', 'read-only'])).toBe('one_shot');expect(directPoolProfileForCommand('serve', ['--surface', 'full', '--access', 'read-only'])).toBe('one_shot');- for (const args of [[], ['--access', 'full'], ['--surface', 'read-only'], ['--http', '--port', '8080']])+ expect(directPoolProfileForCommand('serve', ['--access=read-only'])).toBe('one_shot');+ for (const args of [[], ['--access', 'full'], ['--access=full'], ['--surface', 'read-only'], ['--http', '--port', '8080']])expect(directPoolProfileForCommand('serve', args)).toBe('resident');});diff --git a/test/serve-stdio-read-only.test.ts b/test/serve-stdio-read-only.test.tsindex 9e08fa0c19..2abaabd914 100644--- a/test/serve-stdio-read-only.test.ts+++ b/test/serve-stdio-read-only.test.ts@@ -19,7 +19,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js';import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';import { keylessBrainEnv } from './helpers/provider-env.ts';import { operations } from '../src/core/operations.ts';-import { isReadOnlyOperation } from '../src/mcp/surface.ts';+import { isReadOnlyOperation, parseAccessFlag } from '../src/mcp/surface.ts';import { CAPABILITIES_URI } from '../src/mcp/capabilities.ts';const MARKER = 'readonly-marker-4768';@@ -66,6 +66,15 @@ test('the read-only predicate admits only non-mutating read operations of the lifor (const name of ['search', 'get_page', 'query', 'recall']) expect(isReadOnlyOperation(operations.find(op => op.name === name)!)).toBe(true);});+test('--access reads both forms; a read-only value is never widened, and a bad value refuses', () => {+ expect(parseAccessFlag([])).toBe('full');+ for (const args of [['--access', 'read-only'], ['--access=read-only'], ['--access=full', '--access', 'read-only'], ['--access', 'read-only', '--access=full']])+ expect(parseAccessFlag(args)).toBe('read-only');+ for (const args of [['--access', 'full'], ['--access=full']]) expect(parseAccessFlag(args)).toBe('full');+ for (const args of [['--access'], ['--access='], ['--access=readonly'], ['--access', '--surface']])+ expect(() => parseAccessFlag(args)).toThrow(/--access takes read-only or full/);+});+describe('serve --access read-only', () => {for (const surface of ['full', 'starter', 'verbs'] as const) {test(`${surface}: catalog, capabilities and dispatch agree and refuse every mutation`, async () => {@@ -95,6 +104,16 @@ describe('serve --access read-only', () => {}, 60_000);}+ test('--access=read-only is the same ceiling, not a full-access serve', async () => {+ const { client, close } = await session(['--access=read-only']);+ try {+ const listed = (await client.listTools()).tools.map(tool => tool.name);+ expect(listed.length).toBeGreaterThan(0);+ for (const name of listed) expect(isReadOnlyOperation(operations.find(op => op.name === name)!)).toBe(true);+ expect(errorOf(await client.callTool({ name: 'put_page', arguments: { slug: 'notes/injected', content: '# Injected' } }))).toBe('unknown_tool');+ } finally { await close(); }+ }, 60_000);+test('nothing was written and the default access is unchanged', async () => {const { client, close } = await session([]);try {@@ -110,5 +129,6 @@ describe('serve --access read-only', () => {const refused = cli(['serve', '--http', '--access', 'read-only', '--port', '0']);expect(refused.status).not.toBe(0);expect(refused.stderr).toContain('gbrain auth rescope-token <name> --operations');+ expect(cli(['serve', '--http', '--access=read-only', '--port', '0']).status).not.toBe(0);});});