From 4273933b87e5323ac6f6c08fe2e15bc152dc6472 Mon Sep 17 00:00:00 2001 From: Yeonwoo Choi <32544727+twoimo@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:11:39 +0900 Subject: [PATCH 01/11] fix(auto-reply): never send a generic confusion reply MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A draft such as "무슨 말인지 모르겠네요" was rejected only when the inbound turn was punctuation and a grounded topic existed, so "그래서?" or a bare "???" with no context could still send it. The question_unknown fallback and the lenient never-skip fallback also returned it unfiltered. The full policy now rejects every generic confusion draft, the no-eligible fallbacks skip them, and when every draft was one of them the worker asks which topic was meant. The clarification is not phrased as a question, so the unchanged pre-send policy recheck accepts it for non-question turns. Ports the intent of 0003e92 from the codex/alden-* lineage. Co-Authored-By: Claude Opus 5.5 --- scripts/auto-reply-worker.py | 46 +++++++++++++++++++++++----- tests/test_auto_reply_cli_runtime.py | 28 +++++++++++++++++ 2 files changed, 67 insertions(+), 7 deletions(-) diff --git a/scripts/auto-reply-worker.py b/scripts/auto-reply-worker.py index 2f86925f..8b1136be 100755 --- a/scripts/auto-reply-worker.py +++ b/scripts/auto-reply-worker.py @@ -6409,11 +6409,7 @@ def reject(reason: str) -> bool: return reject("empty") if len(text) > 220: return reject("too_long") - if ( - _is_context_pointer(inbound) - and _contextual_clarification_reply(inbound, recent_conversation) - and _is_contextless_confusion_reply(text) - ): + if _is_contextless_confusion_reply(text): return reject("contextless_confusion") if not _outbound_reaction_allows( text, inbound, laughter_allowed=laughter_allowed, awe_allowed=awe_allowed @@ -6767,6 +6763,19 @@ def _contextual_clarification_reply( ending = "얘기예요?" if _recipient_requires_honorific(recipient, register) else "얘기야?" return f"아까 “{topic}” {ending}" + +def _missing_context_clarification_reply( + *, + recipient: str | None = None, + register: str | None = None, +) -> str: + # Not phrased as a question: the pre-send policy recheck rejects a + # question reply to a non-question turn such as "???". + if _recipient_requires_honorific(recipient, register): + return "어떤 얘기인지 조금만 더 말씀해 주세요" + return "어떤 얘기인지 조금만 더 말해줘" + + def _photo_fallback_reply( inbound: str, recent_conversation: list[dict] | None = None ) -> str: @@ -6834,7 +6843,8 @@ def _lenient_policy_draft(drafts: list[str], inbound: str) -> str | None: Operator rule: an authorized sender is never skipped, so a draft that the full policy refused may still go out when it clears the light rules — not empty, not longer than 220 characters, not a verbatim copy of the inbound - message. Every relaxation stays visible through the policy_rejections list. + message, not a generic confusion line. Every relaxation stays visible + through the policy_rejections list. """ normalized_inbound = " ".join(str(inbound or "").split()) for item in drafts: @@ -6843,6 +6853,8 @@ def _lenient_policy_draft(drafts: list[str], inbound: str) -> str | None: continue if normalized_inbound and text == normalized_inbound: continue + if _is_contextless_confusion_reply(text): + continue return text return None @@ -6917,10 +6929,14 @@ def select_ranked_reply( inbound ) fallback_text = "" + has_contextless_confusion = False for item in [preferred, *drafts]: text = " ".join(str(item or "").split()) if _outbound_youtube_title_label(text, inbound): text = _rewrite_youtube_title_label(text) + if _is_contextless_confusion_reply(text): + has_contextless_confusion = True + continue if text: fallback_text = text break @@ -6931,7 +6947,7 @@ def select_ranked_reply( register=register, ) if contextual_clarification and ( - not fallback_text or _is_contextless_confusion_reply(fallback_text) + not fallback_text or has_contextless_confusion ): return { "reply": contextual_clarification, @@ -6941,6 +6957,22 @@ def select_ranked_reply( "fallback": "contextual_clarification", "policy_rejections": policy_rejections, } + if ( + has_contextless_confusion + and not fallback_text + and str(event.get("attachment") or "") != "image" + ): + clarification = _missing_context_clarification_reply( + recipient=recipient, register=register + ) + return { + "reply": clarification, + "drafts": [clarification], + "scores": [], + "winner_index": 0, + "fallback": "missing_context_clarification", + "policy_rejections": policy_rejections, + } if inbound_is_question and str(event.get("attachment") or "") != "image": fallback_text = fallback_text or _unknown_detail_reply( inbound, recent_conversation diff --git a/tests/test_auto_reply_cli_runtime.py b/tests/test_auto_reply_cli_runtime.py index b04ccc59..17f69cb4 100644 --- a/tests/test_auto_reply_cli_runtime.py +++ b/tests/test_auto_reply_cli_runtime.py @@ -1946,6 +1946,34 @@ def test_punctuation_followup_uses_recent_topic_instead_of_generic_confusion(sel self.assertEqual(unknown["fallback"], "question_unknown") self.assertEqual(unknown["reply"], "몇 명인진 안 나와서 모르겠네") + def test_generic_confusion_reply_is_never_sent(self): + module = self._load_auto_reply_module("auto_reply_ungrounded_confusion_test") + confusion = ["무슨 말인지 모르겠네요", "무슨 말인지 모르겠어요"] + for inbound in ("그래서?", "???", "아 그렇구나"): + with self.subTest(inbound=inbound): + result = module.select_ranked_reply( + inbound, confusion[0], confusion[1:], {"author_nickname": "MOM"}, [] + ) + self.assertEqual(result["fallback"], "missing_context_clarification") + self.assertEqual(result["reply"], "어떤 얘기인지 조금만 더 말해줘") + self.assertTrue( + module._policy_valid_draft(result["reply"], inbound, [], recipient="MOM") + ) + honorific = module.select_ranked_reply( + "그래서?", confusion[0], confusion[1:], {"author_nickname": "현준"}, [] + ) + self.assertEqual(honorific["reply"], "어떤 얘기인지 조금만 더 말씀해 주세요") + self.assertTrue( + module._policy_valid_draft(honorific["reply"], "그래서?", [], recipient="현준") + ) + + mixed = module.select_ranked_reply( + "아 그렇구나", confusion[0], ["ㅋㅋㅋㅋ"], {"author_nickname": "MOM"}, [] + ) + self.assertEqual(mixed["fallback"], "lenient_policy") + self.assertEqual(mixed["reply"], "ㅋㅋㅋㅋ") + self.assertIsNone(module._lenient_policy_draft([confusion[0]], "아 그렇구나")) + def test_punctuation_followup_can_clarify_the_last_self_reply(self): module = self._load_auto_reply_module("auto_reply_self_context_pointer_test") recent = [ From 8e9de89a0fb81d5b4c8642a3070ba89c9abcbbf6 Mon Sep 17 00:00:00 2001 From: Yeonwoo Choi <32544727+twoimo@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:15:41 +0900 Subject: [PATCH 02/11] fix(auto-reply): stop inventing remarks about uninspected photos MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When no draft was eligible, or the model stayed unavailable, or the media fetch failed, the photo fallback picked a stock visual remark such as "화질이 별로네" about a photo nobody looked at. It now says the photo was not checked and asks for the needed part in text, in the current recipient's register. The wording is not a question, so the unchanged pre-send policy recheck accepts it for a bare photo turn. When every image failed to load, the runner still sent a text-only model request and relied on prompt wording to stop a made-up answer. It now sends nothing. generate_reply releases that call's lease without opening a cooldown or clearing earlier failures, and returns image_unavailable. Ports the worker part of 8ceeea8 from the codex/alden-* lineage. Co-Authored-By: Claude Opus 5.5 --- scripts/auto-reply-worker.py | 131 +++++++++++++++++---------- tests/test_auto_reply_cli_runtime.py | 119 +++++++++++++++++++----- 2 files changed, 178 insertions(+), 72 deletions(-) diff --git a/scripts/auto-reply-worker.py b/scripts/auto-reply-worker.py index 8b1136be..ca80dcc5 100755 --- a/scripts/auto-reply-worker.py +++ b/scripts/auto-reply-worker.py @@ -403,8 +403,9 @@ def kakao_image_kind(message_type: object) -> int | None: "directed_at_self", } ) -MEDIA_UNAVAILABLE_CLARIFICATION = "사진이 안 열리네 다시 보내봐" +MEDIA_UNAVAILABLE_CLARIFICATION = "사진 내용을 확인하지 못했어. 필요한 부분은 글로 알려줘" MEDIA_UNAVAILABLE_CLARIFICATION_REASON = "media_unavailable_clarification" +IMAGE_INPUT_UNAVAILABLE = b"image_input_unavailable" REPLY_LAUGHTER_POLICY_REASON = "reply_laughter_policy_violation" AI_TELL_PROBE = "그래? 어떤 부분이 AI처럼 느껴졌는데" # Trailing laughter, jamo runs and punctuation are ignored when a rule checks the @@ -2038,6 +2039,62 @@ def _finish_model_call_success(lease_token: str, *, model: str | None = None) -> connection.close() +def _release_unsent_model_call(lease_token: str, model: str | None = None) -> bool: + """Release a lease whose request was never sent, keeping prior failures.""" + connection: sqlite3.Connection | None = None + transaction_started = False + try: + connection = _model_circuit_connection() + connection.execute("BEGIN IMMEDIATE") + transaction_started = True + key = _model_circuit_key(model) + row = connection.execute( + """ + SELECT state, failure_class, consecutive_failures, + open_until, lease_token + FROM model_circuit_breaker WHERE model_key = ? + """, + (key,), + ).fetchone() + current = time.time() + if ( + row is None + or not _valid_model_circuit_row(row, current) + or str(row["state"]) != "in_flight" + or str(row["lease_token"]) != lease_token + ): + connection.commit() + transaction_started = False + return False + if int(row["consecutive_failures"]) == 0: + changed = connection.execute( + """ + DELETE FROM model_circuit_breaker + WHERE model_key = ? AND state = 'in_flight' AND lease_token = ? + """, + (key, lease_token), + ).rowcount + else: + changed = connection.execute( + """ + UPDATE model_circuit_breaker + SET state = 'open', open_until = ?, lease_token = NULL, updated_at = ? + WHERE model_key = ? AND state = 'in_flight' AND lease_token = ? + """, + (current, current, key, lease_token), + ).rowcount + connection.commit() + transaction_started = False + return changed == 1 + except (OSError, PermissionError, sqlite3.Error, ValueError): + if transaction_started and connection is not None: + _rollback_queue_transaction(connection) + return False + finally: + if connection is not None: + connection.close() + + def _bounded_error_scalars(value: object, *, depth: int = 0) -> list[str]: if depth > 3: return [] @@ -6777,40 +6834,12 @@ def _missing_context_clarification_reply( def _photo_fallback_reply( - inbound: str, recent_conversation: list[dict] | None = None + *, recipient: str | None = None, register: str | None = None ) -> str: - honorific = False - for row in recent_conversation or []: - if not isinstance(row, dict) or _is_self_chat_row(row): - continue - if str(row.get("author_nickname") or "") == "현준": - honorific = True - break - informal = ( - "화면이 좀 깨지네", - "화질이 별로네", - "이거 잘 안 보이네", - "구도가 이상하네", - "색감이 별로네", - ) - formal = ( - "화면이 좀 깨지네요", - "화질이 별로네요", - "잘 안 보이네요", - "구도가 이상하네요", - "색감이 별로네요", - ) - pool = formal if honorific else informal - recent_self = [ - " ".join(str(row.get("message") or "").split()) - for row in (recent_conversation or []) - if isinstance(row, dict) and _is_self_chat_row(row) - ][-6:] - used = set(recent_self) - unused = [line for line in pool if line not in used] - seed = abs(hash(" ".join(recent_self[-2:] + [str(inbound or "")]))) - chosen = (unused or list(pool))[seed % len(unused or pool)] - return chosen + """Admit that the photo was not inspected instead of inventing a remark.""" + if _recipient_requires_honorific(recipient, register): + return "사진 내용을 확인하지 못했어요. 필요한 부분은 글로 알려주세요" + return MEDIA_UNAVAILABLE_CLARIFICATION def _reply_ending(text: str) -> str: @@ -6987,7 +7016,7 @@ def select_ranked_reply( } if str(event.get("attachment") or "") == "image": fallback_text = fallback_text or _photo_fallback_reply( - inbound, recent_conversation + recipient=recipient, register=register ) return { "reply": fallback_text, @@ -11807,17 +11836,11 @@ def _run_opencodex_generation_unleased( file=sys.stderr, flush=True, ) - if len(user_parts) > 1: - payload["messages"][1]["content"] = user_parts - elif image_paths: - # Every image failed to load. Sending the text alone would answer a - # question about a photo without the photo, so say so in the prompt - # instead of pretending the message had no attachment. - payload["messages"][1]["content"] = ( - user_content - + "\n\n[첨부한 사진을 읽지 못했습니다. 사진 내용을 모르는 상태이므로," - + " 사진에 대해 추측하지 말고 사진을 다시 보내 달라고 답하세요.]" - ) + if len(user_parts) == 1: + # Every image failed to load. A text-only request lets the model + # answer about a photo it never saw, whatever the prompt says. + return 1, b"", IMAGE_INPUT_UNAVAILABLE + payload["messages"][1]["content"] = user_parts data = json.dumps(payload, ensure_ascii=False).encode("utf-8") session_lane = "openkakao-bujamentor" session_digest = hashlib.sha256( @@ -12565,6 +12588,11 @@ def continue_on_fallback( image_paths=normalized_image_paths, timeout=_model_generation_timeout(active_model, deadline=generation_deadline), ) + if returncode != 0 and stderr_bytes == IMAGE_INPUT_UNAVAILABLE: + # No request was sent, so the model is not at fault and another + # model would get the same missing images. + _release_unsent_model_call(lease_token, active_model) + return with_prompt_receipt({**empty, "reason": "image_unavailable"}) if returncode != 0: err_str = stderr_bytes.decode("utf-8", "replace").casefold() failure_class, _ = _classify_model_failure( @@ -14162,7 +14190,10 @@ def analyze_media_unavailable_clarification(event: dict) -> dict: "decision": "reply", "reason": MEDIA_UNAVAILABLE_CLARIFICATION_REASON, "category": "social", - "reply": _photo_fallback_reply(inbound_text, recent_conversation), + "reply": _photo_fallback_reply( + recipient=_event_author_nickname(event), + register=str((recipient_style_profile or {}).get("register") or "") or None, + ), "context": context, "styles": styles, "prior_decisions": prior_decisions, @@ -15745,8 +15776,10 @@ def _analyze_and_schedule_reply( analysis["reason"] = str(analysis.get("reason") or "photo_reply") analysis["category"] = "reaction" analysis["reply"] = str(analysis.get("reply") or "").strip() or _photo_fallback_reply( - str(event.get("message") or ""), - _event_recent_conversation(event), + recipient=_event_author_nickname(event), + register=str( + (analysis.get("recipient_style_profile") or {}).get("register") or "" + ) or None, ) else: # The model remained unavailable through this message's learned diff --git a/tests/test_auto_reply_cli_runtime.py b/tests/test_auto_reply_cli_runtime.py index 17f69cb4..5e9b070b 100644 --- a/tests/test_auto_reply_cli_runtime.py +++ b/tests/test_auto_reply_cli_runtime.py @@ -1397,22 +1397,27 @@ def test_reaction_register_blocks_unprompted_laughter(self): "style:youtube_reaction_register:v1", ) - def test_photo_fallback_varies_and_media_placeholder_is_not_echo(self): - module = self._load_auto_reply_module("auto_reply_photo_fallback_vary_test") + def test_photo_fallback_admits_it_did_not_see_the_photo(self): + module = self._load_auto_reply_module("auto_reply_photo_fallback_truthful_test") self.assertTrue(module._inbound_is_media_placeholder("사진")) self.assertFalse(module._outbound_echoes_inbound("화면이 좀 깨지네", "사진")) - self.assertTrue( - module._policy_valid_draft("화면이 좀 깨지네", "사진", [], []) - ) - recent = [{"is_self": True, "message": "화면이 좀 깨지네"}] - first = module._photo_fallback_reply("사진", recent) - self.assertNotEqual(first, "이거 뭐야") - self.assertNotIn(first, {"화면이 좀 깨지네"}) - second = module._photo_fallback_reply( - "사진", - recent + [{"is_self": True, "message": first}], - ) - self.assertNotEqual(second, first) + for recipient, expected in ( + ("MOM", "사진 내용을 확인하지 못했어. 필요한 부분은 글로 알려줘"), + ("현준", "사진 내용을 확인하지 못했어요. 필요한 부분은 글로 알려주세요"), + ): + with self.subTest(recipient=recipient): + result = module.select_ranked_reply( + "사진", + "", + [], + {"author_nickname": recipient, "attachment": "image"}, + [{"is_self": True, "message": "화면이 좀 깨지네"}], + ) + self.assertEqual(result["fallback"], "photo_passthrough") + self.assertEqual(result["reply"], expected) + self.assertTrue( + module._policy_valid_draft(expected, "사진", [], recipient=recipient) + ) def test_unsolicited_plan_is_rejected(self): module = self._load_auto_reply_module("auto_reply_unsolicited_plan_test") self.assertTrue( @@ -15403,8 +15408,10 @@ def record(decision): (row["scheduled_delay_seconds"], row["error_class"]), (5.0, None) ) # The reply prompt forbids stock photo acks such as 사진이 안 열리네. - self.assertTrue(row["reply"].strip()) self.assertNotIn("사진이 안 열리네", row["reply"]) + self.assertEqual( + row["reply"], "사진 내용을 확인하지 못했어. 필요한 부분은 글로 알려줘" + ) self.assertEqual(recorded["style_policy_version"], module.STYLE_POLICY_VERSION) self.assertIn("db:42:920", recorded["evidence_ids"]) self.assertFalse(recorded["provenance"]["model_invoked"]) @@ -15745,6 +15752,77 @@ def test_generate_reply_passes_ordered_multi_image_flags(self): self.assertTrue(result["should_reply"]) self.assertEqual(result["evidence_ids"], [evidence_id]) + def test_generate_reply_sends_no_request_when_no_image_loads(self): + with tempfile.TemporaryDirectory(dir=Path.home()) as temporary: + root = Path(temporary) + module, _runner = self._load_trusted_codex_module( + "auto_reply_unloadable_image_test", root + ) + with self._owned_image_bundle(module, count=2, message_type=27) as media: + evidence_id = f"media:{media['manifest']['bundle_sha256']}" + response = { + "should_reply": True, + "reply": "화질이 별로네", + "category": "social", + "reason": "useful_image_response", + "evidence_ids": [evidence_id], + } + image_model = module._generation_reply_model(True) + earlier = time.time() - 3600.0 + prior = module._acquire_model_call_slot(now=earlier, model=image_model) + module._finish_model_call_failure( + prior["lease_token"], "runner_failed", now=earlier, model=image_model + ) + for path in media["paths"]: + path.chmod(0o000) + try: + with ( + self._fake_mlx_gateway( + module, + json.dumps(response, ensure_ascii=False), + model_id=module.QWEN38_27B_MODEL_ID, + ) as gateway, + mock.patch.object( + module, "privacy_attestation_current", return_value=True + ), + mock.patch.object(module, "runner_is_trusted", return_value=True), + mock.patch.object(module, "_run_bounded_process") as process_runner, + ): + result = module.generate_reply( + "이 사진 어때?", + [], + [], + [], + [], + attachment="image", + image_path=media["paths"][0], + image_marker=media["marker"], + image_paths=media["paths"], + media_evidence_id=evidence_id, + ) + connection = module._model_circuit_connection() + try: + failures = connection.execute( + "SELECT consecutive_failures FROM model_circuit_breaker" + " WHERE model_key = ?", + (module._model_circuit_key(image_model),), + ).fetchone() + finally: + connection.close() + circuit = module._acquire_model_call_slot(model=image_model) + finally: + for path in media["paths"]: + path.chmod(0o600) + + self.assertEqual(gateway["payloads"], []) + gateway["external_urlopen"].assert_not_called() + process_runner.assert_not_called() + self.assertFalse(result["should_reply"]) + self.assertEqual(result["reply"], "") + self.assertEqual(result["reason"], "image_unavailable") + self.assertEqual(failures[0], 1) + self.assertTrue(circuit["allowed"], circuit) + def test_gjc_generate_reply_sends_prompt_on_stdin_with_at_images(self): with tempfile.TemporaryDirectory(dir=Path.home()) as temporary: root = Path(temporary) @@ -20014,7 +20092,7 @@ def fake_http(url, deadline): self.assertIn("football tactics board", preview["text"]) self.assertTrue(module._inbound_asks_question("리드미 요약해줘")) - def test_unreadable_image_is_named_and_never_answered_blind(self): + def test_unreadable_image_is_never_answered_blind(self): """A photo the worker cannot read must not be dropped in silence. The old code swallowed the read error, so a question about a photo was @@ -20050,13 +20128,8 @@ def fake_urlopen(request, timeout=None): image_paths=[missing], timeout=5.0, ) - self.assertEqual(code, 0) - content = captured["body"]["messages"][1]["content"] - # The text is still sent, but with an explicit note that the photo was - # not readable, so the model cannot guess at a picture it never saw. - self.assertIsInstance(content, str) - self.assertIn("사진을 읽지 못했습니다", content) - self.assertIn("추측하지 말고", content) + self.assertEqual((code, _stderr), (1, b"image_input_unavailable")) + self.assertNotIn("body", captured) def test_readable_image_is_still_attached_as_a_data_url(self): """The failure path must not disturb the working path.""" From 3a02d273f5d9b8489b3c247bdd4e49151abf499c Mon Sep 17 00:00:00 2001 From: Yeonwoo Choi <32544727+twoimo@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:35:29 +0900 Subject: [PATCH 03/11] test(auto-reply): pin replies when a confusion draft or every image drops out MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two red tests for the review of the reply-content guards. A confusion draft that the full policy now rejects must not hand the turn to a second draft that the full policy also rejected. The test feeds the reviewer's cases ("아 그렇군요" from 현준 with "그치 뭐함?", "아 그렇구나" with "너는 뭐 먹었어?" or "ㅋㅋㅋㅋ", a bare photo with "이거 어디야?") and expects the clarification or the honest photo reply, which the pre-send policy recheck accepts. The old assertion that "ㅋㅋㅋㅋ" goes out through the lenient fallback is dropped. A photo turn whose images cannot be read at generation time must still get an honest reply, with no model request sent. Co-Authored-By: Claude Opus 5.5 --- tests/test_auto_reply_cli_runtime.py | 133 ++++++++++++++++++++++++++- 1 file changed, 128 insertions(+), 5 deletions(-) diff --git a/tests/test_auto_reply_cli_runtime.py b/tests/test_auto_reply_cli_runtime.py index 5e9b070b..f5dd3a71 100644 --- a/tests/test_auto_reply_cli_runtime.py +++ b/tests/test_auto_reply_cli_runtime.py @@ -1972,13 +1972,44 @@ def test_generic_confusion_reply_is_never_sent(self): module._policy_valid_draft(honorific["reply"], "그래서?", [], recipient="현준") ) - mixed = module.select_ranked_reply( - "아 그렇구나", confusion[0], ["ㅋㅋㅋㅋ"], {"author_nickname": "MOM"}, [] - ) - self.assertEqual(mixed["fallback"], "lenient_policy") - self.assertEqual(mixed["reply"], "ㅋㅋㅋㅋ") self.assertIsNone(module._lenient_policy_draft([confusion[0]], "아 그렇구나")) + def test_removed_confusion_draft_never_promotes_a_rejected_draft(self): + module = self._load_auto_reply_module("auto_reply_confusion_no_promotion_test") + cases = ( + ("아 그렇군요", "무슨 말인지 모르겠어요", "그치 뭐함?", "현준", "", + "어떤 얘기인지 조금만 더 말씀해 주세요"), + ("아 그렇구나", "무슨 말인지 모르겠어", "너는 뭐 먹었어?", "MOM", "", + "어떤 얘기인지 조금만 더 말해줘"), + ("아 그렇구나", "무슨 말인지 모르겠네요", "ㅋㅋㅋㅋ", "MOM", "", + "어떤 얘기인지 조금만 더 말해줘"), + ("사진", "무슨 말인지 모르겠어", "이거 어디야?", "MOM", "image", + "사진 내용을 확인하지 못했어. 필요한 부분은 글로 알려줘"), + ("사진", "무슨 말인지 모르겠어요", "이거 어디야?", "현준", "image", + "사진 내용을 확인하지 못했어요. 필요한 부분은 글로 알려주세요"), + ) + for inbound, confusion, rejected, recipient, attachment, expected in cases: + with self.subTest(inbound=inbound, rejected=rejected, recipient=recipient): + self.assertFalse( + module._policy_valid_draft(rejected, inbound, [], recipient=recipient) + ) + result = module.select_ranked_reply( + inbound, + confusion, + [rejected], + {"author_nickname": recipient, "attachment": attachment}, + [], + ) + self.assertEqual(result["reply"], expected) + self.assertNotEqual(result["fallback"], "lenient_policy") + reasons = [] + self.assertTrue( + module._policy_valid_draft( + result["reply"], inbound, [], recipient=recipient, reasons_out=reasons + ), + reasons, + ) + def test_punctuation_followup_can_clarify_the_last_self_reply(self): module = self._load_auto_reply_module("auto_reply_self_context_pointer_test") recent = [ @@ -15823,6 +15854,98 @@ def test_generate_reply_sends_no_request_when_no_image_loads(self): self.assertEqual(failures[0], 1) self.assertTrue(circuit["allowed"], circuit) + def test_photo_turn_with_no_loadable_image_replies_honestly_without_a_request(self): + with tempfile.TemporaryDirectory(dir=Path.home()) as temporary: + module, _runner = self._load_trusted_codex_module( + "auto_reply_unloadable_image_turn_test", Path(temporary) + ) + with self._owned_image_bundle(module, count=2, message_type=27) as media: + event = self._burst_event( + module, + 902, + "[사진]", + int(time.time()), + message_type=27, + attachment=True, + ) + event.update(media["event_fields"]) + real_generate_reply = module.generate_reply + + def generate_after_images_become_unreadable(*args, **kwargs): + for path in media["paths"]: + path.chmod(0o000) + return real_generate_reply(*args, **kwargs) + + response = { + "should_reply": True, + "reply": "화질이 별로네", + "category": "social", + "reason": "useful_image_response", + "evidence_ids": [f"media:{media['manifest']['bundle_sha256']}"], + } + try: + with ( + mock.patch.dict( + os.environ, + { + module.DB_MODE_ENV: "database_authoritative", + "OPENKAKAO_ALLOW_IMAGE_ANALYSIS": "1", + }, + clear=False, + ), + mock.patch.object(module, "_reply_turn_hold_reason", return_value=None), + mock.patch.object(module, "privacy_attestation_current", return_value=True), + mock.patch.object(module, "runner_is_trusted", return_value=True), + mock.patch.object(module, "fetch_link_previews", return_value=[]), + mock.patch.object( + module, + "run_context_reply_bundle", + return_value={ + "context": [], + "styles": [], + "prior_decisions": [], + "style_profile": None, + "recipient_style_profile": None, + "response_time": self._timing_stats(module), + }, + ), + self._fake_mlx_gateway( + module, + json.dumps(response, ensure_ascii=False), + model_id=module.QWEN38_27B_MODEL_ID, + ) as gateway, + mock.patch.object(module, "_run_bounded_process") as process_runner, + mock.patch.object( + module, + "generate_reply", + side_effect=generate_after_images_become_unreadable, + ), + ): + result = module.analyze_event(event) + finally: + for path in media["paths"]: + if path.exists(): + path.chmod(0o600) + + self.assertEqual(gateway["payloads"], []) + gateway["external_urlopen"].assert_not_called() + process_runner.assert_not_called() + self.assertEqual(result["decision"], "reply") + self.assertEqual( + result["reply"], "사진 내용을 확인하지 못했어. 필요한 부분은 글로 알려줘" + ) + reasons = [] + self.assertTrue( + module._policy_valid_draft( + result["reply"], + event["message"], + module._event_recent_conversation(event), + recipient=module._event_author_nickname(event), + reasons_out=reasons, + ), + reasons, + ) + def test_gjc_generate_reply_sends_prompt_on_stdin_with_at_images(self): with tempfile.TemporaryDirectory(dir=Path.home()) as temporary: root = Path(temporary) From 25d32f8cbd6399e13505ab5e08d81024cbea19b5 Mon Sep 17 00:00:00 2001 From: Yeonwoo Choi <32544727+twoimo@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:35:42 +0900 Subject: [PATCH 04/11] fix(auto-reply): answer a dropped confusion draft with the clarification MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The full policy now rejects every generic confusion line, but the clarification fired only when no other draft existed. With a second draft the turn fell through to the question_unknown, photo and lenient fallbacks, which sent that draft even though the full policy had refused it, for example "그치 뭐함?" to 현준 after "아 그렇군요". For a photo turn the refused draft also failed the pre-send recheck, so nothing was sent. When any draft was a confusion line, the worker now sends the clarification, or the honest photo reply on an image turn, before any fallback can reuse a refused draft. Both pass the unchanged pre-send policy recheck. Co-Authored-By: Claude Opus 5.5 --- scripts/auto-reply-worker.py | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/scripts/auto-reply-worker.py b/scripts/auto-reply-worker.py index ca80dcc5..1872c91f 100755 --- a/scripts/auto-reply-worker.py +++ b/scripts/auto-reply-worker.py @@ -6986,20 +6986,25 @@ def select_ranked_reply( "fallback": "contextual_clarification", "policy_rejections": policy_rejections, } - if ( - has_contextless_confusion - and not fallback_text - and str(event.get("attachment") or "") != "image" - ): - clarification = _missing_context_clarification_reply( - recipient=recipient, register=register - ) + if has_contextless_confusion: + # Every other draft was refused by the full policy too, so none of + # them may stand in for the confusion line that was dropped. + if str(event.get("attachment") or "") == "image": + clarification = _photo_fallback_reply( + recipient=recipient, register=register + ) + fallback = "photo_passthrough" + else: + clarification = _missing_context_clarification_reply( + recipient=recipient, register=register + ) + fallback = "missing_context_clarification" return { "reply": clarification, "drafts": [clarification], "scores": [], "winner_index": 0, - "fallback": "missing_context_clarification", + "fallback": fallback, "policy_rejections": policy_rejections, } if inbound_is_question and str(event.get("attachment") or "") != "image": From 1bac3c30055a25e4c20d8939ada9f4470d0de458 Mon Sep 17 00:00:00 2001 From: Yeonwoo Choi <32544727+twoimo@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:36:29 +0900 Subject: [PATCH 05/11] fix(auto-reply): reply honestly when no image loads instead of skipping MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When every image of a photo turn failed to load, generate_reply now sends no model request and returns image_unavailable. analyze_event treated that as a model no-reply and skipped the turn for good, which broke the rule that an authorized sender is never skipped. analyze_event now answers that turn with the photo fallback in the recipient's register ("사진 내용을 확인하지 못했어. 필요한 부분은 글로 알려줘"), records model_invoked as false, and uses the media-unavailable clarification reason, so the reply stays out of behavior memory like the existing no-pixel clarification. Still no model request is sent. Co-Authored-By: Claude Opus 5.5 --- scripts/auto-reply-worker.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/scripts/auto-reply-worker.py b/scripts/auto-reply-worker.py index 1872c91f..1b8f5d7b 100755 --- a/scripts/auto-reply-worker.py +++ b/scripts/auto-reply-worker.py @@ -14593,6 +14593,21 @@ def analyze_event(event: dict) -> dict: "prompt_evidence_ids": model.get("prompt_evidence_ids"), "generation_seconds": model.get("generation_seconds"), } + if image_paths and str(model.get("reason") or "") == "image_unavailable": + # No image could be shown to the model, so no request was sent. + # An authorized sender still gets an answer, one that admits it. + provenance["model_invoked"] = False + result.update( + decision="reply", + reason=MEDIA_UNAVAILABLE_CLARIFICATION_REASON, + category="social", + reply=_photo_fallback_reply( + recipient=_event_author_nickname(event), + register=str((recipient_style_profile or {}).get("register") or "") + or None, + ), + ) + return result if not model.get("should_reply"): failure_class = str(model.get("model_failure_class") or "") retry_at = model.get("model_defer_until") From 84432fa85f4a31c4f0d979ffb4bc2df7e56e5a10 Mon Sep 17 00:00:00 2001 From: Yeonwoo Choi <32544727+twoimo@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:50:09 +0900 Subject: [PATCH 06/11] test(auto-reply): pin unsent image requests and every confusion spelling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three rare paths the PR left worse than main or incomplete: - A cooldown fallback whose images will not load sends nothing, yet the chain charged it a runner_failed cooldown and deferred the turn. - A text turn that carries the author's recent photos got the photo apology when those files could not be read, instead of an answer. - "이해가 안 돼" and the other 돼 or 되요 spellings passed as a valid draft. The analyze_event photo tests share one gateway harness, which also stubs the local media download and the screen capture. Co-Authored-By: Claude Opus 5.5 --- tests/test_auto_reply_cli_runtime.py | 294 +++++++++++++++++++++------ 1 file changed, 237 insertions(+), 57 deletions(-) diff --git a/tests/test_auto_reply_cli_runtime.py b/tests/test_auto_reply_cli_runtime.py index f5dd3a71..342031e3 100644 --- a/tests/test_auto_reply_cli_runtime.py +++ b/tests/test_auto_reply_cli_runtime.py @@ -1974,6 +1974,33 @@ def test_generic_confusion_reply_is_never_sent(self): self.assertIsNone(module._lenient_policy_draft([confusion[0]], "아 그렇구나")) + def test_every_spelling_of_not_understanding_is_a_confusion_reply(self): + module = self._load_auto_reply_module("auto_reply_confusion_spelling_test") + spellings = ( + "이해가 안 되네요", + "이해가 안 되어요", + "이해가 안 돼", + "이해가 안 돼요", + "이해가 잘 안 돼", + "잘 이해가 안 돼요", + "이해가 안 되요", + "이해가 안 돼네", + "이해가 안 돼네요", + ) + for confusion in spellings: + with self.subTest(confusion=confusion): + self.assertFalse( + module._policy_valid_draft(confusion, "아 그렇구나", [], recipient="MOM") + ) + self.assertIsNone(module._lenient_policy_draft([confusion], "아 그렇구나")) + result = module.select_ranked_reply( + "아 그렇구나", confusion, [], {"author_nickname": "MOM"}, [] + ) + self.assertEqual(result["reply"], "어떤 얘기인지 조금만 더 말해줘") + self.assertTrue( + module._policy_valid_draft("이해가 안 돼서 다시 물어봤어", "아 그렇구나", [], recipient="MOM") + ) + def test_removed_confusion_draft_never_promotes_a_rejected_draft(self): module = self._load_auto_reply_module("auto_reply_confusion_no_promotion_test") cases = ( @@ -15854,6 +15881,92 @@ def test_generate_reply_sends_no_request_when_no_image_loads(self): self.assertEqual(failures[0], 1) self.assertTrue(circuit["allowed"], circuit) + def _analyze_with_mlx_gateway( + self, module, event, response, *, before_generate, recovered_media=None + ): + """Run analyze_event against the fake local gateway; return what it sent. + + ``recovered_media`` maps a log id to the paths the local media download + would return. No real download or screen capture runs. + """ + real_generate_reply = module.generate_reply + + def generate(*args, **kwargs): + before_generate() + return real_generate_reply(*args, **kwargs) + + with ( + mock.patch.dict( + os.environ, + { + module.DB_MODE_ENV: "database_authoritative", + "OPENKAKAO_ALLOW_IMAGE_ANALYSIS": "1", + }, + clear=False, + ), + mock.patch.object(module, "_reply_turn_hold_reason", return_value=None), + mock.patch.object(module, "privacy_attestation_current", return_value=True), + mock.patch.object(module, "runner_is_trusted", return_value=True), + mock.patch.object(module, "fetch_link_previews", return_value=[]), + mock.patch.object( + module, + "run_context_reply_bundle", + return_value={ + "context": [], + "styles": [], + "prior_decisions": [], + "style_profile": None, + "recipient_style_profile": None, + "response_time": self._timing_stats(module), + }, + ), + self._fake_mlx_gateway( + module, + json.dumps(response, ensure_ascii=False), + model_id=module.QWEN38_27B_MODEL_ID, + ) as gateway, + mock.patch.object(module, "_run_bounded_process") as process_runner, + mock.patch.object(module, "BIN", Path(os.devnull) / "openkakao-cli"), + mock.patch.object( + module, + "_recover_local_media_bundle", + side_effect=lambda media_event: (recovered_media or {}).get( + media_event["log_id"] + ), + ), + mock.patch.object(module, "capture_visible_image", return_value=None), + mock.patch.object(module, "generate_reply", side_effect=generate), + ): + result = module.analyze_event(event) + gateway["external_urlopen"].assert_not_called() + process_runner.assert_not_called() + return result, gateway["payloads"] + + def _assert_presend_accepts(self, module, event, reply): + reasons = [] + self.assertTrue( + module._policy_valid_draft( + reply, + event["message"], + module._event_recent_conversation(event), + recipient=module._event_author_nickname(event), + reasons_out=reasons, + ), + reasons, + ) + + @staticmethod + def _model_failures(module, model): + connection = module._model_circuit_connection() + try: + row = connection.execute( + "SELECT consecutive_failures FROM model_circuit_breaker WHERE model_key = ?", + (module._model_circuit_key(model),), + ).fetchone() + finally: + connection.close() + return 0 if row is None else int(row[0]) + def test_photo_turn_with_no_loadable_image_replies_honestly_without_a_request(self): with tempfile.TemporaryDirectory(dir=Path.home()) as temporary: module, _runner = self._load_trusted_codex_module( @@ -15869,13 +15982,64 @@ def test_photo_turn_with_no_loadable_image_replies_honestly_without_a_request(se attachment=True, ) event.update(media["event_fields"]) - real_generate_reply = module.generate_reply + response = { + "should_reply": True, + "reply": "화질이 별로네", + "category": "social", + "reason": "useful_image_response", + "evidence_ids": [f"media:{media['manifest']['bundle_sha256']}"], + } - def generate_after_images_become_unreadable(*args, **kwargs): + def make_images_unreadable(): for path in media["paths"]: path.chmod(0o000) - return real_generate_reply(*args, **kwargs) + try: + result, payloads = self._analyze_with_mlx_gateway( + module, event, response, before_generate=make_images_unreadable + ) + finally: + for path in media["paths"]: + if path.exists(): + path.chmod(0o600) + + self.assertEqual(payloads, []) + self.assertEqual(result["decision"], "reply") + self.assertEqual( + result["reply"], "사진 내용을 확인하지 못했어. 필요한 부분은 글로 알려줘" + ) + self._assert_presend_accepts(module, event, result["reply"]) + + def test_cooldown_fallback_with_no_loadable_image_is_not_charged_a_failure(self): + with tempfile.TemporaryDirectory(dir=Path.home()) as temporary: + module, _runner = self._load_trusted_codex_module( + "auto_reply_unloadable_image_fallback_test", Path(temporary) + ) + image_model = module._generation_reply_model(True) + vision_fallback = image_model.removeprefix("mlx/") + self.assertNotEqual(vision_fallback, image_model) + fallbacks = module._operator_state_root() / module.REPLY_MODEL_FALLBACKS_NAME + fallbacks.parent.mkdir(parents=True, exist_ok=True) + fallbacks.write_text( + json.dumps({"schema_version": 1, "models": [vision_fallback]}), + encoding="utf-8", + ) + self.assertEqual(module._reply_fallback_candidates(), [vision_fallback]) + cooling = module._acquire_model_call_slot(model=image_model) + module._finish_model_call_failure( + cooling["lease_token"], "runner_failed", model=image_model + ) + self.assertFalse(module._acquire_model_call_slot(model=image_model)["allowed"]) + with self._owned_image_bundle(module, count=2, message_type=27) as media: + event = self._burst_event( + module, + 903, + "[사진]", + int(time.time()), + message_type=27, + attachment=True, + ) + event.update(media["event_fields"]) response = { "should_reply": True, "reply": "화질이 별로네", @@ -15883,68 +16047,84 @@ def generate_after_images_become_unreadable(*args, **kwargs): "reason": "useful_image_response", "evidence_ids": [f"media:{media['manifest']['bundle_sha256']}"], } + + def make_images_unreadable(): + for path in media["paths"]: + path.chmod(0o000) + try: - with ( - mock.patch.dict( - os.environ, - { - module.DB_MODE_ENV: "database_authoritative", - "OPENKAKAO_ALLOW_IMAGE_ANALYSIS": "1", - }, - clear=False, - ), - mock.patch.object(module, "_reply_turn_hold_reason", return_value=None), - mock.patch.object(module, "privacy_attestation_current", return_value=True), - mock.patch.object(module, "runner_is_trusted", return_value=True), - mock.patch.object(module, "fetch_link_previews", return_value=[]), - mock.patch.object( - module, - "run_context_reply_bundle", - return_value={ - "context": [], - "styles": [], - "prior_decisions": [], - "style_profile": None, - "recipient_style_profile": None, - "response_time": self._timing_stats(module), - }, - ), - self._fake_mlx_gateway( - module, - json.dumps(response, ensure_ascii=False), - model_id=module.QWEN38_27B_MODEL_ID, - ) as gateway, - mock.patch.object(module, "_run_bounded_process") as process_runner, - mock.patch.object( - module, - "generate_reply", - side_effect=generate_after_images_become_unreadable, - ), - ): - result = module.analyze_event(event) + result, payloads = self._analyze_with_mlx_gateway( + module, event, response, before_generate=make_images_unreadable + ) finally: for path in media["paths"]: if path.exists(): path.chmod(0o600) - self.assertEqual(gateway["payloads"], []) - gateway["external_urlopen"].assert_not_called() - process_runner.assert_not_called() - self.assertEqual(result["decision"], "reply") - self.assertEqual( - result["reply"], "사진 내용을 확인하지 못했어. 필요한 부분은 글로 알려줘" + self.assertEqual(payloads, []) + self.assertEqual(self._model_failures(module, vision_fallback), 0) + self.assertTrue(module._acquire_model_call_slot(model=vision_fallback)["allowed"]) + self.assertEqual(self._model_failures(module, image_model), 1) + self.assertEqual((result["decision"], result["reason"]), + ("reply", module.MEDIA_UNAVAILABLE_CLARIFICATION_REASON)) + self.assertEqual( + result["reply"], "사진 내용을 확인하지 못했어. 필요한 부분은 글로 알려줘" + ) + self._assert_presend_accepts(module, event, result["reply"]) + + def test_text_turn_whose_recent_photos_do_not_load_is_still_answered(self): + with tempfile.TemporaryDirectory(dir=Path.home()) as temporary: + module, _runner = self._load_trusted_codex_module( + "auto_reply_text_turn_unloadable_photo_test", Path(temporary) + ) + now = int(time.time()) + with self._owned_image_bundle(module, count=1, message_type=2) as media: + photo = self._burst_event( + module, 904, "사진", now - 30, message_type=2, attachment=True ) - reasons = [] - self.assertTrue( - module._policy_valid_draft( - result["reply"], - event["message"], - module._event_recent_conversation(event), - recipient=module._event_author_nickname(event), - reasons_out=reasons, - ), - reasons, + event = self._burst_event( + module, + 905, + "이거 어디서 샀어?", + now, + recent=[self._recent_row(photo)], + ) + self.assertEqual( + [row["log_id"] for row in module._same_author_recent_photo_events(event)], + [904], ) + response = { + "should_reply": True, + "reply": "다이소에서 샀어", + "category": "social", + "reason": "answer", + "evidence_ids": [], + } + + def make_images_unreadable(): + for path in media["paths"]: + path.chmod(0o000) + + try: + result, payloads = self._analyze_with_mlx_gateway( + module, + event, + response, + before_generate=make_images_unreadable, + recovered_media={904: list(media["paths"])}, + ) + finally: + for path in media["paths"]: + if path.exists(): + path.chmod(0o600) + + self.assertEqual( + (result["decision"], result["reply"]), ("reply", "다이소에서 샀어") + ) + self.assertEqual(len(payloads), 1) + content = payloads[0]["messages"][1]["content"] + self.assertIsInstance(content, str) + self.assertIn("사진을 읽지 못했습니다", content) def test_gjc_generate_reply_sends_prompt_on_stdin_with_at_images(self): with tempfile.TemporaryDirectory(dir=Path.home()) as temporary: From 0d435856928a2a0cd19a5e3a6416b59b768c4faa Mon Sep 17 00:00:00 2001 From: Yeonwoo Choi <32544727+twoimo@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:50:20 +0900 Subject: [PATCH 07/11] =?UTF-8?q?fix(auto-reply):=20reject=20the=20?= =?UTF-8?q?=EB=8F=BC=20spellings=20of=20a=20confusion=20reply?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The matcher took only 되, so "이해가 안 돼", "이해가 안 돼요" and the common misspellings "안 되요" and "안 돼네" went out as valid drafts. Co-Authored-By: Claude Opus 5.5 --- scripts/auto-reply-worker.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/auto-reply-worker.py b/scripts/auto-reply-worker.py index 1b8f5d7b..9080077d 100755 --- a/scripts/auto-reply-worker.py +++ b/scripts/auto-reply-worker.py @@ -6775,7 +6775,7 @@ def _is_contextless_confusion_reply(reply: str) -> bool: return bool( re.fullmatch( r"(?:무슨|뭔)(?:말|뜻|소리)인지모르겠(?:네요|어요|네|어)?|" - r"(?:잘)?이해가(?:잘)?안되(?:네요|어요|네|어)?", + r"(?:잘)?이해가(?:잘)?안(?:되(?:네요|어요|네|어|요)?|돼(?:네요|요|네)?)", compact, ) ) From 17086964f65061ae6a856fb8695557f222fab3bb Mon Sep 17 00:00:00 2001 From: Yeonwoo Choi <32544727+twoimo@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:51:28 +0900 Subject: [PATCH 08/11] test(auto-reply): a text turn never gets the photo apology A text turn carrying more context photos than the image cap gets image_unavailable from generate_reply before any request. analyze_event answered it with the photo apology, which is only for a photo turn. Co-Authored-By: Claude Opus 5.5 --- tests/test_auto_reply_cli_runtime.py | 38 ++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/tests/test_auto_reply_cli_runtime.py b/tests/test_auto_reply_cli_runtime.py index 342031e3..50af8ae8 100644 --- a/tests/test_auto_reply_cli_runtime.py +++ b/tests/test_auto_reply_cli_runtime.py @@ -16126,6 +16126,44 @@ def make_images_unreadable(): self.assertIsInstance(content, str) self.assertIn("사진을 읽지 못했습니다", content) + def test_text_turn_never_gets_the_photo_apology_for_context_photos(self): + with tempfile.TemporaryDirectory(dir=Path.home()) as temporary: + module, _runner = self._load_trusted_codex_module( + "auto_reply_text_turn_photo_cap_test", Path(temporary) + ) + now = int(time.time()) + count = module.MAX_IMAGE_INPUTS + 1 + with self._owned_image_bundle(module, count=count, message_type=27) as media: + photo = self._burst_event( + module, 906, "사진", now - 30, message_type=27, attachment=True + ) + event = self._burst_event( + module, + 907, + "이거 어디서 샀어?", + now, + recent=[self._recent_row(photo)], + ) + response = { + "should_reply": True, + "reply": "다이소에서 샀어", + "category": "social", + "reason": "answer", + "evidence_ids": [], + } + result, payloads = self._analyze_with_mlx_gateway( + module, + event, + response, + before_generate=lambda: None, + recovered_media={906: list(media["paths"])}, + ) + + self.assertEqual(payloads, []) + self.assertEqual(result["reason"], "image_unavailable") + self.assertNotEqual(result["decision"], "reply") + self.assertEqual(result["reply"], "") + def test_gjc_generate_reply_sends_prompt_on_stdin_with_at_images(self): with tempfile.TemporaryDirectory(dir=Path.home()) as temporary: root = Path(temporary) From 8f56f1a37581d08c07473f12da5a57f9ca621774 Mon Sep 17 00:00:00 2001 From: Yeonwoo Choi <32544727+twoimo@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:51:28 +0900 Subject: [PATCH 09/11] fix(auto-reply): answer a text turn whose context photos do not load MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit For a text message, analyze_event attaches the same author's recent photos. When those files could not be read, the runner refused to send and the turn got "사진 내용을 확인하지 못했어" instead of an answer. The runner now refuses only when the turn itself is the photo. For a text turn it sends main's text request with the note that the photos could not be read, and analyze_event keeps the photo apology for photo turns. Co-Authored-By: Claude Opus 5.5 --- scripts/auto-reply-worker.py | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/scripts/auto-reply-worker.py b/scripts/auto-reply-worker.py index 9080077d..46a3759e 100755 --- a/scripts/auto-reply-worker.py +++ b/scripts/auto-reply-worker.py @@ -11762,6 +11762,7 @@ def _run_opencodex_generation_unleased( prompt_bytes: bytes, *, image_paths: list[Path] | None = None, + images_required: bool = True, timeout: float = 30.0, base_url: str = "http://127.0.0.1:11234/v1", ) -> tuple[int, bytes, bytes]: @@ -11841,11 +11842,21 @@ def _run_opencodex_generation_unleased( file=sys.stderr, flush=True, ) - if len(user_parts) == 1: - # Every image failed to load. A text-only request lets the model - # answer about a photo it never saw, whatever the prompt says. + if len(user_parts) > 1: + payload["messages"][1]["content"] = user_parts + elif images_required: + # Every image of a photo turn failed to load. A text-only request + # lets the model answer about a photo it never saw, whatever the + # prompt says. return 1, b"", IMAGE_INPUT_UNAVAILABLE - payload["messages"][1]["content"] = user_parts + else: + # The images were only earlier context for a text turn, so answer + # the text and tell the model the photos could not be read. + payload["messages"][1]["content"] = ( + user_content + + "\n\n[첨부한 사진을 읽지 못했습니다. 사진 내용을 모르는 상태이므로," + + " 사진에 대해 추측하지 말고 사진을 다시 보내 달라고 답하세요.]" + ) data = json.dumps(payload, ensure_ascii=False).encode("utf-8") session_lane = "openkakao-bujamentor" session_digest = hashlib.sha256( @@ -11897,6 +11908,7 @@ def _run_opencodex_generation( prompt_bytes: bytes, *, image_paths: list[Path] | None = None, + images_required: bool = True, timeout: float = 30.0, base_url: str = "http://127.0.0.1:11234/v1", ) -> tuple[int, bytes, bytes]: @@ -11908,6 +11920,7 @@ def _run_opencodex_generation( system_prompt, prompt_bytes, image_paths=image_paths, + images_required=images_required, timeout=timeout, base_url=base_url, ) @@ -11918,6 +11931,7 @@ def _run_opencodex_generation( system_prompt, prompt_bytes, image_paths=image_paths, + images_required=images_required, timeout=timeout, base_url=base_url, ) @@ -11933,6 +11947,7 @@ def _run_generation_candidate( env: dict[str, str], model_stdin_bytes: bytes | None, image_paths: list[Path] | None, + images_required: bool = True, timeout: float, ) -> tuple[int, bytes, bytes]: if not _product_local_model_allowed(model): @@ -11945,6 +11960,7 @@ def _run_generation_candidate( system_prompt, prompt_bytes, image_paths=image_paths, + images_required=images_required, timeout=timeout, ) return _run_bounded_process( @@ -12439,6 +12455,7 @@ def run_fallback_candidate(candidate: str) -> tuple[int, bytes, bytes]: env=env, model_stdin_bytes=model_stdin_bytes, image_paths=normalized_image_paths, + images_required=attachment == "image", timeout=_model_generation_timeout(candidate, deadline=generation_deadline), ) @@ -12591,6 +12608,7 @@ def continue_on_fallback( env=env, model_stdin_bytes=model_stdin_bytes, image_paths=normalized_image_paths, + images_required=attachment == "image", timeout=_model_generation_timeout(active_model, deadline=generation_deadline), ) if returncode != 0 and stderr_bytes == IMAGE_INPUT_UNAVAILABLE: @@ -14593,7 +14611,7 @@ def analyze_event(event: dict) -> dict: "prompt_evidence_ids": model.get("prompt_evidence_ids"), "generation_seconds": model.get("generation_seconds"), } - if image_paths and str(model.get("reason") or "") == "image_unavailable": + if attachment == "image" and str(model.get("reason") or "") == "image_unavailable": # No image could be shown to the model, so no request was sent. # An authorized sender still gets an answer, one that admits it. provenance["model_invoked"] = False From b702efa046e4df751aa4cb529cbd0942d1a116b5 Mon Sep 17 00:00:00 2001 From: Yeonwoo Choi <32544727+twoimo@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:52:39 +0900 Subject: [PATCH 10/11] fix(auto-reply): never charge a fallback for a request it never sent With the image model in cooldown, the fallback chain ran a vision candidate whose images would not load. It sent nothing and returned image_input_unavailable, which the chain classified as runner_failed. A healthy model went into cooldown and the turn was deferred. That candidate now ends the chain with its lease open. generate_reply checks for an unsent request once, after every fallback branch, and releases whichever lease is current without a failure, so the turn gets the honest photo reply. The primary's own unsent request still skips the chain, now pinned by asserting no fallback model is charged. Co-Authored-By: Claude Opus 5.5 --- scripts/auto-reply-worker.py | 19 ++++++++++++------- tests/test_auto_reply_cli_runtime.py | 2 ++ 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/scripts/auto-reply-worker.py b/scripts/auto-reply-worker.py index 46a3759e..13d7144c 100755 --- a/scripts/auto-reply-worker.py +++ b/scripts/auto-reply-worker.py @@ -11660,6 +11660,10 @@ def _model_fallback_chain( keeps a fallback that answered from being reported as circuit_unavailable and deferred anyway. Returns None when no candidate could run, and never raises: one broken candidate is skipped instead of ending the turn (2026-09-15). + + A candidate that sent nothing because no image loaded also ends the chain, + with its lease still open: every later candidate would get the same missing + images, and the caller releases that lease without charging a failure. """ for candidate in _reply_fallback_candidates(): @@ -11689,7 +11693,7 @@ def _model_fallback_chain( flush=True, ) continue - if returncode != 0: + if returncode != 0 and stderr_bytes != IMAGE_INPUT_UNAVAILABLE: failure_class, retry_after = _classify_model_failure( returncode, stdout_bytes, @@ -12611,12 +12615,7 @@ def continue_on_fallback( images_required=attachment == "image", timeout=_model_generation_timeout(active_model, deadline=generation_deadline), ) - if returncode != 0 and stderr_bytes == IMAGE_INPUT_UNAVAILABLE: - # No request was sent, so the model is not at fault and another - # model would get the same missing images. - _release_unsent_model_call(lease_token, active_model) - return with_prompt_receipt({**empty, "reason": "image_unavailable"}) - if returncode != 0: + if returncode != 0 and stderr_bytes != IMAGE_INPUT_UNAVAILABLE: err_str = stderr_bytes.decode("utf-8", "replace").casefold() failure_class, _ = _classify_model_failure( returncode, @@ -12724,6 +12723,12 @@ def continue_on_fallback( continue_on_fallback( winner, "opencode_go_quota_fallback", first_class, first_retry ) + if returncode != 0 and stderr_bytes == IMAGE_INPUT_UNAVAILABLE: + # No request was sent, by the primary or by the fallback adopted above, + # so that model is not at fault, and another one would get the same + # missing images. + _release_unsent_model_call(lease_token, active_model) + return with_prompt_receipt({**empty, "reason": "image_unavailable"}) held = turn_hold() if held: diff --git a/tests/test_auto_reply_cli_runtime.py b/tests/test_auto_reply_cli_runtime.py index 50af8ae8..82536d4e 100644 --- a/tests/test_auto_reply_cli_runtime.py +++ b/tests/test_auto_reply_cli_runtime.py @@ -15880,6 +15880,8 @@ def test_generate_reply_sends_no_request_when_no_image_loads(self): self.assertEqual(result["reason"], "image_unavailable") self.assertEqual(failures[0], 1) self.assertTrue(circuit["allowed"], circuit) + for fallback in module._reply_fallback_candidates(): + self.assertEqual(self._model_failures(module, fallback), 0, fallback) def _analyze_with_mlx_gateway( self, module, event, response, *, before_generate, recovered_media=None From 42bded1a5cc7f4d8b1b3911f2da20d4fb8c59fe3 Mon Sep 17 00:00:00 2001 From: Yeonwoo Choi <32544727+twoimo@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:55:04 +0900 Subject: [PATCH 11/11] test(auto-reply): accept images_required in the fake generation candidate The retrieval-command test replaces _run_generation_candidate with a fake that mirrors its signature. 8f56f1a added images_required there. Co-Authored-By: Claude Opus 5.5 --- tests/test_auto_reply_turn_holds.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_auto_reply_turn_holds.py b/tests/test_auto_reply_turn_holds.py index 7d871d0c..466b68f6 100644 --- a/tests/test_auto_reply_turn_holds.py +++ b/tests/test_auto_reply_turn_holds.py @@ -944,6 +944,7 @@ def fake_generation_candidate( env, model_stdin_bytes, image_paths, + images_required, timeout, ): captured["model"] = model