mirror of
https://github.com/kuhyx/signal-bot.git
synced 2026-11-10 21:37:03 +01:00
An unrecognised "!word" was dropped in silence, which made a typo
indistinguishable from the bot being down and threw away the best available
list of commands worth writing. Three things now happen at the one place in
dispatcher.py that used to be a bare `return`.
A near miss is corrected -- "!cta" asks whether you meant "!kot". The
distance is optimal string alignment rather than difflib's ratio: a
transposition is the typo people actually make, it costs one edit here, and
it shreds the matching blocks a ratio counts ("!cta"/"!cat" scores 0.75 but
"!cta"/"!kot" scores 0.50, so no cutoff separates them on principle).
A word with no near miss points at !zaproponuj, which files an idea from
inside the group. Either way the word and the message are recorded, and the
management page grows an Ideas tab that lists them.
Three things stay silent, each for its own reason. "!kot ladny" is a real
trigger with words after it and always has been silent. "!!" is punctuation.
And a command claimed in some *other* group is neither answered nor recorded
-- the album's triggers are real people's names, and pack_scoping.yaml says
it out loud: a refusal would itself announce that the album exists. The
existence check is therefore global, which is what pack_add already asks.
Measured rather than guessed, against the shipped aliases.json:
- a minimum candidate length, because "!ja" is one edit from ~40 of the 676
two-letter words somebody could type; 69 of them got a suggestion before
the rule and 18 after.
- the two-edit budget starts at six characters, not five. At five it put
four pairs of *different* commands within reach of each other --
!pies/!popes, !days/!cats, !dzis/!dni, !mnie/!dni -- and costs nothing to
give up, because every real typo this was written for is one edit away.
test_no_two_commands_are_within_reach_of_each_other fails if a future
alias reopens the gap.
Both new tables are keyed on the envelope's own sent_at_ms, never the wall
clock: signal-cli replays undelivered frames on reconnect, and a clock-keyed
table collects a duplicate row per reconnect instead of ignoring one.
The branch is gated on should_count -- which excludes the bot's own envelope,
and that is the loop guard, since handle() checks is_own nowhere else -- and
wrapped in its own try/except, because it runs above the one that wraps a
handler and Bot.listen has no exception handling of its own.
Suggestions live in SQLite, not in a tracked file, and the export goes to the
state directory. check_personal_data learns the names it refuses from the
live database, so it catches a name somebody has typed and cannot catch a
misspelling of one -- and an unrecognised-command corpus is made of
misspellings. A group-writable file in a public tree is both a leak and a
wedge. The export therefore carries
deliberate !zaproponuj notes in full and unrecognised words as counts only;
bodies stay on the loopback-only page.
Verified on the live bot: restarted, both tables created with every existing
row count unchanged, !cta and !zaproponuj !pogoda delivered through
/_selftest, both rows read back out of the live database, and the journal
names neither the word nor the body.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01416TegJ3sa8xL5qGGgrygP
136 lines
4.6 KiB
Python
136 lines
4.6 KiB
Python
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
|
|
"""Edit distance, and the two rules that keep it from suggesting nonsense."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
import pytest
|
|
|
|
from signal_bot.animals import ALIAS_FILE
|
|
from signal_bot.folding import fold
|
|
from signal_bot.nearest import LONG_BUDGET, MIN_CANDIDATE, SHORT_BUDGET, budget, distance, nearest
|
|
|
|
|
|
def live_triggers() -> dict[str, str]:
|
|
"""Every folded trigger the shipped aliases.json defines, to its command."""
|
|
document = json.loads(ALIAS_FILE.read_text(encoding="utf-8"))
|
|
return {
|
|
fold(trigger): name
|
|
for name, triggers in document.items()
|
|
if not name.startswith("_")
|
|
for trigger in triggers
|
|
}
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("one", "other", "expected"),
|
|
[
|
|
("", "", 0),
|
|
("", "abc", 3),
|
|
("abc", "", 3),
|
|
("abc", "abc", 0),
|
|
("abc", "abd", 1),
|
|
("abc", "ab", 1),
|
|
("ab", "abc", 1),
|
|
# The whole reason this is not difflib: a swap is one edit.
|
|
("!cta", "!cat", 1),
|
|
("!ab", "!ba", 1),
|
|
# Adjacent only. "abc" -> "cba" is not one transposition.
|
|
("abc", "cba", 2),
|
|
],
|
|
)
|
|
def test_distance(one: str, other: str, expected: int) -> None:
|
|
"""Insertion, deletion, substitution and the adjacent swap."""
|
|
assert distance(one, other) == expected
|
|
|
|
|
|
def test_distance_is_symmetric() -> None:
|
|
"""Nothing downstream relies on argument order, so nothing may depend on it."""
|
|
assert distance("!gekno", "!gekon") == distance("!gekon", "!gekno")
|
|
|
|
|
|
def test_the_transposition_arm_is_not_taken_in_the_first_column() -> None:
|
|
"""The guard on both indices, reached with a one-character word.
|
|
|
|
The arm looks two cells back in each direction; without the guard this
|
|
is an IndexError rather than a distance.
|
|
"""
|
|
assert distance("a", "ba") == 1
|
|
|
|
|
|
def test_budget_is_tighter_for_short_words() -> None:
|
|
"""A three-letter word has no room to be wrong twice."""
|
|
assert budget(5) == SHORT_BUDGET
|
|
assert budget(6) == LONG_BUDGET
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("typed", "expected"),
|
|
[
|
|
("!cta", "cat"),
|
|
("!kto", "cat"),
|
|
("!gekno", "gecko"),
|
|
("!papiesz", "pope"),
|
|
("!stat", "stats_today"),
|
|
("!rok2", "stats_year"),
|
|
("!korna", "stats_crown"),
|
|
],
|
|
)
|
|
def test_real_typos_of_real_commands_resolve(typed: str, expected: str) -> None:
|
|
"""Computed against the shipped alias table, not against a synthetic one."""
|
|
hit = nearest(fold(typed), live_triggers())
|
|
assert hit is not None
|
|
assert live_triggers()[hit] == expected
|
|
|
|
|
|
@pytest.mark.parametrize("typed", ["!xyz", "!zzzzzz", "!nosuchcommand"])
|
|
def test_a_word_meaning_nothing_suggests_nothing(typed: str) -> None:
|
|
"""Past the budget is silence, not a confident wrong answer."""
|
|
assert nearest(fold(typed), live_triggers()) is None
|
|
|
|
|
|
def test_nothing_registered_suggests_nothing() -> None:
|
|
"""The empty registry, which is what a bot with no commands has."""
|
|
assert nearest("!cta", []) is None
|
|
|
|
|
|
def test_exactly_at_the_budget_is_offered_and_one_past_it_is_not() -> None:
|
|
"""The boundary, pinned from both sides."""
|
|
assert nearest("!aaab", ["!aaaa"]) == "!aaaa"
|
|
assert nearest("!aabb", ["!aaaa"]) is None
|
|
# Six characters buys the second edit, and only the second.
|
|
assert nearest("!aaaabb", ["!aaaaaa"]) == "!aaaaaa"
|
|
assert nearest("!aaabbb", ["!aaaaaa"]) is None
|
|
|
|
|
|
def test_a_candidate_shorter_than_the_minimum_is_never_offered() -> None:
|
|
"""The !ja magnet.
|
|
|
|
"!ja" is one edit from roughly forty two-letter words. Without this rule
|
|
the bot answers "chodziło o !ja?" to !ba, !ca, !da and so on.
|
|
"""
|
|
assert len("!ja") < MIN_CANDIDATE
|
|
assert nearest("!ba", ["!ja"]) is None
|
|
assert nearest("!jo", live_triggers()) is None
|
|
|
|
|
|
def test_ties_break_on_length_then_alphabetically() -> None:
|
|
"""Otherwise the answer depends on registry iteration order."""
|
|
assert nearest("!aaaa", ["!aaaaa", "!aaab"]) == "!aaab"
|
|
assert nearest("!aaaa", ["!baaa", "!aaab"]) == "!aaab"
|
|
|
|
|
|
def test_no_two_commands_are_within_reach_of_each_other() -> None:
|
|
"""No alias of one command may be a near miss for a different command.
|
|
|
|
If two ever collide the suggestion becomes a coin toss, and the tie-break
|
|
that decides it is alphabetical -- i.e. meaningless to the person who
|
|
mistyped. This fails when a newly added alias creates that ambiguity.
|
|
"""
|
|
triggers = live_triggers()
|
|
for typed, owner in triggers.items():
|
|
hit = nearest(typed, {t: n for t, n in triggers.items() if t != typed})
|
|
if hit is not None:
|
|
assert triggers[hit] == owner, f"{typed} ({owner}) is a near miss for {hit}"
|