Skip to content

refactor(cli): derive contract-backed command options from the tool contract - #10571

Merged
morluto merged 3 commits into
mainfrom
refactor/cli-contract-command
Nov 14, 2026
Merged

morluto merged 3 commits into
mainfrom
refactor/cli-contract-command

Conversation

@morluto

@morluto morluto commented Nov 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

Contract-backed CLI commands restate each tool contract's input fields as hand-written incur options, then map them back to snake_case input with conditional spreads. Nothing checks that the CLI and the contract admit the same values, which has produced the "CLI schema drift" issue family (S01/S02: NUL bytes, missing bounds, renamed fields, decimal tokens).

This PR adds one owner for that projection, registerContractCommand, migrates a pilot set of commands onto it, and adds a parity guard. It is the first slice of plan W1 ("one definition per operation"). Refs #9348 (decimal-token bounds class; not closed here). Refs #10583: the description is framework-neutral, so a REA-owned CLI layer could render it in place of Incur.

Problem and expected behavior

  • Before: src/cli/sqliteCommands.ts re-declared six options, a superRefine "mirroring" the contract's table-selection rules, a dependentRequired/if/then block, and six conditional spreads. src/cli/binaryDiagnosticsCommands.ts repeated a ~40-line command body per inspector with a hand-written camelCase-to-snake_case map.
  • After: each migrated command is a declarative projection. The CLI admits exactly what the contract admits (a caller-relative path is validated as typed, then resolved with absoluteCallerPath), and a test enforces that.

Change and scope

  • New src/cli/contractCliDescription.ts (framework-neutral; imports zod, not Incur):
    • CliContractProjection: command name, description, positionals, callerPaths, per-field name (rename), alias (short flag) and description (CLI help wording), omit (optional fields the one-shot command does not expose, each with a reason), and crossFieldRules: "argv".
    • describeContractCommand(contract, projection) returns a ContractCliDescription:
      • One parameter per exposed field: key, short flag, positional or option, help, argv admission schema, and boolean-flag/repeatable/decimal/caller-path facts. Each schema reuses the contract field's own schema; numeric fields use the existing cliDecimalShape/cliDecimalField; caller-path fields admit localPathStringSchema.
      • The contract's dependentRequired/if/then/else metadata, renamed to CLI keys.
      • An optional argv-time check that runs the contract's own object checks with issue paths renamed to CLI keys. It is used only when the projection sets crossFieldRules: "argv"; inspect-sqlite-database does, matching its previous hand-written refinement. Otherwise the service's contract parse refuses the combination, as for hand-written commands.
      • toContractInput(values), which drops omissions and resolves caller paths with absoluteCallerPath, and callerInputs(values).
    • Fails closed: only string, number, boolean, enum and string/enum arrays are accepted as argv forms; any root input keyword other than the projected constraints and presentation annotations is refused; two fields mapping to one key are refused.
    • Exact-optional fields are projected as optional. Argv cannot carry an explicit undefined, and Incur's help reads flag and choice types only through optional.
  • src/cli/contractCommand.ts is a thin Incur adapter. registerContractCommand(cli, logger, contract, projection, run) renders the description as Incur args/options/alias and runs the handler inside the existing withCommandCancellation and logCliCommand wrappers. inspectWithService(service, providerId) is the shared finishCliEvidenceCommand + projectCliAnalysisResult body the inspectors used.
  • Migrated: inspect-sqlite-database, plus 13 flat binary-diagnostics inspectors (inspect-elf-notes, -native-initializers, -elf-unwind-ranges, -apple-ips, -kernel-module, -kernel-build-config, -pe-load-config, -binary-hardening, -byte-entropy, -pe-certificates, -pe-imports, -windows-shortcut, -pe-resources). Deleted their hand-written option schemas, spreads and the mirrored SQLite superRefine.
  • Not included (later slices):
    • inspect-devicetree, inspect-native-exports, inspect-binary-layout and inspect-recorded-crash stay hand-written for now: they use evidence delivery options, producer-limit JSON, or a renamed boolean.
    • Other families.
    • Deriving CLI_COMMANDS, the MCP registration loop, TOOL_EFFECT_AUDIT keys and CapabilityInventory checks.
    • Projecting service-level error paths to CLI names (report 02 finding 3).
  • Contribution scope: not applicable (refactor within existing boundaries; no new provider or capability).

