From d2dba30be202ec5a679463b57b6ef90e3f1a1f0b Mon Sep 17 00:00:00 2001 From: "warp-factories[bot]" <243557089+warp-factories[bot]@users.noreply.github.com> Date: Fri, 4 Sep 2026 22:05:36 +0000 Subject: [PATCH 1/4] spec: validate conflicting short flags --- specs/GH400/product.md | 86 ++++++++++++++++++++++++++++++ specs/GH400/tech.md | 115 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 201 insertions(+) create mode 100644 specs/GH400/product.md create mode 100644 specs/GH400/tech.md diff --git a/specs/GH400/product.md b/specs/GH400/product.md new file mode 100644 index 00000000..2dfea251 --- /dev/null +++ b/specs/GH400/product.md @@ -0,0 +1,86 @@ +# Validate conflicting short flags in command signatures + +Issue: [#400](https://github.com/warpdotdev/command-signatures/issues/400) + +## Problem +Handwritten command specs represent every spelling of an option in `CommandOption.name`. A short spelling such as `-h` is converted into `Opt.exact_string` and offered to the completion engine. When two distinct option entries on the same command node claim the same short flag, the completion metadata does not identify which option the spelling belongs to. Contributors can therefore merge an ambiguous completion without receiving a repository validation failure. + +This matters even when the two entries have similar descriptions or long names: the generated completion metadata contains two candidates for the same exact token, so downstream code cannot reliably select the intended option. + +## Desired behavior +Repository validation must detect every duplicate short flag claimed by two or more distinct option entries directly declared on the same handwritten command or subcommand. + +For this rule: + +- A short flag uses the existing `is_short_hand_flag` classification: its UTF-8 representation is exactly two bytes, it begins with `-`, and it is not `--`. Examples include `-h`, `-v`, and `-1`. `--help` and single-dash multi-character names such as `-version` are not short flags. +- Each root command and each nested subcommand is a separate option namespace. Sibling subcommands may reuse a short flag, and a parent and child may reuse it because the authored command nodes are checked separately. +- Only distinct option entries conflict. Multiple aliases in one option's `name` array describe one option. Repetition inside one `name` array belongs to the duplicate-option-name validation proposed in [#399](https://github.com/warpdotdev/command-signatures/issues/399), not this rule. +- A command or subcommand with multiple names still has one namespace; aliases do not create separate validation scopes. +- Validation examines options directly authored on each node before `isPersistent` options are copied into descendant `Signature` values. Inherited copies do not become new authored definitions for this rule. + +## Files in scope +The hard repository check covers handwritten command definitions in `command-signatures/json/*.json`. + +- `command-signatures/json/autogenerated/**/*.json` remains outside this rule. Generated output must be corrected at its source rather than maintained through a handwritten baseline. The current autogenerated PowerShell set has no directly declared duplicate short-flag conflicts. +- `command-signatures/json/overrides/**/*.json` remains outside this rule. The current override schema can only locate an existing option by name and override argument metadata; it cannot add or rename option spellings. If that capability is added later, validation of the merged generated command should be specified with it. + +## Validation error +The validator produces one diagnostic for each `(file, command path, short flag)` conflict and includes every distinct conflicting option in source order. The repository test reports unexpected diagnostics in deterministic file, command-path, and short-flag order. + +The human-readable form must contain: + +1. the handwritten JSON file path; +2. the full command path, using the first declared name at each command level; +3. the duplicate short flag, including its dash; +4. every conflicting option's one-based position and complete `name` array. + +Example: + +`command-signatures/json/flutter.json: command "flutter assemble": duplicate short flag "-d" is used by options #3 ["-d", "--device-id"] and #8 ["-d", "--define"]` + +Including positions keeps the message actionable when the conflicting options have identical `name` arrays, as several current offenders do. + +## Rollout +The recommended rollout is a hard “no new conflicts” gate backed by an exact, temporary baseline allowlist for existing offenders. + +At `origin/main` commit `d69b340ef622540ac28340ef565dae45287d51d8`, direct authored-option validation finds 45 conflict keys across 13 handwritten files: + +- `brew.json`: 2 +- `copilot.json`: 27 +- `flutter.json`: 2 +- `kubecolor.json`: 1 +- `kubectl.json`: 1 +- `oc.json`: 1 +- `pscale.json`: 2 +- `pulumi.json`: 1 +- `rsync.json`: 1 +- `sfdx.json`: 1 +- `stripe.json`: 4 +- `yarn.json`: 1 +- `zapier.json`: 1 + +Each baseline entry is keyed by relative file path, canonical command path, and short flag. CI fails if validation finds a key that is not in the baseline. CI also fails when a baseline key no longer exists, forcing the same change that fixes an offender to remove its stale entry. The implementation PR must link a dedicated follow-up issue that tracks reducing the baseline to zero, and the allowlist must link that issue in a comment. + +This approach prevents new ambiguity immediately without forcing 45 potentially behavior-sensitive command-spec corrections into the validator change. It is preferred over warn-only validation, which does not prevent regressions, and over an unconditional fix-first gate, which would make `main` fail until every existing command's intended CLI semantics had been researched. + +Once the baseline is empty, remove the allowlist mechanism and make every diagnostic a direct failure. + +## Acceptance criteria +- Two distinct option entries directly declared on one handwritten command or subcommand and sharing a short flag produce one actionable diagnostic. +- The diagnostic identifies the JSON file, full command path, offending short flag, and all conflicting option names and positions. +- Reusing a short flag on unrelated root commands, sibling subcommands, or a parent and child does not produce a conflict. +- Short flags use the repository's existing classification rather than a second definition. +- Multiple names on one option or command do not create duplicate namespaces or pairwise false positives. +- Focused fixtures cover valid reuse across namespaces and invalid reuse within one namespace, including identical option-name arrays and more than two claimants. +- A repository invariant test scans only handwritten command JSON, rejects any conflict not in the temporary baseline, and rejects stale baseline entries. +- The invariant runs through `cargo test`, and therefore through `script/presubmit` and the CI test job without a separate manual command. + +## Non-goals +- Correcting or otherwise editing the 45 existing command-spec conflicts as part of the validator implementation. +- Validating duplicate long option names or repeated exact option names; [#399](https://github.com/warpdotdev/command-signatures/issues/399) covers that rule. +- Defining when contributors should pair short and long names in one option entry; [#374](https://github.com/warpdotdev/command-signatures/issues/374) covers that convention. +- Changing completion ranking, parsing, deduplication, or any Warp application UI. +- Validating autogenerated PowerShell output or redesigning the override format. + +## Open questions +- Maintainers may choose an unconditional fix-first rollout during spec review. The recommendation remains the exact shrinking baseline above because it creates an immediate regression gate while keeping command-specific semantic cleanup independently reviewable. diff --git a/specs/GH400/tech.md b/specs/GH400/tech.md new file mode 100644 index 00000000..81424632 --- /dev/null +++ b/specs/GH400/tech.md @@ -0,0 +1,115 @@ +# Technical design: conflicting short-flag validation + +## Current behavior +`completion-metadata/src/fig_types.rs` defines `CommandOption.name` as one or more strings and converts every string into `Opt.exact_string` in `From for Opt`. `From for Vec` recursively converts command nodes and copies persistent options into child commands during conversion. + +`completion-metadata/src/signature.rs` already classifies short flags in `is_short_hand_flag` and exposes converted short flags through `Signature::short_hand_flags`. The classifier is currently private, and neither conversion nor the command-signature crate checks whether distinct options claim the same short flag. + +Repository invariants live in the test module in `command-signatures/src/lib.rs`. Its tests deserialize embedded specs, verify generator references, and reject unsafe generator newlines. `script/presubmit` runs formatting, Clippy, and `cargo test`; `.github/workflows/CI.yml` also has a `cargo test --verbose` job. No separate validation command or fixture tree exists. + +`command-signatures/src/assets.rs` deliberately combines handwritten and autogenerated assets for runtime lookup, so the existing `commands()` iterator is not an appropriate discovery source for a handwritten-only rule. It also returns post-conversion `Signature` values, which have lost the source option boundaries needed for precise diagnostics. + +## Proposed implementation +### Shared metadata validator +Add a small validation module in `completion-metadata`, operating on `fig_types::Command` before conversion. It should: + +1. recursively walk the root command and all `subcommands`; +2. build a canonical path from the first name declared at each level; +3. inspect only the current node's `options`; +4. classify each name with the existing short-hand classifier; +5. group occurrences by short flag while deduplicating repeated occurrences from the same option entry; +6. emit one structured conflict per flag claimed by at least two option entries. + +The structured conflict must retain the canonical command path, short flag, each option's zero-based source index for programmatic use, and each option's complete name list. Formatting converts indices to one-based positions. File paths belong to the caller because `fig_types::Command` does not know its source. + +Move or expose `is_short_hand_flag` within the crate so the validator and `Signature::short_hand_flags` share one implementation. Do not publish a second classifier with subtly different Unicode or dash behavior. + +The recursive walk and diagnostic types should be reusable by the duplicate-name work in #399. That issue can add another rule over the same command/option traversal, but duplicate full-name validation is not implemented under #400. + +### Handwritten-spec invariant +Add an invariant test in `command-signatures/src/lib.rs` that reads only the top-level `command-signatures/json/*.json` files from `CARGO_MANIFEST_DIR`, deserializes each into `fig_types::Command`, calls the shared validator, attaches the repository-relative file path, and sorts the collected conflicts deterministically. + +Do not use `Assets::iter()` or `commands()` for this test: both combine manual and autogenerated assets, and `commands()` validates converted rather than authored option sets. + +The test compares the collected conflict keys with a constant baseline of the 45 current `(relative file, canonical command path, short flag)` keys: + +- Any collected conflict absent from the baseline fails with the complete diagnostic. +- Any baseline entry absent from the collected set fails as stale and tells the contributor to remove it. +- Matching baseline conflicts do not fail the test. +- The baseline is documented as temporary and links the dedicated cleanup issue required by the product rollout. + +This exact-set comparison makes the allowlist non-expandable by accident and guarantees monotonically reviewed burn-down. Adding an entry remains possible only as an explicit code-review decision; it must not be generated automatically during tests. + +### Diagnostic formatting +Formatting must be deterministic and use this shape: + +`: command "": duplicate short flag "" is used by options # [, ...]` + +Use JSON array formatting for names so aliases and punctuation are unambiguous. List conflicting options in source order. Aggregate all unexpected conflicts into one assertion failure so contributors can fix every reported location in one pass. + +## Fixture and test coverage +Create focused JSON fixtures under `completion-metadata/tests/fixtures/duplicate_short_flags/` and exercise them from validation tests. + +Invalid coverage: + +- two differently named option entries on one command share one short flag; +- two distinct entries have identical complete name arrays, proving positions distinguish them; +- three option entries share one short flag and produce one diagnostic listing all three; +- a duplicate exists on a nested subcommand and the diagnostic contains the full root-to-leaf path; +- an option repeats the same short spelling internally and another option claims it, proving the first option is counted once rather than creating pairwise duplicate diagnostics. + +Valid coverage: + +- every option on one command has a distinct short flag; +- root options and child options reuse a short flag; +- sibling subcommands reuse a short flag; +- unrelated top-level fixture commands reuse a short flag; +- one option contains a short and long alias without conflict; +- names classified as long flags (`--help` and `-version`) do not participate in the short-flag rule; +- a command or subcommand name array is treated as aliases for one namespace. + +The command-signature crate should also test file discovery boundaries: a fixture or helper-level test confirms that only top-level handwritten JSON is selected, not `autogenerated/` or `overrides/`. + +## Edge cases +- Report one conflict per command namespace and short flag, not one error per pair of options. +- Preserve case. `-v` and `-V` are different flags. +- Preserve the exact token. No normalization is applied beyond the existing classifier. +- A duplicate spelling inside one option entry alone is not a #400 conflict. +- Parent and child nodes are independent even when the parent option is persistent. The validator runs before persistent-option expansion and does not report the inherited copy as another authored option. +- If a node has multiple command names, its options are validated once and its first declared name is used in the canonical path. +- Existing malformed JSON remains the responsibility of deserialization validation; the new validator receives a successfully deserialized `Command`. + +## Verified baseline +The inventory was recomputed against `origin/main` commit `d69b340ef622540ac28340ef565dae45287d51d8` by recursively examining the directly declared options of every `command-signatures/json/*.json` command node and excluding `autogenerated/` and `overrides/`. + +The 45 keys are distributed as follows: + +- `brew.json`: `brew services` (`-v`, `-h`) +- `copilot.json`: 27 `-n` conflicts across `svc`, `job`, `task`, `deploy`, and mirrored `help` descendants +- `flutter.json`: `flutter assemble` (`-d`), `flutter symbolize` (`-d`) +- `kubecolor.json`: `kubecolor expose` (`-l`) +- `kubectl.json`: `kubectl expose` (`-l`) +- `oc.json`: `oc expose` (`-l`) +- `pscale.json`: `pscale completion` (`-h`), `pscale connect` (`-h`) +- `pulumi.json`: `pulumi import` (`-f`) +- `rsync.json`: `rsync` (`-h`) +- `sfdx.json`: `sfdx auth:accesstoken:store` (`-s`) +- `stripe.json`: `stripe events resend`, `stripe get`, `stripe post`, and `stripe delete` (`-v`) +- `yarn.json`: `yarn` (`-s`) +- `zapier.json`: `zapier-platform-cli scaffold` (`-d`) + +## Validation commands +The implementation must pass: + +- focused validator tests for all valid and invalid fixtures; +- `cargo test --verbose`; +- `cargo clippy -p warp-command-signatures -p warp-completion-metadata --all-targets --all-features -- -D warnings`; +- `cargo fmt -p warp-command-signatures -p warp-completion-metadata --check`; +- `script/presubmit`. + +No change to `script/presubmit` or `.github/workflows/CI.yml` is required because both already invoke the selected test path. + +## Implementation boundaries +Expected implementation areas are `completion-metadata/src/signature.rs`, a new validation module exported from `completion-metadata/src/lib.rs`, focused fixtures/tests in `completion-metadata/tests/`, and the invariant test in `command-signatures/src/lib.rs`. + +The implementation must not modify command JSON, autogenerated output, overrides, completion parsing behavior, or Warp UI code as part of #400. From 51b4dc5110d27ac00d03bea0c07c8962ed53f043 Mon Sep 17 00:00:00 2001 From: "warp-factories[bot]" <243557089+warp-factories[bot]@users.noreply.github.com> Date: Fri, 4 Sep 2026 22:19:21 +0000 Subject: [PATCH 2/4] spec: tighten short flag validation invariants --- specs/GH400/product.md | 18 +++++++++--------- specs/GH400/tech.md | 28 ++++++++++++++++------------ 2 files changed, 25 insertions(+), 21 deletions(-) diff --git a/specs/GH400/product.md b/specs/GH400/product.md index 2dfea251..7cc844b6 100644 --- a/specs/GH400/product.md +++ b/specs/GH400/product.md @@ -12,7 +12,7 @@ Repository validation must detect every duplicate short flag claimed by two or m For this rule: -- A short flag uses the existing `is_short_hand_flag` classification: its UTF-8 representation is exactly two bytes, it begins with `-`, and it is not `--`. Examples include `-h`, `-v`, and `-1`. `--help` and single-dash multi-character names such as `-version` are not short flags. +- Before classification, each authored option name is decoded with the same HTML-entity unescaping used by `From for Opt`. The normalized name then uses the existing `is_short_hand_flag` classification: its UTF-8 representation is exactly two bytes, it begins with `-`, and it is not `--`. Examples include `-h`, `-v`, and `-1`; an authored `-h` is normalized to `-h`. `--help` and single-dash multi-character names such as `-version` are not short flags. - Each root command and each nested subcommand is a separate option namespace. Sibling subcommands may reuse a short flag, and a parent and child may reuse it because the authored command nodes are checked separately. - Only distinct option entries conflict. Multiple aliases in one option's `name` array describe one option. Repetition inside one `name` array belongs to the duplicate-option-name validation proposed in [#399](https://github.com/warpdotdev/command-signatures/issues/399), not this rule. - A command or subcommand with multiple names still has one namespace; aliases do not create separate validation scopes. @@ -25,20 +25,20 @@ The hard repository check covers handwritten command definitions in `command-sig - `command-signatures/json/overrides/**/*.json` remains outside this rule. The current override schema can only locate an existing option by name and override argument metadata; it cannot add or rename option spellings. If that capability is added later, validation of the merged generated command should be specified with it. ## Validation error -The validator produces one diagnostic for each `(file, command path, short flag)` conflict and includes every distinct conflicting option in source order. The repository test reports unexpected diagnostics in deterministic file, command-path, and short-flag order. +The validator produces one diagnostic for each `(file, command path, normalized short flag)` conflict and includes every distinct conflicting option in source order. The repository test reports unexpected diagnostics in deterministic file, command-path, and short-flag order. The human-readable form must contain: 1. the handwritten JSON file path; 2. the full command path, using the first declared name at each command level; -3. the duplicate short flag, including its dash; -4. every conflicting option's one-based position and complete `name` array. +3. the normalized duplicate short flag, including its dash; +4. every conflicting option's one-based position and complete raw `name` array exactly as authored in the JSON. Example: `command-signatures/json/flutter.json: command "flutter assemble": duplicate short flag "-d" is used by options #3 ["-d", "--device-id"] and #8 ["-d", "--define"]` -Including positions keeps the message actionable when the conflicting options have identical `name` arrays, as several current offenders do. +The normalized flag identifies the token that conflicts at runtime, while raw arrays keep the source edit actionable when HTML entities are present. Including positions distinguishes options with identical `name` arrays, as several current offenders have. ## Rollout The recommended rollout is a hard “no new conflicts” gate backed by an exact, temporary baseline allowlist for existing offenders. @@ -59,7 +59,7 @@ At `origin/main` commit `d69b340ef622540ac28340ef565dae45287d51d8`, direct autho - `yarn.json`: 1 - `zapier.json`: 1 -Each baseline entry is keyed by relative file path, canonical command path, and short flag. CI fails if validation finds a key that is not in the baseline. CI also fails when a baseline key no longer exists, forcing the same change that fixes an offender to remove its stale entry. The implementation PR must link a dedicated follow-up issue that tracks reducing the baseline to zero, and the allowlist must link that issue in a comment. +Each baseline entry contains the relative file path, canonical command path, normalized short flag, and ordered claimant identity: every claimant's source position and complete raw `name` array. CI fails if validation finds a new conflict key or if the claimant identity for an existing key changes, including adding a third claimant or replacing one claimant while retaining the same flag. CI also fails when a baseline entry no longer exists, forcing the same change that fixes an offender to remove its stale entry. The implementation PR must link a dedicated follow-up issue that tracks reducing the baseline to zero, and the allowlist must link that issue in a comment. This approach prevents new ambiguity immediately without forcing 45 potentially behavior-sensitive command-spec corrections into the validator change. It is preferred over warn-only validation, which does not prevent regressions, and over an unconditional fix-first gate, which would make `main` fail until every existing command's intended CLI semantics had been researched. @@ -69,10 +69,10 @@ Once the baseline is empty, remove the allowlist mechanism and make every diagno - Two distinct option entries directly declared on one handwritten command or subcommand and sharing a short flag produce one actionable diagnostic. - The diagnostic identifies the JSON file, full command path, offending short flag, and all conflicting option names and positions. - Reusing a short flag on unrelated root commands, sibling subcommands, or a parent and child does not produce a conflict. -- Short flags use the repository's existing classification rather than a second definition. +- Option names receive the same HTML-entity unescaping as runtime conversion, then use the repository's existing short-flag classification rather than a second definition. - Multiple names on one option or command do not create duplicate namespaces or pairwise false positives. -- Focused fixtures cover valid reuse across namespaces and invalid reuse within one namespace, including identical option-name arrays and more than two claimants. -- A repository invariant test scans only handwritten command JSON, rejects any conflict not in the temporary baseline, and rejects stale baseline entries. +- Focused fixtures cover valid reuse across namespaces and invalid reuse within one namespace, including an HTML-escaped spelling conflicting with its literal form, identical option-name arrays, and more than two claimants. +- A repository invariant test scans only handwritten command JSON, rejects any conflict not in the temporary baseline, rejects changes to a baselined conflict's ordered claimant identity, and rejects stale baseline entries. - The invariant runs through `cargo test`, and therefore through `script/presubmit` and the CI test job without a separate manual command. ## Non-goals diff --git a/specs/GH400/tech.md b/specs/GH400/tech.md index 81424632..d493f25f 100644 --- a/specs/GH400/tech.md +++ b/specs/GH400/tech.md @@ -1,7 +1,7 @@ # Technical design: conflicting short-flag validation ## Current behavior -`completion-metadata/src/fig_types.rs` defines `CommandOption.name` as one or more strings and converts every string into `Opt.exact_string` in `From for Opt`. `From for Vec` recursively converts command nodes and copies persistent options into child commands during conversion. +`completion-metadata/src/fig_types.rs` defines `CommandOption.name` as one or more strings. `From for Opt` applies `html_unescape` to every authored name before storing it in `Opt.exact_string`. `From for Vec` recursively converts command nodes and copies persistent options into child commands during conversion. `completion-metadata/src/signature.rs` already classifies short flags in `is_short_hand_flag` and exposes converted short flags through `Signature::short_hand_flags`. The classifier is currently private, and neither conversion nor the command-signature crate checks whether distinct options claim the same short flag. @@ -16,13 +16,13 @@ Add a small validation module in `completion-metadata`, operating on `fig_types: 1. recursively walk the root command and all `subcommands`; 2. build a canonical path from the first name declared at each level; 3. inspect only the current node's `options`; -4. classify each name with the existing short-hand classifier; +4. transform each option name with the same HTML-entity unescaping used by `From for Opt`, then classify that normalized spelling with the existing short-hand classifier; 5. group occurrences by short flag while deduplicating repeated occurrences from the same option entry; 6. emit one structured conflict per flag claimed by at least two option entries. -The structured conflict must retain the canonical command path, short flag, each option's zero-based source index for programmatic use, and each option's complete name list. Formatting converts indices to one-based positions. File paths belong to the caller because `fig_types::Command` does not know its source. +The structured conflict must retain the canonical command path, normalized short flag, each option's zero-based source index for programmatic use, and each option's complete raw name list. Formatting converts indices to one-based positions and displays raw name arrays exactly as authored; this makes an encoded source such as `-h` findable while the normalized `-h` identifies the runtime collision. File paths belong to the caller because `fig_types::Command` does not know its source. -Move or expose `is_short_hand_flag` within the crate so the validator and `Signature::short_hand_flags` share one implementation. Do not publish a second classifier with subtly different Unicode or dash behavior. +Move or expose `html_unescape` and `is_short_hand_flag` within the crate so validation and conversion share the same normalization and classification implementations. Do not publish duplicate helpers with subtly different entity, Unicode, or dash behavior. The recursive walk and diagnostic types should be reusable by the duplicate-name work in #399. That issue can add another rule over the same command/option traversal, but duplicate full-name validation is not implemented under #400. @@ -31,21 +31,22 @@ Add an invariant test in `command-signatures/src/lib.rs` that reads only the top Do not use `Assets::iter()` or `commands()` for this test: both combine manual and autogenerated assets, and `commands()` validates converted rather than authored option sets. -The test compares the collected conflict keys with a constant baseline of the 45 current `(relative file, canonical command path, short flag)` keys: +The test compares complete collected conflict records with a constant baseline of the 45 current `(relative file, canonical command path, normalized short flag)` keys and each key's ordered claimant list of source indices and complete raw `name` arrays: -- Any collected conflict absent from the baseline fails with the complete diagnostic. -- Any baseline entry absent from the collected set fails as stale and tells the contributor to remove it. -- Matching baseline conflicts do not fail the test. +- Any collected conflict key absent from the baseline fails with the complete diagnostic. +- Any existing key whose ordered claimant list differs from its baseline fails and shows the expected and actual claimants. Adding a claimant, removing one, reordering options, or swapping a claimant is therefore review-visible even when the key is unchanged. +- Any baseline conflict absent from the collected set fails as stale and tells the contributor to remove it. +- Only records matching both the key and ordered claimant list avoid failure. - The baseline is documented as temporary and links the dedicated cleanup issue required by the product rollout. -This exact-set comparison makes the allowlist non-expandable by accident and guarantees monotonically reviewed burn-down. Adding an entry remains possible only as an explicit code-review decision; it must not be generated automatically during tests. +This complete-record comparison makes the allowlist non-expandable by accident and guarantees monotonically reviewed burn-down. Adding or changing an entry remains possible only as an explicit code-review decision; baseline content must not be generated automatically during tests. ### Diagnostic formatting Formatting must be deterministic and use this shape: `: command "": duplicate short flag "" is used by options # [, ...]` -Use JSON array formatting for names so aliases and punctuation are unambiguous. List conflicting options in source order. Aggregate all unexpected conflicts into one assertion failure so contributors can fix every reported location in one pass. +Display the normalized short flag but use the raw authored name arrays in JSON formatting so aliases, entities, and punctuation are unambiguous and findable in source. List conflicting options in source order. Aggregate all unexpected or changed conflicts into one assertion failure so contributors can fix every reported location in one pass. ## Fixture and test coverage Create focused JSON fixtures under `completion-metadata/tests/fixtures/duplicate_short_flags/` and exercise them from validation tests. @@ -57,6 +58,7 @@ Invalid coverage: - three option entries share one short flag and produce one diagnostic listing all three; - a duplicate exists on a nested subcommand and the diagnostic contains the full root-to-leaf path; - an option repeats the same short spelling internally and another option claims it, proving the first option is counted once rather than creating pairwise duplicate diagnostics. +- one option spells `-h` as `-h` and another spells it literally, proving runtime-equivalent names conflict and the diagnostic displays normalized `-h` with both raw arrays. Valid coverage: @@ -70,17 +72,19 @@ Valid coverage: The command-signature crate should also test file discovery boundaries: a fixture or helper-level test confirms that only top-level handwritten JSON is selected, not `autogenerated/` or `overrides/`. +The baseline comparison must have regression tests in which an otherwise matching baselined key gains a third claimant and in which one claimant is replaced. Both cases must fail because their ordered claimant records differ even though `(file, command path, short flag)` is unchanged. + ## Edge cases - Report one conflict per command namespace and short flag, not one error per pair of options. - Preserve case. `-v` and `-V` are different flags. -- Preserve the exact token. No normalization is applied beyond the existing classifier. +- Decode HTML entities exactly once through the shared conversion helper before classification; apply no other normalization. Diagnostics preserve raw authored names while identifying the normalized conflicting flag. - A duplicate spelling inside one option entry alone is not a #400 conflict. - Parent and child nodes are independent even when the parent option is persistent. The validator runs before persistent-option expansion and does not report the inherited copy as another authored option. - If a node has multiple command names, its options are validated once and its first declared name is used in the canonical path. - Existing malformed JSON remains the responsibility of deserialization validation; the new validator receives a successfully deserialized `Command`. ## Verified baseline -The inventory was recomputed against `origin/main` commit `d69b340ef622540ac28340ef565dae45287d51d8` by recursively examining the directly declared options of every `command-signatures/json/*.json` command node and excluding `autogenerated/` and `overrides/`. +The inventory was recomputed against `origin/main` commit `d69b340ef622540ac28340ef565dae45287d51d8` by recursively examining the directly declared options of every `command-signatures/json/*.json` command node, HTML-unescaping names before short-flag classification, and excluding `autogenerated/` and `overrides/`. Runtime-equivalent normalization does not change the verified total or distribution. The 45 keys are distributed as follows: From 95d904ba185986f7518eb4f825b611dd60e3649c Mon Sep 17 00:00:00 2001 From: "warp-factories[bot]" <243557089+warp-factories[bot]@users.noreply.github.com> Date: Fri, 4 Sep 2026 22:34:16 +0000 Subject: [PATCH 3/4] Validate conflicting short flags in handwritten command signatures Adds a shared validator in warp-completion-metadata that detects two or more distinct option entries directly authored on the same command or subcommand node claiming the same normalized short flag. Option names are HTML-unescaped with the same helper used by `From for Opt` before classification, so encoded and literal spellings (e.g. `-h` and `-h`) are recognized as the same flag; diagnostics show the normalized flag alongside the raw authored name arrays. A repository invariant test in warp-command-signatures scans only the top-level handwritten command-signatures/json/*.json files (excluding autogenerated/ and overrides/) and compares collected conflicts against a temporary, exact baseline allowlist of the 45 pre-existing conflicts across 13 files. The comparison is against complete records -- (file, command path, short flag) plus the ordered claimant list of source indices and raw name arrays -- so adding, removing, reordering, or swapping a claimant fails even when the key itself is unchanged. Regression tests cover both the third-claimant and swapped-claimant cases directly against the comparison function. Fixes #400. Follow-up: https://github.com/warpdotdev/command-signatures/issues/402 tracks reducing the baseline to zero. --- command-signatures/src/lib.rs | 565 ++++++++++++++++++ completion-metadata/src/fig_types.rs | 2 +- completion-metadata/src/lib.rs | 1 + completion-metadata/src/signature.rs | 2 +- completion-metadata/src/validation.rs | 176 ++++++ .../tests/duplicate_short_flags.rs | 145 +++++ .../invalid_command_alias_namespace.json | 7 + .../invalid_html_escaped_vs_literal.json | 7 + .../invalid_identical_name_arrays.json | 7 + .../invalid_nested_subcommand.json | 17 + .../invalid_repeated_internal_spelling.json | 7 + .../invalid_three_claimants.json | 8 + .../invalid_two_distinct_options.json | 13 + .../valid_distinct_short_flags.json | 7 + .../valid_long_flags_not_short.json | 9 + .../valid_root_and_child_reuse.json | 10 + .../valid_short_and_long_alias.json | 4 + .../valid_sibling_subcommands_reuse.json | 7 + .../valid_unrelated_top_level_a.json | 4 + .../valid_unrelated_top_level_b.json | 4 + 20 files changed, 1000 insertions(+), 2 deletions(-) create mode 100644 completion-metadata/src/validation.rs create mode 100644 completion-metadata/tests/duplicate_short_flags.rs create mode 100644 completion-metadata/tests/fixtures/duplicate_short_flags/invalid_command_alias_namespace.json create mode 100644 completion-metadata/tests/fixtures/duplicate_short_flags/invalid_html_escaped_vs_literal.json create mode 100644 completion-metadata/tests/fixtures/duplicate_short_flags/invalid_identical_name_arrays.json create mode 100644 completion-metadata/tests/fixtures/duplicate_short_flags/invalid_nested_subcommand.json create mode 100644 completion-metadata/tests/fixtures/duplicate_short_flags/invalid_repeated_internal_spelling.json create mode 100644 completion-metadata/tests/fixtures/duplicate_short_flags/invalid_three_claimants.json create mode 100644 completion-metadata/tests/fixtures/duplicate_short_flags/invalid_two_distinct_options.json create mode 100644 completion-metadata/tests/fixtures/duplicate_short_flags/valid_distinct_short_flags.json create mode 100644 completion-metadata/tests/fixtures/duplicate_short_flags/valid_long_flags_not_short.json create mode 100644 completion-metadata/tests/fixtures/duplicate_short_flags/valid_root_and_child_reuse.json create mode 100644 completion-metadata/tests/fixtures/duplicate_short_flags/valid_short_and_long_alias.json create mode 100644 completion-metadata/tests/fixtures/duplicate_short_flags/valid_sibling_subcommands_reuse.json create mode 100644 completion-metadata/tests/fixtures/duplicate_short_flags/valid_unrelated_top_level_a.json create mode 100644 completion-metadata/tests/fixtures/duplicate_short_flags/valid_unrelated_top_level_b.json diff --git a/command-signatures/src/lib.rs b/command-signatures/src/lib.rs index b0a74f1d..0436f294 100644 --- a/command-signatures/src/lib.rs +++ b/command-signatures/src/lib.rs @@ -257,3 +257,568 @@ mod tests { } } } + +/// Invariant: no handwritten command spec has two distinct option entries directly declaring +/// the same short flag (https://github.com/warpdotdev/command-signatures/issues/400). +/// +/// A hard "no new conflicts" gate is backed by an exact, temporary baseline allowlist of the 45 +/// conflicts that predate this rule (tracked by +/// https://github.com/warpdotdev/command-signatures/issues/402). The baseline is compared as +/// complete records — `(file, command path, short flag)` plus the ordered claimant list of +/// source indices and raw `name` arrays — so adding a claimant, removing one, reordering +/// options, or swapping a claimant is review-visible even when the key itself is unchanged. +#[cfg(test)] +mod duplicate_short_flags { + use crate::fig_types::Command; + use crate::validation::find_short_flag_conflicts; + use std::collections::BTreeMap; + use std::fs; + use std::path::{Path, PathBuf}; + + /// `(file, command path, short flag)`. + type ConflictKey = (String, Vec, String); + /// Ordered `(zero-based source index, complete raw name array)` per claimant. + type Claimants = Vec<(usize, Vec)>; + + struct BaselineConflict { + file: &'static str, + command_path: &'static [&'static str], + flag: &'static str, + claimants: &'static [(usize, &'static [&'static str])], + } + + /// Temporary allowlist of pre-existing conflicts. See the module doc comment above. + /// + /// Do not add entries to this baseline for newly introduced conflicts: fix the command spec + /// instead. Removing an entry because its conflict was fixed is always welcome; see + /// https://github.com/warpdotdev/command-signatures/issues/402. + const SHORT_FLAG_CONFLICT_BASELINE: &[BaselineConflict] = &[ + BaselineConflict { + file: "brew.json", + command_path: &["brew", "services"], + flag: "-h", + claimants: &[(3, &["-h", "--help"]), (7, &["-h", "--help"])], + }, + BaselineConflict { + file: "brew.json", + command_path: &["brew", "services"], + flag: "-v", + claimants: &[(2, &["-v", "--verbose"]), (6, &["-v", "--verbose"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "svc", "package"], + flag: "-n", + claimants: &[(1, &["--name", "-n"]), (2, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "svc", "deploy"], + flag: "-n", + claimants: &[(1, &["--name", "-n"]), (3, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "svc", "delete"], + flag: "-n", + claimants: &[(1, &["--name", "-n"]), (2, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "svc", "status"], + flag: "-n", + claimants: &[(1, &["--name", "-n"]), (3, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "svc", "logs"], + flag: "-n", + claimants: &[(2, &["--name", "-n"]), (7, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "svc", "exec"], + flag: "-n", + claimants: &[(3, &["--name", "-n"]), (4, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "svc", "pause"], + flag: "-n", + claimants: &[(1, &["--name", "-n"]), (2, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "svc", "resume"], + flag: "-n", + claimants: &[(1, &["--name", "-n"]), (2, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "job", "package"], + flag: "-n", + claimants: &[(1, &["--name", "-n"]), (2, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "job", "deploy"], + flag: "-n", + claimants: &[(1, &["--name", "-n"]), (2, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "job", "delete"], + flag: "-n", + claimants: &[(1, &["--name", "-n"]), (2, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "task", "exec"], + flag: "-n", + claimants: &[(3, &["--name", "-n"]), (4, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "task", "delete"], + flag: "-n", + claimants: &[(2, &["--name", "-n"]), (3, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "deploy"], + flag: "-n", + claimants: &[(1, &["--name", "-n"]), (3, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "help", "svc", "package"], + flag: "-n", + claimants: &[(1, &["--name", "-n"]), (2, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "help", "svc", "deploy"], + flag: "-n", + claimants: &[(1, &["--name", "-n"]), (3, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "help", "svc", "delete"], + flag: "-n", + claimants: &[(1, &["--name", "-n"]), (2, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "help", "svc", "status"], + flag: "-n", + claimants: &[(1, &["--name", "-n"]), (3, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "help", "svc", "logs"], + flag: "-n", + claimants: &[(2, &["--name", "-n"]), (7, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "help", "svc", "exec"], + flag: "-n", + claimants: &[(3, &["--name", "-n"]), (4, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "help", "svc", "pause"], + flag: "-n", + claimants: &[(1, &["--name", "-n"]), (2, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "help", "svc", "resume"], + flag: "-n", + claimants: &[(1, &["--name", "-n"]), (2, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "help", "job", "package"], + flag: "-n", + claimants: &[(1, &["--name", "-n"]), (2, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "help", "job", "deploy"], + flag: "-n", + claimants: &[(1, &["--name", "-n"]), (2, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "help", "job", "delete"], + flag: "-n", + claimants: &[(1, &["--name", "-n"]), (2, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "help", "task", "exec"], + flag: "-n", + claimants: &[(3, &["--name", "-n"]), (4, &["--name", "-n"])], + }, + BaselineConflict { + file: "copilot.json", + command_path: &["copilot", "help", "task", "delete"], + flag: "-n", + claimants: &[(2, &["--name", "-n"]), (3, &["--name", "-n"])], + }, + BaselineConflict { + file: "flutter.json", + command_path: &["flutter", "assemble"], + flag: "-d", + claimants: &[(2, &["-d", "--device-id"]), (4, &["-d", "--define"])], + }, + BaselineConflict { + file: "flutter.json", + command_path: &["flutter", "symbolize"], + flag: "-d", + claimants: &[(2, &["-d", "--device-id"]), (4, &["-d", "--debug-info"])], + }, + BaselineConflict { + file: "kubecolor.json", + command_path: &["kubecolor", "expose"], + flag: "-l", + claimants: &[(7, &["-l", "--selector"]), (12, &["-l", "--labels"])], + }, + BaselineConflict { + file: "kubectl.json", + command_path: &["kubectl", "expose"], + flag: "-l", + claimants: &[(7, &["-l", "--selector"]), (12, &["-l", "--labels"])], + }, + BaselineConflict { + file: "oc.json", + command_path: &["oc", "expose"], + flag: "-l", + claimants: &[(7, &["-l", "--selector"]), (12, &["-l", "--labels"])], + }, + BaselineConflict { + file: "pscale.json", + command_path: &["pscale", "completion"], + flag: "-h", + claimants: &[(1, &["--help", "-h"]), (2, &["--help", "-h"])], + }, + BaselineConflict { + file: "pscale.json", + command_path: &["pscale", "connect"], + flag: "-h", + claimants: &[(0, &["--help", "-h"]), (8, &["--help", "-h"])], + }, + BaselineConflict { + file: "pulumi.json", + command_path: &["pulumi", "import"], + flag: "-f", + claimants: &[(17, &["-f", "--skip-preview"]), (19, &["-f", "--file"])], + }, + BaselineConflict { + file: "rsync.json", + command_path: &["rsync"], + flag: "-h", + claimants: &[(111, &["-h", "--human-readable"]), (134, &["-h", "--help"])], + }, + BaselineConflict { + file: "sfdx.json", + command_path: &["sfdx", "auth:accesstoken:store"], + flag: "-s", + claimants: &[ + (3, &["-s", "--setdefaultdevhubusername"]), + (4, &["-s", "--setdefaultusername"]), + ], + }, + BaselineConflict { + file: "stripe.json", + command_path: &["stripe", "events resend"], + flag: "-v", + claimants: &[ + (11, &["-v", "--stripe-version"]), + (18, &["-v", "--version"]), + ], + }, + BaselineConflict { + file: "stripe.json", + command_path: &["stripe", "get"], + flag: "-v", + claimants: &[ + (11, &["-v", "--stripe-version"]), + (18, &["-v", "--version"]), + ], + }, + BaselineConflict { + file: "stripe.json", + command_path: &["stripe", "post"], + flag: "-v", + claimants: &[(8, &["-v", "--stripe-version"]), (15, &["-v", "--version"])], + }, + BaselineConflict { + file: "stripe.json", + command_path: &["stripe", "delete"], + flag: "-v", + claimants: &[(8, &["-v", "--stripe-version"]), (15, &["-v", "--version"])], + }, + BaselineConflict { + file: "yarn.json", + command_path: &["yarn"], + flag: "-s", + claimants: &[(35, &["-s", "--silent"]), (39, &["-s", "--silent"])], + }, + BaselineConflict { + file: "zapier.json", + command_path: &["zapier-platform-cli", "scaffold"], + flag: "-d", + claimants: &[(0, &["-d", "--dest"]), (5, &["-d", "--debug"])], + }, + ]; + + fn baseline_map() -> BTreeMap { + let mut map = BTreeMap::new(); + for entry in SHORT_FLAG_CONFLICT_BASELINE { + let key: ConflictKey = ( + format!("command-signatures/json/{}", entry.file), + entry.command_path.iter().map(|s| s.to_string()).collect(), + entry.flag.to_string(), + ); + let claimants: Claimants = entry + .claimants + .iter() + .map(|(index, names)| (*index, names.iter().map(|s| s.to_string()).collect())) + .collect(); + assert!( + map.insert(key, claimants).is_none(), + "duplicate baseline entry for {} {:?} {}", + entry.file, + entry.command_path, + entry.flag + ); + } + map + } + + /// Only the top-level handwritten `command-signatures/json/*.json` files, excluding + /// `autogenerated/` and `overrides/`. + fn handwritten_json_files() -> Vec { + let json_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("json"); + let mut files: Vec = fs::read_dir(&json_dir) + .unwrap_or_else(|err| panic!("failed to read {}: {err}", json_dir.display())) + .filter_map(|entry| entry.ok()) + .map(|entry| entry.path()) + .filter(|path| path.is_file() && path.extension().is_some_and(|ext| ext == "json")) + .collect(); + files.sort(); + files + } + + fn collect_actual_conflicts() -> BTreeMap { + let mut actual = BTreeMap::new(); + for path in handwritten_json_files() { + let filename = path + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or_default() + .to_string(); + let relative_file = format!("command-signatures/json/{filename}"); + let content = fs::read_to_string(&path) + .unwrap_or_else(|err| panic!("failed to read {}: {err}", path.display())); + let command: Command = serde_json::from_str(&content) + .unwrap_or_else(|err| panic!("{relative_file} failed to deserialize: {err}")); + + for conflict in find_short_flag_conflicts(&command) { + let key: ConflictKey = ( + relative_file.clone(), + conflict.command_path.clone(), + conflict.flag.clone(), + ); + let claimants: Claimants = conflict + .claimants + .iter() + .map(|claimant| (claimant.index, claimant.names.clone())) + .collect(); + assert!( + actual.insert(key, claimants).is_none(), + "validator produced two records for the same conflict key in {relative_file}" + ); + } + } + actual + } + + /// Compares collected conflicts against the baseline as complete records. Returns one + /// human-readable failure message per problem found: + /// - a collected conflict whose key is absent from the baseline (a new conflict); + /// - a collected conflict whose ordered claimant list differs from the baseline's (the + /// claimant identity changed even though the key is unchanged); + /// - a baseline entry with no matching collected conflict (a stale entry that must be + /// removed). + fn diff_against_baseline( + actual: &BTreeMap, + baseline: &BTreeMap, + ) -> Vec { + let mut failures = Vec::new(); + + for (key, claimants) in actual { + let (file, command_path, flag) = key; + match baseline.get(key) { + None => failures.push(format!( + "new duplicate short flag conflict not in baseline: {file}: command {command_path:?}: duplicate short flag {flag:?} is used by options {claimants:?}" + )), + Some(expected_claimants) if expected_claimants != claimants => failures.push(format!( + "claimant identity changed for baselined conflict {file}: command {command_path:?}: duplicate short flag {flag:?}\n expected claimants: {expected_claimants:?}\n actual claimants: {claimants:?}" + )), + _ => {} + } + } + + for key in baseline.keys() { + if !actual.contains_key(key) { + let (file, command_path, flag) = key; + failures.push(format!( + "stale baseline entry, remove it: {file}: command {command_path:?}: duplicate short flag {flag:?}" + )); + } + } + + failures + } + + #[test] + fn duplicate_short_flags_match_baseline() { + let actual = collect_actual_conflicts(); + let baseline = baseline_map(); + let failures = diff_against_baseline(&actual, &baseline); + assert!( + failures.is_empty(), + "\n{}\n\nSee https://github.com/warpdotdev/command-signatures/issues/400 and the \ + temporary baseline allowlist tracked by \ + https://github.com/warpdotdev/command-signatures/issues/402.", + failures.join("\n") + ); + } + + #[test] + fn only_top_level_handwritten_json_is_discovered() { + let files = handwritten_json_files(); + assert!( + !files.is_empty(), + "expected to discover handwritten JSON files" + ); + for path in &files { + let path_str = path.to_string_lossy(); + assert!( + !path_str.contains("autogenerated"), + "discovered file should not come from autogenerated/: {path_str}" + ); + assert!( + !path_str.contains("overrides"), + "discovered file should not come from overrides/: {path_str}" + ); + } + assert!( + files + .iter() + .any(|path| path.file_name().and_then(|n| n.to_str()) == Some("flutter.json")), + "expected to discover the top-level flutter.json fixture" + ); + } + + /// Regression test: an otherwise matching baselined key that gains a third claimant must + /// fail, even though `(file, command path, short flag)` is unchanged. + #[test] + fn diff_detects_a_claimant_added_to_a_baselined_conflict() { + let key: ConflictKey = ( + "tool.json".to_string(), + vec!["tool".to_string()], + "-t".to_string(), + ); + let mut baseline = BTreeMap::new(); + baseline.insert( + key.clone(), + vec![(0, vec!["-t".to_string()]), (1, vec!["-t".to_string()])], + ); + + let mut actual = BTreeMap::new(); + actual.insert( + key, + vec![ + (0, vec!["-t".to_string()]), + (1, vec!["-t".to_string()]), + (2, vec!["-t".to_string()]), + ], + ); + + let failures = diff_against_baseline(&actual, &baseline); + assert_eq!(failures.len(), 1); + assert!(failures[0].contains("claimant identity changed")); + } + + /// Regression test: replacing one claimant of an otherwise matching baselined key must fail, + /// even though `(file, command path, short flag)` is unchanged. + #[test] + fn diff_detects_a_claimant_replaced_in_a_baselined_conflict() { + let key: ConflictKey = ( + "tool.json".to_string(), + vec!["tool".to_string()], + "-t".to_string(), + ); + let mut baseline = BTreeMap::new(); + baseline.insert( + key.clone(), + vec![ + (0, vec!["-t".to_string(), "--type-a".to_string()]), + (1, vec!["-t".to_string(), "--type-b".to_string()]), + ], + ); + + let mut actual = BTreeMap::new(); + actual.insert( + key, + vec![ + (0, vec!["-t".to_string(), "--type-a".to_string()]), + (1, vec!["-t".to_string(), "--type-c".to_string()]), + ], + ); + + let failures = diff_against_baseline(&actual, &baseline); + assert_eq!(failures.len(), 1); + assert!(failures[0].contains("claimant identity changed")); + } + + #[test] + fn diff_flags_new_conflicts_not_in_baseline() { + let baseline = BTreeMap::new(); + let mut actual = BTreeMap::new(); + actual.insert( + ( + "tool.json".to_string(), + vec!["tool".to_string()], + "-t".to_string(), + ), + vec![(0, vec!["-t".to_string()]), (1, vec!["-t".to_string()])], + ); + + let failures = diff_against_baseline(&actual, &baseline); + assert_eq!(failures.len(), 1); + assert!(failures[0].contains("new duplicate short flag conflict")); + } + + #[test] + fn diff_flags_stale_baseline_entries() { + let mut baseline = BTreeMap::new(); + baseline.insert( + ( + "tool.json".to_string(), + vec!["tool".to_string()], + "-t".to_string(), + ), + vec![(0, vec!["-t".to_string()]), (1, vec!["-t".to_string()])], + ); + let actual = BTreeMap::new(); + + let failures = diff_against_baseline(&actual, &baseline); + assert_eq!(failures.len(), 1); + assert!(failures[0].contains("stale baseline entry")); + } +} diff --git a/completion-metadata/src/fig_types.rs b/completion-metadata/src/fig_types.rs index 7500620c..ae7027e4 100644 --- a/completion-metadata/src/fig_types.rs +++ b/completion-metadata/src/fig_types.rs @@ -528,7 +528,7 @@ impl From for crate::ParserDirectives { } /// Unescape HTML entities that Fig allows in `name` or `description` fields. -fn html_unescape(input: String) -> String { +pub(crate) fn html_unescape(input: String) -> String { match html_escape::decode_html_entities(&input) { // If the input is returned as-is, it contains no HTML entities so we can reuse the owned String. Cow::Borrowed(_) => input, diff --git a/completion-metadata/src/lib.rs b/completion-metadata/src/lib.rs index 8cf47bbc..3ad3156a 100644 --- a/completion-metadata/src/lib.rs +++ b/completion-metadata/src/lib.rs @@ -1,6 +1,7 @@ mod command_builder; pub mod fig_types; mod signature; +pub mod validation; use serde::{Deserialize, Serialize}; pub use signature::*; diff --git a/completion-metadata/src/signature.rs b/completion-metadata/src/signature.rs index 16b6041f..e877d67c 100644 --- a/completion-metadata/src/signature.rs +++ b/completion-metadata/src/signature.rs @@ -91,7 +91,7 @@ impl Signature { /// * A single dash followed by a single character (`-h`, `-v`, etc.) is short-hand, unless the second character is also a dash. /// * A single dash followed by multiple characters (`-version`) is long-hand /// * Two dashes followed by 0 or more characters is long-hand -fn is_short_hand_flag(name: &str) -> bool { +pub(crate) fn is_short_hand_flag(name: &str) -> bool { name.len() == 2 && name.starts_with('-') && name != "--" } diff --git a/completion-metadata/src/validation.rs b/completion-metadata/src/validation.rs new file mode 100644 index 00000000..304c2534 --- /dev/null +++ b/completion-metadata/src/validation.rs @@ -0,0 +1,176 @@ +//! Shared metadata validation for handwritten command specs. +//! +//! These checks operate on [`fig_types::Command`] before it is converted into [`crate::Signature`], +//! because conversion loses the source option boundaries (and, for persistent options, copies +//! options into descendant nodes) that precise diagnostics depend on. +//! +//! The recursive command/option traversal here is intentionally reusable: additional rules over +//! the same authored command tree (such as duplicate full option names) can be added alongside +//! [`find_short_flag_conflicts`] without re-implementing traversal. + +use crate::fig_types::{html_unescape, Command, CommandOption}; +use crate::signature::is_short_hand_flag; +use std::collections::{BTreeMap, HashSet}; + +/// A single option entry that claims a short flag involved in a [`ShortFlagConflict`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ShortFlagClaimant { + /// The option's zero-based position within its command node's authored `options` array. + pub index: usize, + /// The complete, raw `name` array exactly as authored in the JSON (before HTML-entity + /// unescaping). + pub names: Vec, +} + +/// A short flag claimed by two or more distinct option entries directly authored on the same +/// command or subcommand node. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ShortFlagConflict { + /// The canonical command path, using the first declared name at each command level. + pub command_path: Vec, + /// The normalized short flag (e.g. `-h`), after HTML-entity unescaping. + pub flag: String, + /// Every distinct conflicting option, in source order. + pub claimants: Vec, +} + +impl ShortFlagConflict { + /// Formats a deterministic, human-readable diagnostic for this conflict. + /// + /// `file` is the (repository-relative) path of the JSON file the conflict was found in; it is + /// supplied by the caller because `fig_types::Command` does not know its own source file. + pub fn describe(&self, file: &str) -> String { + let path = self.command_path.join(" "); + let options = self + .claimants + .iter() + .map(|claimant| { + format!( + "#{} {}", + claimant.index + 1, + format_name_array(&claimant.names) + ) + }) + .collect::>(); + format!( + "{file}: command \"{path}\": duplicate short flag \"{flag}\" is used by options {options}", + file = file, + path = path, + flag = self.flag, + options = join_with_and(&options), + ) + } +} + +fn format_name_array(names: &[String]) -> String { + let entries = names + .iter() + .map(|name| format!("{name:?}")) + .collect::>() + .join(", "); + format!("[{entries}]") +} + +/// Joins strings such that `["a"]` -> `"a"`, `["a", "b"]` -> `"a and b"`, and +/// `["a", "b", "c"]` -> `"a, b, and c"`. +fn join_with_and(parts: &[String]) -> String { + match parts { + [] => String::new(), + [only] => only.clone(), + [first, second] => format!("{first} and {second}"), + _ => { + let (last, rest) = parts.split_last().expect("parts has more than 2 elements"); + format!("{}, and {}", rest.join(", "), last) + } + } +} + +/// Recursively finds every duplicate-short-flag conflict directly authored on `command` and its +/// subcommands. +/// +/// Each command or subcommand node is treated as an independent option namespace: sibling +/// subcommands, and a parent and its children, may reuse the same short flag without conflict. +/// Only options directly declared on a node are considered; persistent options are not yet copied +/// into descendants at this stage, so they are not double-counted as new authored definitions. +pub fn find_short_flag_conflicts(command: &Command) -> Vec { + let mut conflicts = Vec::new(); + walk(command, &[], &mut conflicts); + conflicts +} + +fn walk(command: &Command, path_prefix: &[String], conflicts: &mut Vec) { + let mut path = path_prefix.to_vec(); + // A command/subcommand's `name` array holds aliases for one namespace; the first declared + // name is used as the canonical path segment. + path.push(command.name.first().cloned().unwrap_or_default()); + + conflicts.extend(conflicts_in_options(&command.options, &path)); + + for subcommand in &command.subcommands { + walk(subcommand, &path, conflicts); + } +} + +fn conflicts_in_options(options: &[CommandOption], path: &[String]) -> Vec { + let mut claimants_by_flag: BTreeMap> = BTreeMap::new(); + + for (index, option) in options.iter().enumerate() { + // Repeated spellings of the same normalized flag within one option's `name` array + // describe one option, so it must only be counted once per flag here. + let mut flags_claimed_by_this_option = HashSet::new(); + for name in &option.name { + let normalized = html_unescape(name.clone()); + if is_short_hand_flag(&normalized) + && flags_claimed_by_this_option.insert(normalized.clone()) + { + claimants_by_flag + .entry(normalized) + .or_default() + .push(ShortFlagClaimant { + index, + names: option.name.clone(), + }); + } + } + } + + claimants_by_flag + .into_iter() + .filter(|(_, claimants)| claimants.len() > 1) + .map(|(flag, claimants)| ShortFlagConflict { + command_path: path.to_vec(), + flag, + claimants, + }) + .collect() +} + +// Focused valid/invalid fixture coverage for this rule lives in +// `completion-metadata/tests/duplicate_short_flags.rs`, which exercises the fixtures under +// `completion-metadata/tests/fixtures/duplicate_short_flags/`. +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn join_with_and_formats_by_count() { + assert_eq!(join_with_and(&[]), ""); + assert_eq!(join_with_and(&["a".to_string()]), "a"); + assert_eq!( + join_with_and(&["a".to_string(), "b".to_string()]), + "a and b" + ); + assert_eq!( + join_with_and(&["a".to_string(), "b".to_string(), "c".to_string()]), + "a, b, and c" + ); + } + + #[test] + fn format_name_array_uses_debug_quoting() { + assert_eq!( + format_name_array(&["-d".to_string(), "--device-id".to_string()]), + "[\"-d\", \"--device-id\"]" + ); + } +} diff --git a/completion-metadata/tests/duplicate_short_flags.rs b/completion-metadata/tests/duplicate_short_flags.rs new file mode 100644 index 00000000..4e0e9afc --- /dev/null +++ b/completion-metadata/tests/duplicate_short_flags.rs @@ -0,0 +1,145 @@ +//! Focused valid/invalid fixture coverage for the duplicate-short-flag validation rule +//! (https://github.com/warpdotdev/command-signatures/issues/400). +//! +//! Fixtures live under `tests/fixtures/duplicate_short_flags/`. + +use warp_completion_metadata::fig_types::Command; +use warp_completion_metadata::validation::{find_short_flag_conflicts, ShortFlagConflict}; + +fn load(fixture_name: &str) -> Command { + let path = format!( + "{}/tests/fixtures/duplicate_short_flags/{fixture_name}", + env!("CARGO_MANIFEST_DIR") + ); + let json = std::fs::read_to_string(&path) + .unwrap_or_else(|err| panic!("failed to read fixture {path}: {err}")); + serde_json::from_str(&json) + .unwrap_or_else(|err| panic!("fixture {path} failed to deserialize: {err}")) +} + +fn conflicts_for(fixture_name: &str) -> Vec { + find_short_flag_conflicts(&load(fixture_name)) +} + +#[test] +fn two_distinct_options_conflict() { + let conflicts = conflicts_for("invalid_two_distinct_options.json"); + assert_eq!(conflicts.len(), 1); + let conflict = &conflicts[0]; + assert_eq!(conflict.command_path, vec!["flutter", "assemble"]); + assert_eq!(conflict.flag, "-d"); + assert_eq!( + conflict + .claimants + .iter() + .map(|c| c.index) + .collect::>(), + vec![0, 2] + ); + assert_eq!( + conflict.describe("command-signatures/json/flutter.json"), + "command-signatures/json/flutter.json: command \"flutter assemble\": duplicate short flag \"-d\" is used by options #1 [\"-d\", \"--device-id\"] and #3 [\"-d\", \"--define\"]" + ); +} + +#[test] +fn identical_name_arrays_are_distinguished_by_position() { + let conflicts = conflicts_for("invalid_identical_name_arrays.json"); + assert_eq!(conflicts.len(), 1); + assert_eq!( + conflicts[0] + .claimants + .iter() + .map(|c| c.index) + .collect::>(), + vec![0, 1] + ); + assert_eq!( + conflicts[0].describe("tool.json"), + "tool.json: command \"tool\": duplicate short flag \"-v\" is used by options #1 [\"-v\", \"--verbose\"] and #2 [\"-v\", \"--verbose\"]" + ); +} + +#[test] +fn three_claimants_produce_one_diagnostic_listing_all_three() { + let conflicts = conflicts_for("invalid_three_claimants.json"); + assert_eq!(conflicts.len(), 1); + assert_eq!(conflicts[0].claimants.len(), 3); + assert_eq!( + conflicts[0].describe("tool.json"), + "tool.json: command \"tool\": duplicate short flag \"-t\" is used by options #1 [\"-t\", \"--type-a\"], #2 [\"-t\", \"--type-b\"], and #3 [\"-t\", \"--type-c\"]" + ); +} + +#[test] +fn nested_subcommand_conflict_reports_full_root_to_leaf_path() { + let conflicts = conflicts_for("invalid_nested_subcommand.json"); + assert_eq!(conflicts.len(), 1); + assert_eq!(conflicts[0].command_path, vec!["tool", "group", "leaf"]); +} + +#[test] +fn repeated_internal_spelling_counts_the_option_once() { + let conflicts = conflicts_for("invalid_repeated_internal_spelling.json"); + assert_eq!(conflicts.len(), 1); + assert_eq!(conflicts[0].claimants.len(), 2); + assert_eq!( + conflicts[0] + .claimants + .iter() + .map(|c| c.index) + .collect::>(), + vec![0, 1] + ); +} + +#[test] +fn html_escaped_spelling_conflicts_with_literal_form() { + let conflicts = conflicts_for("invalid_html_escaped_vs_literal.json"); + assert_eq!(conflicts.len(), 1); + assert_eq!(conflicts[0].flag, "-h"); + assert_eq!( + conflicts[0].describe("tool.json"), + "tool.json: command \"tool\": duplicate short flag \"-h\" is used by options #1 [\"-h\", \"--help\"] and #2 [\"-h\", \"--history\"]" + ); +} + +#[test] +fn command_alias_names_share_one_namespace() { + let conflicts = conflicts_for("invalid_command_alias_namespace.json"); + assert_eq!(conflicts.len(), 1); + // The conflict is reported once (not once per alias), and the canonical path uses only the + // first declared name. + assert_eq!(conflicts[0].command_path, vec!["foo"]); +} + +#[test] +fn distinct_short_flags_do_not_conflict() { + assert!(conflicts_for("valid_distinct_short_flags.json").is_empty()); +} + +#[test] +fn parent_and_child_may_reuse_a_short_flag() { + assert!(conflicts_for("valid_root_and_child_reuse.json").is_empty()); +} + +#[test] +fn sibling_subcommands_may_reuse_a_short_flag() { + assert!(conflicts_for("valid_sibling_subcommands_reuse.json").is_empty()); +} + +#[test] +fn unrelated_top_level_fixtures_may_reuse_a_short_flag() { + assert!(conflicts_for("valid_unrelated_top_level_a.json").is_empty()); + assert!(conflicts_for("valid_unrelated_top_level_b.json").is_empty()); +} + +#[test] +fn short_and_long_alias_on_one_option_does_not_conflict() { + assert!(conflicts_for("valid_short_and_long_alias.json").is_empty()); +} + +#[test] +fn single_dash_long_names_are_not_short_flags() { + assert!(conflicts_for("valid_long_flags_not_short.json").is_empty()); +} diff --git a/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_command_alias_namespace.json b/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_command_alias_namespace.json new file mode 100644 index 00000000..c5eced64 --- /dev/null +++ b/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_command_alias_namespace.json @@ -0,0 +1,7 @@ +{ + "name": ["foo", "bar"], + "options": [ + { "name": ["-x", "--ex-1"] }, + { "name": ["-x", "--ex-2"] } + ] +} diff --git a/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_html_escaped_vs_literal.json b/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_html_escaped_vs_literal.json new file mode 100644 index 00000000..2d34264f --- /dev/null +++ b/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_html_escaped_vs_literal.json @@ -0,0 +1,7 @@ +{ + "name": "tool", + "options": [ + { "name": ["-h", "--help"] }, + { "name": ["-h", "--history"] } + ] +} diff --git a/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_identical_name_arrays.json b/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_identical_name_arrays.json new file mode 100644 index 00000000..014320e9 --- /dev/null +++ b/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_identical_name_arrays.json @@ -0,0 +1,7 @@ +{ + "name": "tool", + "options": [ + { "name": ["-v", "--verbose"] }, + { "name": ["-v", "--verbose"] } + ] +} diff --git a/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_nested_subcommand.json b/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_nested_subcommand.json new file mode 100644 index 00000000..81099506 --- /dev/null +++ b/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_nested_subcommand.json @@ -0,0 +1,17 @@ +{ + "name": "tool", + "subcommands": [ + { + "name": "group", + "subcommands": [ + { + "name": "leaf", + "options": [ + { "name": ["-l", "--long-a"] }, + { "name": ["-l", "--long-b"] } + ] + } + ] + } + ] +} diff --git a/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_repeated_internal_spelling.json b/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_repeated_internal_spelling.json new file mode 100644 index 00000000..8c9366f8 --- /dev/null +++ b/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_repeated_internal_spelling.json @@ -0,0 +1,7 @@ +{ + "name": "tool", + "options": [ + { "name": ["-h", "--help", "-h"] }, + { "name": ["-h", "--history"] } + ] +} diff --git a/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_three_claimants.json b/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_three_claimants.json new file mode 100644 index 00000000..91fcec61 --- /dev/null +++ b/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_three_claimants.json @@ -0,0 +1,8 @@ +{ + "name": "tool", + "options": [ + { "name": ["-t", "--type-a"] }, + { "name": ["-t", "--type-b"] }, + { "name": ["-t", "--type-c"] } + ] +} diff --git a/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_two_distinct_options.json b/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_two_distinct_options.json new file mode 100644 index 00000000..7961cd9b --- /dev/null +++ b/completion-metadata/tests/fixtures/duplicate_short_flags/invalid_two_distinct_options.json @@ -0,0 +1,13 @@ +{ + "name": "flutter", + "subcommands": [ + { + "name": "assemble", + "options": [ + { "name": ["-d", "--device-id"] }, + { "name": ["-x", "--extra"] }, + { "name": ["-d", "--define"] } + ] + } + ] +} diff --git a/completion-metadata/tests/fixtures/duplicate_short_flags/valid_distinct_short_flags.json b/completion-metadata/tests/fixtures/duplicate_short_flags/valid_distinct_short_flags.json new file mode 100644 index 00000000..4d06fefb --- /dev/null +++ b/completion-metadata/tests/fixtures/duplicate_short_flags/valid_distinct_short_flags.json @@ -0,0 +1,7 @@ +{ + "name": "tool", + "options": [ + { "name": ["-a", "--alpha"] }, + { "name": ["-b", "--beta"] } + ] +} diff --git a/completion-metadata/tests/fixtures/duplicate_short_flags/valid_long_flags_not_short.json b/completion-metadata/tests/fixtures/duplicate_short_flags/valid_long_flags_not_short.json new file mode 100644 index 00000000..65eb6d51 --- /dev/null +++ b/completion-metadata/tests/fixtures/duplicate_short_flags/valid_long_flags_not_short.json @@ -0,0 +1,9 @@ +{ + "name": "java", + "options": [ + { "name": ["-version"] }, + { "name": ["-version"] }, + { "name": ["--help"] }, + { "name": ["--help"] } + ] +} diff --git a/completion-metadata/tests/fixtures/duplicate_short_flags/valid_root_and_child_reuse.json b/completion-metadata/tests/fixtures/duplicate_short_flags/valid_root_and_child_reuse.json new file mode 100644 index 00000000..6788f70e --- /dev/null +++ b/completion-metadata/tests/fixtures/duplicate_short_flags/valid_root_and_child_reuse.json @@ -0,0 +1,10 @@ +{ + "name": "tool", + "options": [{ "name": ["-v", "--verbose"] }], + "subcommands": [ + { + "name": "child", + "options": [{ "name": ["-v", "--verbose"] }] + } + ] +} diff --git a/completion-metadata/tests/fixtures/duplicate_short_flags/valid_short_and_long_alias.json b/completion-metadata/tests/fixtures/duplicate_short_flags/valid_short_and_long_alias.json new file mode 100644 index 00000000..0aca2f6c --- /dev/null +++ b/completion-metadata/tests/fixtures/duplicate_short_flags/valid_short_and_long_alias.json @@ -0,0 +1,4 @@ +{ + "name": "tool", + "options": [{ "name": ["-v", "--verbose"] }] +} diff --git a/completion-metadata/tests/fixtures/duplicate_short_flags/valid_sibling_subcommands_reuse.json b/completion-metadata/tests/fixtures/duplicate_short_flags/valid_sibling_subcommands_reuse.json new file mode 100644 index 00000000..44fdd1dd --- /dev/null +++ b/completion-metadata/tests/fixtures/duplicate_short_flags/valid_sibling_subcommands_reuse.json @@ -0,0 +1,7 @@ +{ + "name": "tool", + "subcommands": [ + { "name": "one", "options": [{ "name": ["-v", "--verbose"] }] }, + { "name": "two", "options": [{ "name": ["-v", "--verbose"] }] } + ] +} diff --git a/completion-metadata/tests/fixtures/duplicate_short_flags/valid_unrelated_top_level_a.json b/completion-metadata/tests/fixtures/duplicate_short_flags/valid_unrelated_top_level_a.json new file mode 100644 index 00000000..7ca046fe --- /dev/null +++ b/completion-metadata/tests/fixtures/duplicate_short_flags/valid_unrelated_top_level_a.json @@ -0,0 +1,4 @@ +{ + "name": "one", + "options": [{ "name": ["-v", "--verbose"] }] +} diff --git a/completion-metadata/tests/fixtures/duplicate_short_flags/valid_unrelated_top_level_b.json b/completion-metadata/tests/fixtures/duplicate_short_flags/valid_unrelated_top_level_b.json new file mode 100644 index 00000000..63a636a9 --- /dev/null +++ b/completion-metadata/tests/fixtures/duplicate_short_flags/valid_unrelated_top_level_b.json @@ -0,0 +1,4 @@ +{ + "name": "two", + "options": [{ "name": ["-v", "--verbose"] }] +} From 8f257356f9e5a4cf65686b75e7b9b022253744ec Mon Sep 17 00:00:00 2001 From: "warp-factories[bot]" <243557089+warp-factories[bot]@users.noreply.github.com> Date: Fri, 4 Sep 2026 22:41:27 +0000 Subject: [PATCH 4/4] Reuse ShortFlagConflict::describe for baseline diff diagnostics diff_against_baseline previously formatted failures with {:?} on the raw (command_path, claimants) tuples, producing zero-based debug tuples instead of the one-based, source-actionable diagnostic the issue and spec require. Reconstruct a ShortFlagConflict from each record and reuse its describe() formatter for all three failure modes (new conflict, changed claimant identity, stale baseline entry), and pin the exact emitted text with a new regression test. --- command-signatures/src/lib.rs | 105 +++++++++++++++++++++++++++++++--- 1 file changed, 97 insertions(+), 8 deletions(-) diff --git a/command-signatures/src/lib.rs b/command-signatures/src/lib.rs index 0436f294..213b9ffa 100644 --- a/command-signatures/src/lib.rs +++ b/command-signatures/src/lib.rs @@ -270,7 +270,7 @@ mod tests { #[cfg(test)] mod duplicate_short_flags { use crate::fig_types::Command; - use crate::validation::find_short_flag_conflicts; + use crate::validation::{find_short_flag_conflicts, ShortFlagClaimant, ShortFlagConflict}; use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; @@ -646,8 +646,29 @@ mod duplicate_short_flags { actual } + /// Builds the same `ShortFlagConflict` the validator itself produces from a `(key, + /// claimants)` record, so baseline-diff diagnostics go through the shared + /// `ShortFlagConflict::describe` formatter (canonical space-delimited path, quoted flag, raw + /// JSON name arrays, one-based positions) instead of a bespoke, zero-based debug rendering. + fn describe_record(key: &ConflictKey, claimants: &Claimants) -> String { + let (file, command_path, flag) = key; + let conflict = ShortFlagConflict { + command_path: command_path.clone(), + flag: flag.clone(), + claimants: claimants + .iter() + .map(|(index, names)| ShortFlagClaimant { + index: *index, + names: names.clone(), + }) + .collect(), + }; + conflict.describe(file) + } + /// Compares collected conflicts against the baseline as complete records. Returns one - /// human-readable failure message per problem found: + /// human-readable failure message per problem found, each rendered with the shared + /// `ShortFlagConflict::describe` diagnostic format: /// - a collected conflict whose key is absent from the baseline (a new conflict); /// - a collected conflict whose ordered claimant list differs from the baseline's (the /// claimant identity changed even though the key is unchanged); @@ -660,23 +681,25 @@ mod duplicate_short_flags { let mut failures = Vec::new(); for (key, claimants) in actual { - let (file, command_path, flag) = key; match baseline.get(key) { None => failures.push(format!( - "new duplicate short flag conflict not in baseline: {file}: command {command_path:?}: duplicate short flag {flag:?} is used by options {claimants:?}" + "new duplicate short flag conflict not in baseline:\n {}", + describe_record(key, claimants) )), Some(expected_claimants) if expected_claimants != claimants => failures.push(format!( - "claimant identity changed for baselined conflict {file}: command {command_path:?}: duplicate short flag {flag:?}\n expected claimants: {expected_claimants:?}\n actual claimants: {claimants:?}" + "claimant identity changed for baselined conflict:\n expected: {}\n actual: {}", + describe_record(key, expected_claimants), + describe_record(key, claimants) )), _ => {} } } - for key in baseline.keys() { + for (key, expected_claimants) in baseline { if !actual.contains_key(key) { - let (file, command_path, flag) = key; failures.push(format!( - "stale baseline entry, remove it: {file}: command {command_path:?}: duplicate short flag {flag:?}" + "stale baseline entry, remove it:\n {}", + describe_record(key, expected_claimants) )); } } @@ -821,4 +844,70 @@ mod duplicate_short_flags { assert_eq!(failures.len(), 1); assert!(failures[0].contains("stale baseline entry")); } + + /// Pins the exact, one-based, source-actionable diagnostic text (matching + /// `ShortFlagConflict::describe`) for all three failure modes, so a future change cannot + /// silently regress to a bare zero-based debug rendering of the claimant records. + #[test] + fn diff_messages_use_the_shared_one_based_diagnostic_format() { + let key: ConflictKey = ( + "tool.json".to_string(), + vec!["tool".to_string()], + "-t".to_string(), + ); + let expected_text = "tool.json: command \"tool\": duplicate short flag \"-t\" is used by options #1 [\"-t\", \"--type-a\"] and #2 [\"-t\", \"--type-b\"]"; + let changed_text = "tool.json: command \"tool\": duplicate short flag \"-t\" is used by options #1 [\"-t\", \"--type-a\"] and #2 [\"-t\", \"--type-c\"]"; + let baselined_claimants = vec![ + (0, vec!["-t".to_string(), "--type-a".to_string()]), + (1, vec!["-t".to_string(), "--type-b".to_string()]), + ]; + let changed_claimants = vec![ + (0, vec!["-t".to_string(), "--type-a".to_string()]), + (1, vec!["-t".to_string(), "--type-c".to_string()]), + ]; + + // New conflict: not present in the baseline at all. + let mut actual = BTreeMap::new(); + actual.insert(key.clone(), baselined_claimants.clone()); + let failures = diff_against_baseline(&actual, &BTreeMap::new()); + assert_eq!(failures.len(), 1); + assert!( + failures[0].contains(expected_text), + "expected {:?} to contain {:?}", + failures[0], + expected_text + ); + + // Claimant identity changed: both the expected and actual one-based diagnostics appear. + let mut baseline = BTreeMap::new(); + baseline.insert(key.clone(), baselined_claimants.clone()); + let mut actual = BTreeMap::new(); + actual.insert(key.clone(), changed_claimants); + let failures = diff_against_baseline(&actual, &baseline); + assert_eq!(failures.len(), 1); + assert!( + failures[0].contains(expected_text), + "expected {:?} to contain {:?}", + failures[0], + expected_text + ); + assert!( + failures[0].contains(changed_text), + "expected {:?} to contain {:?}", + failures[0], + changed_text + ); + + // Stale baseline entry: no longer produced, but still described with the shared format. + let mut baseline = BTreeMap::new(); + baseline.insert(key, baselined_claimants); + let failures = diff_against_baseline(&BTreeMap::new(), &baseline); + assert_eq!(failures.len(), 1); + assert!( + failures[0].contains(expected_text), + "expected {:?} to contain {:?}", + failures[0], + expected_text + ); + } }