Skip to content

Commit c8c105c

Browse files
fix(retrieval): council F1/F2 -- fallback never re-enters explicit mode; operators count only outside quotes
The Stage 2 single-seat review found two planner defects, both confirmed at runtime before fixing. F1: after FTS5 rejected an explicit query, the fallback re-planned through plan_query(), which could classify the remainder as explicit again -- `fts:fts:alpha?` stripped one prefix, FTS5 rejected `fts:alpha?`, the fallback planned `alpha?` as explicit and ran it unguarded: syntax error. The fallback now calls plan_natural_language() only and strips every prefix, so the second pass cannot fail to parse by construction. F2: an uppercase operator inside a double-quoted span made the whole query explicit, so `"error OR warning" recovery` ran as FTS5 (a phrase ANDed with a word) and never widened to OR when empty. Operators now count only outside quoted spans; inside quotes they are part of the phrase. Regression tests through both surfaces (MCP planner tests, CLI tests) and a pure-planner classification module. scripts/eval/stage2_council_evidence.py answers the review's evidence findings with artefacts: the full-population census transition table with per-question rows and the mechanism read from the frozen escape function, the gold verification counters (91/91 ordered lists counted, 5 of 42 crashers rescued, nothing moved outside the crash class), and the golden projected-equality check between named commits.
1 parent 0bb6ac4 commit c8c105c

5 files changed

Lines changed: 337 additions & 27 deletions

File tree

‎packages/agent-session-tools/src/agent_session_tools/retrieval.py‎

Lines changed: 39 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -139,23 +139,24 @@ def _phrase_terms(text: str) -> tuple[tuple[str, ...], str]:
139139
return tuple(phrases), remainder
140140

141141

