Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/COMMANDS.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,15 @@
| ---------------------------- | ------------------------------------------------------------------------------------------ |
| `--read-only` / `--readonly` | Activate session-wide refusal of every mutating op. Also honored as `KIT_READ_ONLY=1` env. |
| `--non-interactive` | Skip all confirmation prompts. Required in CI / agent contexts. |
| `--env=<name>` | Select the environment overlay (`[env.<name>]` in `.kit.toml`). Also honored as `KIT_ENV`. |
| `--version` / `-v` | Print kit version + exit. |
| `--help` / `-h` | Print top-level help + exit. |

`--read-only`, `--readonly`, `--non-interactive` and `--env=<name>` may be
written before or after the command word — `kit --read-only check` and
`kit check --read-only` are equivalent. Every command accepts them; a command
that rejects unknown flags allows these on top of its own.

## Core lifecycle

| Command | Purpose |
Expand Down
88 changes: 88 additions & 0 deletions src/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1049,3 +1049,91 @@ describe("mcpExposedToolNames", () => {
assert.deepEqual(mcpExposedToolNames(), EXPECTED_MCP_TOOLS);
});
});

// ---------------------------------------------------------------------------
// Global flags: dispatch position + typo rejection
// ---------------------------------------------------------------------------

describe("global flags before the command word", () => {
let tempDir: string;

before(async () => {
tempDir = await mkdtemp(join(tmpdir(), "kit-globalflags-"));
await writeFile(join(tempDir, ".kit.toml"), FIXTURE_EMPTY, "utf-8");
});

after(async () => {
await rm(tempDir, { recursive: true, force: true });
});

it("`kit --read-only check` runs the check instead of 'Unknown command'", async () => {
// README.md and docs/THREAT_MODEL.md both document this exact form. It used to
// activate read-only mode and then refuse to dispatch, because `--read-only`
// WAS args[0] — kit rejected its own documented security-control invocation.
const result = await runCli(["--read-only", "check"], tempDir);
const output = `${result.stdout}${result.stderr}`;
assert.ok(!output.includes("Unknown command"), `kit refused to dispatch:\n${output}`);
assert.ok(output.includes("read-only mode active"), "read-only mode should still activate");
});

it("`kit check --read-only` is not rejected as an unknown flag", async () => {
const result = await runCli(["check", "--read-only"], tempDir);
const output = `${result.stdout}${result.stderr}`;
assert.ok(!output.includes("unknown flag"), `global flag rejected:\n${output}`);
});

it("`kit check --non-interactive` is not rejected as an unknown flag", async () => {
const result = await runCli(["check", "--non-interactive"], tempDir);
const output = `${result.stdout}${result.stderr}`;
assert.ok(!output.includes("unknown flag"), `global flag rejected:\n${output}`);
});

it("a genuinely unknown flag is still rejected", async () => {
const result = await runCli(["check", "--not-a-real-flag"], tempDir);
const output = `${result.stdout}${result.stderr}`;
assert.equal(result.exitCode, 1);
assert.ok(output.includes("unknown flag"), "the rejection must survive the widened allowlist");
});
});

