Files
floop/ARCHITECTURE.md
T
onibotandClaude 1af308ae60 feat: named inputs/outputs in traces + clickable prompts + expert names
Owner's 27/10 review of the OTel export, four asks, all landed:

1. NAMED IN/OUT PER FUNCTION: fn.done events (fn, in, out) at the
   knowledge pipeline's main functions - search (in.query -> out.titles),
   fetch, skim, compose, chunk_gate, serve_set, list_ingest, harvest,
   promote, check, judge - rendered as spans with in.<arg>/out.<arg>
   attributes. "wiki search ('Pedro date take'): [...]" is now
   knowledge.search with in.query and out.titles as data.
2. SIGNATURE IN/OUT: the dspy prompt-log callback emits sig.start/sig.done
   - the typed fields of every dspy call (in.question, out.entities,
   out.facts...). The LLM span and the sig span are one node.
3. CLICKABLE PROMPT: every LLM span carries a child 'prompt' span with
   the exact prompt + raw response read from prompts/NN-stage.txt at
   export time - retroactive for old runs (the Pedro run re-exports with
   128 prompt children).
4. EXPERT NAMES: EXPERT comp spans carry expert= (EXPERT knowledge);
   nested spans prefix with the expert (knowledge.search,
   knowledge.state, knowledge.TranslateToDSL); each expert exports its
   spans under its own OTel service so Jaeger groups by component.

Live-verified end to end: smoke run (glm-5.3-flash) exported while
running - MASK shows in.question -> out.entities [{France, PLACE}],
EXPERT knowledge nests knowledge.TranslateToDSL under service
knowledge; read back via Jaeger's own API. Suite: traces 7/7, all
floop + knowledge test files green (guards/value_clean caught two bugs
in the new emissions before commit: a wrong-scope variable and a
use-before-define; _rec now reads getattr(streams) so __new__ test
fakes survive).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-27 14:27:56 +01:00

337 lines
21 KiB
Markdown

