Skip to content

Commit 985ce44

Browse files
committed
cli: Say why no correction is shown
Recovery entry, `create --existing` and `correct` now name what happened when no correction is offered: the search found none, the search ran out of time, or several corrections are possible. Each ends with the same advice to check the backup and re-enter it carefully. None of them says how to edit the entry. One private helper in correction.py writes the message, so a GUI can use the same wording. NO_CORRECTION and the three separate `correct` messages are gone. `_suggestions` now also returns whether the search completed. Claude-Session: https://claude.ai/code/session_01Q1TNm1YeYW8K9W2eBvxmCD
1 parent c02d747 commit 985ce44

5 files changed

Lines changed: 85 additions & 54 deletions

File tree

‎src/codex32/_cli_input.py‎

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,13 @@
2222
parse_codex32,
2323
recover_secret,
2424
)
25-
from codex32.correction import CorrectionCandidate, CorrectionContext, _best, _capture_mass
25+
from codex32.correction import (
26+
CorrectionCandidate,
27+
CorrectionContext,
28+
_best,
29+
_capture_mass,
30+
_no_correction_message,
31+
)
2632
from codex32.errors import (
2733
CodexError,
2834
DuplicateShareIndex,
@@ -47,9 +53,6 @@
4753
_line_editor = None
4854

4955

50-
NO_CORRECTION = "No unique correction found. Check your backup and re-enter it carefully."
51-
52-
5356
class InputError(Exception):
5457
pass
5558

@@ -545,21 +548,21 @@ def _suggestions(
545548
*,
546549
allowed: Callable[[CorrectionCandidate], bool] | None = None,
547550
fingerprint: Callable[[MasterSeed], bytes] | None = None,
548-
) -> tuple[CorrectionCandidate, ...]:
551+
) -> tuple[tuple[CorrectionCandidate, ...], bool]:
549552
fingerprint_match = _fingerprint_matcher(fingerprint)
550553
erased = value
551554
if interpretation := _case_interpretation(value, prefix, profiles, allowed):
552555
candidate, value, erased, prefix = interpretation
553556
if candidate is not None:
554-
return (candidate,)
557+
return (candidate,), True
555558
separator = value.lower().rfind("1")
556559
if separator <= 0:
557-
return ()
560+
return (), True
558561
hrp = value[:separator].lower()
559562
rules = _optional_profile_rules(hrp)
560563
profile = rules.profile if rules is not None else None
561564
if profiles is not None and profile not in profiles:
562-
return ()
565+
return (), True
563566
excluded = tuple(artifact.header.index for artifact in accepted)
564567
target = len(accepted[0].text) if accepted else None
565568
immutable = (
@@ -578,7 +581,7 @@ def _suggestions(
578581
allowed=allowed,
579582
deadline=monotonic() + 10,
580583
fingerprint_match=fingerprint_match,
581-
)[0]
584+
)
582585

583586

