Standard-Schema-first CLI builder in the scriptc subset — the library owns
only the seam (argv tokenize → flag-vs-value → validate boundary →
dispatch/help/errors); all value semantics live in whatever schema the
consumer brings. Plain records + functions, no classes, zero deps. Design
source: .agents/plans/2026-11-08-cli-schema-first.md (supersedes the
type-field design in .agents/plans/2026-11-07-cutils-cli.md). Same
subset rules as the root AGENTS.md, plus what authoring this package
verified empirically under the pinned scriptc (0.4.7):
- Generic functions over record literals:
command<O extends Record<string, OptionInput>>lowers fully — the generic only feeds the type-levelOptsFromOptions<O>mapped type; nothing generic survives into runtime values. - Union-typed options entries:
OptionInput = OptionSpec | StandardSchemaInput | ValidateFn— declared in the generic param only, erased; runtime discriminates viaisSchemaValue(typeof === "function"or~standard/validatemember present). - Function values inside records AND a bare function as an options
entry (
mark: (v) => ({value: v})): both lower — the records are produced/consumed inside one program, never class fields. - Validator closures capturing builtin params:
num({min,max})/int({min,max})close overlo/hi— ordinary closures lower. Object.entries+ dynamic record WRITES: every lookup walksObject.entries()with an indexed loop (findLong/findShort/valueOf/command dispatch);values[name] = vwrites are legal. Dynamic record READSobj[key]remain SC1090 — never index a record.instanceof Promisenarrows validator results; async validators are rejected with a clean error.process.exitlowers (elf-app exits withrun's return code).Number.isNaN,Number.isInteger,Number(),String(unknown)all lower — the last two land in the dynamic tier (still static-compiled, runtime-checked).
- One dynamic-slot trap survived:
const h = spec.handlerholds a value declared(opts: OptsFromOptions<O>, ...) => void— a generic mapped type has no static lowering → SC6104 dynamic slot. Fix is the upcast incommand():spec.handler as (opts: unknown, args: string[]) => voidstores the boundary-typed function directly (also saves a wrapper closure). If you touchcommand()'s return path, re-runscriptc coverage gate.ts --explain-dynamic— zerodynamic slotslines is the bar (dynamic TIER statements are expected and fine). optstyping istypes.outputonly — there is notypefield to fall back to. Priority inOptsFromOptions: bare-schema entry →SchemaOutput<O[K]>;{schema: S}→SchemaOutput<S>(notypes→unknown);{flag: true}→boolean; elsestring.TypedValidator<O>is the typed-validator contract:types?: {input?, output: O}—outputmust be a REQUIRED member, matching the Standard Schema spec;SchemaOutput's{output: infer O}pattern never matches an optional one (this burned once —output?: Osilently gaveunknown).defaultgoes throughvalidate()atcommand()time — issues →E_BAD_OPTIONwith the schema's message; a morph output is stored. Schema-less defaults get a cheap typeof check (flag→boolean, else→string).- Values are raw strings until a validator says otherwise: the parser
stores the argv string (or
true/attached for flags); the end-of-parse pass runsvalidateValueper option and stores the OUTPUT — morphs apply.num()/int()doNumber()inside theirvalidate. - Schema-less flag attached values (
--flag=false):true/1→true,false/0→false, else error — done in the validation pass, not the parse loop. optskeys are always present: absent flag →defaultelse the zero value (false/""). A schema that rejects""makes its option effectively required — document viadefault.runnever exits: returns the code;process.exit(run({...}))is the consumer idiom. Keepsnode --testtests in-process.-hyields to a declaredshort: "h"— checkfindShortbefore printing command help.- Help/errors go through
console.log/console.error— noprocess.stdoutwrites or patching (patching is a subset ban).
scriptc build default flags, bench/apps/ cells (argv-baseline is a
hand-rolled equivalent app — bigger than the old 130,016 baseline because
it parses more forms):
| program | bytes | delta vs baseline |
|---|---|---|
| argv-baseline | 375,888 | — |
| cli-basic (one command) | 793,640 | +417,752 |
| cli-full (all v1) | 980,216 | +604,328 |
Tree-shaking works but is per-feature, not per-function: cli-full pays for
the descent machinery cli-basic already carries; the extra ~187 KB is the
variadic/optionalValue/env/negatable/async arms of the shared parse loop.
Reproduce: bash bench/apps/bench-elf.sh.
bench/apps/bench-node.mjs — ops/sec, spec built once outside the loop:
| cell | ops/sec |
|---|---|
| @cutils/cli options | ~840,000 |
| commander options | ~460,000 |
| node:util.parseArgs | ~527,000 |
| hand-rolled argv | ~23,300,000 |
| @cutils/cli subtree | ~1,254,000 |
| commander subtree | ~627,000 |
as string[]on a record-read value copies under scriptc: reading astring[]out ofRecord<string, unknown>then mutating through the cast silently loses writes in the ELF (Node keeps the reference).pushVarre-stores after every push — mutate-then-store, never cast-and-mutate. Caught by the ELF smoke, invisible to coverage.- Generic ProgramSpec<O,A> is a dynamic slot like the handler was: any
use of
progbefore theas ProgramHead/ concrete-instantiationas ProgramSpec<Record<...>, ArgInput[]>casts is SC6104. Both casts happen at the top ofrun/runAsync; keep them. process.env[name]reads lower (dynamic tier only) —env:option fallback relies on this.- async lowers fully (fn decls, arrows in records,
await,instanceof Promise,.then) —runNodeAsync/assignArgsAsync/validateOptsAsync/validateValueAsync/finishNodeAsyncduplicate the sync loop becauseawaitis lexical; do not merge them behind a union return (number | Promise<number>re-poisons the boundary). - Recursive records are fine:
CommandDef.commands: Record<string, CommandDef>+ iterative descent — no record unions. const Ageneric infers the args tuple atcommand()/run()call sites;ArgsFromSpec'snumber extends A["length"]guard keeps plainstring[]annotations on the legacy shape.- SC9001
field ... is nullTwhen consuming dist JS: type-erasedfield: nullinitializers degenerate. FIXED for the npm path: the./elfentry (dist JS) carries JSDoc twins on every signature that builds or returns OptionDef/ArgDef/CommandDef records —str/num/int/bool,mergeExtra,command,normalizeOptions,normalizeArgs,normalizeSchema— using inline literal object types (ValidatorTwinetc. live as/** @typedef */comments in the source; interfaces cannot be named without a.d.ts). Verified bytest/consumer-elf.test.sh: gate.ts + test/elf-app.ts compile error-free from the packed tarball under--npm-static. If you add a function that returns a record with a| nullmember, give it the same twin or consumers hit SC9001 again.
Building test/elf-app.ts against the packed ./elf tarball on scriptc
0.4.10 reports 2 (elf-app) / 4 (gate.ts) SC6001 warnings — the in-repo
build reports none. All remaining sites are the same pattern:
- Factory
extramerges (num/int/bool→mergeExtra): "converting this{min: number}/{default, max, min}/{description, short}to the merged OptionDef shape copies it". The consumer'sextraliteral (e.g.{min: 0}) is inferred as a narrower record and the@returnstwin widens it; scriptc conservatively assumes the conversion copies. Acceptable becausemergeExtraonly readsextramember-by-member into a freshoutrecord; the source object is never written through the merged alias and no identity comparison happens anywhere in the package (verified: zero===on option-def objects), so a hypothetical copy is unobservable. Fixing it would require declaringextrawith the full widened shape at every call site, which defeats the ergonomic partial-literal API. - Same story on the direct
str()site in elf-app/gate: the twin's merged shape vs the{schema, metavar}literal. Same non-observation argument applies.
The bar: zero errors, zero SC9001/SC2020/SC6104 from --npm-static;
SC6001 copy warnings at factory call sites are recorded-acceptable.
pnpm build/pnpm test— tsc +node --test test/*.test.js+bash test/elf.test.shscriptc coverage gate.tsmust reportcompile statically (100%)(viascripts/scriptc-gate.sh)bash test/elf.test.sh— buildstest/elf-app.ts, runs the full matrix (flags,--help,<cmd> --help,--version, unknown command + suggestion, missing arg, bad value, schema rejection, builtin bounds, variadic/optional positionals, optionalValue/negatable/env options, subcommand descent + alias +helpwalk, async handler via runAsync)