From 67f466bd84c0d170231194d8c29845f6f314c5f1 Mon Sep 17 00:00:00 2001 From: Onibot Date: Wed, 14 Oct 2026 10:28:21 +0200 Subject: [PATCH] docs: full rewrite from a clean slate (v0.3) The idea is now clear, so the docs are rewritten from zero around it: LLMs do language, algorithms do thinking, verified knowledge lives on disk. New set: ARCHITECTURE (system + laws: division of labour, LLM calls as typed function calls via dspy Signatures, context as a per-call budget over unlimited machine state, evidence table laws, interface contract, tools as loop output, fleet, guarantees, v1->v2), ALGORITHM (general loop for any goal: reception/typing, main loop, tool action, generic expert, recursion, backtracking, per-call context composition), KNOWLEDGE (substrate: store, gather, checks, probe, offline growth), META (two levels: in-run self-awareness; offline self-analysis, lessons bank, prompt optimization, fine-tuning, v2 router). PIPELINE.md and SCOPE.md removed - superseded; GAPS.md closed with a merge map. Code untouched. --- ALGORITHM.md | 170 ++++++++++++++++++------- ARCHITECTURE.md | 188 ++++++++++++++++++++++++++++ GAPS.md | 264 +++------------------------------------ KNOWLEDGE.md | 86 +++++++++++++ META.md | 87 +++++++++++++ PIPELINE.md | 137 -------------------- README.md | 47 +++++-- SCOPE.md | 101 --------------- code/README.md | 2 +- code/knowledge/DESIGN.md | 2 +- 10 files changed, 540 insertions(+), 544 deletions(-) create mode 100644 ARCHITECTURE.md create mode 100644 KNOWLEDGE.md create mode 100644 META.md delete mode 100644 PIPELINE.md delete mode 100644 SCOPE.md diff --git a/ALGORITHM.md b/ALGORITHM.md index b27be15..b5537ab 100644 --- a/ALGORITHM.md +++ b/ALGORITHM.md @@ -1,72 +1,150 @@ -# FLOOP — how the machine works, in words +# ALGORITHM.md — the machine in words -This document describes what each part of the system **does**. No schemas, no code. +How floop serves any goal: the general loop, tool action, the generic expert, recursion, +stopping, failure, and how every LLM call gets its context composed. ## 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. +A goal arrives (a question to answer, a tool to call, a chat to hold, a maintenance task +to run). floop never "thinks a goal through" in one pass: the goal reduces to open +questions until one is small enough for a single expert call; answers flow back up and are +assembled into the response. Three kinds of parts do the work. **The LLMs** propose: read +the request, type the response expected, decompose the goal into subquestions, translate +between language and formal formats, compose the final prose. They never decide, never +compute, never assert facts. **The engines** — solvers, provers, retrieval, the knowledge +graph — do the deciding: deterministic, typed inputs in, typed payloads and traces out. +**The machine** — plain fixed code — owns the state: the open-question stack, the +dependency order, the budget, the retries, the stopping rule, and the per-call context +composition. One law runs through everything: a claim enters the state only as a typed row +with provenance — never as free-form model prose. -## 1. INIT — the opening +## 1. RECEPTION — typing the goal -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?"** +A request arrives with (possibly) a tool list. One LLM call reads it and declares the +**response type expected by the requester**: `answer` (a question to answer), `tool_call` +(an action to take), `chat` (conversation to hold), `meta` (a floop-maintenance task), +`plan_only` (a plan without execution). This typing annotates the goal — like +`answer_type`, it may be tightened later by evidence. It is NOT a path switch: whatever +the type, the goal is served by the same loop below. The typing costs one cheap call and +buys a contract: the output is checked against the declared type on arrival, and a +mismatch is a refusal-replan, not a silent guess. -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. +## 2. The main loop -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. +The machine keeps the **stack of open questions**, each declaring its answer type and its +dependencies (which questions it waits on). The loop, in words: -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. +1. **Stop check.** No open questions? Ask the prover: is the goal derivable from the + evidence table? Yes → synthesize the response. No → the decomposition was incomplete: + one more LLM call asks "what is still missing?" and new questions open. Stopping is a + formal condition, never a model's feeling. +2. **Pick.** Take the first question whose dependencies are all answered. If none can be + picked, a question is waiting on a failed answer: handle the failure (re-open, + re-decompose, escalate to the user). There is no search: dependency order IS execution + order. +3. **Route.** One cheap LLM judgement, with the expert catalogue in view, picks who + attends the question: a base expert, floop itself (recurse — too big for one call), or + the user (expert of last resort). +4. **Execute.** The attendant runs. Its result is checked on arrival: type must match, + claim must not contradict the table. A mismatch is refused — bounded reformulation + attempts; a contradiction triggers dependency-directed backtracking (§6). Nothing + untyped or unprovenanced is ever appended. +5. **Tick the budget.** Every LLM call and engine run costs. When the budget dies, the + loop stops and the LLM answers directly from what the table holds — explicitly + marked `Unverified`. -## 2. The main loop — the machine +## 3. Tool action — an output of the loop, not an alternative to it -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: +When the goal type is `tool_call`, the loop does not change: the harness's tool schemas +are evidence rows; "which tool satisfies the goal?", "what arguments does it need?", +"which of the previous observations are relevant?" are **ordinary subquestions**, routed +to experts like any other — logic reasons over schemas, analytic/numeric compute argument +values, knowledge supplies world facts. The loop's output is a `tool_call` row (tool, +arguments) whose provenance cites the schema rows and evidence that justify it; fixed +code validates it against the schema before emission. The harness executes the tool and +returns the observation, which enters the table as a `tool_result` row (a user-side fact, +never "verified", never silently retracted). Then the loop iterates on the new +observation — the next decision may be another tool, an expert, or stop. This is the ReAct +pattern with every step typed, evidenced and auditable; for the harness it looks exactly +like an LLM deciding tool calls. The prover's stopping predicate for tool goals: "the +evidence supports a concrete (tool, arguments)". -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. +## 4. The generic expert -## 3. The generic expert +Every expert is the same shape: **translate → check → solve → return**. -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. +- An LLM call (a dspy Signature) turns the question plus its referenced evidence into the + expert's formal format — the call receives a purpose-built context (§7), never the + whole state. +- A cheap formal check runs (well-typed, consistent units, well-formed query, trusted + source); failures go back to the translating LLM for bounded retries (≤3). +- The deterministic engine solves — no LLM inside. Out comes a typed payload with a + trace: a proof, a derivation, a verbatim quote with URL and access date. +- If nothing passes after the retries, the expert returns `Unverified` — the honest + fallback; the loop decides what to do with the hole. -The fleet, in words: +Fleet specializations (formal formats, checks, engines, payloads) live in +ARCHITECTURE.md §7. Two laws bear repeating: the LLM never computes — not even a +multiplication (`numeric` exists to enforce this); and `knowledge` never paraphrases — +its payload is the verbatim quote with provenance. -- **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. +## 5. Recursion — floop inside floop -## 4. Recursion — floop inside floop +A question too big for one expert call recurses: a child floop run on that question, +knowing its parent goal. Same loop, same discipline, two differences: **context shapes +adequacy** (the child knows why it is asked, so it knows when its answer is good enough) +and **budget is partitioned** (a slice of the parent's, plus a depth cap; a child that +cannot finish returns Unverified upward). The recursion bottoms out at the expert +catalogue — base case: one expert call; recursive case: one more level of the same +machine. There is no separate planner component: the plan is the open-question stack, +planning is proposing reductions of it, execution is answering from it. -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: +## 6. Failure and backtracking -- **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. +Failure is information. A contradiction in the table walks the provenance graph to the +culprit assumption, marks it retracted, and retracts exactly its downstream rows — +dependency-directed, not chronological; work that never depended on the dead assumption +survives; the corpse stays for inspection and learning (append-only). Factual hypotheses +(refutable by evidence) open branches; parameter assumptions (no evidence could refute +them) are dimensions of the answer function, never branches. And one thing can never be +retracted: the user. A user-supplied fact colliding with a source is presented verbatim +to the user — never silently resolved. -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.** +## 7. Per-call context composition -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. +Every LLM call gets its own purpose-built context, assembled by fixed code within the +model's window: -## 5. Failure and backtracking +- The machine state (evidence table, question stack, knowledge graph) is machine-sized — + disk, database, RAM — and can exceed any window. **No call ever receives the whole + state.** +- For each call the composer assembles: the task (the Signature's inputs), the referenced + rows (by id, compact summaries), the orientation the task needs (parent goal, section + headers, document chunk). What went in is logged. +- When the needed background exceeds the window, the machine **synthesizes** rather than + truncates: compact row summaries, structured KG subgraphs, chunked documents + (KNOWLEDGE.md). The callee gets what its function needs — not everything floop knows. +- Different calls to the same Signature may carry different context sizes: the contract + is the fields, not the window. -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. +## 8. Stopping and responding -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. +The stop condition is formal (prover over the table; for tool goals: a concrete +justified (tool, args) is derivable). Then — and only then — one final LLM pass composes +the response in natural language from the evidence rows and traces: every number carries +its source, every derivation its steps, every assumption its mark. If the budget died +first, the response is composed anyway from what the table holds — 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. -## 6. Stopping and answering +## 9. Who does what -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). \ No newline at end of file +- **LLM, always**: reading and typing requests; proposing subquestions; translating + between language and formal formats; the routing judgement; composing responses. +- **Fixed code, always**: the question stack and dependency ordering; budget partition; + bounded retries; arrival checks; contradiction detection and retraction; refusing to + stop; per-call context composition. +- **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. \ No newline at end of file diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..274f442 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,188 @@ +# ARCHITECTURE.md — the system and its laws + +The definition of floop in one paragraph, then the laws that make it what it is. + +## 1. What floop is + +floop is an AI built on a division of labour between three kinds of components: + +- **LLMs handle everything language**: reading requests, translating between natural + language and formal representations, proposing decompositions, composing prose. They + never decide, never compute values, never assert facts on their own authority. +- **Algorithms handle everything thinking**: deciding what to do next (dependency-driven + control flow), solving, proving, checking, stopping. Deterministic code and engines do + all of it — no LLM inside an engine, no LLM judgement anywhere the answer's correctness + depends on it. +- **Knowledge is verified and lives on disk**: every fact floop uses is extracted from + trusted sources, checked against them, and stored in the knowledge graph with its + provenance. Nothing is trusted because "the model knows it" — model weights are not a + knowledge store. + +The same loop — **translate → compute → verify** — runs at every level of abstraction: +inside each expert (formalize, check, solve, return typed payload), at the orchestration +level (decompose, execute, re-decide), and on floop's own behaviour (analyze a run, learn, +adjust). That is the fractal. And floop is aware of the loop it is executing — it sees +its own state — and of its own past runs, which it studies to improve. See META.md. + +From the outside this looks like an LLM: `messages + system + tools in → text or +tool_call out`, on an OpenAI-compatible endpoint. Answering questions, calling tools, +holding a conversation, maintaining itself — all are goals the same loop serves. + +## 2. LLM calls are function calls + +floop calls LLMs through **dspy Signatures**: typed input fields in, typed output fields +out, with the function's contract written in the Signature's docstring. An LLM call is a +**non-deterministic function call with a huge solution space** — but still a function +call: arguments in, result out, a contract it can be checked against. + +- **The Signature docstring IS the prompt.** We do not write prompts elsewhere; we write + the contract, minimally, as the class docstring — per floop convention, prompts are + kept small and say only what the call needs. +- **Fields are typed.** Inputs are what the caller provides; outputs are what the + algorithm consumes. Every consumer of an LLM output is fixed code that validates and + parses — a bad output is a bounded-retry error (≤3 attempts), never a silent guess. +- **Every call declares its own context budget.** The context window limit is a property + of the model, not of floop; floop manages machine-sized state (disk, database, RAM) and + composes, for each call, a context that fits the model. See §3. +- **Non-determinism is contained, not eliminated.** Same inputs may yield different + outputs; correctness therefore rests on the deterministic checks downstream of every + call, and on self-analysis of logged outputs over time (META.md). + +This is why dspy: it treats LLM calls as typed, declared, optimizable function calls — +which is exactly what they are for us. Later, the same Signatures are the unit of prompt +optimization and fine-tuning (META.md §4). + +## 3. Context is a per-call budget; the machine's context is unlimited + +The context window is a limitation of LLMs, not of floop. floop runs on a computer — +disk, databases, RAM — and its total state (evidence, knowledge graph, run history) can +be far larger than any window. What is bounded is **each call's input**. + +- **Per-call context composition** is therefore an explicit job, owned by fixed code: for + every LLM call, the machine decides what the callee needs — the task, the referenced + evidence rows, enough background to orient it — and assembles a prompt within the + model's window. What goes in is logged with the call. +- **Summarize, don't truncate.** When the needed background exceeds the window, the + machine synthesizes it: the evidence table has compact per-row summaries; the knowledge + graph serves structured subgraphs; documents are processed in chunks (KNOWLEDGE.md). + The LLM gets what it needs for its specific task — not everything the system knows. +- **The general context is kept machine-side.** No call ever receives "the whole + conversation"; each receives a purpose-built context for its function. Different calls + to the same Signature may carry different context sizes — the contract is the fields, + not the window. +- **Windows are config, not assumptions.** The model's window size is a config parameter + used by the composer; prompt-assembly failures are visible (logged, budgeted retries), + not silent. + +## 4. The evidence table — the machine's working memory + +One table per run, append-only, visible to every component. Each row: an id, a type, a +typed payload (formal value, verbatim quote, user reply, tool observation), a trace (the +engine's proof/derivation/fetch chain), and provenance (who produced it, from what, when, +at what cost). Laws: + +1. **Only engines and users write to it.** LLM prose never enters as a row. The + orchestrator's LLM reads the table but never writes free-form rows — the single most + dangerous injection point, closed by rule. +2. **Every row carries provenance.** A claim without provenance cannot support anything. +3. **A citation is a premise, not a fact.** A quote must be formalized (checked against + its source, stored) before it can support a milestone. +4. **Prose is never stored.** The only text in the table is verbatim source quotes and + user replies, typed as such. +5. **Append-only, with retraction flags.** Corrections never overwrite; contradiction + triggers dependency-directed backtracking (ALGORITHM.md §6) and the corpse stays for + inspection and learning. + +## 5. The interface contract (floop as an LLM) + +floop serves any harness on an OpenAI-compatible endpoint: + +- **In**: `messages`, optional `system`, optional `tools` (name + JSON schema each). +- **Out**: text, or a `tool_call` object — exactly what an LLM returns. +- **Intent typing.** The first thing floop does with a request is type the expected + response: `answer | tool_call | chat | meta | plan_only`. This is a **typing, not a + path switch**: it annotates the goal the way `answer_type` is declared and tightened by + evidence. Deciding the next step — which tool, which expert, whether to stop — is + reasoning, and all reasoning goes through the loop. A mis-typed goal degrades as a type + mismatch on output arrival (refusal and replan), never as skipped reasoning. + +## 6. Tools + +A harness's tool list and schemas enter as typed evidence (`tool_schema` rows). Selecting +a tool and filling its arguments are ordinary reasoning: subquestions routed to experts — +logic over schemas, analytic/numeric for argument values, knowledge for world facts. The +loop's output may be a `tool_call` row (tool, arguments) with provenance over the schema +and evidence rows that justify it; fixed code validates it against the schema before +emission. The tool executes outside the LLM — harness-side when floop serves as the +model. Its result returns as a `tool_result` row: an observation with provenance (tool +name, args, timestamp, payload) — a user-side fact, like user replies: never "verified", +never silently retracted, no containment check (that gate is for source-document quotes). +Then the loop iterates on the new observation. ReAct, with every step typed and evidenced. + +## 7. The expert fleet + +Each expert is the generic loop (translate → compute → verify) plus a configuration. All +return typed payloads, never prose. + +| Expert | Formalizes into | Check | Engine | Payload | +|---|---|---|---|---| +| `knowledge` | retrieval plan (queries, slots) over the KG and trusted sources | source trusted, quote verbatim, no paraphrase | KG probe + search + fetch | verbatim quote + url + date | +| `logic` | sorted FOL / ASP program + query | well-sorted, consistent | clingo / Z3 / Prover9 | model + proof | +| `analytic` | equations over quantities with units | dimensional analysis | SymPy solve/simplify | symbolic value + unit | +| `numeric` | closed-form expressions + constants | dimensional analysis | SymPy evalf | numeric value + unit + precision | +| `floop` | a subgoal too big for one call | dependencies typed, acyclic | **a recursive floop run** | child's answer + trace | +| `user` | anything nothing else covers | — | the person | user reply, typed | + +The `user` is the expert of last resort: precise questions, replies filed as evidence. +Multi-hop retrieval lives in the plan (one question references another's slot), never +inside the knowledge expert. The prover (clingo/Z3) owns "done", "answerable" and the +final derivability check — never the LLM. + +## 7-bis. The orchestrator is an expert + +The component that decides how to serve a goal is the same pattern one level up: the LLM +proposes subquestions; fixed code sequences them by dependency (execution order IS +dependency order — no search); each is routed (one LLM judgement over the catalogue) to +an expert, to a recursive floop run, or to the user; the prover gates stopping. With +dependent chains there is nothing to search, so v1 has no meta-planner; when parallel +branches compete for budget, a learned router earns its place (v2). + +## 8. Guarantees and honest limits + +- **Auditable answers.** Every output ships its derivation: which evidence, which rules, + which engines, which sources. The product is reasoning you can check. +- **Honesty at the boundary.** What cannot be formalized or solved within budget is + answered directly and explicitly marked `Unverified`. Nothing is ever silently guessed. +- **Conditional soundness.** The checks make misformalization harder (types, units, + containment), not impossible. The top failure mode is a wrong formalization producing + a correct answer to the wrong question. Mitigations: per-expert checks, bounded + refinement, the round-trip re-translation check (v1.1), self-analysis (META.md). +- **Stated limits.** Ambiguity and pragmatics stay on the neural side, deliberately. + Default reasoning lives in the logic expert (ASP negation-as-failure), not FOL-pure + solving. Recursion is depth-capped; budget is partitioned; children that cannot finish + return Unverified upward. + +## 9. v1 → v2 + +- **v1** (now): fixed control code; LLMs translate and propose; engines and the prover + are sound; every run is fully logged. +- **v2**: the router is learned — costs and expected gains estimated from logged + trajectories (rational metareasoning). The machine stays sound; only its cost model + becomes data-driven. v1's logs — enriched by meta-level critiques — are v2's training + data, and the same data feeds prompt optimization and fine-tuning (META.md). + +## 10. Risks + +1. **Misformalization** (top failure mode) — wrong formalization, correct math, wrong + question. Mitigated by type/unit/containment checks, bounded refinement, round-trip + checks, self-analysis. +2. **Over-decomposition** — subquestions whose answers never feed the parent. Contained + by dependency typing (unconsumed answers flag dead questions) and the final + derivability check. +3. **Infinite regress** — depth caps, budget slices per level, honest Unverified upward. +4. **Non-monotonicity** — defaults via ASP, contradictions via dependency-directed + retraction. +5. **Context mis-composition** — a per-call context missing what the task needed. + Mitigated by logging what each call received, self-analysis of failures (META.md). +6. **Scope.** Several small pipelines, not one project. Build order: one expert vertical + end-to-end, then the loop hardening, then the fleet. \ No newline at end of file diff --git a/GAPS.md b/GAPS.md index 6dc39bf..6941d49 100644 --- a/GAPS.md +++ b/GAPS.md @@ -1,249 +1,23 @@ -# FLOOP — Gap log (step-by-step replay) +# GAPS.md — design-gap log (CLOSED) -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?"* +Status: **closed 2026-10-13**. The gap log of the walkthrough replays (GAP-1..14, +including the 2026-10-13 intent/tool corrections) has served its purpose: every +resolution is now merged into the rewritten documents. This file stays as history — +do not add new entries here; new design gaps get their own doc and a RUNLOG note. -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. +Merged mapping (resolution → new home): ---- +| Gap (short) | New home | +|---|---| +| GAP-1 goal schema; GAP-4 answer typing (constant/interval/function); GAP-8 INIT epistemic closure | ALGORITHM.md §1-§2 (typing declared, tightened by evidence; decomposition is a linguistic act) | +| GAP-2 assumption typing; GAP-7 hypothesis branching + TMS retraction; GAP-9 user-reply semantics | ALGORITHM.md §6 (branch vs parameter; user never retracted) | +| GAP-3 decomposition is heuristic — soundness rests on the prover | ALGORITHM.md §8; ARCHITECTURE.md §8 | +| GAP-5 fractal-table mapping; GAP-10 adequacy contract, decompose-on-failure | ALGORITHM.md §4-§5 (the type is the parent-child interface) | +| GAP-6 budget units | ALGORITHM.md §2 step 5 (every call and engine run costs, logged) | +| GAP-11 intent layer; GAP-12 tool_call/tool_result semantics | ARCHITECTURE.md §5-§6; ALGORITHM.md §1, §3 (typing, not path switch; tool_call as loop output) | +| GAP-13 progress streaming + run logs | code/README.md + code/floop/stream.py (CLI part done); endpoint SSE future | +| GAP-14 meta level | META.md (all of it) | +| REDESIGN-1 orchestrator-as-recursion, no v1 meta-planner | ARCHITECTURE.md §7-bis; ALGORITHM.md §5 | -## 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. - -### GAP-11 — floop's scope is "answer questions"; the drop-in-LLM contract has no intent layer -Emili (2026-10-13): floop's final goal is to **replace the LLM of a Hermes agent (or any -harness)** — floop acts as an LLM from the outside. A harness request is not always a -question: it can be a tool execution request, chat, or self-management. The current design -only handles `answer`-shaped requests. -**Bites:** positioned as a harness model, floop would decompose "what's the weather in -Barcelona?" (needing the harness's weather tool) into retrieval subquestions instead of -emitting a tool call — unusable as an agent LLM. -**Resolution (design in SCOPE.md) — CORRECTED by Emili (2026-10-13):** the intent gate -TYPES the response expected by the user/harness (`answer | tool_call | chat | meta | -plan_only(future)`), like answer_type on GoalSchema — it does NOT choose the processing -path and does NOT pick tools or experts. Deciding the next step (call a tool, ask an -expert, stop) is reasoning, and all reasoning goes through the loop: subquestions, ROUTE, -experts, prover-gated stopping. A wrong response type degrades as a type mismatch on -output arrival (refusal/replan), never as skipped reasoning. -**Patch:** SCOPE.md §1-§2 (new doc); README.md definition; PIPELINE.md §1 note. - -### GAP-12 — tool_call flow and `tool_result` semantics -Follows GAP-11: nothing defines how a harness's tool list flows through floop, nor what a -tool result is epistemically. -**Resolution (SCOPE.md §3) — CORRECTED by Emili (2026-10-13):** tool_call is an OUTPUT of -the loop, not an alternative path to it. Tool list + JSON schemas enter as typed evidence -(`tool_schema` rows); "which tool satisfies this?", "what arguments?", "is the observation -enough?" are ordinary subquestions routed to experts (logic over schemas, analytic/numeric -for argument values, knowledge for world facts) — no LLM shortcut decides a tool directly. -The loop emits a typed tool_call row (tool, args) with provenance over the schema/evidence -rows that justify it; the tool executes outside the LLM (harness-side when floop serves as -the model); its result enters the table as a **`tool_result` row: an observation with -provenance** (tool name, args, ts, payload) — epistemically like UserReply rows: user-side -facts about what happened, never "verified" claims, no containment check (that gate is for -source-document quotes), never silently retracted; conflicts → user. Then the loop iterates -on the new observation (ReAct with typed, evidenced steps; stop = prover). -**Patch:** SCOPE.md §3; PIPELINE.md §5 (add row types + provenance law note). - -### GAP-13 — serving is invisible: no per-call progress stream, no run log -Emili (2026-10-13): running from CLI shows only the final summary; LLM calls can be long — -he wants (a) a line before each LLM call naming it, (b) the raw LLM output as it lands, -(c) the same for engines, (d) log-to-file always (flushed, `tail -f`-able) + screen output -only under a flag. -**Resolution (DESIGN in SCOPE.md §4) — CLARIFIED by Emili the same day:** screen ≠ log. The -screen is the future **"thinking" output of floop-as-LLM** (a readable subset); the log is -the full technical record and stays a superset — they will diverge. **IMPLEMENTED (CLI part, -2026-10-13):** `floop/stream.py` (`RunStreams`: log always flushed; `think()` → screen iff -verbose), machine hooks on every LLM stage + engine + budget tick, child runs share the -parent's stream; `run_app.py --verbose`. Verified live: 8-call run shows reasoning inline. -**Remaining:** real token-level streaming (dspy/litellm path) and the endpoint SSE mode. -**Patch:** SCOPE.md §4; code/floop/stream.py; code/README.md next-steps. - -### GAP-14 — no meta level: floop does not learn from its own behaviour -Emili (2026-10-13): after executing, floop should analyse its own answer — **offline, as a -scheduled task, after having already replied** — to (a) grow the knowledge store (fill KG -gaps observed in runs) and (b) learn from itself; and later, fine-tune the called LLMs and/or -let dspy optimizers (MIPROv2-class) improve the Signature-docstring prompts from our own -usage data. -**Resolution (design in SCOPE.md §5):** a `SelfAnalysis` dspy signature consumes a completed -run (report + stack + evidence + failures) and emits a structured critique, appended to the -run dir and to a lessons bank (`runs/lessons.md`). Dspy optimizer trainsets come from -critiques; the metric = post-hoc evaluator agreement (improvements adopted when measured, -never silently shipped). The v2 router connection: PIPELINE §7 says v1's logs are v2's -training data — the meta-level is the machinery that produces them. -**Patch:** SCOPE.md §5; PIPELINE.md §7 pointer. - ---- - -## 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". \ No newline at end of file +The original entries (with the reasoning that produced them) live in git history — see +the pre-rewrite versions of PIPELINE.md and SCOPE.md. \ No newline at end of file diff --git a/KNOWLEDGE.md b/KNOWLEDGE.md new file mode 100644 index 0000000..a56291a --- /dev/null +++ b/KNOWLEDGE.md @@ -0,0 +1,86 @@ +# KNOWLEDGE.md — the knowledge substrate + +floop's knowledge lives on disk, not in model weights. This document defines the store, +how facts enter it, and how experts consult it. + +## 1. The principle + +**Model weights are not a knowledge store.** Anything floop claims to know must be +traceable to a trusted source: extracted from a fetched document, checked against it, +stored with provenance, and re-consulted from the store — never re-asserted from "model +memory". This is the epistemic core of the architecture: LLMs handle the language of +knowledge (find, extract, paraphrase-never, quote); algorithms handle its custody +(checks, storage, retrieval, merging). + +## 2. The store + +A persistent, append-only store on disk (SQLite + JSONL mirror in the draft; see +`code/knowledge/DESIGN.md` for schema and trade-offs). Contents: + +- **documents** — fetched source texts (url, source, access date, checksum, text). +- **quotes** — verbatim spans from documents (the canonical text of a fact; url + access + date). Never paraphrased. +- **nodes** — entities (normalized name, sort: person, organization, concept, event, + quantity, document, place, date, other). +- **edges** — typed relations between nodes (or to literal values), each pointing at the + quote(s) that back it, with corroboration counts and extraction confidence. +- **conflicts** — same subject+relation with two different values: recorded and surfaced, + never silently merged. + +Laws of the store: append-only (corrections are retraction flags, never overwrites); +every edge points at quotes (the quote carries the truth, the edge is the index); +quantities carry values AND units (the bridge to analytic/numeric computation); conflicts +are surfaced to the user, never auto-resolved; entity identity merges only on +normalized-name equality within the same sort (conservative by design). + +## 3. How knowledge enters (the gather pipeline) + +Extraction is the generic expert shape, run per document: + +1. **Search & fetch** (engine): Wikipedia first (trusted-domain list in config), general + web later. Documents stored whole with checksums. +2. **Chunk** (engine): section-aware splitting sized to the model's window (~8k tokens + target, hard cap per call config). Context composition applies here like everywhere: + the extractor LLM sees the chunk plus its section path, not the whole document. +3. **Extract** (LLM Signature): per chunk, propose typed candidates — (subject, relation, + object/value+unit, verbatim span). Bounded retries on malformed output. +4. **Check** (engine, the gate): **verbatim containment** — the span must be + string-contained in the fetched document text; sort-checks on the relation's + endpoints; trusted-source check; dedupe. Rejected candidates are counted, never + silently dropped. +5. **Merge** (engine): into the store; corroboration counts; conflicts recorded. + +A fact that fails containment does not exist. This is the cheap, deterministic check that +makes the KG trustworthy today, before any prover runs. + +## 4. How knowledge is consulted (the probe) + +KG-first: before any external fetch, an expert's question is matched to graph nodes +(seeds from the question's mentions) and the neighborhood is traversed (BFS depth 1 with +corroboration weighting in the draft; Personalized PageRank — HippoRAG's mechanism — is +the planned upgrade, adopted when measured recall justifies it). The probe is an engine: +no LLM inside. Multi-hop lives in the plan (one question referencing another's answer +slot), never hidden inside the expert. + +What the probe returns feeds the calling LLM as compact, purpose-built context: quoted +spans with provenance, structured subgraphs sized to the window — not the whole store. + +## 5. Knowledge growth over time + +The store grows two ways: on-demand (a run's questions trigger gathers) and +**offline** — scheduled maintenance that fills gaps observed in past runs (entities +repeatedly unresolved, quotes whose checks failed, sources gone stale). Offline growth is +a `meta` goal (META.md §3): it uses the same gather pipeline, charged to a maintenance +budget, never inside a serving run. + +## 6. Honest limits + +- Extraction quality bounds KG quality: containment guarantees fidelity to the source, + not source truth — a quote can faithfully carry a false claim. +- Entity resolution is conservative (name-equality only in the draft); distinct nodes for + "Einstein" the person and near-miss names remain distinct until a measured linker + exists. +- Freshness: access dates are provenance; re-fetch policy is future work (a source older + than its field's decay rate should be re-consulted). +- The KG is floop's memory, not a world model: it holds what floop has had reason to + fetch, verify and keep. \ No newline at end of file diff --git a/META.md b/META.md new file mode 100644 index 0000000..ff4a304 --- /dev/null +++ b/META.md @@ -0,0 +1,87 @@ +# META.md — the two meta levels + +floop is aware of itself at two levels, one within the run and one between runs. Both are +instances of the fractal: the loop applied to floop's own behaviour. Neither ever runs +inside a serving response — level 2 is offline by definition. + +## 1. Level one — in-run self-awareness + +While serving a goal, floop **sees its own loop**: the question stack, the budget spent +and remaining, the depth of recursion, which calls are in flight, which retries are +burning, what the evidence table holds. This is not introspection mysticism — it is that +the machine's state is explicit, typed and queryable, and the per-call context composer +(ARCHITECTURE.md §3) can include it: an expert call whose context says "attempt 2 of 3, +budget 12/40, this question failed once as numeric" behaves differently from a blind +retry. + +Concretely, the state that any call can be given as context: + +- the goal and the response type it serves; +- the open questions and their dependency status; +- the budget ledger (calls spent, remaining, depth caps); +- the evidence rows relevant to the task (and how many times anything similar failed); +- floop's own operating notes — lessons from past runs (level two's output) — consulted + like any other knowledge, when relevant. + +Self-awareness in the run is therefore **context composition over an explicit state**, +plus the honesty rules that already govern it: the machine, not the LLM, decides what is +true of the run; the LLM only reads what it is given. + +## 2. Level two — offline self-analysis + +After a run completes and the response is already delivered, floop analyzes its own +performance — as a scheduled task over its own logs, never inside the serving loop. + +**Input**: the complete run record — the run log (every call, every context composed, +every output, every cost), the question stack, the evidence table, the failures and +retried calls, the final response and its verification status. + +**Process**: a `SelfAnalysis` pass (an LLM Signature over the run record, composed +safely within the window — chunked if the run is long) plus deterministic statistics +(call counts by stage, retry rates, budget waste, routing decisions that preceded +failures, questions that never fed the parent). + +**Output — a structured critique**: where decomposition over-split or under-split; where +routing misfired (and what signal would have caught it); where the per-call context was +missing something (context mis-composition); which checks should have caught what slipped; +what the run's honest quality was versus what it claimed. The critique is appended to the +run's directory and to a **lessons bank** (`runs/lessons.md`) — typed, citable, and +consultable by future runs at level one. + +## 3. Offline maintenance (the `meta` goal type) + +The same scheduled machinery serves floop's housekeeping as explicit goals: + +- **Knowledge growth**: fill KG gaps observed in past runs (repeatedly unresolved + entities, failed checks, stale sources) via the standard gather pipeline. +- **Lessons distillation**: periodically condense the lessons bank into operating notes + (compact, high-signal), which level-one context composition serves to calls that need + them. +- **Cost accounting**: aggregate run economics — which stages dominate cost, which + experts pay for themselves — feeding v2's learned router. + +## 4. Learning loops (the future path, stated now because the design must admit it) + +1. **Prompt optimization (dspy-native)**: our prompts are Signature docstrings; dspy + optimizers (BootstrapFewShot now; MIPROv2-class later) compile improved prompts using + the lessons bank and critiques as trainset, with a post-hoc evaluator as metric. + Improvements are adopted when measured, never silently. +2. **Fine-tuning**: logged trajectories (contexts in, outputs out, verdicts from + self-analysis) become SFT data for the models floop calls. +3. **The learned router (v2)**: rational metareasoning — the value of computation + estimated from logged trajectories. The machine stays sound; its cost model becomes + data-driven. + +All three eat the same substrate: **honest, complete logs of what floop actually did**. +That is why every run is logged the way it is (ARCHITECTURE.md §3; the run log IS the +training set). + +## 5. Guardrails + +- Self-analysis never edits the past: runs are append-only records; critiques are + annotations, not rewrites. +- Operating notes are knowledge like any other: typed, provenance-carrying (which runs + produced them), and revocable. +- Learning changes the *process*, never the laws: an optimizer may change a prompt's + wording, never the division of labour or the checks. A fine-tuned model still passes + the same gates. \ No newline at end of file diff --git a/PIPELINE.md b/PIPELINE.md deleted file mode 100644 index 90f3d13..0000000 --- a/PIPELINE.md +++ /dev/null @@ -1,137 +0,0 @@ -# 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. \ No newline at end of file diff --git a/README.md b/README.md index 08b5530..73feb15 100644 --- a/README.md +++ b/README.md @@ -1,27 +1,48 @@ # 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. +**Fractal loop.** An AI built on one division of labour: **LLMs do the language** +(translating, decomposing, composing prose), **algorithms do the thinking** (solvers, +provers, planners, retrieval — deterministic computation decides, checks and stops), +and **knowledge is verified and stored on disk** (extracted from trusted sources, checked, +persisted — never trusted from model "memory"). The same loop — translate → compute → +verify — runs inside every expert, at the orchestration level, and on floop's own +behaviour. floop is aware of the loop it is running, and studies its own past runs to +improve the process that produced them. -FLOOP is ReAct where the "thought" step is replaced by computation and the "observation" is typed before it enters the state. From the outside floop acts as an **LLM** (`messages + tools in → text or tool_call out`): the final goal is to be a drop-in replacement for the LLM of an agent harness. Answering questions is one use case; see [`SCOPE.md`](SCOPE.md) for the intent layer, the tool interface, and the self-learning meta level. +From the outside, floop acts as an **LLM**: `messages + system + tools in → text or +tool_call out`, OpenAI-compatible. A Hermes agent — or any harness — can point its model +provider at floop and get a reasoner whose steps are typed, evidenced and auditable. +Answering questions is one use case; acting with tools, holding a conversation and +managing itself are others. ## Documents | File | Contents | |---|---| -| [`SCOPE.md`](SCOPE.md) | floop beyond Q&A: drop-in-LLM positioning, the intent layer (answer / tool_call / chat / meta), tool_call + tool_result semantics, progress streaming, the offline self-analysis meta level. DESIGN, no code yet. | -| [`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. GAP-11..14 = the 2026-10-13 scope additions. | +| [`ARCHITECTURE.md`](ARCHITECTURE.md) | The system and its laws: division of labour, LLM calls as function calls, context as a per-call budget, the evidence table, the interface contract, tools, the fleet, guarantees, risks, v1→v2. | +| [`ALGORITHM.md`](ALGORITHM.md) | The machine in words: the general loop for any goal, tool action as loop output, the generic expert, recursion, stopping, backtracking, per-call context composition. | +| [`KNOWLEDGE.md`](KNOWLEDGE.md) | The knowledge substrate: verified facts on disk, the knowledge graph, extraction and its checks. | +| [`META.md`](META.md) | The two meta levels: in-run self-awareness; offline self-analysis and learning. | +| [`GAPS.md`](GAPS.md) | Design-gap log of the walkthrough replays (closed — resolutions merged into the docs above). | +| [`RUNLOG.md`](RUNLOG.md) | Run log: virtual walkthrough, executable runs. | +| [`code/`](code/) | v0.1 draft (dspy); `code/README.md` maps real vs stub per stage. | ## 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). +Design docs v0.3 (full rewrite, 2026-10-13). Executable draft: the loop runs on dspy LLM +calls — INIT / ROUTE / EXPERT / MISSING / ANSWER as Signatures, the machine as fixed +code — with formal checks, prover and expert engines stubbed, so every output is honestly +`Unverified`. Next: real check layer, the knowledge vertical (`code/knowledge/`), the +prover (clingo/Z3), the OpenAI-compatible endpoint. ## 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. \ No newline at end of file +floop's parts have measured prior art; the composition is ours. Logic-LM +(arXiv:2305.12295) — lm→solver with self-refinement (+39% on logic benchmarks). ReWOO +(arXiv:2305.18323) — plan on slots, decouple execution (5× token efficiency). LLM-Modulo +(arXiv:2402.01817) — LLMs propose, external verifiers decide. LLM+P (arXiv:2304.11477) — +NL→PDDL→classical planner. POMDP-Coder (arXiv:2505.02216) — the LLM writes the model, a +solver plans. HippoRAG (arXiv:2405.14831) — knowledge graph + PPR as memory (+20% +multi-hop QA, 10–30× cheaper than iterative retrieval). GraphRAG (arXiv:2404.16130) — +LLM-extracted graphs for global questions. Rational metareasoning (Russell & Wefald 1991; +arXiv:2410.05563) — the value of computation decides what to do next (v2's router). \ No newline at end of file diff --git a/SCOPE.md b/SCOPE.md deleted file mode 100644 index 9cb6afe..0000000 --- a/SCOPE.md +++ /dev/null @@ -1,101 +0,0 @@ -# SCOPE.md — floop beyond Q&A - -Status: DESIGN for review — no code yet. Three additions from Emili's review of 2026-10-13 -(floop as a drop-in LLM, CLI streaming, offline meta level), **corrected the same day**: -the intent gate types the response; it never bypasses the loop (§2). - -## 1. Reframing: floop as a drop-in LLM - -floop exposes an **LLM-like interface**: `messages + system + tools in → text (or tool_call) -out`, OpenAI-compatible. A Hermes agent (or any harness) should be able to point its model -provider at floop and behave exactly as before. Everything inside is the fractal loop — LLM -calls that translate/propose, typed evidence, engines that decide, a prover that gates -stopping. "Answer questions" is what the loop does for one response type; the contract with -the harness is broader. - -## 2. The intent layer — a response-type gate, not a path switch - -Every harness request first passes an intent classification — one LLM judgement + fixed-code -validation — that declares **what kind of response is expected**: `answer | tool_call | -chat | meta | plan_only` (future). That is ALL the gate does. - -What the gate does NOT do (Emili's correction, 2026-10-13): choose the processing path, pick -tools, or decide which experts run. Deciding the next step — call this tool, ask that -expert, stop here — is **reasoning**, and all reasoning goes through the loop: subquestions, -ROUTE per question, experts as attendants, prover-gated stopping. The gate only annotates -the goal with the expected response type (GoalSchema.response_type), the same way -answer_type is declared and then tightened by evidence. - -`chat` and `meta` are goal types too: the loop still runs and simply finds them trivially -derivable (a greeting needs no decomposition), or — for `meta` — schedules floop's own -maintenance (§5). - -## 3. tool_call is an OUTPUT of the loop, not an alternative to it - -A harness runs a ReAct loop: observe tool results, decide the next action, repeat. floop -serves that loop with the same machinery it uses for questions: - -1. The harness's tool list + JSON schemas enter as typed evidence (`tool_schema` rows). -2. "Which tool can satisfy this?", "what arguments does it need?", "is the last observation - enough to answer?" are **ordinary subquestions**, routed to experts like any other: - logic reasons over schemas, analytic/numeric compute argument values, knowledge supplies - world facts. No LLM shortcut decides a tool directly. -3. The loop's OUTPUT can be a `tool_call`: a typed row (tool, args) whose provenance cites - the schema rows and evidence that justify it. Fixed code validates it against the tool's - schema before emission — the LLM proposes, code disposes. -4. The tool executes **outside the LLM** (harness-side when floop serves as the model — - same contract as any LLM). Its observation enters the table as a `tool_result` row: a - user-side fact with provenance (tool name, args, ts, payload) — like UserReply rows, - never "verified", never silently retracted; conflicts go to the user. -5. Then the loop iterates on the new observation: re-decide — another tool, an expert, or - stop (prover). Every step of the ReAct chain is evidenced and auditable: "thought" is - replaced by computation, "observation" is typed before it enters the state. - -Stopping for a tool-call goal: the prover's derivability instantiates as "the evidence -supports a concrete (tool, args)" — same formal shape, different predicate. Misroutes -degrade cheaply: a wrong response type is a type mismatch on output arrival — the same -refusal/replan path any type mismatch takes; the reasoning was never skipped. - -## 4. progress streaming + run logs (CLI) — IMPLEMENTED (CLI part) - -Design: an event stream is produced on every run — one format, two channels. - -- **Always**: `runs/-/run.log` with explicit flush (tail -f-able): timestamps, - budget ticks, raw payloads, all technical detail. -- **`--verbose`**: the **thinking** subset prints to the screen (flushed, `[T]` lines, `>` - depth prefixes). Thinking is the future user-facing "thinking" output of floop-as-LLM; - log ⊇ thinking, and they will diverge. -- (later, same events) the endpoint's streaming mode: SSE-style events for external - consumers. - -## 5. The meta level: floop learns from its own runs (offline, future) - -After answering, floop analyses itself — **as a scheduled task, not inside the serving -loop**. Design shape: - -- **Self-analysis run** (a dspy signature, e.g. `SelfAnalysis`): input = a completed run's - report + question stack + evidence table (+ tool results, + which steps failed); output = - structured critique — where decomposition over-split or under-split, where routing - misfired, where the check layer should have caught something, budget spent well or wasted. - The critique is appended to the run dir and to a **lessons bank** (`runs/lessons.md`). -- **Knowledge growth**: the same scheduled task runs the knowledge gather offline — filling - KG gaps observed in past runs (entities repeatedly unresolved → fetch proactively). -- **Prompt improvement (dspy-native)**: our prompts are Signature docstrings; dspy - optimizers (BootstrapFewShot now, MIPROv2-class later) compile improved prompts from the - lessons bank + critiques — trainset = critiques with quality labels, metric = post-hoc - evaluator agreement. Adopted only when measured. -- **Fine-tuning path (later)**: logged trajectories become SFT data for the models we call. - -Connection to the plan: v2's learned router (PIPELINE §7) needs exactly these logged -trajectories + critiques as training data; the meta-level is how they get produced. - -## 6. Doc ripple - -- README: definition already repositioned; PIPELINE.md still to note the response-type gate - and the `tool_schema` / `tool_result` row types (§5). -- GAPS.md: GAP-11/12 carry the 2026-10-13 correction; GAP-13 (streaming) CLI part done. - -## 7. Explicitly NOT now - -No code for the gate, the endpoint, or self-analysis — this document only. Everything here -is future work recorded while the project is being defined. \ No newline at end of file diff --git a/code/README.md b/code/README.md index 9c5a840..a908d47 100644 --- a/code/README.md +++ b/code/README.md @@ -21,7 +21,7 @@ FLOOP_LM=ollama-cloud .venv/bin/python run_app.py "..." # cloud LM instead of SUBSET of the log — the log keeps all technical detail (budget, provenance, raw payloads), thinking stays readable. They will diverge over time (Emili, 2026-10-13). - Screen thinking lines carry the `[T]` marker; recursion depth shows as `>` prefixes. -- The same events will drive the OpenAI-compatible endpoint's streaming mode (SCOPE.md §4). +- The same events will drive the OpenAI-compatible endpoint's streaming mode (ARCHITECTURE.md §5). `config.yaml` holds the budget knobs and the two LM providers (no keys in code: `ollama-cloud` reads `OLLAMA_API_KEY` from the environment). Logs live in `runs/`. diff --git a/code/knowledge/DESIGN.md b/code/knowledge/DESIGN.md index 2c786fb..5816b05 100644 --- a/code/knowledge/DESIGN.md +++ b/code/knowledge/DESIGN.md @@ -7,7 +7,7 @@ Status: DESIGN FOR REVIEW — nothing built yet. This document is the "pensem-lo 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: +unchanged from ARCHITECTURE.md §4: - in: an instantiated question (+ parent question + referenced evidence rows) - out: typed evidence rows — **verbatim quote + url + access date**, never paraphrase