2 Commits
Author SHA1 Message Date
onibot cc1eceb720 Merge pull request 'floop: INIT told placeholders are resolved + identity seed' (#17) from feature/init-resolved-placeholders into main 2026-10-22 17:03:53 +02:00
onibot 4766b47127 floop: INIT told placeholders are resolved + identity seed (his design)
His two-part direction after the PR-16 live run (the model spent a
subquestion asking 'who is PERSON_1?'):

1. INIT desc now says masked entities (PERSON_1, ORGANIZATION_1...) are
   ALREADY-RESOLVED named entities — treat each as a known specific
   entity; do not ask what or who the placeholder is.
2. Safety net: identity_answer() detects a subquestion that ONLY asks
   who/what one placeholder refers to — the mask map already knows. The
   machine seeds it as evidence (engine=mask:seed, verified, zero LLM
   calls) instead of routing it to an expert.

Detection is deterministic and conservative by law: exactly one
placeholder in the text, literal 'who/what is <ph>' (ending there or in
punctuation — possessives like 'who is PERSON_1's predecessor' do NOT
match) or the text names the mask mechanism. Detection runs on the
MASKED text (placeholders still present) before restore.

VERIFIED: tests/anonymize.py 6/6 (seed marking, conservative detection
incl. possessives/comparatives/no-placeholder forms); suite 15/15.
Live E2E (glm-5.3-flash): with the new desc INIT returns exactly the
TWO subquestions he wants (term years + predecessor) — no identity
question, seed unused but armed; run answers Rajoy (E1+E2, 30 calls).
2026-10-22 17:03:44 +02:00
4 changed files with 99 additions and 6 deletions
+33 -1
View File
@@ -9,6 +9,8 @@ LLMs translate (NER proposal); fixed code applies and restores (ALGORITHM
"""
from __future__ import annotations
import re
import dspy
from pydantic import BaseModel
@@ -64,4 +66,34 @@ def restore_mask(text: str, restore: dict[str, str]) -> str:
for ph, name in sorted(restore.items(), key=lambda kv: len(kv[0]),
reverse=True):
text = text.replace(ph, name)
return text
return text
# an identity question about ONE placeholder — the model asking who/what
# the mask refers to. Detection lives in identity_answer: conservative
# by law (his: never over-detect) — 'who/what is <ph>' exactly, or the
# text names the mask mechanism ('placeholder', 'refer(s) to').
def identity_answer(masked_text: str, restore: dict[str, str]) -> str | None:
"""If a subquestion only asks who/what one placeholder refers to, the
answer is the mask map itself — no expert ever needed. None otherwise.
Conservative by law (never over-detect): exactly one placeholder in
the text, and the question is literally 'who/what is <ph>' (ending
there or in punctuation — 'who is PERSON_1's predecessor' does NOT
match) or it names the mask mechanism ('placeholder', 'refer(s) to')."""
phs = [ph for ph in restore if re.search(rf"\b{re.escape(ph)}\b",
masked_text)]
if len(phs) != 1:
return None
ph = phs[0]
t = masked_text.strip()
literal = re.match(
rf"^(?:who|what)\s+(?:is|are)\s+{re.escape(ph)}(?=$|[\s,.?!:;)\"'])",
t, flags=re.IGNORECASE)
mechanism = any(k in t.casefold() for k in
("placeholder", "refer to", "refers to"))
if literal or mechanism:
return restore[ph]
return None
+17 -4
View File
@@ -19,7 +19,8 @@ try:
except ImportError: # pragma: no cover — dspy <3.x
AdapterParseError = type("AdapterParseError", (Exception,), {"lm_response": ""})
from .anonymize import EntityMaskSignature, apply_mask, restore_mask
from .anonymize import (EntityMaskSignature, apply_mask, identity_answer,
restore_mask)
class Subquestion(BaseModel):
@@ -36,7 +37,10 @@ class InitSignature(dspy.Signature):
"""You are the INIT step of a reasoning machine. Using ONLY concepts literally
present in the question plus a generic planning scaffold (number, method,
machine, resources, dependencies), ask: what information or knowledge do I
need to answer this? Write 1-4 open subquestions in dependency order."""
need to answer this? Write 1-4 open subquestions in dependency order.
Masked entities like PERSON_1 or ORGANIZATION_1 are ALREADY-RESOLVED
named entities from the question — treat each as a known specific entity;
do not ask what or who the placeholder is."""
question: str = dspy.InputField()
subquestions: list[Subquestion] = dspy.OutputField(
desc="1-4 subquestions in dependency order; empty when the question is atomic")
@@ -137,7 +141,10 @@ class FloopModules:
ANONYMIZATION (his design): named entities are masked before INIT
so the model decomposes shape, not identity — restored in the
returned subquestions, deterministically."""
returned subquestions, deterministically. Identity questions about
the placeholders (PR-16 live run: 'who is PERSON_1?') carry a
KNOWN answer; the machine seeds them as evidence instead of
routing them to an expert."""
masked, restore = self.anonymize(question)
try:
pred = self.init(question=masked)
@@ -145,7 +152,13 @@ class FloopModules:
return [], (e.lm_response or "unparseable response")
subs = []
for s in self._subs_from_typed(pred.subquestions):
subs.append({**s, "text": restore_mask(s["text"], restore)})
# identity detection on the MASKED text (placeholders still
# present); then restore for the machine's question text
ans = identity_answer(s["text"], restore)
text = restore_mask(s["text"], restore)
if ans is not None:
s = {**s, "known_answer": ans} # seeded by the machine
subs.append({**s, "text": text})
return subs, ""
def anonymize(self, question: str) -> tuple[str, dict]:
+14
View File
@@ -192,6 +192,20 @@ class FloopRun:
if isinstance(tok, int) and 1 <= tok <= len(created):
resolved.append(created[tok - 1].qid)
q.deps = resolved
# anonymization seeds (his design): identity questions the mask map
# already answers land as evidence NOW — zero LLM calls
for q, s in zip(created, subs):
if s.get("known_answer"):
self.table.append(EvidenceRow(
qid=q.qid, answer_type=q.answer_type,
payload={"value": s["known_answer"],
"quote": f"{s['known_answer']} — named in the question itself"},
engine="mask:seed", trace=["anonymization: placeholder resolved from the mask map"],
provenance={}, verified=True))
q.status = "answered"
q.reason = "identity seeded from the mask map"
self.notes.append(
f"{q.qid}: seeded from anonymization — no expert call needed")
# ---- fan-out (the planner's expansion; deterministic guard) --------------
+35 -1
View File
@@ -26,7 +26,7 @@ from dspy._vendor.lm15 import Response, TextPart, Message, Usage
from dspy.utils.exceptions import AdapterParseError
from floop.dspy_modules import FloopModules
from floop.anonymize import NamedEntity, apply_mask, restore_mask
from floop.anonymize import NamedEntity, apply_mask, identity_answer, restore_mask
def _lm(script: list[str]) -> None:
@@ -95,6 +95,38 @@ def test_no_entities_passthrough():
print("ok: no entities found -> question reaches INIT unchanged")
_TWO_SUBS_ID = '''[[ ## subquestions ## ]]
[{"text": "Who is PERSON_1, i.e., which specific individual does the placeholder refer to?", "depends_on": [], "answer_type": "OPEN"},
{"text": "Which office does PERSON_1 hold as President?", "depends_on": [1], "answer_type": "OPEN"},
{"text": "Who held that office before PERSON_1?", "depends_on": [2], "answer_type": "OPEN"}]
[[ ## completed ## ]]'''
def test_identity_subquestion_seeded():
# the live PR-16 shape: subquestion 1 asks who PERSON_1 is — the mask
# map already knows. It must come back marked known_answer, never routed.
_lm([_MASKED_ENTS, _TWO_SUBS_ID])
subs, _ = FloopModules().init_decompose(Q)
assert len(subs) == 3, subs
assert subs[0].get("known_answer") == "Pedro Sanchez", subs[0]
assert not subs[1].get("known_answer") and not subs[2].get("known_answer")
print("ok: identity subquestion carries known_answer (never routed)")
def test_identity_detection_conservative():
# 'who is PERSON_1's predecessor' is NOT an identity question
r = {"PERSON_1": "Pedro Sanchez"}
assert identity_answer("Who is PERSON_1?", r) == "Pedro Sanchez"
assert identity_answer("What is ORGANIZATION_1?", {"ORGANIZATION_1": "PSOE"}) == "PSOE"
assert identity_answer("Which specific individual does the placeholder refer to?", r) is None
assert identity_answer("Who is PERSON_1, i.e., which specific individual does the placeholder refer to?", r) == "Pedro Sanchez"
assert identity_answer("Who was PERSON_1's predecessor?", r) is None
assert identity_answer("What office does PERSON_1 hold?", r) is None
assert identity_answer("Who is PERSON_1 compared to PERSON_2?", {**r, "PERSON_2": "x"}) is None
print("ok: identity detection conservative (possessives/comparatives not eaten)")
def test_mask_death_passthrough():
# MASK response violates the schema -> AdapterParseError -> passthrough
_lm(["garbage", _TWO_SUBS.replace("PERSON_1", "Pedro Sanchez")])
@@ -107,5 +139,7 @@ if __name__ == "__main__":
test_apply_restore_deterministic()
test_init_decompose_masks_and_restores()
test_no_entities_passthrough()
test_identity_subquestion_seeded()
test_identity_detection_conservative()
test_mask_death_passthrough()
print("\nanonymization tests passed")