Commit Graph
9 Commits
Author SHA1 Message Date
Cato 4b9542c14e feat(loki): deepen investigations without repeating tool actions (#865) 2026-09-22 14:04:50 -07:00
CatoandClaude Opus 5 a4529b94e3 fix(loki): the tool loop answers too, it does not narrate its plan (#717)
#709 stopped the Groq FALLBACK serving the model's plan as the answer. The same
guard was missing on the tool loop — the path that serves nearly every turn.

WHY GROUNDING CANNOT COVER THIS

A plan asserts nothing, cites nothing and invents no proper noun, so it passes
every rule in verifyAnswer while telling the operator nothing at all. That is
exactly how it reached production: retrieval was fine, the answer was
scratchpad, and every automatic check said the turn was clean.

WHY THE GAP IS REAL AND NOT THEORETICAL

openai/gpt-oss-20b — the model that demonstrably wrote "We need to answer: … We
must cite each claim … Let's go through each:" and spent its whole budget on it
— is link TWO of this chain. The only reason the leak has not been seen here is
that gpt-oss-120b usually answers first. That is luck, and a fallback chain
exists precisely for the times the first link cannot answer.

MEASURED BEFORE ADDING IT

Ran the detector over every assistant reply Loki has stored: 106 replies, fires
on exactly 2 — both the same question, both from before the fallback fix, both
genuine leaks. ZERO false positives on the other 104.

That was the deciding number rather than the hit rate. A guard that misfires
costs a second model call on a rate-limited free tier, which is the resource
this whole week of work has been about conserving.

THE CURE MUST NOT BE WORSE

Four properties pinned, three of them about restraint:

  - a plan is retried ONCE, with the instruction the first attempt showed it
    needed — never a loop
  - a second plan is not an improvement, so it is not retried again
  - an EMPTY retry never replaces a real reply: a plan at least shows the model
    read the question
  - a good answer is never re-asked, so the common path costs nothing

The retry carries no tools: the model already gathered what it needed, and the
failure was in writing the answer, not in finding it. A failed retry leaves the
first reply standing — losing the turn to protect its formatting is the worse
trade. The stream is reset so the plan does not sit on screen above the answer.

Proved by mutation: disabling the guard fails "the plan must not reach the
operator" and nothing else.

Verify green, 233 checks.


Claude-Session: https://claude.ai/code/session_01Nm2REqtdsVsvjukBU2maCz

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-14 22:40:09 -07:00
CatoandClaude Opus 5 83968bae23 perf(loki): show the tools the question needs, accept all of them (#687)
Groq's window is 8,000 tokens per minute. A measured feedback turn was 10,153,
so the preflight skips Groq on every single call and a whole free provider is
never used — which is the direct reason OpenRouter burns its 50 requests a day.

Cutting RECORDS to fit would recreate the failure this retrieval layer exists to
end. So I measured where the tokens actually are before touching anything:

  system prompt (tools on) : 1,869   of which the catalogue: 1,328
  native tool schema       : 1,141
  FIXED OVERHEAD           : 3,010 tokens, before a single record

That is 47% of a 6,442-token turn, spent on eighteen tool descriptions.

Scoping the catalogue to what the planner already routed saves 1,100–1,700
tokens per turn. The feedback question goes 6,442 -> ~4,780, inside Groq's
budget, without dropping one record.

THIS REMOVES NO CAPABILITY, AND THAT IS TESTED

Only what the model SEES narrows. The accepted-name set stays the whole registry
and every handler stays reachable, so a model that names an unadvertised tool
still runs it. A test advertises exactly one tool, has the model call a
different one, and asserts it executes.

Three more properties pinned: the tools for every planned source are always
advertised; the core four are always present (the pulse and project list answer
"what else", the knowledge index answers "why did we decide that", and
propose_action is the only lever Loki has on the world); and a question nobody
could route advertises EVERYTHING, because it might need anything.

MEASURED FIRST, ON PRODUCTION

Baseline across five real questions before changing anything: every answer
grounded ok, both objective checks passed (named "Heidi" for the latest
feedback, "34" for the project count) — and ZERO turns called a tool. The seed
answered all five. So this reclaims tokens from capability that no measured turn
was spending.

The same five re-run after deploy is what decides whether this stays.

164/164 unit test files; 38 planner checks (up from 33), 17 loop checks (15).


Claude-Session: https://claude.ai/code/session_01Nm2REqtdsVsvjukBU2maCz

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 06:13:21 -07:00
ebeeb8101d feat(loki): retrieve before answering — Loki could not see the fleet it is named for (#647)
George filed two reports through FleetCrown's own feedback widget, watched
nothing happen, and asked Loki "what was the most recent feedback sent".

  Not in your data.

Both rows were in site_feedback, filed minutes earlier. Four runs spawned from
them sat in `waiting`. Twenty-four runs had errored in three days. The answer
was nevertheless honest: Loki had been handed no records, so the sentence was
true of what it could see — which is worse than an error, because a truthful
negative reads as a checked one.

Three independent causes, each sufficient alone.

1. NO SOURCE READ THE TABLE. `grep -rn feedback src/lib/agent/` returned
   nothing. Nor did runs, agent sessions, alerts, or notes. Loki could see the
   "life" half of the product (people, projects, goals) and nothing of the
   fleet half the product is named after.

2. THE PROMPT BUDGET WAS ARITHMETICALLY IMPOSSIBLE. One module constant —
   Groq's 12000-token minute window x 0.8 / 3 rounds = 3200 — applied to every
   vendor. Groq has since cut the window to 8000, and the prompt's own fixed
   cost measures 2946 tokens (system prompt 1264 + native tool schema 977 +
   catalog), leaving ~254 tokens: one fact. With the operator's message it goes
   negative, the fit correctly returns zero, and production logged
   `[loki] round 1: 40 facts exceed the call budget — sending 0` on every turn
   and sent it anyway with an empty Records block.

3. THE RICHER SEED WAS ON THE FALLBACK PATH ONLY. buildGroundedTurn (approvals,
   knowledge, economy, cues) ran only inside askLokiViaGateway. The primary
   loop seeded people + projects. So the approval queue seeded in #262
   *specifically to survive losing the tool loop* was, on the path that
   normally ran, reachable only by the tool call the loop could not afford.

WHAT CHANGED

Retrieve first, then reason. A pure keyword planner (src/lib/agent/plan.ts)
reads the question and fetches the relevant sources in parallel BEFORE the
model is called; tools become depth, not basic retrieval. A tool loop needs a
healthy model and a fitting prompt before it can ask its first question, which
is exactly what is missing when this class fires. A regex is dumber than a
model and never rate-limited. This is how OrangeCat's Cat has always worked.

Eleven new fact adapters: feedback, runs, live agent sessions, alerts, notes,
plus a computed fleet pulse (runner state, runs waiting/errored, unread
feedback, pending approvals, today's AI budget) and a buildFleetBrief of
SQL-computed answers the model may only phrase. Six new tools over them.

Budgets follow the vendor: linkPromptBudgetTokens() sizes Groq from its minute
window and large-context vendors by usefulness; the prompt is sized against the
largest usable link and the walker SKIPS links it does not fit (a preflight,
not a refused round-trip). Env-tunable without a deploy. When overhead busts
every budget the loop now throws instead of sending an empty Records block.

Conversation history reaches the primary path, so continuity no longer appears
and disappears depending on which brain served the turn.

Provenance is rendered: model, what was read per source, tools used, elapsed
time, and the grounding verdict. The verdict was always computed and always
returned; the route dropped it on persist and the assistant never read it, so a
flagged answer looked exactly like a clean one — the failure the harness exists
to prevent, reintroduced at the last inch.

THE GATE (this is the third time this class has fired)

Every read tool's data must ALSO be reachable from the seed. Seed =
survivability, tool = depth, one adapter called by both.
scripts/test/loki-retrieval-plan.ts fails the build on a read tool with no seed
source, and on a seed source no question can reach. It caught a real orphan on
its first run: the OrangeCat economy feed, fetchable but unreachable.

Also fixed while here: propose_action reported a failed DB write as a
successfully queued draft; the repair pass accepted a repair that invented a
NEW unsupported claim if it had fewer total; assignee matching used a bare
substring (the dr-UZH-nikov pattern on the write side); pageContext over 2000
chars 400'd the whole request instead of being clamped; the native tool schema
repeated each full description, paying for the same prose twice.

Docs: docs/architecture/loki-answering.md.
Tests: 4 files, 63 checks, all env-independent.


Claude-Session: https://claude.ai/code/session_01CAfKwM1oUSA9tU9fgdhfdf

Co-authored-by: Cato <georgy.butaev@revamp-it.ch>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-11 06:31:48 -07:00
d97fd69db1 refactor(deps): ai-kit comes from npm — @bitbaum/ai-kit ^0.6.2 (#473)
The package is now published to the npm registry as @bitbaum/ai-kit
(npm's typosquat guard blocked the bare name "ai-kit", hence the scope;
ai-kit PR #25 documents the rename — content is identical to the
github:bitbaum/ai-kit#v0.6.2 tag). The git pin is retired: the lockfile
no longer records the writer's ssh transport and npm-major-specific
resolution for this dependency, so the whole lockfile-writer trap class
dies with it. All imports move from 'ai-kit' / 'ai-kit/grounding' to
'@bitbaum/ai-kit' / '@bitbaum/ai-kit/grounding'.


Claude-Session: https://claude.ai/code/session_01WqKqMnHQHSmkGFfc5t7Rxn

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-04 00:11:06 +00:00
GandClaude Opus 5 caa0e41c3b chore: add a formatter (#449)
* chore: add a formatter, matching the style this repo already writes

singleQuote=false was chosen by counting this repo's own
imports, not by fleet decree. The fleet is genuinely split and the two repos
that already had a .prettierrc disagreed with each other, so there was no
standard to restore. Quote style does not cross repo boundaries; having a
gate does.

Markdown is ignored for now — prettier rewraps prose, which would bury the
real diff.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* style: format with prettier (1062 files)

Mechanical. No behaviour change. This SHA is listed in
.git-blame-ignore-revs so `git blame` skips it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore: teach git blame to skip the reformat

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(lint): reattach two guards the reformat detached

Both effects were one-liners, so a trailing eslint-disable-line covered the
setState call:

  useEffect(() => { setSelected(new Set()); }, [q.length]); // eslint-disable-line ...

prettier expanded the block. The comment stayed on the closing line while the
call moved above it, so the guard protected nothing and the rule its author had
deliberately silenced failed the build.

This is the second shape of the same defect — hirnli had the eslint-disable-NEXT-line
variant. Both come from the same fact: an eslint directive binds to a line
number, so reformatting can silently unbind it, which makes 'mechanical, no
behaviour change' false for any bulk reformat.

* chore(desktop): bump the runner version the reformat requires

desktop-release-drift enforces that anything built into Fleet Runner which
differs from the last released tag must carry a version ahead of that tag —
main read 0.8.15 and fleet-runner-v0.8.15 already shipped.

A whole-repo reformat changes bytes under desktop/, so the gate fires. The
alternative was adding desktop/ to .prettierignore, which would buy a quiet PR
by carving a permanent hole in the formatter's coverage — the precise shape of
silent drift this test was written to catch. Bumping is what the rule asks for
and costs one patch release whose only content is whitespace.

* chore: merge main and re-format

A whole-repo reformat conflicts with any concurrent commit, and a conflicting PR
runs no checks at all while reporting nothing. Conflicts resolved to main,
which is correct because this branch changes formatting and nothing else.

* chore: leave desktop/ out of this reformat

desktop-release-drift is right to refuse this. Everything under desktop/ is
built into Fleet Runner, so changing it means shipping: bump the version AND add
a FLEET_RUNNER_RELEASES entry, whose stated audience is 'person who installed
Fleet Runner and wants to know what changed'. For a whitespace-only build the
honest answer is 'nothing', so that release should not exist — and I should not
write release notes claiming otherwise.

I had bumped to 0.8.16 to get the gate green. That was the wrong direction:
publishing a build to three OS runners to keep a formatting PR quiet. Reverted.

desktop/ is excluded in .prettierignore with the reasoning recorded there, to be
formatted alongside the next real runner change, where the bump and the notes are
true anyway.

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-31 09:23:30 +00:00
bc0493f68f refactor(agent): the grounding harness is imported, not mirrored (#448)
FleetCrown half of the mirror retirement (fleet AI-engine plan, Phase 2).
src/lib/agent/core was the CANONICAL copy of the harness, mirrored
byte-for-byte into OrangeCat and policed by scripts/test/agent-core-drift.ts
plus scripts/sync-agent-core.ts. Its own README called the duplication
"deliberate and temporary" and named extraction to a package as the exit.
ai-kit v0.6.2 is that exit; OrangeCat's twin PR (#846, merged) deletes the
other side.

Fourteen imports across nine files collapse from three deep paths to one
subpath import. The sync script, the drift check and the npm script that ran
it are deleted rather than kept green: with a single copy there is nothing
left to drift, and a gate with no possible failure mode is noise wearing a
uniform. ai-kit also moves v0.2.1 -> v0.6.2 (still the ai-ration name in the
old lock entry); the three root imports this repo uses (chain, fair-share,
limits) are unchanged surfaces across that jump, which typecheck confirms.

The packaged copy differs from the deleted canonical by two mechanical
deltas, both made where the code now lives: .js extensions on relative
imports (pure ESM) and two null-guards under ai-kit's
noUncheckedIndexedAccess.

tsc clean; 124/124 unit test files pass (one fewer than before: the drift
check no longer exists to run).


Claude-Session: https://claude.ai/code/session_01WqKqMnHQHSmkGFfc5t7Rxn

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-31 09:45:07 +02:00
44a9ffbd5f fix(loki): shed facts on a 413 instead of abandoning the tool loop (#223)
Browser-tested the previous fix and read the box log. The 429 step-down
fired exactly as designed:

  [loki] llama-3.3-70b-versatile rate-limited, stepping down to
         llama-3.1-8b-instant
  [loki] tool loop failed: groq 413: Request too large for model
         `llama-3.1-8b-instant`

A prompt sized for a 128k context does not fit a small one. So the loop
still gave up and fell back to the weaker-retrieval path, and the
step-down that was supposed to keep tools working achieved nothing — it
just moved the failure one line down the log.

The answer the operator saw was correct, but only because the FALLBACK
path now has fixed people lookup. The tool loop itself was not serving
production turns at all.

Facts are the elastic part of the prompt (projects plus accumulated tool
results) and the first ones are the most relevant, so a 413 now halves
the fact budget and retries: 40 -> 20 -> 10, which fits every model in
the chain. Non-413 errors still propagate immediately — retrying a 401
or a 500 only burns latency for a guaranteed second failure.

Both behaviours pinned in scripts/test/agent-tool-loop.ts (11 checks).
67/67 unit files pass.

Co-authored-by: test <test@test>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-13 14:16:21 +00:00
538d9993f0 feat(loki): give Loki its own in-app tool loop (#214)
Loki was a thin proxy to the OpenClaw `main` agent, whose tool root is
~/.openclaw/workspace/. Asked who to contact, it grepped a schema-less
JSON blob there and narrated the incidental matches as attributes —
"Ilya Druzhnikov (UZH)", where UZH is the substring inside drUZHnikov.
FleetCrown's own `people` table, the authoritative one, was invisible.

You cannot constrain an agent whose retrieval you do not own. The
previous PR grounded the CONTEXT; this moves retrieval in-app so the
grounding is actually enforceable.

  tools/registry.ts   SSOT + defineTool(). Two kinds only: `read` and
                      `propose`. There is deliberately no `execute` —
                      Loki still cannot act, it queues drafts and the
                      operator approves. A test asserts that boundary.
  tools/handlers.ts   8 tools over FleetCrown's own tables: people,
                      projects, pgvector knowledge, goals, habits,
                      commitments/events, propose_action — and
                      ask_openclaw, the gateway DEMOTED to one tool
                      whose output is labelled an unverified
                      second-hand report.
  llm.ts              the model seam, with TWO tool protocols.
  loop.ts             seed → model → tools → facts → verify → repair.

THE INVARIANT: every tool returns Fact[], never prose. A tool result
therefore enters the same contract as everything else — declared fields,
<not recorded> gaps, a citation id, the verifier. There is no channel by
which a tool can put text in front of the model without it also becoming
checkable evidence. ToolResult has no escape hatch; keep it that way.

Dual protocol, because tool calling is where cheap models diverge most.
Native `tools` is advertised; a line protocol (TOOL:/ARGS:) is parsed
from ordinary text on every response regardless, and the two are merged
and deduped. Line-based, not nested JSON, chosen for the weakest model
expected to run it.

That decision is measured, not assumed. `npm run probe:loki-models`
against live Groq: llama-3.3-70b, llama-3.1-8b-instant, qwen3.6-27b,
allam-2-7b and compound-mini ALL drive the loop — and all five did it
via the TEXT protocol, even where native tool calling was advertised
and supported. A native-only parser would have scored zero on every one.

Loop bounds are observed failure modes, not padding: weak models re-call
a tool that already answered, so 3 rounds; the final round advertises no
tools so the model is forced to answer rather than hang; a repair is kept
only if it reduces violations, so the safety pass cannot degrade a turn.

loki-core prefers the loop, falls back to the gateway (still grounded and
verified) on error or LOKI_TOOL_LOOP=0 — an operational escape hatch, not
a feature flag.

Loop deps are imported lazily so the module stays pure to load, which is
what lets scripts/test/agent-tool-loop.ts run with no DB and no API key:
10 checks over protocol tolerance (bolded keys, fenced ARGS, copied
parens, bare calls, trailing prose), the no-execute boundary, fact
accumulation, bad-argument recovery, and bounds.

Co-authored-by: test <test@test>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-13 11:12:56 +00:00