Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: pre-landing review fixes (--surface=<v> sets the serve surface; doctor and docstring wording; test pins)

garrytan6cfabf3b2a9d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 900e2a4b07..353325d3a2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,13 +18,13 @@ A killed pass used to read `resumable` / `pass_unfinished`, the same as one that
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.
+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. `--surface=verbs` had the same gap (an HTTP or stdio serve kept the full surface): both forms now set the surface, and a repeated `--surface` takes the narrowest value.
### 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/direct-pool-profile.ts` (`flagValues`), `src/mcp/surface.ts` (`parseAccessFlag`, `parseSurfaceFlag`): one parse for both forms of `--access` and `--surface`, behind the MCP access and surface ceilings and the pool profile. Tests: `test/serve-stdio-read-only.test.ts` (real stdio sessions: `--access=read-only` lists only read-only tools and refuses `put_page`; `--surface=verbs` lists the verbs surface), `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`.
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.md
index a15d9749fd..f630c4760a 100644
--- a/docs/architecture/key-files/managed-sync-bookkeeping.md
+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md
@@ -48,7 +48,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
- `src/commands/doctor/checks/managed-sync-movement.ts` + `src/core/persistence/sync-movement.ts` — #6317 (B4, I2): the movement reader and its doctor check. `readManagedSyncMovement` snapshots, per active managed source, the newest `completed_at` of committed `managed_sync_*` receipts in the current source incarnation (the watermark: one probe of the partial index `persistence_requests_sync_watermark`, v223; a count would shrink under compaction), the head claim's `step_since`, the `managed-sync` cursor (`index/total`, `held`) and `sources.last_sync_at`/`last_commit`, and whether a drain or full consumer is live on the owner host. `data_moving` is false when an unfinished cursor has had neither a committed receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` while a consumer is live; with none live the state is `parked` (informational). `sources status --json` and `writer status --json` print `data_moving`, `not_moving_since` and `movement_state` beside `sync_running`, and `sources status` prints the writer-status command beside `data_moving: false`; doctor `managed_sync_not_moving` (warn, scored for `not_moving` only) uses the same rule and command as its fix, and fails on a parked cursor whose admitted queue has no consumer past the ceiling (#6552; fix: the resume sync); `serve` prints one `[gbrain notice]` when a source flips. A failed backlog read is `unknown`, never `nothing_pending` (doctor warns). `/health` stays liveness-only.
- `src/commands/sources-writer-movement.ts` — #6317 (I2): `gbrain sources writer movement [<source>] [--wait <dur>] [--warn-only] [--json]`, the deploy gate `gbrain upgrade` and `post-upgrade` end by printing (bare, so it inherits the default window; neither runs it, because neither restarts the resident processes). The printed step is `MOVEMENT_SUPERVISOR_STEP` from the import-free leaf `src/commands/movement-step.ts` (re-exported here), so upgrade loads it before the swap (#6604). Same source selection as `writer status` (`persistence-admin.ts`). It snapshots through `sync-movement.ts`, waits `max(300 s, preparation budget + 60 s)` (printed as the effective budget; `--wait <dur>` takes sync's duration syntax) and judges each source: `moved` (a new committed publication; a cursor advanced only by holds or a `last_sync_at` touched by an up-to-date check is not movement) and `current` exit 0; `held` exits 0 with a warning and the hold kind's route (`gbrain repair fences --source <id>`; `preparation_stalled` → writer status, then `gbrain sources retry-held <id>`); `within_allowance` (the head's step advanced inside the window) exits 0 with `retry_after_ms`; `not_moving` exits 1 with `managed_sync_not_moving` (`reason: movement_check`, `fix.argv` the writer-status command, `fix.verify` this command); `unknown` (backlog unreadable) exits 1 with `movement_unknown`; other read failures keep their code. `--warn-only` prints the same envelopes and exits 0. Flags are regenerated into `src/core/cli-flag-registry.generated.ts` with `bun run build:flag-registry`.
- `src/core/serve-head-watcher.ts` + `src/core/persistence/sync-freshness.ts` + `src/commands/doctor/checks/managed-sync-latency.ts` — #6858 ask 6: on-commit sync and its latency metric. `startServeHeadWatcher` (two call sites: `installResidentTickers` in `src/commands/serve.ts`, stopped before `shutdownDelegatedSync`, and `runServeHttp` in `src/commands/serve-http.ts`, beside `startMovementWatch` and stopped on the same shutdown path) re-reads `sync.on_commit` every 30 s; while on it polls `git rev-parse HEAD` in each managed source checkout this host owns (`GBRAIN_SERVE_HEAD_POLL_MS`, default 3 s; an `fs.watch` on the git dir only nudges the poll), debounces 3 s (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`) and starts one managed sync through the unchanged `startDelegatedSync` with this host's `cli` registration. It never starts beside a running delegated sync or a held drain lease (the move stays pending and fires once after), skips a HEAD `sources.last_commit` already has, resumes a resumable stop up to `MAX_RESUMES`, and logs each distinct error once. `readSyncFreshness` samples committed `managed_sync_import` receipts of the last 24 h (not first syncs or working-tree entries): commit time is the git committer time of `intent.target`, searchable is `completed_at`, embedded is the page's newest `content_chunks.embedded_at` once every chunk has one, sampled only from a receipt no later committed write to the same page supersedes and only at or after its `completed_at`; p50/p95 in one aggregate over the `persistence_requests_sync_watermark` predicate. #7604: the supersede check reads the newest committed sequence per (source, slug) once, over the rows after the oldest sample (a materialized CTE), so the read stays linear in the samples after a killed pass leaves tens of thousands of receipts (a per-receipt subquery is quadratic and reaches the 300 s statement timeout). `gbrain sync status` (the `freshness` block) and `gbrain status` print it; doctor `managed_sync_latency` grades p95 against `sync.freshness_target_seconds` (default 300; fail over max(1 h, target)) only with `sync.on_commit` on or a target set. Tests: `test/serve-head-watcher.test.ts`, `test/serve-head-watcher-managed.serial.test.ts`, `test/serve-http-head-watcher.serial.test.ts`, `test/sync-freshness-6858.test.ts`. #7189: each `SourceFreshness` carries `behind` (`readGitBehind`, injectable `BehindReader`: `rev-list --count <last_commit>..HEAD` and the oldest of those commits' committer age; null without a checkout or a synced commit), printed by `formatSyncFreshness`.
-- `src/core/persistence/sync-status.ts` (status coherence) — GBRA-150: `state: blocked` means the source cannot advance (the drain outcome's meaning); a file hold that waits on a person while the source keeps syncing reads `synced` with reason `held_needs_human`, `needs_human` and `next` unchanged (`test/sync-status-blocked-definition.test.ts`); `detail` adds `landing` / `landing_read` (`landing-gaps.ts`). #7189: a `last_error` whose cursor failure row (`op_checkpoints` `managed-sync-failure`) is older than the source's newest committed managed-sync receipt carries `superseded` and sets neither `needs_human`, `state` nor `next` (`liveError`); `needs_human_from` names the hold or the error. #7243 (GBRA-133 PR 3a): every status carries `last_commit` (`sources.last_commit`) and `live` (the drain-lease holder from `readDrainHolder`, read only when the source read's `gbrain_cycle_locks` probe finds a row, with `job_id` for a Minions sync job and `stalled` from `holderStalled`; #7596: a holder that stopped renewing the lease (`readDrainLease`, `drainLeaseLive`) is not `live`, and an open pass with no live holder reads `pass_interrupted` (`passStatusState`) with an `interrupted` block (pass, last row write, the dead holder), which `sync-blocked.ts` also lists for doctor `managed_sync_blocked`; test `test/sync-pass-interrupted-7596.test.ts`; `live_job_id` also takes a job holder of a pass); `supersedingAttempt` marks a `last_error` `superseded` (`by`, `age_seconds`) when evidence newer than the failure row passed its phase (`resume` < `discovery` < `freeze`/`admission` < `receipt`/`checkpoint`; evidence: the pass row's `started_at` (pin), a level read (`timings_ms` set or an `up_to_date` idle tick), an uncommitted managed import or delete admitted later, a later commit). The CLI (`sync/operator.ts` `holdsListing`) bounds the holds: `holds_summary` (`topCounts` by code and by state: `needs_human`, `actionable`, `held`) over every hold, then `PLAIN_STATUS_HOLDS` (20) rows needs-human first, or with `--detail` a page of the shared listing contract (`bounded-listing.ts`, kind `sync_status_holds:<source>:<state>`, `--limit`/`--cursor`/`--all`, `--hold-state`), `holds_page` only when a page left rows out or took a cursor, the rows last. Test: `test/sync-status-truthful-7243.test.ts` (both engines).
+- `src/core/persistence/sync-status.ts` (status coherence) — GBRA-150: `state: blocked` means the source cannot advance (the drain outcome's meaning); a file hold that waits on a person while the source keeps syncing reads `synced` with reason `held_needs_human`, `needs_human` and `next` unchanged (`test/sync-status-blocked-definition.test.ts`); `detail` adds `landing` / `landing_read` (`landing-gaps.ts`). #7189: a `last_error` whose cursor failure row (`op_checkpoints` `managed-sync-failure`) is older than the source's newest committed managed-sync receipt carries `superseded` and sets neither `needs_human`, `state` nor `next` (`liveError`); `needs_human_from` names the hold or the error. #7243 (GBRA-133 PR 3a): every status carries `last_commit` (`sources.last_commit`) and `live` (the drain-lease holder still renewing it, from `readDrainLease`, read only when the source read's `gbrain_cycle_locks` probe finds a row, with `job_id` for a Minions sync job and `stalled` from `holderStalled`; #7596: a holder that stopped renewing the lease (`readDrainLease`, `drainLeaseLive`) is not `live`, and an open pass with no live holder reads `pass_interrupted` (`passStatusState`) with an `interrupted` block (pass, last row write, the dead holder), which `sync-blocked.ts` also lists for doctor `managed_sync_blocked`; test `test/sync-pass-interrupted-7596.test.ts`; `live_job_id` also takes a job holder of a pass); `supersedingAttempt` marks a `last_error` `superseded` (`by`, `age_seconds`) when evidence newer than the failure row passed its phase (`resume` < `discovery` < `freeze`/`admission` < `receipt`/`checkpoint`; evidence: the pass row's `started_at` (pin), a level read (`timings_ms` set or an `up_to_date` idle tick), an uncommitted managed import or delete admitted later, a later commit). The CLI (`sync/operator.ts` `holdsListing`) bounds the holds: `holds_summary` (`topCounts` by code and by state: `needs_human`, `actionable`, `held`) over every hold, then `PLAIN_STATUS_HOLDS` (20) rows needs-human first, or with `--detail` a page of the shared listing contract (`bounded-listing.ts`, kind `sync_status_holds:<source>:<state>`, `--limit`/`--cursor`/`--all`, `--hold-state`), `holds_page` only when a page left rows out or took a cursor, the rows last. Test: `test/sync-status-truthful-7243.test.ts` (both engines).
- `src/core/persistence/resolve-paths.ts` — GBRA-150 `resolveSourcePaths`: what gbrain did with each file path of a source, by its own rules, so a landing check stops copying them. Per path: the sync slug (`resolveSlugForPath`), presence in the last synced commit and at HEAD (Git object reads), the skip reason (`unsyncableReason`, plus `typed_frontmatter` for a skipped metafile), the open hold, the live page by origin (`source_path`) and by slug (`slug_owner` when another file owns it, so a case-folded twin never reads as this file's page), a differing frontmatter `slug:`, chunk and embedding counts (`listEmbeddingStateRows` with its `slugs` filter), and one of `RESOLVE_PATH_STATES` with `searchable` (true / 'keyword' / false), `why` and an existing-command `fix`. Bounded: at most 200 paths, indexed lookups only, nothing written. Tests: `test/sources-resolve-path.test.ts`.
- `src/core/page-searchability.ts` — #7190 `readPageSearchability`: each live page's state, `searchable: true | 'keyword' | false`, chunks, `unembedded` (visible chunks with a NULL active-column vector) and `embedding_hold`, folded from `listEmbeddingStateRows` and the budget-hold read. Shared by resolve-path and `get_write_request`'s `applied`; `gbrain pages status` (#7181) can compose it with its Git view.
- `src/core/persistence/applied-watermark.ts` — #7190 `readAppliedWatermark` (sources status, MCP `sources_status`, `sync --json`) and the cheap `readWriteWatermark` (`get_write_request`): `indexed_through` is `sources.last_commit` (only a finished pass moves it), `embedded_through` reads the oldest page with a NULL vector (held pages count), `committed_through_request` is one below the oldest unsettled request of the incarnation, `pending` adds requests, files behind HEAD, held files and withheld deletes, `writer_heartbeat` is the drain-lease holder and its last progress (redacted for remote callers).
diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.md
index bc78a5084b..839d53906b 100644
--- a/docs/mcp/ADMIN.md
+++ b/docs/mcp/ADMIN.md
@@ -583,7 +583,8 @@ drives `tools/list`, the `gbrain://capabilities` resource (`access:
mutations; owner maintenance on the same process (startup migrations, hook
IPC 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.
+read-only value. `--surface=verbs` is likewise the same as `--surface verbs`, and a
+repeated `--surface` takes the narrowest value.
On Postgres a read-only serve is also not a resident owner, because harnesses
start one per session. It holds no session-lane (direct pool) connection, starts no
diff --git a/src/commands/doctor/checks/managed-sync-blocked.ts b/src/commands/doctor/checks/managed-sync-blocked.ts
index 8b0a3677bc..f6007743d4 100644
--- a/src/commands/doctor/checks/managed-sync-blocked.ts
+++ b/src/commands/doctor/checks/managed-sync-blocked.ts
@@ -28,7 +28,7 @@ async function runManagedSyncBlockedCheck(ctx: DoctorContext): Promise<Check[]>
const over = blocked.filter(b => now - Date.parse(b.blocked_since) > MANAGED_SYNC_BLOCKED_FAIL_MS);
const first = over[0] ?? blocked[0]!;
const minutes = (since: string) => Math.max(0, Math.floor((now - Date.parse(since)) / 60_000));
- const list = blocked.map(b => `${b.source_id} (${b.code}, blocked ${minutes(b.blocked_since)} min)`).join('; ');
+ const list = blocked.map(b => `${b.source_id} (${b.code}, ${b.code === 'pass_interrupted' ? 'stopped' : 'blocked'} ${minutes(b.blocked_since)} min)`).join('; ');
checks.push({ name: 'managed_sync_blocked', status: over.length ? 'fail' : 'warn', readiness_state: 'degraded',
details: { threshold_ms: MANAGED_SYNC_BLOCKED_FAIL_MS, sources: blocked.map(b => ({ ...b, blocked_minutes: minutes(b.blocked_since) })), docs: DOCS },
message: `${list}: the managed sync run is stopped on a page that did not commit, its passes keep stopping without converging, or its pass stopped before it ended with no process left to finish it (killed or crashed), so the source indexes nothing new until it is cleared`
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 889b9927d1..3c294e1d6c 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1303,7 +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: '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. `--surface=<v>` likewise now sets the serve surface (it was ignored, leaving the full surface), and a repeated `--surface` takes the narrowest value.' },
{ 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.ts
index c4ca80fb97..5453cff24f 100644
--- a/src/core/direct-pool-profile.ts
+++ b/src/core/direct-pool-profile.ts
@@ -22,17 +22,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.
+ * Every value of `flag` in `args`, in either form (`--access read-only`, `--access=read-only`; a bare flag at the end reads '').
+ * The one parse behind serve's ceilings (`parseAccessFlag`, `parseSurfaceFlag` in src/mcp/surface.ts) and the pool profile; it
+ * lives here because this module imports nothing. Reading only the bare form let `--access=read-only` and `--surface=verbs` pass
+ * flag validation and start a serve without the ceiling they asked for.
*/
-export function accessFlagValues(args: readonly string[]): string[] {
- return args.flatMap((arg, i) => arg === '--access' ? [args[i + 1] ?? ''] : arg.startsWith('--access=') ? [arg.slice('--access='.length)] : []);
+export function flagValues(args: readonly string[], flag: string): string[] {
+ return args.flatMap((arg, i) => arg === flag ? [args[i + 1] ?? ''] : arg.startsWith(`${flag}=`) ? [arg.slice(flag.length + 1)] : []);
}
/** `serve ... --access read-only`: a stdio serve that runs no resident write duty on Postgres (#7599). */
export function isReadOnlyServeArgs(args: readonly string[]): boolean {
- return accessFlagValues(args).includes('read-only');
+ return flagValues(args, '--access').includes('read-only');
}
/**
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index 1e0b003780..3800be9766 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -113,7 +113,7 @@ export function supersedingAttempt(phase: ManagedSyncFailure['phase'], failureAt
return passed[0] ? { at: new Date(passed[0][1]).toISOString(), by: passed[0][0] } : null;
}
-/** #7243: the process holding the source's drain lease (`readDrainHolder`), with the Minions job id when it is a sync job and whether it stalled. */
+/** #7243: the process holding the source's drain lease while it still renews it (`readDrainLease` with `live`, #7596), with the Minions job id when it is a sync job and whether it stalled. */
export type SyncStatusLive = DrainHolder & { job_id: number | null; stalled: boolean };
export interface SyncStatus {
diff --git a/src/mcp/surface.ts b/src/mcp/surface.ts
index ad41af8382..b55529535e 100644
--- a/src/mcp/surface.ts
+++ b/src/mcp/surface.ts
@@ -39,7 +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';
+import { flagValues } from '../core/direct-pool-profile.ts';
export type McpSurface = 'verbs' | 'starter' | 'full';
@@ -134,19 +134,23 @@ export const ALWAYS_INCLUDED_STARTER_OPS: ReadonlySet<string> = new Set([
'join_brain', 'sync_brain_skills', 'leave_brain', 'put_skill', 'delete_skill',
]);
-/** Strict flag parser — unknown values reject loudly (parseStdioIdleTimeout pattern). */
+/**
+ * Strict flag parser — unknown values reject loudly (parseStdioIdleTimeout pattern). `--surface=verbs` is the same flag
+ * (`flagValues`), and a repeated flag takes the narrowest value, so it never widens the ceiling.
+ */
export function parseSurfaceFlag(args: string[]): McpSurface | null {
- const idx = args.indexOf('--surface');
- if (idx < 0) return null;
- const raw = args[idx + 1];
- if (raw === undefined || raw.startsWith('--')) {
- throw opError('invalid_params', `--surface requires a value: verbs | starter | full`, 'Pass --surface verbs, --surface starter or --surface full (default full).');
- }
- if (!isMcpSurface(raw)) {
- throw opError('invalid_params', `Unknown --surface "${raw}". Use: verbs (the 7 memory verbs) | starter (the ~20 daily-driver ops) | full (all operations, default)`,
- 'Pass --surface verbs (the 7 memory verbs), --surface starter (the ~20 daily-driver ops) or --surface full (all operations, default).');
+ const values = flagValues(args, '--surface');
+ if (!values.length) return null;
+ for (const raw of values) {
+ if (!raw || raw.startsWith('--')) {
+ throw opError('invalid_params', `--surface requires a value: verbs | starter | full`, 'Pass --surface verbs, --surface starter or --surface full (default full).');
+ }
+ if (!isMcpSurface(raw)) {
+ throw opError('invalid_params', `Unknown --surface "${raw}". Use: verbs (the 7 memory verbs) | starter (the ~20 daily-driver ops) | full (all operations, default)`,
+ 'Pass --surface verbs (the 7 memory verbs), --surface starter (the ~20 daily-driver ops) or --surface full (all operations, default).');
+ }
}
- return raw;
+ return (values as McpSurface[]).reduce(minSurface);
}
/**
@@ -157,13 +161,13 @@ 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
+ * `--access=read-only` is the same flag (`flagValues`); 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 values = accessFlagValues(args);
+ const values = flagValues(args, '--access');
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' });
diff --git a/test/cli-flag-validation.test.ts b/test/cli-flag-validation.test.ts
index 4233bf8b68..20fdc18898 100644
--- a/test/cli-flag-validation.test.ts
+++ b/test/cli-flag-validation.test.ts
@@ -110,6 +110,7 @@ describe('#2185 acceptance — real usage stays legal', () => {
test('#7599: serve does not take sync --watch from the pool-profile module it imports', () => {
expect(validateCommandFlags('serve', ['--watch'])).toBe('--watch');
expect(validateCommandFlags('sync', ['--watch'])).toBeNull();
+ for (const args of [['--access', 'read-only'], ['--access=read-only']]) expect(validateCommandFlags('serve', args)).toBeNull();
});
test('scope flags require direct consumption on upgrade surfaces', () => {
diff --git a/test/serve-stdio-read-only.test.ts b/test/serve-stdio-read-only.test.ts
index 2abaabd914..acc2e29cff 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, parseAccessFlag } from '../src/mcp/surface.ts';
+import { isReadOnlyOperation, parseAccessFlag, parseSurfaceFlag } from '../src/mcp/surface.ts';
import { CAPABILITIES_URI } from '../src/mcp/capabilities.ts';
const MARKER = 'readonly-marker-4768';
@@ -75,6 +75,25 @@ test('--access reads both forms; a read-only value is never widened, and a bad v
expect(() => parseAccessFlag(args)).toThrow(/--access takes read-only or full/);
});
+test('--surface reads both forms; a repeated flag takes the narrowest value, and a bad value refuses', () => {
+ expect(parseSurfaceFlag([])).toBeNull();
+ for (const args of [['--surface', 'verbs'], ['--http', '--surface=verbs'], ['--surface=full', '--surface', 'verbs'], ['--surface', 'starter', '--surface=verbs']])
+ expect(parseSurfaceFlag(args)).toBe('verbs');
+ expect(parseSurfaceFlag(['--surface=starter'])).toBe('starter');
+ for (const args of [['--surface'], ['--surface='], ['--surface', '--http']]) expect(() => parseSurfaceFlag(args)).toThrow(/--surface requires a value/);
+ expect(() => parseSurfaceFlag(['--surface=all'])).toThrow(/Unknown --surface "all"/);
+});
+
+test('a stdio serve with --surface=verbs lists the verbs surface, not the full one', async () => {
+ const listed = async (args: string[]) => {
+ const { client, close } = await session(args);
+ try { return (await client.listTools()).tools.map(tool => tool.name).sort(); } finally { await close(); }
+ };
+ const verbs = await listed(['--surface', 'verbs']);
+ expect(await listed(['--surface=verbs'])).toEqual(verbs);
+ expect((await listed([])).length).toBeGreaterThan(verbs.length);
+}, 90_000);
+
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 () => {
@@ -129,6 +148,8 @@ 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);
+ const refusedEq = cli(['serve', '--http', '--access=read-only', '--port', '0']);
+ expect(refusedEq.status).not.toBe(0);
+ expect(refusedEq.stderr).toContain('gbrain auth rescope-token <name> --operations');
});
});