describe("kit upgrade rejects a typo'd flag instead of doing something else", () => {
let tempDir: string;
const LOCK = `{
"tools": {
"node": { "version": "22", "source": "mise", "installedAt": "2020-01-01T00:00:00.000Z" }
}
}
`;

beforeEach(async () => {
tempDir = await mkdtemp(join(tmpdir(), "kit-upgradeflag-"));
await writeFile(join(tempDir, ".kit.toml"), '[tools]\nnode = "22"\n', "utf-8");
await mkdir(join(tempDir, ".kit"), { recursive: true });
await writeFile(join(tempDir, ".kit", "cli-lock.json"), LOCK, "utf-8");
});

afterEach(async () => {
await rm(tempDir, { recursive: true, force: true });
});

it("`--self.` exits 1 and never touches the lock file", async () => {
// The reported failure: a trailing period missed hasFlag's exact match, so the
// self-upgrade silently became the lock-file path — it rewrote every
// installedAt to "now", installed nothing, and printed a success line.
const result = await runCli(["upgrade", "--self."], tempDir);
const output = `${result.stdout}${result.stderr}`;
assert.equal(result.exitCode, 1, `expected rejection, got:\n${output}`);
assert.ok(output.includes("unknown flag"), `no rejection printed:\n${output}`);
const lock = await readFile(join(tempDir, ".kit", "cli-lock.json"), "utf-8");
assert.ok(
lock.includes("2020-01-01T00:00:00.000Z"),
"a rejected invocation must not rewrite installedAt",
);
});

it("plain `kit upgrade` still updates the lock files", async () => {
const result = await runCli(["upgrade"], tempDir);
const output = `${result.stdout}${result.stderr}`;
assert.ok(output.includes("Updated lock files"), `the happy path regressed:\n${output}`);
});
});
25 changes: 18 additions & 7 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { readFileSync, realpathSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { loadConfig } from "./config.js";
import { hasFlag } from "./utils/flags.js";
import { hasFlag, splitLeadingGlobalFlags } from "./utils/flags.js";
import { generateCompletions } from "./completions.js";
import { checkForUpdate, printUpdateNotice } from "./update-check.js";
import { SKIPPED_COMMITS_LOG } from "./hooks.js";
Expand Down Expand Up @@ -280,8 +280,19 @@ async function showSkippedCommitBanner(): Promise<void> {
*/

async function main(): Promise<void> {
const args = process.argv.slice(2);
const command = args[0];
// Global flags may precede the command word (`kit --read-only check`, the form
// README.md:299 and docs/THREAT_MODEL.md:98 document). Move them behind the
// positionals — and rewrite process.argv to match — so command modules that
// read subcommands off raw indices (`process.argv[3]`) see the same shape they
// would for `kit check ...`. Without this the flag WAS the command and kit
// answered "Unknown command: --read-only".
const rawArgs = process.argv.slice(2);
const { leading: leadingGlobals, rest: positional } = splitLeadingGlobalFlags(rawArgs);
const args = leadingGlobals.length > 0 ? [...positional, ...leadingGlobals] : rawArgs;
if (leadingGlobals.length > 0) {
process.argv = [...process.argv.slice(0, 2), ...args];
}
const command = positional[0];
const nonInteractive =
hasFlag(args, "--non-interactive") ||
process.env.CI === "true" ||
Expand Down Expand Up @@ -326,12 +337,12 @@ async function main(): Promise<void> {
let ok: boolean;

// --version / --help flags before the switch
if (args[0] === "--version" || args[0] === "-v") {
if (positional[0] === "--version" || positional[0] === "-v") {
ok = cmdVersion();
process.exitCode = ok ? 0 : 1;
return;
}
if (args[0] === "--help" || args[0] === "-h") {
if (positional[0] === "--help" || positional[0] === "-h") {
ok = cmdHelp();
process.exitCode = 0;
return;
Expand All @@ -352,9 +363,9 @@ async function main(): Promise<void> {
if (command === "version") {
ok = cmdVersion();
} else if (command === "help") {
ok = cmdHelp(args[1]);
ok = cmdHelp(positional[1]);
} else if (command === "completions") {
const shell = args[1];
const shell = positional[1];
const script = generateCompletions(shell);
if (!script) {
console.error(`Unknown shell: ${shell}. Use: bash, zsh, fish`);
Expand Down
16 changes: 16 additions & 0 deletions src/commands/check-flags.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { readFileSync } from "node:fs";
import { resolve } from "node:path";

import { CHECK_FLAGS } from "./check.js";
import { GLOBAL_FLAGS } from "../utils/flags.js";

/**
* The allowlist behind `kit check`'s unknown-flag rejection must cover every flag the check path
Expand Down Expand Up @@ -73,3 +74,18 @@ describe("kit check flag allowlist", () => {
for (const f of CHECK_FLAGS) assert.match(f, /^--[a-z][a-z0-9-]*$/, f);
});
});

describe("kit check accepts the documented global flags", () => {
/**
* `--read-only` and `--non-interactive` are honored by cli.ts for every command
* and are in docs/COMMANDS.md's global table, but CHECK_FLAGS was built from the
* check path's own literals — so `kit check --read-only` exited 1 with "unknown
* flag" and the security check never ran. Same class as the `--attest` break
* above: a gate that refuses to run is a false red.
*/
it("CHECK_FLAGS is a superset of GLOBAL_FLAGS", () => {
const allowed = new Set<string>(CHECK_FLAGS);
const missing = (GLOBAL_FLAGS as readonly string[]).filter((f) => !allowed.has(f));
assert.deepEqual(missing, [], `globals kit check would reject: ${missing.join(", ")}`);
});
});
11 changes: 8 additions & 3 deletions src/commands/check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
*/
import { resolve } from "node:path";
import { c } from "../utils/colors.js";
import { hasFlag, flagValue, envTruthy, unknownFlags } from "../utils/flags.js";
import { hasFlag, flagValue, envTruthy, unknownFlags, GLOBAL_FLAGS } from "../utils/flags.js";
import { loadConfig } from "../config.js";
import { resolveConfigPath } from "../cli-shared.js";
import { withGovernance } from "../governance-middleware.js";
Expand Down Expand Up @@ -70,9 +70,14 @@ export const CHECK_FLAGS = [
"--key",
"--attest", // cli-checks-shared.ts:emitAttestation
"--no-auto-install", // cli-checks-shared.ts:autoInstallScanners
// Honored for every command by cli.ts / config.ts, not by the check path itself.
// Omitting them made `kit check --read-only` and `kit check --non-interactive`
// — both in the "Global flags" table of docs/COMMANDS.md — exit 1 without
// running the check: the same false-red as the `--attest` regression above.
...GLOBAL_FLAGS,
] as const;
const COMPARE_FLAGS = ["--json", "--fail-on-worse"] as const;
const VERIFY_FLAGS = ["--json", "--key"] as const;
const COMPARE_FLAGS = ["--json", "--fail-on-worse", ...GLOBAL_FLAGS] as const;
const VERIFY_FLAGS = ["--json", "--key", ...GLOBAL_FLAGS] as const;

/** Print the rejection and return false, so every caller fails the same way. */
function rejectUnknownFlags(form: string, allowed: readonly string[]): boolean {
Expand Down
20 changes: 19 additions & 1 deletion src/commands/upgrade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
* four are exported. Imports only sibling core modules, never cli.ts.
*/
import { c } from "../utils/colors.js";
import { hasFlag } from "../utils/flags.js";
import { hasFlag, unknownFlags, GLOBAL_FLAGS } from "../utils/flags.js";
import { loadConfig } from "../config.js";
import { resolveConfigPath } from "../cli-shared.js";
import { readkitMeta, updateSkillsLock, updateCliLock } from "../lock.js";
Expand Down Expand Up @@ -98,10 +98,28 @@ export async function selfUpgrade(): Promise<boolean> {
}
}

/**
* Every flag `kit upgrade` honors. `--self` is the only one the command reads;
* the globals are honored by cli.ts / config.ts for every command.
*/
export const UPGRADE_FLAGS = ["--self", ...GLOBAL_FLAGS] as const;

export async function cmdUpgrade(): Promise<boolean> {
console.log(`${c.bold}${c.cyan}kit upgrade${c.reset}`);
console.log(`${c.dim}${"─".repeat(50)}${c.reset}\n`);

// A typo'd flag must not silently become a DIFFERENT operation. `kit upgrade
// --self.` (trailing period) missed the exact-match in hasFlag, fell through
// to the lock-file path, and rewrote every `installedAt` in .kit/cli-lock.json
// to "now" while installing nothing — reported as a successful upgrade.
const bad = unknownFlags(process.argv, UPGRADE_FLAGS);
if (bad.length > 0) {
const plural = bad.length > 1 ? "s" : "";
console.error(`${c.red}unknown flag${plural} for kit upgrade: ${bad.join(", ")}${c.reset}`);
console.error(`${c.dim}accepted: ${UPGRADE_FLAGS.join(" ")}${c.reset}`);
return false;
}

if (hasFlag(process.argv, "--self")) {
return await selfUpgrade();
}
Expand Down
89 changes: 88 additions & 1 deletion src/utils/flags.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import { hasFlag, flagValue, flagInt, unknownFlags } from "./flags.js";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import {
hasFlag,
flagValue,
flagInt,
unknownFlags,
GLOBAL_FLAGS,
splitLeadingGlobalFlags,
} from "./flags.js";

describe("flag helpers", () => {
describe("hasFlag", () => {
Expand Down Expand Up @@ -154,3 +163,81 @@ describe("flagInt — boundaries and malformed input", () => {
assert.equal(flagInt(["--", "--ttl-minutes", "30"], "--ttl-minutes", 5), 30);
});
});

describe("GLOBAL_FLAGS", () => {
/**
* The ORACLE is docs/COMMANDS.md's "Global flags" table, not a second copy of
* the list: `kit check --read-only` shipped broken precisely because the only
* thing asserting the allowlist was the allowlist. If a global is documented,
* a command allowlist must accept it.
*/
function documentedGlobals(): string[] {
const root = resolve(import.meta.dirname, "..", "..");
const doc = readFileSync(resolve(root, "docs", "COMMANDS.md"), "utf-8");
const start = doc.indexOf("## Global flags");
assert.ok(start >= 0, "docs/COMMANDS.md no longer has a '## Global flags' section");
const section = doc.slice(start, doc.indexOf("\n## ", start + 1));
const flags = new Set<string>();
for (const m of section.matchAll(/`(--[a-z][a-z0-9-]*)`/g)) flags.add(m[1]);
return [...flags];
}

it("the oracle itself finds something (a regex that matches nothing reads as full coverage)", () => {
const found = documentedGlobals();
assert.ok(found.length >= 4, `the docs scan found only ${found.length} global flags`);
assert.ok(found.includes("--read-only"), "expected the scan to see --read-only");
});

it("every flag documented as global is in GLOBAL_FLAGS", () => {
const allowed = new Set<string>(GLOBAL_FLAGS);
const missing = documentedGlobals().filter((f) => !allowed.has(f));
assert.deepEqual(missing, [], `documented as global but rejectable by a command: ${missing}`);
});

it("includes --env, which config.ts honors globally off raw argv", () => {
// resolveActiveEnvironment() reads `--env=<name>` from process.argv for every
// command, so a command allowlist that omits it rejects a working flag.
assert.ok((GLOBAL_FLAGS as readonly string[]).includes("--env"));
});
});

describe("splitLeadingGlobalFlags", () => {
it("moves a leading global off the front so the command word is positional 0", () => {
const { leading, rest } = splitLeadingGlobalFlags(["--read-only", "check"]);
assert.deepEqual(leading, ["--read-only"]);
assert.deepEqual(rest, ["check"]);
});

it("preserves subcommand positions (the reason raw argv indices break)", () => {
const { rest } = splitLeadingGlobalFlags(["--read-only", "check", "verify-attestation"]);
// commands/check.ts reads process.argv[3] === "verify-attestation"
assert.equal(rest[1], "verify-attestation");
});

it("takes several leading globals, including --env=<name>", () => {
const { leading, rest } = splitLeadingGlobalFlags([
"--non-interactive",
"--env=prod",
"secrets",
]);
assert.deepEqual(leading, ["--non-interactive", "--env=prod"]);
assert.deepEqual(rest, ["secrets"]);
});

it("stops at the command word — a global AFTER it is the command's to see", () => {
const { leading, rest } = splitLeadingGlobalFlags(["check", "--read-only"]);
assert.deepEqual(leading, []);
assert.deepEqual(rest, ["check", "--read-only"]);
});

it("leaves --version / --help alone: as token 0 they ARE the command", () => {
assert.deepEqual(splitLeadingGlobalFlags(["--version"]).rest, ["--version"]);
assert.deepEqual(splitLeadingGlobalFlags(["--help"]).rest, ["--help"]);
});

it("does not eat a command-specific flag it has never heard of", () => {
const { leading, rest } = splitLeadingGlobalFlags(["--nope", "check"]);
assert.deepEqual(leading, []);
assert.deepEqual(rest, ["--nope", "check"]);
});
});
Loading
Loading