Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

skills: runtime skill health (gbrain skillpack health, doctor skill_health)

garrytan0fe8da0a6b8e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0f6ee23392..bd41d3d8f3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,6 +25,16 @@ Every `gbrain ...` invocation a bundled skill shows now runs through the dispatc
| A SKILL.md grows past its ceiling, or a new one passes 16 KB | passed | fails; raising a ceiling is a reviewer-visible edit |
| `skills-commit-gate.sh` | four checks | also runs the skill health guard and prints `Skill-size:` lines for staged skills |
+**Installed skills get the same health check at runtime.**
+
+`gbrain skillpack health [<skill>]` checks the skills an agent actually loads (the harness or workspace skills folder, else the bundled skills) for size against budget, growth past 10% over the last diet, description size, missing triggers, and `gbrain` commands, flags or tools this gbrain does not have. Each finding names what it saw, what it expected, the fix (for an unedited copy of a bundled skill, `gbrain skillpack reference <skill>` first) and a verify command. It reads files only, so a brain with no git repository gets the same report. Folders without a skills manifest or `skills.lock.json` are checked only for copies of gbrain's bundled skills.
+
+| Situation | Before | Now |
+|---|---|---|
+| An installed skill still shows a flag a newer gbrain removed | an agent following it got an error | `gbrain doctor` warns (`skill_health`) with the line and the fix |
+| An installed skill grew well past its last diet | nothing reported | `gbrain skillpack health` reports it; doctor shows it without warning |
+| `gbrain maintain`, `gbrain skillpack-check` | no skill information | one-line skill health summary (`skill_health` in skillpack-check's JSON) |
+
## [0.60.474.0] - 2026-10-27
**A database role that can't read the writer state is now refused instead of let through.**
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index eadbcbc925..c259ec5e1d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -636,6 +636,8 @@ loads, place every fact on its level, cut what the model already knows, and
keep the slim version only if a blinded before/after eval on tasks written
before cutting shows agents do at least as well. Then set its row's
`last_diet_bytes` and lower the ceiling to the new size plus 10%.
+`gbrain skillpack health <skill>` applies the same limits to an installed
+copy and prints the fix for each finding.
**Verify** by rerunning the case that prompted the change in a fresh session,
plus any test that asserts the skill's text.
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.md
index 2aca357867..2b9203ca4c 100644
--- a/docs/architecture/key-files/agent-contract.md
+++ b/docs/architecture/key-files/agent-contract.md
@@ -14,6 +14,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-
- `src/cli/cli-error.ts` — the CLI's one error writer (D1): `writeCliError`/`exitCliError` render through `renderCliError` (human `Error [code]` / `Fix:` / `Why:` / `Docs:` on stderr; under `--json` one envelope on stdout plus the human lines on stderr) and record the code for the guard's fallback document; a `legacy` shape (unknown flag's `{status, reason:'invalid_flag', message}`, `pglite_busy`'s `next_action`) leads, keeps its values and stays one line. `usageError` (`invalid_params` / `unknown_flag` / `unknown_command`, exit 2), `unknownFlagError` (did-you-mean from the command's curated help flags, else the acceptance registry), `writeFatalCliError` (the `import.meta.main` seam; keeps the `GBRAIN_DB_ACCESS` marker + remediation on human output; a `pglite_busy` with reason `legacy_owner_unverified` renders its own ask_user fix, `retryable: false`, exit 3). Test: `test/cli-error-render.test.ts`.
- `src/cli/help/<command>.ts` + `src/cli/help/render.ts` + `src/cli/help/validate.ts` — D3/D4 curated CLI help. Each spec module exports `help: CliHelpSpec` (`summary`, `usage`, `flags: [{name, type: boolean|string|number|enum, values?, desc, consent?}]`, 2–4 `examples`, `end_of_options?`) and is loaded lazily through its command-table record's `help: () => import('./help/<name>.ts')` (literal, so `bun build --compile` bundles it and `gbrain --version` loads none; pinned by `test/cli-command-table.test.ts` and `scripts/check-compile-autoload.sh`). Curated today: doctor, import, serve, apply-migrations, autopilot, status, onboard; every curated flag must be in the generated acceptance registry and `--yes` is listed wherever the handler parses it. `printCuratedHelp` answers `gbrain <cmd> --help`/`-h` first in main()'s help short-circuit, engine-free (human table with type/values/consent; `--help --json` one document `{command, …spec, contract_version}`). `curatedFlagError(command, args)` (called in main() after the unknown-flag check) refuses a missing/non-numeric `number` value or an out-of-set `enum` value with `invalid_params` (exit 2) via `flagValueError`, example value drawn from the spec's examples; `--flag=value` and `--flag value`, stops at a bare `--`; `string` flags (e.g. onboard's `--max-usd off`) are not checked. `unknownFlagError` draws did-you-mean candidates from the curated flags. Tests: `test/cli-help-curated.test.ts`, `test/cli-help-curated-cli.test.ts`.
- `src/cli/flag-values.ts` — strict numeric values for CLI-only flags (D4): `intFlagValue` / `numberFlagValue` (digits only, safe integer, `[min, max]`) and `flagValueError` raise `invalid_params` usage errors (exit 2) naming the flag, what it accepts and an example. Used by jobs submit, extract-conversation-facts, eval run-all, sync `--interval`, connectors sync, book-mirror (the absorbed community fixes #5936 #5934 #5933 #5931 #5930 #5909). Tests: each command's `*-numeric-flags`/`*-flags` test.
+- `src/cli/flag-validation.ts` — the pre-dispatch unknown-flag validator (`validateCommandFlags`, `findUnknownOpFlag`) and the CLI alias table (`buildCliAliases`, `cliAliases`), moved verbatim out of `src/cli/main.ts`, which re-exports them. `src/cli/skill-surface.ts` imports them from here, so the skill drift surface never imports the dispatcher; main registers that surface with `setSkillSurfaceProvider` (`src/core/skill-health.ts`) so doctor, which the operations graph also loads, checks skill drift without importing the command table. Pinned by `test/cli-flag-validation.test.ts`.
- `src/cli/flag-equals.ts` — `--flag=value` on CLI_ONLY commands (#7619). `cliOnlyFlagArgs` in `src/cli/main.ts` runs `splitFlagEquals` once after routing and the help printers that run no handler, before the self-help handlers' help path, strict arguments, flag validation and dispatch, so no `=` token reaches a handler that would drop it. It also covers the hand-parsed `search modes|stats|tune|diagnose` subcommands, the validation-exempt paths (`jobs submit`, whose consent check reads the `=` spending cap, and `config` except `set`) and the direct `bun run src/commands/auth.ts` entry (which strips and applies the global flags, hands `auth local-writer` to its own parser and runs the unknown-flag validator, `findUnknownFlag` with the same `unknown_flag` envelope and legacy keys, all as main does). Per registered `--flag=value` token: a switch refuses (`invalid_params`, exit 2: a boolean in the command's own table, curated help or `SYNC_FLAGS` for sync, a `--no-` negation, the command's `COMMAND_SWITCHES`, or a name `knownSwitches()` finds boolean in the handler-free `OPERATION_MANIFEST` or any curated help, so `--yes=n` is never answered with `--yes <value>`); `EQUALS_READERS`, keyed by command or `command sub` (the `sync --status` alias reads as `sync status`, `forget --purge` is its own path, and `repos` reads the `sources` keys through `READER_ALIASES`), keeps the token where the handler on that path reads the `=` form itself, empty values included (that handler owns refusing them); elsewhere an empty or flag-like value refuses; the token splits into `--flag value` only when the command's own table declares a value; every other `=` form refuses with the two-argument spelling. Splitting a flag the subcommand never reads leaves its value as a stray positional that handlers taking the first numeric or non-flag token act on (`forget --purge --reason=3 34` purging fact 3), and a reader key wider than its path drops the token in sibling subcommands (`extract links --source-id=x` walked every source), so keys name the narrowest path. A short flag never takes `=` (`-y=n` refuses). A bare `--` ends the scan only on `END_OF_OPTIONS` paths (`agent run`, `frontmatter validate`), whose handler stops there; `serve`, `auth`, `frontmatter generate`, `questions` and `agent logs` read flags after it, so past `--` an `=` token that is not a registered flag refuses (the unknown-flag validator stops at `--`). A true/false word or 0/1 on a flag with no table entry (`--apply=false`, `--expect=on`) refuses naming both readings, never `--apply <value>`, and says a value never turns a switch off. `sources pull --path=` refuses, because main's database-free route matches only the exact token. On the hand-parsed `search` subcommands, which have no registry row, every `=` token but `--json=true` refuses with a neutral message that names the subcommand, echoes no value and vouches for no switch. `--json=true` becomes `--json`. Refusals name `--flag=…`, never the value. `OWN_EQUALS_PARSERS` (own `=`-aware parsers on every path that refuse `=` on their switches, `retrieval-upgrade` and `migrate embeddings` included; not the sources lifecycle subcommands, whose unmanaged fallback reads exact tokens), `call`, `config set`, `eval brainbench` and every subcommand `src/cli/strict-args.ts` governs (`strictSpecFor`) keep their argv. `scripts/generate-flag-registry.ts` skips this module. Pinned by `test/cli-flag-equals.test.ts` (a table over every registered CLI_ONLY flag, both-direction pins of `EQUALS_READERS` against every `=` reader in `src` and of `OWN_EQUALS_PARSERS` against every `=` option parser, stray-positional, dropped-scope, consent and `--` rows, own-parser switch refusals) and `test/serve-flag-equals.test.ts` (real CLI processes on PGLite, `--json` envelope, the direct `auth.ts` entry, `serve -- --access=` and `frontmatter generate` behind `--help` or `--` included).
- `src/cli/search-timings.ts` — `gbrain search|query --timings` (#7158; global flag claimed by search/query/ask in `cli-options.ts`): `timeCliPhase` books `connect`, `context` and `remote` in `runSharedOperation`/`runThinClientRouted`; `searchTimingsDocument` makes `--json` print `{results, timings_ms, cost}` (bare array without the flag) and `searchTimingsLine` the stderr line. Absent phase = did not run. Guide: `docs/guides/search-explain.md`. Test: `test/cli-search-timings.test.ts`.
- `src/cli/op-param-values.ts` — `opParamValue`: typed values for shared ops from `ParamDef` inside `parseOpArgs` (number → finite, string enum → declared values), `invalid_params` with an example otherwise; mirrors MCP `validateParams`. `opStructuredValue` turns object/array flag text into its value: JSON, or for a string-item array a bare value or comma list (`--types company`, `--types person,company`, #7173); `test/cli-types-param.test.ts`. `parseOpArgs` also honours a bare `--` (D6). Test: `test/cli-op-typed-args.test.ts`.
diff --git a/docs/architecture/key-files/skills.md b/docs/architecture/key-files/skills.md
index 0e4cbe346b..e7b6211abf 100644
--- a/docs/architecture/key-files/skills.md
+++ b/docs/architecture/key-files/skills.md
@@ -15,6 +15,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/skill-drift.ts`, `src/cli/skill-surface.ts`, `scripts/check-skill-health.ts` — skill drift and size guard (`bun run check:skill-health`, in verify and `scripts/skills-commit-gate.sh`). `extractInvocations` reads every `gbrain ...` invocation in shell fences and inline code (placeholders kept as one token, `<!-- skill-drift-ok: reason -->` skips a line or the line after it); `analyzeSkillDrift` runs each through the injected `CliSurface`, which is the dispatcher's own code (`CLI_ONLY`, `cliOps`/`cliAliases`, `ROUTERS` subcommand inventories, `parseGlobalFlags`, `validateCommandFlags`; a router subcommand of an op command checks against `CLI_FLAG_REGISTRY`), so a skill passes exactly when the CLI would accept the invocation. Subcommands are verified only for commands with a declared inventory; the rest are counted as not declared, never reported as drift. Operation-shaped frontmatter `tools:` entries (snake_case or `mcp:`) must be real operations (`web_fetch`/`web_search` are host tools). Size: a SKILL.md over 16384 bytes needs a `skills/skill-budgets.tsv` row and stays under its ceiling; descriptions stay within 1024 bytes; a row for a skill back under the cap with no diet recorded is stale. `scripts/skill-drift-baseline.txt` is shrink-only. `--sizes <files>` prints the `Skill-size:` lines the commit gate shows. Pinned by `test/skill-drift.test.ts` and the `test/fixtures/guards/check-skill-health.ts/` bad-<variant> fixtures.
+- `src/core/skill-health.ts`, `src/commands/skillpack/health.ts`, `src/commands/doctor/checks/skill-health.ts` — runtime skill health (`gbrain skillpack health`, doctor `skill_health`, a `gbrain maintain` line, `skillpack-check`'s `skill_health` field). `computeSkillHealth` checks one skills folder: bytes against the bundle's `skills/skill-budgets.tsv` row (else the 16384-byte cap), growth past 110% of `last_diet`, description bytes, frontmatter `triggers:`, and `analyzeSkillDrift` over every markdown file in the skill with the live `cliSurface()`. Each finding has `code`, `observed`, `expected`, `fix` and `verify`. Scope: a folder with `manifest.json` or `skills.lock.json` (`isManagedSkillsDir`) checks every skill; otherwise only copies of bundled slugs (`bundled_copies`), else nothing (`not_gbrain`, doctor reports info / not_applicable). Files only: no git, database or model calls. The doctor check warns only on drift. `parseSkillBudgets` and the caps are shared with `scripts/check-skill-health.ts`. Pinned by `test/skill-health.test.ts` (including 100 skills under 500 ms).
+
- `src/core/skill-catalog.ts` — legacy host-repo fallback for MCP `list_skills` / `get_skill`. Canonical schema-version-2 discovery uses [shared brain skills](shared-skills.md); version 1 also uses the canonical compatibility layer when that catalog is active. This module serves the remaining host-catalog fallback, not canonical revision discovery. `buildSkillCatalog(ctx, dir, source, { section, query, limit, gateDisabled })` builds the catalog after the publish gate and confinement; with `query` (#6471) it ranks the section-filtered entries by `scoreSkillMatch` (lexical token overlap: trigger tokens ×2, a whole trigger phrase inside the query ×4, name tokens ×3, description tokens ×1; no model call), drops zero-score entries, breaks ties by name, caps at `limit` (default 10, max 100) and sets `match: { score, matched_on }` per entry; without `query` the output is byte-identical to the unranked build. The `list_skills` op refuses `query` with `invalid_params` on the schema-version-2 and active shared-catalog routes before any catalog read (`ops/skills-catalog.ts`); `query` is advertised on the full MCP surface only (`fullSurfaceOnly`) so the starter list keeps its size budget. Pinned by `test/list-skills-query-6471.test.ts`. Lets a thin MCP client (Codex desktop, Claude Code, Claude Cowork, Perplexity) DISCOVER + FOLLOW the agent repo's fat-markdown skills over `gbrain serve` — a skill is prose, so "using" one = fetching its body then calling the gbrain MCP tools the server already exposes. Read-scope, NOT localOnly (defensible only via the full mitigation stack): (1) **publish gate** — `assertPublishEnabled(ctx, publishSkills)`; remote callers require `mcp.publish_skills === true`, default-OFF so an upgrade never silently grants existing read tokens host-skill read; local callers (`ctx.remote === false`) always pass. (2) **path confinement** — `assertSkillNameShape` rejects separators/`..`/null/space before any FS access; the client `name` is a manifest LOOKUP KEY (via `loadOrDeriveManifest`), never a raw path segment; `confineManifestPath` does realpath + relative-containment + `SKILL.md`-regular-file check on EVERY entry (defeats poisoned manifest.json `path`, symlink/`..` escape). (3) **frontmatter allowlist** — `GetSkillResult.frontmatter` projects a safe subset; private `writes_to` + `sources` dropped. (4) **prose-only + 256KB cap** (`MAX_SKILL_MD_BYTES`, env `GBRAIN_MAX_SKILL_MD_BYTES`), size-checked twice (statSync + UTF-8 byte length). (5) **no install_path serve for remote** — remote callers use `autoDetectSkillsDir` (no install-path tier) so a hosted gbrain with no agent repo returns `storage_error`; local callers use `autoDetectSkillsDirReadOnly`. (6) MCP rate-limiter caps call rate. Config reads honor BOTH planes: `readMcpPublishSkills` / `readMcpSkillsDir` prefer the DB plane (`engine.getConfig`) over the file plane (`ctx.config.mcp`). Tool-honesty: `resolveSkillTools` shares list/detail semantics: declared `tools:` narrow the caller's effective inventory via `crossReferenceTools`; valid mapping frontmatter that omits `tools` inherits `availableBrainTools(ctx)` without granting new permissions. Explicit `tools: []` stays empty; invalid tools values, malformed YAML, and missing frontmatter never receive the inherited inventory. The operation handlers resolve current DB/file publication gates through `disabledOpsForPublishGates` before building either response; unpublished operations are excluded from declared and inherited tools and both instruction envelopes. `opAllowedForBoundClient` also applies the same operation grants, slug-bound write fences, and degraded-projection policy as dispatch. Pure catalog calls without resolved gates conservatively hide gated operations from remote callers. The list's `tools` remains the declared list (empty when omitted), while `usable_tools` carries the effective inventory. Pinned by `test/skill-catalog-optional-tools.test.ts`. `buildSkillCatalog`'s `instructions` envelope (`SKILL_CATALOG_INSTRUCTIONS`) carries the "these are prose, follow-then-call-tools" protocol. These fallback skills are host-filesystem repo-global — `sourceScopeOpts(ctx)` / `ctx.brainId` deliberately do NOT apply. `buildSkillCatalog` is resilient (one malformed/escaping skill is skipped, never throws). Config keys in `src/core/config.ts`: `GBrainConfig.mcp?: { publish_skills?, skills_dir? }` + `KNOWN_CONFIG_KEYS` entries `mcp.publish_skills`/`mcp.publish_skills_prompted`/`mcp.skills_dir` + `mcp.` prefix in `KNOWN_CONFIG_KEY_PREFIXES`. `src/commands/init.ts` writes `config.mcp = { publish_skills: true, ... }` for new installs (existing config wins on re-init). `src/commands/upgrade.ts:runPostUpgrade` adds a one-time consent prompt (gated by `mcp.publish_skills_prompted`; existing installs stay OFF until owner opts in). The legacy catalog entrypoints in `src/core/ops/skills-catalog.ts` (spread into the `operations.ts` façade) are: `list_skills` with optional `section` filter + `cliHints:{name:'skills'}`; `get_skill` taking `name` (+ `source_id` for brain-resident packs) + `cliHints:{name:'skill', positional:['name']}`; `list_brain_skillpack`. They dynamically import this module to avoid the import cycle (skill-catalog statically imports the `operations` array). Descriptions in `src/core/operations-descriptions.ts` (`LIST_SKILLS_DESCRIPTION`, `GET_SKILL_DESCRIPTION`, `SKILL_CATALOG_INSTRUCTIONS`, `SKILL_CLIENT_GUIDANCE`), pinned by `test/operations-descriptions.test.ts`. CLI: `gbrain skills` / `gbrain skill <name>`. Pinned by `test/skill-catalog.test.ts`, `test/skill-catalog-security.test.ts` (path-confinement / poisoned-manifest / symlink-escape), `test/skill-catalog-transports.test.ts` (publish-gate + remote-vs-local) over `test/fixtures/skill-catalog/`.
- `src/core/skill-fix-gates.ts` — shared safety primitives for `dry-fix.ts`. `getWorkingTreeStatus(file)` 3-state (`'clean' | 'dirty' | 'not_a_repo'`); `isInsideCodeFence(content, offset)`; `findAfterH1Paragraph(content)` (canonical insertion offset for the auto-inserted Convention callout). Both REPLACE expanders (DRY violations) and the INSERT expander (MISSING_RULE_PATTERNS) consume from here so the install-path refusal and dirty-tree gates apply uniformly. `src/core/dry-fix.ts` re-exports them.
diff --git a/docs/guides/skillpacks-as-scaffolding.md b/docs/guides/skillpacks-as-scaffolding.md
index 62294f743e..f1a69d18b8 100644
--- a/docs/guides/skillpacks-as-scaffolding.md
+++ b/docs/guides/skillpacks-as-scaffolding.md
@@ -83,6 +83,23 @@ from "you changed X." Applied hunks align everything to gbrain. Use
`--dry-run` first to preview, or run plain `reference` to inspect the
diff before letting auto-apply touch anything.
+### `gbrain skillpack health [<skill>] [--skills-dir PATH] [--json] [--strict]`
+
+Read-only. For the active skills folder (the harness or workspace skills
+dir, else the bundled skills) it reports each skill's bytes against its
+budget, growth past 10% over its last diet, description size, missing
+frontmatter triggers, and every `gbrain` command, flag or tool the skill
+shows that this gbrain does not have. Each finding carries what was
+observed, what was expected, the edit or command that fixes it (for an
+unedited copy of a bundled skill, `gbrain skillpack reference <skill>`
+first) and a verify command. A folder with no skills manifest or
+`skills.lock.json` is checked only for copies of gbrain's bundled skills,
+so other agents' skills are never reported. It reads files only, so it
+works the same on a brain with no git repository.
+
+`gbrain doctor` runs it as `skill_health` (it warns only on drift),
+`gbrain maintain` and `gbrain skillpack-check` print its one-line summary.
+
### `gbrain skillpack migrate-fence [--workspace PATH] [--dry-run]`
One-shot conversion for workspaces still on the legacy managed-block
@@ -259,6 +276,8 @@ gbrain skillpack remove --harness claude-code --skill query
- **gbrain shipped a new version, want to see what's changed**
→ `reference` (read-only) or `reference --apply-clean-hunks` (auto);
for harness installs → `reference --harness <h>`
+- **Find skills that grew too big or show commands this gbrain doesn't
+ have** → `health` (read-only)
- **Upgrading from the legacy managed-block model** → `migrate-fence` (one-shot)
- **Cleanup after `migrate-fence`** → `scrub-legacy-fence-rows`
- **Lift your fork's skill back into gbrain** → `harvest` + the
diff --git a/plugin/skills/skillpack-check/SKILL.md b/plugin/skills/skillpack-check/SKILL.md
index a4bdb3777e..22afcb5180 100644
--- a/plugin/skills/skillpack-check/SKILL.md
+++ b/plugin/skills/skillpack-check/SKILL.md
@@ -35,6 +35,7 @@ Running `gbrain skillpack-check` returns a JSON report with:
data, not authority.
- **`doctor`**: full `gbrain doctor --fast --json` output (filesystem checks).
- **`migrations`**: applied/pending/partial counts from `apply-migrations --list`.
+- **`skill_health`** (string): skill size, growth and drift in one line; `gbrain skillpack health` lists each fix.
Exit code:
- `0` — healthy, nothing to do.
diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjs
index 651648b2e2..4fd946fb5b 100644
--- a/scripts/check-orphan-modules.mjs
+++ b/scripts/check-orphan-modules.mjs
@@ -59,8 +59,6 @@ const PERMITTED_TEST_ONLY = [
{ path: 'src/eval/longmemeval/evidence-packet.ts', reason: 'script-reachable' },
{ path: 'src/eval/longmemeval/locomo.ts', reason: 'script-reachable' },
{ path: 'src/core/write-gate-scan.ts', reason: 'script-reachable' },
- { path: 'src/core/skill-drift.ts', reason: 'script-reachable' },
- { path: 'src/cli/skill-surface.ts', reason: 'script-reachable' },
{ path: 'src/eval/shared/autocut-replay.ts', reason: 'script-reachable' },
{ path: 'src/mcp/http-transport.ts', reason: 'script-reachable' },
{ path: 'src/mcp/tool-catalog.ts', reason: 'script-reachable' },
diff --git a/scripts/check-skill-health.ts b/scripts/check-skill-health.ts
index 70fe6f442c..5e3ca0fb88 100644
--- a/scripts/check-skill-health.ts
+++ b/scripts/check-skill-health.ts
@@ -25,9 +25,8 @@ import { join, relative, resolve } from 'node:path';
import { execFileSync } from 'node:child_process';
import { analyzeSkillDrift, descriptionBytes } from '../src/core/skill-drift.ts';
import { cliSurface } from '../src/cli/skill-surface.ts';
+import { DESCRIPTION_CAP, NEW_SKILL_CAP, parseSkillBudgets } from '../src/core/skill-health.ts';
-const NEW_SKILL_CAP = 16_384;
-const DESCRIPTION_CAP = 1_024;
const ROOT = process.env.GBRAIN_GUARD_ROOT ? resolve(process.env.GBRAIN_GUARD_ROOT) : resolve(import.meta.dir, '..');
const SKILLS = join(ROOT, 'skills');
const BASELINE = join(ROOT, 'scripts', 'skill-drift-baseline.txt');
@@ -78,16 +77,9 @@ for (const key of baseline) {
}
// Size
-const rows = new Map<string, { max: number; lastDiet: number | null }>();
-if (existsSync(BUDGETS)) {
- for (const line of readFileSync(BUDGETS, 'utf8').split('\n')) {
- if (!line.trim() || line.startsWith('#')) continue;
- const [skill, max, lastDiet] = line.split('\t');
- if (!skill || !/^\d+$/.test(max ?? '')) { failures.push(`SKILL_BUDGET_ROW_INVALID skills/skill-budgets.tsv '${line}'\n fix: write <skill>\t<max bytes>\t<last diet bytes or ->\t<note>`); continue; }
- if (rows.has(skill)) failures.push(`SKILL_BUDGET_ROW_DUPLICATE skills/skill-budgets.tsv '${skill}'\n fix: keep one row per skill`);
- rows.set(skill, { max: Number(max), lastDiet: lastDiet && /^\d+$/.test(lastDiet) ? Number(lastDiet) : null });
- }
-}
+const { rows, invalid, duplicates } = parseSkillBudgets(existsSync(BUDGETS) ? readFileSync(BUDGETS, 'utf8') : '');
+for (const line of invalid) failures.push(`SKILL_BUDGET_ROW_INVALID skills/skill-budgets.tsv '${line}'\n fix: write <skill>\t<max bytes>\t<last diet bytes or ->\t<note>`);
+for (const skill of duplicates) failures.push(`SKILL_BUDGET_ROW_DUPLICATE skills/skill-budgets.tsv '${skill}'\n fix: keep one row per skill`);
const skillFiles = files.filter(f => f.endsWith('/SKILL.md'));
const present = new Set<string>();
for (const file of skillFiles) {
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index bfa01bceb3..b776fd1c72 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,7 +3,7 @@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
-src/cli/main.ts 2956 ratchet +1 #7619: the --flag=value gate call after the handler-free help printers, covering the hand-parsed search subcommands and the exact-token validation-exempt paths (logic, findUnknownFlag included, in cli/flag-equals.ts); +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe); +1 GBRA-133 PR 2a merge: master and the sync trigger serve hand-off each added a dispatch row; +1 GBRA-154 #7171: captureRetrievalNotices call after a search/query op (logic in cli/op-notices.ts); GBRA-151 operability wave x v0.60.332.0 merge: both sides added a line, re-summed (3020 measured); GBRA-151 #7147 follow-up (cold one-shot read snapshot handoff and pool cap) re-summed at the v0.60.333.0 merge (3027 measured); +1 GBRA-156 warm CLI socket: one gated dispatch call before CLI_ONLY (logic in cli/cli-socket-client.ts); -11 GBRA-156: MERGED_CONFIG_BY_ENGINE and its comment moved to core/published-config.ts (serve reads it); lowered at the v0.60.340.0 merge (3018 measured); +5 #7191: search --exact routing call (dispatch, cannot move; rule in cli/command-route.ts) and the search_exact formatter case + imports; +3 GBRA-156 warm CLI startup: page-render, volunteer and operation-load imported lazily where used, so a warm socket hit loads 169 modules instead of 709 (2955 measured)
+src/cli/main.ts 2830 ratchet +1 #7619: the --flag=value gate call after the handler-free help printers, covering the hand-parsed search subcommands and the exact-token validation-exempt paths (logic, findUnknownFlag included, in cli/flag-equals.ts); +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe); +1 GBRA-133 PR 2a merge: master and the sync trigger serve hand-off each added a dispatch row; +1 GBRA-154 #7171: captureRetrievalNotices call after a search/query op (logic in cli/op-notices.ts); GBRA-151 operability wave x v0.60.332.0 merge: both sides added a line, re-summed (3020 measured); GBRA-151 #7147 follow-up (cold one-shot read snapshot handoff and pool cap) re-summed at the v0.60.333.0 merge (3027 measured); +1 GBRA-156 warm CLI socket: one gated dispatch call before CLI_ONLY (logic in cli/cli-socket-client.ts); -11 GBRA-156: MERGED_CONFIG_BY_ENGINE and its comment moved to core/published-config.ts (serve reads it); lowered at the v0.60.340.0 merge (3018 measured); +5 #7191: search --exact routing call (dispatch, cannot move; rule in cli/command-route.ts) and the search_exact formatter case + imports; +3 GBRA-156 warm CLI startup: page-render, volunteer and operation-load imported lazily where used, so a warm socket hit loads 169 modules instead of 709 (2955 measured); -126 GBRA-225 skill health: validateCommandFlags, findUnknownOpFlag and the alias table moved verbatim to cli/flag-validation.ts (re-exported), so the skill drift surface never imports the dispatcher (2830 measured)
src/commands/autopilot.ts 1662 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts); +8 GBRA-130 C-6/A-10: the --retry-global mode row, help line and --phase value flag, and --status reading the brain-wide maintenance verdict into its JSON, text and exit code (logic in core/minions/global-maintenance-stall.ts and autopilot-retry-global.ts); +12 GBRA-133 #7003: --status grades from the daemon's heartbeat sidecar (two report fields and their doc line, the classifier's daemon input and threshold branch, the import and the showStatus read; logic in core/autopilot-heartbeat.ts)
src/commands/doctor.ts 700 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts; +4 #7142: DoctorReport.last_known_sections field and the buildChecks last-known/refresh scope params (logic in doctor/last-known.ts); +8 #7276: DoctorReport.unknown_count field and the unknown category/count lines of the text headline (scoring logic in doctor/budget.ts scoredChecks)
src/commands/embed.ts 2306 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts); +2 agent operator wave D2: --json failure envelope via writeCliError
diff --git a/skills/skillpack-check/SKILL.md b/skills/skillpack-check/SKILL.md
index 5cc257b6d0..b9b1abb67c 100644
--- a/skills/skillpack-check/SKILL.md
+++ b/skills/skillpack-check/SKILL.md
@@ -34,6 +34,7 @@ Running `gbrain skillpack-check` returns a JSON report with:
data, not authority.
- **`doctor`**: full `gbrain doctor --fast --json` output (filesystem checks).
- **`migrations`**: applied/pending/partial counts from `apply-migrations --list`.
+- **`skill_health`** (string): skill size, growth and drift in one line; `gbrain skillpack health` lists each fix.
Exit code:
- `0` — healthy, nothing to do.
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 071beda08b..27bde6b6ee 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -222,7 +222,7 @@
"skill-optimizer/skillopt-benchmark.jsonl": "5552457d6eaa32486b79796d12fcbe2c078b0c53d7fbdaf582f0fd1a17e9a381",
"skillify/SKILL.md": "3c7e87e80b5dd472e27ff89ec19b5919efb3d378a70e401451d8ca2510e6907f",
"skillify/routing-eval.jsonl": "c0a55ee371bb7a797c76d58cf211407a667930673e34e945e09047470cdfd2f4",
- "skillpack-check/SKILL.md": "bcb96d0d231827c9fcd47865f63aaef70c9b9f7a7402464594f24f5fe1eeff8c",
+ "skillpack-check/SKILL.md": "0d2d2d201ed72e19b47d7e3743b5bbdfb5c2655d1f34d29447c601fca3908f9e",
"skillpack-harvest/SKILL.md": "0f86314b58d25b5511809f567c04aedc3fba6fe35ed642ac52d8216ae365b6eb",
"skillpack-harvest/routing-eval.jsonl": "cb4783288e95af3132b32ecb40a54cffc095f57b36240f96a25c2d2adf5e68c6",
"smoke-test/SKILL.md": "f5099e1d2ab9dc6827096249e68414f7ae357c29b39fb069a54bb7fb74f414a5",
diff --git a/src/cli/flag-validation.ts b/src/cli/flag-validation.ts
new file mode 100644
index 0000000000..dcaa11bd91
--- /dev/null
+++ b/src/cli/flag-validation.ts
@@ -0,0 +1,147 @@
+/**
+ * Pre-dispatch flag validation and the CLI alias table, kept out of
+ * src/cli/main.ts so modules that only need to check an invocation (the
+ * skill drift surface, src/cli/skill-surface.ts, which doctor reaches through
+ * the operations graph) do not load the whole dispatcher. main.ts re-exports
+ * every symbol here.
+ */
+import type { OperationMeta } from '../core/ops/contract.ts';
+import { OPERATION_MANIFEST, cliOps } from './op-manifest.ts';
+import { CLI_ONLY } from './command-table.ts';
+import { findUnknownFlag } from './flag-equals.ts';
+import { isBooleanLiteral } from '../core/op-flag-tokens.ts';
+import { CLI_FLAG_REGISTRY } from '../core/cli-flag-registry.generated.ts';
+import { migrationCliArgumentError } from '../core/embedding-migration-cli.ts';
+
+// v114 (#1941): alias -> operation lookup, kept separate from `cliOps` so
+// aliases don't double-list in printHelp's auto-generated section. Collisions
+// with a primary CLI name, a CLI_ONLY command, or another alias throw at module
+// load — a silent route-shadow is worse than a loud boot failure. CLI_ONLY is
+// derived from the command table (src/cli/command-table.ts), so the check runs
+// over every table record. Exported for the table test's collision case.
+export function buildCliAliases<T extends OperationMeta>(
+ ops: readonly T[],
+ primary: ReadonlyMap<string, OperationMeta>,
+ cliOnly: ReadonlySet<string>,
+): Map<string, T> {
+ const aliases = new Map<string, T>();
+ for (const op of ops) {
+ if (op.cliHints?.hidden) continue;
+ for (const alias of op.cliHints?.aliases ?? []) {
+ if (primary.has(alias) || cliOnly.has(alias) || aliases.has(alias)) {
+ throw new Error(
+ `CLI alias collision: '${alias}' (op '${op.name}') conflicts with an existing ` +
+ `command or alias. Rename the alias in src/core/operations.ts.`,
+ );
+ }
+ aliases.set(alias, op);
+ }
+ }
+ return aliases;
+}
+
+export const cliAliases = buildCliAliases(OPERATION_MANIFEST, cliOps, CLI_ONLY);
+
+// ─────────────────────────────────────────────────────────────────
+// #2185 — strict unknown-flag validation (pre-dispatch, pre-engine).
+// A flag no handler consults must fail loud instead of silently doing the
+// destructive thing (`init --migrate-only --dry-run` applied REAL migrations
+// while the user asked for a rehearsal). Two lanes:
+// - op commands: legal flags derive from the operation contract
+// (op.params) + the CLI-local formatter flags, mirroring parseOpArgs's
+// traversal so values that begin with '--' are never misread.
+// - CLI_ONLY commands: legal flags come from the generated
+// CLI_FLAG_REGISTRY (scripts/generate-flag-registry.ts scans each
+// command's source; freshness + coverage pinned by
+// test/cli-flag-validation.test.ts).
+// Everything after a literal `--` is passthrough and never validated.
+// ─────────────────────────────────────────────────────────────────
+
+// Exempt by contract, not oversight:
+// - call: the generic op invoker — arbitrary --param names are its interface.
+// - config: `config set <key> <value>` values are arbitrary strings.
+// - jobs submit: job payloads carry handler-defined params (shell lane incl.).
+// - eval brainbench: owns the 0/1/2 CI exit-code contract (0 pass · 1
+// regression · 2 error/inconclusive) via its own arg parser. The global
+// validator's exit(1) on an unknown flag would be read by a CI harness as a
+// memory REGRESSION rather than a typo; brainbench maps a bad flag to exit 2
+// (error) with its own usage. Its legal flags still land in the generated
+// registry (the generator scans eval's modules), so freshness/drift hold.
+function flagValidationExempt(command: string, subArgs: string[]): boolean {
+ return command === 'call' || command === 'config'
+ || (command === 'jobs' && subArgs[0] === 'submit')
+ || (command === 'eval' && subArgs[0] === 'brainbench');
+}
+
+/** Returns the first unknown flag (e.g. '--dry-run') or null when clean. */
+export function validateCommandFlags(command: string, subArgs: string[]): string | null {
+ if (flagValidationExempt(command, subArgs)) return null;
+ if (command === 'retrieval-upgrade' || command === 'migrate' && subArgs[0] === 'embeddings') return migrationCliArgumentError(command, subArgs)?.flag ?? null;
+ // Lane order MUST mirror dispatch order (CLI_ONLY first): commands that are
+ // BOTH an op and a CLI_ONLY member (think, salience, anomalies) dispatch to
+ // handleCliOnly, whose handlers parse flags the op contract doesn't declare
+ // (`salience --kind`, `think --with-calibration`) — validating those
+ // against op.params rejected documented invocations.
+ if (CLI_ONLY.has(command)) {
+ const legal = CLI_FLAG_REGISTRY[command];
+ // Registry drift fails OPEN at runtime (never brick a command); the
+ // drift-guard test fails the build instead.
+ if (!legal) return null;
+ return findUnknownFlag(subArgs, new Set(legal));
+ }
+ const op = cliOps.get(command) ?? cliAliases.get(command);
+ if (op) return findUnknownOpFlag(op, op.name === 'put_page' ? subArgs.filter((a, i) => !/^--file(=|$)/.test(a) && subArgs[i - 1] !== '--file') : subArgs); // put --file: cli/commands/append.ts
+ return null; // unknown command — the dispatcher's own error handles it
+}
+
+/** Op lane: mirrors parseOpArgs so flag VALUES starting with '--' are skipped. */
+export function findUnknownOpFlag(op: OperationMeta, args: string[]): string | null {
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i];
+ if (a === '--') break;
+ const m = /^--([a-z0-9][a-z0-9-]*)(?:=(.*))?$/i.exec(a);
+ if (!m) continue;
+ // Casing typo = unknown flag (see findUnknownFlag).
+ if (/[A-Z]/.test(m[1])) return `--${m[1]}`;
+ const rawKey = m[1];
+ // CLI-local flags consumed OUTSIDE the op contract (never wire params):
+ // json/explain — formatter flags; help — short-circuits pre-dispatch;
+ // source — makeContext's 6-tier source resolution (deleted before wire);
+ // dry-run — makeContext's ctx.dryRun projection.
+ // Pre-fix, rejecting these broke documented invocations
+ // (`gbrain search "x" --source y`, `gbrain put x --dry-run`).
+ if (rawKey === 'json') {
+ // #4602: parseOpArgs consumes a literal true/false as this boolean's
+ // value — mirror the traversal so the token counts as consumed here too.
+ if (m[2] === undefined && isBooleanLiteral(args[i + 1])) i++;
+ continue;
+ }
+ // Bare-only even where an op also declares `explain` (search/query): the `=` form is refused, never parsed as a value.
+ if (rawKey === 'explain' || rawKey === 'help') { if (m[2] === undefined) continue; return `--${rawKey}`; }
+ if (rawKey === 'source' || rawKey === 'dry-run') {
+ // Non-boolean-style CLI-locals consume the next token as their value
+ // in parseOpArgs (source does; dry-run is boolean-read) — mirror the
+ // parser: source consumes a value when not inline-`=`; dry-run
+ // consumes only a literal true/false (#4602).
+ if (rawKey === 'source' && m[2] === undefined) i++;
+ if (rawKey === 'dry-run' && m[2] === undefined && isBooleanLiteral(args[i + 1])) i++;
+ continue;
+ }
+ if (rawKey.startsWith('no-')) {
+ const positive = rawKey.slice(3).replace(/-/g, '_');
+ if (op.params[positive]?.type === 'boolean') continue;
+ }
+ const key = rawKey.replace(/-/g, '_');
+ const paramDef = op.params[key];
+ if (paramDef) {
+ // Non-boolean flags consume the next token as their value unless
+ // provided inline via `=` — exactly like parseOpArgs. Boolean flags
+ // consume only a literal true/false value token (#4602).
+ if (paramDef.type !== 'boolean' && m[2] === undefined) i++;
+ else if (paramDef.type === 'boolean' && m[2] === undefined && isBooleanLiteral(args[i + 1])) i++;
+ continue;
+ }
+ return `--${rawKey}`;
+ }
+ return null;
+}
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 9069c3803e..c9456ec1d5 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -33,7 +33,7 @@ import type { GBrainConfig } from '../core/config.ts';
import type { AIGatewayConfig } from '../core/ai/types.ts';
import type { BrainEngine } from '../core/engine.ts';
import { OperationError, type OperationMeta } from '../core/ops/contract.ts';
-import { OPERATION_MANIFEST, cliOps } from './op-manifest.ts';
+import { cliOps } from './op-manifest.ts';
import { openRequestConfigSnapshot, withoutRequestConfigSnapshot } from '../core/config-snapshot.ts';
import { resolveSourceIdEngineFree } from '../core/source-resolver.ts';
import { installCliRoutingFor } from './fix-routing-provider.ts';
@@ -43,6 +43,9 @@ import { isScopeErrorCode } from '../core/error-catalogue.ts';
import { shouldForceExitAfterMain, finishCliTeardown, flushThenExit, currentExitCode, setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';
import { printCuratedHelp } from './help/render.ts';
import { OWN_EQUALS_PARSERS, READER_ALIASES, findUnknownFlag, splitFlagEquals } from './flag-equals.ts';
+import { buildCliAliases, cliAliases, findUnknownOpFlag, validateCommandFlags } from './flag-validation.ts';
+import { cliSurface } from './skill-surface.ts';
+import { setSkillSurfaceProvider } from '../core/skill-health.ts';
import { printHelp } from './top-help.ts';
import { curatedFlagError } from './help/validate.ts';
import { cliCommandOf, exitCliError, exitOnRepairFailed, unknownFlagError, usageError, writeCliError, writeCliNotice, writeFatalCliError } from './cli-error.ts';
@@ -176,35 +179,6 @@ async function printSelfHelpWithoutEngine(command: string, args: string[]): Prom
return true;
}
-// v114 (#1941): alias -> operation lookup, kept separate from `cliOps` so
-// aliases don't double-list in printHelp's auto-generated section. Collisions
-// with a primary CLI name, a CLI_ONLY command, or another alias throw at module
-// load — a silent route-shadow is worse than a loud boot failure. CLI_ONLY is
-// derived from the command table (src/cli/command-table.ts), so the check runs
-// over every table record. Exported for the table test's collision case.
-export function buildCliAliases<T extends OperationMeta>(
- ops: readonly T[],
- primary: ReadonlyMap<string, OperationMeta>,
- cliOnly: ReadonlySet<string>,
-): Map<string, T> {
- const aliases = new Map<string, T>();
- for (const op of ops) {
- if (op.cliHints?.hidden) continue;
- for (const alias of op.cliHints?.aliases ?? []) {
- if (primary.has(alias) || cliOnly.has(alias) || aliases.has(alias)) {
- throw new Error(
- `CLI alias collision: '${alias}' (op '${op.name}') conflicts with an existing ` +
- `command or alias. Rename the alias in src/core/operations.ts.`,
- );
- }
- aliases.set(alias, op);
- }
- }
- return aliases;
-}
-
-export const cliAliases = buildCliAliases(OPERATION_MANIFEST, cliOps, CLI_ONLY);
-
/**
* Emit the self-upgrade marker on the hot path. CACHE-READ-ONLY: a statSync +
* read, sub-ms. On a stale/missing cache it kicks a DETACHED, single-flighted
@@ -1276,57 +1250,6 @@ export function applyThinClientSourceScope(
}
// Exported for tests (same import-safety contract as applyThinClientSourceScope).
-// ─────────────────────────────────────────────────────────────────
-// #2185 — strict unknown-flag validation (pre-dispatch, pre-engine).
-// A flag no handler consults must fail loud instead of silently doing the
-// destructive thing (`init --migrate-only --dry-run` applied REAL migrations
-// while the user asked for a rehearsal). Two lanes:
-// - op commands: legal flags derive from the operation contract
-// (op.params) + the CLI-local formatter flags, mirroring parseOpArgs's
-// traversal so values that begin with '--' are never misread.
-// - CLI_ONLY commands: legal flags come from the generated
-// CLI_FLAG_REGISTRY (scripts/generate-flag-registry.ts scans each
-// command's source; freshness + coverage pinned by
-// test/cli-flag-validation.test.ts).
-// Everything after a literal `--` is passthrough and never validated.
-// ─────────────────────────────────────────────────────────────────
-
-// Exempt by contract, not oversight:
-// - call: the generic op invoker — arbitrary --param names are its interface.
-// - config: `config set <key> <value>` values are arbitrary strings.
-// - jobs submit: job payloads carry handler-defined params (shell lane incl.).
-// - eval brainbench: owns the 0/1/2 CI exit-code contract (0 pass · 1
-// regression · 2 error/inconclusive) via its own arg parser. The global
-// validator's exit(1) on an unknown flag would be read by a CI harness as a
-// memory REGRESSION rather than a typo; brainbench maps a bad flag to exit 2
-// (error) with its own usage. Its legal flags still land in the generated
-// registry (the generator scans eval's modules), so freshness/drift hold.
-function flagValidationExempt(command: string, subArgs: string[]): boolean {
- return command === 'call' || command === 'config'
- || (command === 'jobs' && subArgs[0] === 'submit')
- || (command === 'eval' && subArgs[0] === 'brainbench');
-}
-
-/** Returns the first unknown flag (e.g. '--dry-run') or null when clean. */
-export function validateCommandFlags(command: string, subArgs: string[]): string | null {
- if (flagValidationExempt(command, subArgs)) return null;
- if (command === 'retrieval-upgrade' || command === 'migrate' && subArgs[0] === 'embeddings') return migrationCliArgumentError(command, subArgs)?.flag ?? null;
- // Lane order MUST mirror dispatch order (CLI_ONLY first): commands that are
- // BOTH an op and a CLI_ONLY member (think, salience, anomalies) dispatch to
- // handleCliOnly, whose handlers parse flags the op contract doesn't declare
- // (`salience --kind`, `think --with-calibration`) — validating those
- // against op.params rejected documented invocations.
- if (CLI_ONLY.has(command)) {
- const legal = CLI_FLAG_REGISTRY[command];
- // Registry drift fails OPEN at runtime (never brick a command); the
- // drift-guard test fails the build instead.
- if (!legal) return null;
- return findUnknownFlag(subArgs, new Set(legal));
- }
- const op = cliOps.get(command) ?? cliAliases.get(command);
- if (op) return findUnknownOpFlag(op, op.name === 'put_page' ? subArgs.filter((a, i) => !/^--file(=|$)/.test(a) && subArgs[i - 1] !== '--file') : subArgs); // put --file: cli/commands/append.ts
- return null; // unknown command — the dispatcher's own error handles it
-}
/** #7619: the argv a CLI_ONLY handler receives, `--flag=value` split or refused (cli/flag-equals.ts); commands with their own `=`-aware parser keep it. */
export async function cliOnlyFlagArgs(command: string, subArgs: string[]): Promise<{ args: string[] } | { refusal: OperationError }> {
@@ -1340,59 +1263,10 @@ function equalsExempt(command: string, subArgs: string[]): boolean {
return command === 'call' || command === 'config' && subArgs[0] === 'set' || command === 'eval' && subArgs[0] === 'brainbench';
}
-export { findUnknownFlag };
+export { findUnknownFlag, buildCliAliases, cliAliases, findUnknownOpFlag, validateCommandFlags };
+
+setSkillSurfaceProvider(cliSurface);
-/** Op lane: mirrors parseOpArgs so flag VALUES starting with '--' are skipped. */
-export function findUnknownOpFlag(op: OperationMeta, args: string[]): string | null {
- for (let i = 0; i < args.length; i++) {
- const a = args[i];
- if (a === '--') break;
- const m = /^--([a-z0-9][a-z0-9-]*)(?:=(.*))?$/i.exec(a);
- if (!m) continue;
- // Casing typo = unknown flag (see findUnknownFlag).
- if (/[A-Z]/.test(m[1])) return `--${m[1]}`;
- const rawKey = m[1];
- // CLI-local flags consumed OUTSIDE the op contract (never wire params):
- // json/explain — formatter flags; help — short-circuits pre-dispatch;
- // source — makeContext's 6-tier source resolution (deleted before wire);
- // dry-run — makeContext's ctx.dryRun projection.
- // Pre-fix, rejecting these broke documented invocations
- // (`gbrain search "x" --source y`, `gbrain put x --dry-run`).
- if (rawKey === 'json') {
- // #4602: parseOpArgs consumes a literal true/false as this boolean's
- // value — mirror the traversal so the token counts as consumed here too.
- if (m[2] === undefined && isBooleanLiteral(args[i + 1])) i++;
- continue;
- }
- // Bare-only even where an op also declares `explain` (search/query): the `=` form is refused, never parsed as a value.
- if (rawKey === 'explain' || rawKey === 'help') { if (m[2] === undefined) continue; return `--${rawKey}`; }
- if (rawKey === 'source' || rawKey === 'dry-run') {
- // Non-boolean-style CLI-locals consume the next token as their value
- // in parseOpArgs (source does; dry-run is boolean-read) — mirror the
- // parser: source consumes a value when not inline-`=`; dry-run
- // consumes only a literal true/false (#4602).
- if (rawKey === 'source' && m[2] === undefined) i++;
- if (rawKey === 'dry-run' && m[2] === undefined && isBooleanLiteral(args[i + 1])) i++;
- continue;
- }
- if (rawKey.startsWith('no-')) {
- const positive = rawKey.slice(3).replace(/-/g, '_');
- if (op.params[positive]?.type === 'boolean') continue;
- }
- const key = rawKey.replace(/-/g, '_');
- const paramDef = op.params[key];
- if (paramDef) {
- // Non-boolean flags consume the next token as their value unless
- // provided inline via `=` — exactly like parseOpArgs. Boolean flags
- // consume only a literal true/false value token (#4602).
- if (paramDef.type !== 'boolean' && m[2] === undefined) i++;
- else if (paramDef.type === 'boolean' && m[2] === undefined && isBooleanLiteral(args[i + 1])) i++;
- continue;
- }
- return `--${rawKey}`;
- }
- return null;
-}
const SELECTED_CONFIG_BY_ENGINE = new WeakMap<BrainEngine, GBrainConfig>();
diff --git a/src/cli/skill-surface.ts b/src/cli/skill-surface.ts
index 13f17b2d14..70819570e7 100644
--- a/src/cli/skill-surface.ts
+++ b/src/cli/skill-surface.ts
@@ -8,7 +8,8 @@ import type { CliSurface } from '../core/skill-drift.ts';
import { CLI_ONLY } from './command-table.ts';
import { ROUTERS } from './subcommands.ts';
import { OPERATION_MANIFEST, cliOps } from './op-manifest.ts';
-import { cliAliases, findUnknownFlag, validateCommandFlags } from './main.ts';
+import { cliAliases, validateCommandFlags } from './flag-validation.ts';
+import { findUnknownFlag } from './flag-equals.ts';
import { parseGlobalFlags } from '../core/cli-options.ts';
import { CLI_FLAG_REGISTRY } from '../core/cli-flag-registry.generated.ts';
diff --git a/src/commands/doctor/checks/skill-health.ts b/src/commands/doctor/checks/skill-health.ts
new file mode 100644
index 0000000000..9b7a374207
--- /dev/null
+++ b/src/commands/doctor/checks/skill-health.ts
@@ -0,0 +1,43 @@
+/**
+ * SKILL check: `skill_health`, the doctor face of `gbrain skillpack health`
+ * (src/core/skill-health.ts). Warn-only: a skill that shows a gbrain command,
+ * flag or tool this gbrain does not have warns; size, growth and frontmatter
+ * findings are reported without warning; a folder gbrain does not manage, with
+ * no copies of bundled skills, is not applicable. Reads files only, so it runs
+ * the same on repo-less brains.
+ */
+
+import { skillHealthFor } from '../../skillpack/health.ts';
+import { skillHealthSummary } from '../../../core/skill-health.ts';
+import type { Check } from '../../doctor.ts';
+import type { DoctorContext, DoctorEntry } from '../context.ts';
+import { checkError, infoCheck } from '../check-fix.ts';
+
+async function runSkillHealth(ctx: DoctorContext): Promise<Check[]> {
+ const skillsDir = ctx.skillsDirResolution.dir;
+ const checks: Check[] = [];
+ if (ctx.scope !== 'all' || !skillsDir) return checks;
+ try {
+ const report = skillHealthFor(skillsDir);
+ const summary = skillHealthSummary(report);
+ const issues = report.findings.slice(0, 50).map(f => ({ type: f.code, skill: f.skill, action: f.fix }));
+ const details = { scope: report.scope, totals: report.totals };
+ if (report.scope === 'not_gbrain') {
+ checks.push(infoCheck('skill_health', summary, 'not_applicable'));
+ } else if (report.totals.drift > 0) {
+ checks.push({ name: 'skill_health', status: 'warn', message: `${summary}. Run: gbrain skillpack health`, issues, details });
+ } else {
+ checks.push({ name: 'skill_health', status: 'ok', message: report.findings.length ? `${summary} (gbrain skillpack health lists them)` : summary,
+ ...(issues.length ? { issues } : {}), details });
+ }
+ } catch (err) {
+ checks.push(checkError('skill_health', 'read skill health', err, { status: 'warn' }));
+ }
+ return checks;
+}
+
+export const skillHealthEntry: DoctorEntry = {
+ name: 'skill_health',
+ emits: ['skill_health'],
+ run: runSkillHealth,
+};
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 9cda613b88..e361c3c188 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -20,6 +20,7 @@
*/
import { resolverHealthEntry, retrievalReflexEntry, skillConformanceEntry } from './checks/skill-group.ts';
+import { skillHealthEntry } from './checks/skill-health.ts';
import {
bootstrapChecksEntry,
memorableRelayEntry,
@@ -169,6 +170,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
resolverHealthEntry,
retrievalReflexEntry,
skillConformanceEntry,
+ skillHealthEntry,
bootstrapChecksEntry,
memorableRelayEntry,
connectorsEntry,
diff --git a/src/commands/maintain.ts b/src/commands/maintain.ts
index da783778f2..8eabf1c08a 100644
--- a/src/commands/maintain.ts
+++ b/src/commands/maintain.ts
@@ -19,6 +19,8 @@ import { extractStaleFromDB } from './extract.ts';
import { runCycle, type CycleReport } from '../core/cycle.ts';
import { ItemRun } from '../core/item-failure.ts';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
+import { autoDetectSkillsDirReadOnly } from '../core/repo-root.ts';
+import { skillHealthSummary } from '../core/skill-health.ts';
type ActionStatus = 'ok' | 'would_apply' | 'applied' | 'blocked' | 'skipped';
@@ -77,6 +79,16 @@ async function buildDoctorReport(engine: BrainEngine): Promise<DoctorReport> {
return computeDoctorReport(checks);
}
+/** Read-only: skill size, growth and drift for the active skills folder; never edits a skill. */
+async function reportSkillHealth(): Promise<MaintenanceAction> {
+ const dir = autoDetectSkillsDirReadOnly().dir;
+ if (!dir) return { name: 'skill_health', status: 'skipped', message: 'no skills folder found' };
+ const { skillHealthFor } = await import('./skillpack/health.ts');
+ const report = skillHealthFor(dir);
+ const message = skillHealthSummary(report) + (report.findings.length ? '; run `gbrain skillpack health` for the fixes' : '');
+ return { name: 'skill_health', status: 'ok', message, details: { scope: report.scope, totals: report.totals } };
+}
+
async function runStaleExtraction(
engine: BrainEngine,
beforeHealth: BrainHealth,
@@ -193,6 +205,7 @@ Conservative self-healing maintenance.
Modes:
--dry-run Preview safe actions without writes. Default when --safe is absent.
--safe Apply safe actions: stale extraction and source cycle freshness.
+ Skill health (size, growth, drift) is reported, never applied.
--json Emit a structured before/action/after report.
Not auto-applied:
@@ -208,6 +221,7 @@ Not auto-applied:
actions.push(await runStaleExtraction(engine, beforeHealth, opts.dryRun, opts.json));
actions.push(...await runCycleFreshnessMaintenance(engine, beforeDoctor, opts.dryRun));
+ actions.push(await reportSkillHealth());
const afterHealth = await engine.getHealth();
const afterDoctor = await buildDoctorReport(engine);
diff --git a/src/commands/skillpack-check.ts b/src/commands/skillpack-check.ts
index cdbd10b700..80afd30be4 100644
--- a/src/commands/skillpack-check.ts
+++ b/src/commands/skillpack-check.ts
@@ -63,6 +63,8 @@ interface SkillpackReport {
summary: string;
/** Every recommended action the user/agent should take. */
actions: string[];
+ /** The skill_health doctor line (size, growth, drift); absent when doctor did not run it. */
+ skill_health?: string;
/** Full doctor output, machine-readable. */
doctor: {
exit_code: number;
@@ -184,12 +186,15 @@ function buildReport(): SkillpackReport {
? 'gbrain skillpack healthy'
: `gbrain skillpack needs attention: ${actions.length} action(s) — ${actions[0]}`;
+ const skillHealth = 'checks' in doctor ? doctor.checks.find(c => c.name === 'skill_health')?.message : undefined;
+
return {
version: VERSION,
ts: new Date().toISOString(),
healthy,
summary,
actions,
+ ...(skillHealth ? { skill_health: skillHealth } : {}),
doctor,
migrations,
};
diff --git a/src/commands/skillpack.ts b/src/commands/skillpack.ts
index b0ef6e65ff..025043d699 100644
--- a/src/commands/skillpack.ts
+++ b/src/commands/skillpack.ts
@@ -81,6 +81,9 @@ Subcommands:
check Health report. \`check --strict\` exits non-zero
on any drift (for CI gating).
+ health [<skill>] Read-only skill health: size against budget,
+ growth since the last diet, triggers, and
+ commands or flags this gbrain doesn't have.
search [<query>] Search the third-party registry catalog.
info <name> Show full metadata for a registry entry.
@@ -148,6 +151,11 @@ export async function runSkillpack(args: string[]): Promise<void> {
case 'check':
await routeCheck(rest);
return;
+ case 'health': {
+ const { cmdHealth } = await import('./skillpack/health.ts');
+ await cmdHealth(rest);
+ return;
+ }
case 'search':
await cmdSearch(rest);
return;
diff --git a/src/commands/skillpack/health.ts b/src/commands/skillpack/health.ts
new file mode 100644
index 0000000000..f1d81b9d0e
--- /dev/null
+++ b/src/commands/skillpack/health.ts
@@ -0,0 +1,80 @@
+/**
+ * `gbrain skillpack health [<skill>] [--skills-dir PATH] [--json] [--strict]`:
+ * read-only skill health (size, growth since the last diet, description,
+ * triggers, drift against this gbrain) for the active skills folder: the
+ * harness or workspace skills dir, else the bundled skills. Also the loader the
+ * `skill_health` doctor check and `gbrain maintain` use.
+ */
+
+import { existsSync, readFileSync } from 'fs';
+import { join } from 'path';
+
+import { autoDetectSkillsDirReadOnly } from '../../core/repo-root.ts';
+import { bundledSkillSlugs, findGbrainRoot, loadBundleManifest } from '../../core/skillpack/bundle.ts';
+import { computeSkillHealth, parseSkillBudgets, registeredSkillSurface, skillHealthSummary, type SkillHealthReport } from '../../core/skill-health.ts';
+import { resolveAbs } from './shared.ts';
+
+const HELP = `gbrain skillpack health [<skill>] [--skills-dir PATH] [--json] [--strict]
+
+Read-only skill health for the active skills folder (the harness or workspace
+skills dir, else gbrain's bundled skills): bytes against the skill's budget,
+growth past 10% over its last diet, description size, frontmatter triggers,
+and every gbrain command, flag or tool the skill shows that this gbrain does
+not have. Each finding names the edit or command that fixes it and a verify
+command. A folder without a skills manifest or skills.lock.json is checked
+only for copies of gbrain's bundled skills.
+
+Exit 0 (findings included), 1 with --strict when there are findings, 2 when
+no skills folder is found.`;
+
+/** Health for one skills folder, with the bundle's budgets and slugs when a bundle is found. */
+export function skillHealthFor(skillsDir: string, only?: string): SkillHealthReport {
+ const gbrainRoot = findGbrainRoot();
+ const budgetsPath = gbrainRoot ? join(gbrainRoot, 'skills', 'skill-budgets.tsv') : null;
+ const budgets = budgetsPath && existsSync(budgetsPath) ? parseSkillBudgets(readFileSync(budgetsPath, 'utf8')).rows : new Map();
+ let bundled = new Set<string>();
+ try {
+ if (gbrainRoot) bundled = new Set(bundledSkillSlugs(loadBundleManifest(gbrainRoot)));
+ } catch {
+ // A broken bundle manifest leaves only managed folders checkable.
+ }
+ return computeSkillHealth({ skillsDir, surface: registeredSkillSurface(), budgets, bundled, only });
+}
+
+export async function cmdHealth(args: string[]): Promise<void> {
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(HELP);
+ process.exit(0);
+ }
+ const json = args.includes('--json');
+ const strict = args.includes('--strict');
+ let skillsDir: string | null = null;
+ let only: string | undefined;
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i]!;
+ if (a === '--skills-dir') skillsDir = args[++i] ?? null;
+ else if (!a.startsWith('-')) only = a;
+ }
+ const dir = skillsDir ? resolveAbs(skillsDir) : autoDetectSkillsDirReadOnly().dir;
+ if (!dir || !existsSync(dir)) {
+ console.error('skillpack health: no skills folder found. Pass --skills-dir <path> or set $GBRAIN_SKILLS_DIR.');
+ process.exit(2);
+ }
+ const report = skillHealthFor(dir, only);
+ if (only && report.skills.length === 0) {
+ console.error(`skillpack health: no gbrain skill named '${only}' in ${dir}.`);
+ process.exit(2);
+ }
+ if (json) {
+ console.log(JSON.stringify(report, null, 2));
+ } else {
+ console.log(`skill health (${dir}, ${report.scope}): ${skillHealthSummary(report)}`);
+ for (const s of report.skills) {
+ console.log(` ${s.skill.padEnd(32)} ${String(s.bytes).padStart(6)} / ${s.ceiling} bytes ${s.invocations} invocation(s)${s.findings ? ` ${s.findings} finding(s)` : ''}`);
+ }
+ for (const f of report.findings) {
+ console.log(`\n${f.code} ${f.file}${f.line ? `:${f.line}` : ''}\n observed: ${f.observed}\n expected: ${f.expected}\n fix: ${f.fix}\n verify: ${f.verify}`);
+ }
+ }
+ process.exit(strict && report.findings.length ? 1 : 0);
+}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index b441be94f8..7547628bb0 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -83,7 +83,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'lint': ['--abbrev-ref', '--accept-pending', '--add', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
- 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--clear', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],
+ 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--clear', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--strict', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],
'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],
'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 71ffac93f4..69b777aac7 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -271,6 +271,8 @@ export const SKILL_CHECK_NAMES: ReadonlySet<string> = new Set([
'skills_manifest_integrity',
'skill_currency',
'skill_preconditions',
+ // Skill size, growth since the last diet, triggers, and drift against this gbrain (gbrain skillpack health).
+ 'skill_health',
'whoknows_health',
]);
diff --git a/src/core/skill-health.ts b/src/core/skill-health.ts
new file mode 100644
index 0000000000..9e6479789e
--- /dev/null
+++ b/src/core/skill-health.ts
@@ -0,0 +1,226 @@
+/**
+ * Runtime skill health for one skills folder: size against its budget, growth
+ * since the last diet, description size, frontmatter triggers, and drift
+ * against the running CLI (src/core/skill-drift.ts). Read-only, with no git,
+ * database or model calls, so it behaves the same on repo-less brains.
+ * Shared by `gbrain skillpack health`, the `skill_health` doctor check and
+ * `gbrain maintain`; scripts/check-skill-health.ts enforces the same limits
+ * on the bundled skills in CI.
+ */
+import { existsSync, readdirSync, readFileSync } from 'node:fs';
+import { join, relative } from 'node:path';
+import { analyzeSkillDrift, descriptionBytes, type CliSurface, type DriftCode } from './skill-drift.ts';
+import { SKILLS_MANIFEST_FILENAME } from './skills-integrity.ts';
+
+export const NEW_SKILL_CAP = 16_384;
+export const DESCRIPTION_CAP = 1_024;
+export const DIET_GROWTH_LIMIT = 1.1;
+const REDIET = 'CONTRIBUTING.md#changing-a-skill';
+
+let surfaceProvider: (() => CliSurface) | null = null;
+
+/**
+ * The CLI dispatcher registers its surface here (src/cli/main.ts), so doctor,
+ * which the operations graph also loads, checks drift without importing the
+ * command table. Without a provider drift is reported as not checked.
+ */
+export function setSkillSurfaceProvider(provider: (() => CliSurface) | null): void {
+ surfaceProvider = provider;
+}
+
+export function registeredSkillSurface(): CliSurface | null {
+ return surfaceProvider ? surfaceProvider() : null;
+}
+
+export type SkillHealthCode =
+ | 'SKILL_HEALTH_OVER_BUDGET'
+ | 'SKILL_HEALTH_DIET_GROWTH'
+ | 'SKILL_HEALTH_DESCRIPTION'
+ | 'SKILL_HEALTH_MISSING_TRIGGERS'
+ | DriftCode;
+
+export interface SkillBudget { max: number; lastDiet: number | null }
+
+export interface SkillHealthFinding {
+ code: SkillHealthCode;
+ skill: string;
+ /** Relative to the skills folder. */
+ file: string;
+ line?: number;
+ observed: string;
+ expected: string;
+ fix: string;
+ verify: string;
+}
+
+export interface SkillHealthEntry {
+ skill: string;
+ bytes: number;
+ description_bytes: number;
+ ceiling: number;
+ last_diet: number | null;
+ invocations: number;
+ /** Invocations of commands that dispatch subcommands by hand: only their flags were checked. */
+ subcommands_unverified: number;
+ findings: number;
+}
+
+export interface SkillHealthReport {
+ skills_dir: string;
+ /** managed: a skills manifest or skills.lock.json is present, every skill is checked; bundled_copies: only copies of gbrain's bundled skills are checked; not_gbrain: nothing is checked. */
+ scope: 'managed' | 'bundled_copies' | 'not_gbrain';
+ skills: SkillHealthEntry[];
+ findings: SkillHealthFinding[];
+ /** False when no CLI surface was available, so commands, flags and tools were not checked. */
+ drift_checked: boolean;
+ totals: { skills: number; bytes: number; invocations: number; subcommands_unverified: number; drift: number; size: number };
+}
+
+export interface SkillBudgetRows {
+ rows: Map<string, SkillBudget>;
+ invalid: string[];
+ duplicates: string[];
+}
+
+/** Parse skills/skill-budgets.tsv (tab-separated: skill, max bytes, last diet bytes or `-`, note). */
+export function parseSkillBudgets(text: string): SkillBudgetRows {
+ const out: SkillBudgetRows = { rows: new Map(), invalid: [], duplicates: [] };
+ for (const line of text.split('\n')) {
+ if (!line.trim() || line.startsWith('#')) continue;
+ const [skill, max, lastDiet] = line.split('\t');
+ if (!skill || !/^\d+$/.test(max ?? '')) { out.invalid.push(line); continue; }
+ if (out.rows.has(skill)) out.duplicates.push(skill);
+ out.rows.set(skill, { max: Number(max), lastDiet: lastDiet && /^\d+$/.test(lastDiet) ? Number(lastDiet) : null });
+ }
+ return out;
+}
+
+/** A folder gbrain manages: it holds a real skills manifest or skills lock (never a derived one). */
+export function isManagedSkillsDir(dir: string): boolean {
+ return existsSync(join(dir, 'manifest.json')) || existsSync(join(dir, SKILLS_MANIFEST_FILENAME));
+}
+
+function markdownFiles(dir: string): string[] {
+ return readdirSync(dir, { withFileTypes: true }).flatMap(e => {
+ const p = join(dir, e.name);
+ if (e.isDirectory()) return e.name === 'migrations' ? [] : markdownFiles(p);
+ return e.name.endsWith('.md') ? [p] : [];
+ });
+}
+
+function hasTriggers(markdown: string): boolean {
+ const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(markdown)?.[1];
+ if (!fm) return false;
+ const m = /^triggers:[ \t]*(.*)$/m.exec(fm);
+ if (!m) return false;
+ if (m[1].trim() && m[1].trim() !== '[]') return true;
+ return /^[ \t]+-[ \t]*\S/m.test(fm.slice(m.index + m[0].length).split(/\n(?=\S)/)[0] ?? '');
+}
+
+export interface SkillHealthOptions {
+ skillsDir: string;
+ /** null skips the drift check (no CLI surface registered). */
+ surface: CliSurface | null;
+ /** Rows of the bundle's skills/skill-budgets.tsv, applied to skills of the same name. */
+ budgets: ReadonlyMap<string, SkillBudget>;
+ /** Slugs gbrain bundles; copies of them are checked even in a folder gbrain does not manage. */
+ bundled: ReadonlySet<string>;
+ /** Check one skill only. */
+ only?: string;
+ /** Overrides the managed-folder test (tests, and later the shared predicate). */
+ isManaged?: (dir: string) => boolean;
+}
+
+export function computeSkillHealth(opts: SkillHealthOptions): SkillHealthReport {
+ const { skillsDir, surface, budgets, bundled, only } = opts;
+ const scope: SkillHealthReport['scope'] = (opts.isManaged ?? isManagedSkillsDir)(skillsDir)
+ ? 'managed'
+ : [...bundled].some(s => existsSync(join(skillsDir, s, 'SKILL.md'))) ? 'bundled_copies' : 'not_gbrain';
+ const report: SkillHealthReport = {
+ skills_dir: skillsDir, scope, skills: [], findings: [], drift_checked: surface !== null,
+ totals: { skills: 0, bytes: 0, invocations: 0, subcommands_unverified: 0, drift: 0, size: 0 },
+ };
+ if (scope === 'not_gbrain' || !existsSync(skillsDir)) return report;
+
+ const slugs = readdirSync(skillsDir, { withFileTypes: true })
+ .filter(e => e.isDirectory() && existsSync(join(skillsDir, e.name, 'SKILL.md')))
+ .map(e => e.name)
+ .filter(s => (scope === 'managed' || bundled.has(s)) && (!only || s === only))
+ .sort();
+
+ for (const skill of slugs) {
+ const dir = join(skillsDir, skill);
+ const skillMd = readFileSync(join(dir, 'SKILL.md'), 'utf8');
+ const bytes = Buffer.byteLength(skillMd);
+ const desc = descriptionBytes(skillMd);
+ const budget = budgets.get(skill);
+ const ceiling = budget?.max ?? NEW_SKILL_CAP;
+ const verify = `gbrain skillpack health ${skill}`;
+ const findings: SkillHealthFinding[] = [];
+ const file = `${skill}/SKILL.md`;
+ const upstream = bundled.has(skill)
+ ? `if this copy is unedited, read gbrain's current version with \`gbrain skillpack reference ${skill}\`; otherwise `
+ : '';
+
+ if (bytes > ceiling) {
+ findings.push({ code: 'SKILL_HEALTH_OVER_BUDGET', skill, file, observed: `${bytes} bytes`, expected: `at most ${ceiling} bytes`,
+ fix: `${upstream}move detail only some tasks need into references/ behind a link that says when to read it (${REDIET})`, verify });
+ }
+ if (budget?.lastDiet && bytes > budget.lastDiet * DIET_GROWTH_LIMIT) {
+ findings.push({ code: 'SKILL_HEALTH_DIET_GROWTH', skill, file,
+ observed: `${bytes} bytes, ${Math.round((bytes / budget.lastDiet - 1) * 100)}% over its last diet`,
+ expected: `at most ${Math.floor(budget.lastDiet * DIET_GROWTH_LIMIT)} bytes (last diet ${budget.lastDiet} + 10%)`,
+ fix: `${upstream}re-diet the skill (${REDIET})`, verify });
+ }
+ if (desc > DESCRIPTION_CAP) {
+ findings.push({ code: 'SKILL_HEALTH_DESCRIPTION', skill, file, observed: `description ${desc} bytes`, expected: `at most ${DESCRIPTION_CAP} bytes`,
+ fix: 'the description loads in every session; keep one trigger per case and move the rest into the body', verify });
+ }
+ if (!hasTriggers(skillMd)) {
+ findings.push({ code: 'SKILL_HEALTH_MISSING_TRIGGERS', skill, file, observed: 'no frontmatter triggers', expected: 'a triggers: list naming when to load the skill',
+ fix: `add a triggers: list to the frontmatter of ${file}; without it the resolver cannot route to the skill`, verify });
+ }
+
+ let invocations = 0;
+ let unverified = 0;
+ let drift = 0;
+ if (surface) {
+ for (const path of markdownFiles(dir)) {
+ const rel = relative(skillsDir, path);
+ const d = analyzeSkillDrift(rel, rel === file ? skillMd : readFileSync(path, 'utf8'), surface);
+ invocations += d.invocations;
+ unverified += d.subcommandUnverified;
+ for (const f of d.findings) {
+ drift++;
+ findings.push({ code: f.code, skill, file: f.file, line: f.line, observed: f.snippet,
+ expected: f.suggestion ? `'${f.suggestion}'` : 'a command, flag or tool this gbrain has', fix: f.remedy, verify });
+ }
+ }
+ }
+
+ report.skills.push({ skill, bytes, description_bytes: desc, ceiling, last_diet: budget?.lastDiet ?? null,
+ invocations, subcommands_unverified: unverified, findings: findings.length });
+ report.findings.push(...findings);
+ report.totals.skills++;
+ report.totals.bytes += bytes;
+ report.totals.invocations += invocations;
+ report.totals.subcommands_unverified += unverified;
+ report.totals.drift += drift;
+ report.totals.size += findings.length - drift;
+ }
+ return report;
+}
+
+/** One line for doctor, maintain and skillpack-check. */
+export function skillHealthSummary(r: SkillHealthReport): string {
+ if (r.scope === 'not_gbrain') return 'no gbrain skills in this folder';
+ const t = r.totals;
+ const kb = (t.bytes / 1024).toFixed(0);
+ const head = r.drift_checked
+ ? `${t.skills} skill(s), ${kb} KB, ${t.invocations} gbrain invocation(s) (${t.subcommands_unverified} with undeclared subcommands, flags checked)`
+ : `${t.skills} skill(s), ${kb} KB (commands and flags not checked outside the CLI)`;
+ if (!r.findings.length) return `${head}; no findings`;
+ const parts = [t.drift ? `${t.drift} drift` : '', t.size ? `${t.size} size/frontmatter` : ''].filter(Boolean).join(', ');
+ const skills = [...new Set(r.findings.map(f => f.skill))];
+ return `${head}; ${parts} finding(s) in ${skills.slice(0, 5).join(', ')}${skills.length > 5 ? `, … +${skills.length - 5} more` : ''}`;
+}
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index bfd69e8f61..5da3ab4c08 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -175,6 +175,24 @@
"name": "skill_preconditions",
"status": "ok"
},
+ {
+ "category": "skill",
+ "details": {
+ "scope": "managed",
+ "totals": {
+ "bytes": 100,
+ "drift": 0,
+ "invocations": 0,
+ "size": 0,
+ "skills": 1,
+ "subcommands_unverified": 0
+ }
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "1 skill(s), 0 KB, 0 gbrain invocation(s) (0 with undeclared subcommands, flags checked); no findings",
+ "name": "skill_health",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fast.json b/test/fixtures/goldens/doctor/json-pglite-fast.json
index 4d1ca44ac2..667dfd6a03 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fast.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fast.json
@@ -165,6 +165,24 @@
"name": "skill_preconditions",
"status": "ok"
},
+ {
+ "category": "skill",
+ "details": {
+ "scope": "managed",
+ "totals": {
+ "bytes": 100,
+ "drift": 0,
+ "invocations": 0,
+ "size": 0,
+ "skills": 1,
+ "subcommands_unverified": 0
+ }
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "1 skill(s), 0 KB, 0 gbrain invocation(s) (0 with undeclared subcommands, flags checked); no findings",
+ "name": "skill_health",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 51067b4375..242ea6e23d 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -178,6 +178,24 @@
"name": "skill_preconditions",
"status": "ok"
},
+ {
+ "category": "skill",
+ "details": {
+ "scope": "managed",
+ "totals": {
+ "bytes": 100,
+ "drift": 0,
+ "invocations": 0,
+ "size": 0,
+ "skills": 1,
+ "subcommands_unverified": 0
+ }
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "1 skill(s), 0 KB, 0 gbrain invocation(s) (0 with undeclared subcommands, flags checked); no findings",
+ "name": "skill_health",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json b/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json
index 070b59a802..72fb6b795a 100644
--- a/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json
+++ b/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json
@@ -152,6 +152,24 @@
"name": "skill_preconditions",
"status": "ok"
},
+ {
+ "category": "skill",
+ "details": {
+ "scope": "managed",
+ "totals": {
+ "bytes": 100,
+ "drift": 0,
+ "invocations": 0,
+ "size": 0,
+ "skills": 1,
+ "subcommands_unverified": 0
+ }
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "1 skill(s), 0 KB, 0 gbrain invocation(s) (0 with undeclared subcommands, flags checked); no findings",
+ "name": "skill_health",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-postgres-unreachable.json b/test/fixtures/goldens/doctor/json-postgres-unreachable.json
index e116f0916e..3bcb767203 100644
--- a/test/fixtures/goldens/doctor/json-postgres-unreachable.json
+++ b/test/fixtures/goldens/doctor/json-postgres-unreachable.json
@@ -151,6 +151,24 @@
"name": "skill_preconditions",
"status": "ok"
},
+ {
+ "category": "skill",
+ "details": {
+ "scope": "managed",
+ "totals": {
+ "bytes": 100,
+ "drift": 0,
+ "invocations": 0,
+ "size": 0,
+ "skills": 1,
+ "subcommands_unverified": 0
+ }
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "1 skill(s), 0 KB, 0 gbrain invocation(s) (0 with undeclared subcommands, flags checked); no findings",
+ "name": "skill_health",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 62f403be06..905c11cc53 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -37,6 +37,10 @@
"category": "skill",
"name": "skill_preconditions"
},
+ {
+ "category": "skill",
+ "name": "skill_health"
+ },
{
"category": "ops",
"name": "plugin_lane_collision"
diff --git a/test/skill-health.test.ts b/test/skill-health.test.ts
new file mode 100644
index 0000000000..5b5c491d08
--- /dev/null
+++ b/test/skill-health.test.ts
@@ -0,0 +1,158 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { computeSkillHealth, parseSkillBudgets, registeredSkillSurface, setSkillSurfaceProvider, skillHealthSummary, type SkillBudget } from '../src/core/skill-health.ts';
+import type { CliSurface } from '../src/core/skill-drift.ts';
+import { skillHealthEntry } from '../src/commands/doctor/checks/skill-health.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+
+const surface: CliSurface = {
+ isCommand: n => ['doctor', 'search'].includes(n),
+ subcommands: () => undefined,
+ stripGlobalFlags: argv => argv,
+ unknownFlag: (_c, args) => args.find(a => a.startsWith('--') && !['--json', '--limit'].includes(a)) ?? null,
+ legalFlags: () => ['--json', '--limit'],
+ isOperation: n => n === 'get_page',
+ operationNames: () => ['get_page'],
+};
+
+const roots: string[] = [];
+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });
+
+/** A skills folder in a fresh temp dir: no git repository anywhere above it, like a repo-less brain. */
+function folder(skills: Record<string, string>, managed = true): string {
+ const dir = mkdtempSync(join(tmpdir(), 'gb-skill-health-'));
+ roots.push(dir);
+ if (managed) writeFileSync(join(dir, 'manifest.json'), '{"skills":[]}');
+ for (const [name, body] of Object.entries(skills)) {
+ mkdirSync(join(dir, name), { recursive: true });
+ writeFileSync(join(dir, name, 'SKILL.md'), body);
+ }
+ return dir;
+}
+const skill = (body: string, extra = 'triggers:\n - when x\n') => `---\nname: s\ndescription: d\n${extra}---\n\n${body}\n`;
+const run = (dir: string, budgets = new Map<string, SkillBudget>(), bundled = new Set<string>(), only?: string) =>
+ computeSkillHealth({ skillsDir: dir, surface, budgets, bundled, only });
+
+describe('computeSkillHealth', () => {
+ test('a clean managed folder has no findings and counts invocations', () => {
+ const r = run(folder({ a: skill('Run `gbrain doctor --json`.') }));
+ expect(r.scope).toBe('managed');
+ expect(r.findings).toEqual([]);
+ expect(r.totals).toMatchObject({ skills: 1, invocations: 1, drift: 0, size: 0 });
+ expect(skillHealthSummary(r)).toContain('no findings');
+ });
+
+ test('each finding carries observed, expected, a fix and a read-only verify command', () => {
+ const big = 'x'.repeat(2_000);
+ const dir = folder({
+ over: skill(big),
+ grown: skill('y'.repeat(1_200)),
+ nodesc: `---\nname: s\ndescription: ${'d'.repeat(1_100)}\ntriggers:\n - t\n---\nbody\n`,
+ untriggered: skill('body', ''),
+ drifted: skill('Run `gbrain search q --no-such-flag`.'),
+ });
+ const budgets = new Map<string, SkillBudget>([['over', { max: 1_000, lastDiet: null }], ['grown', { max: 5_000, lastDiet: 1_000 }]]);
+ const r = run(dir, budgets);
+ const byCode = Object.fromEntries(r.findings.map(f => [f.code, f]));
+ expect(Object.keys(byCode).sort()).toEqual([
+ 'SKILL_DRIFT_UNKNOWN_FLAG', 'SKILL_HEALTH_DESCRIPTION', 'SKILL_HEALTH_DIET_GROWTH', 'SKILL_HEALTH_MISSING_TRIGGERS', 'SKILL_HEALTH_OVER_BUDGET',
+ ]);
+ expect(byCode.SKILL_HEALTH_OVER_BUDGET).toMatchObject({ skill: 'over', file: 'over/SKILL.md', expected: 'at most 1000 bytes' });
+ expect(byCode.SKILL_HEALTH_DIET_GROWTH!.expected).toContain('last diet 1000');
+ expect(byCode.SKILL_DRIFT_UNKNOWN_FLAG).toMatchObject({ skill: 'drifted', line: 8 });
+ for (const f of r.findings) {
+ expect(f.fix.length).toBeGreaterThan(10);
+ expect(f.verify).toBe(`gbrain skillpack health ${f.skill}`);
+ }
+ expect(r.totals).toMatchObject({ drift: 1, size: 4 });
+ });
+
+ test('an over-budget copy of a bundled skill points at the upstream version first', () => {
+ const r = run(folder({ brainy: skill('x'.repeat(20_000)) }), new Map(), new Set(['brainy']));
+ expect(r.findings[0]!.fix).toContain('gbrain skillpack reference brainy');
+ });
+
+ test('a folder gbrain does not manage gets no findings', () => {
+ const r = run(folder({ theirs: skill('x'.repeat(20_000), '') }, false), new Map(), new Set(['brainy']));
+ expect(r.scope).toBe('not_gbrain');
+ expect(r.skills).toEqual([]);
+ expect(skillHealthSummary(r)).toBe('no gbrain skills in this folder');
+ });
+
+ test('in an unmanaged folder only copies of bundled skills are checked', () => {
+ const r = run(folder({ brainy: skill('body', ''), theirs: skill('body', '') }, false), new Map(), new Set(['brainy']));
+ expect(r.scope).toBe('bundled_copies');
+ expect(r.skills.map(s => s.skill)).toEqual(['brainy']);
+ });
+
+ test('without a CLI surface only size and frontmatter are checked, and the summary says so', () => {
+ const r = computeSkillHealth({ skillsDir: folder({ a: skill('Run `gbrain search q --no-such-flag`.') }), surface: null, budgets: new Map(), bundled: new Set() });
+ expect(r.drift_checked).toBe(false);
+ expect(r.findings).toEqual([]);
+ expect(skillHealthSummary(r)).toContain('not checked outside the CLI');
+ });
+
+ test('only narrows to one skill', () => {
+ const r = run(folder({ a: skill('a'), b: skill('b') }), new Map(), new Set(), 'b');
+ expect(r.skills.map(s => s.skill)).toEqual(['b']);
+ });
+
+ test('100 skills in under 500 ms', () => {
+ const skills: Record<string, string> = {};
+ for (let i = 0; i < 100; i++) skills[`s${i}`] = skill(`Run \`gbrain doctor --json\`.\n${'text '.repeat(2_000)}`);
+ const dir = folder(skills);
+ const t0 = performance.now();
+ const r = run(dir);
+ expect(r.totals.skills).toBe(100);
+ expect(performance.now() - t0).toBeLessThan(500);
+ });
+});
+
+describe('surface registration', () => {
+ test('loading the CLI dispatcher registers the real surface', async () => {
+ await import('../src/cli/main.ts');
+ expect(registeredSkillSurface()?.isCommand('doctor')).toBe(true);
+ setSkillSurfaceProvider(null);
+ });
+});
+
+describe('parseSkillBudgets', () => {
+ test('reads rows and reports invalid and duplicate ones', () => {
+ const p = parseSkillBudgets('# c\na\t100\t90\tnote\nb\t200\t-\tnote\nbad\tx\na\t50\t-\n');
+ expect(p.rows.get('a')).toEqual({ max: 50, lastDiet: null });
+ expect(p.rows.get('b')).toEqual({ max: 200, lastDiet: null });
+ expect(p.invalid).toEqual(['bad\tx']);
+ expect(p.duplicates).toEqual(['a']);
+ });
+});
+
+describe('skill_health doctor check', () => {
+ beforeAll(() => setSkillSurfaceProvider(() => surface));
+ afterAll(() => setSkillSurfaceProvider(null));
+ const ctx = (dir: string | null, scope: 'all' | 'brain' = 'all') =>
+ ({ scope, skillsDirResolution: { dir, source: dir ? 'explicit' : 'none' } }) as unknown as DoctorContext;
+
+ test('warns on drift and points at the fix command', async () => {
+ const dir = folder({ doctor: skill('Run `gbrain doctor --no-such-flag`.') });
+ const [c] = (await skillHealthEntry.run(ctx(dir))) as Array<{ name: string; status: string; message: string; issues?: unknown[] }>;
+ expect(c!.status).toBe('warn');
+ expect(c!.message).toContain('Run: gbrain skillpack health');
+ expect(c!.issues).toHaveLength(1);
+ });
+
+ test('size findings alone do not warn', async () => {
+ const dir = folder({ big: skill('x'.repeat(20_000)) });
+ const [c] = (await skillHealthEntry.run(ctx(dir))) as Array<{ status: string; message: string }>;
+ expect(c!.status).toBe('ok');
+ expect(c!.message).toContain('gbrain skillpack health lists them');
+ });
+
+ test('is not applicable to a folder gbrain does not manage, and silent without a skills dir or under --scope=brain', async () => {
+ const [c] = (await skillHealthEntry.run(ctx(folder({ theirs: skill('x', '') }, false)))) as Array<{ status: string; severity?: string }>;
+ expect(c).toMatchObject({ status: 'ok', severity: 'info' });
+ expect(await skillHealthEntry.run(ctx(null))).toEqual([]);
+ expect(await skillHealthEntry.run(ctx(folder({ a: skill('a') }), 'brain'))).toEqual([]);
+ });
+});