584587
def _validate_operational_artifact(
@@ -631,7 +634,7 @@ def allowed(candidate: CorrectionCandidate) -> bool:
631634
return False
632635
return True
633636

634-
candidates = _suggestions(
637+
candidates, complete = _suggestions(
635638
token,
636639
"",
637640
profiles,
@@ -641,7 +644,7 @@ def allowed(candidate: CorrectionCandidate) -> bool:
641644
)
642645
if len(candidates) != 1:
643646
if isinstance(error.__cause__, CodexError):
644-
raise InputError(NO_CORRECTION) from error
647+
raise InputError(_no_correction_message(candidates, complete)) from error
645648
raise
646649
if not _confirm_correction(candidates[0], accepted, basis, fingerprint):
647650
raise CorrectionDeclined
@@ -699,8 +702,8 @@ def allowed(candidate: CorrectionCandidate) -> bool:
699702
try:
700703
artifact = _parse(complete_value, profiles)
701704
except InputError as error:
702-
candidates = (
703-
()
705+
candidates, complete = (
706+
((), True)
704707
if one
705708
else _suggestions(
706709
complete_value,
@@ -724,7 +727,11 @@ def allowed(candidate: CorrectionCandidate) -> bool:
724727
if confirmation is True:
725728
artifact = candidates[0].artifact
726729
else:
727-
message = NO_CORRECTION if not one and isinstance(error.__cause__, CodexError) else str(error)
730+
message = (
731+
_no_correction_message(candidates, complete)
732+
if not one and isinstance(error.__cause__, CodexError)
733+
else str(error)
734+
)
728735
_stderr(f"Rejected: {message}\n")
729736
prefill = _retry_text(entered, prefix)
730737
prefix = _prefix_for_suffix(prefix, prefill)

‎src/codex32/cli.py‎

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
from codex32.correction import (
4848
CorrectionCandidate,
4949
_best,
50+
_no_correction_message,
5051
_residue_low_discrimination,
5152
correct_worksheet_residue,
5253
)
@@ -261,7 +262,7 @@ def _creation_source(
261262
except CodexError as error:
262263
if not sys.stdin.isatty():
263264
raise _UsageError(str(error)) from error
264-
candidates = _suggestions(
265+
candidates, complete = _suggestions(
265266
value,
266267
"",
267268
(profile,),
@@ -281,10 +282,7 @@ def _creation_source(
281282
_print("", err=True)
282283
prefill = value
283284
continue
284-
_print(
285-
"Rejected: No unique correction found. Check your codex32 backup and re-enter it carefully.",
286-
err=True,
287-
)
285+
_print(f"Rejected: {_no_correction_message(candidates, complete)}", err=True)
288286

289287

290288
def _confirm_card(artifact: Artifact, confirm: Callable[[str], ConfirmationResult] | None = None) -> None:
@@ -637,14 +635,10 @@ def _correct(
637635
complete = True
638636
else:
639637
candidates, complete = _scheduled_candidates(search_value, erased, hrp, byte_length, immutable)
640-
if not complete and not candidates:
641-
raise _CommandError("The correction search did not complete within ten seconds.")
642-
if not candidates:
643-
raise _CommandError("No valid correction found. Check the original backup.")
644638
if core is not None and len(candidates) > 1:
645639
candidates = _best(candidates, fingerprint_match=_fingerprint_matcher(core.fingerprint))
646640
if len(candidates) != 1:
647-
raise _CommandError("Several corrections are possible. Check the original backup.")
641+
raise _CommandError(_no_correction_message(candidates, complete))
648642
fixed = candidates[0]
649643
_require_correction_confirmation(fixed.low_checksum_discrimination)
650644
warning = (

‎src/codex32/correction.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,17 @@ def _low_discrimination(volume: int, bits: int) -> bool:
111111
return 32 * volume > 1 << bits
112112

113113

114+
def _no_correction_message(candidates: Sequence[CorrectionCandidate], complete: bool) -> str:
115+
"""Say why no correction is shown, never how to edit the entry."""
116+
if len(candidates) > 1:
117+
reason = "Several corrections are possible."
118+
elif not complete:
119+
reason = "The correction search ran out of time."
120+
else:
121+
reason = "No correction was found."
122+
return f"{reason} Check your backup and re-enter it carefully."
123+
124+
114125
def _capture_mass(layers: Sequence[tuple[int, int]], rank: int) -> tuple[int, int]:
115126
"""Normalize all admitted equal-or-better classes, including unsearched work."""
116127
included = tuple((volume, bits) for volume, bits in layers if volume <= rank)

‎tests/test_cli.py‎

Lines changed: 45 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -620,7 +620,7 @@ def test_embedded_correction_schedules_both_mixed_case_interpretations_before_al
620620
source = "ms10testsxxxxxxxxxxxxxxxxxxxxxxxxxx4nzvca9cmczlw"
621621
damaged = "ms10testsxPxxxxxPxxxxxPxxxxxPxxxxxP4nzvca9cmczlw"
622622

623-
candidates = input_module._suggestions(damaged, "", (Profile.MS,), [])
623+
candidates, _complete = input_module._suggestions(damaged, "", (Profile.MS,), [])
624624

625625
assert len(candidates) == 1
626626
assert candidates[0].artifact.text == source
@@ -660,9 +660,7 @@ def test_xprv_rejects_unreadable_entries_without_edit_hints(monkeypatch, capsys)
660660
assert ms_main(["xprv"]) == 0
661661
rejected = [line for line in capsys.readouterr().err.splitlines() if line.startswith("Rejected:")]
662662
# A hint about what is wrong invites a guess, and a wrong guess can make a wrong correction findable.
663-
assert (
664-
rejected == ["Rejected: No unique correction found. Check your backup and re-enter it carefully."] * 2
665-
)
663+
assert rejected == ["Rejected: No correction was found. Check your backup and re-enter it carefully."] * 2
666664

667665

668666
def test_xprv_rejects_every_uncorrectable_prefixed_ms_length(monkeypatch, capsys) -> None:
@@ -678,7 +676,7 @@ def test_xprv_rejects_every_uncorrectable_prefixed_ms_length(monkeypatch, capsys
678676
assert ms_main(["xprv"]) == 0
679677
output = capsys.readouterr().err
680678
assert output.count(
681-
"Rejected: No unique correction found. Check your backup and re-enter it carefully."
679+
"Rejected: No correction was found. Check your backup and re-enter it carefully."
682680
) == len(lengths)
683681
assert "characters" not in output
684682

@@ -692,7 +690,7 @@ def test_prefixed_ms_lengths_at_correction_boundary_still_search(monkeypatch, ca
692690

693691
def suggestions(value, *_args, **_kwargs):
694692
searched.append(value)
695-
return ()
693+
return (), True
696694

697695
monkeypatch.setattr(input_module.sys, "stdin", _TTYInput())
698696
monkeypatch.setattr(input_module, "_line_editor", None)
@@ -703,7 +701,7 @@ def suggestions(value, *_args, **_kwargs):
703701
output = capsys.readouterr().err
704702
assert [len(value) for value in searched] == list(lengths)
705703
assert output.count(
706-
"Rejected: No unique correction found. Check your backup and re-enter it carefully."
704+
"Rejected: No correction was found. Check your backup and re-enter it carefully."
707705
) == len(lengths)
708706

709707

@@ -714,35 +712,55 @@ def test_complete_paste_with_bad_threshold_gets_no_hint(monkeypatch, capsys) ->
714712
monkeypatch.setattr(input_module.sys, "stdin", _TTYInput())
715713
monkeypatch.setattr(input_module, "_line_editor", None)
716714
monkeypatch.setattr(input_module, "_editable_input", lambda _prompt, _prefill="": next(answers))
717-
monkeypatch.setattr(input_module, "_suggestions", lambda *_args, **_kwargs: ())
715+
monkeypatch.setattr(input_module, "_suggestions", lambda *_args, **_kwargs: ((), True))
718716

719717
assert ms_main(["xprv"]) == 0
720718
output = capsys.readouterr().err
721-
assert "Rejected: No unique correction found. Check your backup and re-enter it carefully." in output
719+
assert "Rejected: No correction was found. Check your backup and re-enter it carefully." in output
722720
assert "threshold" not in output
723721

724722

725723
def test_redirected_uncorrectable_input_gets_no_hint(monkeypatch) -> None:
726724
input_module = importlib.import_module("codex32._cli_input")
727-
monkeypatch.setattr(input_module, "_suggestions", lambda *_args, **_kwargs: ())
725+
monkeypatch.setattr(input_module, "_suggestions", lambda *_args, **_kwargs: ((), True))
728726

729727
result = _invoke(["secret"], VECTOR_1["secret_s"][:-1] + "b")
730728

731729
assert result.exit_code != 0
732-
assert "No unique correction found. Check your backup and re-enter it carefully." in result.stderr
730+
assert "No correction was found. Check your backup and re-enter it carefully." in result.stderr
733731
assert "character" not in result.stderr
734732

735733

734+
@pytest.mark.parametrize(
735+
("result", "reason"),
736+
(
737+
(((), True), "No correction was found."),
738+
(((), False), "The correction search ran out of time."),
739+
(((object(), object()), True), "Several corrections are possible."),
740+
),
741+
)
742+
def test_redirected_rejection_says_why_no_correction_is_shown(monkeypatch, result, reason) -> None:
743+
input_module = importlib.import_module("codex32._cli_input")
744+
monkeypatch.setattr(input_module, "_suggestions", lambda *_args, **_kwargs: result)
745+
746+
rejected = _invoke(["secret"], VECTOR_1["secret_s"][:-1] + "b")
747+
748+
assert rejected.exit_code != 0
749+
# Say what happened, never how to edit the entry.
750+
assert f"{reason} Check your backup and re-enter it carefully." in rejected.stderr
751+
assert "character" not in rejected.stderr
752+
753+
736754
def test_existing_seed_without_unique_correction_gets_no_hint(monkeypatch, capsys) -> None:
737755
cli_module = importlib.import_module("codex32.cli")
738756
answers = iter((VECTOR_1["secret_s"][:-1] + "b", "00" * 16))
739757
monkeypatch.setattr(cli_module.sys, "stdin", _TTYInput())
740758
monkeypatch.setattr(cli_module, "_text", lambda *_args, **_kwargs: next(answers))
741-
monkeypatch.setattr(cli_module, "_suggestions", lambda *_args, **_kwargs: ())
759+
monkeypatch.setattr(cli_module, "_suggestions", lambda *_args, **_kwargs: ((), True))
742760

743761
assert cli_module._creation_source(Profile.MS) == bytes(16)
744762
assert capsys.readouterr().err == (
745-
"Rejected: No unique correction found. Check your codex32 backup and re-enter it carefully.\n"
763+
"Rejected: No correction was found. Check your backup and re-enter it carefully.\n"
746764
)
747765

748766

@@ -768,7 +786,7 @@ def answer(*_args, **kwargs):
768786
assert seen_prefills == ["", ""]
769787
output = capsys.readouterr().err
770788
assert "Hexadecimal seeds must contain 16, 20, 24, 28, 32, or 64 bytes" in output
771-
assert "No unique correction" not in output
789+
assert "correction" not in output
772790

773791

774792
@pytest.mark.parametrize(("difference", "word"), ((-9, "short of"), (9, "too long for")))
@@ -788,7 +806,7 @@ def test_subsequent_prefixed_ms_input_with_wrong_length_gets_no_hint(
788806
assert main(["secret", "--plain"]) == 0
789807
output = capsys.readouterr()
790808
assert output.out.strip() == VECTOR_2["secret_S"]
791-
assert "Rejected: No unique correction found. Check your backup and re-enter it carefully." in output.err
809+
assert "Rejected: No correction was found. Check your backup and re-enter it carefully." in output.err
792810
assert word not in output.err
793811

794812

@@ -1847,7 +1865,7 @@ def test_cli_rejects_statistically_inadmissible_structural_burst() -> None:
18471865
result = _invoke(["correct"], damaged)
18481866

18491867
assert result.exit_code == 3
1850-
assert "No valid correction found" in result.stderr
1868+
assert "No correction was found" in result.stderr
18511869

18521870

18531871
def test_cli_rejects_sixteen_consecutive_erasures_as_outside_regular_bound() -> None:
@@ -1858,7 +1876,7 @@ def test_cli_rejects_sixteen_consecutive_erasures_as_outside_regular_bound() ->
18581876
assert len("".join(damaged.split())) == 48
18591877
assert damaged.count("?") == 16
18601878
assert result.exit_code == 3
1861-
assert "No valid correction found" in result.stderr
1879+
assert "No correction was found" in result.stderr
18621880

18631881

18641882
def test_correct_rejects_malformed_immutable_hrp_as_usage() -> None:
@@ -1910,7 +1928,7 @@ def test_cli_never_accepts_an_incomplete_structural_search() -> None:
19101928

19111929
assert result.exit_code == 3
19121930
assert result.stdout == ""
1913-
assert "did not complete" in result.stderr and original not in result.stderr
1931+
assert "ran out of time" in result.stderr and original not in result.stderr
19141932

19151933

19161934
@pytest.mark.parametrize(
@@ -1997,7 +2015,7 @@ def test_correct_suggests_the_majority_case_for_mixed_case_damage() -> None:
19972015

19982016
assert result.exit_code == 1
19992017
assert source in result.stderr
2000-
assert "No valid correction found" not in result.stderr
2018+
assert "No correction was found" not in result.stderr
20012019
assert wrong_length.exit_code == 2
20022020
assert "--bytes does not match" in wrong_length.stderr
20032021
assert source not in wrong_length.stderr
@@ -2069,7 +2087,7 @@ def test_correct_required_work_is_not_starved_by_erasure_alignment() -> None:
20692087

20702088
assert result.exit_code == 1
20712089
assert source in result.stderr
2072-
assert "did not complete within ten seconds" not in result.stderr
2090+
assert "ran out of time" not in result.stderr
20732091
assert "interactive confirmation required" not in result.stderr
20742092

20752093

@@ -2118,8 +2136,8 @@ def test_correction_hides_internal_candidate_reparse_failures() -> None:
21182136
assert result.exit_code == 3
21192137
assert result.stdout == ""
21202138
assert result.stderr.strip() in {
2121-
"codex32 correct: No valid correction found. Check the original backup.",
2122-
"codex32 correct: The correction search did not complete within ten seconds.",
2139+
"codex32 correct: No correction was found. Check your backup and re-enter it carefully.",
2140+
"codex32 correct: The correction search ran out of time. Check your backup and re-enter it carefully.",
21232141
}
21242142
assert "threshold" not in result.stderr
21252143

@@ -2876,7 +2894,7 @@ def test_creation_source_unusable_candidates_retry(monkeypatch, capsys, kind):
28762894
artifact = parse_codex32(VECTOR_6["codex32_peev"])
28772895
candidate = SimpleNamespace(artifact=artifact, search_complete=True, low_checksum_discrimination=False)
28782896
candidates = () if kind == "none" else (candidate, candidate) if kind == "ambiguous" else (candidate,)
2879-
monkeypatch.setattr(cli, "_suggestions", lambda *args, **kwargs: candidates)
2897+
monkeypatch.setattr(cli, "_suggestions", lambda *args, **kwargs: (candidates, True))
28802898
answers = iter(("ms1invalid", "00" * 16))
28812899
monkeypatch.setattr(sys, "stdin", _TTYInput())
28822900
monkeypatch.setattr(module, "_editable_input", lambda *args: next(answers))
@@ -2903,7 +2921,7 @@ def test_creation_source_does_not_label_an_incomplete_share_candidate(monkeypatc
29032921

29042922
def suggestions(*args, **kwargs):
29052923
assert not kwargs["allowed"](candidate)
2906-
return (candidate,)
2924+
return (candidate,), True
29072925

29082926
monkeypatch.setattr(sys, "stdin", _TTYInput())
29092927
monkeypatch.setattr(module, "_editable_input", lambda *args: next(answers))
@@ -2930,7 +2948,7 @@ def answer(*args):
29302948

29312949
monkeypatch.setattr(sys, "stdin", _TTYInput())
29322950
monkeypatch.setattr(module, "_editable_input", answer)
2933-
monkeypatch.setattr(cli, "_suggestions", lambda *args, **kwargs: ())
2951+
monkeypatch.setattr(cli, "_suggestions", lambda *args, **kwargs: ((), True))
29342952
with pytest.raises(exception):
29352953
cli._creation_source(Profile.MS)
29362954

@@ -2981,7 +2999,8 @@ def test_corrected_creation_source_identity_and_acceptance_boundary(monkeypatch)
29812999
cli,
29823000
"_suggestions",
29833001
lambda *args, **kwargs: (
2984-
SimpleNamespace(artifact=secret, search_complete=True, low_checksum_discrimination=False),
3002+
(SimpleNamespace(artifact=secret, search_complete=True, low_checksum_discrimination=False),),
3003+
True,
29853004
),
29863005
)
29873006
answers = iter(("ms1invalid", "n", "ms1invalid", "yes", "", secret.text))

0 commit comments

Comments
 (0)