Files
floop/ARCHITECTURE.md
onibot 8a3f8b37e3 floop: strict mask-seed detection + WARNING on seeded answers
His 23/10 review of the merged run found Q1's answer missing from the
stream. Chain, verified against the real code:

1. Q1 ('...does the title "President" refer to in relation to
   PERSON_1?') fired the mask-seed detector's loose mechanism clause —
   any 'refer to' in the sentence, even when the verb governs the
   TITLE, not the placeholder. The seed answered 'Pedro Sanchez' to a
   question that asked which OFFICE 'President' means: wrong semantics,
   a false positive born from the collision of the detector's word
   list with INIT's new hidden-precondition phrasing.

Fixes (both his ask):
- identity_answer STRICT: the mechanism clause now fires only with the
  placeholder as the REFERENT of 'refer(s) to' (regex adjacency, both
  orders). The literal 'who/what is <ph>' clause is unchanged.
- Found while verifying: the literal clause's lookahead accepted
  apostrophes, so 'Who is PERSON_1's predecessor?' (possessive) seeded
  too — the old test only covered 'Who WAS...'. Apostrophe removed from
  the end-of-question char class; possessives never seed again.
- THE SEED IS NOW LOUD: RunStreams.warn() (new channel — WARNING line
  in run.log, [W] on screen ALWAYS, even non-verbose) fires on every
  seeded answer: 'WARNING SEED auto-answered Q1 ... (mask map; zero
  expert calls)'. Self-improvement signal (META): which phrasings the
  seed eats belongs to the lessons bank, and it must be legible that
  the machine auto-answered without any expert.

Also: ARCHITECTURE.md §9-bis — OpenTelemetry observability roadmap
(his future plan ask): run = trace, calls/steps/rows = spans carrying
today's log fields, events.jsonl as the shared bus, warnings as
first-class span events; deferred until the loop hardening settles.

Tests: anonymize +4 assertions (his false positive, possessive trap,
strict positive shapes), machine +1 (seed WARNING lands in run.log).
Suite 17/17.
2026-10-23 16:03:13 +02:00

299 lines
19 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 roadmap (future plan): OpenTelemetry
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.
**Planned, not built:** export the run as **OpenTelemetry** traces/spans so floop is
observable from the standard tooling that already exists — Jaeger, Grafana Tempo,
any OTLP consumer — instead of floop growing its own dashboards. The mapping is
natural: 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).
The planned `events.jsonl` (machine-readable event stream) becomes the in-process
event bus this exporter reads — one schema, two consumers (offline self-analysis in
META.md, live OTel export). Warnings export as span events first-class, since they are
the self-improvement signal the lessons bank counts.
Deferred until the loop hardening is done — building it before v1's shape settles
would instrument a moving target.
## 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.