142-
def plan_query(query: str) -> QueryPlan:
143-
"""Turn what the caller typed into FTS5 ``MATCH`` strings that cannot fail to parse.
142+
def _has_operator_outside_quotes(text: str) -> bool:
143+
"""True when an uppercase FTS5 operator appears outside every double-quoted span.
144144
145-
Natural language becomes quoted content terms, tried as an AND query and
146-
widened to OR when the AND form finds nothing (today's shipped behaviour,
147-
pinned by the planner golden). Double-quoted spans are kept as phrases so
148-
adjacency survives planning. Only an uppercase operator or the ``fts:``
149-
prefix makes the query explicit FTS5, passed through verbatim.
145+
``"error OR warning" recovery`` is a phrase plus a word, not an explicit
146+
query: an operator inside quotes is part of the phrase.
150147
"""
151-
stripped = query.strip()
152-
if stripped.lower().startswith(FTS_PREFIX):
153-
body = stripped[len(FTS_PREFIX) :].strip()
154-
return QueryPlan(explicit=True, terms=(), queries=(body,) if body else ())
155-
if _EXPLICIT_OPERATOR.search(stripped):
156-
return QueryPlan(explicit=True, terms=(), queries=(stripped,))
148+
return bool(_EXPLICIT_OPERATOR.search(_PHRASE.sub(" ", text)))
149+
150+
151+
def plan_natural_language(query: str) -> QueryPlan:
152+
"""Plan ``query`` as natural language, never as explicit FTS5.
157153
158-
phrases, remainder = _phrase_terms(stripped)
154+
Double-quoted spans are kept as phrases so adjacency survives planning;
155+
the remaining words become quoted content terms, tried as an AND query and
156+
widened to OR when the AND form finds nothing (today's shipped behaviour,
157+
pinned by the planner golden). Nothing this returns can fail to parse.
158+
"""
159+
phrases, remainder = _phrase_terms(query.strip())
159160
words = _terms(remainder)
160161
terms = (*phrases, *words)
161162
if not terms:
@@ -177,6 +178,22 @@ def plan_query(query: str) -> QueryPlan:
177178
return QueryPlan(explicit=False, terms=terms, queries=queries)
178179

179180

181+
def plan_query(query: str) -> QueryPlan:
182+
"""Turn what the caller typed into FTS5 ``MATCH`` strings that cannot fail to parse.
183+
184+
Only the ``fts:`` prefix or an uppercase operator *outside* double quotes
185+
makes the query explicit FTS5, passed through verbatim; everything else
186+
goes to :func:`plan_natural_language`.
187+
"""
188+
stripped = query.strip()
189+
if stripped.lower().startswith(FTS_PREFIX):
190+
body = stripped[len(FTS_PREFIX) :].strip()
191+
return QueryPlan(explicit=True, terms=(), queries=(body,) if body else ())
192+
if _has_operator_outside_quotes(stripped):
193+
return QueryPlan(explicit=True, terms=(), queries=(stripped,))
194+
return plan_natural_language(stripped)
195+
196+
180197
def _search_sql(
181198
conn: sqlite3.Connection,
182199
*,
@@ -347,13 +364,13 @@ def search(
347364
f"explicit FTS5 syntax was rejected ({exc}); "
348365
"the query was searched as natural language instead"
349366
)
350-
stripped = query.strip()
351-
body = (
352-
stripped[len(FTS_PREFIX) :]
353-
if stripped.lower().startswith(FTS_PREFIX)
354-
else stripped
355-
)
356-
query_plan = plan_query(_defuse_operators(body))
367+
# Re-plan as natural language only -- never re-enter explicit
368+
# detection, or ``fts:fts:x?`` and a second uppercase operator
369+
# would run unguarded and crash. Every prefix is stripped.
370+
body = query.strip()
371+
while body.lower().startswith(FTS_PREFIX):
372+
body = body[len(FTS_PREFIX) :].strip()
373+
query_plan = plan_natural_language(body)
357374
else:
358375
return RetrievalResult(
359376
hits=_hits(rows),
@@ -393,9 +410,4 @@ def search(
393410
note=note,
394411
),
395412
)
396-
raise AssertionError("unreachable: plan_query returned queries but none ran")
397-
398-
399-
def _defuse_operators(text: str) -> str:
400-
"""Lower-case the uppercase operators so a rejected explicit query plans as words."""
401-
return _EXPLICIT_OPERATOR.sub(lambda m: m.group(0).lower(), text)
413+
raise AssertionError("unreachable: the planner returned queries but none ran")

‎packages/agent-session-tools/tests/test_query_logic.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -959,3 +959,26 @@ def test_token_count_appended(self):
959959
messages = [{"role": "user", "content": "task", "seq": 0}]
960960
result = _generate_summary_context(session, messages, max_tokens=10000)
961961
assert "tokens" in result.lower()
962+
963+
964+
class TestCouncilStage2Regressions:
965+
"""The two planner defects the Stage 2 seat found, through the CLI surface."""
966+
967+
def test_nested_fts_prefix_and_broken_syntax_never_crash_the_cli(
968+
self, populated_db, capsys
969+
):
970+
for query in ("fts:fts:pytest?", 'fts:"pytest" OR ? AND'):
971+
search(populated_db, query, output_format="json")
972+
payload = json.loads(capsys.readouterr().out)
973+
status = payload["retrieval_status"]
974+
assert status["plan"] in {"and", "or"}, (query, status)
975+
assert "rejected" in status["note"]
976+
assert payload["rows"], query
977+
978+
def test_an_operator_inside_quotes_is_planned_not_explicit(
979+
self, populated_db, capsys
980+
):
981+
search(populated_db, '"unit OR tests" pytest', output_format="json")
982+
status = json.loads(capsys.readouterr().out)["retrieval_status"]
983+
assert status["plan"] in {"and", "or"}
984+
assert status["queries"][0] == '"unit OR tests" AND "pytest"'
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
"""Pure planner classification: what is explicit FTS5 and what is a sentence.
2+
3+
These pin the two rules the Stage 2 council review sharpened -- operators count
4+
only outside double-quoted spans, and the fallback after a rejected explicit
5+
query can never itself be explicit.
6+
"""
7+
8+
from __future__ import annotations
9+
10+
import pytest
11+
12+
from agent_session_tools.retrieval import plan_natural_language, plan_query
13+
14+
15+
@pytest.mark.parametrize(
16+
"query",
17+
[
18+
"error OR authentication",
19+
'error NOT "exact phrase"',
20+
"fts:anything at all?",
21+
'"exact phrase" OR authentication',
22+
"alpha NEAR bravo",
23+
],
24+
)
25+
def test_uppercase_operators_outside_quotes_and_the_prefix_are_explicit(query):
26+
assert plan_query(query).explicit is True
27+
28+
29+
@pytest.mark.parametrize(
30+
"query",
31+
[
32+
"how do I read and write files, or not?",
33+
'"error OR warning" recovery',
34+
'docker "NOT found" and cache',
35+
"ORDER and ANDROID are words",
36+
"and or not",
37+
],
38+
)
39+
def test_lowercase_or_quoted_operators_are_words(query):
40+
plan = plan_query(query)
41+
assert plan.explicit is False
42+
for match in plan.queries:
43+
# Every planned MATCH string is a conjunction/disjunction of quoted terms.
44+
assert all(
45+
part.startswith('"') and part.endswith('"') for part in match.split(" AND ")
46+
)
47+
48+
49+
def test_natural_language_planning_never_returns_an_explicit_plan():
50+
for query in ("fts:fts:alpha?", "alpha OR ?", 'NOT "x" AND', "fts:"):
51+
plan = plan_natural_language(query)
52+
assert plan.explicit is False
53+
assert all(
54+
part.startswith('"')
55+
for match in plan.queries
56+
for part in match.split(" OR ")
57+
)
58+
59+
60+
def test_a_phrase_with_an_inner_operator_survives_as_one_term():
61+
plan = plan_query('"error OR warning" recovery')
62+
assert plan.terms == ('"error OR warning"', "recovery")
63+
assert plan.queries == (
64+
'"error OR warning" AND "recovery"',
65+
'"error OR warning" OR "recovery"',
66+
)

‎packages/agent-session-tools/tests/test_session_search_planner.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,3 +359,41 @@ def test_session_search_safely_plans_adversarial_plain_text_punctuation(
359359
assert [row["preview"] for row in first["rows"]] == expected
360360
assert first == second
361361
assert first["retrieval_status"]["plan"] == "or"
362+
363+
364+
def test_session_search_survives_nested_fts_prefixes_and_a_twice_broken_query(
365+
planner_search,
366+
) -> None:
367+
"""Council Stage 2 F1: the fallback after a rejected explicit query must plan
368+
as natural language only. Re-entering explicit detection ran ``alpha?``
369+
unguarded and crashed the tool."""
370+
for query in ("fts:fts:alpha?", 'fts:"alpha" OR ? AND', "fts: fts: alpha ?"):
371+
payload = planner_search(query=query)
372+
status = payload["retrieval_status"]
373+
assert status["plan"] in {"and", "or"}, (query, status)
374+
assert "rejected" in (status["note"] or ""), (query, status)
375+
assert [row["session_id"] for row in payload["rows"]] == ["sess-auth-001"]
376+
377+
378+
def test_session_search_keeps_an_operator_inside_quotes_as_part_of_the_phrase(
379+
planner_search,
380+
) -> None:
381+
"""Council Stage 2 F2: ``"error OR warning" recovery`` is a phrase plus a
382+
word, so it plans (and widens) like any sentence; uppercase and lowercase
383+
inside the quotes must behave identically. The fixture has no message
384+
containing both, so only the OR widening can reach ``error diagnostic``."""
385+
upper = planner_search(query='"error OR warning" recovery')
386+
lower = planner_search(query='"error or warning" recovery')
387+
assert (
388+
upper["retrieval_status"]["plan"] == lower["retrieval_status"]["plan"] == "or"
389+
)
390+
assert upper["retrieval_status"]["queries"] == [
391+
'"error OR warning" AND "recovery"',
392+
'"error OR warning" OR "recovery"',
393+
]
394+
assert upper["rows"] == lower["rows"] or [
395+
r["session_id"] for r in upper["rows"]
396+
] == [r["session_id"] for r in lower["rows"]]
397+
# An operator OUTSIDE the quotes is still explicit.
398+
explicit = planner_search(query='"exact phrase" OR authentication')
399+
assert explicit["retrieval_status"]["plan"] == "explicit"

0 commit comments

Comments
 (0)