Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(bootstrap): --seat / --no-seat on bootstrap hooks and harness (#4618)

garrytan99b4e4f9b81b
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 818c24d3ba..787344a294 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -6,7 +6,7 @@
# fewer. Raising a row or adding one needs an issue/TODO id in the justification.
# docs/TESTING.md#function-size-ratchet
path name lines justification
-src/commands/bootstrap.ts runHooks 597 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
+src/commands/bootstrap.ts runHooks 600 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #4618: --seat/--no-seat parse + refusal/note (logic in core/bootstrap/hooks.ts parseSeatFlags)
src/commands/bootstrap.ts runHooks>withLock(#1) 449 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/config.ts runConfig 767 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5232: persistence.write_wait_ms dispatch line (logic in setFileWriteWait)
src/commands/doctor/bootstrap-checks.ts bootstrapDoctorChecks 476 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 9d83f5a962..15da3f8f11 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -28,7 +28,7 @@ src/core/minions/queue.ts 2522 ratchet grown #4078 + megawave probe-liveness unl
src/commands/init.ts 1932 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1918 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
-src/commands/bootstrap.ts 2131 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
+src/commands/bootstrap.ts 2142 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 1764 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
src/commands/sources.ts 2013 ratchet +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)
src/core/link-extraction.ts 2158 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
@@ -37,7 +37,7 @@ src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in
src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
src/core/config.ts 1819 ratchet +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts)
-src/core/bootstrap/harness.ts 2704 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts)
+src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 644 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso
src/core/search/mode.ts 1527 ratchet +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part
diff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.ts
index ff1a356b35..7af3e87011 100644
--- a/src/commands/bootstrap.ts
+++ b/src/commands/bootstrap.ts
@@ -57,6 +57,7 @@ import { uninstallWorkspace } from '../core/bootstrap/uninstall.ts';
import {
registerClaudeMcp,
registerCodexMcp,
+ parseSeatFlags,
writeClaudeHooks,
writeCommittedClaudeHooks,
removeClaudeHooks,
@@ -124,12 +125,15 @@ Subcommands (run \`gbrain bootstrap status\` first — it is the resume entrypoi
contract [--repair] Audit the same-turn GBrain write-back contract.
--repair appends it additively and backs up AGENTS.md.
hooks [--harness claude-code|codex|opencode] [--repair] [--no-hooks] [--gbrain-bin <path>]
+ [--seat <label> | --no-seat]
Register MCP (+ per-turn hooks on Claude Code,
ON by default; --no-hooks opts out, GBRAIN_HOOKS=0
disables at runtime). opencode registrations are
written directly into its JSONC config (user-global
by default; MCP_SCOPE=project is an explicit opt-in
- with a sharing warning).
+ with a sharing warning). --seat credits captured
+ sessions to this agent seat (kept on re-install;
+ --no-seat clears it; --seat off records none).
repo Create the dedicated PRIVATE GitHub repo (or adopt
an EMPTY private repo you created under your own
account), verify the privacy bit via the API, push.
@@ -139,6 +143,7 @@ Subcommands (run \`gbrain bootstrap status\` first — it is the resume entrypoi
harness [--harness claude-code|codex|opencode|all] [--url U | --port N] [--source ID]
[--token-name NAME | --token TOK] [--name MCPNAME] [--project DIR]...
[--no-hooks] [--no-capture] [--force] [--status] [--remove] [--refresh-skills] [--yes] [--json]
+ [--seat <label> | --no-seat]
Wire framework-spawned Claude Code / Codex / opencode
sessions to a RUNNING \`gbrain serve --http\` on this box
(#4043): scoped bearer token, user-scope MCP + headless
@@ -194,7 +199,9 @@ const SUBCOMMAND_HELP: Record<string, string> = {
' under your own account), verify the privacy bit via the API, push.',
hooks:
'gbrain bootstrap hooks [--harness claude-code|codex|opencode] [--repair] [--no-hooks] [--gbrain-bin <path>]\n' +
- ' Register MCP (+ per-turn hooks on Claude Code, ON by default; --no-hooks opts out).',
+ ' [--seat <label> | --no-seat]\n' +
+ ' Register MCP (+ per-turn hooks on Claude Code, ON by default; --no-hooks opts out).\n' +
+ ' --seat credits captured sessions to this agent seat (kept on re-install; --no-seat clears it; --seat off records none).',
verify:
'gbrain bootstrap verify [--json]\n' +
' The whole install contract (round-trip, graph floor, magic moment, scans, hooks smoke). Exit 0 or not done.',
@@ -215,6 +222,7 @@ const SUBCOMMAND_HELP: Record<string, string> = {
'gbrain bootstrap harness [--harness claude-code|codex|opencode|all] [--url U | --port N] [--source ID]\n' +
' [--token-name NAME | --token TOK] [--name MCPNAME] [--project DIR]...\n' +
' [--no-hooks] [--no-capture] [--force] [--status] [--remove] [--yes] [--json]\n' +
+ ' [--seat <label> | --no-seat]\n' +
' Wire framework-spawned Claude Code / Codex / opencode sessions to a RUNNING `gbrain serve --http`\n' +
' on this box (#4043). Idempotent; --remove tears it down. (--local is an accepted no-op alias.)\n' +
' See `gbrain bootstrap --help` for the per-flag description.',
@@ -1079,6 +1087,9 @@ async function runHooks(
// `--no-hooks` is the explicit install-time opt-out; `GBRAIN_HOOKS=0` and
// `uninstall` are the runtime/after off-ramps.
const noHooks = rest.includes('--no-hooks');
+ const seatFlags = parseSeatFlags(rest, harness);
+ if (seatFlags.error || seatFlags.note) console.error(seatFlags.error ?? seatFlags.note);
+ if (seatFlags.error) return 2;
// Plugin-lane override: detection reads the plugin-ENABLE config entry,
// which is not a health signal — a plugin whose launcher can't find the
// gbrain binary still matches. This flag forces the hand-wired MCP
@@ -1545,7 +1556,7 @@ async function runHooks(
// installs keep the gitignored settings.local.json with the absolute
// binary path. The writers enforce that one event never fires from
// both files.
- const hookEnv = { GBRAIN_SOURCE: sourceId, ...(gbrainHome ? { GBRAIN_HOME: gbrainHome } : {}) };
+ const hookEnv = { GBRAIN_SOURCE: sourceId, ...(gbrainHome ? { GBRAIN_HOME: gbrainHome } : {}), GBRAIN_SEAT: seatFlags.seat };
const cloudCarrier = detectExecutionEnvironment() === 'cloud-sandbox';
let r: ReturnType<typeof writeClaudeHooks> | ReturnType<typeof writeCommittedClaudeHooks>;
try {
diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.ts
index 38329aac12..f6099c8108 100644
--- a/src/core/bootstrap/harness.ts
+++ b/src/core/bootstrap/harness.ts
@@ -96,6 +96,7 @@ import {
addPermissionsAllowEntry,
claudeSettingsPath,
committedHookEvents,
+ parseSeatFlags,
removeClaudeHooksAt,
removePermissionsAllowEntry,
writeClaudeHooksAt,
@@ -160,6 +161,8 @@ export interface HarnessFlags {
json: boolean;
gbrainBin?: string;
skills?: 'follow' | 'memory-only';
+ /** #4618 `--seat <label>` ('' = `--no-seat`); undefined keeps the installed seat. */
+ seat?: string;
error?: string;
}
@@ -259,6 +262,9 @@ export function parseHarnessArgs(rest: string[]): HarnessFlags {
out.json = rest.includes('--json');
const bin = value('--gbrain-bin');
if (bin !== undefined) out.gbrainBin = bin;
+ const seat = parseSeatFlags(rest);
+ if (seat.error) out.error = out.error ?? seat.error;
+ if (seat.seat !== undefined) out.seat = seat.seat;
// [X14] Conflicting invocations error instead of resolving by precedence.
if (out.url !== undefined && out.port !== undefined) {
out.error = out.error ?? 'pass --url OR --port, not both (the url wins would be a silent guess)';
@@ -1414,6 +1420,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
const env: ClaudeHookEnv = {
...(hookSource !== null ? { GBRAIN_SOURCE: hookSource } : {}),
GBRAIN_HOOK_LANE: 'harness',
+ GBRAIN_SEAT: flags.seat,
};
const bin = flags.gbrainBin ?? d.gbrainBin;
if (!bin) {
diff --git a/src/core/bootstrap/hooks.ts b/src/core/bootstrap/hooks.ts
index b45f09d00a..1e323f91e1 100644
--- a/src/core/bootstrap/hooks.ts
+++ b/src/core/bootstrap/hooks.ts
@@ -27,6 +27,8 @@
import { copyFileSync, existsSync, readFileSync } from 'node:fs';
import { isAbsolute, join } from 'node:path';
import { atomicWriteTextFile } from './atomic-write.ts';
+import { normalizeSeatLabel } from '../context/seat.ts';
+import { detectExecutionEnvironment } from '../execution-env.ts';
import {
CLAUDE_COMMITTED_SETTINGS_FILE_RELPATH,
CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS,
@@ -56,6 +58,13 @@ export interface ClaudeHookEnv {
* the same event never fires twice (Claude Code merges settings scopes).
*/
GBRAIN_HOOK_LANE?: string;
+ /**
+ * #4618 seat label credited on captured sessions (`--seat`). Undefined
+ * keeps the seat a prior install of the same marker rendered; '' clears it
+ * (`--no-seat`). Local carriers only: the committed carrier travels between
+ * machines and never carries a seat.
+ */
+ GBRAIN_SEAT?: string;
}
export interface WriteClaudeHooksOpts {
@@ -163,10 +172,58 @@ export function buildClaudeHookCommand(
if (env.GBRAIN_SOURCE !== undefined) assignments.push(`GBRAIN_SOURCE=${env.GBRAIN_SOURCE}`);
if (env.GBRAIN_HOME) assignments.push(`GBRAIN_HOME=${env.GBRAIN_HOME}`);
if (env.GBRAIN_HOOK_LANE) assignments.push(`GBRAIN_HOOK_LANE=${env.GBRAIN_HOOK_LANE}`);
+ if (env.GBRAIN_SEAT) assignments.push(`GBRAIN_SEAT=${env.GBRAIN_SEAT}`);
const parts = ['env', ...assignments, gbrainBin, 'hook', CLAUDE_HOOK_SUBCOMMAND[event]];
return parts.map(shellQuote).join(' ');
}
+/**
+ * `--seat <label>` / `--no-seat` → the hook env's GBRAIN_SEAT: the validated
+ * label, '' to clear a carried seat, or undefined to keep the installed one.
+ * With the workspace lane's `harness`, `note` says where a seat cannot be
+ * rendered into a hook command and how to set it instead.
+ */
+export function parseSeatFlags(rest: string[], harness?: string): { seat?: string; error?: string; note?: string } {
+ const noSeat = rest.includes('--no-seat');
+ const i = rest.indexOf('--seat');
+ if (i < 0) return noSeat ? { seat: '' } : {};
+ if (noSeat) return { error: 'pass --seat <label> OR --no-seat, not both' };
+ const raw = rest[i + 1];
+ const seat = raw === undefined || raw.startsWith('--') ? null : normalizeSeatLabel(raw);
+ if (seat === null) {
+ return {
+ error:
+ `invalid --seat '${raw ?? ''}': a seat label is 1-64 characters of a-z, 0-9, '.', '_' or '-', ` +
+ 'starting with a letter or digit — re-run with a valid label, e.g. `--seat alice-desk`',
+ };
+ }
+ if (harness === 'codex') {
+ return { seat, note: `note: --seat applies to Claude Code hooks; codex sessions are credited to their CODEX_HOME seat (home-<hash>) unless GBRAIN_SEAT=${seat} is set in the environment codex runs in.` };
+ }
+ if (harness === 'opencode') return { seat, note: 'note: --seat has no effect for opencode — gbrain installs no opencode session-capture hooks.' };
+ if (harness === 'claude-code' && detectExecutionEnvironment() === 'cloud-sandbox') {
+ return { seat, note: `note: --seat is not written to the COMMITTED hook carrier (it travels with the repo) — set GBRAIN_SEAT=${seat} in this cloud environment's variables instead.` };
+ }
+ return { seat };
+}
+
+/** The seat a prior install of `marker` rendered into this file's hook commands. */
+function installedSeat(hooks: Record<string, unknown>, marker: string): string | undefined {
+ for (const groups of Object.values(hooks)) {
+ if (!Array.isArray(groups)) continue;
+ for (const group of groups) {
+ const entries = (group as HookMatcherGroup)?.hooks;
+ if (!Array.isArray(entries)) continue;
+ for (const entry of entries) {
+ if (!isOurs(entry, marker) || typeof (entry as HookCommandEntry).command !== 'string') continue;
+ const m = /(?:^| )GBRAIN_SEAT=([a-z0-9][a-z0-9._-]{0,63})(?= )/.exec((entry as HookCommandEntry).command);
+ if (m) return m[1];
+ }
+ }
+ }
+ return undefined;
+}
+
export function claudeCommittedSettingsPath(workspaceDir: string): string {
return join(workspaceDir, CLAUDE_COMMITTED_SETTINGS_FILE_RELPATH);
}
@@ -423,6 +480,10 @@ export function writeClaudeHooksAt(
// --project lane does the same for its dirs) — this path-parameterized
// writer has no workspace to derive it from.
const carried = opts.carriedEvents ?? new Set<ClaudeHookEvent>();
+ // #4618: a re-install without --seat keeps the seat the prior install chose.
+ const env = opts.env.GBRAIN_SEAT === undefined
+ ? { ...opts.env, GBRAIN_SEAT: installedSeat(hooks, marker) }
+ : opts.env;
let removedPrior = 0;
const installed: Array<{ event: ClaudeHookEvent; command: string }> = [];
@@ -462,7 +523,7 @@ export function writeClaudeHooksAt(
continue;
}
- const command = buildClaudeHookCommand(opts.gbrainBin, event, opts.env);
+ const command = buildClaudeHookCommand(opts.gbrainBin, event, env);
const timeout = opts.timeoutSecs?.[event] ?? CLAUDE_HOOK_DEFAULT_TIMEOUT_SECS[event];
const entry: HookCommandEntry = {
type: 'command',
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index b317c262d5..e33f0a23c5 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -24,7 +24,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout', '--wait'],
'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],
'book-mirror': ['--accept-pending', '--access', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--file', '--follow', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-turns', '--mode', '--model', '--multimodal', '--no-accept-pending', '--no-confirm', '--no-follow', '--once', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stats', '--surface', '--timeout', '--timeout-ms', '--title', '--trusted-extraction', '--types', '--url', '--wait', '--yes'],
- 'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--env', '--error-unmatch', '--exclude-standard', '--exit-code', '--file', '--force', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-ancestor', '--is-inside-work-tree', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-hooks', '--no-tags', '--no-verify', '--no-write-fetch-head', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pure', '--push', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--scope', '--scopes', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
+ 'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--env', '--error-unmatch', '--exclude-standard', '--exit-code', '--file', '--force', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-ancestor', '--is-inside-work-tree', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-hooks', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pure', '--push', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--stale', '--strict-budget', '--yes'],
'cache': ['--brain', '--help', '--json', '--source', '--yes'],
'calibration': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--dry-run', '--entities', '--federated-read', '--file', '--full', '--help', '--holder', '--http', '--image', '--json', '--key-prefix', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--phase', '--regenerate', '--scrub-gstack', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stats', '--surface', '--trusted-extraction', '--types', '--undo-wave', '--url', '--with-calibration', '--yes'],
@@ -65,7 +65,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'frontmatter': ['--allow-catch-all', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--get', '--git-common-dir', '--help', '--include-catch-all', '--json', '--name-only', '--no-verify', '--others', '--source', '--type', '--uninstall'],
'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],
'graph-query': ['--brain', '--depth', '--direction', '--help', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
- 'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--session', '--show-current', '--show-toplevel', '--source'],
+ 'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--seat', '--session', '--show-current', '--show-toplevel', '--source'],
'import': ['--accept-pending', '--allow-empty', '--allow-noncanonical-root', '--background', '--brain', '--cached', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-renames', '--no-verify', '--others', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
'init': ['--all', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--quiet', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--version', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
diff --git a/test/bootstrap-seat.serial.test.ts b/test/bootstrap-seat.serial.test.ts
new file mode 100644
index 0000000000..92ee5c903d
--- /dev/null
+++ b/test/bootstrap-seat.serial.test.ts
@@ -0,0 +1,132 @@
+/**
+ * #4618 `gbrain bootstrap hooks --seat <label>` / `bootstrap harness --seat`:
+ * the seat label is rendered as `GBRAIN_SEAT=<label>` into every gbrain hook
+ * command, survives a re-install that omits the flag, is cleared by
+ * `--no-seat`, and an invalid label is refused with the fix spelled out.
+ *
+ * Authoring gate: protects the install-time seat contract (the only way an
+ * operator names a seat for framework-spawned sessions). A regression that
+ * drops the env assignment, loses the seat on `--repair`, or writes an
+ * unvalidated label into a shell command fails here. No existing test renders
+ * a seat; no production seam is added (the recording exec runner is the
+ * dispatcher suite's).
+ *
+ * SERIAL: mutates GBRAIN_HOME.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runBootstrap } from '../src/commands/bootstrap.ts';
+import type { ExecRunner } from '../src/core/bootstrap/repo.ts';
+import { parseHarnessArgs } from '../src/core/bootstrap/harness.ts';
+import { writeClaudeHooksAt } from '../src/core/bootstrap/hooks.ts';
+import { GBRAIN_HARNESS_MARKER_VALUE } from '../src/core/bootstrap/host-specs.ts';
+import { confirm, initState, readBackHash, setAnswer } from '../src/core/bootstrap/interview.ts';
+
+const scratch: string[] = [];
+afterAll(() => {
+ for (const d of scratch) rmSync(d, { recursive: true, force: true });
+});
+
+const runner: ExecRunner = async (argv: string[]) =>
+ argv[1] === 'mcp' && argv[2] === 'list' ? { code: 0, stdout: 'gbrain: stdio serve', stderr: '' } : { code: 0, stdout: '', stderr: '' };
+
+async function capture<T>(fn: () => Promise<T>): Promise<{ result: T; err: string }> {
+ const [origLog, origErr] = [console.log, console.error];
+ let err = '';
+ console.log = () => {};
+ console.error = (...args: unknown[]) => { err += args.map(String).join(' ') + '\n'; };
+ try {
+ return { result: await fn(), err };
+ } finally {
+ console.log = origLog;
+ console.error = origErr;
+ }
+}
+
+async function withHome<T>(parent: string, fn: () => Promise<T>): Promise<T> {
+ const prev = process.env.GBRAIN_HOME;
+ process.env.GBRAIN_HOME = parent;
+ try {
+ return await fn();
+ } finally {
+ if (prev === undefined) delete process.env.GBRAIN_HOME;
+ else process.env.GBRAIN_HOME = prev;
+ }
+}
+
+function freshWorkspace(): { ws: string; parent: string } {
+ const parent = mkdtempSync(join(tmpdir(), 'gb-seat-home-'));
+ mkdirSync(join(parent, '.gbrain'), { recursive: true });
+ const ws = mkdtempSync(join(tmpdir(), 'gb-seat-ws-'));
+ scratch.push(parent, ws);
+ expect(initState(ws).ok).toBe(true);
+ for (const [key, value] of Object.entries({
+ AGENT_NAME: 'Dispatch', PRINCIPAL_NAME: 'Pat Example',
+ AGENT_PURPOSE: 'Maintain the research corpus and draft the weekly memo without re-briefing.',
+ AGENT_TOP_JOBS: '- corpus upkeep\n- weekly memo\n- meeting prep',
+ PRINCIPAL_CONTEXT: 'Runs a small research group; values signal over noise.',
+ VOICE_REGISTER: 'Direct: three options, the second one wins.', MCP_SCOPE: 'project',
+ })) {
+ const r = setAnswer(ws, key, value);
+ if (!r.ok) throw new Error(r.message);
+ }
+ const h = readBackHash(ws);
+ if (!h.ok) throw new Error(h.message);
+ expect(confirm(ws, h.hash).ok).toBe(true);
+ return { ws, parent };
+}
+
+/** Every gbrain hook command in a settings file. */
+function hookCommands(settingsPath: string): string[] {
+ const hooks = JSON.parse(readFileSync(settingsPath, 'utf8')).hooks as Record<string, Array<{ hooks: Array<{ command: string; _gbrain?: string }> }>>;
+ return Object.values(hooks).flatMap((groups) => groups.flatMap((g) => g.hooks.filter((h) => h._gbrain).map((h) => h.command)));
+}
+
+describe('bootstrap --seat (#4618)', () => {
+ test('10. hooks --seat renders GBRAIN_SEAT into every hook command and survives a re-install; --no-seat clears it', async () => {
+ const { ws, parent } = freshWorkspace();
+ const settings = join(ws, '.claude', 'settings.local.json');
+ const hooks = (...extra: string[]) =>
+ capture(() => runBootstrap(['hooks', '--workspace', ws, '--harness', 'claude-code', '--gbrain-bin', process.execPath, ...extra], { runner }));
+ await withHome(parent, async () => {
+ expect((await capture(() => runBootstrap(['render', '--workspace', ws]))).result).toBe(0);
+ expect((await hooks('--seat', 'Alice-Desk')).result).toBe(0);
+ const installed = hookCommands(settings);
+ expect(installed.length).toBeGreaterThan(0);
+ for (const c of installed) expect(c).toContain(' GBRAIN_SEAT=alice-desk ');
+
+ expect((await hooks('--repair')).result).toBe(0);
+ expect(hookCommands(settings)).toEqual(installed);
+
+ const refused = await hooks('--seat', 'Not A Seat');
+ expect(refused.result).toBe(2);
+ expect(refused.err).toContain("invalid --seat 'Not A Seat'");
+ expect(refused.err).toContain('--seat alice-desk');
+ expect(hookCommands(settings)).toEqual(installed);
+
+ expect((await hooks('--no-seat')).result).toBe(0);
+ for (const c of hookCommands(settings)) expect(c).not.toContain('GBRAIN_SEAT');
+ });
+ }, 60_000);
+
+ test('harness lane: --seat parses into the flags and the harness-marker hooks keep it across a re-install', () => {
+ expect(parseHarnessArgs(['--seat', 'Bob-Desk']).seat).toBe('bob-desk');
+ expect(parseHarnessArgs(['--no-seat']).seat).toBe('');
+ expect(parseHarnessArgs([]).seat).toBeUndefined();
+ expect(parseHarnessArgs(['--seat', '-bad']).error).toContain("invalid --seat '-bad'");
+
+ const dir = mkdtempSync(join(tmpdir(), 'gb-seat-harness-'));
+ scratch.push(dir);
+ const settings = join(dir, 'settings.json');
+ const write = (env: { GBRAIN_SEAT?: string }) => writeClaudeHooksAt(settings, {
+ gbrainBin: process.execPath, env: { GBRAIN_HOOK_LANE: 'harness', ...env }, marker: GBRAIN_HARNESS_MARKER_VALUE,
+ });
+ write({ GBRAIN_SEAT: 'bob-desk' });
+ const installed = hookCommands(settings);
+ for (const c of installed) expect(c).toContain('GBRAIN_HOOK_LANE=harness GBRAIN_SEAT=bob-desk ');
+ write({});
+ expect(hookCommands(settings)).toEqual(installed);
+ });
+});