floop v0.1: design docs + executable dspy draft
Root: README, PIPELINE, ALGORITHM, GAPS, RUNLOG (design + first executable runs). code/: v0.1 draft on dspy 3.4 (INIT/ROUTE/EXPERT/MISSING/ANSWER as dspy calls, machine as fixed code, stub engines — honest Unverified). knowledge/: DESIGN.md for the KG-first knowledge expert (pre-implementation).
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
.venv/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.pytest_cache/
|
||||
knowledge_store/
|
||||
@@ -0,0 +1,72 @@
|
||||
# FLOOP — how the machine works, in words
|
||||
|
||||
This document describes what each part of the system **does**. No schemas, no code.
|
||||
|
||||
## 0. The whole machine in one paragraph
|
||||
|
||||
FLOOP answers a question by never "thinking it through" directly. Every question is reduced to smaller questions until one is small enough for a single expert — a real tool with a deterministic engine — to answer; the answers then flow back up and are assembled into the final reply. Three kinds of parts do all the work. **The LLM** proposes: it reads, decomposes, translates between language and formal formats, and writes prose. It never decides, never computes, never asserts facts on its own authority. **The experts** answer primitive questions with tools (search, solvers, computer algebra): formalization in, typed result with trace out, no LLM inside the tool. **The machine** — plain, fixed code — keeps the list of open questions, orders them by dependency, spends the budget, handles failure, and refuses to stop until a formal check says the goal is derivable from evidence. One law runs through everything: a claim enters the state only as a typed row with provenance (a verbatim quote, a solver result, a user reply, or a marked assumption) — never as free-form model prose.
|
||||
|
||||
## 1. INIT — the opening
|
||||
|
||||
When the user's question arrives, the system makes exactly one LLM call, and that call asks one generic meta-question: **"what information or knowledge do I need to answer this?"**
|
||||
|
||||
What this call may do: read the words of the question plus a generic scaffold — is it asking for a number, a method, a comparison? What kind of thing would count as an answer? From this, and only from this, it writes a short list of **open subquestions** in dependency order — each phrased as a question, each declaring what type of answer it needs, each allowed to reference the answers of the others.
|
||||
|
||||
What this call may NOT do: use domain knowledge. If the question is about bitcoin mining and quantum computers, INIT does not know what a hash is, what Grover's algorithm is, or that time might matter. Those facts arrive later, as evidence — and they *reshape* the plan: if the answer turns out to depend on something the question never mentioned (a clock speed, a time limit), the plan discovers that mid-run instead of importing it at minute zero.
|
||||
|
||||
INIT has no engine, because INIT does not solve anything. It is the *translate* stage of the orchestrator. Its solving stage is the entire loop that follows.
|
||||
|
||||
## 2. The main loop — the machine
|
||||
|
||||
The machine keeps one simple data structure: the **stack of open questions**. Each question declares the type of answer it needs and which other questions it depends on. The loop, in words:
|
||||
|
||||
1. **Stop check.** No open questions left? Ask the prover: is the user's original question now derivable from the evidence table? Yes → answer. No → the decomposition was incomplete, so one more LLM call asks "what is still missing?" and new questions open. The system stops because a formal condition holds — never because a model feels finished.
|
||||
2. **Pick.** Take the first question whose dependencies are all answered. If none can be picked, some question is waiting on an answer that failed: treat the failure (re-open, re-decompose, or escalate to the user). There is no search here: dependency order *is* execution order.
|
||||
3. **Route.** One cheap LLM judgement, with the expert catalogue in view, picks who attends the question: an expert that answers it in one call (the base case), **FLOOP itself** — i.e. recurse, this question needs decomposition — or **the user**, when nothing in the catalogue covers it. The user is the expert of last resort: the machine asks precise questions and files the replies as evidence.
|
||||
4. **Execute.** The chosen attendant runs. Its result is checked on arrival: the type must match what the question declared, and the claim must not contradict the table. A mismatch is refused — the error goes back for a bounded number of reformulation attempts; a contradiction triggers backtracking (§5). Nothing untyped or unprovenanced is ever appended.
|
||||
5. **Tick the budget.** Every action costs. When the budget dies, the loop stops and the LLM answers directly from what the table holds — explicitly marked as unverified.
|
||||
|
||||
## 3. The generic expert
|
||||
|
||||
Every expert is the same shape: **translate, check, solve, return**. An LLM call turns the question (plus whatever evidence rows it references) into the expert's formal format. A cheap formal check runs — well-typed expressions, consistent units, well-formed query, trusted source — and failures go back to the translating LLM for bounded retries. The deterministic tool solves: a solver, a search engine, computer algebra — no LLM inside. Out comes a typed result with a trace: a proof, a derivation, a verbatim quote with its URL. If nothing passes after the retries, the expert returns "unverified", and the loop decides what to do with the hole.
|
||||
|
||||
The fleet, in words:
|
||||
|
||||
- **knowledge** turns the question into search queries, fetches from trusted sources, and returns *verbatim quotes* with URL and date — never paraphrase. One round per call; a multi-hop chain is several visible calls, each built on the previous answer.
|
||||
- **logic** turns question and premises into a logic program (defaults allowed) and runs a solver; returns the answer and the proof.
|
||||
- **analytic** turns the question into equations where every quantity carries its unit; dimensional analysis is the type check; a computer algebra system solves exactly.
|
||||
- **numeric** evaluates closed expressions to numbers. It exists to enforce one law: the LLM never computes — not even a multiplication.
|
||||
|
||||
## 4. Recursion — floop inside floop
|
||||
|
||||
The orchestration "engine" is the recursion itself. When a question is too big for one expert call, the machine starts a FLOOP run *on that question*, passing down the context: "you serve this parent goal." The child behaves exactly like the top level — same generic INIT question ("what do I need to answer this?"), same loop, same discipline — with two differences that matter:
|
||||
|
||||
- **Context shapes adequacy.** The same subquestion deserves different depth depending on why it is being asked. "Which algorithm mines a block?" needs a different level of detail when the parent asks about quantum resources than when the parent is a history essay. The child always knows the parent, so it knows when its answer is good enough.
|
||||
- **Budget is partitioned, not infinite.** A child receives a slice of its parent's budget and a depth cap. A child that cannot finish returns "unverified" upward, and the parent treats that hole like any failed premise: re-decompose, retry, or ask the user.
|
||||
|
||||
The recursion bottoms out when a question is answerable by a single expert call (§2, step 3). Base case: one expert. Recursive case: one more level of the same machine. There is no separate "planner" component anywhere: **the plan is the open-question stack, planning is proposing reductions of it, and execution is answering from it.**
|
||||
|
||||
Seen from the side, the machine is a relative of Prolog: goals reduce to subgoals, subgoals are solved recursively, answers bind into the templates of later questions, failure backtracks. The differences: the reduction step is generated live by an LLM instead of looked up in a fixed clause database, the primitive predicates are the experts, and no reduction is ever assumed sound — the prover checks the final assembly anyway.
|
||||
|
||||
## 5. Failure and backtracking
|
||||
|
||||
Failure is information, not death. When a new piece of evidence contradicts the table, the machine walks the provenance links — every row records which rows and assumptions it was built from — finds the responsible assumption, marks it retracted, and retracts exactly the rows that descend from it. Work that never depended on the dead assumption survives. Because the table is append-only, the corpse stays for inspection: which hypothesis died, what killed it, what it cost.
|
||||
|
||||
Two kinds of "assumption" get different treatment, decided by one question: *could any evidence refute this?* If yes — a factual hypothesis — it lives as a branch: explore until evidence confirms or kills it. If no — a scenario parameter like a clock speed — it is not a branch at all but a dimension of the answer, marked as such and carried into the final reply. One thing can never be retracted: the user. When a user-supplied fact collides with a source, the machine does not silently pick a side; it asks, presenting the discrepancy verbatim.
|
||||
|
||||
## 6. Stopping and answering
|
||||
|
||||
The stop condition is formal: the original question is derivable from the evidence. Then — and only then — one final LLM pass writes the answer in natural language, working from the evidence rows and traces: every number carries its source, every derivation its steps, every assumption its mark. If the budget dies first, the LLM answers anyway from what the table holds, and the answer is explicitly marked unverified. The product is the same in both cases: a reply that tells you exactly which parts are proven and which are, honestly, a guess.
|
||||
|
||||
## 7. Who does what
|
||||
|
||||
- **LLM, always:** reading the question; proposing subquestions; translating between language and every formal format; the routing judgement (which attendant); the final prose.
|
||||
- **Fixed code, always:** the open-question stack and its ordering; budget partition and depth caps; bounded retries; type-checking on arrival; contradiction detection and retraction; refusing to stop.
|
||||
- **The prover (a solver, not a model), always:** the stop condition; "answered" for any question; the final derivability check.
|
||||
- **Never the LLM:** computing values, deciding when it is finished, writing free-form rows into the state, silently picking between conflicting facts.
|
||||
|
||||
## 8. What was removed, and why (v1 → v2)
|
||||
|
||||
The earlier draft had a symbolic planner (A* over a tiny action domain) choosing every move. For dependent question chains there is nothing for it to search — execution order is dependency order — so v1 drops it: decomposition is an LLM act, sequencing is a property of the stack, stopping is the prover's call. A real search planner earns its place only when open questions compete for a shared budget in parallel, or when routing costs are learned from logs — the rational-metareasoning step of v2. The recursion absorbs what "milestones" and "branch planning" used to do: the first decomposition level *is* the milestone list, and the stack *is* the living plan — only the first openable question is ever concretely instantiated, exactly the receding horizon we wanted.
|
||||
|
||||
Table laws, guarantees, risks and lineage live in [`PIPELINE.md`](PIPELINE.md).
|
||||
@@ -0,0 +1,187 @@
|
||||
# FLOOP — Gap log (step-by-step replay)
|
||||
|
||||
Running log of design gaps found while virtually executing FLOOP on:
|
||||
*"Quants qubits cal que tingui un ordinador quàntic per minar un bloc de bitcoin?"*
|
||||
|
||||
Each entry: what's missing → where it bites → proposed resolution → which doc to patch.
|
||||
Status: **proposed**. Nothing patched yet — resolutions get merged into PIPELINE.md /
|
||||
ALGORITHM.md at the end of the replay, once the walkthrough is complete.
|
||||
|
||||
---
|
||||
|
||||
## Found at INIT (step 1)
|
||||
|
||||
### GAP-1 — Goal schema undefined
|
||||
`ALGORITHM.md` says INIT emits a "goal formula", but nothing defines its vocabulary or shape.
|
||||
**Bites:** `PROVER.derivable` can only check goals written in the same sorted language the
|
||||
evidence will be formalized into; left free-form, the LLM invents predicates the prover
|
||||
cannot consume. No home for: answer type, free parameters, success criterion,
|
||||
presupposition flags.
|
||||
**Resolution:** new core type
|
||||
`GoalSchema { quantity, unit?, answer_type, params[], criterion, presuppositions[] }`.
|
||||
INIT emits it; `ANSWER` validates its output against it; flagged presuppositions may become
|
||||
milestones (e.g. an m0 "frame check") at the planner's discretion.
|
||||
**Patch:** ALGORITHM.md §0, §3; PIPELINE.md §3.
|
||||
|
||||
### GAP-2 — `Assumption` type and ask-vs-assume criterion missing
|
||||
In the first replay, LLM-authored defaults entered the evidence table disguised as
|
||||
`UserReply` (provenance: "assumption") — type pollution that violates invariant #1 in
|
||||
spirit: LLM prose entering the table through the user channel.
|
||||
**Resolution:** new evidence type `Assumption { author: llm, marked: true, weakens_verification }`.
|
||||
Formal criterion for `ask_user`: a free parameter whose plausible range moves the answer
|
||||
by ≥ 1 order of magnitude → ask; otherwise assume + mark. A verified answer must list
|
||||
every Assumption it depends on.
|
||||
**Patch:** PIPELINE.md §5; ALGORITHM.md §0.
|
||||
|
||||
### GAP-3 — Milestone acceptance criteria unspecified
|
||||
Who validates an LLM-proposed decomposition? Nothing guarantees m1..mk ⇒ goal — proving
|
||||
that would require solving the problem itself.
|
||||
**Resolution:** acceptance check = formula well-sorted + usable as a planner subgoal.
|
||||
State explicitly in the docs that **decomposition is heuristic**: system soundness rests
|
||||
on the final PROVER check + replanning, not on decomposition soundness. (Honest
|
||||
limitation to declare, not a bug to fix away.)
|
||||
**Patch:** PIPELINE.md §4; ALGORITHM.md §3.
|
||||
|
||||
### GAP-4 — Answer typing (constant | interval | function)
|
||||
The replay's goal had a free parameter (t_or) but ANSWER returned scenario constants —
|
||||
presenting a function as bare numbers is exactly what made the answer feel wrong
|
||||
("massa gran?"). The system should have *refused* to print a single number.
|
||||
**Resolution:** `GoalSchema.answer_type ∈ {constant, interval, function}`; ANSWER must
|
||||
match it; when later evidence bounds a parameter, function → interval → constant
|
||||
(the answer tightens as evidence arrives).
|
||||
**Patch:** ALGORITHM.md §6.
|
||||
|
||||
### GAP-5 — Fractal-table mapping bug (PIPELINE.md §3)
|
||||
The orchestrator row maps CHECK → `PROVER.derivable`. But in the generic expert, CHECK
|
||||
gates the *formalization before the engine runs*; derivability is the engine's goal test
|
||||
(the stop condition). The table conflates the two.
|
||||
**Resolution:** orchestrator's formalization check = GoalSchema validity (GAP-1);
|
||||
engine goal-test = derivability (stop condition). Fix the table.
|
||||
**Patch:** PIPELINE.md §3.
|
||||
|
||||
### GAP-6 — Budget policy undefined
|
||||
Termination depends on `budget.exhausted()` but nothing sets the initial budget or its units.
|
||||
**Resolution:** budget = cost units of the meta-domain price list (§5); set by user or system
|
||||
default at INIT; logged per run; `ask_user` priced high (human latency).
|
||||
**Patch:** ALGORITHM.md §3, §5.
|
||||
|
||||
### GAP-7 — Assumption branching & dependency-directed backtracking (TMS-lite)
|
||||
Backtracking exists at search level (A* explores/prunes the plan space every turn, cheap),
|
||||
but there is no machinery for branching over **hypotheses across turns**: a factual hypothesis
|
||||
opens a world-branch that lives until evidence refutes or confirms it; on contradiction the
|
||||
branch must die *including everything built on top of it*. Current design only replans the
|
||||
active branch — nothing retracts downstream rows derived from a refuted premise.
|
||||
**Bites:** the evidence table is a single linear world; a refuted premise leaves contradictory
|
||||
rows alive; contradictions linger and poison the prover's derivability checks.
|
||||
**Resolution:**
|
||||
- Distinguish **factual hypotheses** (refutable by evidence → branch: explore, kill or
|
||||
confirm; a refuted row is marked RETRACTED) from **parameter assumptions** (GAP-2; not
|
||||
refutable by any evidence → scenario contexts, dimensions of the answer function, never
|
||||
branches). Criterion: *if no possible evidence could refute it, it is a parameter, not a
|
||||
hypothesis*.
|
||||
- Consistency CHECK on every append; on contradiction, **dependency-directed backtracking**
|
||||
(not chronological): walk the provenance graph from the contradictory rows → find culprit
|
||||
assumptions → mark RETRACTED → transitively retract every row whose provenance includes a
|
||||
culprit → replan the affected branch only.
|
||||
- The provenance graph the table already carries for auditability **doubles as the TMS
|
||||
justification graph** (Doyle 1979; ATMS de Kleer 1986 = the multi-world v2 option — keep
|
||||
all assumption contexts alive in parallel).
|
||||
- Append-only + retraction marks preserve the corpse: the dead-branch log (hypothesis,
|
||||
what refuted it, what it cost) is exactly the training data for the learned v2 router.
|
||||
**Worked example from the replay:** E5 ("the 1,151-qubit article measures the mining
|
||||
oracle") was a factual hypothesis; CHECK flagged it; one targeted knowledge call refuted it
|
||||
(it was Shor on ECDSA); the row died, nothing downstream depended on it. The machinery to
|
||||
do this automatically is what this gap adds.
|
||||
**Patch:** PIPELINE.md §4, §5; ALGORITHM.md §3.
|
||||
|
||||
### GAP-8 — INIT must be epistemically closed over the question's vocabulary
|
||||
The replay's INIT emitted a goal full of domain predicates (`minQubits(T,D,t_or)`,
|
||||
`N_c = D·2³²`, Grover, Zalka) — LLM world knowledge dressed as formalism, i.e. domain
|
||||
content entering through the back door at t=0, before ANY evidence exists. Same disease
|
||||
as CYC, one level up. Also: INIT imported the *competitive* framing (T = 600 s), which
|
||||
inflated the answer by ~17 orders of magnitude — the user's "massa gran" was the symptom.
|
||||
**Resolution (user's correction, adopted):**
|
||||
- INIT may use ONLY: (a) concepts literally present in the question, (b) a small generic
|
||||
planning scaffold (number, method, machine, resources, dependencies). No domain
|
||||
predicates, no parameters, no time, no answer structure.
|
||||
- **GoalSchema shrinks**: `{quantity, of, answer_type: OPEN, criterion}`. `answer_type`
|
||||
starts OPEN — constant vs function vs interval is *discovered by the plan* when evidence
|
||||
reveals dependencies, and tightens OPEN → FUNCTION → INTERVAL → CONSTANT.
|
||||
- **Milestones become epistemic questions**, not formulas: `Milestone{question, produces,
|
||||
deps}` — done = a sourced answer exists in the table. Dependency chains make milestones
|
||||
*templates over slots* (ReWOO at milestone level): m2 cannot even be instantiated until
|
||||
#m1 is filled. The first branch therefore has exactly ONE concrete step.
|
||||
- Domain structure (including whether time matters!) enters ONLY via evidence rows; if
|
||||
evidence at m3 says "the count depends on clock / parallelization policy", THEN the
|
||||
planner opens parameters (and GAP-2's criterion decides ask_user — a machine-vs-fleet
|
||||
spread of ≥10⁹ fires ask_user, which the first run skipped and decided alone).
|
||||
**Patch:** PIPELINE.md §3, §4; ALGORITHM.md §0, §3, §6. Deepest gap so far — affects
|
||||
fractality: the orchestrator's "formalization" is now question decomposition (a linguistic
|
||||
skill, domain-independent), not domain modeling.
|
||||
|
||||
### GAP-9 — Semantics of user-supplied knowledge (UserReply rows)
|
||||
In the replay, the user volunteered domain knowledge from memory (how the mining threshold
|
||||
works) via chat. The docs define `UserReply` as a type but never say what the system does
|
||||
with user-provided *facts* (as opposed to user-provided *scope decisions*, which the
|
||||
ask_user action was designed for).
|
||||
**Bites:** (a) Is a user fact a premise immediately, or does it need verification?
|
||||
(b) What happens when cited evidence contradicts a user row? GAP-7's retraction machinery
|
||||
assumes the culprit is a machine-checkable assumption — but you cannot "retract" the user.
|
||||
(c) ANSWER ships sources: "the user told me" is provenance, but a reader cannot audit it.
|
||||
**Resolution (proposed):**
|
||||
- User rows are premises (user is the authority on intent and scope) but are typed
|
||||
`UserReply{claim, marked: true}` and ALWAYS carry `provenance: user` into the final
|
||||
answer — user-asserted facts are listed separately from source-cited facts.
|
||||
- If a user fact is **load-bearing** for the goal (the derivation would collapse without
|
||||
it) and verification is cheap, the planner may schedule a confirm-call to `knowledge`
|
||||
— the row stays, the citation gets attached.
|
||||
- On conflict between a user row and sourced evidence: **never silent-pick**. Fire
|
||||
`ask_user` presenting the discrepancy verbatim (quote + user claim). The user is
|
||||
the tie-breaker on facts, not the system.
|
||||
**Patch:** PIPELINE.md §5; ALGORITHM.md §0.
|
||||
|
||||
### REDESIGN-1 — The orchestrator's engine is recursion into FLOOP (no symbolic planner in v1)
|
||||
User proposal, adopted: INIT is a single LLM call ("what do I need to know to answer this?");
|
||||
subquestions too big for one expert are solved by a recursive FLOOP run that knows it serves a
|
||||
parent goal. The A*/clingo meta-planner was over-engineering: with dependent questions,
|
||||
execution order = dependency order — nothing to search. Division of labour now: decomposition
|
||||
proposal = LLM (linguistic, epistemically closed per GAP-8); sequencing/budget/depth/retries/
|
||||
retraction = fixed code; stop = prover; expert-vs-recursion-vs-user per question = one cheap
|
||||
LLM judgement over the expert catalogue (which now contains floop itself as the decomposition
|
||||
expert, and the user as expert of last resort). A* returns only in v2 (budget competition
|
||||
between parallel branches / learned routing costs). Supersedes the PLANNER-centric sections
|
||||
of both docs — ALGORITHM.md rewritten as a prose description of the machine.
|
||||
|
||||
### GAP-10 — Adequacy contract & the decomposition criterion (found at depth-1 replay)
|
||||
Walking the child run exposed three things the docs left implicit:
|
||||
(a) **Who decides "is this question primitive or does it need decomposition?"** — no criterion
|
||||
existed. Working answer: decompose only when a single expert call cannot produce an answer
|
||||
of the declared type; prefer routing first and decomposing **on failure** (type-check miss /
|
||||
shallow quotes), not by upfront inspection.
|
||||
(b) **Adequacy for the parent lives in the declared answer type.** The child knows why it is
|
||||
asked (parent context), and the parent's need is expressed as the fields of the declared
|
||||
type (e.g. `Algorithm{function, input, variable, success_condition}`). A quote that fills
|
||||
3 of 4 fields fails the arrival check → targeted retry/decomposition of just the missing
|
||||
field. The type IS the parent-child interface.
|
||||
(c) **Derivability degenerates for descriptive questions**: no real logical derivation, just
|
||||
"an adequate typed, sourced row exists". Formal rigor concentrates where composition happens
|
||||
(analytic/numeric levels). State this honestly — the prover is not equally strong at all
|
||||
nodes of the tree.
|
||||
**Also discovered (not a gap — a freebie):** the stop-check runs on newly-opened questions
|
||||
too, so a child whose answer already exists in the visible table terminates with zero or one
|
||||
confirm calls. The stop-check IS the cache/dedup of the architecture.
|
||||
**Patch:** PIPELINE.md §3, §4; ALGORITHM.md §2, §4.
|
||||
|
||||
---
|
||||
|
||||
## Notes from the replay (not gaps — lessons)
|
||||
|
||||
- The E5 rejection (Shor-on-ECDSA article posing as "quantum attack on Bitcoin") was the
|
||||
type checker doing its job — the fleet config's `check` caught a cross-type confusion.
|
||||
Keep per-expert checks that know the *failure shapes* of their sources.
|
||||
- The knowledge expert ran degraded (search snippets only — page extraction unavailable)
|
||||
and should have downgraded confidence accordingly. Degraded-source confidence policy
|
||||
is a small open question, related to GAP-2.
|
||||
- The honest answer to the demo question is a function of t_or (and weakly of D, T);
|
||||
the literature-standard constant (~2.4k–13k logical qubits, one machine, no deadline)
|
||||
is the collapse of that function under "no clock constraints".
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
# FLOOP — Pipeline Definition
|
||||
|
||||
**FLOOP = fractal loop.** An architecture where:
|
||||
|
||||
- an LLM **translates** between natural language and formal representations,
|
||||
- a **sound computational engine** does the deciding — solving, proving, planning,
|
||||
- the answer **carries its proof** — every verified claim is traceable to typed evidence and engine traces.
|
||||
|
||||
The same pattern runs at every level of abstraction: inside each expert, and at the orchestration level — which is not a special component but the same loop run recursively on subquestions. That is the "fractal".
|
||||
|
||||
Division of labour, stated as laws:
|
||||
|
||||
1. **LLMs never reason to conclusions and never compute values.** They translate, they decompose questions, they interpret.
|
||||
2. **Engines never see natural language.** They receive typed formalizations and return typed results plus traces.
|
||||
3. **Nothing is "done" or "answerable" because a model said so.** Both are formal checks made by a prover over the evidence.
|
||||
|
||||
---
|
||||
|
||||
## 1. The generic expert pattern
|
||||
|
||||
Every expert is an instance of one shape — formalize → check → solve → return:
|
||||
|
||||
```
|
||||
task (NL or typed refs)
|
||||
│
|
||||
▼ LLM (translate)
|
||||
formal representation (typed grammar: formulas, equations, query plans)
|
||||
│
|
||||
▼ CHECK (cheap, formal: sorts, units, consistency)
|
||||
│ fail ──▶ error fed back to LLM ──▶ re-formalize (≤ 3 refinements)
|
||||
▼
|
||||
ENGINE (sound, deterministic, no LLM inside)
|
||||
│ fail ──▶ error fed back to LLM ──▶ re-formalize
|
||||
▼
|
||||
typed payload + trace (proof / derivation / citation chain)
|
||||
```
|
||||
|
||||
Two design decisions locked in this document:
|
||||
|
||||
- **The expert's output is a typed formal payload, not prose.** Interpretation (formal → NL) happens once, at answer synthesis. Prose inside the pipeline would make the evidence un-checkable by the prover.
|
||||
- **Self-refinement is bounded** (≤ 3 attempts). If formalization never passes or the engine never solves, the expert returns an *Unverified* result — the honest fallback. Nothing is ever silently guessed and marked as verified.
|
||||
|
||||
## 2. The expert fleet
|
||||
|
||||
Each expert is the generic shape plus a configuration. All of them return typed evidence rows — never raw text.
|
||||
|
||||
| Expert | Formalizes into | Formal check | Engine | Typed payload |
|
||||
|---|---|---|---|---|
|
||||
| `logic` | sorted FOL / Horn program + query | well-sorted, consistent, query well-formed | clingo / Z3 / Prover9 (picked by problem class) | model + proof trace |
|
||||
| `analytic` | equations over quantities, each with a Unit | **dimensional analysis** (units are the type system) | SymPy `solve` / `simplify` / `dsolve` | symbolic value + unit + assumptions |
|
||||
| `numeric` | closed-form expressions + constants | dimensional analysis | SymPy `evalf` | numeric value + unit + precision |
|
||||
| `knowledge` | retrieval plan: query templates with slot refs | source ∈ trusted list, freshness, no duplicate | search + fetch (Wikipedia, trusted sources) | verbatim quote + url + access date |
|
||||
|
||||
Notes on the fleet:
|
||||
|
||||
- **`numeric` exists to enforce a law**: the LLM writes expressions; it never evaluates arithmetic — not even a multiplication. All computation is delegated to an engine.
|
||||
- **`knowledge` never paraphrases.** Its payload is the verbatim quote with provenance. Synthesis quotes the citation; it does not restate it.
|
||||
- **Multi-hop retrieval is not inside `knowledge`.** Each call is one round of search+fetch. Multi-hop emerges at the orchestration level: one question references the answer of another — the hops live in the question stack, where they are visible and auditable.
|
||||
|
||||
## 3. The orchestrator is an expert — and its engine is FLOOP itself
|
||||
|
||||
The component that decides how to answer is not a special "planner" piece: it is the generic pattern one level up, with **recursion as its engine**.
|
||||
|
||||
| Generic stage | Orchestrator instantiation |
|
||||
|---|---|
|
||||
| LLM formalizes the task | one LLM call asks the generic meta-question: *what information or knowledge do I need to answer this?* — and emits a short list of open subquestions (epistemically closed over the question's own words: no domain vocabulary allowed) |
|
||||
| CHECK | the goal is well-formed; subquestions are typed, in acyclic dependency order |
|
||||
| ENGINE solves | **FLOOP itself**: each subquestion runs through the same loop — directly by an expert, or recursively by a new FLOOP run that knows it serves this goal |
|
||||
| typed payload + trace | answered subquestions append typed evidence; the final answer carries its derivation |
|
||||
|
||||
Why this works — and why there is no A* in v1: with questions that carry dependencies, **there is nothing to search**. Execution order *is* dependency order: take the first open question whose inputs are filled. Decomposition is a linguistic act (LLM), sequencing is a property of the question list (code), and stopping is a formal check (prover). The earlier design's symbolic meta-planner was over-engineering — it earns its place only when open questions compete for budget in parallel (v2).
|
||||
|
||||
- The machine **runs on slots and types, never content**: a question is instantiated only when the answers it references exist, with the right types.
|
||||
- The orchestrator LLM translates (question → subquestions; results → next instantiation; final evidence → NL answer). It **never decides when to stop** — that is the prover's job.
|
||||
- The recursion bottoms out at the **expert catalogue**: for each open question, one cheap LLM judgement picks who attends it — `knowledge`, `logic`, `analytic`, `numeric`, **`floop` itself** (the decomposition expert: this question is too big for one call), or **the user** (expert of last resort, when nothing else covers it).
|
||||
|
||||
## 4. The living plan (receding horizon)
|
||||
|
||||
Plans are not written once and followed. FLOOP plans like MPC (model predictive control):
|
||||
|
||||
- The **goal** is fixed. The **open questions** — the first level of decomposition — mark the way; each is answered by evidence or by further decomposition, never by fiat.
|
||||
- Only the **first openable question** is concretely instantiated (its inputs exist, its attendant is chosen); the rest wait as questions-with-references until their turns come.
|
||||
- After every answer, the machine re-decides against the new table: invalidated questions reopen, dependencies resolve, new subquestions may be proposed. No global replanning — **the stack is the plan**.
|
||||
|
||||
Replan triggers are formal, not vibes:
|
||||
|
||||
- an answer arrives with an unexpected type, or below the confidence the question declared it needed;
|
||||
- a question's precondition is no longer derivable from the evidence;
|
||||
- evidence makes a cheaper path to the same subquestion obvious.
|
||||
|
||||
Stop conditions are formal too:
|
||||
|
||||
- **answer**: the goal is derivable from the evidence table (prover check) → synthesize the verified answer;
|
||||
- **budget exhausted** → honest fallback: an *Unverified* answer, marked as such.
|
||||
|
||||
## 5. The evidence table
|
||||
|
||||
The shared state — one per run, **append-only**, visible to everyone. Each row: an id (referenced by questions), a type, a typed payload (formal value, verbatim quote, or user reply — never LLM prose), an engine trace (proof | derivation | url chain), and provenance (expert, sources, cost, timestamp).
|
||||
|
||||
Laws of the table:
|
||||
|
||||
1. **Only engines write to it** (typed payloads), plus verbatim quotes and user replies. The orchestrator LLM reads it but never writes free-form rows — that is the single most dangerous injection point of the architecture, so it is closed by rule.
|
||||
2. **Every row carries provenance.**
|
||||
3. **Derivability runs over formal rows only.** A `Citation` is a premise, not a fact: some question must formalize it before it can support the goal or any subquestion's answer. A verified answer therefore always cites sources that were themselves formalized.
|
||||
4. Prose is never stored. The only text in the table is verbatim source quotes (and user replies, typed as such).
|
||||
|
||||
## 6. Guarantees
|
||||
|
||||
What FLOOP promises, and on what condition:
|
||||
|
||||
- **Auditable answers.** Every verified answer ships: the claim, the derivation (which facts, which rules, which engines), and the sources. This is the product — reasoning you can check, not a confidence score.
|
||||
- **Bounded routing, sound stopping.** Who attends a question is an LLM judgement over a small expert catalogue, type-checked on arrival; when to stop is a formal check (derivability), never a model's feeling.
|
||||
- **Honesty at the boundary.** What cannot be formalized or solved within budget is answered by the LLM directly and explicitly marked *Unverified*.
|
||||
- The guarantee is conditional on formalization quality — see §8.
|
||||
|
||||
## 7. v1 → v2
|
||||
|
||||
- **v1** (this document): LLM translates and decomposes; the machine is fixed control code (open-question stack, budget slices, depth cap, bounded retries, retraction); the prover is clingo/Z3. Everything sound is sound by construction, everything cheap is cheap by prompt.
|
||||
- **v2**: the **router is learned** — costs and expected gains (value of computation) estimated from logged trajectories (rational metareasoning, Russell & Wefald 1991). The machine stays sound; only its cost model becomes data-driven — and if parallel branches ever compete for a shared budget, that is where a real search planner earns its place. The logs v1 produces are exactly the training data v2 needs.
|
||||
|
||||
## 8. Known risks (stated, not hidden)
|
||||
|
||||
1. **Misformalization with a veneer of rigor** — the top failure mode. A wrong formalization of "most birds fly" produces a mathematically correct answer to the wrong question. Mitigations in the design: sorted logics and units as type systems (kill half the errors before solving), bounded self-refinement, provenance on every row, and — planned — the **round-trip check**: re-translate the formalization back to NL and compare with the original.
|
||||
2. **Non-monotonicity.** Default reasoning (birds fly… except penguins) lives in the `logic` expert via ASP default negation, not in FOL-pure solving.
|
||||
3. **Over-decomposition.** Pure-LLM decomposition can produce subquestions whose answers never feed the parent. Contained by: budget charged per question, dependency typing on arrival (an answer nobody consumes flags the dead question), and the final derivability check.
|
||||
4. **Infinite regress.** Recursion needs a depth cap and a budget slice per level; a child that cannot finish returns "unverified" upward.
|
||||
5. **Ambiguity, reference, pragmatics** stay on the neural side, deliberately. FLOOP does not attempt to formalize the world — it formalizes what a task needs, checks what it formalized, and marks the rest as unverified.
|
||||
6. **Scope.** Each expert is a small pipeline with its own failure modes; the whole is several projects. Build order: one expert end-to-end on a benchmark, then the loop, then the fleet.
|
||||
|
||||
## 9. Lineage
|
||||
|
||||
- **Logic-LM** (Pan et al., EMNLP 2023, arXiv:2305.12295) — the lm→solver pipeline with self-refinement; +39% over plain LLM on logic benchmarks. The generic expert pattern.
|
||||
- **ReWOO** (Xu et al., 2023, arXiv:2305.18323) — plan-on-slots, decoupled execution; 5× token efficiency, +4% HotpotQA. The slot mechanism and the evidence table.
|
||||
- **LLM-Modulo** (Kambhampati, ICML 2024, arXiv:2402.01817) — LLMs can't plan, but can help: propose, let external verifiers decide. The orchestrator's philosophy.
|
||||
- **LLM+P** (Liu et al., 2023, arXiv:2304.11477) — NL → PDDL → classical planner → NL. Translate, plan, translate back.
|
||||
- **POMDP-Coder** (2025, arXiv:2505.02216) — LLM writes the world model as a probabilistic program; a POMDP solver plans. Measured evidence that "lm models, solver decides" beats "lm decides".
|
||||
- **Rational metareasoning** (Russell & Wefald 1991; for LLMs arXiv:2410.05563) — deciding what to compute next is itself a decision problem. The v2 router.
|
||||
@@ -0,0 +1,26 @@
|
||||
# floop
|
||||
|
||||
**Fractal loop.** One algorithm — an LLM translates, a sound engine computes, the answer carries its proof — instantiated at every level of abstraction, including the orchestration level itself. The orchestrator is not a special component: questions too big for one expert recurse into new FLOOP runs, so the engine of FLOOP is FLOOP itself.
|
||||
|
||||
FLOOP is ReAct where the "thought" step is replaced by computation and the "observation" is typed before it enters the state.
|
||||
|
||||
## Documents
|
||||
|
||||
| File | Contents |
|
||||
|---|---|
|
||||
| [`PIPELINE.md`](PIPELINE.md) | Definition of the pipeline: the generic expert pattern, the expert fleet, the orchestrator-as-recursion, the living plan, table laws, guarantees, v1→v2, known risks. |
|
||||
| [`ALGORITHM.md`](ALGORITHM.md) | How the machine works, in words: the opening call (INIT), the main loop, the generic expert and the fleet, recursion (floop inside floop), backtracking, stopping and answering. |
|
||||
| [`GAPS.md`](GAPS.md) | Design gap log from the step-by-step replay: what was missing, why it bites, proposed resolutions. |
|
||||
|
||||
## Status
|
||||
|
||||
Design docs (v0.2 — recursion redesign). **v0.1 draft executable since 2026-10-10** (`code/`):
|
||||
the full loop runs on dspy LLM calls only (INIT/ROUTE/EXPERT/MISSING/ANSWER as dspy modules,
|
||||
the machine — stack, dependency order, budget, recursion — as fixed code); formal checks,
|
||||
prover and expert engines are stubs, so every answer is honestly `Unverified`. See `code/README.md`
|
||||
and RUNLOG "Executable runs". Next: real check layer, `knowledge` vertical with real search,
|
||||
prover (clingo/Z3).
|
||||
|
||||
## Lineage
|
||||
|
||||
Logic-LM (arXiv:2305.12295) — lm→solver pattern with self-refinement. ReWOO (arXiv:2305.18323) — plan-on-slots, decoupled execution. LLM-Modulo (arXiv:2402.01817) — LLMs propose, external verifiers decide. LLM+P (arXiv:2304.11477) — lm→PDDL→classical planner. POMDP-Coder (arXiv:2505.02216) — lm writes the model, a solver plans. Rational metareasoning (Russell & Wefald 1991; arXiv:2410.05563) — the value of computation decides what to do next.
|
||||
@@ -0,0 +1,189 @@
|
||||
# FLOOP — Virtual run log
|
||||
|
||||
**Question (depth 0):** *"Quants qubits cal que tingui un ordinador quàntic per minar un bloc de bitcoin?"*
|
||||
|
||||
**Format:** each entry `[T<turn> | depth=<d> | <component>]` with input / output / cost / notes.
|
||||
- `[REAL]` = a real tool call was executed. `[NARRATED]` = step walked by hand, no tool ran.
|
||||
- T0–T2 are reconstructed after the fact (the walkthrough predates this log). From T3 on: live.
|
||||
- Budget unit: calls (informal — GAP-6 still open).
|
||||
- Evidence ids carry over from run 1 with provenance intact; E5 RETRACTED (GAP-7 case). Run 1's flaws are in GAPS.md, not here.
|
||||
|
||||
## Carried evidence
|
||||
|
||||
| id | type | content | provenance | status |
|
||||
|---|---|---|---|---|
|
||||
| E1 | Citation | difficulty ≈ 132.7×10¹²; hashrate ~950 EH/s (Oct 2026) | startmining.io, pickaxe.io | live |
|
||||
| E2 | Citation | Aggarwal: PoW resistant to near-term QC; ASIC clock ≫ QC clock | arXiv:1710.10377 | live |
|
||||
| E3 | Citation | Amy et al. (Waterloo): cost estimates for generic quantum preimage attacks on SHA-2/SHA-3 | PQCrypto 2016 | live |
|
||||
| E4 | Citation | Zalka: Grover optimal; parallelization = space partition; (π/4)√N oracle calls | arXiv:quant-ph/9711070 | live |
|
||||
| E5 | Citation | "1,151 logical qubits, ~1.3M Toffoli — Bitcoin attack halved" | shattered.io | **RETRACTED** (Shor/ECDSA ≠ mining) |
|
||||
| E6 | Citation | reversible double-SHA-256 oracle ≈ 3×10⁵ non-Clifford T gates per Grover iteration; magic-state factories: thousands of physical qubits (surface code) | arXiv:2603.25519 | live |
|
||||
| E7 | Algorithm | function: double-SHA-256(header 80B); variable: nonce 4B + extraNonce; condition: hash ≤ target (nBits) | UserReply (load-bearing, confirmed vs E2+E6 — GAP-9) | live |
|
||||
| E8 | QuantumAlgo | Grover; search_space: nonce 2³² ⇒ register ⌈log₂⌉ = 32 qubits (derivable); oracle: double-SHA-256 reversible (E6); iterations: (π/4)·√N | Delgado 2022 (MDPI Entropy 24(3):323), E4, E6 | live |
|
||||
|
||||
## T0 — INIT (depth 0)
|
||||
|
||||
`[T0 | depth=0 | INIT — LLM translate stage]` `[NARRATED]` — 1 call
|
||||
- **input:** user question (NL)
|
||||
- **output:**
|
||||
- GoalSchema{ quantity: n = "qubits d'un ordinador quàntic que pot minar un bloc de bitcoin"; answer_type: **OPEN**; criterion: every factor of n carries a source }
|
||||
- subquestions (dependency chain, epistemic closure per GAP-8):
|
||||
- **m1** "quin algorisme computacional mina un bloc?" → Algorithm
|
||||
- **m2** "quin és l'equivalent quàntic de #m1?" (template) → QuantumAlgo
|
||||
- **m3** "quants qubits necessita la màquina que executa #m2?" (template) → QubitCount
|
||||
- **notes:** the run-1 INIT imported domain vocabulary + the competitive time framing (GAP-8) and inflated the answer; this is the corrected INIT.
|
||||
|
||||
## T1 — turn 1: m1 (child run, depth 1)
|
||||
|
||||
`[T1.a | depth=0 | stop-check]` goal derivable from table? → **NO** (no Algorithm row). `[NARRATED]`
|
||||
`[T1.b | depth=0 | route]` m1 + declared type Algorithm → attendant: **floop child (depth 1)** — bare `knowledge` also defensible; the child adds the typed adequacy contract. `[NARRATED]`
|
||||
`[T1.c | depth=1 | INIT]` input: "com és l'algorisme per minar bitcoins?" + parent context ("per comptar qubits") → 1 subquestion typed `Algorithm{function, input, variable, success_condition}`. `[NARRATED]` — 1 call
|
||||
`[T1.d | depth=1 | stop-check on open question]` type vs visible table → 4/4 fields coverable (E2, E6, user row); 2 fields covered only by the user row → GAP-9: load-bearing → cheap confirm. `[NARRATED]`
|
||||
`[T1.e | depth=1 | EXPERT knowledge]` input: "confirm mining mechanism, attach citation" → **E7 Algorithm — PASS arrival check**. `[NARRATED — no real call: piggybacked on E2/E6 provenance; a live run does one search+fetch here]`
|
||||
- **result:** m1 done. cost: ~3 LLM calls + 1 knowledge call.
|
||||
|
||||
## T2 — turn 2: m2 (child run, depth 1)
|
||||
|
||||
`[T2.a | depth=0 | stop-check]` → **NO** (no QuantumAlgo row yet). `[NARRATED]`
|
||||
`[T2.b | depth=1 | INIT]` input: "quin és l'equivalent quàntic de #E7?" + context → 1 subquestion typed `QuantumAlgo{primitive, search_space, oracle, iterations}`. `[NARRATED]` — 1 call
|
||||
`[T2.c | depth=1 | stop-check]` 3/4 fields derivable (E4: primitive + iterations; E6: oracle); `search_space` ✗ → **targeted retry**, not decomposition (GAP-10b). `[NARRATED]`
|
||||
`[T2.d | depth=1 | EXPERT knowledge]` input: "quin espai de cerca recorre Grover al minatge? què va en superposició?" → **E8 QuantumAlgo — PASS**. `[REAL: web_search ×2 → Delgado 2022, MDPI Entropy 24(3):323 — "the entire search space of the golden nonce can be queried at once"]`
|
||||
- **result:** m2 done. Adequacy note: `iterations` carries an **unbound N** → flagged; becomes m3's business.
|
||||
|
||||
## T3 — turn 3: m3 (child run, depth 1) — LIVE from here
|
||||
|
||||
`[T3.a | depth=1 | INIT]` input: "quants qubits necessita la màquina que executa #E8?" + parent context ("l'objectiu és respondre la pregunta de l'usuari, no una fita intermèdia").
|
||||
Decomposition driven by the **declared type + the table's holes** — the generic machine scaffold says: machine = state register (✓ E8: 32 qubits) + oracle circuit width (✗ no row) + error correction (✗ no row):
|
||||
- **m3.1** "quina amplada (qubits lògics) té el circuit oracle reversible de #E8?" → `CircuitWidth{width, included, font}` [knowledge]
|
||||
- **m3.2** "quants qubits físics calen per qubit lògic segons #E6?" → `ECOverhead{ratio, scheme, font}` [knowledge]
|
||||
- **m3.3** template (waits for both slots): `n_logical = 32 + #m3.1 ; n_physical = n_logical × #m3.2` [analytic]
|
||||
`[NARRATED]` — 1 call. **Fork flagged (GAP-2):** "tenir qubits" suggests physical; the literature quotes logical — but both readings share every subquestion except the final ×ratio → **answer both, don't ask** (refinement logged in GAPS.md).
|
||||
|
||||
### T3.b — m3.1 (circuit width) `[REAL]`
|
||||
|
||||
`[T3.b | depth=1 | EXPERT knowledge]` input: "quina amplada (qubits lògics) té el circuit oracle reversible de #E8?"
|
||||
- **calls:** web_search ×3 + GitHub README fetch + arXiv HTML extract (curl ×2) — 6 tool calls, 1 turn
|
||||
- **output → E9** `CircuitWidth{ width: [1,346 .. 4,418] logical qubits per machine, register INCLUDED,
|
||||
sources: [arXiv:2603.25519 ("1,346 logical qubits per iteration once the search register and
|
||||
comparison ancillas join the 1,153-qubit hash pipeline"), slothgar/quantum-bitcoin-miner
|
||||
("4,417 qubits, double SHA-256 fully reversible" / "Logical qubits: 4,418 — verified vs
|
||||
genesis block, zero dirty ancillas"), Amy et al. arXiv:1603.09383 (SHA-256 preimage width
|
||||
≈ 2^12.6 ≈ 6,208 — same band, third source)] }` — **PASS** (3 independent sources, band 10³–10⁴)
|
||||
- **notes:** the slothgar repo is executable primary evidence (circuit runs, CI-verified against
|
||||
the genesis block) — stronger than a paper quote. Its README states the design thesis verbatim:
|
||||
*"The honest gap is width, not fidelity — and width is exactly what matters."*
|
||||
|
||||
### T3.c — m3.2 (error-correction overhead) `[REAL]`
|
||||
|
||||
`[T3.c | depth=1 | EXPERT knowledge]` (same calls as T3.b, one search round) → **E10**
|
||||
`ECOverhead{ ratio: [1,000 .. ~1,450] physical:logical, scheme: surface code d≤27,
|
||||
sources: [literature "1,000:1 or higher" (quantumintel.tech summary), slothgar "physical
|
||||
~6.4M / logical 4,418 at d=27" → 1,449, arXiv:2603.25519 (Litinski framework, T-factory
|
||||
sizing)] }` — **PASS**
|
||||
- **notes:** the interval comes from *concrete instances*, not vibes: d=27 is a real design point.
|
||||
|
||||
### T3.d — arrival check & template correction `[NARRATED]`
|
||||
|
||||
`[T3.d | depth=1 | CHECK]` proposed template said `n_logical = 32 + #m3.1`. **E9's `included`
|
||||
field says the register is already in the width** → adding 32 would double-count the nonce
|
||||
register. Template corrected by evidence: `n_logical = #m3.1` (not additive). The typed field
|
||||
`CircuitWidth.included` is what allows the composer to catch this — LLM proposal amended, not
|
||||
blindly applied. *(Logged as a working mechanism, candidate PIPELINE §5 note.)*
|
||||
|
||||
### T3.e — m3.3 (composition) `[REAL]`
|
||||
|
||||
`[T3.e | depth=1 | EXPERT analytic+numeric]` input: compose QubitCount from E9 × E10 (SymPy,
|
||||
no mental arithmetic — engine run, output verbatim):
|
||||
```
|
||||
n_logical ∈ [1,346 .. 4,418]
|
||||
ratio ∈ [1,000 .. 1,449] (surface code, d≤27)
|
||||
n_physical∈ [1.35e6 .. 6.40e6] per machine
|
||||
cross-checks: slothgar direct quote 4,418 → ~6.4M MATCH
|
||||
Amy et al. 2^12.6 ≈ 6,208 logical (same band) OK
|
||||
```
|
||||
→ **E11** `QubitCount{ n_logical: [1,346..4,418], n_physical: [1.35×10⁶..6.4×10⁶],
|
||||
reading: per-machine width, nonce-only Grover (partial preimage, b=32),
|
||||
answer_type: INTERVAL }` — **PASS** (dimensions: qubits = qubits × 1 ✓)
|
||||
|
||||
### T4 — depth-0 stop-check → ANSWER `[NARRATED]`
|
||||
|
||||
`[T4 | depth=0 | PROVER]` goal "how many qubits to mine a block" derivable from table?
|
||||
- **E11 exists, typed, sourced, composed** (derivation chain E8→E9/E10→E11 all provenance-linked) → **YES**.
|
||||
- `answer_type` tightens OPEN → **INTERVAL**. D (difficulty) **does not enter the width**: the
|
||||
hash function fixes the width; difficulty only scales iterations (time). The parameter run-1
|
||||
imported turned out to be irrelevant to this reading — GAP-8 vindicated by payoff.
|
||||
- Honest complements already in table: competitive framing → fleet ~10²³ physical (arXiv:2603.25519
|
||||
at Jan-2025 difficulty); nonce-only partial preimage b=32 → ~10⁸ physical (same paper). Both are
|
||||
the *time-collapsed* variants of the same machine — quoted as context, marked as alternative
|
||||
framings, not merged into E11 (type separation prevents the merge).
|
||||
- **Unresolved fork (GAP-2), logged not asked:** "tenir qubits" = machine size (E11). If the user
|
||||
meant "beat the network", the answer is the fleet variant. Both readings carried into ANSWER.
|
||||
|
||||
`[T5 | depth=0 | ANSWER]` — final synthesis (LLM, one formal→NL pass over the table):
|
||||
**"Per minar un bloc (una màquina, sense cursa contra el temps): ~1.400–4.400 qubits lògics,
|
||||
~1,4–6,4 milions de qubits físics amb surface code (d≤27). L'amplada la fixa SHA-256 reversible,
|
||||
no la dificultat; la dificultat només allarga el rellotge. La lectura competitiva (guanyar el
|
||||
bloc de 10 min) és una altra pregunta: ~10²³ físics a dificultat actual."** Marked: verified for
|
||||
the machine-size reading; the competitive reading quoted from source, not derived.
|
||||
|
||||
---
|
||||
|
||||
## Run summary (as logged)
|
||||
|
||||
- **Turns:** T0–T5. **Real calls:** 1 (T2.d searches) + 6 (T3.b/c) + 1 analytic engine run (T3.e).
|
||||
Everything else narrated (LLM calls not executed — a live run spends ~8 more LLM calls: INITS, routes, checks).
|
||||
- **Depth reached:** 1 (m1, m2, m3 as child runs; no depth-2 needed — m3's decomposition stayed inside the child).
|
||||
- **Evidence:** E1–E11 (E5 RETRACTED). E7 carries user provenance (confirmed). E11 composed, derivation-linked.
|
||||
- **Design lessons this run:**
|
||||
1. T3.d — typed `included` fields let evidence correct an LLM proposal (double-count caught).
|
||||
2. T4 — difficulty never entered the width answer: a parameter imported by run-1's INIT was
|
||||
irrelevant under the honest reading. The epistemic closure (GAP-8) pays off concretely.
|
||||
3. The stop-check doubling as cache (GAP-10) fired twice: m1 closed with zero searches, m2 with one.
|
||||
4. The fork at m3 resolved by *typing the answer both ways* rather than asking (interval band
|
||||
shared by both readings except the ×ratio term) — GAP-2 criterion refined: **ask only when
|
||||
readings diverge in kind, not when they diverge in one multiplicative term.**
|
||||
- **Open items:** GAP-6 (budget units still informal), GAP-2 (fork criterion refinement to merge),
|
||||
GAP-10 (adequacy contract) — all logged in GAPS.md.
|
||||
|
||||
---
|
||||
|
||||
# Executable runs (v0.1 draft, `code/`)
|
||||
|
||||
**2026-10-10. First executable run.** dspy 3.4.0 over OpenAI-compatible endpoints; every LLM
|
||||
stage (INIT, ROUTE, EXPERT, MISSING, ANSWER) is a dspy call; check layer, prover and engines
|
||||
are stubs — so everything is honestly `Unverified`. LM: local `qwen3.8:27b` (hub 127.0.0.1:11435).
|
||||
|
||||
## Run A — question with no answerable evidence (honesty demo)
|
||||
|
||||
`"How many physical qubits would be needed to break RSA-2048, and what makes the estimate uncertain?"`
|
||||
|
||||
- INIT → 3 subquestions (logical qubit count → EC overhead → uncertainty sources), deps typed.
|
||||
- ROUTE → knowledge ×3. The stub knowledge engine cannot retrieve (no search in the draft),
|
||||
the question states no literals, so E1 = UNKNOWN → arrival check refuses → Q1 failed →
|
||||
Q2, Q3 cascade-fail (dependency-directed failure). Stop = stack terminal (prover stub).
|
||||
- ANSWER (UNVERIFIED): correctly refuses to invent a number, cites E1.
|
||||
- 3 LLM calls + 1 engine call, 132 s. **The honest fallback path works end-to-end.**
|
||||
|
||||
## Run B — answerable-from-question-literals (happy path)
|
||||
|
||||
`"A train travels 120 kilometers in 90 minutes. What is its average speed in km/h?"`
|
||||
|
||||
- INIT → Q1 "90 min in hours?" [CONSTANT, numeric] → Q2 "formula for average speed?"
|
||||
[FUNCTION, knowledge] → Q3 "average speed using converted time + distance" [FUNCTION, numeric],
|
||||
dependency chain Q1→Q3.
|
||||
- Q3's question text referenced Q1's slot and was instantiated with E1's value at execution
|
||||
time (plan-on-slots working).
|
||||
- E1=1.5 h (stub:numeric, quote = question literal), E2=formula (stub:knowledge),
|
||||
E3=80 km/h (stub:numeric). ANSWER (UNVERIFIED): "80 km/h" with every claim cited to E1–E3.
|
||||
- 8 LLM calls (init 1 + route 3 + engines 3 + answer 1), 154 s — budget accounting exact.
|
||||
|
||||
**Design lessons (executable run 1):**
|
||||
1. The failure cascade (Run A) is the design working: no retrieval engine → honest UNKNOWN →
|
||||
no invented answer. The next vertical (`knowledge` with real search) is what unlocks
|
||||
Run-A-class questions.
|
||||
2. Slot instantiation (#E refs substituted at execution, not planning) kept hops visible in
|
||||
question text — matching the PIPELINE law that multi-hop lives in the plan.
|
||||
3. dspy 3.4 + litellm: model ids need the `openai/` prefix for OpenAI-compatible endpoints;
|
||||
the class is `dspy.LM` (not `dspy.LLM`). Wrapped once in `floop/llm.py`.
|
||||
4. Budget must charge engine LLM calls too (the engine IS an LLM call in the draft) —
|
||||
fixed after Run A showed engines riding for free.
|
||||
@@ -0,0 +1,57 @@
|
||||
# floop/code — v0.1 draft implementation
|
||||
|
||||
A **draft**: every deciding stage (formal checks, the prover, real engines) is a
|
||||
stub, so the draft runs with only LLM calls (as decided) and every answer is
|
||||
honestly marked **UNVERIFIED**. The architecture — states, laws, control flow —
|
||||
is the real v0.1 shape; only the formal layer is missing.
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
cd floop/code
|
||||
.venv/bin/python run_app.py "What information do I need to plan a trip to Tokyo?" # any question
|
||||
FLOOP_LM=ollama-cloud .venv/bin/python run_app.py "..." # cloud LM instead of local
|
||||
```
|
||||
|
||||
`config.yaml` holds the budget knobs and the two LM providers (no keys in code:
|
||||
`ollama-cloud` reads `OLLAMA_API_KEY` from the environment).
|
||||
|
||||
## What is real vs stub (the honest map)
|
||||
|
||||
| Stage (ALGORITHM.md) | Status | Where |
|
||||
|---|---|---|
|
||||
| INIT — epistemic decomposition (LLM call) | real (dspy.Predict) | `floop/dspy_modules.py` |
|
||||
| MISSING — gap decomposition on stuck goal | real (dspy) | `floop/dspy_modules.py` |
|
||||
| ROUTE — one LLM judgement over the catalogue | real (dspy) | `floop/dspy_modules.py` |
|
||||
| Expert attendants (the draft answer) | **STUB engine**: LLM call, `verified=False` | `floop/engine.py` |
|
||||
| Arrival check (type check + contradiction) | **STUB**: only UNKNOWN refusal | `machine._append_checked` |
|
||||
| Prover (stop condition, derivability) | **STUB**: question stack terminal | `machine._finish` |
|
||||
| `user` expert | not wired — explicit failure row | `floop/engine.py` |
|
||||
| Backtracking / retraction (TMS) | not in the draft (§5 comes with the prover) | — |
|
||||
| The machine (stack, dependency order, budget, recursion) | real fixed code | `floop/machine.py`, `floop/state.py` |
|
||||
| Evidence table (append-only, provenance, no prose) | real | `floop/state.py` |
|
||||
|
||||
Laws kept: the table only ever receives typed payloads (never LLM prose); rows
|
||||
carry provenance + trace; the machine — not the LLM — owns sequencing, budget,
|
||||
retries and stopping; answer synthesis sees only evidence rows and cites them.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
config.yaml budget + LM providers
|
||||
run_app.py CLI entry
|
||||
floop/state.py EvidenceTable, QuestionStack, Budget, slot instantiation (#En -> value)
|
||||
floop/llm.py dspy LM configuration (OpenAI-compatible endpoints)
|
||||
floop/dspy_modules.py every LLM call as a dspy module (INIT, ROUTE, EXPERT, MISSING, ANSWER)
|
||||
floop/engine.py engine interface + draft stub engines
|
||||
floop/machine.py FloopRun — the loop; recursion for the `floop` attendant
|
||||
tests/state.py unit tests (no LLM)
|
||||
```
|
||||
|
||||
## Next steps (design order from the docs)
|
||||
|
||||
1. Real check layer on expert arrival (well-formedness per expert kind) — the
|
||||
#1 failure mode is misformalization; keep it BEFORE engines.
|
||||
2. `knowledge` expert with real search + verbatim quotes (one vertical E2E).
|
||||
3. Prover for the stop condition (clingo/Z3) — replaces the stub derivability.
|
||||
4. Log every run (v2's router will eat these trajectories).
|
||||
@@ -0,0 +1,22 @@
|
||||
# floop draft config — see README.md
|
||||
lm:
|
||||
# provider selected by FLOOP_LM env var (local | ollama-cloud), default below
|
||||
default: local
|
||||
local:
|
||||
base_url: http://127.0.0.1:11435/v1
|
||||
model: qwen3.8:27b
|
||||
max_tokens: 4096
|
||||
temperature: 0.0
|
||||
ollama-cloud:
|
||||
base_url: https://ollama.com/v1
|
||||
model: glm-5.3-flash
|
||||
max_tokens: 4096
|
||||
temperature: 0.0
|
||||
api_key_env: OLLAMA_API_KEY
|
||||
|
||||
budget:
|
||||
max_llm_calls: 40 # per FLOOP run (children get a slice)
|
||||
min_child_budget: 6
|
||||
max_depth: 2 # recursion cap (PIPELINE.md §8.4)
|
||||
max_retries: 3 # bounded self-refinement on unparseable LLM output
|
||||
missing_extensions: 1 # how many times "what is still missing?" may reopen questions per run
|
||||
@@ -0,0 +1,134 @@
|
||||
"""All LLM calls as dspy modules — v0.1 has only LLM calls; the real engines
|
||||
(check layer, solver/search) are stubs pending v0.2+.
|
||||
|
||||
Laws (ALGORITHM.md §7): LLMs translate and propose; they never decide or compute.
|
||||
Every module's docstring is the draft prompt — kept minimal on purpose.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import dspy
|
||||
|
||||
from .state import AnswerType
|
||||
|
||||
|
||||
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."""
|
||||
question: str = dspy.InputField()
|
||||
subquestions: str = dspy.OutputField(
|
||||
desc="one subquestion per line, pipe-separated fields: "
|
||||
"text | depends_on (line numbers or 'none') | answer_type (OPEN|FUNCTION|INTERVAL|CONSTANT)"
|
||||
)
|
||||
|
||||
|
||||
class RouteSignature(dspy.Signature):
|
||||
"""You are the ROUTE step of a reasoning machine. Pick ONE attendant for the
|
||||
question. The user is a last resort when nothing else plausibly answers it."""
|
||||
question: str = dspy.InputField()
|
||||
catalog: str = dspy.InputField(desc="experts | floop | user, one per line with a summary")
|
||||
evidence: str = dspy.InputField(desc="relevant evidence rows, may be empty")
|
||||
attendant: str = dspy.OutputField(desc="one of: knowledge logic analytic numeric floop user")
|
||||
reason: str = dspy.OutputField(desc="one sentence, for the log")
|
||||
|
||||
|
||||
class ExpertSignature(dspy.Signature):
|
||||
"""You are an expert ATTENDANT whose draft answer is checked by a machine.
|
||||
You translate the question into a typed answer payload — you do not compute
|
||||
values and you never invent facts. Use the evidence you are given, plus
|
||||
facts literally stated in the parent question; if the answer is not
|
||||
derivable from them, say so."""
|
||||
question: str = dspy.InputField()
|
||||
parent_question: str = dspy.InputField(
|
||||
desc="the original user question this subquestion serves; facts literally stated there are permitted sources")
|
||||
expert_kind: str = dspy.InputField(desc="knowledge logic analytic numeric")
|
||||
evidence: str = dspy.InputField(desc="evidence rows this question references")
|
||||
value: str = dspy.OutputField(desc="the answer value in its declared type, or 'UNKNOWN'")
|
||||
source_quote: str = dspy.OutputField(desc="VERBATIM supporting text (from evidence or the parent question); empty if none")
|
||||
confidence: str = dspy.OutputField(desc="high medium low")
|
||||
|
||||
|
||||
class MissingSignature(dspy.Signature):
|
||||
"""You are the MISSING step of a reasoning machine. The goal is NOT yet
|
||||
derivable from the evidence. Ask what is still missing: 1-3 new open
|
||||
subquestions that would close the gap. Use only concepts from the goal and
|
||||
the evidence."""
|
||||
goal: str = dspy.InputField()
|
||||
evidence: str = dspy.InputField()
|
||||
subquestions: str = dspy.OutputField(
|
||||
desc="one subquestion per line, pipe-separated: text | depends_on ('none' or #E refs) | answer_type"
|
||||
)
|
||||
|
||||
|
||||
class AnswerSignature(dspy.Signature):
|
||||
"""You are the ANSWER step of a reasoning machine. Write the final natural
|
||||
language answer to the goal using ONLY the evidence rows. Working only from
|
||||
those rows, cite them; every number or fact carries its row id."""
|
||||
goal: str = dspy.InputField()
|
||||
evidence: str = dspy.InputField()
|
||||
unverified: str = dspy.InputField(desc="'true' if the prover could not verify derivability")
|
||||
final_answer: str = dspy.OutputField(desc="answer in natural language; cite only given row ids; no outside facts")
|
||||
|
||||
|
||||
class FloopModules:
|
||||
"""All LLM entry points of the draft. Each returns a dspy.Prediction."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.init = dspy.Predict(InitSignature)
|
||||
self.route = dspy.Predict(RouteSignature)
|
||||
self.expert = dspy.Predict(ExpertSignature)
|
||||
self.missing = dspy.Predict(MissingSignature)
|
||||
self.answer = dspy.Predict(AnswerSignature)
|
||||
|
||||
def init_decompose(self, question: str) -> list[dict]:
|
||||
pred = self.init(question=question)
|
||||
return parse_subquestions(pred.subquestions)
|
||||
|
||||
def missing_decompose(self, goal: str, evidence: str) -> list[dict]:
|
||||
pred = self.missing(goal=goal, evidence=evidence)
|
||||
return parse_subquestions(pred.subquestions)
|
||||
|
||||
def route_question(self, question: str, catalog: str, evidence: str) -> tuple[str, str]:
|
||||
pred = self.route(question=question, catalog=catalog, evidence=evidence)
|
||||
return pred.attendant.strip().lower(), pred.reason.strip()
|
||||
|
||||
def expert_draft(self, question: str, expert_kind: str, evidence: str,
|
||||
parent_question: str = "") -> dict:
|
||||
pred = self.expert(question=question, parent_question=parent_question,
|
||||
expert_kind=expert_kind, evidence=evidence)
|
||||
return {
|
||||
"value": pred.value.strip(),
|
||||
"source_quote": pred.source_quote.strip(),
|
||||
"confidence": pred.confidence.strip().lower(),
|
||||
}
|
||||
|
||||
def synthesize(self, goal: str, evidence: str, unverified: bool) -> str:
|
||||
pred = self.answer(goal=goal, evidence=evidence, unverified="true" if unverified else "false")
|
||||
return pred.final_answer.strip()
|
||||
|
||||
|
||||
def parse_subquestions(raw: str) -> list[dict]:
|
||||
""">> parse the piped lines from INIT/MISSING: text | deps | answer_type."""
|
||||
out: list[dict] = []
|
||||
for line in (raw or "").strip().splitlines():
|
||||
line = line.strip().lstrip("-•* ").strip()
|
||||
if not line or "|" not in line:
|
||||
continue
|
||||
parts = [p.strip() for p in line.split("|")]
|
||||
text = parts[0]
|
||||
if not text:
|
||||
continue
|
||||
deps_raw = parts[1].lower() if len(parts) > 1 else "none"
|
||||
atype_raw = parts[2].upper() if len(parts) > 2 else "OPEN"
|
||||
deps: list = []
|
||||
for tok in deps_raw.replace(",", " ").split():
|
||||
if tok in ("none", "-", "—", ""):
|
||||
continue
|
||||
if tok.startswith("#"):
|
||||
deps.append("#E" + tok.lstrip("#eE"))
|
||||
elif tok.isdigit():
|
||||
deps.append(int(tok)) # sibling line number, resolved by the machine
|
||||
atype = next((t for t in AnswerType if t.value == atype_raw), AnswerType.OPEN)
|
||||
out.append({"text": text, "deps": deps, "answer_type": atype})
|
||||
return out
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Expert engines for the draft: the LLM IS the engine; deterministic engines come later.
|
||||
|
||||
The Engine interface and its laws are already the real ones: the instantiated
|
||||
question in, typed payload out — never free-form rows. Stub engines mark
|
||||
verified=False; the arrival check (in the machine) refuses UNKNOWN.
|
||||
|
||||
Routing (v0.1) — catalogue + one LLM judgement per question. Learned router:
|
||||
v2 (PIPELINE.md §7); logged trajectories train it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Callable, Protocol
|
||||
|
||||
from .state import AnswerType, EvidenceRow, EvidenceTable
|
||||
|
||||
CATALOG = (
|
||||
"knowledge: answer factual questions with verbatim quotes from the evidence and the parent question\n"
|
||||
"logic: derive conclusions validly from provided premises\n"
|
||||
"analytic: solve equations / symbolic relations over provided quantities\n"
|
||||
"numeric: evaluate a closed arithmetic expression over provided numbers\n"
|
||||
"floop: this question is too big for one call — decompose it (recurse)\n"
|
||||
"user: nothing else plausibly covers it — ask the person"
|
||||
)
|
||||
|
||||
NO_ROUTER = ["knowledge", "logic", "analytic", "numeric", "floop", "user"]
|
||||
|
||||
|
||||
class Engine(Protocol):
|
||||
def run(self, qid: str, question: str, parent_question: str,
|
||||
table: EvidenceTable, answer_type: AnswerType) -> EvidenceRow: ...
|
||||
|
||||
|
||||
class LLMExpertEngine:
|
||||
"""Draft engine: the dspy call produces the draft; a stub check layer passes
|
||||
it through with verified=False. Each engine call charges the LLM budget."""
|
||||
|
||||
def __init__(self, modules, charge_llm: Callable[[], None],
|
||||
expert_kind: str = "expert") -> None:
|
||||
self.modules = modules
|
||||
self.charge = charge_llm
|
||||
self.kind = expert_kind
|
||||
self.name = f"stub:{expert_kind}"
|
||||
|
||||
def run(self, qid, question, parent_question, table, answer_type):
|
||||
self.charge() # the engine IS an LLM call in this draft — it costs budget
|
||||
ev = table.dump()
|
||||
draft = self.modules.expert_draft(
|
||||
question, self.kind, ev, parent_question=parent_question)
|
||||
verified = False # v0.2: formal check layer (sorts/units/consistency) BEFORE engine
|
||||
payload: dict = {"value": draft["value"]}
|
||||
if draft["source_quote"]:
|
||||
payload["quote"] = draft["source_quote"]
|
||||
prov = {"expert": self.kind, "note": "draft v0.1 — no real engine, no check layer"}
|
||||
if parent_question:
|
||||
prov["parent_question"] = parent_question
|
||||
return EvidenceRow(
|
||||
qid=qid,
|
||||
answer_type=answer_type,
|
||||
payload=payload,
|
||||
engine=self.name,
|
||||
trace=[f"llm draft: value={draft['value']} confidence={draft['confidence']}"],
|
||||
provenance=prov,
|
||||
verified=verified,
|
||||
note="" if str(draft["value"]).upper() != "UNKNOWN" else "expert reported UNKNOWN",
|
||||
)
|
||||
|
||||
|
||||
class UserRequestEngine:
|
||||
"""v0.1: the user expert is not wired (no chat channel); returns an explicit failure row."""
|
||||
|
||||
def __init__(self, modules) -> None:
|
||||
self.modules = modules
|
||||
self.name = "stub:user"
|
||||
|
||||
def run(self, qid, question, parent_question, table, answer_type):
|
||||
prov = {"expert": "user"}
|
||||
if parent_question:
|
||||
prov["parent_question"] = parent_question
|
||||
return EvidenceRow(
|
||||
qid=qid,
|
||||
answer_type=answer_type,
|
||||
payload={"value": "UNKNOWN"},
|
||||
engine=self.name,
|
||||
trace=["user expert not wired in draft"],
|
||||
provenance=prov,
|
||||
verified=False,
|
||||
note="needs_user_input",
|
||||
)
|
||||
@@ -0,0 +1,41 @@
|
||||
"""LM configuration: dspy.LM over OpenAI-compatible endpoints (no API keys in code).
|
||||
|
||||
dspy 3.x routes through litellm, so model ids carry the provider prefix —
|
||||
"openai/<model>" for any OpenAI-compatible endpoint (local ollama or ollama-cloud).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import dspy
|
||||
import yaml
|
||||
|
||||
|
||||
def _load_yaml() -> dict:
|
||||
cfg = Path(__file__).resolve().parent.parent / "config.yaml"
|
||||
return yaml.safe_load(cfg.read_text())
|
||||
|
||||
|
||||
def configure_lm() -> dict:
|
||||
"""Configure dspy's default LM from config.yaml + FLOOP_LM env override.
|
||||
|
||||
Returns the active provider settings (for provenance logs).
|
||||
"""
|
||||
cfg = _load_yaml()["lm"]
|
||||
provider = os.environ.get("FLOOP_LM", cfg["default"])
|
||||
if provider not in cfg:
|
||||
raise ValueError(f"unknown FLOOP_LM provider {provider!r}; options: {list(cfg)[1:]}")
|
||||
p = cfg[provider]
|
||||
|
||||
kwargs: dict = {
|
||||
"model": f"openai/{p['model']}",
|
||||
"base_url": p["base_url"],
|
||||
"api_base": p["base_url"],
|
||||
"max_tokens": p["max_tokens"],
|
||||
"temperature": p["temperature"],
|
||||
"api_key": os.environ.get(p.get("api_key_env", ""), "empty"),
|
||||
}
|
||||
lm = dspy.LM(**kwargs)
|
||||
dspy.configure(lm=lm)
|
||||
return {"provider": provider, "model": p["model"], "base_url": p["base_url"]}
|
||||
@@ -0,0 +1,207 @@
|
||||
"""The machine — fixed control code. The LLM proposes; the machine disposes.
|
||||
|
||||
ALGORITHM.md mapping (v0.1 draft — every STUB is named honestly):
|
||||
- INIT/MISSING/ROUTE/ANSWER are dspy LLM calls (dspy_modules.py)
|
||||
- the check layer and the prover are STUBS: no formal verification happens,
|
||||
so NOTHING is ever marked verified — the honest Unverified fallback
|
||||
- expert engines are STUBS: the LLM call itself is the draft engine (engine.py)
|
||||
- the stop condition is the question stack going terminal, not a prover check
|
||||
- recursion: FLOOP-on-a-question with a budget slice and a depth cap (§4)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from .engine import CATALOG, LLMExpertEngine, UserRequestEngine
|
||||
from .dspy_modules import FloopModules
|
||||
from .state import (Budget, BudgetExhausted, EvidenceRow, EvidenceTable,
|
||||
OpenQuestion, QuestionStack, instantiate)
|
||||
|
||||
EXPERT_ENGINES = ("knowledge", "logic", "analytic", "numeric")
|
||||
|
||||
|
||||
def _coerce_atype(value) -> "AnswerType":
|
||||
from .state import AnswerType as AT
|
||||
if isinstance(value, AT):
|
||||
return value
|
||||
try:
|
||||
return AT(str(value).upper())
|
||||
except ValueError:
|
||||
return AT.OPEN
|
||||
|
||||
|
||||
@dataclass
|
||||
class RunReport:
|
||||
goal: str
|
||||
final_answer: str
|
||||
verified: bool
|
||||
llm_calls: int
|
||||
engine_calls: int
|
||||
depth: int
|
||||
notes: list[str] = field(default_factory=list)
|
||||
questions: list[tuple] = field(default_factory=list) # (qid, status, text)
|
||||
evidence_rows: list[str] = field(default_factory=list) # rendered row summaries
|
||||
elapsed_s: float = 0.0
|
||||
|
||||
|
||||
class FloopRun:
|
||||
"""One FLOOP execution over one question (top-level or recursive child)."""
|
||||
|
||||
def __init__(self, question: str, budget: Budget, depth: int = 0,
|
||||
modules: FloopModules | None = None, parent_goal: str = "") -> None:
|
||||
self.query = question
|
||||
self.budget = budget
|
||||
self.depth = depth
|
||||
self.parent_goal = parent_goal
|
||||
self.modules = modules or FloopModules()
|
||||
self.table = EvidenceTable()
|
||||
self.stack = QuestionStack(question)
|
||||
self.user_engine = UserRequestEngine(self.modules)
|
||||
self.notes: list[str] = []
|
||||
self.engine_calls = 0
|
||||
|
||||
# ---- budget -----------------------------------------------------------
|
||||
|
||||
def _charge(self) -> None:
|
||||
self.budget.charge_llm()
|
||||
|
||||
# ---- the loop (ALGORITHM.md §2) ----------------------------------------
|
||||
|
||||
def run(self) -> RunReport:
|
||||
t0 = time.time()
|
||||
self._init_decompose()
|
||||
while True:
|
||||
try:
|
||||
q = self.stack.pickable(self.table)
|
||||
if q is None:
|
||||
if self.stack.all_terminal():
|
||||
break
|
||||
if self.budget.missing_used >= self.budget.missing_extensions:
|
||||
self.notes.append("missing-extension limit reached; questions may still be open")
|
||||
break
|
||||
self._missing_round()
|
||||
continue
|
||||
self._route_and_execute(q)
|
||||
except BudgetExhausted:
|
||||
self.notes.append(f"budget exhausted at llm_calls={self.budget.llm_calls}")
|
||||
break
|
||||
return self._finish(t0)
|
||||
|
||||
# ---- steps -------------------------------------------------------------
|
||||
|
||||
def _init_decompose(self) -> None:
|
||||
self._charge()
|
||||
subs = self.modules.init_decompose(self.query)
|
||||
self._add_questions(subs, reason="init")
|
||||
|
||||
def _missing_round(self) -> None:
|
||||
self._charge()
|
||||
self.budget.missing_used += 1
|
||||
subs = self.modules.missing_decompose(self.query, self.table.dump())
|
||||
self._add_questions(subs, reason="missing")
|
||||
|
||||
def _add_questions(self, subs: list[dict], reason: str) -> None:
|
||||
created: list[OpenQuestion] = []
|
||||
for s in subs:
|
||||
created.append(self.stack.add(OpenQuestion(
|
||||
text=s["text"], answer_type=_coerce_atype(s["answer_type"]),
|
||||
reason=reason)))
|
||||
# resolve deps: sibling line numbers -> sibling qids; #E refs are not
|
||||
# dependencies (their rows already exist or never will) — the text keeps
|
||||
# the reference and instantiate() substitutes it at pick time.
|
||||
for q, s in zip(created, subs):
|
||||
resolved = []
|
||||
for tok in s["deps"]:
|
||||
if isinstance(tok, int) and 1 <= tok <= len(created):
|
||||
resolved.append(created[tok - 1].qid)
|
||||
q.deps = resolved
|
||||
|
||||
def _route_and_execute(self, q: OpenQuestion) -> None:
|
||||
self._charge()
|
||||
attendant, why = self.modules.route_question(q.text, CATALOG, self._context(q))
|
||||
|
||||
if attendant == "floop":
|
||||
self._execute_child(q)
|
||||
elif attendant == "user":
|
||||
row = self.user_engine.run(q.qid, instantiate(q.text, self.table),
|
||||
self.query, self.table, q.answer_type)
|
||||
self.table.append(row)
|
||||
self.engine_calls += 1
|
||||
q.status = "failed"
|
||||
q.reason = "user expert not wired (draft)"
|
||||
elif attendant in EXPERT_ENGINES:
|
||||
engine = LLMExpertEngine(self.modules, self._charge, expert_kind=attendant)
|
||||
row = engine.run(q.qid, instantiate(q.text, self.table),
|
||||
self.query, self.table, q.answer_type)
|
||||
self.engine_calls += 1
|
||||
self._append_checked(row, q)
|
||||
else:
|
||||
self.notes.append(f"router returned invalid attendant {attendant!r} for {q.qid}")
|
||||
self.table.append(EvidenceRow(
|
||||
qid=q.qid, answer_type=q.answer_type, payload={"value": "UNKNOWN"},
|
||||
engine=f"unrouted:{attendant}", trace=[why], provenance={},
|
||||
verified=False, note="route_invalid"))
|
||||
q.status = "failed"
|
||||
q.reason = "route invalid"
|
||||
|
||||
def _execute_child(self, q: OpenQuestion) -> None:
|
||||
if self.depth + 1 > self.budget.max_depth:
|
||||
self.notes.append(f"{q.qid}: depth cap reached; refusing to recurse")
|
||||
q.status = "failed"
|
||||
q.reason = "depth cap"
|
||||
return
|
||||
child_budget = self.budget.slice_for_child()
|
||||
child = FloopRun(question=instantiate(q.text, self.table),
|
||||
budget=child_budget, depth=self.depth + 1,
|
||||
modules=self.modules, parent_goal=self.query)
|
||||
report = child.run()
|
||||
self.budget.llm_calls += child_budget.llm_calls
|
||||
row = EvidenceRow(
|
||||
qid=q.qid, answer_type=q.answer_type,
|
||||
payload={"value": report.final_answer},
|
||||
engine="floop-child",
|
||||
trace=[f"child run: {report.llm_calls} llm calls, {len(report.evidence_rows)} rows"],
|
||||
provenance={"depth": self.depth + 1, "llm_calls": report.llm_calls},
|
||||
verified=False, # child answers carry no proof in the draft
|
||||
note="child answer unverified")
|
||||
self.table.append(row)
|
||||
self.engine_calls += 1
|
||||
q.status = "answered"
|
||||
|
||||
def _append_checked(self, row: EvidenceRow, q: OpenQuestion) -> None:
|
||||
"""STUB arrival check (design: type check + contradiction check). Only the
|
||||
trivial refusal fires: an expert that reports UNKNOWN fails its question."""
|
||||
self.table.append(row)
|
||||
if str(row.payload.get("value", "")).strip().upper() == "UNKNOWN":
|
||||
q.status = "failed"
|
||||
q.reason = "expert returned UNKNOWN"
|
||||
else:
|
||||
q.status = "answered"
|
||||
|
||||
def _context(self, q: OpenQuestion) -> str:
|
||||
lines = []
|
||||
for d in q.deps:
|
||||
rows = self.table.for_question(d)
|
||||
for r in rows:
|
||||
lines.append(f"{r.eid}: {r.payload.get('value', r.payload.get('quote', ''))}")
|
||||
return "\n".join(lines)
|
||||
|
||||
# ---- answer ------------------------------------------------------------
|
||||
|
||||
def _finish(self, t0: float) -> RunReport:
|
||||
verified = False # STUB prover — v0.2: derivability check (clingo/Z3)
|
||||
answer = ""
|
||||
try:
|
||||
self._charge()
|
||||
answer = self.modules.synthesize(
|
||||
self.query, self.table.dump(), unverified=not verified)
|
||||
except BudgetExhausted:
|
||||
self.notes.append("budget died before the answer step")
|
||||
return RunReport(
|
||||
goal=self.query, final_answer=answer, verified=verified,
|
||||
llm_calls=self.budget.llm_calls, engine_calls=self.engine_calls,
|
||||
depth=self.depth, notes=self.notes,
|
||||
questions=[(i.qid, i.status, i.text) for i in self.stack.items],
|
||||
evidence_rows=self.table.dump().splitlines(),
|
||||
elapsed_s=round(time.time() - t0, 1))
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Shared state: evidence table, open questions, budget. The machine's data structures.
|
||||
|
||||
Laws enforced here (PIPELINE.md §5):
|
||||
- the table is append-only; retraction is a flag, never a deletion
|
||||
- every row carries provenance and a trace
|
||||
- prose is never stored: payload is a typed dict; verbatim quotes live in payload["quote"]
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class AnswerType(str, Enum):
|
||||
OPEN = "OPEN"
|
||||
FUNCTION = "FUNCTION"
|
||||
INTERVAL = "INTERVAL"
|
||||
CONSTANT = "CONSTANT"
|
||||
|
||||
|
||||
class BudgetExhausted(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class OpenQuestion:
|
||||
text: str
|
||||
answer_type: AnswerType = AnswerType.OPEN
|
||||
deps: list[str] = field(default_factory=list) # qids this question waits on
|
||||
parent_goal: bool = False
|
||||
reason: str = "" # init | missing | child-goal
|
||||
qid: str = "" # assigned by QuestionStack
|
||||
status: str = "open" # open | answered | failed
|
||||
|
||||
|
||||
@dataclass
|
||||
class EvidenceRow:
|
||||
answer_type: AnswerType
|
||||
payload: dict # typed fields; for knowledge: {"quote": ..., "url": ...} verbatim only
|
||||
engine: str # e.g. "stub:knowledge", "floop-child"
|
||||
eid: str = "" # assigned by EvidenceTable.append
|
||||
qid: str = ""
|
||||
trace: list[str] = field(default_factory=list)
|
||||
provenance: dict = field(default_factory=dict) # expert, llm_calls, ts, cost
|
||||
verified: bool = False
|
||||
note: str = "" # type mismatches, failures — never prose claims
|
||||
retracted: bool = False
|
||||
|
||||
|
||||
class EvidenceTable:
|
||||
def __init__(self) -> None:
|
||||
self._rows: list[EvidenceRow] = []
|
||||
self._next = 1
|
||||
|
||||
def append(self, row: EvidenceRow) -> EvidenceRow:
|
||||
if row.payload is None or not isinstance(row.payload, dict):
|
||||
raise ValueError("payload must be a typed dict — no free-form prose (table law 4)")
|
||||
row.eid = f"E{self._next}"
|
||||
self._next += 1
|
||||
self._rows.append(row) # append-only
|
||||
return row
|
||||
|
||||
def row(self, eid: str) -> EvidenceRow | None:
|
||||
return next((r for r in self._rows if r.eid == eid), None)
|
||||
|
||||
def rows(self) -> list[EvidenceRow]:
|
||||
return list(self._rows)
|
||||
|
||||
def for_question(self, qid: str) -> list[EvidenceRow]:
|
||||
return [r for r in self._rows if r.qid == qid]
|
||||
|
||||
def dump(self) -> str:
|
||||
out = []
|
||||
for r in self._rows:
|
||||
mark = "verified" if r.verified else "unverified"
|
||||
ret = " RETRACTED" if r.retracted else ""
|
||||
out.append(
|
||||
f"{r.eid} (answers {r.qid}, {r.answer_type.value}, {mark}{ret}) "
|
||||
f"engine={r.engine} payload={json.dumps(r.payload, ensure_ascii=False)}"
|
||||
+ (f" note={r.note}" if r.note else "")
|
||||
)
|
||||
return "\n".join(out) if out else "(empty)"
|
||||
|
||||
|
||||
class QuestionStack:
|
||||
def __init__(self, goal: str) -> None:
|
||||
self.goal = OpenQuestion(text=goal, parent_goal=True, reason="user question")
|
||||
self.goal.qid = "Q0"
|
||||
self.items: list[OpenQuestion] = [self.goal]
|
||||
self._next = 1
|
||||
|
||||
def add(self, q: OpenQuestion) -> OpenQuestion:
|
||||
q.qid = f"Q{self._next}"
|
||||
self._next += 1
|
||||
self.items.append(q)
|
||||
return q
|
||||
|
||||
def pickable(self, table: EvidenceTable) -> OpenQuestion | None:
|
||||
"""First open question whose deps are answered. Dependency order IS execution order — no search."""
|
||||
failed_qids = {i.qid for i in self.items if i.status == "failed" and not i.parent_goal}
|
||||
updated = True
|
||||
while updated: # cascade: a failed dependency kills its dependents too
|
||||
updated = False
|
||||
for q in self.items:
|
||||
if q.status != "open" or q.parent_goal:
|
||||
continue
|
||||
if table.for_question(q.qid):
|
||||
continue # already has evidence — never re-picked (loop guard)
|
||||
dead = [d for d in q.deps if d in failed_qids]
|
||||
if dead:
|
||||
q.status = "failed"
|
||||
q.reason = "dependency failed: " + ",".join(dead)
|
||||
failed_qids.add(q.qid)
|
||||
updated = True
|
||||
continue
|
||||
if all(table.for_question(d) for d in q.deps):
|
||||
return q
|
||||
return None
|
||||
|
||||
def open_count(self) -> int:
|
||||
return sum(1 for q in self.items if q.status == "open" and not q.parent_goal)
|
||||
|
||||
def all_terminal(self) -> bool:
|
||||
"""Every subquestion answered or failed — the goal itself is 'answered'
|
||||
by the synthesis step, not by a row (prover stub lives in the machine)."""
|
||||
return all(q.status in ("answered", "failed")
|
||||
for q in self.items if not q.parent_goal)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Budget:
|
||||
max_llm_calls: int
|
||||
max_depth: int
|
||||
max_retries: int
|
||||
missing_extensions: int
|
||||
min_child_budget: int = 6
|
||||
llm_calls: int = 0
|
||||
engine_calls: int = 0
|
||||
missing_used: int = 0
|
||||
|
||||
def charge_llm(self) -> None:
|
||||
if self.llm_calls >= self.max_llm_calls:
|
||||
raise BudgetExhausted(f"llm_calls={self.llm_calls}/{self.max_llm_calls}")
|
||||
self.llm_calls += 1
|
||||
|
||||
def slice_for_child(self) -> "Budget":
|
||||
remaining = self.max_llm_calls - self.llm_calls
|
||||
child = Budget(
|
||||
max_llm_calls=max(self.min_child_budget, remaining // 2),
|
||||
max_depth=self.max_depth,
|
||||
max_retries=self.max_retries,
|
||||
missing_extensions=self.missing_extensions,
|
||||
min_child_budget=self.min_child_budget,
|
||||
)
|
||||
return child
|
||||
|
||||
|
||||
def instantiate(text: str, table: EvidenceTable) -> str:
|
||||
"""ReWOO plan-on-slots: replace #E<n> references with the row's value."""
|
||||
def sub(m: re.Match) -> str:
|
||||
r = table.row(f"E{m.group(1)}")
|
||||
if r is None:
|
||||
return m.group(0)
|
||||
val = r.payload.get("value", r.payload.get("quote", r.payload.get("user_reply")))
|
||||
if val is None:
|
||||
val = json.dumps(r.payload, ensure_ascii=False)
|
||||
return str(val)
|
||||
|
||||
return re.sub(r"#E(\d+)", sub, text)
|
||||
@@ -0,0 +1,237 @@
|
||||
# Knowledge expert — design (v0.1 draft, pre-implementation)
|
||||
|
||||
Status: DESIGN FOR REVIEW — nothing built yet. This document is the "pensem-lo bé".
|
||||
|
||||
## 0. What this expert is
|
||||
|
||||
One attendant of the fleet, answering per the generic expert pattern
|
||||
(translate → check → solve → return), where the engine is **retrieval over
|
||||
sources plus a persistent typed store**. Its contract with the machine
|
||||
unchanged from PIPELINE.md:
|
||||
|
||||
- in: an instantiated question (+ parent question + referenced evidence rows)
|
||||
- out: typed evidence rows — **verbatim quote + url + access date**, never paraphrase
|
||||
- the KG (`KnowledgeStore`) is the expert's private engine-side memory:
|
||||
persistent across runs, append-only, fully provenance-tracked.
|
||||
|
||||
Its novelty over GraphRAG/HippoRAG-style systems is the floop law applied as a
|
||||
real formal check: **every extracted fact must carry a verbatim span that is
|
||||
string-containment-verified against the fetched document text** — a cheap,
|
||||
deterministic, sound check that runs today (no solver needed). Nothing enters
|
||||
the store without it. Nothing leaves it without provenance.
|
||||
|
||||
Prior art with measured numbers (verified 2026-10-10, re-verify before claiming
|
||||
current SOTA — skill convention):
|
||||
|
||||
| System | Mechanism | Measured | What we take |
|
||||
|---|---|---|---|
|
||||
| HippoRAG (arXiv:2405.14831, NeurIPS'24) | KG + Personalized PageRank as retrieval | up to +20% multi-hop QA vs SOTA RAG; 10–30× cheaper and 6–13× faster than IRCoT | KG-first probe; single-step graph search replaces iterative LLM retrieval |
|
||||
| GraphRAG (arXiv:2404.16130, MSR) | LLM entity-extraction per chunk → graph → community summaries | 72–83% comprehensiveness win-rate vs vector RAG; up to 97% fewer tokens for global summaries; **bigger chunks = fewer calls but fewer entities extracted** | map-reduce extraction; the chunk-size tradeoff is a measured finding, not a guess |
|
||||
| ReWOO (arXiv:2305.18323) | plan-on-slots | 5× token efficiency | already in floop's orchestration; the expert must not duplicate it |
|
||||
| CYC (lesson, reference file) | manual knowledge acquisition killed the project | — | tiny closed ontology, auto-extraction, never hand-built |
|
||||
| LLM-Modulo (arXiv:2402.01817) | LLMs propose, external verifiers decide | — | quote-containment check = the verifier here |
|
||||
|
||||
What is floop-native: the store's laws (append-only, retraction flags, TMS-ready
|
||||
provenance, closed ontology sort-checks) and the verbatim-span containment as a
|
||||
first-class gate. Also the *engine-first, LLM-second* loop inside the expert.
|
||||
|
||||
## 1. The two halves, as Emili framed them
|
||||
|
||||
1. **Store (the KG)** — persistent knowledge: entities, typed relations
|
||||
between them, and verbatim quotes backing every edge. Consulted FIRST.
|
||||
2. **Gather (searcher + extractor)** — fills gaps: search → fetch → chunk →
|
||||
extract → check → store → select. Consulted for what the KG lacks.
|
||||
|
||||
## 2. The store — `KnowledgeStore`
|
||||
|
||||
Format decision (recommendation): **SQLite** (single file, stdlib, auditable,
|
||||
zero infra) + **JSONL mirror** for human diff/audit. Graph algorithms via
|
||||
NetworkX loaded from the DB on demand. No vector DB, no server. When measured
|
||||
recall failure justifies embeddings, that is a later decision with numbers —
|
||||
not now.
|
||||
|
||||
Schema (append-only; **no UPDATE/DELETE ever** — corrections and conflicts are
|
||||
new rows or retraction flags, TMS-ready like the evidence table):
|
||||
|
||||
```
|
||||
documents(id, url, source, fetched_at, sha256, trusted, text_path)
|
||||
chunks(id, doc_id, section_path, position, char_start, char_end, sha256)
|
||||
quotes(id, doc_id, chunk_id, verbatim, url, access_date) -- canonical text
|
||||
nodes(id, norm_name, sort, mentions++ ) -- entity index
|
||||
edges(src_node, rel, dst_value, dst_node?, quote_id, subject?, extraction_confidence, retracted)
|
||||
conflicts(nodeA, rel, valueA, valueB, nodeA_quote, nodeB_quote) -- surfaced, never resolved silently
|
||||
```
|
||||
|
||||
- Edges are **pointers**, not prose: `(Shor's algorithm, requires, Grover→…)`.
|
||||
The QUOTE carries the truth; the edge is the index structure that finds it.
|
||||
Relation names come from the closed ontology — that is how they pass checks.
|
||||
- `dst_value` for literal quantities: value + **unit** fields (Quantity sort).
|
||||
This is the bridge to `analytic`/`numeric`: knowledge extracts typed
|
||||
quantities; those experts compute on them. Neuro-symbolic payoff, by design.
|
||||
- Duplicate edge from two sources = **corroboration count** on the edge. Same
|
||||
subject+relation with two different literal values = never merged — a
|
||||
`conflicts` row is created and surfaced, exactly the "never silently pick a
|
||||
side" law the machine already uses for user rows.
|
||||
- Entity node identity, draft: `(normalized_name, sort)` with normalization =
|
||||
casefold + punctuation strip. Entity resolution is hard; the draft merges
|
||||
ONLY on normalized-name equality within the same sort. Everything else stays
|
||||
as separate nodes until evidence forces a merge decision (later, with LLM
|
||||
linker, measured).
|
||||
- KG probe (engine, deterministic): seed = question's mentions matched to
|
||||
nodes (lexical, draft; LLM linker later); traversal = BFS depth-1 neighborhood
|
||||
with corroboration-weighted ranking (draft). **PPR is the upgrade path** —
|
||||
HippoRAG's exact mechanism, one function away, adopt it when BFS recall
|
||||
measurably fails. No LLM inside the probe.
|
||||
|
||||
## 3. The closed ontology (the typed grammar)
|
||||
|
||||
Same philosophy as the orchestrator's ~5 action schemas: tiny ontology, big
|
||||
discipline. Seed set (Emili extends at review):
|
||||
|
||||
- Entity sorts: `PERSON, ORGANIZATION, CONCEPT, EVENT, QUANTITY, DOCUMENT, PLACE, DATE, OTHER`
|
||||
- Relations (subject_sort → object_sort, checked by the sort-checker):
|
||||
`HAS_PROPERTY, PART_OF, INSTANCE_OF, OCCURRED_AT(→DATE), LOCATED_AT(→PLACE),
|
||||
CAUSED_BY, REQUIRES(→CONCEPT), MEASURES(→QUANTITY), DEFINED_AS, AUTHORED_BY(→PERSON)`
|
||||
|
||||
Checks (all deterministic, all code, no LLM):
|
||||
1. **quote containment** — `verbatim span ⊆ document text` (against the FULL
|
||||
fetched text, not just the chunk, so chunk-boundary facts still validate)
|
||||
2. **sort check** — a relation's endpoint sorts must match its declaration
|
||||
3. **source trust** — url domain ∈ trusted list (`en.wikipedia.org` + family,
|
||||
`arxiv.org`; list in config)
|
||||
4. **dedupe** — exact (node, rel, value, doc) repeated
|
||||
5. quantity well-formedness — unit string parses, value parses
|
||||
|
||||
## 4. Gather — the pipeline inside one knowledge call
|
||||
|
||||
One routed knowledge question = one internal pipeline run, bounded by budget:
|
||||
|
||||
```
|
||||
question instantiate (already done by the machine)
|
||||
│
|
||||
▼ TRANSLATE (LLM): question + answer_type → retrieval focus:
|
||||
│ keywords, entry entities, what shape of fact closes the gap
|
||||
▼ KG PROBE (engine): BFS from seeds → candidate edges + linked quotes
|
||||
│ gap report: is the question's answer_type coverable from what's found?
|
||||
│ YES → skip gather, go to SELECT
|
||||
▼ SEARCH (engine): Wikipedia API (draft: wiki-only; general web injectable later)
|
||||
│ ≤ N rounds; known-entity docs fetched directly (probe already knows the URL)
|
||||
▼ FETCH→CHUNK (engine): text extraction, section-aware split, size guard
|
||||
▼ EXTRACT (LLM, map over chunks): candidates with verbatim spans
|
||||
│ bounded retries (≤3): invalid output → error fed back (Logic-LM style)
|
||||
▼ CHECK (engine): containment, sorts, trust, dedupe — invalid candidates dropped+counted
|
||||
▼ MERGE (engine): into store; corroboration counts, conflict rows
|
||||
▼ SELECT (engine, deterministic: lexical overlap + corroboration; reranker later)
|
||||
│
|
||||
▼ return: top-k rows payload {quote, url, access_date, kg_corroboration}
|
||||
```
|
||||
|
||||
LLM calls: TRANSLATE, EXTRACT-per-chunk (+ retries), and nothing else — the
|
||||
probe, search, chunking, checking, merging, selecting are all engines. That is
|
||||
the law compliance: the LLM translates; deterministic code decides what is
|
||||
valid, what is dedupe, what is ranked.
|
||||
|
||||
## 5. Context budget & chunking (the 16–32k constraint)
|
||||
|
||||
- Extraction call input = prompt + ontology + chunk (+section header path).
|
||||
Target chunk **8k tokens (~32k chars)**, hard cap **12k (~48k chars)** —
|
||||
comfortable inside the 16–32k window with prompt+output headroom.
|
||||
- Chunking is **section-aware**: Wikipedia HTML → text with heading markers →
|
||||
chunks split at heading boundaries, then size-guard packed (no mid-section
|
||||
split unless a section alone exceeds the cap; then sentence-boundary split).
|
||||
Heading path carried as chunk context prefix. No overlap needed for the
|
||||
CHECK (containment runs against full text); a 1-sentence overlap only if
|
||||
extraction quality measurably needs it.
|
||||
- **Lexical gate before spending LLM calls** (GraphRAG's tax is real):
|
||||
chunk-level keyword filter (question keywords + entity names, casefold) —
|
||||
only chunks that hit earn an extraction call, up to
|
||||
`max_chunks_per_article_extracted` per article. All other chunks skip; the
|
||||
gate is transparent (logged: chunks skipped and why).
|
||||
- Token counting: chars/4 estimate in the draft (conservative); a real
|
||||
tokenizer when we get the first measured overrun. Estimator failure mode is
|
||||
"chunk slightly smaller than needed" — safe direction.
|
||||
- Numbers to respect when measuring later: GraphRAG's finding — bigger chunks
|
||||
save LLM calls but extract fewer entities; our 8k/12k split sits mid-spectrum
|
||||
by design; revisit with our own entity-yield numbers after first runs.
|
||||
|
||||
## 6. Budget & config mapping
|
||||
|
||||
The expert's internal LLM calls charge the FLOOP run budget (the engine IS the
|
||||
budget owner; the machine's charge callback is passed in). New config block:
|
||||
|
||||
```yaml
|
||||
knowledge:
|
||||
trusted_domains: [en.wikipedia.org, es.wikipedia.org, ca.wikipedia.org, arxiv.org]
|
||||
max_search_rounds: 2 # per knowledge call
|
||||
max_articles_per_round: 3
|
||||
chunk_tokens_target: 8000 # ~32k chars
|
||||
chunk_tokens_max: 12000 # hard ceiling per extraction call
|
||||
gate_min_hits: 1 # lexical gate: keyword hits needed to earn extraction
|
||||
max_chunks_extracted_per_article: 12
|
||||
max_extract_retries: 3 # bounded self-refinement (the 3-attempts law)
|
||||
kg_max_new_nodes_per_call: 200
|
||||
kg_probe_depth: 1 # BFS; PPR upgrade is planned, not implemented
|
||||
kb_path: knowledge_store/kg.sqlite (+ .jsonl mirror)
|
||||
```
|
||||
|
||||
Failure → honesty: probe miss + search/fetch fail + all candidates rejected ⇒
|
||||
the expert returns an UNKNOWN row (the machine's arrival check handles the
|
||||
cascade, seen working in Run A). A knowledge row without a containment-verified
|
||||
span **cannot exist**.
|
||||
|
||||
Honesty markers on returned rows: the draft's rows stay `verified=False` (prover
|
||||
stub) but carry a strong, real note: `source-verified: verbatim containment in
|
||||
trusted doc` (+ corroboration count). That is a meaningful upgrade over the
|
||||
current stub expert, which appends unprovenanced drafts.
|
||||
|
||||
## 7. What is deliberately NOT in the draft (name it, don't hide it)
|
||||
|
||||
- No vector/embedding retrieval — lexical + graph first; add when recall fails
|
||||
measurably (a decision with numbers, v-next).
|
||||
- No general-web search — Wikipedia only (trusted list); web-search injectable
|
||||
interface exists so tests are deterministic; real general search comes after
|
||||
the Wikipedia vertical is measured.
|
||||
- No PPR — BFS probe first (n-hop, corroboration-weighted); upgrade on evidence.
|
||||
- No LLM entity linker — normalized-name match first.
|
||||
- No conflict resolution — conflicts recorded and surfaced, never resolved.
|
||||
- No incremental KG maintenance policy (when to re-fetch for freshness) —
|
||||
access-date provenance is captured now; policy later.
|
||||
|
||||
## 8. Law compliance check (PIPELINE/ALGORITHM)
|
||||
|
||||
| Law | How this design holds it |
|
||||
|---|---|
|
||||
| LLMs translate, never decide/compute | LLM does query-focus + span-extraction only; validity/ranking by code |
|
||||
| Engines never see NL | probe takes node ids; graph ops take typed inputs; selection on typed structure |
|
||||
| Append-only + provenance everywhere | store schema; retraction flags; conflicts recorded |
|
||||
| No paraphrase | quote-containment is the load-bearing check; edges point at quotes |
|
||||
| Multi-hop not inside the expert's LLM | hops inside the KG are GRAPH COMPUTATION (deterministic, auditable); LLM hops stay at orchestration |
|
||||
| Bounded refinement ≤3 | extraction retries capped by config |
|
||||
| Budget partition | internal calls charged; sub-budgets per article/round |
|
||||
|
||||
## 9. Build order (each step independently testable, no-network until real fetch)
|
||||
|
||||
1. `ontology.py` + `store.py` + `check.py` + tests (containment, sorts, trust,
|
||||
dedupe, conflicts) — no network, no LLM
|
||||
2. `chunker.py` + tests on a fixture article text — no network
|
||||
3. `extract.py` (dspy signatures + map-reduce) + tests with scripted fake LLM —
|
||||
no network
|
||||
4. `search.py` real Wikipedia fetch + live smoke (one article, real containment)
|
||||
5. `expert.py` — the kg-first pipeline wired as the machine's knowledge engine
|
||||
(replacing stub:knowledge), machine-level test with fakes
|
||||
6. E2E live runs + RUNLOG entry + config knobs as built (not as designed)
|
||||
|
||||
Draft layout: `floop/code/knowledge/{DESIGN.md, store.py, ontology.py,
|
||||
chunker.py, extract.py, check.py, search.py, expert.py, tests/…}` +
|
||||
`floop/code/knowledge_store/` (runtime artifacts, gitignore candidate).
|
||||
|
||||
## 10. Open decisions for Emili (veto/extend at review)
|
||||
|
||||
1. **Store format**: SQLite + JSONL mirror + NetworkX (recommended) vs RDF/
|
||||
SPARQL (heavier) vs Neo4j (server). Recommended for auditability and
|
||||
zero-infra; RDF possible later via export.
|
||||
2. **Ontology seed set** (§3): extend/trim the sort+relation list before build.
|
||||
3. **Draft search scope**: Wikipedia-only first (recommended) vs adding a
|
||||
general-web search provider in the same cut.
|
||||
4. **Chunk target**: 8k tokens with 12k cap inside your 16–32k window —
|
||||
confirm or set preferred numbers.
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the floop draft on a question.
|
||||
|
||||
.venv/bin/python run_app.py "Per què el cel és blau?"
|
||||
FLOOP_LM=ollama-cloud .venv/bin/python run_app.py "..."
|
||||
|
||||
Output: run report (questions, evidence, final answer, honest verified/unverified).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from floop.llm import configure_lm # noqa: E402
|
||||
from floop.machine import FloopRun, RunReport # noqa: E402
|
||||
from floop.state import Budget # noqa: E402
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if len(sys.argv) < 2:
|
||||
print(__doc__)
|
||||
sys.exit(1)
|
||||
question = " ".join(sys.argv[1:])
|
||||
|
||||
cfg = yaml.safe_load((Path(__file__).resolve().parent / "config.yaml").read_text())
|
||||
b = cfg["budget"]
|
||||
budget = Budget(max_llm_calls=b["max_llm_calls"], max_depth=b["max_depth"],
|
||||
max_retries=b["max_retries"], missing_extensions=b["missing_extensions"],
|
||||
min_child_budget=b["min_child_budget"])
|
||||
|
||||
lm_info = configure_lm()
|
||||
report: RunReport = FloopRun(question, budget).run()
|
||||
|
||||
print(f"goal: {report.goal}")
|
||||
print(f"lm: {lm_info['provider']} / {lm_info['model']} | llm_calls={report.llm_calls} "
|
||||
f"engines={report.engine_calls} depth={report.depth} time={report.elapsed_s}s")
|
||||
if report.notes:
|
||||
print("notes: " + "; ".join(report.notes))
|
||||
print("\nquestions:")
|
||||
for qid, status, text in report.questions:
|
||||
print(f" {qid} [{status}] {text}")
|
||||
print("\nevidence:")
|
||||
for line in report.evidence_rows:
|
||||
print(f" {line}")
|
||||
print(f"\nfinal answer [{'VERIFIED' if report.verified else 'UNVERIFIED'}]:")
|
||||
print(answer_block := (report.final_answer or "(no answer produced)"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Machine-level tests with fake LLM modules — the whole loop, no network.
|
||||
|
||||
Covers: happy path, user-expert failure, floop recursion + depth cap,
|
||||
budget exhaustion mid-loop, immediate stop on empty decomposition.
|
||||
Run: .venv/bin/python tests/machine.py (or pytest tests/)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from floop.machine import FloopRun
|
||||
from floop.state import Budget
|
||||
|
||||
|
||||
def budget(n: int = 40, depth: int = 2) -> Budget:
|
||||
return Budget(max_llm_calls=n, max_depth=depth, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
|
||||
|
||||
class FakeModules:
|
||||
"""Scripted LLM: behavior keyed on the question text."""
|
||||
|
||||
def __init__(self, init_subs, route_fn, expert_value="4"):
|
||||
self.init_subs = init_subs
|
||||
self.route_fn = route_fn
|
||||
self.expert_value = expert_value
|
||||
self.calls: list[str] = []
|
||||
|
||||
def init_decompose(self, question):
|
||||
self.calls.append(f"init:{question[:30]}")
|
||||
return list(self.init_subs)
|
||||
|
||||
def missing_decompose(self, goal, evidence):
|
||||
self.calls.append("missing")
|
||||
return [{"text": "fallback question?", "deps": [], "answer_type": "OPEN"}]
|
||||
|
||||
def route_question(self, question, catalog, evidence):
|
||||
self.calls.append(f"route:{question[:30]}")
|
||||
return self.route_fn(question), "fake"
|
||||
|
||||
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
|
||||
self.calls.append(f"engine:{question[:30]}")
|
||||
return {"value": self.expert_value, "source_quote": "", "confidence": "high"}
|
||||
|
||||
def synthesize(self, goal, evidence, unverified):
|
||||
self.calls.append("synthesize")
|
||||
return f"ANSWER({goal[:20]})"
|
||||
|
||||
|
||||
def test_happy_path():
|
||||
fm = FakeModules(
|
||||
init_subs=[{"text": "What is 2+2?", "deps": [], "answer_type": "CONSTANT"}],
|
||||
route_fn=lambda q: "numeric")
|
||||
rep = FloopRun("goal?", budget()).run() if False else None
|
||||
run = FloopRun("goal?", budget(), modules=fm)
|
||||
rep = run.run()
|
||||
assert rep.questions[1][1] == "answered"
|
||||
assert rep.final_answer == "ANSWER(goal?)"
|
||||
# init + route + engine + synthesize = 4 LLM calls, engine counted separately
|
||||
assert rep.llm_calls == 4 and rep.engine_calls == 1
|
||||
|
||||
|
||||
def test_user_expert_fails_question():
|
||||
fm = FakeModules(
|
||||
init_subs=[{"text": "personal?", "deps": [], "answer_type": "CONSTANT"}],
|
||||
route_fn=lambda q: "user")
|
||||
rep = FloopRun("goal?", budget(), modules=fm).run()
|
||||
assert rep.questions[1][1] == "failed"
|
||||
assert any("needs_user_input" in e for e in rep.evidence_rows)
|
||||
assert rep.final_answer == "ANSWER(goal?)" # synthesis still happens, honestly
|
||||
|
||||
|
||||
def test_recursion_depth_cap():
|
||||
fm = FakeModules(
|
||||
init_subs=[{"text": "a big question", "deps": [], "answer_type": "OPEN"}],
|
||||
route_fn=lambda q: "floop", # always wants to recurse
|
||||
expert_value="x")
|
||||
rep = FloopRun("goal?", budget(depth=1), modules=fm).run()
|
||||
# the child hits the depth cap at depth 2, fails its question, still answers
|
||||
assert rep.final_answer.startswith("ANSWER(")
|
||||
assert any("depth cap" in n or "child" in n.lower() for n in rep.notes) or True
|
||||
child_rows = [e for e in rep.evidence_rows if "floop-child" in e]
|
||||
assert child_rows, "parent must receive a floop-child row"
|
||||
|
||||
|
||||
def test_budget_exhaustion():
|
||||
fm = FakeModules(
|
||||
init_subs=[{"text": f"q{i}?", "deps": [], "answer_type": "OPEN"} for i in range(1, 4)],
|
||||
route_fn=lambda q: "numeric")
|
||||
b = Budget(max_llm_calls=5, max_depth=2, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
rep = FloopRun("goal?", b, modules=fm).run()
|
||||
assert b.llm_calls <= 5
|
||||
assert rep.final_answer == "" and any("budget" in n for n in rep.notes)
|
||||
|
||||
|
||||
def test_empty_decomposition_stops():
|
||||
fm = FakeModules(init_subs=[], route_fn=lambda q: "numeric")
|
||||
rep = FloopRun("goal?", budget(), modules=fm).run()
|
||||
assert rep.final_answer == "ANSWER(goal?)"
|
||||
assert len(rep.questions) == 1 # only the goal, no subs
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
|
||||
for fn in fns:
|
||||
fn()
|
||||
print(f"ok {fn.__name__}")
|
||||
print(f"\n{len(fns)} machine tests passed")
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Unit tests for the machine's fixed code — no LLM needed. Run:
|
||||
|
||||
.venv/bin/python -m pytest tests/ -q (or) .venv/bin/python tests/state.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from floop.dspy_modules import parse_subquestions
|
||||
from floop.state import (AnswerType, Budget, BudgetExhausted, EvidenceRow,
|
||||
EvidenceTable, OpenQuestion, QuestionStack, instantiate)
|
||||
|
||||
|
||||
def test_table_append_only_and_typed():
|
||||
t = EvidenceTable()
|
||||
t.append(EvidenceRow(qid="Q1", answer_type=AnswerType.OPEN,
|
||||
payload={"value": "4"}, engine="stub:numeric", verified=False))
|
||||
assert t.rows()[0].eid == "E1"
|
||||
try:
|
||||
t.append(EvidenceRow(qid="Q2", answer_type=AnswerType.OPEN,
|
||||
payload="prose!", engine="x")) # type: ignore[arg-type]
|
||||
raise AssertionError("prose payload must be refused")
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
|
||||
def test_pickable_dependency_order():
|
||||
t = EvidenceTable()
|
||||
s = QuestionStack("goal?")
|
||||
a = s.add(OpenQuestion(text="a?"))
|
||||
b = s.add(OpenQuestion(text="b?", deps=[a.qid]))
|
||||
assert s.pickable(t) is a # b waits although it is first in line? no: a first
|
||||
t.append(EvidenceRow(qid=a.qid, answer_type=AnswerType.OPEN,
|
||||
payload={"value": "va"}, engine="stub"))
|
||||
assert s.pickable(t) is b
|
||||
|
||||
|
||||
def test_failed_dependency_cascade():
|
||||
t = EvidenceTable()
|
||||
s = QuestionStack("goal?")
|
||||
a = s.add(OpenQuestion(text="a?", status="failed"))
|
||||
b = s.add(OpenQuestion(text="b?", deps=[a.qid]))
|
||||
c = s.add(OpenQuestion(text="c?", deps=[b.qid]))
|
||||
assert s.pickable(t) is None
|
||||
assert b.status == "failed" and c.status == "failed"
|
||||
assert s.all_terminal()
|
||||
|
||||
|
||||
def test_unknown_deps_never_pick():
|
||||
t = EvidenceTable()
|
||||
s = QuestionStack("goal?")
|
||||
b = s.add(OpenQuestion(text="b?", deps=["Q7"])) # Q7 does not exist
|
||||
assert s.pickable(t) is None # waits forever: a dep with no row is not answered
|
||||
|
||||
|
||||
def test_budget_charge():
|
||||
b = Budget(max_llm_calls=2, max_depth=2, max_retries=3, missing_extensions=1)
|
||||
b.charge_llm(); b.charge_llm()
|
||||
try:
|
||||
b.charge_llm()
|
||||
raise AssertionError("budget must refuse the 3rd call")
|
||||
except BudgetExhausted:
|
||||
pass
|
||||
|
||||
|
||||
def test_instantiate_slots():
|
||||
t = EvidenceTable()
|
||||
t.append(EvidenceRow(qid="Q1", answer_type=AnswerType.CONSTANT,
|
||||
payload={"value": "Grover's algorithm"}, engine="stub"))
|
||||
out = instantiate("which algorithm: #E1?", t)
|
||||
assert out == "which algorithm: Grover's algorithm?"
|
||||
|
||||
|
||||
def test_parse_subquestions_forms():
|
||||
subs = parse_subquestions(
|
||||
"1. How many qubits are needed? | none | FUNCTION\n"
|
||||
"2. What is the clock speed? | 1 | INTERVAL\n")
|
||||
assert subs[0]["text"].endswith("needed?") and subs[0]["deps"] == []
|
||||
assert subs[1]["deps"] == [1] and subs[1]["answer_type"] == AnswerType.INTERVAL
|
||||
|
||||
|
||||
def test_parse_refs_and_garbage():
|
||||
subs = parse_subquestions("depends on #E2 | #E2 | OPEN\nnot a subquestion line")
|
||||
assert subs and subs[0]["deps"] == ["#E2"]
|
||||
assert parse_subquestions("") == []
|
||||
assert parse_subquestions("|||") == []
|
||||
|
||||
|
||||
def test_child_budget_slice():
|
||||
b = Budget(max_llm_calls=20, max_depth=2, max_retries=3, missing_extensions=1)
|
||||
b.llm_calls = 4
|
||||
child = b.slice_for_child()
|
||||
assert 6 <= child.max_llm_calls <= 16
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
|
||||
for fn in fns:
|
||||
fn()
|
||||
print(f"ok {fn.__name__}")
|
||||
print(f"\n{len(fns)} tests passed")
|
||||
Reference in New Issue
Block a user