Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(cli): help never acts; strict args for destructive subcommands; purge asks first (#6114)
garrytan38ae58a5c98c
diff --git a/docs/architecture/key-files/agent-bootstrap.md b/docs/architecture/key-files/agent-bootstrap.mdindex d86a27f885..dc71c8e9e5 100644--- a/docs/architecture/key-files/agent-bootstrap.md+++ b/docs/architecture/key-files/agent-bootstrap.md@@ -25,7 +25,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche- `src/core/bootstrap/atomic-write.ts` — the ONE atomic config-file writer for bootstrap host surfaces: symlink-target-resolving, mode-inheriting (`freshMode` for new files, `forceMode` for secret-bearing targets), random-suffix tmp + rename, tmp unlinked best-effort when write/chmod/rename throws (ENOSPC/EACCES never strand `.tmp-` litter), and the existsSync→realpathSync race falls back to fresh-path resolution instead of throwing raw ENOENT. hooks.ts (JSON), codex-toml.ts (TOML+EOL), and opencode-json.ts (JSONC) all swap through it; serialization and EOL policy stay caller-side.- `src/core/bootstrap/harness.ts` — `gbrain bootstrap harness`: machine-level wiring of framework-spawned Claude Code/Codex/opencode sessions to a RUNNING `gbrain serve --http`, no `agent.json`. The opencode target mirrors the codex posture: forced-wire on explicit `--harness opencode` (the JSONC writer needs no CLI), one managed `mcp.<name>` remote entry with the inline bearer header (0600) via `opencode-json.ts`, rotation across a url change recognized through the PRIOR receipt's url, failed-smoke rollback restoring the run's UNIQUE backup or removing a fresh entry — guarded by a content compare against the exact text this run wrote, so a NEWER registration that landed after the lock released is never clobbered (rollback skips with a note; the fresh mint is revoked either way), with the backup unlinked once consumed or once the smoke verifies — `--remove` classifying against the receipt url (not-ours skips with a note), and `--status` bearer recovery via `parseOpencodeEntryBearer` (url-matched). An explicit private posture (file-plane `memory.visibility_posture`) prints a pre-consent WARNING outside registrar mode: the wired HTTP sessions read world facts only, so they cannot read back what they save as private. Consent block in the honesty register (reach as fact, transcript capture its own numbered item + `--no-capture`, off-ramps in the same breath), then `requireConsent` via `consentGate` (effects `persistent_install`, plus `credentials` when it mints the token; `--yes` approves; the TTY prompt runs only when `isInteractive()`, and EOF/decline or no human at the terminal writes nothing and exits 3 with the consent payload, whose argv never repeats `--token`); /health probe with a loopback guard on `--url` (remote brains are `gbrain connect`'s charter; `--token` makes it a pure registrar); mint-first rotation (previous token revoked BY ID only after every target confirms + the bearer smoke passes — clients are never dead mid-swap; revoke-by-name never happens); the smoke is canary-gated: a random same-format bearer must FAIL auth before the real token is sent, so a loopback impostor is caught whichever way it answers, and ANY failed smoke rolls back symmetrically — fresh registrations removed, replaced ones restored (an unrestorable replacement fails the target honestly), the freshly-added pre-approval stripped, and the fresh mint revoked immediately so nothing live stays pointed at an unverified endpoint; the `permissions.allow` pre-approval only lands after the MCP registration itself confirms; stale prior-target cleanup runs AFTER the smoke passes, so a run that failed to establish its replacement never unwires working prior wiring; write-ahead harness receipt (targets persist as `pending` at mint time and flip per-target, so a crash leaves consumable state); registration ownership checks (`--force` to replace a foreign-url server; `--remove` skips what it no longer owns); user-XOR-project hook scopes; `GBRAIN_HOOK_LANE=harness` on hook commands so `gbrain hook` yields to a workspace bootstrap install in the cwd (Claude Code merges settings scopes — same event must not fire twice); the hook `GBRAIN_SOURCE`, the receipt `source_id`, and the token grant bind to a validated `--source` (scalar write floor), else to the source `HarnessDeps.resolveHookSource` resolves through the SAME chain the serve's resolve-IPC binding runs (`resolveSourceWithTier`: env → dotfile → local_path → `sources.default` → sole populated non-default → seed default) with that source's federated read set as the grant, so the hooks' `turn_context` claim is never `source_mismatch`; a resolution landing on `default`/`__all__` is the federated floor. Lookup failures are NOT papered over with `default`: a typo'd `--source` or stale env/dotfile throws `SOURCE_UNRESOLVED` before any mint or receipt; an explicit `--source` with an unopenable engine binds unverified with a warning; a live PGLite serve (engine cannot open) refuses with the `LIVE_SERVE` escape hatches when no token was supplied and, on the `--token` lane without `--source`, wires the hooks UNPINNED with a warning (an unpinned hook resolves through the live serve's own binding; the receipt records the federated floor `default` plus `source_pinned: false`); any other lookup failure throws `SOURCE_UNRESOLVED` naming `--source`; Postgres degradation + serve-version-skew honesty lines (`isServeOlderThanScopes` pinned to `SCOPES_MIN_SERVE_VERSION`, the first scope-aware release, so later CLI bumps never re-trigger the warning); `--status` probes the live truth with host-config token recovery (redacted; the Claude Code lane recovers a bearer ONLY from a registration whose URL matches the receipt — never another install's credential; the codex fallback reads OUR managed block at the receipt-recorded path, its `url` key not yet compared — TODOS.md; the opencode fallback IS url-compared inside `parseOpencodeEntryBearer`) and honest `verify: unavailable` degrades, with a cron-honest exit contract: 0 only when serve + token + every target verify and the rotation has converged (honest degrades count), 1 on an unreachable serve, a failed token verify, failed/pending targets, unconverged rotations, or a half-removed receipt (zero targets, minted token awaiting deferred revoke — also a doctor FAIL); no receipt prints honestly and exits 0 in plain mode, 2 under `--json`; `--json` on apply emits ONLY the final JSON document on stdout (prose → stderr); `--remove` is engine-free-first and defers the token revoke with exact instructions under a live PGLite serve. Locks on the gbrain HOME, plus the host config dir around codex/opencode writes, removals, rollbacks, and stale cleanup (stale prior-target cleanup nests the codex/opencode config-dir lock inside the held claude config-dir lock — same claude-first ordering as apply/remove, same-dir skip — so its read-modify-write can't interleave with a concurrent config-dir-locked writer); `bootstrap uninstall` holds the HOME lock across the whole teardown and runs harness removal FIRST (revoke needs the DB alive; `--delete-brain` would destroy harness.json) and treats NO_RECEIPT/HOME_GUARD/RECEIPT_MISMATCH as "no workspace install" once harness wiring is cleared. Pinned by `test/bootstrap-harness.serial.test.ts` + `test/bootstrap-harness-lifecycle.serial.test.ts`. The production mint (`mintHarnessToken`, exported) rotates each host's token from the token it replaces via `carryLegacyGrant`. `--refresh-skills` (`src/core/bootstrap/harness-skills.ts`, `refreshHarnessSkills`) re-joins each live shared-skills entry under its recorded credential so the receipt and native router adopt the server's current enrollment epoch, with no token rotation; `localEnrollment` reads the adapter receipt epoch for `--status`, and `supersededEnrollments` is doctor's read-only comparison against `shared_skill_members` (`bootstrap_harness_health` warn, code `shared_skills_epoch_superseded`). Pinned by `test/harness-skills-epoch.test.ts`.- `src/core/token-mint.ts` — programmatic legacy-token mint/revoke for the harness lane: `mintLegacyToken` (scopes → the TEXT[] column; required `takesHolders` per-token allow-list, harness default `['world']`; optional `permissions.source_id` federation array mirroring the stdio lane's `localFederatedSourceIds` grant, element 0 = write floor, `[]` stored as the explicit no-source grant; `RETURNING id`) and `revokeLegacyTokenById` (never touches same-name siblings). `carryLegacyGrant` + `readActiveTokenPermissions` are the harness rotation carry-over: takes holders and the source grant carry as stored (explicit empty lists included; an explicit `--source` wins), a stored operation snapshot narrows to the run's snapshot plus only skills-policy-added operations, and newer operations are reported as withheld (pinned by `test/harness-rotation-grants.test.ts`). Exports `TOKEN_ID_RE`, the canonical token-id shape shared with the `auth revoke --id` CLI gate. Canonical `hashToken`/`generateToken` from `src/core/utils.ts`. Pinned by `test/token-mint.test.ts`. `insertUnifiedToken` (shared with `auth create`) births every token on the unified grant columns at revision 1 plus the `permissions` mirror; a brain whose schema predates the columns refuses with `migrations_pending` (fix: `gbrain apply-migrations --yes`) and nothing is written; `carryLegacyGrant` parses the prior grant from its JSONB through `tokenGrantFromPermissions`, so a drifted prior carries its JSON edit (the `--adopt-permissions` resolution).-- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). When `GBRAIN_HOOK_LANE=harness` (set on harness-mode hook commands), each event PARSES the cwd's workspace settings carriers — `.claude/settings.local.json` AND the committed `.claude/settings.json` — and yields silently only when a live `bootstrap-v1` hook entry wires THAT event: the workspace install wins over user-scope harness wiring so the merged settings scopes can't fire the same event twice, unwired events still run, and a repo committing marker-lookalike strings in unrelated fields can't disable the machine-wide capture lane (fail-open — a read/parse hiccup means the event runs normally). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: a transcript path or payload cwd carrying the claude-cli scratch fingerprint (`isClaudeCliSelfTranscriptPath`) is gbrain's own subprocess session — heartbeat `segment: self_transcript`, no parse, no corpus write; otherwise confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune via `gcCorpusTurnFiles`: an extracted `.txt` goes at `corpus_retention_days`, one with no `.ingested` sidecar only at `CORPUS_UNINGESTED_RETENTION_FACTOR` (3) times that, E-N1, pinned by `test/corpus-retention-uningested.serial.test.ts`; an assistant-only whole-file parse heartbeats `degraded`/`no_user_turns`, E-N4; the corpus scan runs highEntropy whenever the relay is on — the relay child derives its egress task line from the corpus text — and stays vendor-prefix-only otherwise) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push would block harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events. Session-end capture dispatches per harness through `captureSpecFor(io.harness)` (`src/core/transcripts/capture-spec.ts`): claude-code and codex each pin their OWN confinement root + parser; unknown/undefined/opencode resolve to the claude spec (golden-pinned). The codex lane confines to `codexSessionsDir()` + `codexArchivedSessionsDir()` (codex moves rollouts into the flat archived store), parses rollouts via `parseCodexHookTranscript`, and falls back to bounded id-matched discovery across both stores when the SessionEnd payload carries `transcript_path: null` or a path that no longer exists (`missing_path`; `unreadable` is reserved for EACCES/IO faults) — the fallback and prior-run relay failures are DEFERRED heartbeat reasons, applied after current-session reasons so they never mask one (first-degrade-wins). ONE gate covers the whole optional Memorable seam — `memorableGateAllowed(cfg)` in hook-heartbeat.ts: the config flag (`integrations.memorable.enabled === true`, file plane), the `GBRAIN_MEMORABLE` kill switch (any common negative spelling, trimmed; env can only ever disable), AND the gbrain-authored consent stamp (`memorable-consent.json` — see hook-heartbeat.ts). Off is the default: no tool-call collection, no receipt, no spawn. On, session-end runs the shared `redactedToolCallsJson` (span-filtered to the corpus window, highEntropy ALWAYS on — those args are the one artifact that leaves the machine) and `recordAndRelayReceipt` (receipt dedup by post-redaction content hash → CLI-side consent evidence → `resolveMemorableBin` → detached fire-and-forget `memorable record` spawn; both capture lanes trim memorable-relay.jsonl). Fail-closed egress guards: a scanner-import failure skips the receipt+relay entirely (`memorable_relay_skipped_unscanned` — parity with the openclaw lane), and a newest-mtime discovery GUESS (no session-id match) writes the local corpus but never relays (`memorable_relay_skipped_newest_guess` — the newest rollout can be a different, still-running session). A payload without session_id adopts the transcript's own id post-parse (never a shared unknown.txt corpus), and the gate answer is hoisted BEFORE the parse and collection is opt-in, so the default gate-off population never collects tool calls (`collectToolCalls: memorableAllowed`). Operator-facing doc: `docs/memorable-agents.md` (install is `npm i -g memorable-cli`; closed source, no source install, no embedding model to configure). `spawnDetachedPush` passes `env: process.env` explicitly so the detached push child inherits the parent's quarantined env view. `tryExecAsync` (the git wrapper behind `resolveBootstrapWorkspaceRoot` / `repoPhaseComplete`) also passes `env: process.env` so git sees the quarantined view, not Bun's startup snapshot; pinned by `test/hook-push-spawn-env.test.ts`. Seat identity (#4618): session-end (before any corpus write of the session), compact (before `bankCompactSegment`) and the stop hook's writeback bank (before `bankWritebackTurn`) record `<sessionId>.seat.json` through `context/seat.ts` — `GBRAIN_SEAT` when valid, else the hashed harness-home seat; `seat_label_invalid`, `seat_conflict` (first seat kept) and `seat_write_failed` are heartbeat reasons with a fixed `hint` (session-end applies them last, like the deferred reasons). `gcCorpusArtifacts` reaps a seat sidecar once no `.txt` of its session remains, after a 10-minute grace. Pinned by `test/session-seat-capture.serial.test.ts`.+- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). When `GBRAIN_HOOK_LANE=harness` (set on harness-mode hook commands), each event PARSES the cwd's workspace settings carriers — `.claude/settings.local.json` AND the committed `.claude/settings.json` — and yields silently only when a live `bootstrap-v1` hook entry wires THAT event: the workspace install wins over user-scope harness wiring so the merged settings scopes can't fire the same event twice, unwired events still run, and a repo committing marker-lookalike strings in unrelated fields can't disable the machine-wide capture lane (fail-open — a read/parse hiccup means the event runs normally). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: a transcript path or payload cwd carrying the claude-cli scratch fingerprint (`isClaudeCliSelfTranscriptPath`) is gbrain's own subprocess session — heartbeat `segment: self_transcript`, no parse, no corpus write; otherwise confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune via `gcCorpusTurnFiles`: an extracted `.txt` goes at `corpus_retention_days`, one with no `.ingested` sidecar only at `CORPUS_UNINGESTED_RETENTION_FACTOR` (3) times that, E-N1, pinned by `test/corpus-retention-uningested.serial.test.ts`; an assistant-only whole-file parse heartbeats `degraded`/`no_user_turns`, E-N4; the corpus scan runs highEntropy whenever the relay is on — the relay child derives its egress task line from the corpus text — and stays vendor-prefix-only otherwise) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push would block harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events. Session-end capture dispatches per harness through `captureSpecFor(io.harness)` (`src/core/transcripts/capture-spec.ts`): claude-code and codex each pin their OWN confinement root + parser; unknown/undefined/opencode resolve to the claude spec (golden-pinned). The codex lane confines to `codexSessionsDir()` + `codexArchivedSessionsDir()` (codex moves rollouts into the flat archived store), parses rollouts via `parseCodexHookTranscript`, and falls back to bounded id-matched discovery across both stores when the SessionEnd payload carries `transcript_path: null` or a path that no longer exists (`missing_path`; `unreadable` is reserved for EACCES/IO faults) — the fallback and prior-run relay failures are DEFERRED heartbeat reasons, applied after current-session reasons so they never mask one (first-degrade-wins). ONE gate covers the whole optional Memorable seam — `memorableGateAllowed(cfg)` in hook-heartbeat.ts: the config flag (`integrations.memorable.enabled === true`, file plane), the `GBRAIN_MEMORABLE` kill switch (any common negative spelling, trimmed; env can only ever disable), AND the gbrain-authored consent stamp (`memorable-consent.json` — see hook-heartbeat.ts). Off is the default: no tool-call collection, no receipt, no spawn. On, session-end runs the shared `redactedToolCallsJson` (span-filtered to the corpus window, highEntropy ALWAYS on — those args are the one artifact that leaves the machine) and `recordAndRelayReceipt` (receipt dedup by post-redaction content hash → CLI-side consent evidence → `resolveMemorableBin` → detached fire-and-forget `memorable record` spawn; both capture lanes trim memorable-relay.jsonl). Fail-closed egress guards: a scanner-import failure skips the receipt+relay entirely (`memorable_relay_skipped_unscanned` — parity with the openclaw lane), and a newest-mtime discovery GUESS (no session-id match) writes the local corpus but never relays (`memorable_relay_skipped_newest_guess` — the newest rollout can be a different, still-running session). A payload without session_id adopts the transcript's own id post-parse (never a shared unknown.txt corpus), and the gate answer is hoisted BEFORE the parse and collection is opt-in, so the default gate-off population never collects tool calls (`collectToolCalls: memorableAllowed`). Operator-facing doc: `docs/memorable-agents.md` (install is `npm i -g memorable-cli`; closed source, no source install, no embedding model to configure). `spawnDetachedPush` passes `env: process.env` explicitly so the detached push child inherits the parent's quarantined env view. `tryExecAsync` (the git wrapper behind `resolveBootstrapWorkspaceRoot` / `repoPhaseComplete`) also passes `env: process.env` so git sees the quarantined view, not Bun's startup snapshot; pinned by `test/hook-push-spawn-env.test.ts`. Seat identity (#4618): session-end (before any corpus write of the session), compact (before `bankCompactSegment`) and the stop hook's writeback bank (before `bankWritebackTurn`) record `<sessionId>.seat.json` through `context/seat.ts` — `GBRAIN_SEAT` when valid, else the hashed harness-home seat; `seat_label_invalid`, `seat_conflict` (first seat kept) and `seat_write_failed` are heartbeat reasons with a fixed `hint` (session-end applies them last, like the deferred reasons). `gcCorpusArtifacts` reaps a seat sidecar once no `.txt` of its session remains, after a 10-minute grace. Pinned by `test/session-seat-capture.serial.test.ts`. `HOOK_EVENTS` is the router inventory from `src/cli/subcommands.ts`; `hook <event> --help` prints usage and never runs the event.- `src/core/transcripts/claude-code-jsonl.ts` — the Claude Code transcript parser as a dated spec-target (tool_use/tool_result/thinking/image/sidechain/summary/compact-boundary shapes; placeholders for non-text content). Both the hook-tail and full-session parsers skip root `isSidechain`, `isMeta`, or `isCompactSummary` exactly `true`; nested markers and truthy non-booleans do not exclude a turn. User text with a non-empty string root `origin.kind` other than `'human'` is excluded; missing, empty, or unstructured origins stay compatible, without guessing from message text. Assistant text and non-text placeholders remain eligible, while skipped metadata entries also contribute no collected tool calls. `test/claude-code-jsonl-origin.test.ts` uses synthetic fixtures, not new live-harness validation. `genuineUserTurnIndexes` separately records accepted user-role turns containing real text blocks (harness tags and paste blocks removed first), because Claude stores tool-result-only entries with `role:'user'`; archival consumers keep every placeholder while prompt-only consumers select by structure. Also extracts `injectedContextBlocks` — the `hook_additional_context` attachment lines a gbrain hook previously injected (verified live against claude CLI 2.1.224; marker-filtered, so a foreign hook's blocks are excluded and another tool's output can't suppress volunteering — a same-user mislabeling guard, not an authenticity check), the user-prompt hook's cross-turn dedupe input; `confineTranscriptPath` (contained under `~/.claude/projects`, `.jsonl`, lstat-rejects symlinks, byte cap; under WSL, a Windows drive-literal `transcript_path` — Claude Code on the Windows host invoking hooks via `wsl.exe` — is translated through `src/core/wsl-paths.ts` and then held to the SAME confinement, rooted Windows-side, so translation never widens what a hook may read). Fixtures: `test/fixtures/conversation-formats/claude-code.jsonl` (synthetic, privacy-guarded) + `test/fixtures/hook-transcript.jsonl` (real captured hook round-trip). `parseTranscript` additionally returns `toolCalls`, but collection is OPT-IN (`collectToolCalls: true`; the bare parse — every per-prompt lane — collects nothing, so tool INPUTS are never retained for users who never opted in): the tool name + input args for every `tool_use` block, oldest → newest, each joined to its `tool_result` outcome by `tool_use_id` and then stripped of that id so no transcript-internal identifier reaches a consumer; every STRING in a collected input is bounded to `TOOL_CALL_VALUE_MAX_CHARS` (32k) with an explicit `…[N chars omitted]` marker (`capToolCallInput`, shared with the codex lane — one receipt-size ceiling for every harness). It is a parallel extraction, never a change to the placeholder-only archival rendering, which is load-bearing for the token-budget-constrained ambient-recall path; existing callers that ignore the field see no behavior change.- `src/core/transcripts/pasted-content.ts` — #5812, the ONE Claude Code paste detector (`<pasted_content id="…">…</pasted_content id="…">`, tag shape from a real 2.1.287 transcript; depends on that harness format). `stripPastedContent` removes closed blocks and an unclosed tail only when the opening tag has the exact harness shape, scanning with `indexOf` (no lazy regex); `stripPastedContentFromCorpus` strips inside each `[user]` block of the `toCorpusText` rendering, never across the flattened corpus, so an unclosed paste ends with its turn. Consumers: the writeback gate (banked text), `isGenuineUserText` in the parser (classification only; turn, corpus, segment and ingest text keep the paste), and `corpusTextForExtraction` (`corpus-segments.ts`: a `.wb-` file is one turn, other corpus files per block) used by the sweep, the checkpoint harvest and dream `extract_atoms`. `synthesize` keeps pastes. Tests: `test/transcripts-pasted-content.test.ts`, `test/facts/writeback-gate.test.ts`, `test/extract-atoms-pasted-content.test.ts`.- `src/core/transcripts/grok.ts` — the Grok Build (grok CLI) transcript adapter: one session directory (`~/.grok/sessions/<url-encoded-cwd>/<uuid>/chat_history.jsonl`) = one session; `GROK_HOME` relocates the root. Turn selection is STRUCTURAL (`mapGrokLine`, exported so the dated `SPEC_TARGET` mapping is pinned): user turns are `type:'user'` text blocks WITHOUT `synthetic_reason` (injected system_reminder/task_completed rows are `typed`, i.e. intentionally text-free, as are tool_result-only user arrays); assistant turns need non-empty string `content` (tool-only rows — `content` ''/null WITH `tool_calls` — are `typed`); system/reasoning/tool_result/backend_tool_call rows are `typed`; unknown row types `skip`. A recognised HUMAN-turn row whose content this parser cannot decode (user `content` missing / non-string / non-array / an array holding non-block entries; assistant non-string `content` with no `tool_calls`) is `malformed` and counted as SKIPPED, never typed, so a file made only of such rows is never `expectedEmpty` — the ingest drift signal fires (`bytesRead > 0`, sessions 0, `cleanScan=false`, watermark frozen) and `zeroSessionsReason` names the malformed row count, instead of an upstream schema change silently advancing the watermark past whole conversations. `chat_history.jsonl` carries NO per-message timestamps: session times come from the sibling `summary.json` (`created_at`/`last_active_at`; a malformed summary is ignored, an unparseable date is never fabricated) and, because grok writes `summary.json` at session END, an in-progress session or partial rsync falls back to the log file's own mtime — a real filesystem time — with `raw.timestamp_source` stamped `'summary.json'` vs `'file_mtime'` so consumers can tell them apart (without the fallback the render refusal would freeze the `--since-last` watermark for the whole grok root). Every message carries the session bounds (last message = `last_active_at`, the rest = start). Session id: summary → UUID dir name → `stableIdFromPath` (a sha256 prefix of the log path, never the bare `chat_history` basename, which would collapse every such session onto one page). Sidecars (updates.jsonl, events.jsonl, rewind_points.jsonl, summary.json, prompt_history.jsonl) are not sessions — discover.ts's grok-sidecar filter is scoped to PROVEN grok trees and the head sniff rejects claude-family keys (grok detection runs after claude-code; an oversized system head still detects through the truncated-line sniff); a percent-encoded cwd segment that fails to decode yields `cwd` undefined with the session id intact.diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex a54247f703..27771773dd 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/integrations.ts` — recipe install. The resolver-row install fence is keyed by `manifest.recipe` (`gbrain:<recipe>:resolver-rows`), so a second `copy-into-host-repo` recipe never writes a block mislabeled with the first recipe's name. Pinned by `test/integrations-install.test.ts`. Health-check DSL includes the staleness-aware `heartbeat_max_age` type: declares the sense's expected cadence (`max_age: 48h`), and `integrations doctor` FAILS when the newest heartbeat event is older — the only check type that catches a green-but-dead sense (all others are point-in-time). Not embedded-gated (reads only the local heartbeat file). Recipe frontmatter carries `output_paths` (repo-relative dirs the collector writes, e.g. calendar-to-brain → `daily/calendar/`); `getConfiguredCollectorOutputs()` surfaces them for the db_only-collision check/warning. Pinned by `test/integrations-heartbeat-max-age.test.ts`. Standalone integration recipe management (no DB needed). Exports `getRecipeDirs()` (trust-tagged recipe sources), SSRF helpers (`isInternalUrl`, `parseOctet`, `hostnameToOctets`, `isPrivateIpv4`). Only package-bundled recipes are `embedded=true`; `$GBRAIN_RECIPES_DIR` and cwd `./recipes/` are untrusted and cannot run `command`/`http`/string health checks.-- `src/commands/integrity.ts` — `gbrain integrity check|auto|review|extract`: bare-tweet detection, dead-link detection, three-bucket repair (auto-repair / review-queue / skip). `scanIntegrity()` is the shared library function called from `gbrain doctor` (sampled at limit=500) and `cmdCheck` (full scan). Batch-load fast path on Postgres uses a single SQL query (avoids the PgBouncer per-row round-trip timeout), gated by `engine.kind === 'postgres'` at the call site so PGLite never enters batch; fallback `catch` logs at `GBRAIN_DEBUG=1`. Batch projection is `SELECT ... ORDER BY source_id, slug` (NOT `SELECT DISTINCT ON (slug)`, which would collapse same-slug-different-source pages into one scan) so multi-source brains scan each `(source, slug)` row independently. Sequential and auto-repair loops use `listAllPageRefs()` to enumerate `(slug, source_id)` pairs and thread `sourceId` to `getPage`; batch + sequential paths report the same page count on multi-source brains.+- `src/commands/integrity.ts` — `gbrain integrity check|auto|review|extract`: bare-tweet detection, dead-link detection, three-bucket repair (auto-repair / review-queue / skip). `scanIntegrity()` is the shared library function called from `gbrain doctor` (sampled at limit=500) and `cmdCheck` (full scan). Batch-load fast path on Postgres uses a single SQL query (avoids the PgBouncer per-row round-trip timeout), gated by `engine.kind === 'postgres'` at the call site so PGLite never enters batch; fallback `catch` logs at `GBRAIN_DEBUG=1`. Batch projection is `SELECT ... ORDER BY source_id, slug` (NOT `SELECT DISTINCT ON (slug)`, which would collapse same-slug-different-source pages into one scan) so multi-source brains scan each `(source, slug)` row independently. Sequential and auto-repair loops use `listAllPageRefs()` to enumerate `(slug, source_id)` pairs and thread `sourceId` to `getPage`; batch + sequential paths report the same page count on multi-source brains. Help (`--help`/`-h`/`help` after any subcommand) prints usage without running it, and `auto` / `reset-progress` take strict arguments (`src/cli/strict-args.ts`).- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. `jobs-readiness.ts` orchestrates bounded driver-lane and selected-child readiness before worker schema/recovery, handler registration or claims. After `ensureSchema`, `maybeRunWorkerStartupRecovery(queue, process.env, true)` runs for both bare and supervised workers; the final worker `ready` event publishes readiness, and a worker handed an owner status channel (`GBRAIN_WORKER_STATUS_PATH` or `GBRAIN_WORKER_STATUS_TOKEN`, even partially) refuses admission if its status cannot be published, while a legacy supervised worker (`GBRAIN_SUPERVISED=1` from a pre-0.59.1 owner, no channel) publishes nothing and proceeds; typed faults report `configuration_blocked` and exit `WORKER_EXIT_CONFIGURATION`, while transient readiness failures admit no jobs and remain retryable. Help is real and guarded: `JOBS_HELP` (full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) and `JOBS_SUBCOMMAND_HELP` (work/supervisor/submit/watch/prune) print from a guard at the TOP of `runJobs`, BEFORE the thin-client refusal and the `JOBS_SUBCOMMANDS` dispatch — `jobs work --help` can never start a daemon; only `--help`/`-h` are help tokens (bare `help` can be a job name); cli.ts routes it engine-free via `SELF_HELP_WITHOUT_ENGINE` + `CLI_ONLY_SELF_HELP`. `formatJobDetail` prints the effective wall-clock budget (`Timeout:`/`Deadline:` — 1x deadline kill when claimed, 2x wall-clock backstop, or which default applies) with a Date|string-defensive renderer; `timeout_at` is in `JOB_DATE_FIELDS` for thin-client rehydration. `jobs stats` prints a `Backpressure (24h)` line (per-name coalesce counts from the backpressure audit, current+previous ISO-week files, queue-filtered, best-effort) plus a suppressed-by hint naming the in-flight live-lock job when waiting=0 past the shared `GBRAIN_WEDGED_QUEUE_WARN_MINUTES` threshold — the read-only visibility for maxPending single-flight suppression. Pinned by `test/jobs-subcommand-help.test.ts`, `test/jobs-format-detail.test.ts`, `test/jobs-stats-backpressure.serial.test.ts`. `jobs work` (`src/commands/jobs/work.ts`) wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive). `jobs submit` surfaces the `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`, `--max-waiting` (`maxPending` is deliberately internal-only — no flag; see TODOS). `jobs smoke` (`jobs/smoke.ts`) tracks every job it adds to the private `smoke` queue and discards exactly those (cancel if live, then delete) in one `finally` on pass, failure, timeout and throw (`test/jobs-smoke-cleanup.test.ts`); its `--sigkill-rescue`/`--wedge-rescue` cases forge `status='active'` with raw SQL, which the queue protocol trigger currently refuses, so both throw (TODOS.md). `registerBuiltinHandlers` always registers `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at startup with a loud per-plugin line; `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface). The `autopilot-cycle` handler forwards `job.data.phases` to `runCycle`, validated against `ALL_PHASES` from `src/core/cycle.ts` (invalid names filtered; empty/missing falls back to the default cycle); when `source_id` is set it binds `brainDir` to that source's `local_path` (null for a pure-DB source, never the global repo) and checks `isSourceInCooldown` before `runCycle`, returning a no-op `skipped` (not a failure) for a source still in its failure cooldown. The sibling `autopilot-global-maintenance` handler runs `MAINTENANCE_PHASES` (mixed ∪ global) once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` only when no phase failed, no synthesis/pattern child is incomplete, no work was explicitly budget/triage-deferred, and the run was neither aborted nor lock-stolen; benign warning-only runs remain eligible. `resolveJobPull` gives both cycle and standalone sync jobs one positive-polarity `pull` contract while preserving queued payloads that still carry the inverse legacy `noPull` key; explicit `pull` wins. The `sync` handler resolves `sourceId` at entry from `sources.local_path` (mirrors `cycle.ts:480`) so multi-source brains read the per-source `last_commit` anchor; concurrency routes through `autoConcurrency()` in `src/core/sync-concurrency.ts` (PGLite stays serial); `noEmbed` default is `true`. `gbrain jobs supervisor status --json` adds `processing_ready`, lowercase `processing_state` (`starting`/`ready`/`configuration_blocked`, or `unknown`/`stopped` without current state), `reason_code`, `blocked_since` and worker/child identities without changing `running` or crash counters. A live local pidfile keeps this diagnostic engine-free; a missing pidfile retains the DB-lock fallback. It consumes `summarizeCrashes()` from `src/core/minions/handlers/supervisor-audit.ts` for parity with `gbrain doctor`: JSON adds `crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}` + `clean_exits_24h`; human output includes per-cause + clean-exits lines. Pinned by `test/job-pull-policy.test.ts` and 4 source-grep wiring assertions in `test/doctor.test.ts` requiring `crashes_by_cause` + `clean_exits_24h=` in both `doctor.ts` and `jobs.ts`. `gbrain jobs watch` decouples its two output axes: `--json` picks FORMAT (human default, never gated on isTTY), `--follow` picks LOOP (default `isTTY && !json`). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); `--follow` opts into a continuous stream (human plain per tick, or JSONL with `--json`); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pure `resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}` in `src/commands/jobs-watch.ts`; the dispatch wires `--follow`. Pinned by `test/jobs-watch-mode.test.ts` (format×loop matrix incl. the TTY+`--json`-one-shot case) + `test/e2e/non-tty-output.serial.test.ts` (the `cmd </dev/null` non-empty-stdout contract). registers 11 Minion handlers: `reindex`, `repair-jsonb`, `orphans`, `integrity`, `purge`, `synthesize` (PROTECTED), `patterns` (PROTECTED), `consolidate` (PROTECTED), `extract_facts`, `resolve_symbol_edges`, `recompute_emotional_weight`. Phase wrappers delegate to `runCycle({phases:[name]})` so `src/core/cycle.ts` stays the single source of truth for phase semantics. The standalone `sync` handler passes `noExtract: true` to match `runPhaseSync`'s contract (doctor's remediation plan emitting `[sync, extract]` would otherwise double-extract). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress. `parseJobIsolationFlag(args, env?)` (`--job-isolation`, space/= forms, `GBRAIN_JOB_ISOLATION` fallback, default inline); `jobs work` resolves the actual selected child and validates its bounded protocol/capability handshake and warns when `--max-rss` is combined with isolation (watchdog covers the worker only); `jobs run-child` is the INTERNAL child entrypoint (quiet registerBuiltinHandlers incl. plugin discovery, CLI owns disconnect+exit); startup warning when a Supabase-shaped engine runs single-pool (kill-switch collapse made loud); the `db_dead` fatal text is verdict-aware (pool starved vs server unreachable). Generic `jobs submit` normalizes the job name once before trust, queueing, handler lookup, and audit; after the admission check and dry-run return, its explicit `ensureSchema()` preflight still runs before shell/handler validation so stale brains retain the canonical init/migration error precedence. On PGLite, `jobs submit embed-backfill` refuses with `no_worker_surface` and a paste-ready inline embed command before any queue access; `--dry-run` evaluates the same read-only feasibility gate and never says “Would submit” for an impossible job. `--follow` is the sole CLI exception because it starts and awaits the inline worker; padded names follow the same normalized path and cannot strand a row. The MCP `submit_job` operation applies the same gate (including dry-run), translates the expected refusal to branchable `OperationError('no_worker_surface')`, and never emits `internal_error` for this capability miss. The `sync` handler forwards `job.data.github_item` ({repo, number, kind}) into `performSync` for github-kind single-item webhook refreshes. `jobs work` registers the shell handler always; the startup line names the flag first (`--allow-shell-jobs` / `GBRAIN_ALLOW_SHELL_JOBS=1`); `jobs start` computes `allowShellJobs` as `--allow-shell-jobs || GBRAIN_ALLOW_SHELL_JOBS === '1'` — the same literal `handlers/shell.ts` and `buildChildArgs` check. `extract-atoms-drain` accepts a trusted `retryRequestId` in submitted params; a new job ID distinguishes a newly approved malformed-output provider attempt from provider-free publication replay. PGLite `jobs --follow` still requires exclusive owner access. D2: `jobs supervisor start --detach` writes its payload (`event`, `status:'started'`, `supervisor_pid`, `pid_file`, `detached`, `stderr_log`) through `writeStdoutFinal`; the `jobs` record declares no `json` because work/watch/foreground supervisor stream. Start refusals add an envelope under `--json` (`invalid_params` exit 2 for an unknown subcommand or bad `--health-interval`, `config_error` for PGLite). `jobs submit enrich|subagent` runs the paid consent gate and stores an `authorized` spend record on the row; `jobs get --json` adds `spend_basis`, `spend_why` and `spend_group`; `jobs list --group <id>` and `jobs cancel --group <id>` act on one spend group.Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). `runJobs` resolves help and the thin-client refusal, builds the queue, then dispatches through `JOBS_SUBCOMMANDS` (Object.hasOwn lookup, same unknown-subcommand error) to one module per subcommand in `src/commands/jobs/<sub>.ts` (`runJobs<Sub>(ctx)`; parsers, formatters and `JobsCommandContext` in `jobs/shared.ts`; `maybeRunWorkerStartupRecovery` in `jobs/work.ts`), all re-exported from `jobs.ts`. Subcommands that register handlers import `registerBuiltinHandlers` lazily from `jobs.ts`. `registerBuiltinHandlers` is the ordered registration table (worker.register vs gateway-refreshing registerBuiltinJob stay here); handler bodies live in `src/core/minions/handlers/` (see core-minions-1). Registration names and order are pinned by `test/jobs-handler-registry-golden.test.ts`, which also drives the supervisor's `deriveHandlerNames` probe.@@ -36,7 +36,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/orphans.ts` — `gbrain orphans` and MCP `find_orphans` share islanded (no live inbound or outbound links) and legacy inbound-only modes. Read policy scopes candidates and excludes private candidates, endpoints and independent origin pages before counting. Cross-source public links still establish reachability by the documented orphan definition. Reporting exclusions (`shouldExcludeFromOrphanReporting`) stay centralized; the scoped live-page denominator excludes the same private/reporting rows. `--source` remains explicit; no new remote privacy parameter. Connector renders (an `email`/`meeting` page whose source `config.kind` is a connector kind) are islanded by construction, so they leave both totals and are reported as `connector_renders_excluded` (`--include-pseudo` keeps them); doctor `orphan_ratio` carries that count in `details` and prints `gbrain extract links --by-mention --source db` (plus `--source-id` when scoped). Pinned by `test/orphan-ratio-connector-renders.test.ts`.-- `src/commands/pages.ts` — `gbrain pages purge-deleted [--older-than HOURS|Nd] [--dry-run] [--json]` operator escape hatch. Mirror of `gbrain sources purge` for the page-level lifecycle. Hard-deletes pages whose `deleted_at` is older than the cutoff; cascades to content_chunks/page_links/chunk_relations. Its help points soft-delete and restore at `gbrain delete|restore <slug> --force` (page writes are revisioned).+- `src/commands/pages.ts` — `gbrain pages purge-deleted [--older-than HOURS|Nh|Nd] [--dry-run] [--json] [--yes]` operator escape hatch. Mirror of `gbrain sources purge` for the page-level lifecycle. Hard-deletes pages whose `deleted_at` is older than the cutoff in every source (per-source purge is not supported); cascades to content_chunks/page_links/chunk_relations. `parsePurgeArgs` is strict (the `pages purge-deleted` row of `src/cli/strict-args.ts`): `--older-than N` and `--older-than=N` both work, and any other token throws `invalid_params` before the engine is touched. The real purge first previews the count and, when anything would be purged, goes through `consentGate` (destructive): a TTY prompt, `--yes`, or exit 3 with the consent payload whose fix is the exact `--yes` argv and whose preview is `--dry-run --json`. The autopilot purge phase calls `purgeDeletedPagesCoordinated` directly and never asks. Exports `SUBCOMMANDS` and `printUsage` for the help route. Pinned by `test/pages-purge-deleted-args.test.ts` and the `pages purge-deleted` consent-table row. Its help points soft-delete and restore at `gbrain delete|restore <slug> --force` (page writes are revisioned).- `src/commands/persistence-admin.ts` + `src/core/persistence/{admin-contract,administration}.ts` — trusted local `sources writer status|claim|transfer` and `auth local-writer list|register|revoke`. Parse and resolve the brain before opening PGLite; an existing owner receives a separate private administration envelope verified against the current CLI registration. These names never enter the public MCP operation registry; stdio, hook credentials, forged trust fields and revoked CLI registrations cannot administer. Transfer requires exact manifest and owner epoch; status `--probe` acquires/releases a real native lock. Explicit credential replacement commits old revocation and new registration together before atomically publishing the private file, preserving old credentials for recovery without keeping their authority. No credential/hash appears in output. `test/persistence-administration.test.ts` covers database rollback, parallel rotations, transfer conflicts, real sockets and real CLI subprocesses. `retry-effects <source> --request-id <original-uuid> --dry-run --json` previews a failed embedding effect without work; applying the same reviewed request requires original/current authority, selected-brain config, source/page/owner CAS and one additional allowance. For a request with parked Git or withdrawal effects the same command previews the parked targets (`--dry-run`) or authorizes one more attempt per parked target, reporting each effect's state and whether it is terminal. It never claims ownership or rewrites canonical receipts.diff --git a/docs/architecture/key-files/entrypoints-and-docs.md b/docs/architecture/key-files/entrypoints-and-docs.mdindex 61a04a7a50..7520b7c6a9 100644--- a/docs/architecture/key-files/entrypoints-and-docs.md+++ b/docs/architecture/key-files/entrypoints-and-docs.md@@ -121,6 +121,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGELSize ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers `handleCliOnly`'s explicit ordered pipeline (`@cliPipelineStage` functions: thin-client guard, deferred-persistence routing, subcommand and help routes, read-only timeout path, sync watchdog and delegation, connectEngine terminator with degraded-serve recovery, teardown), thin-client routing and refusal, help and self-help text, strict flag parsing and process-exit teardown. Per-command dispatch (pre- and post-connect) lives in the command table (entry below), not in `src/cli.ts`.- `src/cli/remember-format.ts` — the `remember` human formatter (`formatRememberResult`: status, entity with `(inferred from mention)`, expiry, degraded dedup, `warnings` + `hint`), kept out of `src/cli.ts`; `--json` prints the raw envelope. Pinned by `test/remember-entity-inference.test.ts`.+- `src/cli/subcommands.ts` + `src/cli/router-help.ts` + `src/cli/strict-args.ts` — help never acts (#6114). `subcommands.ts` holds each router command's inventory (`ROUTERS`: pages, cache, integrity, hook, search, edge-proposals, schema, config; each router re-exports its list as `SUBCOMMANDS` and types its dispatch over it, so an unlisted subcommand fails typecheck) and the help grammar: `--help`/`-h` anywhere before `--` (a flag-value slot included) and a bare `help` only as the first token after a router command or one of its subcommands (`search help` stays a query). `cli.ts` decides `cliHelpRequested` once, before the update marker, backup nag and key warnings; on help it calls `printRouterHelp`, which loads only the router's `printUsage`, before any subcommand, thin-client route or engine. `strict-args.ts` is the per-subcommand table for destructive subcommands (pages purge-deleted, cache clear/prune, schema use/downgrade/init/remove-*, integrity auto/reset-progress, search modes --reset): an argument the handler would ignore refuses with `invalid_params` (exit 2) after help and before dispatch, with a read-only fix that itself parses under the table (`ask_user` for integrity reset-progress). The flag-registry generator skips `strict-args.ts` (its literals belong to the commands it lists). Pinned by `test/cli-help-grammar.test.ts` and the four-part subprocess gate `test/cli-help-no-side-effects*.serial.test.ts` (harness `test/helpers/cli-help-gate.ts`, child probe `test/helpers/cli-side-effect-probe.ts`): every self-help command's `--help`/`-h` and every router subcommand's `--help`/`-h`/`help` on a copy of a seeded PGLite brain, asserting exit 0 with usage, unchanged table rows and HOME/cwd files, and no fetch or spawn.- `src/cli/command-table.ts` + `src/cli/commands/<name>.ts` — one record per CLI-only command (`name`, `phase`, `thinClient`, `selfHelp`, `skipStartupHooks`, `load: () => import('<literal>')`, and the agent-contract fields `json`, `read_only`, `startup`, `end_of_options`, `help: () => import('./help/<name>.ts')` — see `src/cli/help/` in [agent contract](agent-contract.md)). A `selfHelp` record whose handler needs an engine answers `--help` brainless through `SELF_HELP_WITHOUT_ENGINE` in `src/cli.ts` (an explicit loader, or `true` to run the record's own module with a null engine). The records derive `CLI_ONLY`, `CLI_ONLY_SELF_HELP`, `THIN_CLIENT_REFUSED_COMMANDS` and `STARTUP_HOOK_SKIP_COMMANDS` (re-exported from `src/cli.ts`); `cliAliases`' collision check runs over the derived `CLI_ONLY`. Each module holds the body its switch case or plain branch had, moved verbatim, and receives dispatcher-owned pieces through `CliDispatchContext`. Master's membership inconsistencies are preserved (the dead second `auth` branch, the unreachable `capture --help` branch, the `connectors` and `recall` refuse hints that only `connectEngine`'s thin-client backstop reaches (the static extractor reports them as never reached), `watch` refused without a hint, `eval whoknows` shadowed by the refusal) and pinned by `test/fixtures/goldens/cli/membership-sets.json`. Contract: `test/cli-command-table.test.ts`; engine lifecycle per path: `test/cli-dispatch-lifecycle.serial.test.ts`. `json` / `jsonSubcommands` declare the D2 `--json` contract (record-wide / per subcommand).- `scripts/lib/cli-pipeline.ts` — flattens `handleCliOnly` (inlining `@cliPipelineStage` functions) and reads the command table by AST, for the W0 dispatch-shape extractor (`test/helpers/cli-dispatch-extract.ts`) and `scripts/generate-flag-registry.ts`.diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex 6e2940700f..da8def9a43 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -120,5 +120,5 @@ rejection of serve-only flags before a brain opens.- `src/core/link-validity.ts` + `src/core/link-relationships.ts` + `src/core/link-temporal-evidence.ts` + `src/core/link-temporal-apply.ts` + `src/core/ops/edge-temporal.ts` — temporal typed edges ([guide](../../guides/temporal-edges.md)). Relation semantics (state / event / reference), `buildRelationshipState` (order-invariant stints from `links` assertions with `assertion_tense` plus dated `link_transitions`; dated beats undated, same-page present beats past), `closeContradiction` (pure date arithmetic, relationship-specific starts only), and `relationshipFilterSql` / `annotateTemporalRow` / `edgeMatchesTemporal` (one liveness rule: a relationship with no `link_relationships` row reads live). `refreshRelationships` recomputes per-scope state (`all`, `world` ignores private-origin evidence) inside the writer's transaction; `replaceDerivedLinks` calls `applyTemporalEvidence`, and the engine link writers refresh touched temporal keys; the extract phase sweeps lagging or orphaned state. Graph ops read live relationships by default; default reads keep the established row shape, history reads (`status`, `as_of`, `during`) return `status`/`stints`/`recorded_at`/`retired_at`; hidden rows emit `former_relationships_hidden` + `gbrain.temporal` meta. `graph.edge_validity off` is a read policy only. `src/core/link-semantics-pack.ts` installs pack-declared `link_types[].temporal` semantics (union of the active and per-source packs, `state` wins) over the built-in table; `replaceDerivedLinks`, `add_link`/`remove_link` and the extract sweep prime it before deriving or refreshing state (lint rule `link_types_temporal`; `test/link-semantics-pack.test.ts`). `src/core/link-relationship-notes.ts` renders the shared relationship note (`now: … ; ended: … ; summary may be stale`) with one batched read for entity cards, `context_pack`, ambient turn-context synopses and compiled context entries. Pinned by `test/link-validity.test.ts`, `test/link-temporal-evidence.test.ts`, `test/link-relationships.test.ts` (+ Postgres twin), `test/link-temporal-put-page.test.ts`, `test/link-temporal-reads.test.ts`.-- `src/core/cycle/edge-contradictions.ts` + `src/commands/edge-proposals.ts` — the `edge_contradictions` dream phase and `gbrain edge-proposals`. Candidates are subjects with ≥2 live same-type state relationships whose pair evidence hash has no proposal; one judge call per subject returns only conflict flags; `closeContradiction` picks the ending relationship and date (undated → `undated_unresolved`). Modes propose (default) / apply (certified models in `CERTIFIED_APPLY_MODELS`) / off; applying appends a `gbrain-dream (inferred)` "Ended <type> [[target]]" timeline line through the coordinated `add_timeline_entry` path and re-derives the page; a hand-deleted line becomes `reverted_by_user`. Budget through the cycle `BudgetMeter`. Pinned by `test/cycle-edge-contradictions.test.ts` and the managed phase matrix.+- `src/core/cycle/edge-contradictions.ts` + `src/commands/edge-proposals.ts` — the `edge_contradictions` dream phase and `gbrain edge-proposals`. Candidates are subjects with ≥2 live same-type state relationships whose pair evidence hash has no proposal; one judge call per subject returns only conflict flags; `closeContradiction` picks the ending relationship and date (undated → `undated_unresolved`). Modes propose (default) / apply (certified models in `CERTIFIED_APPLY_MODELS`) / off; applying appends a `gbrain-dream (inferred)` "Ended <type> [[target]]" timeline line through the coordinated `add_timeline_entry` path and re-derives the page; a hand-deleted line becomes `reverted_by_user`. Budget through the cycle `BudgetMeter`. Pinned by `test/cycle-edge-contradictions.test.ts` and the managed phase matrix. `edge-proposals <sub> --help` prints usage before any engine read (router help, `src/cli/subcommands.ts`).- `src/core/link-single-value.ts` — declared single-value relations ([guide](../../guides/temporal-edges.md#declared-single-value-relations)). A pack's `cardinality: one_per_from` on a state relation, built in or declared `temporal: state` (manifest-v1 `LinkTypeSchema`; lint rule `link_types_cardinality` rejects it elsewhere) makes `edge_contradictions` close that type's competing live relationships without a model: `planSingleValueClosures` orders members by latest dated start and applies `closeContradiction` to each consecutive pair (undated and same-date members stay open as proposals). `declaredSingleValueTypes` reads the source's resolved pack; `previewSingleValue` backs the read-only `gbrain schema cardinality-preview`. `dream.single_value.mode` propose (default) / apply / off. Pinned by `test/link-single-value.test.ts`.diff --git a/docs/architecture/key-files/schema-mutation.md b/docs/architecture/key-files/schema-mutation.mdindex 13ad9a5bd5..13fd8a28cf 100644--- a/docs/architecture/key-files/schema-mutation.md+++ b/docs/architecture/key-files/schema-mutation.md@@ -27,7 +27,7 @@ Key files:- `src/core/schema-pack/stats.ts` — `runStatsCore(engine, opts)` returns per-source + aggregate page counts + coverage % + `dead_prefixes` (declared prefixes with zero matching pages — agent drilldown signal). Multi-source aware (`sourceIds[]` federated, `sourceId` single, or whole-brain). PGLite + Postgres parity via `executeRaw`. `undeclared_pages` counts pages whose non-empty type the active pack neither declares nor aliases; `coverage` is the share of pages matching the pack (untyped and undeclared both count against it). Empty brain → coverage:1.0 (vacuous truth).- `src/core/schema-pack/review.ts` — `schema review-candidates` / `review-orphans`. `findTypeOrphans(engine, manifest, scope, limit)` (shared by the CLI and the `schema_review_orphans` MCP op) returns pages with no active-pack type match (untyped or undeclared, each with `type` + `reason`), the true `orphan_count`, `undeclared_types` counts and `truncated`; a query failure throws instead of reading as zero orphans.- `src/core/schema-pack/sync.ts` — `runSyncCore(engine, opts)` chunked UPDATE in 1000-row batches per declared prefix. Concurrent writers never block on a single row >100ms. Write-side scoping via `ctx.sourceId` directly (NOT `sourceScopeOpts`, which inherits OAuth read federation). Idempotent on `--apply` re-run.-- `src/commands/schema.ts` — schema CLI dispatch, including `lint [<pack>] [--with-db] [--json]`. Lint parses `--with-db` as a boolean rather than a pack name, accepts it before or after the optional pack, and rejects unknown flags, boolean values, and multiple pack positionals. The DB-backed lane resolves the active pack and runs DB-plane rules on the same connection; plain lint does not run those rules. `test/schema-cli-lint-with-db.test.ts` drives real isolated CLI subprocesses for implicit/explicit packs, JSON output, missing packs, global source flags, invalid arguments, and plain-lint separation. `withConnectedEngine` routes `loadConfig()` through the canonical `toEngineConfig()` helper and passes the complete result (`database_url` and `database_path`) to factory construction and connect, so PGLite schema commands open the configured brain. Lifecycle-grouped help text (Inspection / Activation / Authoring / Discovery+repair). Pinned by `test/schema-cli-database-path.serial.test.ts`.+- `src/commands/schema.ts` — schema CLI dispatch, including `lint [<pack>] [--with-db] [--json]`. Lint parses `--with-db` as a boolean rather than a pack name, accepts it before or after the optional pack, and rejects unknown flags, boolean values, and multiple pack positionals. The DB-backed lane resolves the active pack and runs DB-plane rules on the same connection; plain lint does not run those rules. `test/schema-cli-lint-with-db.test.ts` drives real isolated CLI subprocesses for implicit/explicit packs, JSON output, missing packs, global source flags, invalid arguments, and plain-lint separation. `withConnectedEngine` routes `loadConfig()` through the canonical `toEngineConfig()` helper and passes the complete result (`database_url` and `database_path`) to factory construction and connect, so PGLite schema commands open the configured brain. Lifecycle-grouped help text (Inspection / Activation / Authoring / Discovery+repair). Pinned by `test/schema-cli-database-path.serial.test.ts`. Help after any subcommand prints usage without running it, and `use`, `downgrade`, `init` and `remove-*` refuse arguments they would ignore (`src/cli/strict-args.ts`).- `skills/schema-author/SKILL.md` — Agent dispatcher for "evolve the schema pack." Triggers: 15+ phrasings incl. "add a page type", "my brain has untyped pages", "propose new types from my corpus", "backfill page types". Explicit Non-goals callout to `brain-taxonomist` (files one page) and `eiirp` (schema-check during iteration) so agents pick the right surface. 7-phase workflow: brain → assess → propose → apply → sync → verify → commit. Lists every gbrain schema CLI verb + every MCP op the skill uses. `brain_first: exempt` frontmatter. Required conformance sections: Contract, Anti-Patterns, Output Format.- `skills/conventions/schema-evolution.md` — Canonical convention: "when to add a type vs alias vs prefix." Decision tree: <20 pages → don't pack-codify; 20-100 → alias or narrow prefix on existing type; 100+ → first-class type. Don'ts section + "when to remove a type" + "when to commit the pack" all answered in one place.diff --git a/plugin-variants/gbrain-coding/skills/data-loss-gate/SKILL.md b/plugin-variants/gbrain-coding/skills/data-loss-gate/SKILL.mdindex 9c92f22a1a..4749174afc 100644--- a/plugin-variants/gbrain-coding/skills/data-loss-gate/SKILL.md+++ b/plugin-variants/gbrain-coding/skills/data-loss-gate/SKILL.md@@ -77,8 +77,11 @@ Brain / database level (gbrain-specific):sweeps `delete_page` across a set of slugs. Deletes are soft (recoverable via`gbrain restore <slug>`) until purged — say so on the card, then gate anyway:a sweep that's wrong in bulk is expensive to un-wrong in bulk.-- **`gbrain purge-deleted`** — permanently removes soft-deleted pages. This is- the point of no return for the soft-delete safety net.+- **`gbrain pages purge-deleted`** — permanently removes soft-deleted pages+ from every source of the brain. This is the point of no return for the+ soft-delete safety net. Show the user `gbrain pages purge-deleted --dry-run --json`+ first; the command itself asks (exit 3 without a terminal) and runs with+ `--yes` only after the user agrees.- **Source removal** — `gbrain sources remove <id>` deletes the source ANDevery page in it. The `--confirm-destructive` flag does not substitute forthe card.@@ -181,7 +184,7 @@ still wrong because:Follow the [agent operator protocol](../../docs/protocol/AGENT_OPERATOR_v1.md) for any gbrain error `code`, exit code, `[AGENT]` block or notice block. Specific to this skill:- A destructive command exits 3 (`confirmation_required`) or asks for `--confirm-destructive`: that flag confirms the agent is sure, not the user. Show the recoverability card and wait for the user's explicit yes.-- `gbrain purge-deleted` removes soft-deleted pages for good, so `gbrain restore` cannot bring them back afterwards: say so on the card. Never promise physical erasure or a recovery you cannot verify.+- `gbrain pages purge-deleted` removes soft-deleted pages for good, so `gbrain restore` cannot bring them back afterwards: say so on the card. Never promise physical erasure or a recovery you cannot verify.- A delete or forget returns `write_pending` (exit 10): poll the receipt before writing the deletion log entry.## Anti-Patternsdiff --git a/plugin/skills/data-loss-gate/SKILL.md b/plugin/skills/data-loss-gate/SKILL.mdindex 9c92f22a1a..4749174afc 100644--- a/plugin/skills/data-loss-gate/SKILL.md+++ b/plugin/skills/data-loss-gate/SKILL.md@@ -77,8 +77,11 @@ Brain / database level (gbrain-specific):sweeps `delete_page` across a set of slugs. Deletes are soft (recoverable via`gbrain restore <slug>`) until purged — say so on the card, then gate anyway:a sweep that's wrong in bulk is expensive to un-wrong in bulk.-- **`gbrain purge-deleted`** — permanently removes soft-deleted pages. This is- the point of no return for the soft-delete safety net.+- **`gbrain pages purge-deleted`** — permanently removes soft-deleted pages+ from every source of the brain. This is the point of no return for the+ soft-delete safety net. Show the user `gbrain pages purge-deleted --dry-run --json`+ first; the command itself asks (exit 3 without a terminal) and runs with+ `--yes` only after the user agrees.- **Source removal** — `gbrain sources remove <id>` deletes the source ANDevery page in it. The `--confirm-destructive` flag does not substitute forthe card.@@ -181,7 +184,7 @@ still wrong because:Follow the [agent operator protocol](../../docs/protocol/AGENT_OPERATOR_v1.md) for any gbrain error `code`, exit code, `[AGENT]` block or notice block. Specific to this skill:- A destructive command exits 3 (`confirmation_required`) or asks for `--confirm-destructive`: that flag confirms the agent is sure, not the user. Show the recoverability card and wait for the user's explicit yes.-- `gbrain purge-deleted` removes soft-deleted pages for good, so `gbrain restore` cannot bring them back afterwards: say so on the card. Never promise physical erasure or a recovery you cannot verify.+- `gbrain pages purge-deleted` removes soft-deleted pages for good, so `gbrain restore` cannot bring them back afterwards: say so on the card. Never promise physical erasure or a recovery you cannot verify.- A delete or forget returns `write_pending` (exit 10): poll the receipt before writing the deletion log entry.## Anti-Patternsdiff --git a/scripts/generate-flag-registry.ts b/scripts/generate-flag-registry.tsindex 4557766039..c99fefd886 100644--- a/scripts/generate-flag-registry.ts+++ b/scripts/generate-flag-registry.ts@@ -77,9 +77,12 @@ const DELEGATED_MODULES: Record<string, string[]> = {* builds the INTERNAL `jobs run-child` argv (`--job-id`, `--allow-shell-jobs`):* those literals are what a worker passes to its child, not flags an importer* parses — autopilot imports it only to resolve the child CLI, and `jobs`- * declares both flags in its own source.+ * declares both flags in its own source. strict-args.ts is the strict-argument+ * table for several commands' destructive subcommands (#6114): its literals+ * belong to pages, cache, schema, integrity and search, each of which reads+ * its own flags in its own source.*/-const EXCLUDED_MODULES = ['thin-client-routing.ts', 'persistence-delegate.ts', 'job-isolation.ts'];+const EXCLUDED_MODULES = ['thin-client-routing.ts', 'persistence-delegate.ts', 'job-isolation.ts', 'strict-args.ts'];function isExcludedModule(p: string): boolean {// Basename comparison is path-separator agnostic: on Windows p ends indiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 86d6d9188e..a5a48b1462 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -34,7 +34,7 @@ src/commands/sources.ts 2042 ratchet +5 #5988: sources status/retry-held help rosrc/core/link-extraction.ts 2204 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_atsrc/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budgetsrc/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh-src/commands/hook.ts 1916 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; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts)+src/commands/hook.ts 1918 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; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +2 #6114: router help (printUsage + SUBCOMMANDS re-export of the HOOK_EVENTS inventory from cli/subcommands.ts)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 1896 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +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); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYSsrc/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 envdiff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 10d5f5691b..c372fb7b52 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -290,7 +290,7 @@ test/scripts/nightly-issue.test.ts nightly-watch incidents 9 readFileSynctest/scripts/nightly-issue.test.ts nightly-watch routing and guard 9 readFileSynctest/scripts/nightly-issue.test.ts operator messages carry docs anchors that resolve 1 readFileSynctest/scripts/postgres-lane-coverage.test.ts check-postgres-lane-coverage.ts 9 readFileSync-test/scripts/regen-all.test.ts regen:all 4 readFileSync+test/scripts/regen-all.test.ts regen:all 5 readFileSynctest/scripts/run-verify-parallel.test.ts guard registration ⇒ execution coverage 1 readFileSynctest/scripts/run-verify-parallel.test.ts run-verify-parallel.sh — no-timeout-binary fallback rc capture (regression) 7 readFileSynctest/scripts/serial-files.test.ts scripts/serial-files.tsv (serial lane manifest) 5 readFileSyncdiff --git a/skills/data-loss-gate/SKILL.md b/skills/data-loss-gate/SKILL.mdindex b22a34b328..ce2045abb3 100644--- a/skills/data-loss-gate/SKILL.md+++ b/skills/data-loss-gate/SKILL.md@@ -76,8 +76,11 @@ Brain / database level (gbrain-specific):sweeps `delete_page` across a set of slugs. Deletes are soft (recoverable via`gbrain restore <slug>`) until purged — say so on the card, then gate anyway:a sweep that's wrong in bulk is expensive to un-wrong in bulk.-- **`gbrain purge-deleted`** — permanently removes soft-deleted pages. This is- the point of no return for the soft-delete safety net.+- **`gbrain pages purge-deleted`** — permanently removes soft-deleted pages+ from every source of the brain. This is the point of no return for the+ soft-delete safety net. Show the user `gbrain pages purge-deleted --dry-run --json`+ first; the command itself asks (exit 3 without a terminal) and runs with+ `--yes` only after the user agrees.- **Source removal** — `gbrain sources remove <id>` deletes the source ANDevery page in it. The `--confirm-destructive` flag does not substitute forthe card.@@ -180,7 +183,7 @@ still wrong because:Follow the [agent operator protocol](../../docs/protocol/AGENT_OPERATOR_v1.md) for any gbrain error `code`, exit code, `[AGENT]` block or notice block. Specific to this skill:- A destructive command exits 3 (`confirmation_required`) or asks for `--confirm-destructive`: that flag confirms the agent is sure, not the user. Show the recoverability card and wait for the user's explicit yes.-- `gbrain purge-deleted` removes soft-deleted pages for good, so `gbrain restore` cannot bring them back afterwards: say so on the card. Never promise physical erasure or a recovery you cannot verify.+- `gbrain pages purge-deleted` removes soft-deleted pages for good, so `gbrain restore` cannot bring them back afterwards: say so on the card. Never promise physical erasure or a recovery you cannot verify.- A delete or forget returns `write_pending` (exit 10): poll the receipt before writing the deletion log entry.## Anti-Patternsdiff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex cf0ad15f68..835ad1940d 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -70,7 +70,7 @@"daily-task-manager/SKILL.md": "cbec93c0d90829a9c3772722d69056616d3eddf13db6216f21f5b43c57282f40","daily-task-manager/routing-eval.jsonl": "e98b2592e65c26952242436a960d8b2061e375b269004a18c230cbcf1d692ff9","daily-task-prep/SKILL.md": "37758d345cfec37e7d8cf36dd876e8292110e3b85cef93e3dcf4c566014b5a9d",- "data-loss-gate/SKILL.md": "790407f6a91dba74d6ca1f482bb2eaa28977e79a5cf9a8e642f71691cab69652",+ "data-loss-gate/SKILL.md": "6422deaee9a5656f1c9eba1c8c80c7b6fa0e8b93d9d495ff2af6c54d7e9af626","data-loss-gate/routing-eval.jsonl": "825358a5600641061a02b25097cd84c1c28bb0359a7608a10b9f25f661bd88f9","data-research/SKILL.md": "2b1d7a70772ff8c202604867ed02e08cff473b2da808974f3f0a18b78b112116","db-repair/SKILL.md": "0ff994ad468234c9020e8005ec2d8f40c27382ab00fb6f4ea1482cec76f507e5",diff --git a/src/cli.ts b/src/cli.tsindex 4e762bf167..6a699b0f64 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -55,6 +55,9 @@ import { callRemoteTool, RemoteMcpError, unpackToolResult, extractResponseMeta }import { assertSingleSourceScopeFlag, checkHostHonoredParams, hintAmbientNarrowing, type AmbientSourceBinding } from './cli/source-scope.ts';import { maybePromptForUpgrade } from './core/thin-client-upgrade-prompt.ts';import { CLI_FLAG_REGISTRY } from './core/cli-flag-registry.generated.ts';+import { cliHelpRequested } from './cli/subcommands.ts';+import { printRouterHelp } from './cli/router-help.ts';+import { strictArgsRefusal } from './cli/strict-args.ts';import { migrationCliArgumentError } from './core/embedding-migration-cli.ts';import { VERSION } from './version.ts';import { exitOnUnsupportedBun } from './core/runtime-version.ts';@@ -331,6 +334,9 @@ async function main() {return;}+ // #6114: decided once, before startup side effects; help never runs the command (grammar: cli/subcommands.ts).+ const helpRequested = cliHelpRequested(command, args.slice(1));+if (command === 'extract' && !args.some(arg => arg === '--help' || arg === '-h')&& args.some(arg => ['--repair-attendance', '--apply-preview', '--backup-verified', '--confirm', '--checkpoint'].includes(arg.split('=')[0]))) {const { runAttendanceRepairCli } = await import('./commands/extract-attendance-repair.ts');@@ -341,16 +347,16 @@ async function main() {// v0.42 self-upgrade: ride this invocation as an update heartbeat. Cache-read-// only, fail-open, never blocks. Skips the update path's own commands + sets// GBRAIN_SKIP_STARTUP_HOOKS for their children. Runs for every real command.- maybeEmitUpdateMarker(command);+ if (!helpRequested) {+ maybeEmitUpdateMarker(command);- // Monthly backup-coverage nag (cache-read-only, bounded by the nag gate;- // guards + skip set live inside the helper — one place, every call site).- {+ // Monthly backup-coverage nag (cache-read-only, bounded by the nag gate;+ // guards + skip set live inside the helper — one place, every call site).const { maybeEmitBackupNag } = await import('./core/backup/status-file.ts');maybeEmitBackupNag(command, { quiet: getCliOptions().quiet === true });+ // #5137: once per process, when an env key shadows a different config key; never from hook commands.+ if (command !== 'hook') (await import('./core/ai/key-warnings.ts')).warnShadowedProviderKeys();}- // #5137: once per process, when an env key shadows a different config key; never from hook commands.- if (command !== 'hook') (await import('./core/ai/key-warnings.ts')).warnShadowedProviderKeys();const subArgs = args.slice(1);@@ -371,6 +377,36 @@ async function main() {markShortLivedCliProcess();}+ // Per-command --help; the scan stops at `--` (`agent run -- --help` submits the prompt). Router+ // commands print usage here, so `<cmd> <sub> --help` never reaches the subcommand (#6114).+ if (helpRequested) {+ if (await printRouterHelp(command, subArgs)) return;+ if (await printCuratedHelp(command, subArgs)) return;+ // `eval brainbench` ships a published foreign-runner flag surface — its+ // own usage() must win over the generic eval stub (codex P3). Fall+ // through to handleCliOnly's no-DB brainbench route, which prints it.+ const selfHelpSub = command === 'eval' && subArgs[0] === 'brainbench';+ const op = cliOps.get(command) ?? cliAliases.get(command);+ if (op && !selfHelpSub) {+ printOpHelp(op, command);+ return;+ }+ if (!selfHelpSub && CLI_ONLY.has(command) && !CLI_ONLY_SELF_HELP.has(command)) {+ printCliOnlyHelp(command);+ return;+ }+ // Self-help members whose handler answers --help before it touches the+ // engine. Without this they fall through to the normal dispatch, which+ // connects first — so `gbrain models --help` on a machine with no brain+ // exits 1 with "No brain configured", and the handler's own help block is+ // unreachable. That is the state a reader is most likely to be in.+ if (await printSelfHelpWithoutEngine(command, subArgs)) return;+ }++ // #6114: destructive subcommands refuse a token they would ignore (exit 2) before dispatch.+ const strictRefusal = helpRequested ? null : strictArgsRefusal(command, subArgs);+ if (strictRefusal) exitCliError(strictRefusal, command);+// T5 — `gbrain search modes|stats|tune` is the read-only config dashboard,// NOT a free-text search for the literal word "modes". Free-text// `gbrain search "<query>"` falls through to the cheap-hybrid `search` op@@ -416,35 +452,6 @@ async function main() {return;}- // Per-command --help. For `agent`, the scan STOPS at the `--` terminator:- // everything after it is literal prompt text, so `agent run -- --help`- // must submit the prompt, never print help (cathedral-6 eng review).- const helpScanArgs = command === 'agent' && subArgs.includes('--')- ? subArgs.slice(0, subArgs.indexOf('--'))- : subArgs;- if (hasHelpFlag(helpScanArgs)) {- if (await printCuratedHelp(command, subArgs)) return;- // `eval brainbench` ships a published foreign-runner flag surface — its- // own usage() must win over the generic eval stub (codex P3). Fall- // through to handleCliOnly's no-DB brainbench route, which prints it.- const selfHelpSub = command === 'eval' && subArgs[0] === 'brainbench';- const op = cliOps.get(command) ?? cliAliases.get(command);- if (op && !selfHelpSub) {- printOpHelp(op, command);- return;- }- if (!selfHelpSub && CLI_ONLY.has(command) && !CLI_ONLY_SELF_HELP.has(command)) {- printCliOnlyHelp(command);- return;- }- // Self-help members whose handler answers --help before it touches the- // engine. Without this they fall through to the normal dispatch, which- // connects first — so `gbrain models --help` on a machine with no brain- // exits 1 with "No brain configured", and the handler's own help block is- // unreachable. That is the state a reader is most likely to be in.- if (await printSelfHelpWithoutEngine(command, subArgs)) return;- }-if (command === 'sources' && subArgs[0] === 'inspect') {const { runCompanyBrainInspection } = await import('./commands/company-brain-inspect.ts');await runCompanyBrainInspection(subArgs.slice(1));diff --git a/src/cli/router-help.ts b/src/cli/router-help.tsnew file mode 100644index 0000000000..fd97c87041--- /dev/null+++ b/src/cli/router-help.ts@@ -0,0 +1,37 @@+/**+ * Usage for router commands when help is requested (#6114). cli.ts calls+ * this before dispatch, so a help request reaches only the router's+ * `printUsage`, never a subcommand, a thin-client route or the engine.+ */+import { ROUTERS } from './subcommands.ts';++export interface RouterModule {+ SUBCOMMANDS: readonly string[];+ printUsage(): void;+}++/** The router modules, one per ROUTERS entry (the help gate checks they match). */+export const ROUTER_MODULES: Readonly<Record<string, () => Promise<RouterModule>>> = {+ pages: () => import('../commands/pages.ts'),+ cache: () => import('../commands/cache.ts'),+ integrity: () => import('../commands/integrity.ts'),+ hook: () => import('../commands/hook.ts'),+ search: () => import('../commands/search.ts'),+ 'edge-proposals': () => import('../commands/edge-proposals.ts'),+ schema: () => import('../commands/schema.ts'),+ config: () => import('../commands/config.ts'),+};++/**+ * Prints the router's usage and returns true. `search` prints its dashboard+ * usage only for its dashboard subcommands; `search --help` alone keeps the+ * search operation's help.+ */+export async function printRouterHelp(command: string, subArgs: readonly string[]): Promise<boolean> {+ const router = ROUTERS[command];+ const load = ROUTER_MODULES[command];+ if (!router || !load) return false;+ if (!router.bareHelpFirst && !router.subcommands.includes(subArgs[0] ?? '')) return false;+ (await load()).printUsage();+ return true;+}diff --git a/src/cli/strict-args.ts b/src/cli/strict-args.tsnew file mode 100644index 0000000000..a022f0a7f4--- /dev/null+++ b/src/cli/strict-args.ts@@ -0,0 +1,135 @@+/**+ * Strict arguments for destructive subcommands (#6114).+ *+ * A destructive subcommand that ignored a token it did not understand did+ * the destructive thing anyway: `pages purge-deleted --source x` purged+ * brain-wide, `--older-than=9999` silently became 72h. Each subcommand in+ * STRICT_SUBCOMMANDS declares exactly what it consumes; any other token, a+ * flag without its value, a repeated value flag or a value of the wrong+ * shape refuses with `invalid_params` (exit 2) before any engine or file+ * access. cli.ts consults the table after help is resolved (help always+ * wins) and before dispatch. Each refusal's fix is a real read-only command+ * that itself parses under this table, or, where none exists, an ask_user+ * fix naming the command.+ */+import { opError, type OperationError } from '../core/ops/contract.ts';+import type { Action } from '../core/agent-output.ts';++export const OLDER_THAN_RE = /^\d+[hd]?$/;++interface StrictSpec {+ /** Boolean flags (no value). */+ flags?: readonly string[];+ /** Value flags, each with the shape its value must have (null: any non-empty value). */+ values?: Readonly<Record<string, { re: RegExp; shape: string } | null>>;+ /** The most positional arguments it reads (a missing one is the handler's own usage error). */+ maxPositionals: number;+ /** The read-only command an agent runs instead (argv after `gbrain`), or ask_user. */+ fix: { argv: readonly string[]; why: string } | { ask_user: string };+ /** Applies only when this returns true (e.g. `search modes` only with `--reset`). */+ when?: (args: readonly string[]) => boolean;+ /** Extra why for specific refused flags. */+ refusedWhy?: Readonly<Record<string, string>>;+}++const SCHEMA_FIX = { argv: ['schema', 'active', '--json'], why: 'Shows the active schema pack and where it was resolved; changes nothing.' } as const;+const CACHE_FIX = { argv: ['cache', 'stats'], why: 'Shows the cache rows this command would touch; changes nothing.' } as const;+const PACK = { '--pack': null } as const;++export const STRICT_SUBCOMMANDS: Readonly<Record<string, StrictSpec>> = {+ 'pages purge-deleted': {+ flags: ['--dry-run', '--json', '--yes'],+ values: { '--older-than': { re: OLDER_THAN_RE, shape: 'hours (72 or 72h) or days (3d)' } },+ maxPositionals: 0,+ fix: { argv: ['pages', 'purge-deleted', '--dry-run', '--json'], why: 'Lists the soft-deleted pages a brain-wide purge would remove; changes nothing.' },+ refusedWhy: {+ '--source': 'The purge is brain-wide: it removes soft-deleted pages from every source, and per-source purge is not supported.',+ '--source-id': 'The purge is brain-wide: it removes soft-deleted pages from every source, and per-source purge is not supported.',+ },+ },+ 'cache clear': { flags: ['--yes', '-y'], values: { '--source': null }, maxPositionals: 0, fix: CACHE_FIX },+ 'cache prune': { maxPositionals: 0, fix: CACHE_FIX },+ 'schema use': { maxPositionals: 1, fix: SCHEMA_FIX },+ 'schema downgrade': { flags: ['--json'], values: { '--to': null }, maxPositionals: 0, fix: SCHEMA_FIX },+ 'schema init': { flags: ['--json'], maxPositionals: 1, fix: SCHEMA_FIX },+ 'schema remove-type': { flags: ['--json'], values: PACK, maxPositionals: 1, fix: SCHEMA_FIX },+ 'schema remove-alias': { flags: ['--json'], values: PACK, maxPositionals: 2, fix: SCHEMA_FIX },+ 'schema remove-prefix': { flags: ['--json'], values: PACK, maxPositionals: 2, fix: SCHEMA_FIX },+ 'schema remove-link-type': { flags: ['--json'], values: PACK, maxPositionals: 1, fix: SCHEMA_FIX },+ 'integrity auto': {+ flags: ['--dry-run', '--fresh', '--skip-bare-tweet', '--skip-urls'],+ values: {+ '--confidence': { re: /^(?:0|1|0?\.\d+|1\.0+)$/, shape: 'a number from 0 to 1' },+ '--review-lower': { re: /^(?:0|1|0?\.\d+|1\.0+)$/, shape: 'a number from 0 to 1' },+ '--limit': { re: /^\d+$/, shape: 'a whole number' },+ },+ maxPositionals: 0,+ fix: { argv: ['integrity', 'check'], why: 'Reports the bare-tweet and external-link findings the repair loop would act on; changes nothing.' },+ },+ 'integrity reset-progress': {+ maxPositionals: 0,+ fix: { ask_user: 'Clear the integrity repair progress log so the next `gbrain integrity auto` starts over?' },+ },+ 'search modes': {+ flags: ['--reset', '--json'],+ values: { '--source': null },+ maxPositionals: 0,+ when: args => args.includes('--reset'),+ fix: { argv: ['search', 'modes'], why: 'Shows every search.* override and its value; changes nothing.' },+ },+};++export interface StrictArgsProblem { token: string; problem: string }++/** The first problem with `args` (the tokens after the subcommand) under `spec`, or null. */+export function strictArgsProblem(spec: StrictSpec, args: readonly string[]): StrictArgsProblem | null {+ const flags = new Set(spec.flags ?? []);+ const values = spec.values ?? {};+ const seen = new Set<string>();+ let positionals = 0;+ for (let i = 0; i < args.length; i++) {+ const token = args[i]!;+ if (!token.startsWith('-')) {+ positionals++;+ if (positionals > spec.maxPositionals) return { token, problem: spec.maxPositionals === 0 ? 'takes no positional arguments' : `takes at most ${spec.maxPositionals} positional argument(s)` };+ continue;+ }+ const eq = token.indexOf('=');+ const name = token.startsWith('--') && eq > 0 ? token.slice(0, eq) : token;+ if (flags.has(name)) {+ if (name !== token) return { token, problem: `${name} takes no value` };+ continue;+ }+ if (!(name in values)) return { token, problem: 'is not an argument this subcommand reads' };+ if (seen.has(name)) return { token, problem: `${name} was given more than once` };+ seen.add(name);+ const value = name !== token ? token.slice(eq + 1) : args[i + 1];+ if (name === token) {+ if (value === undefined || value.startsWith('--')) return { token, problem: `${name} needs a value` };+ i++;+ }+ const shape = values[name];+ if (!value || (shape && !shape.re.test(value))) return { token: value || token, problem: `is not a valid ${name} value${shape ? ` (expected ${shape.shape})` : ''}` };+ }+ return null;+}++/** The `invalid_params` refusal for `gbrain <command> <sub> ...rest`, or null when the subcommand is not strict or the arguments parse. */+export function strictArgsRefusal(command: string, subArgs: readonly string[]): OperationError | null {+ const key = `${command} ${subArgs[0] ?? ''}`;+ const spec = STRICT_SUBCOMMANDS[key];+ if (!spec) return null;+ const rest = subArgs.slice(1);+ if (spec.when && !spec.when(rest)) return null;+ const p = strictArgsProblem(spec, rest);+ if (!p) return null;+ const name = p.token.split('=')[0]!;+ const why = [`gbrain ${key} refuses an argument it would ignore, because an ignored argument would still run the destructive command. Nothing was changed.`,+ spec.refusedWhy?.[name]].filter(Boolean).join(' ');+ const fix: Action = 'ask_user' in spec.fix+ ? { argv: ['gbrain', ...key.split(' ')], consent: ['destructive'], actor: 'agent', requires_exclusive: false,+ user_message: spec.fix.ask_user, why: 'No read-only form exists; run it without extra arguments only after the user agrees.' }+ : { argv: ['gbrain', ...spec.fix.argv], consent: [], actor: 'agent', requires_exclusive: false, why: spec.fix.why };+ return opError('invalid_params', `gbrain ${key}: \`${p.token}\` ${p.problem}.`,+ `Run \`gbrain ${key} --help\` for the accepted arguments.`, { why, fix });+}diff --git a/src/cli/subcommands.ts b/src/cli/subcommands.tsnew file mode 100644index 0000000000..0936a5f0be--- /dev/null+++ b/src/cli/subcommands.ts@@ -0,0 +1,79 @@+/**+ * Subcommand inventories and the help grammar (#6114).+ *+ * Each router command exports its inventory as `SUBCOMMANDS` (re-exported+ * from here, so cli.ts can read them without loading the routers). The+ * router types its dispatch over the inventory, so a subcommand the router+ * handles but the inventory omits fails typecheck, and the help gate+ * (test/cli-help-no-side-effects*.serial.test.ts) runs every listed+ * subcommand's help.+ *+ * Help grammar: `--help` / `-h` anywhere before `--` asks for help, even in+ * a flag-value slot (`--older-than --help`). A bare `help` asks for help only+ * as the first token after a router command (`pages help`) or after one of+ * its subcommands (`pages purge-deleted help`); anywhere else (a free-text+ * query such as `search help`, a flag value) it is an ordinary argument.+ * Help never runs the subcommand: cli.ts prints the router's usage and+ * returns before startup side effects, strict argument checks and engine+ * access.+ */+export const PAGES_SUBCOMMANDS = ['purge-deleted'] as const;+export const CACHE_SUBCOMMANDS = ['stats', 'clear', 'prune'] as const;+export const INTEGRITY_SUBCOMMANDS = ['check', 'auto', 'review', 'reset-progress'] as const;+export const HOOK_SUBCOMMANDS = ['session-start', 'user-prompt', 'stop', 'session-end', 'compact'] as const;+export const SEARCH_SUBCOMMANDS = ['modes', 'stats', 'tune', 'diagnose'] as const;+export const EDGE_PROPOSALS_SUBCOMMANDS = ['list', 'show', 'accept', 'reject', 'undo', 'date'] as const;+export const CONFIG_SUBCOMMANDS = ['show', 'get', 'set', 'unset'] as const;+export const SCHEMA_SUBCOMMANDS = [+ 'active', 'list', 'show', 'validate', 'use', 'detect', 'suggest', 'review-candidates', 'init', 'fork', 'edit',+ 'diff', 'graph', 'lint', 'explain', 'review-orphans', 'downgrade', 'usage', 'stats', 'cardinality-preview',+ 'sync', 'reload', 'add-type', 'remove-type', 'update-type', 'add-alias', 'remove-alias', 'add-prefix',+ 'remove-prefix', 'add-link-type', 'remove-link-type', 'set-extractable', 'set-expert-routing', 'scaffold-extractable',+] as const;++export interface RouterInventory {+ subcommands: readonly string[];+ /**+ * The router's first argument is a subcommand, so a bare `help` there asks+ * for help. False for `search`, whose first argument is otherwise a query.+ */+ bareHelpFirst: boolean;+}++/** Every router command with an inventory, keyed by command name. */+export const ROUTERS: Readonly<Record<string, RouterInventory>> = {+ pages: { subcommands: PAGES_SUBCOMMANDS, bareHelpFirst: true },+ cache: { subcommands: CACHE_SUBCOMMANDS, bareHelpFirst: true },+ integrity: { subcommands: INTEGRITY_SUBCOMMANDS, bareHelpFirst: true },+ hook: { subcommands: HOOK_SUBCOMMANDS, bareHelpFirst: true },+ search: { subcommands: SEARCH_SUBCOMMANDS, bareHelpFirst: false },+ 'edge-proposals': { subcommands: EDGE_PROPOSALS_SUBCOMMANDS, bareHelpFirst: true },+ schema: { subcommands: SCHEMA_SUBCOMMANDS, bareHelpFirst: true },+ config: { subcommands: CONFIG_SUBCOMMANDS, bareHelpFirst: true },+};++/** `--help` / `-h` before any `--` terminator. */+export function helpFlagRequested(args: readonly string[]): boolean {+ for (const a of args) {+ if (a === '--') return false;+ if (a === '--help' || a === '-h') return true;+ }+ return false;+}++/**+ * True when `args` (the tokens after the command) ask for help under the+ * grammar above. `router` is the command's inventory, or undefined for a+ * command without subcommands (only the flags count there).+ */+export function subcommandHelpRequested(args: readonly string[], router?: RouterInventory): boolean {+ if (helpFlagRequested(args)) return true;+ if (!router) return false;+ if (router.bareHelpFirst && args[0] === 'help') return true;+ return router.subcommands.includes(args[0] ?? '') && args[1] === 'help';+}++/** The help decision for `gbrain <command> ...args`, made once in cli.ts before any side effect. */+export function cliHelpRequested(command: string, args: readonly string[]): boolean {+ return subcommandHelpRequested(args, ROUTERS[command]);+}diff --git a/src/commands/cache.ts b/src/commands/cache.tsindex d3b2d38e99..692dd16fc3 100644--- a/src/commands/cache.ts+++ b/src/commands/cache.ts@@ -14,8 +14,11 @@import { loadConfig, toEngineConfig } from '../core/config.ts';import { createEngine } from '../core/engine-factory.ts';import { SemanticQueryCache, loadCacheConfig, semanticResultCacheAvailable } from '../core/search/query-cache.ts';+import { CACHE_SUBCOMMANDS, ROUTERS, subcommandHelpRequested } from '../cli/subcommands.ts';-function printHelp(): void {+export { CACHE_SUBCOMMANDS as SUBCOMMANDS } from '../cli/subcommands.ts';++export function printUsage(): void {// eslint-disable-next-line no-consoleconsole.log(`gbrain cache \u2014 manage the semantic query cache (v0.32.x search-lite)@@ -33,9 +36,9 @@ Flags:}export async function runCache(args: string[]): Promise<void> {- const sub = args[0];- if (!sub || sub === '--help' || sub === '-h') {- printHelp();+ const sub = args[0] as (typeof CACHE_SUBCOMMANDS)[number] | undefined;+ if (!sub || subcommandHelpRequested(args, ROUTERS.cache)) {+ printUsage();return;}diff --git a/src/commands/config.ts b/src/commands/config.tsindex dc61c9b86c..9cf8543998 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -14,6 +14,7 @@ import { redactPgUrl } from '../core/url-redact.ts';import { PUBLISH_GATE_KEYS } from '../mcp/publish-gates.ts';import { isConsentConfigKey, setConsentPreapproval, unsetConsentPreapproval } from '../core/consent-preapproval.ts';import { WRITER_ADMIN_LOCK_KEY } from '../core/persistence/admin-contract.ts';+import { CONFIG_SUBCOMMANDS, ROUTERS, subcommandHelpRequested } from '../cli/subcommands.ts';import {SELF_UPGRADE_CONFIG_LEAVES,isSelfUpgradeConfigLeaf,@@ -653,8 +654,27 @@ async function showConfig(engine: BrainEngine): Promise<void> {}}+export { CONFIG_SUBCOMMANDS as SUBCOMMANDS } from '../cli/subcommands.ts';++const USAGE = `Usage: gbrain config [show|get|set|unset] <key> [value]+ gbrain config unset --pattern <prefix>++Subcommands:+ show Print the effective configuration+ get <key> [--raw] Print one value (--raw: no secret redaction)+ set <key> <value> Write a value. --force accepts an unknown key;+ --coverage-override (or --yes) passes the embedding+ coverage gate; --yes accepts a disclosure prompt+ unset <key> Remove one key+ unset --pattern <prefix> Remove every key under a prefix`;++export function printUsage(): void {+ console.log(USAGE);+}+export async function runConfig(engine: BrainEngine, args: string[]) {- const action = args[0];+ if (subcommandHelpRequested(args, ROUTERS.config)) { printUsage(); return; }+ const action = args[0] as (typeof CONFIG_SUBCOMMANDS)[number] | undefined;// The writer admin lock is reserved for `gbrain sources writer lock|unlock`; --force is no escape.if (action === 'set' || action === 'unset') {@@ -1423,8 +1443,7 @@ export async function runConfig(engine: BrainEngine, args: string[]) {}}} else {- console.error('Usage: gbrain config [show|get|set|unset] <key> [value]');- console.error(' gbrain config unset --pattern <prefix>');+ console.error(USAGE);process.exit(1);}}diff --git a/src/commands/core.ts b/src/commands/core.tsindex af41b1e4b6..d647102629 100644--- a/src/commands/core.ts+++ b/src/commands/core.ts@@ -254,7 +254,7 @@ export async function runCore(engine: BrainEngine, args: string[]): Promise<void}default:console.log(USAGE);- if (sub && sub !== '--help' && sub !== 'help') setCliExitVerdict(1);+ if (sub && sub !== '--help' && sub !== '-h' && sub !== 'help') setCliExitVerdict(1);}}diff --git a/src/commands/edge-proposals.ts b/src/commands/edge-proposals.tsindex 76fd59dd30..c63e8bac27 100644--- a/src/commands/edge-proposals.ts+++ b/src/commands/edge-proposals.ts@@ -17,6 +17,7 @@ import type { BrainEngine } from '../core/engine.ts';import { applyEdgeProposal, rejectEdgeProposal, undoEdgeProposal, DREAM_TIMELINE_SOURCE } from '../core/cycle/edge-contradictions.ts';import { isCalendarDate, dateKey } from '../core/link-validity.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';+import { EDGE_PROPOSALS_SUBCOMMANDS, ROUTERS, subcommandHelpRequested } from '../cli/subcommands.ts';const STATUSES = ['proposed', 'applied', 'rejected', 'undone', 'stale', 'reverted_by_user', 'undated_unresolved', 'ambiguous_same_date', 'compatible', 'error'];@@ -56,14 +57,21 @@ function describe(r: Row): string {return `#${r.id} [${r.status}] ${pair}`;}+export { EDGE_PROPOSALS_SUBCOMMANDS as SUBCOMMANDS } from '../cli/subcommands.ts';++export function printUsage(): void {+ console.log(usage());+}+export async function runEdgeProposals(engine: BrainEngine, args: string[]): Promise<void> {- const [sub, ...rest] = args;+ if (subcommandHelpRequested(args, ROUTERS['edge-proposals'])) { printUsage(); return; }+ const [sub, ...rest] = args as [(typeof EDGE_PROPOSALS_SUBCOMMANDS)[number] | undefined, ...string[]];const json = rest.includes('--json');const flag = (name: string) => { const i = rest.indexOf(name); return i >= 0 ? rest[i + 1] : undefined; };const id = Number(rest.find(a => /^\d+$/.test(a)));const out = (value: unknown, text: string) => console.log(json ? JSON.stringify(value, null, 2) : text);- if (!sub || sub === '--help' || sub === 'help') { console.log(usage()); return; }+ if (!sub) { printUsage(); return; }if (sub === 'list') {const status = flag('--status');if (status && status !== 'all' && !STATUSES.includes(status)) { console.error(`Unknown status ${status}. One of: ${STATUSES.join(', ')}, all`); setCliExitVerdict(2); return; }diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex 1c9cd86cc7..71e5bd840e 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -112,6 +112,7 @@ import {import { realpathOrResolve } from '../core/path-confine.ts';import { isClaudeCliSelfTranscriptPath } from '../core/ai/providers/claude-cli-scratch.ts';import { withoutPhysicalRootMetadata } from '../core/persistence/root-metadata.ts';+import { HOOK_SUBCOMMANDS as HOOK_EVENTS, ROUTERS, subcommandHelpRequested } from '../cli/subcommands.ts';// ── Tunables ────────────────────────────────────────────────────────────────@@ -232,7 +233,8 @@ export interface HookIo {// ── Entry point ─────────────────────────────────────────────────────────────-export const HOOK_EVENTS = ['session-start', 'user-prompt', 'stop', 'session-end', 'compact'] as const;+export { HOOK_EVENTS, HOOK_EVENTS as SUBCOMMANDS };+export const printUsage = (): void => { process.stdout.write(`${USAGE}\n`); };const USAGE = `Usage: gbrain hook <event>@@ -257,7 +259,7 @@ All events fail open: errors exit 0 with empty stdout and a heartbeat entry at/** Dispatch a hook event. Returns the process exit code (0 for every runtime path). */export async function runHook(args: string[], io: HookIo = {}): Promise<number> {const event = args[0];- if (event === '--help' || event === '-h' || event === 'help') {+ if (subcommandHelpRequested(args, ROUTERS.hook)) {write(io, USAGE + '\n');return 0;}diff --git a/src/commands/integrity.ts b/src/commands/integrity.tsindex 27c8591f62..2e525d11f1 100644--- a/src/commands/integrity.ts+++ b/src/commands/integrity.ts@@ -39,6 +39,7 @@ import {} from '../core/resolvers/index.ts';import { registerBuiltinResolvers } from './resolvers.ts';import { tweetCitation } from '../core/output/scaffold.ts';+import { INTEGRITY_SUBCOMMANDS, ROUTERS, subcommandHelpRequested } from '../cli/subcommands.ts';// ---------------------------------------------------------------------------// Paths@@ -222,11 +223,13 @@ function ensureDir(path: string): void {// CLI entry point// ---------------------------------------------------------------------------+export { INTEGRITY_SUBCOMMANDS as SUBCOMMANDS } from '../cli/subcommands.ts';+export async function runIntegrity(args: string[]): Promise<void> {- const sub = args[0];+ const sub = args[0] as (typeof INTEGRITY_SUBCOMMANDS)[number] | undefined;- if (!sub || sub === '--help' || sub === '-h') {- printHelp();+ if (!sub || subcommandHelpRequested(args, ROUTERS.integrity)) {+ printUsage();return;}@@ -249,7 +252,7 @@ export async function runIntegrity(args: string[]): Promise<void> {}console.error(`Unknown subcommand: ${sub}`);- printHelp();+ printUsage();process.exit(1);}@@ -801,7 +804,7 @@ function truncate(s: string, n: number): string {return s.length <= n ? s : s.slice(0, n - 3) + '...';}-function printHelp(): void {+export function printUsage(): void {console.log(`Usage: gbrain integrity <subcommand> [options]Subcommands:diff --git a/src/commands/pages.ts b/src/commands/pages.tsindex a58815596d..fc7b9becf2 100644--- a/src/commands/pages.ts+++ b/src/commands/pages.ts@@ -1,7 +1,7 @@/*** gbrain pages — page-level operator commands. v0.26.5+.*- * The first subcommand: `pages purge-deleted [--older-than HOURS] [--dry-run]`.+ * The first subcommand: `pages purge-deleted [--older-than HOURS|Nh|Nd] [--dry-run] [--json] [--yes]`.* Manual escape hatch alongside the autopilot purge phase. Hard-deletes pages* whose `deleted_at` is older than the cutoff; cascades to content_chunks,* page_links, chunk_relations via existing FKs.@@ -9,27 +9,38 @@import type { BrainEngine } from '../core/engine.ts';import { purgeDeletedPagesCoordinated } from '../core/persistence/purge-deleted.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';+import { consentGate } from '../core/consent-cli.ts';+import { strictArgsRefusal } from '../cli/strict-args.ts';+import { PAGES_SUBCOMMANDS, ROUTERS, subcommandHelpRequested } from '../cli/subcommands.ts';const SOFT_DELETE_TTL_HOURS_DEFAULT = 72;-function parseOlderThanHours(args: string[]): number {- const idx = args.indexOf('--older-than');- if (idx === -1 || idx === args.length - 1) return SOFT_DELETE_TTL_HOURS_DEFAULT;- const raw = args[idx + 1];- // Accept bare numbers (hours) or `<N>h` / `<N>d`. Reject anything ambiguous.- const trimmed = raw.trim();- const dayMatch = trimmed.match(/^(\d+)d$/);- if (dayMatch) return Math.max(0, parseInt(dayMatch[1], 10) * 24);- const hourMatch = trimmed.match(/^(\d+)h?$/);- if (hourMatch) return Math.max(0, parseInt(hourMatch[1], 10));- console.error(`Invalid --older-than value: "${raw}". Expected hours (e.g. 72 or 72h) or days (e.g. 3d).`);- process.exit(2);+export { PAGES_SUBCOMMANDS as SUBCOMMANDS } from '../cli/subcommands.ts';++export interface PurgeArgs { olderThanHours: number; dryRun: boolean; json: boolean }++/**+ * Strict `purge-deleted` arguments (#6114): exactly `--dry-run`, `--json`,+ * `--yes` (read by the consent gate) and one `--older-than <HOURS|Nh|Nd>` (also `--older-than=N`).+ * Anything else throws `invalid_params` before the engine is touched; cli.ts+ * refuses the same tokens earlier through the same table.+ */+export function parsePurgeArgs(args: readonly string[]): PurgeArgs {+ const refusal = strictArgsRefusal('pages', ['purge-deleted', ...args]);+ if (refusal) throw refusal;+ let olderThanHours = SOFT_DELETE_TTL_HOURS_DEFAULT;+ for (let i = 0; i < args.length; i++) {+ const a = args[i]!;+ const raw = a === '--older-than' ? args[++i]! : a.startsWith('--older-than=') ? a.slice('--older-than='.length) : null;+ if (raw === null) continue;+ const n = parseInt(raw, 10);+ olderThanHours = raw.endsWith('d') ? n * 24 : n;+ }+ return { olderThanHours, dryRun: args.includes('--dry-run'), json: args.includes('--json') };}async function runPurgeDeleted(engine: BrainEngine, args: string[]): Promise<void> {- const olderThanHours = parseOlderThanHours(args);- const dryRun = args.includes('--dry-run');- const json = args.includes('--json');+ const { olderThanHours, dryRun, json } = parsePurgeArgs(args);if (dryRun) {// Same engine method, same WHERE predicate, same DB now() clock as the@@ -46,6 +57,27 @@ async function runPurgeDeleted(engine: BrainEngine, args: string[]): Promise<voireturn;}+ // D6: a hard purge is irreversible and brain-wide, so the CLI asks first+ // (a TTY prompt, `--yes`, or exit 3 with the consent payload). The+ // autopilot purge phase calls the library directly and is unaffected.+ const preview = await engine.purgeDeletedPages(olderThanHours, { dryRun: true });+ if (preview.count === 0) {+ if (json) console.log(JSON.stringify({ older_than_hours: olderThanHours, count: 0, slugs: [] }, null, 2));+ else console.log(`No pages to purge (older than ${olderThanHours}h).`);+ return;+ }+ const authorized = await consentGate({+ command: 'pages purge-deleted', effects: ['destructive'], actor: 'agent',+ what: `Permanently purge ${preview.count} soft-deleted page(s)`,+ why: 'A hard purge removes soft-deleted pages, their chunks and links, from every source of this brain.',+ risk: 'Purged pages cannot be restored with `gbrain restore`.',+ user_message: `Permanently delete ${preview.count} page(s) soft-deleted more than ${olderThanHours}h ago, across every source in this brain? They cannot be restored afterwards.`,+ argv: ['gbrain', 'pages', 'purge-deleted', '--older-than', `${olderThanHours}h`, ...(json ? ['--json'] : []), '--yes'],+ preview_argv: ['gbrain', 'pages', 'purge-deleted', '--older-than', `${olderThanHours}h`, '--dry-run', '--json'],+ args,+ }, { json });+ if (!authorized) return;+const result = await purgeDeletedPagesCoordinated(engine, olderThanHours);if (json) {console.log(JSON.stringify({ older_than_hours: olderThanHours, count: result.count, slugs: result.slugs,@@ -63,13 +95,16 @@ async function runPurgeDeleted(engine: BrainEngine, args: string[]): Promise<voi}}-function printHelp(): void {+export function printUsage(): void {console.log(`gbrain pages — page-level operator commands (v0.26.5)Subcommands:- purge-deleted [--older-than HOURS|Nd] [--dry-run] [--json]+ purge-deleted [--older-than HOURS|Nh|Nd] [--dry-run] [--json] [--yes]Hard-delete soft-deleted pages older than the cutoff- (default 72h). Cascades to chunks/links/edges.+ (default 72h) in every source of the brain (per-source+ purge is not supported). Cascades to chunks/links/edges.+ Asks first: a TTY prompt, --yes, or exit 3 with the+ consent payload. Preview with --dry-run --json.Mirror of the autopilot purge phase.Notes:@@ -82,19 +117,16 @@ Notes:}export async function runPages(engine: BrainEngine, args: string[]): Promise<void> {- const sub = args[0];- const rest = args.slice(1);-+ if (subcommandHelpRequested(args, ROUTERS.pages)) { printUsage(); return; }+ const sub = args[0] as (typeof PAGES_SUBCOMMANDS)[number] | undefined;switch (sub) {- case 'purge-deleted': return runPurgeDeleted(engine, rest);+ case 'purge-deleted': return runPurgeDeleted(engine, args.slice(1));case undefined:- case '--help':- case '-h':- printHelp();+ printUsage();return;default:console.error(`Unknown subcommand: ${sub}`);- printHelp();+ printUsage();process.exit(2);}}diff --git a/src/commands/schema.ts b/src/commands/schema.tsindex da837a4158..0f263101de 100644--- a/src/commands/schema.ts+++ b/src/commands/schema.ts@@ -58,9 +58,17 @@ import { opError } from '../core/ops/contract.ts';import { readDbSchemaPack } from '../core/schema-pack/best-effort.ts';import { sanitizeTypeForDisplay } from '../core/schema-pack/type-usage.ts';import { yamlScalar } from '../core/frontmatter-inference.ts';+import { ROUTERS, SCHEMA_SUBCOMMANDS, subcommandHelpRequested } from '../cli/subcommands.ts';++export { SCHEMA_SUBCOMMANDS as SUBCOMMANDS } from '../cli/subcommands.ts';++export function printUsage(): void {+ printHelp();+}export async function runSchema(args: string[]): Promise<void> {- const sub = args[0];+ if (subcommandHelpRequested(args, ROUTERS.schema)) return printHelp();+ const sub = args[0] as (typeof SCHEMA_SUBCOMMANDS)[number] | undefined;switch (sub) {case 'active': return runActive(args.slice(1));case 'list': return runList(args.slice(1));@@ -97,8 +105,6 @@ export async function runSchema(args: string[]): Promise<void> {case 'set-expert-routing': return runSetExpertRoutingCmd(args.slice(1));case 'scaffold-extractable': return runScaffoldExtractableCmd(args.slice(1));case undefined:- case '--help':- case '-h':return printHelp();default:console.error(`Unknown schema subcommand: ${sub}`);diff --git a/src/commands/search.ts b/src/commands/search.tsindex afe530180d..5780473a21 100644--- a/src/commands/search.ts+++ b/src/commands/search.ts@@ -54,6 +54,7 @@ import {TUNE_MIN_CALLS,type TuneRecommendation,} from '../core/search/tune-recommendations.ts';+import { ROUTERS, SEARCH_SUBCOMMANDS, subcommandHelpRequested } from '../cli/subcommands.ts';function formatModesText(report: SearchModesReport): string {const lines: string[] = [];@@ -352,7 +353,8 @@ function buildRevertCommand(r: TuneRecommendation): string {return r.apply_command;}-const USAGE = `Usage: gbrain search <modes|stats|tune> [flags]+const USAGE = `Usage: gbrain search <modes|stats|tune|diagnose> [flags]+ gbrain search "<query>" (free-text search; see gbrain search --help)Subcommands:modes [--json] Show active mode, bundles, and per-knob source.@@ -360,6 +362,8 @@ Subcommands:modes --source <mode> Dry-run: list what --reset would change.stats [--days N] [--json] Cache hit rate, intent mix, budget pressure.tune [--apply] [--json] Print recommendations; --apply mutates config.+ diagnose "<query>" --target <slug> [--json] [--source <id>]+ Trace where a target page surfaces across retrieval layers.Examples:gbrain search modes@@ -369,12 +373,18 @@ Examples:gbrain search tune --apply`;+export { SEARCH_SUBCOMMANDS as SUBCOMMANDS } from '../cli/subcommands.ts';++export function printUsage(): void {+ console.log(USAGE);+}+export async function runSearch(engine: BrainEngine, args: string[]): Promise<void> {- const sub = args[0];+ const sub = args[0] as Exclude<(typeof SEARCH_SUBCOMMANDS)[number], 'diagnose'> | undefined;const rest = args.slice(1);- if (!sub || sub === '--help' || sub === '-h') {- console.log(USAGE);+ if (!sub || subcommandHelpRequested(args, ROUTERS.search)) {+ printUsage();return;}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 449dee9b44..9a1ca0e7b4 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -257,6 +257,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.97.0', text: 'Google Calendar sync writes only events between `historyDays` back and 60 days ahead; `gbrain sync --full` removes pages for in-window events the calendar no longer lists (more than 200 is refused and reported partial).' },{ since: '0.60.98.0', text: 'Managed sync now holds a file whose facts or takes fence cannot be imported (code `invalid_fence`; `gbrain sources status <id>` names the fence, section and rows) instead of blocking the whole source, and a source such a fence blocked before recovers on its next sync. Coordinated writes refuse such a fence with `invalid_fence` (wire `error` stays `invalid_params`, or `take_row_collision`). `gbrain config set sync.holds fail` keeps fail-closed blocking.' },{ since: '0.60.99.0', text: 'Fixable facts and takes fences are now rewritten instead of held or refused: managed sync, put_page and the fact and take writers normalize a fence whose meaning is unambiguous (a missing end marker after the table, two-dash takes markers, zero or duplicate row numbers, header aliases, invented kinds and enum synonyms, assistant holders, percent confidences) without changing a claim or an existing row number, and managed sync commits the rewritten file. Results report `fences_normalized`; `gbrain sync --dry-run` lists `would_normalize`. `gbrain config set fences.normalize false` turns it off (such fences are then held or refused).' },+ { since: '0.0.0-wave11', text: '`gbrain pages purge-deleted`, `cache clear|prune`, `schema use|downgrade|init|remove-*`, `integrity auto|reset-progress` and `search modes --reset` refuse an argument they would ignore (exit 2) instead of running; `pages purge-deleted --source <id>` used to purge every source. Preview with `gbrain pages purge-deleted --dry-run --json`.' },+ { since: '0.0.0-wave11', text: '`gbrain pages purge-deleted` asks before a hard purge: without a terminal it exits 3 with the consent payload, and the `--yes` command it names runs only after the user agrees. The autopilot purge is unchanged.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex f543e71e09..428783c13b 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -58,7 +58,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'errors': ['--brain', '--changed', '--help', '--json', '--source'],'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fact-extractor', '--fact-keys', '--fact-keys-max-usd', '--fact-keys-model', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--synopsis-cache', '--synopsis-concurrency', '--synopsis-max-usd', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--time-scope', '--time-scope-pool', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--wait', '--with-code-intel', '--yes'],'export': ['--accept-pending', '--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type', '--wait'],- 'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],+ 'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],'facts': ['--admin-intent', '--after-id', '--brain', '--dry-run', '--entity', '--examples', '--expected-state', '--help', '--include-private', '--json', '--limit', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--retry-model', '--since', '--source'],'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--embedding-model', '--expect', '--explain', '--facts', '--force', '--from-meetings', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],@@ -72,7 +72,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--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', '--seat', '--session', '--show-current', '--show-toplevel', '--source'],'import': ['--accept-pending', '--allow-empty', '--allow-noncanonical-root', '--apply', '--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-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--access', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--budget-ms', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--facts', '--force', '--full', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--path', '--pglite', '--plan', '--prefer-postgres', '--probe', '--provenance', '--query', '--quiet', '--reference-date', '--remediate', '--save', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--yes'],+ 'init': ['--access', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--budget-ms', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--facts', '--force', '--full', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--path', '--pglite', '--plan', '--prefer-postgres', '--probe', '--provenance', '--query', '--quiet', '--reference-date', '--remediate', '--reset', '--save', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],'jobs': ['--abbrev-ref', '--access', '--add', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],@@ -88,7 +88,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'notices': ['--brain', '--help', '--json', '--source'],'onboard': ['--access', '--add', '--allowed-operations', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-pages', '--full', '--fuzzy', '--help', '--history', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--phase', '--probe', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--updated-after', '--url', '--yes'],'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],- 'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--older-than', '--source'],+ 'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--older-than', '--source', '--yes'],'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--path', '--probe', '--source', '--vectors', '--yes'],'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],diff --git a/test/cli-help-grammar.test.ts b/test/cli-help-grammar.test.tsnew file mode 100644index 0000000000..38400dc573--- /dev/null+++ b/test/cli-help-grammar.test.ts@@ -0,0 +1,102 @@+/**+ * The help grammar, router inventories and strict-argument table (#6114),+ * checked in-process. The subprocess gate (cli-help-no-side-effects*.serial)+ * proves the behaviour end to end; this file pins the rules cheaply.+ */+import { describe, expect, test } from 'bun:test';+import { ROUTERS, cliHelpRequested, helpFlagRequested, subcommandHelpRequested } from '../src/cli/subcommands.ts';+import { ROUTER_MODULES } from '../src/cli/router-help.ts';+import { STRICT_SUBCOMMANDS, strictArgsProblem, strictArgsRefusal } from '../src/cli/strict-args.ts';+import { CLI_COMMANDS } from '../src/cli/command-table.ts';++describe('help grammar', () => {+ test.each([+ [['pages', '--help'], true],+ [['pages', 'purge-deleted', '-h'], true],+ [['pages', 'purge-deleted', '--older-than', '--help'], true],+ [['pages', 'help'], true],+ [['pages', 'purge-deleted', 'help'], true],+ [['pages', 'purge-deleted', '--older-than', 'help'], false],+ [['pages', 'purge-deleted', '--', '--help'], false],+ [['search', 'help'], false],+ [['search', 'modes', 'help'], true],+ [['search', '--help'], true],+ [['think', 'help'], false],+ [['think', '-h'], true],+ [['agent', 'run', '--', '--help'], false],+ [['schema', 'use', 'help'], true],+ [['schema', 'explain', 'people', 'help'], false],+ ])('%p asks for help: %p', (argv, want) => {+ const [command, ...args] = argv as string[];+ expect(cliHelpRequested(command!, args)).toBe(want);+ });++ test('flags stop at the -- terminator', () => {+ expect(helpFlagRequested(['a', '-h'])).toBe(true);+ expect(helpFlagRequested(['--', '-h'])).toBe(false);+ expect(subcommandHelpRequested(['help'])).toBe(false);+ });+});++describe('router inventories', () => {+ test('every router is a self-help command with a module exporting the same SUBCOMMANDS and a printUsage', async () => {+ expect(Object.keys(ROUTER_MODULES).sort()).toEqual(Object.keys(ROUTERS).sort());+ for (const [command, router] of Object.entries(ROUTERS)) {+ const mod = await ROUTER_MODULES[command]!();+ expect([...mod.SUBCOMMANDS], command).toEqual([...router.subcommands]);+ expect(typeof mod.printUsage, command).toBe('function');+ if (command !== 'search') expect(CLI_COMMANDS.find(c => c.name === command)?.selfHelp, command).toBe(true);+ }+ });++ test('every strict subcommand belongs to a router inventory', () => {+ for (const key of Object.keys(STRICT_SUBCOMMANDS)) {+ const [command, sub] = key.split(' ');+ expect(ROUTERS[command!]?.subcommands, key).toContain(sub);+ }+ });+});++describe('strict arguments', () => {+ test('each refusal fix is a read-only command that parses under the same table, or an ask_user fix', () => {+ for (const [key, spec] of Object.entries(STRICT_SUBCOMMANDS)) {+ const [command, sub] = key.split(' ');+ const refusal = strictArgsRefusal(command!, [sub!, '--not-a-flag']);+ if (spec.when && !spec.when(['--not-a-flag'])) continue;+ expect(refusal?.code, key).toBe('invalid_params');+ expect(refusal?.why, key).toContain('Nothing was changed');+ const fix = refusal!.fix!;+ if ('ask_user' in spec.fix) {+ expect(fix.consent, key).toEqual(['destructive']);+ expect(fix.user_message, key).toBeTruthy();+ continue;+ }+ expect(fix.consent, key).toEqual([]);+ const [, fixCommand, fixSub, ...fixRest] = fix.argv!;+ expect(strictArgsRefusal(fixCommand!, [fixSub!, ...fixRest]), `${key} fix ${fix.argv!.join(' ')}`).toBeNull();+ }+ });++ test('search modes is strict only with --reset; its --source preview stays accepted', () => {+ expect(strictArgsRefusal('search', ['modes', '--whatever'])).toBeNull();+ expect(strictArgsRefusal('search', ['modes', '--reset', '--source', 'balanced'])).toBeNull();+ expect(strictArgsRefusal('search', ['modes', '--reset', 'extra'])?.message).toContain('`extra`');+ });++ test('value flags: both forms, missing value, repeated, wrong shape', () => {+ const spec = STRICT_SUBCOMMANDS['pages purge-deleted']!;+ expect(strictArgsProblem(spec, ['--older-than', '3d'])).toBeNull();+ expect(strictArgsProblem(spec, ['--older-than=72h'])).toBeNull();+ expect(strictArgsProblem(spec, ['--older-than'])?.problem).toContain('needs a value');+ expect(strictArgsProblem(spec, ['--older-than', '--json'])?.problem).toContain('needs a value');+ expect(strictArgsProblem(spec, ['--older-than', '1', '--older-than=2'])?.problem).toContain('more than once');+ expect(strictArgsProblem(spec, ['--older-than', 'soon'])).toMatchObject({ token: 'soon' });+ expect(strictArgsProblem(spec, ['--json=1'])?.problem).toContain('takes no value');+ });++ test('a missing positional is left to the handler usage; an extra one is refused', () => {+ expect(strictArgsRefusal('schema', ['use'])).toBeNull();+ expect(strictArgsRefusal('schema', ['use', 'a', 'b'])?.message).toContain('`b`');+ expect(strictArgsRefusal('schema', ['remove-type', '--pack', 'mine', 'people'])).toBeNull();+ });+});diff --git a/test/cli-help-no-side-effects-2.serial.test.ts b/test/cli-help-no-side-effects-2.serial.test.tsnew file mode 100644index 0000000000..bd148ccc37--- /dev/null+++ b/test/cli-help-no-side-effects-2.serial.test.ts@@ -0,0 +1,18 @@+/**+ * Help gate part 2 of 4 (#6114): `--help`, `-h` and a bare `help` on every+ * self-help command and every router subcommand print usage, exit 0 and+ * change nothing (brain rows, HOME/cwd files, no fetch, no spawn); strict+ * refusals change nothing and their fixes are read-only. The case list and+ * harness live in test/helpers/cli-help-gate.ts.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { rmSync } from 'node:fs';+import { buildFixture, gateCasesForPart, runGate, type GateFixture } from './helpers/cli-help-gate.ts';++let fx: GateFixture;+beforeAll(async () => { fx = await buildFixture(); }, 120_000);+afterAll(() => { if (fx) rmSync(fx.template, { recursive: true, force: true }); });++test('help never acts (part 2 of 4)', async () => {+ expect(await runGate(fx, gateCasesForPart(1))).toEqual([]);+}, 280_000);diff --git a/test/cli-help-no-side-effects-3.serial.test.ts b/test/cli-help-no-side-effects-3.serial.test.tsnew file mode 100644index 0000000000..8f08339e04--- /dev/null+++ b/test/cli-help-no-side-effects-3.serial.test.ts@@ -0,0 +1,18 @@+/**+ * Help gate part 3 of 4 (#6114): `--help`, `-h` and a bare `help` on every+ * self-help command and every router subcommand print usage, exit 0 and+ * change nothing (brain rows, HOME/cwd files, no fetch, no spawn); strict+ * refusals change nothing and their fixes are read-only. The case list and+ * harness live in test/helpers/cli-help-gate.ts.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { rmSync } from 'node:fs';+import { buildFixture, gateCasesForPart, runGate, type GateFixture } from './helpers/cli-help-gate.ts';++let fx: GateFixture;+beforeAll(async () => { fx = await buildFixture(); }, 120_000);+afterAll(() => { if (fx) rmSync(fx.template, { recursive: true, force: true }); });++test('help never acts (part 3 of 4)', async () => {+ expect(await runGate(fx, gateCasesForPart(2))).toEqual([]);+}, 280_000);diff --git a/test/cli-help-no-side-effects-4.serial.test.ts b/test/cli-help-no-side-effects-4.serial.test.tsnew file mode 100644index 0000000000..e41040f586--- /dev/null+++ b/test/cli-help-no-side-effects-4.serial.test.ts@@ -0,0 +1,18 @@+/**+ * Help gate part 4 of 4 (#6114): `--help`, `-h` and a bare `help` on every+ * self-help command and every router subcommand print usage, exit 0 and+ * change nothing (brain rows, HOME/cwd files, no fetch, no spawn); strict+ * refusals change nothing and their fixes are read-only. The case list and+ * harness live in test/helpers/cli-help-gate.ts.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { rmSync } from 'node:fs';+import { buildFixture, gateCasesForPart, runGate, type GateFixture } from './helpers/cli-help-gate.ts';++let fx: GateFixture;+beforeAll(async () => { fx = await buildFixture(); }, 120_000);+afterAll(() => { if (fx) rmSync(fx.template, { recursive: true, force: true }); });++test('help never acts (part 4 of 4)', async () => {+ expect(await runGate(fx, gateCasesForPart(3))).toEqual([]);+}, 280_000);diff --git a/test/cli-help-no-side-effects.serial.test.ts b/test/cli-help-no-side-effects.serial.test.tsnew file mode 100644index 0000000000..a04390e19f--- /dev/null+++ b/test/cli-help-no-side-effects.serial.test.ts@@ -0,0 +1,18 @@+/**+ * Help gate part 1 of 4 (#6114): `--help`, `-h` and a bare `help` on every+ * self-help command and every router subcommand print usage, exit 0 and+ * change nothing (brain rows, HOME/cwd files, no fetch, no spawn); strict+ * refusals change nothing and their fixes are read-only. The case list and+ * harness live in test/helpers/cli-help-gate.ts.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { rmSync } from 'node:fs';+import { buildFixture, gateCasesForPart, runGate, type GateFixture } from './helpers/cli-help-gate.ts';++let fx: GateFixture;+beforeAll(async () => { fx = await buildFixture(); }, 120_000);+afterAll(() => { if (fx) rmSync(fx.template, { recursive: true, force: true }); });++test('help never acts (part 1 of 4)', async () => {+ expect(await runGate(fx, gateCasesForPart(0))).toEqual([]);+}, 280_000);diff --git a/test/cli-help-without-brain.test.ts b/test/cli-help-without-brain.test.tsindex 63b4809aec..f5918d1d75 100644--- a/test/cli-help-without-brain.test.ts+++ b/test/cli-help-without-brain.test.ts@@ -53,6 +53,8 @@ const HELP_WITHOUT_BRAIN = ['embed',// Core memory: runCore prints its usage for --help before reading the engine.'core',+ // #6114: router commands print their usage from cli.ts before dispatch (src/cli/router-help.ts).+ 'config',];/**@@ -62,9 +64,7 @@ const HELP_WITHOUT_BRAIN = [* CLI_ONLY_SELF_HELP so the generic stub answers, fails this test until the* entry moves.*/-const STILL_NEEDS_A_BRAIN = [- 'config',-];+const STILL_NEEDS_A_BRAIN: string[] = [];async function runHelp(command: string): Promise<{ code: number; out: string }> {const home = mkdtempSync(join(tmpdir(), 'gbrain-nobrain-'));diff --git a/test/consent-table.serial.test.ts b/test/consent-table.serial.test.tsindex a316605d3e..5f5ef84349 100644--- a/test/consent-table.serial.test.ts+++ b/test/consent-table.serial.test.ts@@ -93,6 +93,9 @@ const ROWS: Row[] = [today_non_tty: 'refused: "Refusing to spend without a cap in a non-interactive context", exit 1' },{ name: 'book-mirror', argv: () => ['book-mirror', '--chapters-dir', chapters, '--slug', 'a-book'], effects: ['paid'],today_non_tty: 'refused: "refusing to spend … Pass --yes", exit 0 (nothing submitted)' },+ // D6 (#6114): the hard purge is brain-wide and irreversible; `idea` is soft-deleted in beforeAll.+ { name: 'pages purge-deleted --json', argv: () => ['pages', 'purge-deleted', '--older-than', '0h', '--json'], effects: ['destructive'],+ today_non_tty: 'ran: hard-purged every soft-deleted page past the cutoff with no confirmation (exit 0)' },{ name: 'connect --install (opencode)', argv: () => ['connect', 'https://brain.example.invalid/mcp', '--token', 'gbrain_tok_example', '--agent', 'opencode', '--install', '--json'],effects: ['credentials', 'persistent_install'], today_non_tty: 'refused: "--install in a non-interactive shell requires --yes", exit 1' },];@@ -112,6 +115,7 @@ beforeAll(async () => {writeFileSync(join(notes, 'idea.md'), '---\ntitle: Idea\n---\n\nAn idea page.\n');const imported = await cli(['import', notes, '--no-embed']);expect(imported.exitCode).toBe(0);+ expect((await cli(['delete', 'idea', '--force'])).exitCode).toBe(0);chapters = join(home, 'chapters');mkdirSync(chapters, { recursive: true });writeFileSync(join(chapters, '01.txt'), 'Chapter one text.');diff --git a/test/fixtures/cli-contract/help-baseline.json b/test/fixtures/cli-contract/help-baseline.jsonindex a089671b96..9d844b07bd 100644--- a/test/fixtures/cli-contract/help-baseline.json+++ b/test/fixtures/cli-contract/help-baseline.json@@ -7,8 +7,6 @@"code-callers:stub","code-def:stub","code-refs:stub",- "config:exit",- "config:missing_yes","files:missing_yes","files:stub","forget:stub",diff --git a/test/fixtures/goldens/cli/dispatch-phase.json b/test/fixtures/goldens/cli/dispatch-phase.jsonindex b7d70b0dff..4806bc7e8f 100644--- a/test/fixtures/goldens/cli/dispatch-phase.json+++ b/test/fixtures/goldens/cli/dispatch-phase.json@@ -2021,16 +2021,6 @@"thinClientCheck": false,"unconditionalFor": []},- {- "commands": [],- "condition": "command !== 'hook'",- "connectsEngine": false,- "refusesThinClient": false,- "routesThinClient": false,- "terminates": false,- "thinClientCheck": false,- "unconditionalFor": []- },{"commands": ["ask"diff --git a/test/helpers/cli-help-gate.ts b/test/helpers/cli-help-gate.tsnew file mode 100644index 0000000000..a43007dd6b--- /dev/null+++ b/test/helpers/cli-help-gate.ts@@ -0,0 +1,241 @@+/**+ * Shared harness for the help gate (#6114): `--help`, `-h` and a bare+ * `help` must never perform the command. Each case runs the real CLI in a+ * child process against a copy of one pre-seeded PGLite brain, offline and+ * keyless, with the child-side probe (cli-side-effect-probe.ts) recording+ * any fetch or spawn, and asserts the brain (logically: table contents), the+ * HOME/cwd tree and the probe log are unchanged.+ *+ * The cases are partitioned across several serial files (the serial runner+ * kills one file after 300 s), each running GATE_PARTS-th of the list.+ */+import { appendFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, relative } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { CLI_COMMANDS } from '../../src/cli/command-table.ts';+import { ROUTERS } from '../../src/cli/subcommands.ts';+import { STRICT_SUBCOMMANDS } from '../../src/cli/strict-args.ts';++export const GATE_PARTS = 4;+const REPO = new URL('../..', import.meta.url).pathname.replace(/\/$/, '');+const PROBE = join(REPO, 'test/helpers/cli-side-effect-probe.ts');+/** Files any run may touch without acting: the agent-contract event log is written by the error/exit seam. */+const TREE_ALLOW = [/^\.gbrain\/agent-contract\//];+/** Bookkeeping a brain connection writes (managed-root registration, the behavior-notice baseline): allowed only for cases that connect on purpose. */+const CONNECT_ALLOW = [/^\.gbrain\/persistence\/managed-roots\//, /^\.gbrain\/notices\/behavior-changes\//];++export interface GateCase {+ argv: string[];+ /** Expected exit code. */+ exit: number;+ /** A string stdout must contain (help cases: the usage), or null. */+ stdout?: string | null;+ /** A string stdout must NOT contain. */+ notStdout?: string;+ /** Run with the test-environment startup suppression removed (NODE_ENV, GBRAIN_SKIP_STARTUP_HOOKS). */+ unsuppressed?: boolean;+ /** Skip the brain/tree comparison (a non-help case that legitimately writes, e.g. a search's telemetry). */+ mayWrite?: boolean;+ /** A non-help case that connects to the brain: connection bookkeeping files may change, nothing else. */+ connects?: boolean;+}++/** The usage marker each router prints. */+const ROUTER_USAGE: Record<string, string> = {+ pages: 'gbrain pages —', cache: 'gbrain cache —', integrity: 'Usage: gbrain integrity', hook: 'Usage: gbrain hook',+ search: 'Usage: gbrain search <modes', 'edge-proposals': 'Usage: gbrain edge-proposals', schema: 'gbrain schema —',+ config: 'Usage: gbrain config',+};++/** Every case, in a stable order. */+export function allGateCases(): GateCase[] {+ const cases: GateCase[] = [];+ for (const rec of CLI_COMMANDS) {+ if (!rec.selfHelp) continue;+ cases.push({ argv: [rec.name, '--help'], exit: 0, stdout: null, unsuppressed: true });+ cases.push({ argv: [rec.name, '-h'], exit: 0, stdout: null });+ }+ for (const [command, router] of Object.entries(ROUTERS)) {+ const usage = ROUTER_USAGE[command]!;+ if (router.bareHelpFirst) cases.push({ argv: [command, 'help'], exit: 0, stdout: usage });+ for (const sub of router.subcommands) {+ for (const h of ['--help', '-h', 'help']) cases.push({ argv: [command, sub, h], exit: 0, stdout: usage });+ }+ }+ cases.push(+ { argv: ['pages', 'purge-deleted', '--older-than', '--help'], exit: 0, stdout: ROUTER_USAGE.pages },+ { argv: ['pages', 'purge-deleted', '--older-than', 'help'], exit: 2 },+ { argv: ['pages', 'purge-deleted', '--source', 'nonexistent'], exit: 2 },+ { argv: ['pages', 'purge-deleted', '--older-than'], exit: 2 },+ { argv: ['pages', 'purge-deleted', '--older-than=9999'], exit: 0, stdout: 'No pages to purge', connects: true },+ { argv: ['pages', 'purge-deleted'], exit: 3, connects: true },+ { argv: ['search', 'modes', '--reset', '--help'], exit: 0, stdout: ROUTER_USAGE.search },+ { argv: ['search', 'modes', '--reset', 'extra'], exit: 2 },+ { argv: ['search', 'tune', '--apply', '--help'], exit: 0, stdout: ROUTER_USAGE.search },+ { argv: ['cache', 'clear', '--yes', '--help'], exit: 0, stdout: ROUTER_USAGE.cache },+ { argv: ['cache', 'clear', '--yes', '--source'], exit: 2 },+ { argv: ['schema', 'downgrade', '--help'], exit: 0, stdout: ROUTER_USAGE.schema },+ { argv: ['schema', 'use', 'gbrain-base', '--help'], exit: 0, stdout: ROUTER_USAGE.schema },+ { argv: ['schema', 'use', 'gbrain-base', '--json'], exit: 2 },+ { argv: ['integrity', 'auto', '--help'], exit: 0, stdout: ROUTER_USAGE.integrity },+ { argv: ['integrity', 'reset-progress', 'now'], exit: 2 },+ { argv: ['hook', 'stop', '--help'], exit: 0, stdout: ROUTER_USAGE.hook },+ // A bare `help` in a free-text slot is a query, not a help request.+ { argv: ['search', 'help'], exit: 0, notStdout: ROUTER_USAGE.search, mayWrite: true },+ );+ // Every strict refusal's fix is a real read-only command: it runs, exits 0 and changes nothing.+ const fixes = new Set<string>();+ for (const spec of Object.values(STRICT_SUBCOMMANDS)) if ('argv' in spec.fix) fixes.add(JSON.stringify(spec.fix.argv));+ for (const f of fixes) cases.push({ argv: JSON.parse(f) as string[], exit: 0, connects: true });+ return cases;+}++export function gateCasesForPart(part: number): GateCase[] {+ return allGateCases().filter((_, i) => i % GATE_PARTS === part);+}++function offlineEnv(root: string, unsuppressed: boolean, log: string): Record<string, string> {+ const env: Record<string, string> = {};+ for (const [k, v] of Object.entries(process.env)) {+ if (v === undefined || k.startsWith('GBRAIN_') || /_API_KEY$|_API_TOKEN$/.test(k) || k === 'DATABASE_URL') continue;+ env[k] = v;+ }+ Object.assign(env, { HOME: root, GBRAIN_HOME: root, GBRAIN_NON_INTERACTIVE: '1', GBRAIN_NO_RETRY_CONNECT: '1', GBRAIN_TEST_SIDE_EFFECT_LOG: log,+ // Bun's own transpiler cache, kept outside HOME so the tree comparison sees only gbrain's writes.+ BUN_RUNTIME_TRANSPILER_CACHE_PATH: join(tmpdir(), 'gbrain-help-gate-bun-cache') });+ if (unsuppressed) delete env.NODE_ENV;+ else env.NODE_ENV = 'test';+ return env;+}++export async function runCli(root: string, argv: string[], unsuppressed = false): Promise<{ stdout: string; stderr: string; exitCode: number; effects: string[] }> {+ const log = join(root, '..', `${relative(tmpdir(), root).replace(/\W/g, '_')}.effects`);+ rmSync(log, { force: true });+ const proc = Bun.spawn(['bun', '--no-env-file', '--preload', PROBE, join(REPO, 'src/cli.ts'), ...argv], {+ cwd: join(root, 'work'), env: offlineEnv(root, unsuppressed, log), stdin: Bun.file('/dev/null'), stdout: 'pipe', stderr: 'pipe',+ });+ const killer = setTimeout(() => { try { proc.kill('SIGKILL'); } catch { /* gone */ } }, 60_000);+ try {+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);+ const effects = existsSync(log) ? readFileSync(log, 'utf8').split('\n').filter(Boolean) : [];+ return { stdout, stderr, exitCode, effects };+ } finally {+ clearTimeout(killer);+ }+}++const CONFIG = join('.gbrain', 'config.json');++/** Path → content hash for every file under `dir` (config.json with the copy's own root masked). */+function statTree(dir: string, base = dir, out = new Map<string, string>()): Map<string, string> {+ for (const name of readdirSync(dir)) {+ const p = join(dir, name);+ const rel = relative(base, p);+ if (statSync(p).isDirectory()) statTree(p, base, out);+ else out.set(rel, String(Bun.hash(rel === CONFIG ? readFileSync(p, 'utf8').replaceAll(base, '<ROOT>') : readFileSync(p))));+ }+ return out;+}++/** Logical brain fingerprint: an md5 of every public table's rows. */+async function brainFingerprint(root: string): Promise<Record<string, string>> {+ const engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite', database_path: join(root, '.gbrain', 'brain.pglite') });+ try {+ const tables = await engine.executeRaw<{ t: string }>("SELECT tablename AS t FROM pg_tables WHERE schemaname = 'public' ORDER BY 1");+ const out: Record<string, string> = {};+ for (const { t } of tables) {+ const [row] = await engine.executeRaw<{ h: string | null }>(`SELECT md5(string_agg(x::text, '|' ORDER BY x::text)) AS h FROM "${t}" x`);+ out[t] = row?.h ?? '';+ }+ return out;+ } finally {+ await engine.disconnect();+ }+}++export interface GateFixture {+ template: string;+ brain: Record<string, string>;+ tree: Map<string, string>;+}++/** Build the seeded template brain once per file. */+export async function buildFixture(): Promise<GateFixture> {+ const template = mkdtempSync(join(tmpdir(), 'gbrain-help-gate-'));+ mkdirSync(join(template, 'work'));+ const init = await runCli(template, ['init', '--pglite', '--no-embedding']);+ if (init.exitCode !== 0) throw new Error(`fixture init failed: ${init.stderr}`);+ const engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite', database_path: join(template, '.gbrain', 'brain.pglite') });+ try {+ // Seed rows directly with the managed-writer guard paused, then restore it.+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw(`INSERT INTO pages (source_id, slug, type, title, deleted_at) VALUES+ ('default', 'notes/old-deleted', 'note', 'old', now() - INTERVAL '200 hours'),+ ('default', 'notes/live', 'note', 'live', NULL)`);+ await engine.setConfig('search.cache.enabled', 'false');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ } finally {+ await engine.disconnect();+ }+ return { template, brain: await brainFingerprint(template), tree: statTree(template) };+}++export function copyFixture(fx: GateFixture, into: string): void {+ rmSync(into, { recursive: true, force: true });+ cpSync(fx.template, into, { recursive: true });+ // config.json names the brain by absolute path: point the copy at its own brain.+ const config = join(into, CONFIG);+ writeFileSync(config, readFileSync(config, 'utf8').replaceAll(fx.template, into));+}++/**+ * What changed after a case: tree paths outside the allow list and the brain+ * tables whose rows differ. The brain is compared logically only when its+ * files changed (WAL/lock churn without a row change is not a write).+ */+export async function changesSince(fx: GateFixture, root: string, connects = false): Promise<{ files: string[]; tables: string[] }> {+ const now = statTree(root);+ const changed = new Set<string>();+ for (const [p, v] of now) if (fx.tree.get(p) !== v) changed.add(p);+ for (const p of fx.tree.keys()) if (!now.has(p)) changed.add(p);+ const brainTouched = [...changed].some(p => p.startsWith('.gbrain/brain.pglite/'));+ const allow = connects ? [...TREE_ALLOW, ...CONNECT_ALLOW] : TREE_ALLOW;+ const files = [...changed].filter(p => !p.startsWith('.gbrain/brain.pglite/') && !allow.some(re => re.test(p))).sort();+ if (!brainTouched) return { files, tables: [] };+ const brain = await brainFingerprint(root);+ return { files, tables: Object.keys({ ...brain, ...fx.brain }).filter(t => brain[t] !== fx.brain[t]).sort() };+}++/** Runs `cases` on `workers` fixture copies; returns one failure line per case that acted. */+export async function runGate(fx: GateFixture, cases: GateCase[], workers = 4): Promise<string[]> {+ const failures: string[] = [];+ const queue = [...cases];+ const verbose = process.env.HELP_GATE_LOG;+ await Promise.all(Array.from({ length: workers }, async (_, w) => {+ const root = join(fx.template, '..', `${relative(tmpdir(), fx.template)}-w${w}`);+ copyFixture(fx, root);+ for (let c = queue.shift(); c; c = queue.shift()) {+ const r = await runCli(root, c.argv, c.unsuppressed);+ const problems: string[] = [];+ if (r.exitCode !== c.exit) problems.push(`exit ${r.exitCode} (want ${c.exit})`);+ if (c.stdout === null && !(r.stdout + r.stderr).trim()) problems.push('printed no usage');+ if (c.stdout && !r.stdout.includes(c.stdout)) problems.push(`stdout lacks ${JSON.stringify(c.stdout)}`);+ if (c.notStdout && r.stdout.includes(c.notStdout)) problems.push(`stdout has ${JSON.stringify(c.notStdout)}`);+ if (r.effects.length) problems.push(`side effects ${r.effects.join(' ; ')}`);+ if (!c.mayWrite) {+ const ch = await changesSince(fx, root, c.connects);+ if (ch.files.length) problems.push(`files changed ${ch.files.join(', ')}`);+ if (ch.tables.length) problems.push(`brain tables changed ${ch.tables.join(', ')}`);+ }+ if (problems.length || c.mayWrite) copyFixture(fx, root);+ const line = `gbrain ${c.argv.join(' ')}: ${problems.join('; ')}`;+ if (verbose) appendFileSync(verbose, `${problems.length ? 'FAIL' : 'ok '} ${line}${problems.length ? `\n stderr: ${r.stderr.trim().split('\n').slice(-2).join(' | ')}` : ''}\n`);+ if (problems.length) failures.push(line);+ }+ rmSync(root, { recursive: true, force: true });+ }));+ return failures.sort();+}diff --git a/test/helpers/cli-side-effect-probe.ts b/test/helpers/cli-side-effect-probe.tsnew file mode 100644index 0000000000..1c18327f4e--- /dev/null+++ b/test/helpers/cli-side-effect-probe.ts@@ -0,0 +1,44 @@+/**+ * Child-side side-effect probe for the help gate (#6114). Preloaded into the+ * CLI under test (`bun --preload <this> src/cli.ts ...`): every `fetch` and+ * every subprocess spawn (node:child_process goes through Bun.spawn) is+ * appended to GBRAIN_TEST_SIDE_EFFECT_LOG and blocked, so a help invocation+ * that would call a provider or start a process is recorded instead of+ * leaving the machine. The preflight's sanitizing re-exec (marked with+ * GBRAIN_CWD_ENV_QUARANTINED) is the one spawn allowed through.+ */+import { appendFileSync } from 'node:fs';++const log = process.env.GBRAIN_TEST_SIDE_EFFECT_LOG;++function record(kind: string, detail: string): void {+ if (log) appendFileSync(log, `${JSON.stringify({ kind, detail: detail.slice(0, 300) })}\n`);+}++function argvOf(first: unknown): string {+ if (Array.isArray(first)) return first.join(' ');+ if (first && typeof first === 'object' && Array.isArray((first as { cmd?: unknown }).cmd)) return ((first as { cmd: string[] }).cmd).join(' ');+ return String(first);+}++function isPreflightReexec(args: unknown[]): boolean {+ const opts = (Array.isArray(args[0]) ? args[1] : args[0]) as { env?: Record<string, string | undefined> } | undefined;+ return Boolean(opts?.env?.GBRAIN_CWD_ENV_QUARANTINED);+}++if (log) {+ const realFetch = globalThis.fetch;+ globalThis.fetch = Object.assign(async (input: unknown) => {+ record('fetch', String(input instanceof Request ? input.url : input));+ throw new Error('network blocked by the help gate probe');+ }, { preconnect: realFetch.preconnect }) as typeof fetch;++ for (const name of ['spawn', 'spawnSync'] as const) {+ const real = Bun[name] as (...a: unknown[]) => unknown;+ (Bun as unknown as Record<string, unknown>)[name] = (...args: unknown[]) => {+ if (isPreflightReexec(args)) return real(...args);+ record(name, argvOf(args[0]));+ throw new Error('subprocess blocked by the help gate probe');+ };+ }+}diff --git a/test/pages-purge-deleted-args.test.ts b/test/pages-purge-deleted-args.test.tsnew file mode 100644index 0000000000..35cb8c2705--- /dev/null+++ b/test/pages-purge-deleted-args.test.ts@@ -0,0 +1,142 @@+/**+ * `gbrain pages purge-deleted` argument safety (#6114, D6).+ *+ * The purge is a brain-wide hard delete. Before this fix the handler read+ * only the flags it knew and ignored everything else: a positional `help`,+ * `--source <id>`, a bare `--older-than` and `--older-than=N` all ran the+ * default 72h purge. Now help never acts, any token the purge would ignore+ * refuses with `invalid_params` before the engine is touched, and the real+ * purge asks first (TTY prompt, `--yes`, or exit 3 with the consent payload).+ */+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { parsePurgeArgs, runPages } from '../src/commands/pages.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;++async function slugs(): Promise<string[]> {+ const rows = await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages ORDER BY slug');+ return rows.map(r => r.slug);+}++async function seed(): Promise<void> {+ await engine.executeRaw('DELETE FROM pages');+ await engine.executeRaw(`INSERT INTO pages (source_id, slug, type, title, deleted_at) VALUES+ ('default', 'notes/old-deleted', 'note', 'old', now() - INTERVAL '200 hours'),+ ('default', 'notes/live', 'note', 'live', NULL)`);+}++/** Runs `pages <args>` with stdout captured; returns what it printed. */+async function run(args: string[], eng: PGLiteEngine | null = engine): Promise<string> {+ const lines: string[] = [];+ const log = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { lines.push(a.join(' ')); });+ const write = spyOn(process.stdout, 'write').mockImplementation(((chunk: unknown) => { lines.push(String(chunk)); return true; }) as never);+ const err = spyOn(console, 'error').mockImplementation(() => {});+ try {+ await withEnv({ GBRAIN_NON_INTERACTIVE: '1' }, () => runPages(eng as never, args));+ } finally {+ log.mockRestore(); write.mockRestore(); err.mockRestore();+ }+ return lines.join('\n');+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => { await engine.disconnect(); });++beforeEach(async () => {+ _resetCliExitVerdictForTests();+ await seed();+});++describe('parsePurgeArgs', () => {+ test('accepts the documented forms', () => {+ expect(parsePurgeArgs([])).toEqual({ olderThanHours: 72, dryRun: false, json: false });+ expect(parsePurgeArgs(['--older-than', '720'])).toMatchObject({ olderThanHours: 720 });+ expect(parsePurgeArgs(['--older-than=720'])).toMatchObject({ olderThanHours: 720 });+ expect(parsePurgeArgs(['--older-than', '3d', '--dry-run', '--json'])).toEqual({ olderThanHours: 72, dryRun: true, json: true });+ expect(parsePurgeArgs(['--older-than=0h', '--yes'])).toMatchObject({ olderThanHours: 0 });+ });++ test.each([+ [['help'], 'help'],+ [['--source', 'x'], '--source'],+ [['--source=x'], '--source=x'],+ [['--older-than'], '--older-than'],+ [['--older-than', 'help'], 'help'],+ [['--older-than='], '--older-than='],+ [['--older-than', '1', '--older-than', '2'], '--older-than'],+ [['--dry-run=yes'], '--dry-run=yes'],+ [['--force'], '--force'],+ ])('refuses %p naming %p, with a read-only fix', (args, token) => {+ let caught: unknown;+ try { parsePurgeArgs(args as string[]); } catch (e) { caught = e; }+ expect(caught).toBeInstanceOf(OperationError);+ const e = caught as OperationError;+ expect(e.code).toBe('invalid_params');+ expect(e.message).toContain(`\`${token}\``);+ expect(e.why).toContain('Nothing was changed');+ expect(e.fix?.argv).toEqual(['gbrain', 'pages', 'purge-deleted', '--dry-run', '--json']);+ expect(parsePurgeArgs(e.fix!.argv!.slice(3))).toMatchObject({ dryRun: true });+ });++ test('--source names the brain-wide scope', () => {+ expect(() => parsePurgeArgs(['--source', 'default'])).toThrow(OperationError);+ try { parsePurgeArgs(['--source', 'default']); } catch (e) {+ expect((e as OperationError).why).toContain('per-source purge is not supported');+ }+ });+});++describe('runPages', () => {+ test.each([[['--help']], [['-h']], [['help']], [['purge-deleted', '--help']], [['purge-deleted', '-h']],+ [['purge-deleted', 'help']], [['purge-deleted', '--older-than', '--help']], [['purge-deleted', '--source', 'x', '-h']]])(+ '%p prints usage without an engine and purges nothing', async (args) => {+ expect(await run(args as string[], null)).toContain('purge-deleted [--older-than');+ expect(await slugs()).toEqual(['notes/live', 'notes/old-deleted']);+ });++ test('refused arguments leave every page in place', async () => {+ for (const args of [['purge-deleted', 'extra', '--yes'], ['purge-deleted', '--source', 'x', '--yes'], ['purge-deleted', '--older-than', '--yes'], ['purge-deleted', '--older-than', 'help', '--yes']]) {+ await expect(run(args)).rejects.toBeInstanceOf(OperationError);+ }+ expect(await slugs()).toEqual(['notes/live', 'notes/old-deleted']);+ });++ test('--older-than=N narrows the purge instead of falling back to 72h', async () => {+ await run(['purge-deleted', '--older-than=9999', '--yes']);+ expect(await slugs()).toEqual(['notes/live', 'notes/old-deleted']);+ });++ test('D6: without --yes and no TTY it exits 3 with the consent payload and purges nothing', async () => {+ const out = await run(['purge-deleted', '--json']);+ expect(currentExitCode()).toBe(3);+ const doc = JSON.parse(out.slice(out.indexOf('{'))) as { code: string; user_message: string; fix: { next: string; argv: string[] }; preview: { argv: string[] } };+ expect(doc.code).toBe('confirmation_required');+ expect(doc.fix.next).toBe('ask_user');+ expect(doc.user_message).toContain('1 page(s)');+ expect(doc.user_message).toContain('every source');+ expect(doc.fix.argv).toEqual(['gbrain', 'pages', 'purge-deleted', '--older-than', '72h', '--json', '--yes']);+ expect(doc.preview.argv).toEqual(['gbrain', 'pages', 'purge-deleted', '--older-than', '72h', '--dry-run', '--json']);+ expect(await slugs()).toEqual(['notes/live', 'notes/old-deleted']);+ });++ test('with --yes it purges; --dry-run never needs it', async () => {+ expect(await run(['purge-deleted', '--dry-run'])).toContain('Would purge 1 page(s)');+ expect(currentExitCode()).toBe(0);+ expect(await run(['purge-deleted', '--yes'])).toContain('Purged 1 page(s)');+ expect(await slugs()).toEqual(['notes/live']);+ });++ test('nothing to purge needs no confirmation', async () => {+ expect(await run(['purge-deleted', '--older-than', '9999'])).toContain('No pages to purge');+ expect(currentExitCode()).toBe(0);+ });+});