Contract and boundary impact

  • Semantic owner and earliest changed stage: the CLI argv projection now has one owner, describeContractCommand; registerContractCommand only renders it for Incur. The tool contract stays the single definition. Superseded per-command option declarations and mappings for the 14 commands are removed.
  • Contribution scope fit and linked maintainer decision: not applicable.
  • CLI and MCP/tool-catalog contract:
    • MCP: unchanged.
    • CLI: command names, flag spellings, positionals, admission and help descriptions are unchanged.
    • --schema output for all 14 commands is semantically identical before and after (compared with object keys and required sorted).
    • Help output is byte-identical for 13 commands. inspect-sqlite-database lists the same option lines in contract order, so --worker-timeout-ms moves from first to last.
  • Provider, bridge, target-format, or platform compatibility: none.
  • Evidence, artifact, provenance, or reconstruction contract: unchanged; Evidence still records the caller's verbatim path spelling through finishCliEvidenceCommand.
  • Target selection, authority, upstream behavior, and cleanup details: unchanged; same services, cancellation wrapper and cleanup path.
  • Generated metadata, package, or installation impact: none.

Expected effects:

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

(No effect changes: the migrated commands read the same files as before.)

Evidence and regression coverage

  • Tests added or updated: tests/boundary/cli/cliContractCommandParity.test.ts runs over every contract command description registered in the complete CLI. It checks that:
    • each contract field is exposed, or declared in omit;
    • the registered args and options are exactly the bound fields;
    • each field admits exactly what the contract field admits, across these probes: empty, NUL, lone surrogate, relative and absolute paths, booleans, arrays, numbers around each advertised bound, 0x10, 1e3, 010, +1, -1, 1.5, and enum members;
    • boolean fields parse as bare flags, and no projected field stays exact-optional;
    • parsed defaults map to a contract-admitted input with the caller path resolved;
    • registration refuses unsupported field forms (object, record, union, pipe, array of objects or numbers, tuple) and unsupported root constraints such as not.
  • Review follow-ups: inspect-sqlite-database binds its contract by name (contractNamed), not by catalog position. The argv-form check is now an explicit allowlist. Unknown root input keywords are refused.
  • Mutation check (executed): changing the caller-path projection to a bare z.string() made the "admits exactly what its contract admits" case fail for every migrated command. Reverting restored the pass.
  • Base reproduction or other evidence:
    • Captured rea <cmd> --schema --format json and rea <cmd> --help for all CLI commands from the base build, and again after the change for the 14 migrated commands.
    • --schema was semantically equal for all 14.
    • Help was identical except for the sqlite option order noted above.
    • One mismatch during development (the --architecture help wording on inspect-native-initializers) is preserved with a description override.
  • User-visible CLI/MCP output: none intended, apart from the inspect-sqlite-database help option order.
  • Remaining proof gaps: no real-provider runs; these inspectors are in-process readers and their existing acceptance tests ran.

Validation performed

  • npm run typecheck: passed.

  • npm run check:fast: passed.

  • npm run knip: no findings.

  • npm run verify:architecture-guards: passed.

  • npm run lint:typed: exit 0 (existing warning counts only).

  • npm run docs:check: passed.

  • npx oxfmt --check on changed files: passed.

  • npm run test:focused -- the new parity test plus 41 existing files: 41 passed, 1 skipped; 446 tests passed, 2 skipped.

    • Acceptance: apple-ips (3), pe-resources, binary-hardening, byte-entropy, cli-timings, elf-notes (5), elf-unwind-ranges, format-specific caller path, json-lines, kernel build config/module, local-path admission, markdown selection window, native initializers, pe certificates/imports/load-config, sqlite CLI and worker identity, stable-artifact parser failure, windows shortcut.
    • CLI boundary: caller-path symlink parent, decimal/integer arguments, domain field schema, help default annotations, output, closed stdout, empty diagnostic target, overnight batch-1 schemas (sqlite cross-field cases), tool coverage, startup imports, evidence caller path, lazy registration.
    • SQLite descriptor cleanup.
  • After the framework-neutral split and review fixes (latest commits):

    • npm run check:fast: exit 0.
    • npm run knip: no findings.
    • npm run test:focused -- the parity guard plus 12 files (overnight batch-1 schemas, decimal/integer arguments, lazy registration, startup imports, empty diagnostic target, help default annotations, and the sqlite, apple-ips, local-path admission, format-specific caller path and byte-entropy acceptance tests): 12 passed, 1 skipped; 245 tests passed, 2 skipped.
    • --schema/--help capture re-compared for all 14 commands, with the same result as above.

