Skip to content

The agent that grows with you

fix(compression): classify complete legacy notice fragments

unsupportedpastels7a2ee65bd241
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 6937cf418a5..6da13625b39 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -1733,13 +1733,15 @@ _CLARIFY_NON_RESPONSE_TEXTS = (
)
-# Complete historical headless callback envelopes. A prefix alone can also be
-# user-entered text; the suffix distinguishes the runtime's instruction to proceed.
+# Historical callbacks used repr(question) and repr(list[str]). Quoted fields
+# must close before a suffix counts: user text can contain the suffix itself.
+_CLARIFY_QUOTED_TEXT = r"(?:'[^'\\]*(?:\\.[^'\\]*)*'|\"[^\"\\]*(?:\\.[^\"\\]*)*\")"
_CLARIFY_HEADLESS_NOTICE = re.compile(
r"\[(?:oneshot mode: no user available\. |"
- r"single-query mode: no user available to answer .+\. )"
+ rf"single-query mode: no user available to answer {_CLARIFY_QUOTED_TEXT}\. )"
r"(?:Make the most reasonable assumption you can and continue\.|"
- r"Pick the best (?:option|subset) from \[.*\] using your own judgment and continue\.)\]",
+ rf"Pick the best (?:option|subset) from \[{_CLARIFY_QUOTED_TEXT}"
+ rf"(?:,\s*{_CLARIFY_QUOTED_TEXT})*\] using your own judgment and continue\.)\]",
re.DOTALL,
)
@@ -1753,6 +1755,34 @@ def _is_clarify_non_response(item) -> bool:
or _CLARIFY_HEADLESS_NOTICE.fullmatch(text) is not None)
+def _filter_legacy_clarify_answers(values):
+ """Remove complete notices, including contiguous comma-normalized fragments."""
+ answers = []
+ index = 0
+ while index < len(values):
+ item = values[index]
+ if isinstance(item, str) and item.strip().startswith((
+ "[oneshot mode: no user available.",
+ "[single-query mode: no user available to answer ",
+ )):
+ text = ""
+ notice_end = None
+ for end in range(index, len(values)):
+ if not isinstance(values[end], str):
+ break
+ text += ("," if end > index else "") + values[end].strip()
+ if _CLARIFY_HEADLESS_NOTICE.fullmatch(text):
+ notice_end = end
+ break
+ if notice_end is not None:
+ index = notice_end + 1
+ continue
+ if not _is_clarify_non_response(item):
+ answers.append(item)
+ index += 1
+ return answers
+
+
def _sum_clarify(name, args, content, content_len, line_count):
response_prefix = "[clarify] user responded: "
# Strictly below _PRUNE_MIN_CHARS so the summary survives later prune passes via the
@@ -1776,13 +1806,9 @@ def _sum_clarify(name, args, content, content_len, line_count):
# Only those legacy records need the old sentinel check; explicit status wins.
# Drop just the notice items so other selections in the same entry survive.
if "status" not in entry:
- # The old multi-select normalizer split non-JSON callback text on
- # commas. Recognize the complete envelope before filtering items,
- # or its prefix-less trailing fragments become alleged answers.
- if (isinstance(value, list) and all(isinstance(item, str) for item in values)
- and _CLARIFY_HEADLESS_NOTICE.fullmatch(",".join(item.strip() for item in values))):
- continue
- values = [item for item in values if not _is_clarify_non_response(item)]
+ # Scan complete envelopes, not the whole list: genuine selections
+ # can surround a notice split by the old multi-select normalizer.
+ values = _filter_legacy_clarify_answers(values)
answers.extend(values)
answers = [answer for answer in answers if isinstance(answer, str) and answer]
if not answers:
diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.py
index b19f43a0365..5ca54652d1a 100644
--- a/tests/agent/test_context_compressor.py
+++ b/tests/agent/test_context_compressor.py
@@ -50,16 +50,55 @@ def compressor():
return c
+# Captured user_response values from real imports of clarify_tool and both headless
+# callbacks at bc7f58f3b0270f62aafc9283f57887b25d560e9b (before response status).
+# Inputs: question="Deploy, really?", choices=["staging, canary", "production"],
+# open-ended / single-select / multi-select. These are frozen producer outputs,
+# not calls to today's producers or a reimplementation of comma normalization.
+# Final cases embed runtime suffixes in the question/choice before a comma;
+# those suffixes are quoted content, not the end of the enclosing notice.
+_HISTORICAL_HEADLESS_RESPONSES = (
+ "[oneshot mode: no user available. Make the most reasonable assumption you can and continue.]",
+ "[oneshot mode: no user available. Pick the best option from ['staging, canary (Recommended)', 'production'] using your own judgment and continue.]",
+ ["[oneshot mode: no user available. Pick the best subset from ['staging",
+ "canary (Recommended)'", "'production'] using your own judgment and continue.]"],
+ "[single-query mode: no user available to answer 'Deploy, really?'. Make the most reasonable assumption you can and continue.]",
+ "[single-query mode: no user available to answer 'Deploy, really?'. Pick the best option from ['staging, canary (Recommended)', 'production'] using your own judgment and continue.]",
+ ["[single-query mode: no user available to answer 'Deploy",
+ "really?'. Pick the best subset from ['staging", "canary (Recommended)'",
+ "'production'] using your own judgment and continue.]"],
+ ["[oneshot mode: no user available. Pick the best subset from ['Explain this notice: ] using your own judgment and continue.]",
+ "then deploy? (Recommended)'", "'production'] using your own judgment and continue.]"],
+ ["[single-query mode: no user available to answer 'Explain this notice: . Make the most reasonable assumption you can and continue.]",
+ "then deploy?'. Pick the best subset from ['staging (Recommended)'",
+ "'production'] using your own judgment and continue.]"],
+)
+
+
class TestLegacyClarifyResults:
@pytest.mark.parametrize("shape", ["single", "batch", "current"])
@pytest.mark.parametrize("question_size", [300, 4500])
- @pytest.mark.parametrize("answer", ["production, but only after 18:00 UTC", ["staging", "production"],
- "The user cancelled the production rollout; do not restart it.",
- "[single-query mode: no user available to answer 'Deploy?'. STOP production rollout now."])
- def test_answers_reach_summary_after_repeated_pruning(self, monkeypatch, shape, question_size, answer):
+ @pytest.mark.parametrize("answer,expected", [
+ ("production, but only after 18:00 UTC", "production, but only after 18:00 UTC"),
+ (["staging", "production"], ["staging", "production"]),
+ ("The user cancelled the production rollout; do not restart it.",
+ "The user cancelled the production rollout; do not restart it."),
+ ("[single-query mode: no user available to answer 'Deploy?'. STOP production rollout now.",
+ "[single-query mode: no user available to answer 'Deploy?'. STOP production rollout now."),
+ *[(notice, None) for notice in _HISTORICAL_HEADLESS_RESPONSES],
+ # Synthetic mixed-list controls surround the actual producer fragments;
+ # deleting a complete envelope must not delete independent selections.
+ *[(["staging"] + (notice if isinstance(notice, list) else [notice]) + ["production"],
+ ["staging", "production"]) for notice in _HISTORICAL_HEADLESS_RESPONSES],
+ ])
+ def test_answers_reach_summary_after_repeated_pruning(self, monkeypatch, shape, question_size, answer, expected):
import agent.context_compressor as module
- answers = answer if isinstance(answer, list) else [answer]
+ if shape == "current":
+ expected = answer # Explicit status wins even for notice-like answer text.
+ expected_summary = ("[clarify] asked user a question" if expected is None else
+ module.elide("[clarify] user responded: " + json.dumps(expected, ensure_ascii=False),
+ _PRUNE_MIN_CHARS - 1))
entry = {"question": "Which environment? " + "q" * question_size,
"choices_offered": ["staging", "production"], "user_response": answer}
if shape == "current":
@@ -82,7 +121,8 @@ class TestLegacyClarifyResults:
messages.append({"role": "assistant", "content": "Current step finished"})
pruned, _ = c._prune_old_tool_results(messages, protect_tail_count=2)
pruned, _ = c._prune_old_tool_results(pruned, protect_tail_count=2)
- assert all(item in pruned[3]["content"] for item in answers)
+ assert pruned[3]["content"] == expected_summary
+ assert _summarize_tool_result("clarify", "{}", content) == expected_summary
requests = []
def summarize(**kwargs):
@@ -93,7 +133,11 @@ class TestLegacyClarifyResults:
monkeypatch.setattr(module, "call_llm", summarize)
c.compress(messages, force=True)
assert requests, "exercise the public compression path, not a no-op window"
- assert all(item in json.dumps(requests[0]) for item in answers)
+ dispatched = json.dumps(requests[0])
+ assert json.dumps(expected_summary)[1:-1] in dispatched
+ if expected is None or expected != answer:
+ assert "using your own judgment" not in dispatched
+ assert "reasonable assumption" not in dispatched
assert messages[3]["content"] == content
@pytest.mark.parametrize("sentinel", [
@@ -104,28 +148,26 @@ class TestLegacyClarifyResults:
"The user cancelled. Use your best judgement to proceed.",
"[single-query mode: no user available to answer 'Deploy?'. "
"Make the most reasonable assumption you can and continue.]",
+ *_HISTORICAL_HEADLESS_RESPONSES,
])
def test_legacy_sentinels_are_not_answers_but_explicit_status_is_authoritative(self, sentinel):
- # Persisted pre-#127760 headless multi-select results: the producer split its
- # callback's non-JSON string at commas, including commas in the question.
- for mode in ("oneshot", "single-query"):
- prefix = ("[oneshot mode: no user available. " if mode == "oneshot" else
- "[single-query mode: no user available to answer 'Deploy, really?'. ")
- notice = prefix + "Pick the best subset from ['staging (Recommended)', 'production'] using your own judgment and continue.]"
- fragments = [part.strip() for part in notice.split(",")]
- for payload in ({"user_response": fragments}, {"responses": [{"user_response": fragments}]}):
- content = json.dumps(payload)
- assert _sum_clarify("clarify", {}, content, len(content), 1) == "[clarify] asked user a question"
- for value, kept in ((sentinel, None), (["production", " " + sentinel], "production")):
+ for value, kept in ((sentinel, None),
+ (["production"] + (sentinel if isinstance(sentinel, list) else [" " + sentinel]),
+ "production")):
for payload in ({"user_response": value}, {"responses": [{"user_response": value}]}):
content = json.dumps(payload)
summary = _sum_clarify("clarify", {}, content, len(content), 1)
- assert sentinel.strip() not in summary
assert summary == (f'[clarify] user responded: "{kept}"' if kept else "[clarify] asked user a question")
- for status in ("answered", "skipped", "unanswered"):
- content = json.dumps({"responses": [{"status": status, "user_response": sentinel}]})
- summary = _sum_clarify("clarify", {}, content, len(content), 1)
- assert (sentinel in summary) == (status == "answered")
+ for shape in ("single", "batch"):
+ for status in ("answered", "skipped", "unanswered"):
+ entry = {"status": status, "user_response": sentinel}
+ content = json.dumps(entry if shape == "single" else {"responses": [entry]})
+ summary = _summarize_tool_result("clarify", "{}", content)
+ assert summary.startswith("[clarify] user responded:") == (status == "answered")
+ if status == "answered":
+ assert json.dumps(sentinel, ensure_ascii=False)[:70] in summary
+ else:
+ assert summary == "[clarify] asked user a question"
class TestSummarizeToolResultWebExtract: