Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(skillpack): refuse ignored arguments on `skillpack reference` (#5491)

garrytan46b03fb8a756
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.md
index c5cf2f7968..2057b127d8 100644
--- a/docs/architecture/key-files/commands-5.md
+++ b/docs/architecture/key-files/commands-5.md
@@ -31,7 +31,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/setup.ts` + `src/cli/commands/setup.ts` — `gbrain setup <harness>` (D8), pre-connect and engine-free (`thinClient: 'none'`, `json: 'document'`): an orchestrator over the existing wiring, not a new installation system. Target first: it resolves the brain (`loadConfig`; none → a `gbrain init --pglite --no-embedding` child, `--providers` drops `--no-embedding`), the source (`--source` > `GBRAIN_SOURCE` > unpinned), the launcher (`--gbrain-bin` > `resolveGbrainBin`), the surface (`--surface` > `GBRAIN_SURFACE` > the receipt's > `REGISTRATION_SURFACE`) and the registration owner, prints them, then refuses before any write with `setup_hosted_connection` (thin-client config, hosted connection receipt or remote entry: never a second, local brain) or `setup_owner_conflict` (`live_serve` from `peekLock` unless the live stdio serve is this registration's own, `unowned_entry`, `other_install` by receipt `gbrain_home`, `harness_lane` for a bootstrap harness receipt or another gbrain marker on a wanted event). Consent is three recorded decisions (`resolveConsent`): wiring scope (`--scope`, `--no-hooks`, `GBRAIN_HOOKS=0`), capture (`--capture`/`--no-capture`; a file-config `memory.auto_writeback: off` wins) and providers; read-context events come from the capability row, capture events only when accepted. Verify reuses `smokeStdioRegistration` from `doctor/checks/harness-wiring.ts`; states are `configured` → `connection-verified` → `native-pending` (`native-verified` is never claimed). Unsupported harness ids (`codex`, `openclaw`, `hermes`, unknown) refuse with `setup_harness_unsupported` naming the row's guide (exit 2). `GBRAIN_SETUP_ABORT_AFTER=receipt|mcp|hooks` is the crash-injection seam. Pinned by `test/setup.test.ts`.
- `src/commands/skillify.ts` + `src/core/skillify/{generator,templates}.ts` — `gbrain skillify scaffold <name>` creates all stubs for a new skill: SKILL.md, script, tests, routing-eval.jsonl, resolver entry, filing-rules pointer. `gbrain skillify check <script>` runs the 10-step checklist (LLM evals, routing evals, check-resolvable gate, filing audit) against a candidate skill before it lands.
-- `src/commands/skillpack.ts` + `src/core/skillpack/{bundle,scaffold,reference,migrate-fence,scrub-legacy,harvest,harvest-lint,copy,apply-hunks,diff-text,installer}.ts` — `install`/`uninstall` are not supported (they exit non-zero with a hint to the replacement). Surface: `scaffold` (one-time additive copy via `copyArtifacts` in `copy.ts`; refuses to overwrite; partial-state fills missing paired sources declared in SKILL.md frontmatter `sources:`), `reference` (read-only diff lens + `--apply-clean-hunks` two-way auto-apply via pure-JS unified-diff parser/applier in `apply-hunks.ts` + `diff-text.ts`), `migrate-fence` (one-shot strip of legacy fence; cumulative-slugs receipt → row-parsing fallback; preserves rows verbatim as user-owned routing), `scrub-legacy-fence-rows` (opt-in row cleanup with skill-present + non-empty-triggers gate), `harvest` (host→gbrain inverse with symlink-reject + canonical-path containment via a `validateUploadPath`-style gate + default-on privacy linter in `harvest-lint.ts` against `~/.gbrain/harvest-private-patterns.txt` plus built-in a built-in fork-name pattern + email + Slack-channel patterns; rollback on match). Paired-source declarations live in each SKILL.md's frontmatter `sources:` array (validated by `loadSkillSources` in `bundle.ts`). `autoDetectSkillsDir` (in `src/core/repo-root.ts`) has a `cwd_walk_up` tier ahead of `~/.openclaw/workspace` (`$OPENCLAW_WORKSPACE` precedence preserved). `gbrain skillpack check --strict` exits non-zero on drift (CI gate); top-level `gbrain skillpack-check` keeps exit-1-on-issues for cron. Companion editorial skill `skills/skillpack-harvest/SKILL.md` drives the genericization checklist. Doc: `docs/guides/skillpacks-as-scaffolding.md`. Test coverage across `test/skillpack-{copy,scaffold,reference,reference-apply,apply-hunks,migrate-fence,scrub-legacy,harvest,harvest-lint,frontmatter-sources}.test.ts` + 9-case E2E in `test/skillpack-flow.test.ts`. `installer.ts` + `test/skillpack-install.test.ts` remain because `gbrain skillpack diff` uses `diffSkill` from there.
+- `src/commands/skillpack.ts` + `src/core/skillpack/{bundle,scaffold,reference,migrate-fence,scrub-legacy,harvest,harvest-lint,copy,apply-hunks,diff-text,installer}.ts` — `install`/`uninstall` are not supported (they exit non-zero with a hint to the replacement). Surface: `scaffold` (one-time additive copy via `copyArtifacts` in `copy.ts`; refuses to overwrite; partial-state fills missing paired sources declared in SKILL.md frontmatter `sources:`), `reference` (read-only diff lens + `--apply-clean-hunks` two-way auto-apply via pure-JS unified-diff parser/applier in `apply-hunks.ts` + `diff-text.ts`; strict arguments through the `skillpack reference` row of `src/cli/strict-args.ts` (#5491): `--dry-run=true`, a typo or an unknown flag exits 2 before any write, the per-skill and `--all` grammars print separately, and `--all --apply-clean-hunks` refuses with the three-command update path; pinned by `test/skillpack-reference-strict-args.test.ts`), `migrate-fence` (one-shot strip of legacy fence; cumulative-slugs receipt → row-parsing fallback; preserves rows verbatim as user-owned routing), `scrub-legacy-fence-rows` (opt-in row cleanup with skill-present + non-empty-triggers gate), `harvest` (host→gbrain inverse with symlink-reject + canonical-path containment via a `validateUploadPath`-style gate + default-on privacy linter in `harvest-lint.ts` against `~/.gbrain/harvest-private-patterns.txt` plus built-in a built-in fork-name pattern + email + Slack-channel patterns; rollback on match). Paired-source declarations live in each SKILL.md's frontmatter `sources:` array (validated by `loadSkillSources` in `bundle.ts`). `autoDetectSkillsDir` (in `src/core/repo-root.ts`) has a `cwd_walk_up` tier ahead of `~/.openclaw/workspace` (`$OPENCLAW_WORKSPACE` precedence preserved). `gbrain skillpack check --strict` exits non-zero on drift (CI gate); top-level `gbrain skillpack-check` keeps exit-1-on-issues for cron. Companion editorial skill `skills/skillpack-harvest/SKILL.md` drives the genericization checklist. Doc: `docs/guides/skillpacks-as-scaffolding.md`. Test coverage across `test/skillpack-{copy,scaffold,reference,reference-apply,apply-hunks,migrate-fence,scrub-legacy,harvest,harvest-lint,frontmatter-sources}.test.ts` + 9-case E2E in `test/skillpack-flow.test.ts`. `installer.ts` + `test/skillpack-install.test.ts` remain because `gbrain skillpack diff` uses `diffSkill` from there.
- `src/commands/sources-lifecycle{,-args}.ts` — strict source mutation parsing before engine connection, with stable UUIDs and source incarnation preconditions. The private CLI administration envelope delegates to a live PGLite owner, retains request IDs after lost responses, and refuses preactivation administration or legacy hardening rather than changing worktrees through an uncoordinated writer. Managed purge names one archived source; the expiry worker separately coordinates each source. `test/persistence-source-cli.test.ts` executes real CLI subprocesses, checks replay after deletion/recreation, and verifies global page/lifecycle request identity.
diff --git a/docs/architecture/key-files/entrypoints-and-docs.md b/docs/architecture/key-files/entrypoints-and-docs.md
index 1fe11080e9..b4e7828e9b 100644
--- a/docs/architecture/key-files/entrypoints-and-docs.md
+++ b/docs/architecture/key-files/entrypoints-and-docs.md
@@ -122,7 +122,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
Size ceiling (`src/cli/main.ts`): `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers `handleCliOnly`'s explicit ordered pipeline (`@cliPipelineStage` functions: thin-client guard, deferred-persistence routing, subcommand and help routes, read-only timeout path, sync watchdog and delegation, connectEngine terminator with degraded-serve recovery, teardown), thin-client routing and refusal, help and self-help text, strict flag parsing and process-exit teardown. Per-command dispatch (pre- and post-connect) lives in the command table (entry below), not in `src/cli/main.ts`.
- `src/cli/remember-format.ts` — the `remember` human formatter (`formatRememberResult`: status, entity with `(inferred from mention)`, expiry, degraded dedup, `warnings` + `hint`), kept out of `src/cli.ts`; `--json` prints the raw envelope. Pinned by `test/remember-entity-inference.test.ts`.
-- `src/cli/subcommands.ts` + `src/cli/router-help.ts` + `src/cli/strict-args.ts` — help never acts (#6114). `subcommands.ts` holds each router command's inventory (`ROUTERS`: pages, cache, integrity, hook, search, edge-proposals, schema, config; each router re-exports its list as `SUBCOMMANDS` and types its dispatch over it, so an unlisted subcommand fails typecheck) and the help grammar: `--help`/`-h` anywhere before `--` (a flag-value slot included) and a bare `help` only as the first token after a router command or one of its subcommands (`search help` stays a query). `cli.ts` decides `cliHelpRequested` once, before the update marker, backup nag and key warnings; on help it calls `printRouterHelp`, which loads only the router's `printUsage`, before any subcommand, thin-client route or engine. `strict-args.ts` is the per-subcommand table for destructive subcommands (pages purge-deleted, cache clear/prune, schema use/downgrade/init/remove-*, integrity auto/reset-progress, search modes --reset and its `--mode <mode>` preview, W4.13: `--source <mode>` is the deprecated alias, and the handler refuses a missing value or conflicting `--mode`/`--source` with exit 2 instead of resetting): an argument the handler would ignore refuses with `invalid_params` (exit 2) after help and before dispatch, with a read-only fix that itself parses under the table (`ask_user` for integrity reset-progress). The flag-registry generator skips `strict-args.ts` (its literals belong to the commands it lists). Pinned by `test/cli-help-grammar.test.ts` and the four-part subprocess gate `test/cli-help-no-side-effects*.serial.test.ts` (harness `test/helpers/cli-help-gate.ts`, child probe `test/helpers/cli-side-effect-probe.ts`): every self-help command's `--help`/`-h` and every router subcommand's `--help`/`-h`/`help` on a copy of a seeded PGLite brain, asserting exit 0 with usage, unchanged table rows and HOME/cwd files, and no fetch or spawn. `quarantine` (list, clear, scan) is a router since #6259.
+- `src/cli/subcommands.ts` + `src/cli/router-help.ts` + `src/cli/strict-args.ts` — help never acts (#6114). `subcommands.ts` holds each router command's inventory (`ROUTERS`: pages, cache, integrity, hook, search, edge-proposals, schema, config; each router re-exports its list as `SUBCOMMANDS` and types its dispatch over it, so an unlisted subcommand fails typecheck) and the help grammar: `--help`/`-h` anywhere before `--` (a flag-value slot included) and a bare `help` only as the first token after a router command or one of its subcommands (`search help` stays a query). `cli.ts` decides `cliHelpRequested` once, before the update marker, backup nag and key warnings; on help it calls `printRouterHelp`, which loads only the router's `printUsage`, before any subcommand, thin-client route or engine. `strict-args.ts` is the per-subcommand table for destructive subcommands (pages purge-deleted, cache clear/prune, schema use/downgrade/init/remove-*, integrity auto/reset-progress, search modes --reset and its `--mode <mode>` preview, W4.13: `--source <mode>` is the deprecated alias, and the handler refuses a missing value or conflicting `--mode`/`--source` with exit 2 instead of resetting): an argument the handler would ignore refuses with `invalid_params` (exit 2) after help and before dispatch, with a read-only fix that itself parses under the table (`ask_user` for integrity reset-progress). `STRICT_SELF_HELP_SUBCOMMANDS` is the same table for a self-help command that prints its own per-subcommand help instead of a router inventory: `skillpack reference` (#5491) accepts `<name>` or `--all`, `--workspace`, `--since`, `--apply-clean-hunks`, `--dry-run` and `--json`, so a `--dry-run=true`, a typo or an unknown flag refuses before the apply instead of running it with the flag ignored (the `--harness` lane keeps its own parser; `src/commands/skillpack/reference.ts` re-checks on entry so an in-process caller gets the same refusal). The flag-registry generator skips `strict-args.ts` (its literals belong to the commands it lists). Pinned by `test/cli-help-grammar.test.ts` and the four-part subprocess gate `test/cli-help-no-side-effects*.serial.test.ts` (harness `test/helpers/cli-help-gate.ts`, child probe `test/helpers/cli-side-effect-probe.ts`): every self-help command's `--help`/`-h` and every router subcommand's `--help`/`-h`/`help` on a copy of a seeded PGLite brain, asserting exit 0 with usage, unchanged table rows and HOME/cwd files, and no fetch or spawn. `quarantine` (list, clear, scan) is a router since #6259.
- `src/cli/command-table.ts` + `src/cli/commands/<name>.ts` — one record per CLI-only command (`name`, `phase`, `thinClient`, `selfHelp`, `skipStartupHooks`, `load: () => import('<literal>')`, and the agent-contract fields `json`, `read_only`, `startup`, `end_of_options`, `help: () => import('./help/<name>.ts')` — see `src/cli/help/` in [agent contract](agent-contract.md)). A `selfHelp` record whose handler needs an engine answers `--help` brainless through `SELF_HELP_WITHOUT_ENGINE` in `src/cli.ts` (an explicit loader, or `true` to run the record's own module with a null engine). The records derive `CLI_ONLY`, `CLI_ONLY_SELF_HELP`, `THIN_CLIENT_REFUSED_COMMANDS` and `STARTUP_HOOK_SKIP_COMMANDS` (re-exported from `src/cli.ts`); `cliAliases`' collision check runs over the derived `CLI_ONLY`. Each module holds the body its switch case or plain branch had, moved verbatim, and receives dispatcher-owned pieces through `CliDispatchContext`. Master's membership inconsistencies are preserved (the dead second `auth` branch, the unreachable `capture --help` branch, the `connectors` and `recall` refuse hints that only `connectEngine`'s thin-client backstop reaches (the static extractor reports them as never reached), `watch` refused without a hint, `eval whoknows` shadowed by the refusal) and pinned by `test/fixtures/goldens/cli/membership-sets.json`. Contract: `test/cli-command-table.test.ts`; engine lifecycle per path: `test/cli-dispatch-lifecycle.serial.test.ts`. `json` / `jsonSubcommands` declare the D2 `--json` contract (record-wide / per subcommand).
- `scripts/lib/cli-pipeline.ts` — flattens `handleCliOnly` (inlining `@cliPipelineStage` functions) and reads the command table by AST, for the W0 dispatch-shape extractor (`test/helpers/cli-dispatch-extract.ts`) and `scripts/generate-flag-registry.ts`.
diff --git a/src/cli/strict-args.ts b/src/cli/strict-args.ts
index 9f4b325b27..70d3f07903 100644
--- a/src/cli/strict-args.ts
+++ b/src/cli/strict-args.ts
@@ -82,6 +82,28 @@ export const STRICT_SUBCOMMANDS: Readonly<Record<string, StrictSpec>> = {
},
};
+/**
+ * Strict subcommands of self-help commands that print their own per-subcommand
+ * help (not routers: `gbrain skillpack reference --help` is the reference
+ * command's usage, not an inventory usage). cli.ts applies them exactly like
+ * STRICT_SUBCOMMANDS, after help is resolved and before dispatch; the command
+ * re-checks on its own entry so an in-process caller gets the same refusal.
+ *
+ * `skillpack reference` (#5491): `--apply-clean-hunks` overwrites local skill
+ * edits and `--dry-run` is the only no-write boundary, so a `--dry-run=true`,
+ * a typo or an unknown flag the handler would ignore refuses instead of
+ * running the real apply. The harness lane (`--harness`) has its own parser.
+ */
+export const STRICT_SELF_HELP_SUBCOMMANDS: Readonly<Record<string, StrictSpec>> = {
+ 'skillpack reference': {
+ flags: ['--all', '--apply-clean-hunks', '--dry-run', '--json'],
+ values: { '--workspace': null, '--since': null },
+ maxPositionals: 1,
+ when: args => !args.some(a => a === '--harness' || a.startsWith('--harness=')),
+ fix: { argv: ['skillpack', 'reference', '--all'], why: 'Lists every bundled skill\'s drift against the workspace copy; changes nothing.' },
+ },
+};
+
export interface StrictArgsProblem { token: string; problem: string }
/** The first problem with `args` (the tokens after the subcommand) under `spec`, or null. */
@@ -121,7 +143,7 @@ export function strictArgsProblem(spec: StrictSpec, args: readonly string[]): St
/** The `invalid_params` refusal for `gbrain <command> <sub> ...rest`, or null when the subcommand is not strict or the arguments parse. */
export function strictArgsRefusal(command: string, subArgs: readonly string[]): OperationError | null {
const key = `${command} ${subArgs[0] ?? ''}`;
- const spec = STRICT_SUBCOMMANDS[key];
+ const spec = STRICT_SUBCOMMANDS[key] ?? STRICT_SELF_HELP_SUBCOMMANDS[key];
if (!spec) return null;
const rest = subArgs.slice(1);
if (spec.when && !spec.when(rest)) return null;
diff --git a/src/commands/skillpack/reference.ts b/src/commands/skillpack/reference.ts
index 66059af2ca..159fe587eb 100644
--- a/src/commands/skillpack/reference.ts
+++ b/src/commands/skillpack/reference.ts
@@ -14,6 +14,29 @@ import {
runReferenceApply,
} from '../../core/skillpack/reference.ts';
import { findGbrainOrDie, resolveWorkspace } from './shared.ts';
+import { strictArgsRefusal } from '../../cli/strict-args.ts';
+import { exitCliError } from '../../cli/cli-error.ts';
+
+const REFERENCE_HELP =
+ 'gbrain skillpack reference <name> [--workspace PATH] [--apply-clean-hunks [--dry-run]] [--json]\n' +
+ 'gbrain skillpack reference --all [--workspace PATH] [--since <version>] [--json]\n\n' +
+ ' <name> Read-only diff of gbrain\'s bundle against your local copy.\n' +
+ ' --apply-clean-hunks Two-way merge: align non-conflicting hunks of ONE skill to\n' +
+ ' gbrain. Local edits in those hunks are overwritten; pass the\n' +
+ ' exact --dry-run flag to preview without writing.\n' +
+ ' --all Sweep over every bundled skill (read-only; never applies).\n' +
+ ' --since <version> With --all, restrict the sweep to skills whose source\n' +
+ ' changed in gbrain between <version> and HEAD. Useful\n' +
+ ' after `gbrain upgrade` to see only what moved.\n\n' +
+ 'Any other token, or a flag in a form this command does not read (`--dry-run=true`),\n' +
+ 'refuses with invalid_params before anything is touched.';
+
+const ALL_APPLY_REFUSAL =
+ 'Error: --apply-clean-hunks is intentionally NOT supported with --all (a two-way merge over every\n' +
+ 'skill at once has no safe preview). Update path, one skill at a time:\n' +
+ ' 1. gbrain skillpack reference --all (which skills drifted)\n' +
+ ' 2. gbrain skillpack reference <name> (read the diff; keep intentional edits)\n' +
+ ' 3. gbrain skillpack reference <name> --apply-clean-hunks (add --dry-run to preview first)';
export async function cmdReference(args: string[]): Promise<void> {
// Harness lane (cathedral-7): diff a harness install (stub-aware,
@@ -24,14 +47,14 @@ export async function cmdReference(args: string[]): Promise<void> {
return;
}
if (args.includes('--help') || args.includes('-h')) {
- console.log(
- 'gbrain skillpack reference <name> | --all [--workspace PATH] [--apply-clean-hunks] [--since <version>] [--dry-run] [--json]\n\n' +
- ' --since <version> With --all, restrict the sweep to skills whose source\n' +
- ' changed in gbrain between <version> and HEAD. Useful\n' +
- ' after `gbrain upgrade` to see only what moved.',
- );
+ console.log(REFERENCE_HELP);
process.exit(0);
}
+ // #5491: a token the command would ignore (`--dry-run=true`, a typo) must
+ // not reach the apply. cli.ts refuses before dispatch; this re-check keeps
+ // an in-process caller on the same contract.
+ const refusal = strictArgsRefusal('skillpack', ['reference', ...args]);
+ if (refusal) exitCliError(refusal, 'skillpack');
const json = args.includes('--json');
const apply = args.includes('--apply-clean-hunks');
const dryRun = args.includes('--dry-run');
@@ -66,9 +89,7 @@ export async function cmdReference(args: string[]): Promise<void> {
try {
if (apply) {
if (all) {
- console.error(
- 'Error: --apply-clean-hunks is intentionally NOT supported with --all. Apply one skill at a time.',
- );
+ console.error(ALL_APPLY_REFUSAL);
process.exit(2);
}
// Two-way merge warning fires BEFORE the apply. Goes to stderr so
diff --git a/test/cli-help-grammar.test.ts b/test/cli-help-grammar.test.ts
index 5ee3a972bc..13d4f61c98 100644
--- a/test/cli-help-grammar.test.ts
+++ b/test/cli-help-grammar.test.ts
@@ -6,7 +6,7 @@
import { describe, expect, test } from 'bun:test';
import { ROUTERS, cliHelpRequested, helpFlagRequested, subcommandHelpRequested } from '../src/cli/subcommands.ts';
import { ROUTER_MODULES } from '../src/cli/router-help.ts';
-import { STRICT_SUBCOMMANDS, strictArgsProblem, strictArgsRefusal } from '../src/cli/strict-args.ts';
+import { STRICT_SELF_HELP_SUBCOMMANDS, STRICT_SUBCOMMANDS, strictArgsProblem, strictArgsRefusal } from '../src/cli/strict-args.ts';
import { CLI_COMMANDS } from '../src/cli/command-table.ts';
describe('help grammar', () => {
@@ -58,6 +58,20 @@ describe('router inventories', () => {
});
describe('strict arguments', () => {
+ test('every strict self-help subcommand belongs to a self-help command outside the router inventories, with a read-only fix that parses', () => {
+ for (const [key, spec] of Object.entries(STRICT_SELF_HELP_SUBCOMMANDS)) {
+ const [command, sub] = key.split(' ');
+ expect(ROUTERS[command!], key).toBeUndefined();
+ expect(CLI_COMMANDS.find(c => c.name === command)?.selfHelp, key).toBe(true);
+ const refusal = strictArgsRefusal(command!, [sub!, '--not-a-flag']);
+ expect(refusal?.code, key).toBe('invalid_params');
+ expect('argv' in spec.fix, key).toBe(true);
+ const [, fixCommand, fixSub, ...fixRest] = refusal!.fix!.argv!;
+ expect(strictArgsRefusal(fixCommand!, [fixSub!, ...fixRest]), key).toBeNull();
+ }
+ });
+
+
test('each refusal fix is a read-only command that parses under the same table, or an ask_user fix', () => {
for (const [key, spec] of Object.entries(STRICT_SUBCOMMANDS)) {
const [command, sub] = key.split(' ');
diff --git a/test/skillpack-reference-strict-args.test.ts b/test/skillpack-reference-strict-args.test.ts
new file mode 100644
index 0000000000..85f0a53011
--- /dev/null
+++ b/test/skillpack-reference-strict-args.test.ts
@@ -0,0 +1,138 @@
+/**
+ * `gbrain skillpack reference` argument safety (#5491, wave 14 P1.11).
+ *
+ * Protects: a no-write boundary the user asked for. `--apply-clean-hunks`
+ * overwrites local skill edits; `--dry-run` is the only thing between the
+ * user and that write. Before this fix the handler tested the exact
+ * `--dry-run` token, so `--dry-run=true` (and any typo) ran the real apply.
+ * Regression: a token the command would ignore reaches the writer. Existing
+ * coverage (test/skillpack-reference-apply.test.ts) drives the core
+ * function directly and never sees the CLI flag parse. No production seam:
+ * the child-process cases observe the skill bytes, the in-process cases
+ * spy on the writer the CLI dispatch would reach.
+ */
+import { afterEach, describe, expect, spyOn, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { strictArgsRefusal } from '../src/cli/strict-args.ts';
+import { runSkillpack } from '../src/commands/skillpack.ts';
+import * as referenceCore from '../src/core/skillpack/reference.ts';
+
+const REPO = new URL('..', import.meta.url).pathname.replace(/\/$/, '');
+const SKILL = 'ask-user';
+const created: string[] = [];
+afterEach(() => {
+ while (created.length) rmSync(created.pop()!, { recursive: true, force: true });
+});
+
+/** A workspace whose copy of the bundled skill carries a local edit the apply would align to gbrain. */
+function driftedWorkspace(): { ws: string; file: string; before: string } {
+ const ws = mkdtempSync(join(tmpdir(), 'sp-strict-ws-'));
+ created.push(ws);
+ mkdirSync(join(ws, 'skills', SKILL), { recursive: true });
+ const upstream = readFileSync(join(REPO, 'skills', SKILL, 'SKILL.md'), 'utf-8');
+ const lines = upstream.split('\n');
+ lines.splice(Math.floor(lines.length / 2), 0, 'A local edit the user made on purpose.');
+ const file = join(ws, 'skills', SKILL, 'SKILL.md');
+ writeFileSync(file, lines.join('\n'));
+ return { ws, file, before: readFileSync(file, 'utf-8') };
+}
+
+function runCli(args: string[]) {
+ const r = Bun.spawnSync(['bun', 'src/cli.ts', 'skillpack', 'reference', ...args], {
+ cwd: REPO,
+ env: { ...process.env, NODE_ENV: 'test', GBRAIN_SKIP_STARTUP_HOOKS: '1' },
+ stdout: 'pipe', stderr: 'pipe', timeout: 60_000,
+ });
+ return { exit: r.exitCode, stdout: r.stdout.toString(), stderr: r.stderr.toString() };
+}
+
+describe('strict-args table', () => {
+ test.each([
+ ['--dry-run=true'], ['--dry-run=false'], ['--dry-rnu'], ['--unknown'], ['--json=1'], ['--apply-clean-hunks=yes'],
+ ])('refuses %s with invalid_params and a read-only fix', (bad) => {
+ const refusal = strictArgsRefusal('skillpack', ['reference', SKILL, '--apply-clean-hunks', bad]);
+ expect(refusal?.code).toBe('invalid_params');
+ expect(refusal?.message).toContain(`\`${bad}\``);
+ expect(refusal?.why).toContain('Nothing was changed');
+ expect(refusal?.fix?.argv).toEqual(['gbrain', 'skillpack', 'reference', '--all']);
+ });
+
+ test('accepts both grammars', () => {
+ expect(strictArgsRefusal('skillpack', ['reference', SKILL])).toBeNull();
+ expect(strictArgsRefusal('skillpack', ['reference', SKILL, '--apply-clean-hunks', '--dry-run', '--json'])).toBeNull();
+ expect(strictArgsRefusal('skillpack', ['reference', SKILL, '--workspace', '/tmp/ws'])).toBeNull();
+ expect(strictArgsRefusal('skillpack', ['reference', SKILL, '--workspace=/tmp/ws'])).toBeNull();
+ expect(strictArgsRefusal('skillpack', ['reference', '--all', '--since', '0.59.0.0', '--json'])).toBeNull();
+ expect(strictArgsRefusal('skillpack', ['reference', '--all', '--since=0.59.0.0'])).toBeNull();
+ });
+
+ test('a second positional and a repeated value flag refuse', () => {
+ expect(strictArgsRefusal('skillpack', ['reference', SKILL, 'other'])?.message).toContain('`other`');
+ expect(strictArgsRefusal('skillpack', ['reference', SKILL, '--workspace', 'a', '--workspace', 'b'])?.message).toContain('more than once');
+ });
+
+ test('the harness lane keeps its own parser', () => {
+ expect(strictArgsRefusal('skillpack', ['reference', '--harness', 'claude-code', '--persona', 'gbrain-daily'])).toBeNull();
+ expect(strictArgsRefusal('skillpack', ['reference', '--harness=codex', '--skill', 'brain-ops'])).toBeNull();
+ });
+
+ test('other skillpack subcommands are not strict', () => {
+ expect(strictArgsRefusal('skillpack', ['scaffold', SKILL, '--whatever'])).toBeNull();
+ expect(strictArgsRefusal('skillpack', ['list', '--whatever'])).toBeNull();
+ });
+});
+
+describe('in-process dispatch never reaches the writer', () => {
+ test.each([['--dry-run=true'], ['--dry-run=false'], ['--dry-rnu'], ['--unknown']])('%s exits 2 with zero writer calls', async (bad) => {
+ const { ws, file, before } = driftedWorkspace();
+ const apply = spyOn(referenceCore, 'runReferenceApply');
+ const exit = spyOn(process, 'exit').mockImplementation(((code: number) => { throw new Error(`exit:${code}`); }) as never);
+ const err = spyOn(console, 'error').mockImplementation(() => {});
+ const write = spyOn(process.stderr, 'write').mockImplementation((() => true) as never);
+ try {
+ await expect(runSkillpack(['reference', SKILL, '--apply-clean-hunks', bad, '--workspace', ws])).rejects.toThrow('exit:2');
+ expect(apply).toHaveBeenCalledTimes(0);
+ expect(readFileSync(file, 'utf-8')).toBe(before);
+ } finally {
+ apply.mockRestore(); exit.mockRestore(); err.mockRestore(); write.mockRestore();
+ }
+ });
+});
+
+describe('CLI child process', () => {
+ test.each([['--dry-run=true'], ['--dry-run=false'], ['--dry-rnu'], ['--unknown']])('%s exits 2 and leaves the skill bytes unchanged', (bad) => {
+ const { ws, file, before } = driftedWorkspace();
+ const r = runCli([SKILL, '--apply-clean-hunks', bad, '--workspace', ws]);
+ expect(r.exit).toBe(2);
+ expect(r.stderr).toContain('invalid_params');
+ expect(r.stderr).toContain(bad);
+ expect(readFileSync(file, 'utf-8')).toBe(before);
+ }, 90_000);
+
+ test('the exact --dry-run still previews without writing', () => {
+ const { ws, file, before } = driftedWorkspace();
+ const r = runCli([SKILL, '--apply-clean-hunks', '--dry-run', '--workspace', ws, '--json']);
+ expect(r.exit).toBe(0);
+ expect(JSON.parse(r.stdout).dryRun).toBe(true);
+ expect(readFileSync(file, 'utf-8')).toBe(before);
+ }, 90_000);
+
+ test('--all with --apply-clean-hunks refuses and prints the three-command update path', () => {
+ const { ws } = driftedWorkspace();
+ const r = runCli(['--all', '--apply-clean-hunks', '--workspace', ws]);
+ expect(r.exit).toBe(2);
+ expect(r.stderr).toContain('gbrain skillpack reference --all');
+ expect(r.stderr).toContain('gbrain skillpack reference <name>');
+ expect(r.stderr).toContain('gbrain skillpack reference <name> --apply-clean-hunks');
+ }, 90_000);
+
+ test('help shows the per-skill and --all forms as separate grammars', () => {
+ const r = runCli(['--help']);
+ expect(r.exit).toBe(0);
+ expect(r.stdout).toContain('gbrain skillpack reference <name> [--workspace PATH] [--apply-clean-hunks [--dry-run]] [--json]');
+ expect(r.stdout).toContain('gbrain skillpack reference --all [--workspace PATH] [--since <version>] [--json]');
+ expect(r.stdout).not.toContain('<name> | --all');
+ }, 90_000);
+});