# 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.
### Intake — composing the boundary (the first call's window)
floop may receive an input far larger than the window of the model it runs: as a drop-in
LLM it can accept a context of, say, 1M tokens while the model it calls has 64k — and the
input is free text of unknown format: JSON, markdown, or a huge document with a question
at the end. The **INTAKE** component resolves this before anything else runs:
1. **Keep the original whole, on disk.** The machine's memory is unlimited; the input is
stored verbatim as a run artifact and becomes machine state, referenced by id. No LLM
ever needs to see all of it at once.
2. **Deterministic format detection first, always.** Fixed code probes for known formats:
JSON (parse it), markdown/XML (structure), code (fences, shebang), plain text. Format
detection is a computation, not a judgement — no LLM in it.
3. **Known format → structural splitting.** JSON walks the object; markdown splits at
headings; documents split at section/sentence boundaries. Structure discovered by code
is trusted and typed into rows, each carrying a pointer into the stored original.
4. **Unknown or unstructured → staged LLM compression.** When no structure is found, the
input is compressed in stages: chunked summarization (chunks sized to the model's
window, map-reduce over them), optionally fronted by a cheaper model with a larger
window for the first pass if one is configured. Each stage's output is checked and
typed; because the original stays on disk, compression is always re-derivable —
lossless at the source, lossy only in what the LLM kept, and logged as such.
5. **Extract the goal early.** On every path, one bounded early task separates the
request itself (the question at the end of the document, the instruction in the
message) from the material it refers to: the goal drives the loop, the material
becomes typed evidence rows.
6. **Harness templates for known callers.** Known harnesses have known message shapes:
a Hermes Agent run, for instance, carries its system prompt, tool list and
conversation history in a recognizable layout. INTAKE ships one template per known
harness (**Hermes Agent first** — it is what runs today): when the incoming shape
matches the template, the digest is typed directly by it — no format probing, no
LLM, the mapping caller-shape→rows is already known. Template matching is
deterministic pattern detection; unrecognized shapes fall back to the generic path
above. New templates are added the same way as trusted domains: as config, when a
new harness enters the fleet.
**Sessions and intake caching (pending; designed-in now).** As a drop-in LLM floop is
called in conversations: the same session re-sends, call after call, material that was
already digested once. INTAKE must not re-compress the world each time. The design:
stored originals are cached keyed by content checksum (the artifact's hash IS the key);
each session remembers its already-digested material and rows; a new call processes only
the **delta** — what is new since the last call; cache hits are logged as such. The
cache is machine state like any other: on disk, provenance-carrying, auditable. Not
built yet — noted now so the intake contract admits it from day one.
Intake's output is typed machine state — the goal statement plus rows pointing into the
stored original — and from there per-call context composition (above) governs every call.
Intake is logged like everything else, and it is the same law at the boundary as inside:
the LLM sees a purpose-built context; the machine holds the whole.
### Language at the boundary — English inside, any language outside
floop accepts any language in, and must answer in the caller's language — but
inside, the machine works in **one working language: English**. One loop, one
vocabulary for reasoning: decomposition, routing, extraction, proofs, traces,
and the knowledge graph all live in English; the fractal stays uniform instead of
forking per language.
- **Inbound (right after intake).** The stored original stays verbatim, in its
own language — the input artifact is never translated. The typing call already
detects the input language; a bounded LLM task translates the **goal statement**
(and, in the draft, any material the loop will actually read) into English,
flagged with `source_language` on the run. English text passes through
unchanged. If the goal's translation is ambiguous or partial, the original is
kept alongside and the loop works bilingually on that segment — honesty first,
never a silent guess.
- **Inside: English everywhere.** Every internal representation is English:
subquestions, routing judgements, formalizations, evidence-row summaries, the
knowledge graph itself (nodes, edges, quotes come from English sources), the
run log, and the final synthesized English response. The knowledge vertical's
sources are English (Wikipedia `en`); quotes are verbatim English — they are
never translated, because translation would break the containment check and
provenance.
- **Outbound (last step, before emission).** The machine's English response is
composed first, from evidence and traces (ALGORITHM.md §8); **then** one LLM
task renders it into `source_language` if it is not English. Evidence is
carried across: every fact and number in the translation is traceable to the
English rows; the translated quotes stay in English (or are re-gathered from
the source language's Wikipedia if a same-language quote is available — a
per-source option, default off). Tool calls and schemas are emitted in the
harness's language-neutral form (JSON) — nothing to translate there.
- **What is gained.** Reasoning quality in one language only; the meta-level
analysis and prompt optimization (META.md) compare runs that reasoned in the
same vocabulary; the KG stays one graph (no per-language forks), and every
translation is a logged, auditable boundary event with its own provenance.
## 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).
## 9-bis. Observability (2026-10-27): OpenTelemetry export, BUILT
Today a run's observability is files: `runs/<ts>/run.log` (the line-based technical
superset), `prompts/NN-stage.txt` (every exact rendered prompt + raw response), and the
WARNING channel (machine judgements worth a human's eye — the mask seed that
auto-answered a question, guards refusing ingests, budget starvation). This is complete
but closed: reading it means tailing files.
**BUILT (post-mortem half):** the run exports as **OpenTelemetry** traces/spans
(`floop/traces.py`), so floop is observable from the standard tooling that already
exists — Jaeger (running on the agentvps as a docker container), Grafana Tempo, any
OTLP consumer — instead of floop growing its own dashboards. The mapping is the
natural one: one run = one trace; each LLM call, engine step (probe, search, fetch,
check, merge) and evidence append = one span, carrying the fields the logs carry today
(stage, budget tick, duration, prompt-file pointer, verification flags, warnings).
`events.jsonl` (the flight recorder's machine-readable event stream) is the single
schema with two consumers: offline self-analysis in META.md, and `python -m
floop.traces <run_dir>` replaying it into Jaeger over OTLP/HTTP after the run — the
run itself never touches the network (observability never kills a run). Warnings
export as span attributes/events first-class, since they are the self-improvement
signal the lessons bank counts.
Conventions the exporter keeps:
- Deterministic trace ids (sha of the run dir name) — the same run always maps to
the same trace id, so UI links are stable and a re-push finds the same trace.
- The root span is named by the run's question and carries the final answer as an
attribute; the trace list in Jaeger reads as a list of questions.
- Recursive child runs (recursive floop as an expert attendant) write the SAME
events.jsonl with their own run_ts; each child-run block becomes its own span
nested under the spawning component, so the fractal recursion is visible as
nesting, and `seq` restarting is expected (positions, not seq, identify spans).
- `ts` is local wall time without a date; the date comes from the run dir name,
and a backwards jump means midnight crossed. The clock is only ever fed in
emission order — pre-reading a later event poisons the midnight detector.
Owner's visibility laws (27/10, this PR) — inputs and outputs are data, not
prose:
- Every pipeline function emits `fn.done` (fn, in, out) with NAMED arguments:
in.query / out.titles for the Wikipedia search, in.title / out.{url, chars,
tables} for the fetch, in.question / out.{value, confidence} for the judge,
compose, skim, chunk_gate, serve_set, list_ingest, harvest, promote, check.
- Every dspy call emits `sig.start` (the Signature's input fields, named:
in.question, in.entities...) and `sig.done` (the typed output fields:
out.entities, out.facts, out.value...) — emitted by the prompt-log callback,
which sees the module forward; the LLM span and the sig span are the SAME
node (name = stage, attributes carry in.*/out.* plus dur/call_seq/file).
- The exact prompt + raw response live in a CHILD `prompt` span of every LLM
span, read from the prompts/ file at export time — clickable in Jaeger,
works retroactively for old runs.
- EXPERT component spans carry the attendant's name (EXPERT knowledge);
everything nested inside carries the expert prefix (knowledge.search,
knowledge.state, knowledge.TYPE), and each expert exports its spans under
its own OTel service (floop / knowledge / ...) so Jaeger groups and colors
by component.
**Still deferred:** the in-process LIVE export (an OTLP exporter listening on the
event bus during the run, so Jaeger shows the waterfall while the run is still
going). Same schema, second consumer — build when a live run is actually observed
from outside; the hardening of the loop has priority.
## 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.