His branching design (22-23/10, consolidated; now coded): when an expert returns SEVERAL defensible readings of one question (the knowledge ablation audit's ambiguous + alternatives payload), a question that DEPENDS on that row must not inherit the coin-flip. The old behaviour: alternatives were passed in the router context (rejected — it only moves the guess into answer_kg) or collapsed inside the ANSWER prompt (run L: 'Papandreou was the predecessor' — the exact rejected behaviour). The mechanism (floop/branches.py + machine._run_branch): - LAZY: a branch is born only when the ambiguous row has an OPEN dependent subtree (open_subtree, frozen at fork time so every branch of the fork copies the same questions); an ambiguity nobody needs stays a note. - A branch is a WORLD, not a fork of the run: the dependent subtree is re-created inside the branch with branch-scoped qids (B1.Q2), and the shared evidence table is read through a BranchView that BINDS the ambiguous row to the branch's reading (a VIEW — the table is never mutated, the original row keeps all readings) and hides other branches' rows. - SHARED: acquired knowledge lands in the ONE table, tagged provenance['branch']; the KG/seen-index live in the expert, shared by construction. A later branch reuses an earlier one's gathering. - DEATH: by contradiction, dead end (all branch questions failed) or NATURAL MERGE (same normalized answer as another branch — one conclusion, recorded merged). Never an absurdity judge. - NESTING: an ambiguous row answered inside a branch (with its own dependent) opens sub-branches under it (origin=<branch id>); the parent carries its children's conditional as its answer. Branch cap (6) drops and NAMES extra readings — never silent. - CONDITIONAL ANSWER: _finish composes the final answer by FIXED CODE over surviving branches — 'if you meant X -> A | if you meant Y -> B'; single survivor renders plain. Never a synthesis prompt choosing a reading inside itself. - WARNINGS: FORK/BRANCH lines on screen AND log ([W]) — the fork is a machine judgement worth a human's eye, and META's lessons bank counts them. Docs: ALGORITHM.md §6-bis (the mechanism as a law); README honest map row. Tests: tests/branches.py — 5 E2E (fork+conditional, lazy no-fork, dead-branch honesty, natural merge, nested sub-branches). Suite 18/18. Live smoke (ollama-cloud, warm agent KG): the Pedro question runs clean through the new paths (8 calls, 52s, honest answer; the fork did not fire — the audit found no second reading in that KG; the mechanism is proven by the E2E tests, the real-detector proof is his local run over his accumulated KG).
319 lines
14 KiB
Python
319 lines
14 KiB
Python
"""Execution branches (his branching design, 22-23/10 — now coded).
|
|
|
|
When an expert answers a question with SEVERAL defensible readings
|
|
(payload['ambiguous'] + alternatives, the knowledge expert's ablation
|
|
audit), the machine does NOT hand the alternatives to the next
|
|
subquestion's context (the rejected design — it only moves the
|
|
coin-flip into answer_kg) and does NOT collapse them inside ANSWER
|
|
(run L: 'Papandreou was the predecessor' — the exact rejected
|
|
behaviour). Instead, when a question DEPENDS on an ambiguous row, the
|
|
machine opens ONE LAZY EXECUTION BRANCH PER READING:
|
|
|
|
- a branch is a machine-level construct at floop DEPTH+1-like nesting,
|
|
but INSIDE this run: it owns its question stack and reads the
|
|
evidence through a BranchView that BINDS the ambiguous row to ONE
|
|
reading (a VIEW, never a store mutation — the same law as the
|
|
ablation mask);
|
|
- LAZY: the branch is born only when a dependent of the ambiguous row
|
|
becomes pickable — until then, nothing forks;
|
|
- SHARED: the knowledge acquired by every branch lands in the ONE
|
|
evidence table (the machine's working memory) and the KG/seen-index
|
|
live in the expert, shared by construction — a later branch reuses
|
|
what an earlier one gathered for free;
|
|
- per-branch is the READING of the ambiguous row + the subquestions
|
|
born under it; branch id rides every row's provenance;
|
|
- a branch DIES only by contradiction (its checked arrival refusing a
|
|
value), dead end (its terminal questions all failed — honest
|
|
UNKNOWN), or NATURAL MERGE (its answers converge with another
|
|
branch's — dedupe by value, keep the first) — never by an absurdity
|
|
judge (surprising-but-cited answers render, they are not
|
|
pocket-judged);
|
|
- the final answer is CONDITIONAL over surviving branches, composed
|
|
by FIXED CODE from the branch results — 'si et referies a president
|
|
d'Espanya -> Rajoy; si SI -> Papandreou; si PSOE -> qui sigui' —
|
|
never one reading chosen inside a synthesis prompt;
|
|
- nested ambiguity: a branch that hits its OWN ambiguous row forks
|
|
sub-branches under the same mechanism and the same caps.
|
|
|
|
Open by design (layer 3, a policy ABOVE this mechanism): asking the
|
|
user instead of running all branches = picking one branch upstairs.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
from dataclasses import dataclass, field
|
|
from typing import TYPE_CHECKING
|
|
|
|
if TYPE_CHECKING:
|
|
from .state import EvidenceRow, EvidenceTable
|
|
|
|
# a branch result that is honestly nothing: dead end / contradiction /
|
|
# everything failed. The conditional render skips it (the branch's death
|
|
# is already in the notes), it never masquerades as an answer reading.
|
|
DEAD_END = "UNKNOWN"
|
|
|
|
|
|
def _norm(v: str) -> str:
|
|
"""Merge/dedupe key: casefolded alphanumerics (norm_name's machine-level
|
|
cousin — 'Rajoy' == 'rajoy', 'Pedro Sánchez' == 'Pedro Sanchez')."""
|
|
return re.sub(r"[^a-z0-9]+", " ", (v or "").casefold()).strip()
|
|
|
|
|
|
@dataclass
|
|
class BranchSpec:
|
|
"""One reading of one ambiguous row. The branch binds the row to
|
|
value; reading is the human-legible label ('as President of Spain')."""
|
|
id: str
|
|
ambiguous_eid: str
|
|
ambiguous_qid: str
|
|
value: str # the reading this branch binds
|
|
reading: str # label for the conditional render
|
|
origin: str = "" # the id of the branch that forked this one ("" = root)
|
|
# the open dependent SUBTREE copied into every branch of this fork,
|
|
# frozen at fork time (B1 consuming the originals must not change
|
|
# what B2 copies — the qids in qid order, deps rewired per branch)
|
|
subtree_qids: list[str] = field(default_factory=list)
|
|
|
|
|
|
@dataclass
|
|
class BranchResult:
|
|
"""What a branch concluded, for the conditional render."""
|
|
spec: BranchSpec
|
|
answer: str = "" # the branch's final answer (synthesized inside it)
|
|
status: str = "open" # open | answered | dead | merged
|
|
|
|
|
|
class BranchView:
|
|
"""The evidence table AS ONE BRANCH SEES IT.
|
|
|
|
The shared table is untouched — the ambiguous row is REPLACED in
|
|
this view by a synthetic row binding the branch's reading (same
|
|
qid, same answer_type, the reading's own quote/url, verified as
|
|
its source rows were — the reading IS the expert's pick or one of
|
|
its alternatives, each carried with quote+url by the audit). Rows
|
|
from other branches (provenance['branch'] set and different) are
|
|
HIDDEN: they answer questions that never existed in this world.
|
|
|
|
Everything else (rows with no branch tag, rows this branch appended)
|
|
passes through unchanged — acquired knowledge is shared.
|
|
"""
|
|
|
|
def __init__(self, table: "EvidenceTable", spec: BranchSpec) -> None:
|
|
self._table = table
|
|
self._spec = spec
|
|
|
|
def _bound_row(self) -> "EvidenceRow":
|
|
from .state import EvidenceRow
|
|
src = self._table.row(self._spec.ambiguous_eid)
|
|
payload = {k: v for k, v in (src.payload or {}).items()
|
|
if k not in ("ambiguous", "alternatives")}
|
|
payload["value"] = self._spec.value
|
|
payload["quote"] = self._reading_quote()
|
|
payload["branch_binding"] = True # the branch-fake's marker: this
|
|
# row IS the bound reading
|
|
if self._spec.origin:
|
|
payload["branch_reading"] = self._spec.reading
|
|
return EvidenceRow(
|
|
qid=src.qid, answer_type=src.answer_type, payload=payload,
|
|
engine=src.engine + ":branch-bind",
|
|
trace=[f"branch {self._spec.id}: ambiguous row bound to reading "
|
|
f"'{self._spec.value}'"],
|
|
provenance=dict(src.provenance, branch=self._spec.id),
|
|
verified=src.verified, note="")
|
|
|
|
def _reading_quote(self) -> str:
|
|
"""The reading's OWN quote when the row carries alternatives with
|
|
quotes; else the picked answer's quote (branch = the pick)."""
|
|
src = self._table.row(self._spec.ambiguous_eid)
|
|
for a in (src.payload.get("alternatives") or []):
|
|
if _norm(a.get("value", "")) == _norm(self._spec.value) and a.get("quote"):
|
|
return a["quote"]
|
|
return str(src.payload.get("quote", ""))
|
|
|
|
# -- the EvidenceTable interface the machine reads ---------------------
|
|
def row(self, eid: str) -> "EvidenceRow | None":
|
|
if eid == self._spec.ambiguous_eid:
|
|
return self._bound_row()
|
|
r = self._table.row(eid)
|
|
if r is not None and self._hidden(r):
|
|
return None
|
|
return r
|
|
|
|
def append(self, row: "EvidenceRow") -> "EvidenceRow":
|
|
"""A branch's new rows land in the SHARED table (acquired knowledge
|
|
is shared — a later branch reuses them) tagged with the branch id
|
|
(other branches' views hide them until they merge)."""
|
|
row.provenance["branch"] = self._spec.id
|
|
return self._table.append(row)
|
|
|
|
def rows(self) -> "list[EvidenceRow]":
|
|
return ([self._bound_row()] if self._bound_row() else []) + \
|
|
[r for r in self._table.rows() if r.eid != self._spec.ambiguous_eid
|
|
and not self._hidden(r)]
|
|
|
|
def for_question(self, qid: str) -> "list[EvidenceRow]":
|
|
return [r for r in self.rows() if r.qid == qid]
|
|
|
|
def dump(self) -> str:
|
|
from .state import EvidenceTable
|
|
flat = EvidenceTable()
|
|
for r in self.rows():
|
|
flat.append(type(r)(
|
|
answer_type=r.answer_type, payload=dict(r.payload),
|
|
engine=r.engine, qid=r.qid, trace=list(r.trace),
|
|
provenance=dict(r.provenance), verified=r.verified,
|
|
note=r.note, retracted=r.retracted))
|
|
return flat.dump()
|
|
|
|
def _hidden(self, r: "EvidenceRow") -> bool:
|
|
b = r.provenance.get("branch")
|
|
return bool(b) and b != self._spec.id
|
|
|
|
|
|
@dataclass
|
|
class BranchManager:
|
|
"""The fork bookkeeping. The machine asks 'should I fork on this row?'
|
|
(is it ambiguous AND does an open question depend on it), gets one
|
|
BranchSpec per reading, executes branches lazily, and renders the
|
|
surviving results conditionally.
|
|
|
|
The manager holds no execution logic — the machine runs each branch
|
|
as a plain FloopRun loop over its own stack; the manager owns the
|
|
specs, the merge policy, and the conditional render.
|
|
"""
|
|
max_branches: int = 6
|
|
specs: list[BranchSpec] = field(default_factory=list)
|
|
results: dict[str, BranchResult] = field(default_factory=dict)
|
|
dropped: list[str] = field(default_factory=list)
|
|
|
|
@property
|
|
def pending(self) -> list[BranchSpec]:
|
|
"""Specs not yet executed (FIFO — the picked reading runs first)."""
|
|
return [s for s in self.specs
|
|
if self.results.get(s.id) is None
|
|
or self.results[s.id].status == "open"]
|
|
|
|
def fork_specs(self, row: "EvidenceRow", origin: str = "",
|
|
subtree_qids: list[str] | None = None) -> list[BranchSpec]:
|
|
"""One spec per defensible reading of an ambiguous row whose open
|
|
dependent subtree (computed by the caller, frozen here) is non-
|
|
empty. LAZY LAW: an empty subtree means no fork — the ambiguity
|
|
is noted, the run continues on the pick.
|
|
`origin`: the branch we are inside when the fork fires ("" = the
|
|
root run) — nested ambiguity nests sub-branches under it.
|
|
Branch cap: past max_branches live specs, the extra readings are
|
|
dropped and NAMED (never silent)."""
|
|
if not row.payload.get("ambiguous"):
|
|
return []
|
|
alts = row.payload.get("alternatives") or []
|
|
readings = [(row.payload.get("value", ""), "the picked reading")]
|
|
readings += [(a.get("value", ""), a.get("value", ""))
|
|
for a in alts if a.get("value")]
|
|
specs = []
|
|
for i, (val, label) in enumerate(readings):
|
|
if not val or str(val).upper() == "UNKNOWN":
|
|
continue
|
|
bid = f"B{len(self.specs) + len(specs) + 1}"
|
|
spec = BranchSpec(
|
|
id=bid, ambiguous_eid=row.eid, ambiguous_qid=row.qid,
|
|
value=str(val),
|
|
reading=label if label and label != val else f"reading {bid}",
|
|
origin=origin,
|
|
subtree_qids=list(subtree_qids or []))
|
|
specs.append(spec)
|
|
if len(self.specs) + len(specs) > self.max_branches:
|
|
keep = self.max_branches - len(self.specs)
|
|
dropped = [s.reading for s in specs[keep:]]
|
|
specs = specs[:keep]
|
|
self.dropped = self.dropped + dropped
|
|
for s in specs:
|
|
self.specs.append(s)
|
|
self.results[s.id] = BranchResult(spec=s)
|
|
return specs
|
|
|
|
def record_answer(self, spec_id: str, answer: str) -> None:
|
|
res = self.results.get(spec_id)
|
|
if res is not None:
|
|
res.answer = answer
|
|
res.status = "answered"
|
|
|
|
def record_dead(self, spec_id: str) -> None:
|
|
res = self.results.get(spec_id)
|
|
if res is not None:
|
|
res.status = "dead"
|
|
|
|
def record_merge(self, spec_id: str, into: str) -> None:
|
|
res = self.results.get(spec_id)
|
|
if res is not None:
|
|
res.status = "merged"
|
|
res.answer = f"(merged with {into})"
|
|
|
|
def survivors(self, origin: str = "") -> list[BranchResult]:
|
|
"""Answered branches at one nesting level (origin), deduped by
|
|
normalized value — natural merge: two branches that concluded the
|
|
same thing are one conclusion. First-come order (the picked
|
|
reading usually leads)."""
|
|
seen: dict[str, BranchResult] = {}
|
|
order: list[BranchResult] = []
|
|
for res in self.results.values():
|
|
if res.status != "answered" or res.spec.origin != origin:
|
|
continue
|
|
key = _norm(res.answer)
|
|
if key and key in seen:
|
|
self.record_merge(res.spec.id, seen[key].spec.id)
|
|
continue
|
|
if key:
|
|
seen[key] = res
|
|
order.append(res)
|
|
return order
|
|
|
|
def conditional_answer(self, goal: str, origin: str = "") -> str:
|
|
"""The CONDITIONAL final answer, composed by FIXED CODE (run L
|
|
law: never collapse readings inside a synthesis prompt). All
|
|
surviving branch answers at one nesting level, one clause per
|
|
reading; a single survivor renders plain, its branch noted. A
|
|
branch whose own children answered carries its conditional as
|
|
its recorded answer — nesting is baked in, not re-rendered.
|
|
Dead branches are already in the notes; the render never
|
|
invents their content."""
|
|
alive = self.survivors(origin)
|
|
dropped = self.dropped
|
|
if not alive:
|
|
parts = ["No reading reached an answer."]
|
|
if dropped:
|
|
parts.append(f"(branch cap: readings dropped: {', '.join(dropped)})")
|
|
return " ".join(parts)
|
|
if len(alive) == 1:
|
|
r = alive[0]
|
|
out = f"{r.answer} (reading: {r.spec.reading})"
|
|
if dropped:
|
|
out += f" — other readings hit the branch cap: {', '.join(dropped)}"
|
|
return out
|
|
clauses = [f"if you meant {res.spec.reading} -> {res.answer}"
|
|
for res in alive]
|
|
out = " | ".join(clauses)
|
|
if dropped:
|
|
out += f" | (branch cap: {', '.join(dropped)} not run)"
|
|
return out
|
|
|
|
|
|
def open_subtree(stack, ambiguous_qid: str) -> list[str]:
|
|
"""The OPEN dependent subtree below one question: direct AND transitive
|
|
open dependents, qids in discovery order. LAZY: an empty list means
|
|
no fork — a branch is born only when someone needs the reading.
|
|
Frozen at fork time: every branch of the fork copies the SAME list
|
|
(the first branch consuming the originals must not change what the
|
|
second copies)."""
|
|
found: dict[str, str] = {} # orig qid -> branch copy qid (filled later)
|
|
order: list[str] = []
|
|
changed = True
|
|
while changed:
|
|
changed = False
|
|
for q in stack.items:
|
|
if (q.status == "open" and not q.parent_goal
|
|
and q.qid not in order
|
|
and any(d in found or d == ambiguous_qid for d in q.deps)):
|
|
order.append(q.qid)
|
|
found[q.qid] = ""
|
|
changed = True
|
|
return order |