Compatibility, safety, and release

  • Breaking changes or migration steps: none.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable (macOS host only).
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: no change in authority or side effects; caller paths are still validated before resolution.

Author readiness

Human owner:

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

…ontract

Each contract-backed CLI command restated its contract's input fields as
hand-written incur options and mapped them back to snake_case input with
conditional spreads. Nothing checked that the two schemas agreed.

Add registerContractCommand: a per-command projection names only what the
CLI spells differently (positionals, caller-relative path fields, option
renames, CLI help wording, omitted optional fields with a reason). Option
schemas, decimal argv tokens and the contract's cross-field rules are
derived from the contract input schema, and parsed options map back to the
contract input mechanically.

Migrate inspect-sqlite-database and the thirteen flat binary-diagnostics
inspectors. Their --schema output is unchanged apart from property order,
and help lists options in contract order. Delete the SQLite superRefine that
mirrored the contract and the per-command spreads.

Add a parity test: every projected command exposes each contract field or
declares its omission, and each field admits exactly what the contract
admits for empty, NUL, relative-path, bound and numeric-spelling probes.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-14T15:45:03.957554Z b45ae1b New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4c27b1c552

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/cli/sqliteCommands.ts Resolved
@greptile-apps

greptile-apps Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5 Tier: plus

[Medium impact] The PR appears safe to merge; no blocking issue remains in the reviewed changes.

Summary

Derives options for SQLite and 13 binary inspectors from their tool contracts. describeContractCommand owns the description and input mapping; registerContractCommand renders it for Incur.

  • Contract-backed CLI commands get their fields and input mapping from one projection.
  • Thirteen binary inspectors now get their CLI fields from tool contracts.
  • The SQLite inspector now gets its CLI fields and input mapping from its contract.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A["Tool contract"] --> C["describeContractCommand"]
  B["CLI spelling choices"] --> C
  C --> D["registerContractCommand"]
  D --> E["Incur parses arguments and options"]
  E --> F["Map fields and resolve caller paths"]
  F --> G["Service validates and inspects"]
  G --> H["Finish cleanup and return Evidence"]
Loading

Reviews (4) · Last reviewed commit: "refactor(cli): describe contract command..." · Reviewed by Greptile

Comment thread src/cli/sqliteCommands.ts Resolved
Comment thread src/cli/contractCommand.ts Resolved
Comment thread src/cli/contractCommand.ts Resolved
Address review findings on the contract projection:

- Bind inspect-sqlite-database to its contract by name instead of catalog
  position.
- Accept only field forms argv can carry (string, number, boolean, enum,
  and arrays of strings or enums) instead of rejecting a short list, so
  arrays of objects, tuples and other forms fail at registration.
- Refuse root input keywords other than the projected object constraints
  and presentation annotations, so a contract rule such as `not` cannot
  disappear from --schema.
…amework

Split the contract projection into a framework-neutral description and a
thin Incur adapter, so a later REA-owned CLI layer (#10583) can render the
same description.

- contractCliDescription.ts derives each positional and option from the
  contract and projection: key and short flag, help, argv admission
  schema, boolean-flag/repeatable/decimal/caller-path facts, object
  constraints renamed to CLI keys, the optional argv-time cross-field
  check, and the mapping back to contract input.
- contractCommand.ts only renders that description as Incur args and
  options and runs the handler.

Cross-field rules now refuse at argv parsing only when a projection asks
(inspect-sqlite-database does, keeping its behavior); otherwise the
service's contract parse refuses them as before. Exact-optional fields are
projected as optional because argv cannot carry an explicit undefined and
Incur's help reads flag and choice types only through optional.

The parity guard reads the descriptions, and also checks that boolean
fields parse as bare flags and that no projected field stays
exact-optional.
Comment thread src/cli/contractCommand.ts Resolved
@morluto

morluto commented Nov 14, 2026

Copy link
Copy Markdown
Owner Author

The Greptile summary's Issue 1 ("Dependent callers lose required exports") no longer applies. The dependent PR was updated with this refactor:

@greptileai please re-review.

@morluto
morluto merged commit f3b697d into main Nov 14, 2026
56 of 60 checks passed
@morluto
morluto deleted the refactor/cli-contract-command branch November 14, 2026 20:30
@morluto morluto added the area: cli CLI adapter and one-shot commands label Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: cli CLI adapter and one-shot commands

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant