diff --git a/packages/coding-agent/schema/config.schema.json b/packages/coding-agent/schema/config.schema.json index ec9aef5a..5e80a488 100644 --- a/packages/coding-agent/schema/config.schema.json +++ b/packages/coding-agent/schema/config.schema.json @@ -1571,7 +1571,7 @@ "const": "tinyfish" } ], - "description": "Web search backend. `auto` (default) walks the chain; a backend id pins one; `off` keeps the tool but refuses calls. The runtime treats an unrecognized value as `auto`, so a misspelling silently disables the pin instead of failing." + "description": "Web search backend. `auto` (default) walks the chain; a backend id pins one; `off` keeps the tool but refuses calls. The runtime treats an unrecognized value as `auto`, so a misspelling silently disables the pin instead of failing; `step config check` flags it." } }, "additionalProperties": false, diff --git a/packages/coding-agent/src/cli/args.ts b/packages/coding-agent/src/cli/args.ts index e2367ede..1937cd52 100644 --- a/packages/coding-agent/src/cli/args.ts +++ b/packages/coding-agent/src/cli/args.ts @@ -661,7 +661,8 @@ ${chalk.bold("Configuration:")} ~/.stepcode/models.json Custom providers and models .stepcode/config.toml Project overrides, loaded when the project is trusted ${APP_NAME} config show Print the stored config.toml, models.json, and paths - ${APP_NAME} config schema Print the JSON Schema an editor completes against` + ${APP_NAME} config schema Print the JSON Schema an editor completes against + ${APP_NAME} config check Report keys and values this build would ignore` : ""; const extensionFlagsText = extensionFlags && extensionFlags.length > 0 diff --git a/packages/coding-agent/src/package-manager-cli.ts b/packages/coding-agent/src/package-manager-cli.ts index c28f9eb0..c60dbae3 100644 --- a/packages/coding-agent/src/package-manager-cli.ts +++ b/packages/coding-agent/src/package-manager-cli.ts @@ -81,8 +81,9 @@ project-local modes. Settings themselves (models, compaction, permissions, search, MCP servers) live in the same config.toml. \`config show\` prints the stored global and project documents with credentials redacted, \`config schema\` prints the JSON Schema an -editor completes and validates against, and \`config init\` writes a template -plus that schema beside the global file. +editor completes and validates against, \`config check\` reports keys and values +this build would ignore, and \`config init\` writes a template plus that schema +beside the global file. Options: -l, --local Edit project overrides (${CONFIG_DIR_NAME}/config.toml) diff --git a/packages/coding-agent/src/step/command-compat.ts b/packages/coding-agent/src/step/command-compat.ts index 66feb48c..655f5b7f 100644 --- a/packages/coding-agent/src/step/command-compat.ts +++ b/packages/coding-agent/src/step/command-compat.ts @@ -11,6 +11,7 @@ import { existsSync, readFileSync } from "node:fs"; import { mkdir, readFile, writeFile } from "node:fs/promises"; import { basename, dirname, extname, join, resolve } from "node:path"; +import { checkStepConfigFiles, describePath } from "./config-check.ts"; import { CONFIG_SCHEMA_FILE_NAME, MODELS_SCHEMA_FILE_NAME, @@ -361,6 +362,51 @@ export async function runStepConfigCommand(argv: readonly string[], io: StepConf return; } + if (subcommand === "check") { + const result = checkStepConfigFiles({ + globalSettings: paths.globalSettings, + projectSettings: paths.projectSettings, + models: paths.globalModels, + }); + + if (argv.includes("--json")) { + stdout.write( + `${JSON.stringify( + { + ok: result.problems.length === 0, + checkedFiles: result.checkedFiles, + notes: result.notes, + problems: result.problems, + }, + null, + 2, + )}\n`, + ); + } else if (result.problems.length === 0) { + stdout.write(`Configuration is valid: ${result.checkedFiles.join(", ") || "(no files yet)"}\n`); + for (const note of result.notes) stdout.write(`note: ${note}\n`); + } else { + for (const problem of result.problems) { + const where = problem.path ? `${problem.file}:${describePath(problem.path)}` : problem.file; + stdout.write(`${where}: ${problem.message}\n`); + } + for (const note of result.notes) stdout.write(`note: ${note}\n`); + } + // An unknown key means this binary ignores it, which is a real problem for + // the file's author but not for someone reading a config written by a newer + // release. `--allow-unknown` downgrades those to a note. + const blocking = argv.includes("--allow-unknown") + ? result.problems.filter((problem) => problem.kind !== "unknown") + : result.problems; + if (blocking.length > 0) { + const count = blocking.length; + throw new Error( + `${count} configuration ${count === 1 ? "problem" : "problems"} found. Run "step config schema" for the full key list.`, + ); + } + return; + } + if (subcommand === "show") { const json = argv.includes("--json"); const readJson = async (path: string): Promise => { @@ -534,6 +580,16 @@ function stepConfigUsage(subcommand: string): string { "Usage: step config init [--scope user|workspace] [--path ] [--force]", " Write a Step config template. Defaults to the user scope; --force overwrites an existing file.", ].join("\n"); + case "check": + return [ + "Usage: step config check [--json] [--allow-unknown]", + " Validate the global and project config.toml plus models.json against the", + " schema this build ships. An unknown key or a rejected value is reported", + " and the exit code is 1.", + " --allow-unknown Do not fail on a key this build does not read. Use it in", + " CI for a config shared with a newer release; the key is", + " still reported.", + ].join("\n"); case "schema": return [ "Usage: step config schema [config|models] [--out ]", diff --git a/packages/coding-agent/src/step/config-check.ts b/packages/coding-agent/src/step/config-check.ts new file mode 100644 index 00000000..e86eacab --- /dev/null +++ b/packages/coding-agent/src/step/config-check.ts @@ -0,0 +1,545 @@ +/** + * Validate the configuration files a build reads against the schema it ships. + * + * The runtime never refuses to start over a setting: an unrecognized value + * falls back to its default with a warning, and an unknown key is carried along + * and ignored. That is the right behavior for a running session, but it is also + * why "I configured it and nothing changed" is hard to notice. `step config + * check` answers the question a running session cannot: is every key and value + * in this file actually used? + * + * Any rejection is reported and fails the check, because a rejected key or + * value does not do what it says. A file that cannot be parsed is reported + * instead, and the rest of that file is skipped. + */ + +import { existsSync, readFileSync } from "node:fs"; +import { parse as parseToml } from "smol-toml"; +import { Compile } from "typebox/compile"; +import type { TLocalizedValidationError } from "typebox/error"; +import { Settings as TypeBoxSettings } from "typebox/system"; +import { stripJsonComments } from "../utils/json.ts"; +import { stripBom } from "../utils/text.ts"; +import { ConfigTomlSchema, renderStrictModelsSchema } from "./config-schema.ts"; +import { configSchemaDirective } from "./schema-files.ts"; +import { STEPCODE_VERSION } from "./version.ts"; + +type Validator = { + Check: (value: unknown) => boolean; + Errors: (value: unknown) => TLocalizedValidationError[]; +}; + +type JsonNode = { + readonly type?: string; + readonly anyOf?: readonly JsonNode[]; + readonly oneOf?: readonly JsonNode[]; + readonly const?: unknown; + readonly enum?: readonly unknown[]; + readonly properties?: Record; + readonly patternProperties?: Record; + readonly items?: JsonNode; + readonly additionalProperties?: boolean | JsonNode; +}; + +const validateConfig: Validator = Compile(ConfigTomlSchema); +// The editor schema, not the loader's: an unknown field in models.json is never +// read, and `check` exists to say so. +const modelsSchemaJson = JSON.parse(renderStrictModelsSchema()) as object; +const validateModels: Validator = Compile(modelsSchemaJson); + +export interface ConfigProblem { + /** File the problem was found in, as reported to the user. */ + readonly file: string; + /** + * JSON Pointer into the document. Keys are escaped, so a key that itself + * contains `/` or a dot stays unambiguous + * (`/compaction/modelTriggerRatios/vendor~1model.3`). + */ + readonly path: string; + readonly message: string; + /** + * `unknown` means this build does not read the key; `invalid` means it reads it + * and rejects the value. A reader can filter on this without parsing messages. + */ + readonly kind: "unknown" | "invalid" | "parse"; +} + +export interface ConfigCheckResult { + readonly problems: readonly ConfigProblem[]; + /** Files that were read; a missing optional file is not a problem. */ + readonly checkedFiles: readonly string[]; + /** + * Context a reader needs to interpret the problems, such as a project file + * that the runtime only loads when the project is trusted. + */ + readonly notes: readonly string[]; +} + +const escapePointer = (segment: string) => segment.replace(/~/g, "~0").replace(/\//g, "~1"); +const unescapePointer = (segment: string) => segment.replace(/~1/g, "/").replace(/~0/g, "~"); + +/** Human-readable form of a pointer, for the one-line output. */ +export function describePath(path: string): string { + const segments = path.split("/").filter((segment) => segment.length > 0); + return segments + .map((segment) => { + const key = unescapePointer(segment); + // A key that contains a dot is shown bracketed so it cannot be mistaken + // for two levels. + return key.includes(".") ? `["${key}"]` : key; + }) + .join(".") + .replace(/\.\["/g, '["'); +} + +/** Whether a node accepts one of several shapes. */ +function unionMembers(node: JsonNode): readonly JsonNode[] | undefined { + return node.anyOf ?? node.oneOf; +} + +/** The object-shaped members of a union, or the node itself when it is one. */ +function objectShapes(node: JsonNode): JsonNode[] { + const members = unionMembers(node); + if (!members) return node.properties || node.patternProperties ? [node] : []; + return members.flatMap(objectShapes); +} + +/** Schema node at a pointer, preferring a concrete property over a wildcard. */ +function nodeAt(schema: JsonNode, segments: readonly string[]): JsonNode | undefined { + let node: JsonNode | undefined = schema; + for (const segment of segments) { + if (!node) return undefined; + if (node.items) { + // A pointer inside an array carries the index; `items` describes every + // element, so descend without consuming the index segment. + node = node.items; + continue; + } + const key = unescapePointer(segment); + const byName: JsonNode | undefined = node.properties?.[key]; + if (byName) { + node = byName; + continue; + } + const patterns: Array<[string, JsonNode]> = node.patternProperties ? Object.entries(node.patternProperties) : []; + const matched: JsonNode | undefined = patterns.find(([pattern]) => new RegExp(pattern).test(key))?.[1]; + if (matched) { + node = matched; + continue; + } + const shape: JsonNode | undefined = objectShapes(node)[0]; + if (!shape) return undefined; + node = shape.properties?.[key] ?? patterns[0]?.[1]; + } + return node; +} + +/** Literal values a node accepts, when it is a closed set. */ +function literalsOf(node: JsonNode): string[] | undefined { + const members = unionMembers(node); + if (members) { + // A union may mix literals with plain types (`boolean | "auto"`). List the + // literals and the types together, so the message covers every member + // instead of naming only one of them. + const described = members.map((member) => { + if (member.const !== undefined) return JSON.stringify(member.const); + if (member.enum) return `one of ${member.enum.map((value) => JSON.stringify(value)).join(", ")}`; + return member.type ? `${/^[aeiou]/i.test(member.type) ? "an" : "a"} ${member.type}` : undefined; + }); + return described.some((entry) => entry === undefined) ? undefined : [...new Set(described as string[])]; + } + const values = node.enum ? [...node.enum] : node.const !== undefined ? [node.const] : []; + return values.length > 0 ? values.map((value) => JSON.stringify(value)) : undefined; +} + +/** + * Walk the document once, recording unknown keys and a translation from the raw + * pointer TypeBox produces to a correctly escaped one. + * + * The translation exists because TypeBox builds `instancePath` by joining raw + * key text with `/`. For a record key that contains a slash, such as + * `modelTriggerRatios["vendor/model.3"]`, the raw path is indistinguishable from + * two nested levels, so the reported path would point at a key that does not + * exist. + */ +interface Walk { + readonly unknown: string[]; + readonly canonical: Map; +} + +function walkDocument(schema: JsonNode, document: unknown, pointer = "", rawPath = ""): Walk { + const unknown: string[] = []; + const canonical = new Map(); + + const visit = (node: JsonNode, value: unknown, pointerPath: string, raw: string): void => { + canonical.set(raw, pointerPath); + if (Array.isArray(value)) { + if (!node.items) return; + value.forEach((entry, index) => { + visit(node.items!, entry, `${pointerPath}/${index}`, `${raw}/${index}`); + }); + return; + } + if (value === null || typeof value !== "object") return; + + const shapes = objectShapes(node); + if (shapes.length === 0) return; + + for (const [key, entry] of Object.entries(value as Record)) { + const escaped = escapePointer(key); + const childPointer = `${pointerPath}/${escaped}`; + const childRaw = `${raw}/${key}`; + + let child: JsonNode | undefined; + for (const shape of shapes) { + child = shape.properties?.[key]; + if (child) break; + const patterns = shape.patternProperties ? Object.entries(shape.patternProperties) : []; + child = patterns.find(([pattern]) => new RegExp(pattern).test(key))?.[1]; + if (child) break; + } + + if (!child) { + // Every shape that reached this point rejected the key. + unknown.push(childPointer); + continue; + } + visit(child, entry, childPointer, childRaw); + } + }; + + visit(schema, document, pointer, rawPath); + return { unknown, canonical }; +} + +/** + * Fields the loaders compare case-insensitively after trimming. + * + * `normalizeStepPermissionPresetId` and `normalizeStepPermissionMode` both call + * `trim().toLowerCase()`, so `"Ask"` and `" full-access "` are valid values. + * JSON Schema cannot express a case-insensitive enum, so the copy is normalized + * before it is validated — the alternative is rejecting a file the runtime + * honors. + */ +const CASE_INSENSITIVE_PATHS = [ + ["permissionPreset"], + ["permissionMode"], + ["approvalMode"], + ["nonInteractiveApproval"], + ["noninteractiveApproval"], + ["approval", "preset"], + ["approval", "mode"], + ["approval", "nonInteractive"], + ["approval", "noninteractive"], + ["tools", "approval", "preset"], + ["tools", "approval", "mode"], + ["tools", "approval", "nonInteractive"], + ["tools", "approval", "noninteractive"], + // `parseHttpIdleTimeoutMs` lowercases and trims before comparing. + ["httpIdleTimeoutMs"], + ["websocketConnectTimeoutMs"], +] as const; + +/** A copy with those fields lowercased and trimmed. */ +function normalizeCaseInsensitiveFields(document: Record): Record { + const normalized = structuredClone(document); + for (const path of CASE_INSENSITIVE_PATHS) { + let node: Record | undefined = normalized; + for (const segment of path.slice(0, -1)) { + const child: unknown = node?.[segment]; + node = + child && typeof child === "object" && !Array.isArray(child) + ? (child as Record) + : undefined; + } + const leaf = path[path.length - 1]!; + const value = node?.[leaf]; + if (node && typeof value === "string") node[leaf] = value.trim().toLowerCase(); + } + return normalized; +} + +/** + * TypeBox stops collecting after eight errors by default, which would make a + * file with more problems look like it had eight. The limit is raised for the + * duration of one validation and restored after, so the process-wide setting + * other callers see is unchanged. + */ +function withRaisedErrorLimit(run: () => T): T { + const previous = TypeBoxSettings.Get().maxErrors; + TypeBoxSettings.Set({ maxErrors: 10_000 }); + try { + return run(); + } finally { + TypeBoxSettings.Set({ maxErrors: previous }); + } +} + +/** Validate one document, returning its problems. */ +export function checkConfigDocument(file: string, document: unknown, target: "config" | "models"): ConfigProblem[] { + return withRaisedErrorLimit(() => checkConfigDocumentInner(file, document, target)); +} + +function checkConfigDocumentInner(file: string, document: unknown, target: "config" | "models"): ConfigProblem[] { + const validator = target === "models" ? validateModels : validateConfig; + const schema = (target === "models" ? modelsSchemaJson : ConfigTomlSchema) as unknown as JsonNode; + // The file is validated as written, not after the load path's legacy + // rewrites. Migrating first would report a path the user cannot find: a bad + // `queueMode` would come back as `/steeringMode`, and a value the rewrite + // drops (`retry.maxDelayMs = "abc"`) would disappear from the report + // entirely. Those keys are in the schema instead, so a file that uses one is + // valid and a malformed one is still visible here. + const candidate = + target === "config" && document && typeof document === "object" && !Array.isArray(document) + ? normalizeCaseInsensitiveFields(document as Record) + : document; + if (validator.Check(candidate)) return []; + + const walk = walkDocument(schema, candidate); + const reportedUnknown = new Set(walk.unknown); + const problems: ConfigProblem[] = []; + + for (const pointerPath of [...reportedUnknown].sort()) { + const segments = pointerPath.split("/").filter((segment) => segment.length > 0); + const name = unescapePointer(segments[segments.length - 1] ?? ""); + const parent = nodeAtPath(schema, `/${segments.slice(0, -1).join("/")}`); + const suggestion = nearestKey(name, parent); + problems.push({ + file, + path: pointerPath, + kind: "unknown", + message: [ + `this build (${STEPCODE_VERSION.value}) does not read "${name}", so the setting has no effect`, + suggestion ? `did you mean "${suggestion}"?` : undefined, + ] + .filter(Boolean) + .join("; "), + }); + } + + const canonicalPath = (error: TLocalizedValidationError): string => + walk.canonical.get(error.instancePath) ?? error.instancePath; + + const insideUnknown = (path: string): boolean => { + for (const known of reportedUnknown) if (path === known || path.startsWith(`${known}/`)) return true; + return false; + }; + + // Two passes: collect first, decide second. Deciding while collecting made the + // result depend on the order TypeBox happened to report errors in, and a + // union with both literal and non-literal members produced two messages for + // the same path. + const literalFailures = new Map(); + const typeFailures = new Map(); + const collectionFailures = new Map(); + const direct: Array<{ path: string; message: string }> = []; + const seen = new Set(); + const errors = validator.Errors(candidate).map((error) => ({ error, path: canonicalPath(error) })); + + /** + * Whether something below this path already explains the failure. + * + * Unknown keys are recorded by the walk rather than by TypeBox, so they have + * to be included: `packages = [{ source: "x", bogus: 1 }]` is a valid object + * with one unknown field, and the union summary would contradict that. + */ + const hasFailedDescendant = (path: string): boolean => + errors.some(({ path: other }) => other.startsWith(`${path}/`) && other !== path) || + [...reportedUnknown].some((known) => known.startsWith(`${path}/`)); + + for (const { error, path } of errors) { + if (path && insideUnknown(path)) continue; + const node = nodeAtPath(schema, path); + + if (error.keyword === "const" || error.keyword === "enum") { + const list = literalFailures.get(path) ?? []; + list.push(error.message); + literalFailures.set(path, list); + continue; + } + if (error.keyword === "anyOf" || error.keyword === "oneOf") continue; + // Reported by the walk with a better message. + if (error.keyword === "additionalProperties") continue; + + if (error.keyword === "type" && node && unionMembers(node)) { + // The union's own `type` failure is a summary of its members. It is + // worth reporting only when nothing below it failed: a failure inside + // an object member already says what is wrong, and the parent message + // would contradict it. + const list = typeFailures.get(path) ?? []; + list.push(describeType(error)); + typeFailures.set(path, list); + continue; + } + + // A `collection` limit on an object or array is also a summary; the + // concrete failure inside it is the useful one. + if ((error.keyword === "minItems" || error.keyword === "maxItems") && node) { + const list = collectionFailures.get(path) ?? []; + list.push(error.message); + collectionFailures.set(path, list); + continue; + } + + direct.push({ path, message: error.message }); + } + + // One message per field. A union with a constrained member produces one plain + // failure per member (`pattern`, `type`), and listing them separately makes + // the same value look like several problems. + const byField = new Map(); + for (const { path, message } of direct) { + const list = byField.get(path) ?? []; + if (!list.includes(message)) list.push(message); + byField.set(path, list); + } + for (const [path, messages] of byField) { + // The union summary below covers the field when one is available. + if (literalFailures.has(path) || typeFailures.has(path)) continue; + const key = `${path}\0${messages.join("|")}`; + if (seen.has(key)) continue; + seen.add(key); + problems.push({ file, path, kind: "invalid", message: messages.join("; ") }); + } + + for (const [path, messages] of collectionFailures) { + if (hasFailedDescendant(path)) continue; + problems.push({ file, path, kind: "invalid", message: messages[0]! }); + } + + // One message per field, whatever mix of literal and non-literal members it + // accepts: `hyperlink` is a boolean or "auto", and saying only one of those + // is worse than saying neither. + for (const path of new Set([...literalFailures.keys(), ...typeFailures.keys()])) { + const node = nodeAtPath(schema, path); + const literals = node ? literalsOf(node) : undefined; + const shapes = [...new Set(typeFailures.get(path) ?? [])]; + // A failure inside a member already explains the value; the union summary + // would contradict it (`packages = [{ source: 1 }]` is a valid object). + if (hasFailedDescendant(path)) continue; + + const parts = [...new Set([...shapes, ...(literals ?? [])])]; + const message = + parts.length > 0 + ? `must be ${parts.join(" or ")}` + : `value is not accepted (${literalFailures.get(path)?.[0] ?? "no member matched"})`; + problems.push({ file, path, kind: "invalid", message }); + } + + return problems; +} + +/** + * The declared key closest to `name`, when it is close enough to be a typo. + * + * A one-character edit covers the common case (`baseurl` for `baseUrl`, + * `triggerRation` for `triggerRatio`). Below that threshold the key is more + * likely from a newer release, and guessing would be misleading. + */ +function nearestKey(name: string, parent: JsonNode | undefined): string | undefined { + const candidates = Object.keys(parent?.properties ?? {}); + if (candidates.length === 0) return undefined; + const lower = name.toLowerCase(); + let best: { key: string; distance: number } | undefined; + for (const candidate of candidates) { + const distance = editDistance(lower, candidate.toLowerCase()); + if (!best || distance < best.distance) best = { key: candidate, distance }; + } + // Case-only differences and one edit, but never for a very short key where + // almost anything is "one edit away". + const allowed = Math.max(1, Math.floor(name.length / 3)); + return best && best.distance <= allowed ? best.key : undefined; +} + +/** Levenshtein distance, capped by the caller's threshold. */ +function editDistance(a: string, b: string): number { + const rows = a.length + 1; + const cols = b.length + 1; + let previous = Array.from({ length: cols }, (_, index) => index); + for (let row = 1; row < rows; row += 1) { + const current = [row]; + for (let col = 1; col < cols; col += 1) { + const substitution = a[row - 1] === b[col - 1] ? 0 : 1; + current[col] = Math.min(previous[col]! + 1, current[col - 1]! + 1, previous[col - 1]! + substitution); + } + previous = current; + } + return previous[cols - 1]!; +} + +/** The JSON type an error names, phrased for a reader. */ +function describeType(error: TLocalizedValidationError): string { + const expected = (error.params as { type?: string }).type; + if (!expected) return "the expected shape"; + const article = /^[aeiou]/i.test(expected) ? "an" : "a"; + return `${article} ${expected}`; +} + +function nodeAtPath(schema: JsonNode, pointer: string): JsonNode | undefined { + const segments = pointer.split("/").filter((segment) => segment.length > 0); + return nodeAt(schema, segments); +} + +function parseProblem(file: string, error: unknown): ConfigProblem { + return { + file, + path: "", + message: error instanceof Error ? error.message : String(error), + kind: "parse", + }; +} + +/** + * Check the files that exist. A missing project file is normal, so it is + * skipped rather than reported. + */ +export function checkStepConfigFiles(paths: { + readonly globalSettings: string; + readonly projectSettings: string; + readonly models: string; +}): ConfigCheckResult { + const problems: ConfigProblem[] = []; + const checkedFiles: string[] = []; + const notes: string[] = []; + + // Editor support needs one comment line the file may not have. Saying so is + // cheaper than writing into a file the user has not asked us to change. + const globalHeader = existsSync(paths.globalSettings) + ? readFileSync(paths.globalSettings, "utf8").split("\n").slice(0, 20).join("\n") + : ""; + if (globalHeader.length > 0 && !/^#:schema\s/m.test(globalHeader)) { + notes.push( + `add "${configSchemaDirective()}" as the first line of ${paths.globalSettings} for editor completions`, + ); + } + + // The project file is read here so a contributor can check it before + // committing, but a launch only loads it when the project is trusted. Saying + // so keeps "this file is wrong" from reading as "this is what runs". + if (existsSync(paths.projectSettings)) { + notes.push(`${paths.projectSettings}: only loaded when the project is trusted; use --approve or /trust`); + } + + for (const file of [paths.globalSettings, paths.projectSettings]) { + if (!existsSync(file)) continue; + checkedFiles.push(file); + try { + problems.push(...checkConfigDocument(file, parseToml(readFileSync(file, "utf8")), "config")); + } catch (error) { + problems.push(parseProblem(file, error)); + } + } + + if (existsSync(paths.models)) { + checkedFiles.push(paths.models); + try { + // models.json accepts `//` comments, so the loader strips them first. + const parsed: unknown = JSON.parse(stripJsonComments(stripBom(readFileSync(paths.models, "utf8")))); + problems.push(...checkConfigDocument(paths.models, parsed, "models")); + } catch (error) { + problems.push(parseProblem(paths.models, error)); + } + } + + return { problems, checkedFiles, notes }; +} diff --git a/packages/coding-agent/src/step/config-schema.ts b/packages/coding-agent/src/step/config-schema.ts index 93dd284a..32a556a2 100644 --- a/packages/coding-agent/src/step/config-schema.ts +++ b/packages/coding-agent/src/step/config-schema.ts @@ -10,8 +10,8 @@ * * `additionalProperties: false` makes the schema stricter than the runtime on * purpose: the loaders keep an unknown key and ignore it, while an editor flags - * it. That difference is the feature — a typo becomes visible where it is - * written, and a launch never fails because of it. + * it. That difference is the feature — `step config check` reports the same key + * so a typo is visible without an editor, and a launch never fails because of it. */ import { type Static, Type } from "typebox"; @@ -143,7 +143,7 @@ const SearchTableSchema = Type.Object( SEARCH_CHAIN_MODES.map((mode) => Type.Literal(mode)), { description: - "Web search backend. `auto` (default) walks the chain; a backend id pins one; `off` keeps the tool but refuses calls. The runtime treats an unrecognized value as `auto`, so a misspelling silently disables the pin instead of failing.", + "Web search backend. `auto` (default) walks the chain; a backend id pins one; `off` keeps the tool but refuses calls. The runtime treats an unrecognized value as `auto`, so a misspelling silently disables the pin instead of failing; `step config check` flags it.", }, ), ), @@ -290,7 +290,8 @@ const StepProductProperties = { ), ), // Rewritten by `SettingsManager.migrateSettings` before any read. Listed here - // so a file that still uses them is not flagged as invalid. + // so the editor and `config check`, which validates the file as written, + // agree about a file that still uses them. queueMode: Type.Optional( Type.Union([Type.Literal("all"), Type.Literal("one-at-a-time")], { description: "Older spelling of `steeringMode`; migrated on load.", @@ -395,7 +396,7 @@ function closeObjects(node: SchemaNode): SchemaNode { return closed; } -/** `models.json` as the editor should see it. */ +/** `models.json` as the editor and `step config check` should see it. */ const StrictModelsJsonSchema = closeObjects(ModelsJsonSchema as unknown as SchemaNode) as object; export type ConfigTomlDocument = Static; @@ -430,7 +431,7 @@ export const PermissiveModelsJsonSchema = ModelsJsonSchema; /** The closed tree. */ export const ClosedModelsJsonSchema = StrictModelsJsonSchema; -/** `models.json` with unknown fields closed, for editors. */ +/** `models.json` with unknown fields closed, for editors and `config check`. */ export function renderStrictModelsSchema(): string { return renderSchemaJson(StrictModelsJsonSchema, MODELS_SCHEMA_TITLE); } diff --git a/packages/coding-agent/src/step/config-subcommands.ts b/packages/coding-agent/src/step/config-subcommands.ts index 24a9436b..411969bb 100644 --- a/packages/coding-agent/src/step/config-subcommands.ts +++ b/packages/coding-agent/src/step/config-subcommands.ts @@ -36,6 +36,11 @@ export const STEP_CONFIG_SUBCOMMANDS: readonly StepConfigSubcommand[] = [ summary: "Print the editor JSON Schema for config.toml or models.json (--out ).", flags: ["--out"], }, + { + name: "check", + summary: "Validate config.toml and models.json against that schema (--json, --allow-unknown).", + flags: ["--json", "--allow-unknown"], + }, ]; /** Whether `name` selects a subcommand, so a bare `step config` still opens the TUI. */ diff --git a/packages/coding-agent/test/cli-startup-cost.test.ts b/packages/coding-agent/test/cli-startup-cost.test.ts index 2e5b97b3..4e7495c7 100644 --- a/packages/coding-agent/test/cli-startup-cost.test.ts +++ b/packages/coding-agent/test/cli-startup-cost.test.ts @@ -28,6 +28,7 @@ const FORBIDDEN_MODULES = [ "src/step/config-toml.ts", "src/step/command-compat.ts", "src/step/settings-manager.ts", + "src/step/config-check.ts", "src/step/schema-files.ts", "src/step/subagent-limits.ts", "src/core/model-config.ts", diff --git a/packages/coding-agent/test/config-check.test.ts b/packages/coding-agent/test/config-check.test.ts new file mode 100644 index 00000000..e097e2db --- /dev/null +++ b/packages/coding-agent/test/config-check.test.ts @@ -0,0 +1,353 @@ +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, test } from "vitest"; +import { runStepConfigCommand } from "../src/step/command-compat.ts"; +import { checkStepConfigFiles, describePath } from "../src/step/config-check.ts"; + +const roots: string[] = []; + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); +}); + +async function makeRoot(): Promise<{ root: string; env: Record }> { + const root = await mkdtemp(join(tmpdir(), "step-config-check-")); + roots.push(root); + return { root, env: { STEP_CODING_AGENT_DIR: join(root, "agent"), HOME: join(root, "home") } }; +} + +function capture() { + let text = ""; + return { + stdout: { + write: (chunk: string) => { + text += chunk; + return true; + }, + }, + text: () => text, + }; +} + +describe("config check", () => { + test("accepts the file `config init` writes", async () => { + const { root, env } = await makeRoot(); + await runStepConfigCommand(["config", "init"], { stdout: capture().stdout, homeEnv: env }); + + const result = checkStepConfigFiles({ + globalSettings: join(root, "config.toml"), + projectSettings: join(root, ".stepcode", "config.toml"), + models: join(root, "models.json"), + }); + expect(result.problems).toEqual([]); + expect(result.checkedFiles).toEqual([join(root, "config.toml")]); + }); + + test("reports a misspelled key as an unknown key", () => { + const result = checkConfigFilesWith("triggerRation = 0.9\n"); + const unknown = result.problems.filter((problem) => problem.kind === "unknown"); + expect(unknown).toHaveLength(1); + expect(unknown[0]!.message).toContain("triggerRation"); + }); + + test("reports an out-of-range value with its path", () => { + const result = checkConfigFilesWith("[compaction]\ntriggerRatio = 5\n"); + const invalid = result.problems.filter((problem) => problem.kind === "invalid"); + expect(invalid.map((problem) => describePath(problem.path))).toEqual(["compaction.triggerRatio"]); + expect(invalid[0]!.message).toContain("0.95"); + }); + + test("lists the accepted values of a closed set instead of one error per member", () => { + const result = checkConfigFilesWith('[search]\nprovider = "nope"\n'); + const invalid = result.problems.filter((problem) => problem.kind === "invalid"); + expect(invalid).toHaveLength(1); + expect(invalid[0]!.message).toContain('"auto"'); + expect(invalid[0]!.message).toContain('"tavily"'); + }); + + test("reports a parse error without throwing", () => { + const result = checkConfigFilesWith("this is not toml = = =\n"); + expect(result.problems.map((problem) => problem.kind)).toEqual(["parse"]); + }); + + // An unknown key and a rejected value are the same problem in the end: the + // setting does not do what it says. Both fail the check. + test("`config check` fails on an unknown key and on a rejected value alike", async () => { + const { root, env } = await makeRoot(); + await mkdir(root, { recursive: true }); + + await writeFile(join(root, "config.toml"), "unknownButHarmless = 1\n"); + await expect( + runStepConfigCommand(["config", "check"], { stdout: capture().stdout, homeEnv: env }), + ).rejects.toThrow(/configuration problem/); + + await writeFile(join(root, "config.toml"), "[compaction]\ntriggerRatio = 5\n"); + await expect( + runStepConfigCommand(["config", "check"], { stdout: capture().stdout, homeEnv: env }), + ).rejects.toThrow(/configuration problem/); + }); + + test("`config check --json` reports files, problems and kinds", async () => { + const { root, env } = await makeRoot(); + await mkdir(root, { recursive: true }); + await writeFile(join(root, "config.toml"), "triggerRation = 0.9\n"); + const io = capture(); + + await expect( + runStepConfigCommand(["config", "check", "--json"], { stdout: io.stdout, homeEnv: env }), + ).rejects.toThrow(/configuration problem/); + + const payload = JSON.parse(io.text()); + expect(payload.ok).toBe(false); + expect(payload.problems[0].kind).toBe("unknown"); + }); +}); + +function checkConfigFilesWith(content: string) { + // Reuse the exported entry point against a synchronous temp file so the + // assertions stay about the message, not about setup. + const root = mkdtempSync(join(tmpdir(), "step-config-check-sync-")); + roots.push(root); + writeFileSync(join(root, "config.toml"), content); + return checkStepConfigFiles({ + globalSettings: join(root, "config.toml"), + projectSettings: join(root, "missing", "config.toml"), + models: join(root, "missing.json"), + }); +} + +describe("config check reports every problem, not the first few", () => { + // TypeBox stops collecting after eight errors by default. A file with more + // problems than that must not look clean, and an unrelated error earlier in + // the file must not hide a later one. + // Invalid values, not unknown keys: those come from the schema walk, so they + // would pass even with TypeBox's default eight-error limit. + test("a file with more than eight invalid values reports all of them", async () => { + const { root, env } = await makeRoot(); + await mkdir(root, { recursive: true }); + const entries = Array.from({ length: 12 }, (_, index) => `{ provider = "p${index}", id = "" }`); + await writeFile(join(root, "config.toml"), `recentModels = [${entries.join(", ")}]\n`); + const io = capture(); + + await expect( + runStepConfigCommand(["config", "check", "--json"], { stdout: io.stdout, homeEnv: env }), + ).rejects.toThrow(); + expect(JSON.parse(io.text()).problems.length).toBeGreaterThanOrEqual(12); + }); + + test("a later invalid value is still reported when an unknown key fails first", async () => { + const result = checkConfigFilesWith('triggerRation = 0.9\n[search]\nprovider = "nope"\n'); + const kinds = result.problems.map((problem) => problem.kind).sort(); + expect(kinds).toEqual(["invalid", "unknown"]); + }); +}); + +describe("config check paths", () => { + test("a record key containing a dot is reported unambiguously", () => { + const result = checkConfigFilesWith('[compaction]\nmodelTriggerRatios = { "vendor/model.3" = "bad" }\n'); + const invalid = result.problems.filter((problem) => problem.kind === "invalid"); + expect(invalid).toHaveLength(1); + expect(invalid[0]!.path).toBe("/compaction/modelTriggerRatios/vendor~1model.3"); + }); + + test("an unknown key inside an array entry is found once", () => { + const result = checkConfigFilesWith('packages = [{ source = "x", bogus = 1 }]\n'); + const unknown = result.problems.filter((problem) => problem.kind === "unknown"); + expect(unknown.map((problem) => problem.path)).toEqual(["/packages/0/bogus"]); + // And it does not also surface as "must be string" from the union member. + expect( + result.problems + .filter((problem) => problem.kind === "invalid") + .map((problem) => problem.message) + .filter((message) => message.includes("string")), + ).toEqual([]); + }); + + test("the legacy permission spellings the runtime maps are accepted", () => { + const result = checkConfigFilesWith('permissionPreset = "yolo"\napprovalMode = "bypass"\n'); + expect(result.problems).toEqual([]); + }); +}); + +describe("config check matches what the loader accepts", () => { + // Each case is a value the runtime normalizes or migrates; reporting it as + // invalid made `check` cry wolf on a file that works. + test.each([ + ["legacy steering key", 'queueMode = "all"\n'], + ["legacy transport key", "websockets = true\n"], + ["legacy retry delay", "[retry]\nmaxDelayMs = 5000\n"], + ["legacy skills object", '[skills]\ncustomDirectories = ["/tmp/x"]\n'], + ["uppercase tier", 'permissionPreset = "Ask"\n'], + ["padded tier", 'permissionPreset = " full-access "\n'], + ["uppercase approval mode", 'approvalMode = "Confirm"\n'], + ["legacy flat tier", 'permissionMode = "yolo"\n'], + ["disabled timeout", 'httpIdleTimeoutMs = "disabled"\n'], + ["numeric-string timeout", 'httpIdleTimeoutMs = "60000"\n'], + ])("%s is accepted", (_label, content) => { + expect(checkConfigFilesWith(content).problems).toEqual([]); + }); + + test.each([ + ["ratio out of range", '[compaction]\nmodelTriggerRatios = { "a/b" = 2.0 }\n'], + ["zero token limit", "[compaction]\ntokenLimit = 0\n"], + ["fractional token limit", "[compaction]\ntokenLimit = 1.5\n"], + ])("%s is reported, because the loader drops it", (_label, content) => { + const problems = checkConfigFilesWith(content).problems; + expect(problems.filter((problem) => problem.kind === "invalid")).not.toEqual([]); + }); +}); + +describe("config check and models.json", () => { + test("reports a misspelled provider field", async () => { + const { root, env } = await makeRoot(); + await mkdir(root, { recursive: true }); + await writeFile( + join(root, "models.json"), + JSON.stringify({ providers: { local: { baseurl: "http://x", models: [{ id: "m", contextwindow: 1 }] } } }), + ); + const io = capture(); + + await expect( + runStepConfigCommand(["config", "check", "--json"], { stdout: io.stdout, homeEnv: env }), + ).rejects.toThrow(); + + const paths = (JSON.parse(io.text()).problems as Array<{ path: string }>).map((problem) => problem.path); + expect(paths).toContain("/providers/local/baseurl"); + expect(paths).toContain("/providers/local/models/0/contextwindow"); + }); + + test("a record such as samplingParams stays open", async () => { + const { root, env } = await makeRoot(); + await mkdir(root, { recursive: true }); + await writeFile( + join(root, "models.json"), + JSON.stringify({ + providers: { + local: { models: [{ id: "m", samplingParams: { temperature: 0.2, vendorFlag: true } }] }, + }, + }), + ); + + await expect( + runStepConfigCommand(["config", "check"], { stdout: capture().stdout, homeEnv: env }), + ).resolves.toBeUndefined(); + }); +}); + +describe("config check escape hatch", () => { + // A config written by a newer release is not something this binary can act + // on, but failing a build over it is worse than saying so. + test("--allow-unknown passes with an unknown key and still fails on a bad value", async () => { + const { root, env } = await makeRoot(); + await mkdir(root, { recursive: true }); + + await writeFile(join(root, "config.toml"), "fromAFutureRelease = 1\n"); + await expect( + runStepConfigCommand(["config", "check", "--allow-unknown"], { + stdout: capture().stdout, + homeEnv: env, + }), + ).resolves.toBeUndefined(); + + await writeFile(join(root, "config.toml"), 'fromAFutureRelease = 1\n[search]\nprovider = "nope"\n'); + await expect( + runStepConfigCommand(["config", "check", "--allow-unknown"], { + stdout: capture().stdout, + homeEnv: env, + }), + ).rejects.toThrow(/configuration problem/); + }); +}); + +describe("config check never writes the user's config", () => { + // The schema copies are refreshed on launch; the config file is not. A check + // that rewrote it, even to add one comment, would be a surprise. + test("leaves a config without the editor directive byte-identical", async () => { + const { root, env } = await makeRoot(); + await mkdir(root, { recursive: true }); + const content = 'theme = "dark"\n'; + await writeFile(join(root, "config.toml"), content); + + const io = capture(); + await runStepConfigCommand(["config", "check"], { stdout: io.stdout, homeEnv: env }); + + expect(readFileSync(join(root, "config.toml"), "utf8")).toBe(content); + expect(io.text()).toContain("#:schema ./config.schema.json"); + }); +}); + +describe("config check unknown-key messages", () => { + test("names the build and suggests the closest declared key", () => { + const result = checkConfigFilesWith("[compaction]\ntriggerRation = 0.9\n"); + const unknown = result.problems.filter((problem) => problem.kind === "unknown"); + expect(unknown).toHaveLength(1); + expect(unknown[0]!.message).toContain("does not read"); + expect(unknown[0]!.message).toContain('did you mean "triggerRatio"'); + }); + + test("does not guess when the key is unrelated", () => { + const result = checkConfigFilesWith("fromAFutureRelease = 1\n"); + const unknown = result.problems.filter((problem) => problem.kind === "unknown"); + expect(unknown[0]!.message).not.toContain("did you mean"); + }); +}); + +describe("config check reports one message per field", () => { + // A union produces one failure per member. Listing them separately makes one + // bad value look like several problems, and a summary on a parent contradicts + // a valid object whose field is wrong. + test("a bad field inside a package entry does not also condemn the entry", () => { + const result = checkConfigFilesWith("packages = [{ source = 1 }]\n"); + expect(result.problems.map((problem) => problem.path)).toEqual(["/packages/0/source"]); + }); + + test("a union of a type and a literal names both", () => { + const result = checkConfigFilesWith('[terminal]\nhyperlinks = "sometimes"\n'); + const invalid = result.problems.filter((problem) => problem.kind === "invalid"); + expect(invalid).toHaveLength(1); + expect(invalid[0]!.message).toContain("boolean"); + expect(invalid[0]!.message).toContain('"auto"'); + }); + + test("a timeout accepts the forms the dispatcher parses", () => { + expect(checkConfigFilesWith('httpIdleTimeoutMs = "60000"\n').problems).toEqual([]); + expect(checkConfigFilesWith('httpIdleTimeoutMs = "disabled"\n').problems).toEqual([]); + const bad = checkConfigFilesWith('httpIdleTimeoutMs = "sometimes"\n'); + expect(bad.problems.filter((problem) => problem.kind === "invalid")).toHaveLength(1); + }); + + test("a bad value under a migrated key is reported at the key the user wrote", () => { + // The check validates the file as written. Reporting `/steeringMode` for a + // typo in `queueMode` would point at a line that is not in the file. + const result = checkConfigFilesWith('queueMode = "nope"\n'); + expect(result.problems.map((problem) => problem.path)).toEqual(["/queueMode"]); + }); + + test("a malformed value in a migrated key is not silently dropped", () => { + const result = checkConfigFilesWith('[retry]\nmaxDelayMs = "abc"\n'); + expect(result.problems.map((problem) => problem.path)).toEqual(["/retry/maxDelayMs"]); + }); + + test("a misspelling inside the older skills table is found", () => { + const result = checkConfigFilesWith('[skills]\ncustomDirectores = ["/x"]\n'); + expect(result.problems.map((problem) => problem.path)).toEqual(["/skills/customDirectores"]); + }); +}); + +describe("project settings are never given the editor directive", () => { + test("writing a project config leaves its header alone", async () => { + const { root, env } = await makeRoot(); + const project = join(root, ".stepcode"); + await mkdir(project, { recursive: true }); + const path = join(project, "config.toml"); + await writeFile(path, 'theme = "dark"\n'); + + const { writeStepConfig } = await import("../src/step/config-toml.ts"); + writeStepConfig(path, { theme: "dark", quietStartup: true }, { editorDirective: false }); + + expect(readFileSync(path, "utf8")).not.toContain("#:schema"); + expect(env).toBeDefined(); + }); +}); diff --git a/packages/coding-agent/test/config-help-subcommands.test.ts b/packages/coding-agent/test/config-help-subcommands.test.ts index 2cfd5ff3..401092bc 100644 --- a/packages/coding-agent/test/config-help-subcommands.test.ts +++ b/packages/coding-agent/test/config-help-subcommands.test.ts @@ -27,7 +27,7 @@ describe("config --help subcommands", () => { expect(result.isStepEntrypoint).toBe(true); expect(result.configHandled).toBe(true); expect(result.configHelp).toContain(`${appName} config [-l]`); - expect(STEP_CONFIG_SUBCOMMANDS.map((sub) => sub.name)).toEqual(["path", "show", "init", "schema"]); + expect(STEP_CONFIG_SUBCOMMANDS.map((sub) => sub.name)).toEqual(["path", "show", "init", "schema", "check"]); for (const { name } of STEP_CONFIG_SUBCOMMANDS) { expect(result.configHelp).toMatch(new RegExp(`^\\s+${name}\\s`, "m")); }