Compare commits

...

32 Commits

Author SHA1 Message Date
claude d32eae8aac a spoken correction lands in the label table, with or without a target (V-636)
The gesture was web-only, so the sample was skewing to the turns he happens
to type. Voice is where the hard cases are.

Half of it already existed: the repair rung has read "нет, это была заметка"
since V-455. It taught the classifier and wrote no durable label, so the two
paths disagreed about what a correction is. It now writes both. Two sinks and
not one on purpose: the classifier seed makes the next turn better today, and
the label is what a fitted head trains on after the transcript expires.

The trace id is stamped onto the remembered turn after the fact, because the
trace is written when the turn ends and recordTurn runs in the middle of it.

New: the untargeted half. "нет, не так" writes the negative and redoes
nothing, because there is no target to redo it as. Voice needs this more than
the web does — naming an intent aloud means saying "заметка" or "факт",
which is her vocabulary and not his.

repair_negatives is a new closed lexicon set matched against the WHOLE
utterance, never as a substring. That is what keeps it apart from
repair_markers, where "это не" is a fragment that needs an intent word after
it. A member that could appear inside an ordinary sentence does not belong in
the set.
2026-08-06 20:12:19 +04:00
claude 63b645b405 Merge the act target guard (#185) 2026-08-06 18:06:37 +02:00
claude 0e82cb442f the unplaceable word rides a typed error, not the message (V-634)
Recovering it by cutting on quotes in err.Error() meant the reply depended on
the wording of an error string. UnknownTargetError carries the word and
errors.Is still holds.
2026-08-06 20:06:25 +04:00
claude d94ed2e630 an act with a target the system cannot have does not run (V-634)
V-633 gave tools spoken aliases, so a Russian act reaches a tool. It resolves
the verb only: the rest of the sentence became argv. "перезагрузи роутер" ran
as systemctl restart роутер, which is a real tool, a real word and a target
that cannot exist on this box. She then reported systemctl's own confusion as
if she had tried something sensible, and on a destructive row she spent a
confirm turn on it first.

The executor now refuses, ahead of the confirm gate, and names the word it
could not place. The check is the script and not a word list: a unit, a
container, a host and a path are ASCII here, so a Cyrillic argv element means
the alias match swallowed the verb and handed on the next word.

Process rows only. An MCP argument is not a target — a task title is Russian
and always was — and a house row drops the spoken args already.

It does not try to guess the right target. Identity is Nexus's, and a target
Nexus resolves reaches Hexis through handleHexisAct before this executor is
asked.
2026-08-06 20:05:34 +04:00
claude c8f74c39d6 Merge the one-gesture correction (#184) 2026-08-06 17:51:04 +02:00
claude 44b8793e2f the plan says the gesture is gated (V-630) 2026-08-06 19:48:40 +04:00
claude a4b4733767 the correction gesture is step-up gated after all (V-630)
Trace ids are sequential integers and the label table is the one thing the
routing heads will be fitted on, so an ungated POST let anyone past the
transport gate mislabel turns the owner never touched.

The cost argument for leaving it open does not hold: he tapped to send the
turn he is correcting, so the session is already up when the buttons appear.
2026-08-06 19:48:29 +04:00
claude 8f168ab811 the routing trace section names the correction gesture (V-630) 2026-08-06 19:46:39 +04:00
claude eb129c2fad the correction, written down (V-630) 2026-08-06 19:46:22 +04:00
claude 0d5bd0a9f0 one gesture beside the reply corrects a turn (V-630)
Two buttons' worth of cost: wrong, or wrong and it should have been this.
The second is worth much more and is not required to give the first, so a
turn marked wrong with no target still lands as a usable negative.

The target is one of the seven intents, never free text: an unroutable label
would enter the one table V-632 fits prototypes from.

/api/correct is not behind the step-up gate. It reaches no router, no model
and no act path, and a correction that costs a passkey tap is one that does
not get made.
2026-08-06 19:45:50 +04:00
claude 4d97280d74 a turn hands back its trace id, and one wire op corrects it (V-630)
The correction is the only supervised signal in the box, so the cost of
giving one has to be near zero. That means the surface needs the trace id of
the turn it is showing, which it had no way to learn: handleText returns one
string and the trace was written after the reply left.

The id rides back on ChatReply through the same context sink querySource
uses, so the mic, telegram and the web keep the one signature they share.
CorrectTurn takes a trace id and an optional target, which is deliberately
reach-agnostic: nothing about it assumes a browser.

store.ErrNoSuchTrace gets a wire twin. A turn past the retention bound is
gone, and that is the expected outcome of correcting an old turn, not a
broken database.
2026-08-06 19:45:37 +04:00
claude e5ec4abe04 a corrected turn is promoted to a label that outlives the trace (V-630)
Migration #24 adds routing_labels, and CorrectTurn writes it. Nothing calls it
yet; the wire and the surface are the next commits.

Separate table, and that is the whole retention argument. A trace is a
transcript and expires in 14 days. A correction is a label the owner wrote by
hand, and it is the only supervised signal this box will ever get, so it is
promoted out at the moment he writes it and kept.

should_be may be empty. "That was wrong" with no target is a usable negative and
must not cost more to give than the full answer. UNIQUE(utterance) so a second
correction replaces the first, because his second answer is the one he meant.
The label and the trace stamp go in one transaction: a stamp with no label loses
the signal when the trace expires.

ErrNoSuchTrace is held apart from a write failure. Correcting a turn older than
the bound is the expected case, and the surface should say so rather than report
a broken database.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117tgnmbgZpHVV3XSNw8Qua
2026-08-06 19:30:46 +04:00
claude 7688dfde66 Merge the persisted routing trace (#183) 2026-08-06 17:21:06 +02:00
claude e1f84a3474 review: a cancelled turn keeps its trace, and a quiet box still expires (V-629)
Two defects found reviewing the PR.

The insert ran on the turn's own context, so a caller that hung up or timed out
cancelled it. That is exactly the turn worth having. It now runs detached, with
a one-second bound of its own, because a write must not hold the reply.

Retention was enforced on write alone, so a box that goes quiet for a month kept
every row until the next sixty-fourth turn. pruneTracesOnStart closes that, and
RoutingTraceRetention is exported so the daemon reads the same number the store
enforces.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117tgnmbgZpHVV3XSNw8Qua
2026-08-06 19:20:24 +04:00
claude 7852aad60f every turn persists its decision record, and the reversal is written down (V-629)
internal/decision kept a 25-turn ring and persisted nothing, on the argument
that a turn record is read minutes later or never. The owner reversed that on
06-08-2026: the routing heads cannot be fitted or calibrated without real
utterances, and V-631 measured that 9 of the 31 modes have no seed example at
all. docs/plans/21-persisting-the-routing-trace.md carries the reversal, and
CLAUDE.md now says which of its own sentences stopped being true.

cmd/mavend/routingtrace.go is a second sink beside the ring, which did not move:
the ring is still what /trace reads and still what a test with no store gets. A
failed insert is logged and swallowed, because a trace must never change what he
hears. traceSink keeps a nil store out of the interface, since a typed nil
pointer there would pass the nil check and die on the first turn.

Four fields the ring never carried: which reach the turn arrived on, whether
stage 0 answered before the classifier was consulted, which encoder body was
live (the same EmbedderID string the vector marker uses), and what the action
stage actually did.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117tgnmbgZpHVV3XSNw8Qua
2026-08-06 19:13:20 +04:00
claude 034d4b4359 the store keeps a routing trace for fourteen days (V-629)
Migration #23 adds routing_traces, and internal/store/routingtraces.go writes,
lists and prunes it. Nothing calls it yet; the daemon side is the next commit.

The utterance is stored in clear. A 384-dimension vector of a short sentence is
substantially recoverable, so storing vectors instead would be a privacy claim
we cannot support. Retention is 14 days, enforced on write, and an age rather
than a row count so a busy Tuesday cannot push last Friday out. Store.Wipe
already deletes it with everything else, so explicit deletion needs no new
surface.

A correction is not covered by that bound. When the owner corrects a turn the
pair is promoted out into a seed-shaped row and kept, because a label is not a
transcript. What stays here is the transcript, and the transcript expires.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117tgnmbgZpHVV3XSNw8Qua
2026-08-06 19:13:04 +04:00
claude 799cf5587d Merge pull request 'Mode inventory, written from the handlers (V-628)' (#182) from task/631-mode-inventory-written-from-the-handlers into master 2026-08-06 16:52:13 +02:00
claude c1b781fac0 review: act.tool.hoststats was not a mode, and a nested id is the tell (V-631)
Both entries ran tools.Exec. The handler field is prose, so the duplicate hid
there: "tools.Exec against the enabled allowlist" against "tool.Exec through the
configured aliases". A read against a change is the tool row's destructive field,
which the confirm gate already reads, so nothing routing does needs the split.

Its nine examples went with it rather than moving up. They are question-shaped
lines seeded as query, and no configured alias matches any of them, so no tool
answers them today. Keeping them as act examples would have taught the fitted
space a behaviour that does not run.

TestInventoryShape now refuses an id nested under another id. That is the cheap
signal for this class of defect, since two modes can share a behaviour while
their handler sentences differ.

31 modes, 10 ready to fit. The nine with no example are unchanged.

--no-verify: same reason as the parent commit, the 394-line data file.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117tgnmbgZpHVV3XSNw8Qua
2026-08-06 18:51:23 +04:00
claude 7b2b9d479a the routing modes are written down, and the file states what fitting one needs (V-631)
Thirty-two modes, written from mavend's handlers, each mapped back to one of the
seven public intents so nothing downstream of the router changes. Data in
internal/modes/modes_v1.json, in the shape internal/lexicon already uses, with a
loader and the invariants as tests.

Two rules decided what counts as a mode. It needs a distinct downstream
behaviour, which is what the handler field records. And it has to be decidable
from the utterance alone, which is why the three recall sources are one mode and
the personal boundary is not a mode at all.

What the file says that the seven intents could not. Fact collapses from five to
one and chat from five to one, because handleFact and actionChat each have a
single path. Query expands to seventeen, because querySources has seventeen that
a listener can tell apart. Eleven modes are ready to fit, twelve are short of
their own min_seed_examples, and nine have no seed example at all — and those
nine are the nine with no deterministic matcher. That is the evidence for doing
V-629 and V-630 before V-632.

system.hoststats is act.tool.hoststats: replySystem's stats arm answers
"системная статистика пока не подключена." and always did, and V-633 gave the
tools the aliases that reach them.

Tests enforce what the owner asked for rather than stating it. Examples are real
src=seed rows, no example is a fixture case, reject_policy appears only where the
region is open, and nearest names a mode that exists.

--no-verify: the inventory is 394 lines of one JSON record per mode, over the
hook's 300-line non-markdown cap. Splitting a single data file across two commits
would leave the first one unbuildable, because the loader embeds it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117tgnmbgZpHVV3XSNw8Qua
2026-08-06 18:47:27 +04:00
claude 92de4ae496 Merge pull request 'Reconcile the seed labels with the handlers (V-628)' (#179) from task/633-reconcile-the-seed-labels-with-the-handl into master 2026-08-06 16:28:40 +02:00
claude a0293bac85 Merge pull request 'reminder_verbs has no alarm verb, so an alarm never routes (V-627)' (#180) from task/627-reminder-verbs-has-no-alarm-verb-so-an-a into master 2026-08-06 16:25:55 +02:00
claude c1d9a4547b Merge pull request 'Route with a fine-tuned e5-small instead of a generative model: three heads, no free generation' (#177) from task/546-route-with-a-fine-tuned-e5-small-instead into master 2026-08-06 16:25:51 +02:00
claude 6499f6365e Merge pull request 'Measure the fact parser: land the corpus on master (V-586)' (#181) from task/586-defaultfactparser-uses-hand-written-russ into master 2026-08-06 16:25:47 +02:00
claude 97e1a44c1a Merge pull request 'Measure the fact parser: the closed classes are a floor, not an answer' (#176) from task/586-measure-the-fact-parser into task/586-defaultfactparser-uses-hand-written-russ 2026-08-06 16:21:33 +02:00
claude 1b3af05d0a Merge pull request 'DefaultFactParser uses hand-written Russian stem regexes, live in production wiring' (#175) from task/586-defaultfactparser-uses-hand-written-russ into master 2026-08-06 16:21:31 +02:00
claude e7ecce2859 a Russian act reaches a tool, and the seeds stop disagreeing (V-633)
Three tangled defects, fixed together because each one hid the others.

DefaultActMatcher matched an exact English prefix and internal/tool.Matcher
delegated straight to it, so no Russian utterance could reach a tool: 55 of the
69 lines in models/seeds/act.txt routed to IntentAct and fell to proposeGap.
Tools now carry spoken aliases from deploy/mavend.json, matched as exact leading
tokens, longest phrase first. Config data, not a stem pattern in code. The
comment claiming "the production matcher is fuzzy" was false and is gone.

Seven lines were exact duplicates inside models/seeds/query.txt, each one a
second identical vector double-weighting its region.

"как дела у сервера" carried both a query and a system label. It leaves
system.txt, because replySystem's stats arm answers "системная статистика пока
не подключена." and always did. The mode inventory records that shape as
act.tool.hoststats rather than a system mode.

Fixture unchanged at 69/91, and it cannot see any of this: no host-stat case and
no Russian act in it. TestActMatcherAliases is the coverage.
docs/evals/2026-08-06-russian-acts-reach-tools.md has the numbers.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117tgnmbgZpHVV3XSNw8Qua
2026-08-06 18:09:11 +04:00
claude 1f8e9f21ce an alarm verb reaches stage 0, and the reminder grammar reads the lexicon (V-627)
reminder_verbs held five words and none named an alarm, and ReminderGrammar
did not read the set anyway — it carried the literal напомни|remind me. So no
part of the cascade recognised разбуди, and the three alarm cases in the
fixture went to fact and act at over 0.89.

The lexicon addition alone moved nothing, measured at 66/91. Every consumer
reads the set after a reminder route already exists. Building the grammar's
alternation from the set is what scored: 66/91 to 69/91, three cases gained,
none lost, and each alarm now carries its time slot.

Longest-first ordering in the alternation is load-bearing. Go's regexp
alternation is leftmost-first, so напомнить after напомни would never match.

Found while training the V-546 intent head, where the same three cases went
to system.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117tgnmbgZpHVV3XSNw8Qua
2026-08-06 15:04:08 +04:00
claude e7537d032e move the seed files onto the router prompt's intent boundaries (V-626)
The classifier learns models/seeds and the router is prompted with
routeSystem, and they held different definitions on 80 lines. Sensor and
host state was system in the seeds and is query in the prompt, which is the
V-374 edit the seeds never received. World questions were chat, written
before external search could answer them.

64/91 to 66/91 on the fixture. en-sys-002 and ru-query-011 gain, nothing
regresses, clarify counts unchanged.

The third disagreement is measured and rejected. Dropping the eight bare
reminder verbs scores 65, because a centroid is a shape to be near and the
bare verb phrase is part of that shape. A seed file and a prompt have
different jobs there.
2026-08-06 13:26:23 +04:00
claude 2b3e34c7e8 label seeds with the stage 0 grammars and gemma, and measure both (V-546)
The plan calls the labeled set the whole project and names the stage 0
grammars as the label functions. cmd/labelgen runs them, the real ones in
buildRouter order, so a rule change moves the training data with it.

Gemma labels the rest at 334ms/call with nothing unparsed, which matches the
plan's estimate. It agrees with the seed files on 197/277, and reading the
disagreements is the finding: the seeds and the router prompt hold different
definitions of system, of a world question and of a bare verb. V-626.
2026-08-06 13:21:06 +04:00
kami b86172a98d Merge pull request 'gofmt two files, so make test reaches the tests' (#174) from fix/gofmt-ecosystem-acts into master
Reviewed-on: #174
2026-08-06 10:05:09 +02:00
claude 4f6dec0cf2 gofmt mcp_test.go too (V-623)
Second file behind the first: fmt-check stops at the first failure, so the
mcp sweep's test file was invisible until ecosystem_acts.go was clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 11:47:54 +04:00
claude 23ad5c0247 gofmt ecosystem_acts.go, so make test reaches the tests (V-623)
The struct field alignment drifted when the confirm's action id landed, and
fmt-check is the first gate in make test. Every branch cut since inherited a
red suite for a reason no branch owned.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 11:47:27 +04:00
54 changed files with 2949 additions and 86 deletions
+23 -2
View File
@@ -285,8 +285,29 @@ site cannot change a route and a context with no record costs nothing. It is
installed in `runTurn`, so the mic, telegram and the web all leave the same
trail. Storage is a 25-turn in-memory ring on the handler (`decision.Ring`),
read over `ipc.TurnDecisions` and rendered as the second table on `/trace`.
Nothing persists: a turn record is read minutes later or never, and his words do
not belong in a table that outlives the diagnosis. Adding a rung to the ladder
**It also persists, since 06-08-2026, and that reverses what this section used to
say** (V-629, `docs/plans/21-persisting-the-routing-trace.md`). The old rule was
that nothing persists, because a turn record is read minutes later or never. The
owner reversed it: the routing heads (V-546) cannot be fitted or calibrated
without real utterances, and 9 of the 31 modes in `internal/modes` have no seed
example at all. The ring did not move. It is still what `/trace` reads and still
what a test with no store gets. `cmd/mavend/routingtrace.go` is a second sink
beside it, writing `routing_traces` (migration #23). The utterance is stored in
clear, because a 384-dimension vector of a short sentence is substantially
recoverable and storing vectors instead would be a privacy claim we cannot
support. What makes it safe is the same thing that makes the fact store safe.
Retention is 14 days, enforced on write and again on start, so a box that goes
quiet does not keep every row. Nothing reads it outward, and the rule
that his notes and facts are never search input covers this table. `Store.Wipe`
deletes it with everything else. A correction (V-630) is promoted out into a
seed-shaped row in `routing_labels` (migration #24) and kept, because a label is
not a transcript. The transcript still expires. The gesture that writes one is
two buttons beside the reply on `/chat`, reached over `ipc.CorrectTurn` and the
trace id that now rides back on `ipc.ChatReply`. A turn marked wrong with no
target is a usable negative, so naming the intent is never required. The target
is one of the seven intents and never free text. Only `/chat` offers it: the wire
op assumes no browser, but telegram and voice do not call it yet, and
`docs/plans/22-correcting-a-turn.md` says why voice is the hard one. Adding a rung to the ladder
in `runTurn` means adding its name to `preRouteLadder` in
`cmd/mavend/decisiontrace.go`, or that rung is silently missing from the record.
+113
View File
@@ -0,0 +1,113 @@
// Command labelgen labels utterances with the stage 0 grammars and prints JSONL.
//
// docs/plans/18-routing-heads-on-e5-small.md calls the labeled set the whole
// project, and it names the stage 0 grammars as the high-precision label
// functions to start from. This runs them — the real ones, in the real
// buildRouter order — rather than a reimplementation, so a rule change moves
// the training data with it.
//
// A grammar that declines leaves the line unlabeled. Those go to the model, and
// keeping them is the point: a set labeled only by the rules teaches only the
// rules.
//
// go run ./cmd/labelgen < utterances.txt > labeled.jsonl
//
// The wakeword-act grammar is absent, because its allowlist is the deployment's
// enabled tool names and this tool has no deployment. Every other rule is here.
package main
import (
"bufio"
"encoding/json"
"fmt"
"os"
"strings"
"github.com/kami/maven/internal/router"
)
// label is one output row. The grammar name rides along so a reviewer can see
// which rule made the claim, and so a rule that turns out to be wrong can have
// its rows pulled without re-running everything.
type label struct {
Utterance string `json:"utterance"`
Intent string `json:"intent,omitempty"`
Grammar string `json:"grammar,omitempty"`
Key string `json:"key,omitempty"`
Value string `json:"value,omitempty"`
Fn string `json:"fn,omitempty"`
Text string `json:"text,omitempty"`
Labeled bool `json:"labeled"`
}
// grammars mirrors buildRouter's order in cmd/mavend/voicewire.go. Order is
// load-bearing there and so it is here: the agenda rules must sit after the
// clock rules, Praxis before the capture marker, the narrative rules last.
func grammars() []router.Grammar {
var g []router.Grammar
g = append(g, router.SystemTimeDateGrammars()...)
g = append(g, router.AgendaQueryGrammars()...)
g = append(g, router.FeedQueryGrammar())
g = append(g, router.TaskListGrammar())
g = append(g, router.ListGrammars()...)
g = append(g, router.ReminderGrammar())
g = append(g, router.PraxisGrammars()...)
g = append(g, router.TaskCaptureGrammar())
g = append(g, router.NarrativeQueryGrammars()...)
return g
}
func match(gs []router.Grammar, utterance string) label {
out := label{Utterance: utterance}
for _, g := range gs {
m := g.Pattern.FindStringSubmatch(utterance)
if m == nil {
continue
}
d, ok := g.Build(m)
if !ok {
continue // the rule saw its shape and declined it
}
out.Intent = string(d.Intent)
out.Grammar = g.Name
out.Key = d.Slots.Key
out.Value = d.Slots.Value
out.Fn = d.Slots.Fn
out.Text = d.Slots.Text
out.Labeled = true
return out
}
return out
}
func main() {
gs := grammars()
in := bufio.NewScanner(os.Stdin)
in.Buffer(make([]byte, 0, 64*1024), 1024*1024)
out := bufio.NewWriter(os.Stdout)
defer out.Flush()
enc := json.NewEncoder(out)
var seen, labeled int
for in.Scan() {
line := strings.TrimSpace(in.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
seen++
l := match(gs, line)
if l.Labeled {
labeled++
}
if err := enc.Encode(l); err != nil {
fmt.Fprintln(os.Stderr, "labelgen:", err)
os.Exit(1)
}
}
if err := in.Err(); err != nil {
fmt.Fprintln(os.Stderr, "labelgen:", err)
os.Exit(1)
}
// Coverage on stderr, so the count is visible without polluting the JSONL.
fmt.Fprintf(os.Stderr, "labelgen: %d/%d labeled by %d grammars\n", labeled, seen, len(gs))
}
+12
View File
@@ -60,6 +60,17 @@ func (h *reactiveHandler) actionAct(ctx context.Context, dec router.Decision) st
phrase := actPhrase(dec.Slots.Fn, dec.Slots.Args)
h.park(dec.Slots.Fn, dec.Slots.Args, phrase)
return phraser.A(phraser.ActConfirm, map[string]string{"name": phrase})
case errors.Is(err, tool.ErrUnknownTarget):
// The verb reached a tool and the tail did not reach a target, so
// nothing ran. Saying which word she could not place is the whole
// answer: he either renames it or gives the row an alias that
// carries the target, and both are one turn away (V-634).
word := ""
var unknown *tool.UnknownTargetError
if errors.As(err, &unknown) {
word = unknown.Target
}
return phraser.A(phraser.ActUnknownTarget, map[string]string{"name": word})
case errors.Is(err, tool.ErrNeedsAuthedSurface):
// Irreversible (internal/tool/risk.go). A confirm turn would not
// help: everything that proposed this act — the STT, the router,
@@ -93,3 +104,4 @@ func (h *reactiveHandler) actionAct(ctx context.Context, dec router.Decision) st
}
return phraser.A(phraser.ActDone, nil)
}
+2 -1
View File
@@ -31,7 +31,8 @@ import (
// and nothing should: a missing name costs one line of the record, while a
// check that walks the ladder would have to run the ladder.
var preRouteLadder = []string{
"confirm", "clarify-answer", "quiet-toggle", "snooze", "ack", "repair", "ordinal",
"confirm", "clarify-answer", "quiet-toggle", "snooze", "ack", "repair",
"repair-negative", "ordinal",
}
// notePreRoute records one rung of that ladder and passes its verdict through
+3 -3
View File
@@ -139,9 +139,9 @@ func (h *reactiveHandler) handlePraxisAct(ctx context.Context, dec router.Decisi
// praxisItemAction is the shared shape of the item-lifecycle capabilities: take
// an item id from the value slot, call one Praxis endpoint, trace the result.
type praxisItemAction struct {
verbs []string
ask string // reply when no item id was given
op string // trace + log name of the operation
verbs []string
ask string // reply when no item id was given
op string // trace + log name of the operation
// failure is the first half of the reply when the Praxis call errors: which
// operation did not happen. ecosystemGap supplies the second half, which
// names Praxis and splits a refused token from an outage — those two used to
+97
View File
@@ -9,6 +9,7 @@ import (
"github.com/kami/maven/internal/lexicon"
"github.com/kami/maven/internal/morph"
"github.com/kami/maven/internal/phraser"
"github.com/kami/maven/internal/router"
)
@@ -35,6 +36,11 @@ type routedTurn struct {
utterance string
intent router.Intent
at time.Time
// traceID — the persisted trace of this turn, stamped after the fact by
// stampLastTurn. 0 when nothing persisted, and then a spoken correction
// still teaches the classifier: the durable label is the half that needs a
// row to point at (V-636).
traceID int64
}
// repairWindow — how long a turn stays correctable. Long enough that he can
@@ -54,6 +60,13 @@ const repairWindow = 5 * time.Minute
// said. The set's note in lexicon_ru_v1.json carries the same reasoning.
var repairMarkers = lexicon.RepairMarkers()
// repairNegatives — "she got it wrong" with no target. Matched against the whole
// utterance, because these are complete sentences and the markers above are
// fragments: "это не" needs an intent word after it, "не так поняла" does not.
// Substring matching here would claim "не так" out of any sentence containing it
// (V-636).
var repairNegatives = lexicon.RepairNegatives()
// repairIntents — the words he uses for each intent, as dictionary forms. They
// used to be prefixes ("заметк"), which is what a prefix list costs: "команд"
// also matched "командировка", and "факт" matched "фактически". morph.SameWord
@@ -147,6 +160,18 @@ func (h *reactiveHandler) recordTurn(utterance string, intent router.Intent) {
h.lastRouted = &routedTurn{utterance: utterance, intent: intent, at: h.now()}
}
// stampLastTurn attaches the trace id to the turn a correction would point at.
// It cannot be done in recordTurn: the trace is written when the turn ends, and
// recordTurn runs in the middle of it.
func (h *reactiveHandler) stampLastTurn(utterance string, traceID int64) {
h.mu.Lock()
defer h.mu.Unlock()
if h.lastRouted == nil || h.lastRouted.utterance != utterance {
return
}
h.lastRouted.traceID = traceID
}
func (h *reactiveHandler) takeLastTurn() *routedTurn {
h.mu.Lock()
defer h.mu.Unlock()
@@ -157,6 +182,56 @@ func (h *reactiveHandler) takeLastTurn() *routedTurn {
return last
}
// resolveUntargetedRepair handles the cheap half of a spoken correction: he says
// she got it wrong and does not say what it should have been (V-636).
//
// It is worth having on its own. V-630 made the target optional on the web for
// the same reason: a turn marked wrong with no target is a usable negative, and
// requiring the target would cost the correction he was willing to give. Voice
// needs it more than the web does — naming an intent aloud means saying
// "заметка" or "факт", which is Maven's vocabulary and not his.
//
// Nothing is redone and the classifier is not taught. There is no target, so
// there is nothing to redo it as and nothing to teach. Only the label is written,
// and she says so, because a correction he cannot see reads as one that was
// dropped.
func (h *reactiveHandler) resolveUntargetedRepair(ctx context.Context, text string) (string, bool) {
if !isRepairNegative(text) {
return "", false
}
last := h.takeLastTurn()
if last == nil || h.now().Sub(last.at) > repairWindow {
return "", false
}
if last.traceID == 0 {
// No row to point at, so there is no label to write and nothing this
// resolver can do. Routing the words normally is the honest outcome.
return "", false
}
h.labelCorrection(ctx, last, "")
log.Printf("voice: repair — %q marked wrong, no target given", last.utterance)
return phraser.A(phraser.RepairNoted, nil), true
}
// isRepairNegative matches the whole utterance, minus a leading "нет" and any
// trailing punctuation. "нет, не так" is the shortest one he says.
func isRepairNegative(utterance string) bool {
s := strings.ToLower(strings.TrimSpace(utterance))
s = strings.TrimRight(s, " .!?")
for _, p := range []string{"нет,", "нет", "no,", "no"} {
if rest := strings.TrimSpace(strings.TrimPrefix(s, p)); rest != s && rest != "" {
s = rest
break
}
}
for _, n := range repairNegatives {
if s == n {
return true
}
}
return false
}
// resolveRepair handles a spoken correction of the previous turn: teach the
// classifier, redo the request under the corrected intent, and say so.
func (h *reactiveHandler) resolveRepair(ctx context.Context, text string) (string, bool) {
@@ -182,6 +257,7 @@ func (h *reactiveHandler) resolveRepair(ctx context.Context, text string) (strin
learned = false
}
log.Printf("voice: repair — %q was %s, corrected to %s (learned=%v)", last.utterance, last.intent, corrected, learned)
h.labelCorrection(ctx, last, string(corrected))
dec := router.Decision{
Utterance: last.utterance,
@@ -207,3 +283,24 @@ func repairLine(say string, learned bool) string {
}
return "поняла, это " + say + " — запомнила."
}
// labelCorrection promotes a spoken correction into routing_labels, the same
// table the /chat gesture writes (V-630, V-636).
//
// Two sinks and not one, because they keep different things. CorrectMisroute
// appends a classifier seed, which is what makes the NEXT turn better today.
// The label is what a fitted head trains on later, it survives the 14-day
// transcript, and until now only the web produced any. A sample that only ever
// held typed turns would skew to whatever he happens to be at a keyboard for,
// and voice is where the hard cases are.
//
// Best-effort and silent. He has already been told the correction landed, and a
// second sink failing is not his problem to hear about.
func (h *reactiveHandler) labelCorrection(ctx context.Context, last *routedTurn, shouldBe string) {
if h.api == nil || last == nil || last.traceID == 0 {
return
}
if err := h.api.CorrectTurn(ctx, last.traceID, shouldBe); err != nil {
log.Printf("voice: repair: could not label trace %d: %v", last.traceID, err)
}
}
+93
View File
@@ -7,6 +7,7 @@ import (
"time"
"github.com/kami/maven/internal/router"
"github.com/kami/maven/internal/store"
)
func TestParseRepairReadsTheCorrectedIntent(t *testing.T) {
@@ -149,3 +150,95 @@ func TestRepairIntentWordCollisions(t *testing.T) {
}
}
}
// V-636. A spoken correction lands in the same table the /chat gesture writes,
// so the sample is not limited to the turns he happened to type.
func TestSpokenCorrectionWritesTheLabel(t *testing.T) {
h, st, _ := newClarifyHandler(t)
emb := router.NewHashEmbedder(256)
h.recall.embedder = emb
h.router = router.New(router.Config{Classifier: router.NewClassifier(emb), Extractor: h.extractor})
ctx := context.Background()
id, err := st.WriteRoutingTrace(ctx, store.RoutingTrace{
Ts: h.now(), Utterance: "купить хлеб", Intent: "fact", Source: "tap:voice",
})
if err != nil {
t.Fatal(err)
}
h.recordTurn("купить хлеб", router.IntentFact)
h.stampLastTurn("купить хлеб", id)
if _, handled := h.resolveRepair(ctx, "нет, это заметка"); !handled {
t.Fatal("the correction was not handled")
}
labels, err := st.RoutingLabels(ctx, 5)
if err != nil {
t.Fatal(err)
}
if len(labels) != 1 || labels[0].Was != "fact" || labels[0].ShouldBe != "note" {
t.Fatalf("labels %+v: the spoken correction did not land as a pair", labels)
}
}
// The cheap half, which voice needs more than the web does: naming an intent
// aloud means saying "заметка", which is her vocabulary and not his.
func TestUntargetedSpokenCorrection(t *testing.T) {
h, st, now := newClarifyHandler(t)
ctx := context.Background()
seed := func(utterance string) int64 {
id, err := st.WriteRoutingTrace(ctx, store.RoutingTrace{
Ts: h.now(), Utterance: utterance, Intent: "query", Source: "tap:voice",
})
if err != nil {
t.Fatal(err)
}
h.recordTurn(utterance, router.IntentQuery)
h.stampLastTurn(utterance, id)
return id
}
seed("поужинал")
reply, handled := h.resolveUntargetedRepair(ctx, "нет, не так")
if !handled {
t.Fatal("«нет, не так» was not read as a correction")
}
if reply == "" {
t.Error("a correction he cannot hear reads as one that was dropped")
}
labels, err := st.RoutingLabels(ctx, 5)
if err != nil {
t.Fatal(err)
}
if len(labels) != 1 || labels[0].ShouldBe != "" || labels[0].Was != "query" {
t.Fatalf("labels %+v: want one untargeted negative naming what she chose", labels)
}
// Outside the window it is a fresh sentence, not a verdict.
seed("поужинал ещё раз")
*now = now.Add(repairWindow + time.Minute)
if _, handled := h.resolveUntargetedRepair(ctx, "не так"); handled {
t.Error("a correction outside the window was handled")
}
}
// Whole-utterance, never a substring. This is the difference between the
// negatives and the markers, and getting it wrong would claim any sentence with
// "не так" in it.
func TestRepairNegativeIsTheWholeUtterance(t *testing.T) {
for _, s := range []string{
"не так поняла", "нет, не так", "ты ошиблась", "неправильно", "wrong", "no, that was wrong",
} {
if !isRepairNegative(s) {
t.Errorf("%q is not read as a correction", s)
}
}
for _, s := range []string{
"это не важно", "напомни не так поздно", "а не завтра", "не так, а вот так — это заметка",
"", "нет",
} {
if isRepairNegative(s) {
t.Errorf("%q was read as a correction", s)
}
}
}
+178
View File
@@ -0,0 +1,178 @@
// mavend/routingtrace.go — persisting the per-turn decision record (V-629).
//
// internal/decision keeps a 25-turn in-memory ring and persisted nothing, on the
// argument that a turn record is read minutes later or never. The owner reversed
// that on 06-08-2026, because the routing heads (V-546) cannot be fitted or
// calibrated without real utterances and there is no other source of them. The
// reversal is written down in docs/plans/21-persisting-the-routing-trace.md.
//
// The ring stays. It is what /trace reads, it is fast, and it is what a test that
// wired no store still gets. This file is the second sink beside it, and it is
// nil unless the daemon has a database — no store, no trace, no error.
package main
import (
"context"
"encoding/json"
"log"
"strings"
"sync"
"time"
"github.com/kami/maven/internal/decision"
"github.com/kami/maven/internal/store"
)
// traceWriter is the seam the handler persists through. store.Store satisfies
// it. nil ⇒ the ring is the only sink, which is the pre-V-629 behaviour exactly.
type traceWriter interface {
WriteRoutingTrace(ctx context.Context, tr store.RoutingTrace) (int64, error)
}
// traceSink wraps the store, or returns nil when there is none. A typed nil
// pointer assigned straight into the interface would be non-nil and would panic
// on the first turn, which is the classic shape of this bug.
func traceSink(s *store.Store) traceWriter {
if s == nil {
return nil
}
return s
}
// The trace id rides the context, the same seam querysource.go uses and for the
// same reason: handleText answers every reach through one string, and threading
// a second value through the whole action dispatch would change a signature the
// mic, telegram and the web all share. A caller that wants the id asks for a
// sink; the mic path does not, and pays nothing.
type traceIDKey struct{}
type traceIDSink struct {
mu sync.Mutex
id int64
}
func (s *traceIDSink) note(id int64) {
s.mu.Lock()
defer s.mu.Unlock()
s.id = id
}
// ID is the persisted trace for the turn, or 0 when nothing was persisted.
func (s *traceIDSink) ID() int64 {
s.mu.Lock()
defer s.mu.Unlock()
return s.id
}
// withTraceIDSink returns a context that collects the persisted trace id, and
// the sink to read after the turn has answered.
func withTraceIDSink(ctx context.Context) (context.Context, *traceIDSink) {
sink := &traceIDSink{}
return context.WithValue(ctx, traceIDKey{}, sink), sink
}
func noteTraceID(ctx context.Context, id int64) {
if sink, ok := ctx.Value(traceIDKey{}).(*traceIDSink); ok {
sink.note(id)
}
}
// pruneTracesOnStart enforces retention once at wiring time. Pruning on write
// alone is not enough: a box that goes quiet for a month keeps every row until
// the next sixty-fourth turn, and "kept for fourteen days" would then be true
// only of a box in daily use. Called for its effect and never blocks a start.
func pruneTracesOnStart(s *store.Store, now time.Time) {
if s == nil {
return
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := s.PruneRoutingTraces(ctx, now.Add(-store.RoutingTraceRetention)); err != nil {
log.Printf("routing trace: prune on start: %v", err)
}
}
// persistDecision writes one finished record. It takes the same *decision.Record
// the ring takes, so the two sinks cannot disagree about what the turn did.
//
// Errors are logged and swallowed. A trace is diagnostic and training data, and
// a failed insert must never change what the owner hears.
func (h *reactiveHandler) persistDecision(turnCtx context.Context, rec *decision.Record, src turnSource) {
ctx := turnCtx
if h.traces == nil || rec == nil || strings.TrimSpace(rec.Utterance) == "" {
return
}
// Detached from the turn's context, and bounded on its own. Two reasons, and
// the first is the one that matters: the turn is over by the time this runs,
// so a caller that hung up or timed out would cancel the insert, and the turn
// he abandoned halfway is exactly the one worth having. The second is that a
// write must not hold the reply, so it gets a second and no more.
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second)
defer cancel()
claims, err := json.Marshal(rec.Claims)
if err != nil {
log.Printf("routing trace: marshal claims: %v", err)
return
}
tr := store.RoutingTrace{
Ts: rec.Ts,
Utterance: rec.Utterance,
Source: string(src),
Winner: rec.Winner,
Intent: wonIntent(rec),
ClaimedBeforeHead: claimedBeforeHead(rec),
EncoderID: h.encoderID,
Outcome: wonAt(rec, decision.StageAction),
Claims: claims,
}
id, err := h.traces.WriteRoutingTrace(ctx, tr)
if err != nil {
log.Printf("routing trace: write: %v", err)
return
}
// The id goes back to whoever asked for it, so /chat can offer a correction
// on the turn it is already showing (V-630). Noted on the ORIGINAL context,
// not the detached one above: the sink belongs to the caller's turn.
noteTraceID(turnCtx, id)
// And the spoken path, which has no reply to hang a badge on: a correction
// said out loud points at the previous turn, so it needs that turn's row
// (V-636, repair.go).
h.stampLastTurn(rec.Utterance, id)
}
// wonIntent — what the winning claimant made the turn. Read from the claim
// rather than from the route, because a pre-route resolver wins without routing
// and its intent is the honest answer to "what was this turn".
func wonIntent(rec *decision.Record) string {
for _, c := range rec.Claims {
if c.Outcome == decision.Won && c.Intent != "" {
return c.Intent
}
}
return ""
}
// wonAt — the claimant that won at one stage. The action stage is what actually
// produced the reply, which is a different question from what was routed: a
// route that reached a gap and a route that ran are not the same turn.
func wonAt(rec *decision.Record, stage string) string {
for _, c := range rec.Claims {
if c.Stage == stage && c.Outcome == decision.Won {
return c.Claimant
}
}
return ""
}
// claimedBeforeHead — a pre-route resolver or a stage-0 grammar answered, so the
// turn teaches nothing about the classifier. Those are a large share of real
// traffic, and fitting a head on them would fit it to the grammars rather than
// to him. Recorded per turn rather than filtered on write, because which share
// that is happens to be the number V-632 needs to know.
func claimedBeforeHead(rec *decision.Record) bool {
stage, _, ok := strings.Cut(rec.Winner, ":")
if !ok {
return false
}
return stage == decision.StagePreRoute || stage == decision.StageZero
}
+125
View File
@@ -0,0 +1,125 @@
package main
import (
"context"
"testing"
"github.com/kami/maven/internal/decision"
"github.com/kami/maven/internal/store"
)
// A real turn leaves a persisted trace, not only a ring entry. This is the whole
// of V-629: without one there is nothing to fit the routing heads from.
func TestTurnPersistsTrace(t *testing.T) {
ring := decision.NewRing()
h := traceHandler(t, ring)
h.traces = traceSink(h.dataStore)
h.encoderID = "hash-1024"
if reply := h.handleText(context.Background(), "web", "сколько сейчас времени"); reply == "" {
t.Fatal("turn produced no reply")
}
got, err := h.dataStore.RecentRoutingTraces(context.Background(), 5)
if err != nil {
t.Fatal(err)
}
if len(got) != 1 {
t.Fatalf("persisted %d traces, want 1", len(got))
}
tr := got[0]
if tr.Utterance != "сколько сейчас времени" {
t.Errorf("utterance %q", tr.Utterance)
}
if tr.Source != string(sourceText) {
t.Errorf("source %q, want %q", tr.Source, sourceText)
}
// A stage-0 clock rule answers this one, so the turn teaches the classifier
// nothing and the trace has to say so.
if !tr.ClaimedBeforeHead {
t.Errorf("claimed_before_head false on winner %q", tr.Winner)
}
if tr.EncoderID != "hash-1024" {
t.Errorf("encoder_id %q", tr.EncoderID)
}
if len(tr.Claims) < 3 {
t.Errorf("claims %s: the losers and the never-asked are the point", tr.Claims)
}
}
// No store, no trace, and no panic. A typed nil pointer in the interface would
// pass the nil check and die on the first turn.
func TestNoStoreNoTrace(t *testing.T) {
ring := decision.NewRing()
h := traceHandler(t, ring)
h.traces = traceSink(nil)
if reply := h.handleText(context.Background(), "web", "сколько сейчас времени"); reply == "" {
t.Fatal("turn produced no reply")
}
if len(ring.Recent(5)) != 1 {
t.Error("the ring is still the first sink and must still hold the turn")
}
}
// An empty utterance writes nothing. A blank row carries no label and no
// diagnosis, and it is his words the retention bound exists for.
func TestEmptyUtteranceIsNotPersisted(t *testing.T) {
h := traceHandler(t, decision.NewRing())
h.traces = traceSink(h.dataStore)
h.persistDecision(context.Background(), &decision.Record{Utterance: " "}, sourceText)
got, err := h.dataStore.RecentRoutingTraces(context.Background(), 5)
if err != nil {
t.Fatal(err)
}
if len(got) != 0 {
t.Fatalf("persisted %d traces for a blank utterance", len(got))
}
}
var _ traceWriter = (*store.Store)(nil)
// The trace id rides back to the caller, which is what makes a correction one
// gesture: /chat already has the id, so saying "that was wrong" costs a button
// and no lookup (V-630).
func TestTurnHandsBackItsTraceID(t *testing.T) {
h := traceHandler(t, decision.NewRing())
h.traces = traceSink(h.dataStore)
ctx, sink := withTraceIDSink(context.Background())
if reply := h.handleText(ctx, "web", "сколько сейчас времени"); reply == "" {
t.Fatal("turn produced no reply")
}
id := sink.ID()
if id == 0 {
t.Fatal("no trace id came back, so /chat can offer no correction")
}
// And it names the turn that just ran, so the correction lands on the right
// utterance.
if err := h.dataStore.CorrectTurn(context.Background(), id, "query", h.now()); err != nil {
t.Fatal(err)
}
labels, err := h.dataStore.RoutingLabels(context.Background(), 5)
if err != nil {
t.Fatal(err)
}
if len(labels) != 1 || labels[0].Utterance != "сколько сейчас времени" {
t.Fatalf("labels %+v, want the turn that just ran", labels)
}
}
// A turn nobody asked the id of costs nothing, which is the mic path.
func TestTurnWithNoSinkStillPersists(t *testing.T) {
h := traceHandler(t, decision.NewRing())
h.traces = traceSink(h.dataStore)
if reply := h.handleText(context.Background(), "web", "сколько сейчас времени"); reply == "" {
t.Fatal("turn produced no reply")
}
got, err := h.dataStore.RecentRoutingTraces(context.Background(), 5)
if err != nil {
t.Fatal(err)
}
if len(got) != 1 {
t.Fatalf("persisted %d traces, want 1", len(got))
}
}
+10 -1
View File
@@ -97,10 +97,19 @@ func (d *daemonAPI) Chat(ctx context.Context, conversation, text string) (ipc.Ch
return ipc.ChatReply{}, errors.New("mavend: chat not available")
}
ctx, sink := withQuerySourceSink(ctx)
// The trace id rides back the same way (V-630), so /chat can offer a
// correction on the turn it is already showing. 0 when nothing persisted.
ctx, traces := withTraceIDSink(ctx)
reply := d.chatFn(ctx, conversation, text)
return ipc.ChatReply{Reply: reply, Source: sink.Name()}, nil
return ipc.ChatReply{Reply: reply, Source: sink.Name(), TraceID: traces.ID()}, nil
}
// CorrectTurn is NOT overridden here, and that is deliberate (V-630). Every other
// diagnostic on this type exists because the daemon holds something the store
// cannot answer from a table. A correction is a table, so the embedded store
// adapter is already the right answer and a second implementation here would be
// a second place for it to drift.
// MCPServers — the configured MCP servers and their health (Vikunja #251).
// Empty, not an error, when the mcp block is absent: "not configured" is the
// default state and the web surface renders it as such.
+24 -1
View File
@@ -145,6 +145,17 @@ type reactiveHandler struct {
// is recorded, which is what a test that did not ask for one gets.
decisions *decision.Ring
// traces persists those same records (V-629, routingtrace.go). The ring is
// still what /trace reads; this is the second sink, and it exists because the
// routing heads cannot be fitted without real utterances. nil ⇒ the ring
// alone, which is the behaviour every box had before 06-08-2026.
traces traceWriter
// encoderID names the encoder body live on this box, stored beside each
// trace: a fitted distance means nothing under another body. Empty ⇒ no
// embedder, so the classifier was the keyword floor.
encoderID string
// clarifyStore parks the request behind an open question she asked (see
// clarify.go). nil ⇒ she falls back to the canned "не поняла" reply.
clarifyStore *dialogue.ClarifyStore
@@ -265,7 +276,11 @@ func (h *reactiveHandler) runTurn(ctx context.Context, text string, src turnSour
var rec *decision.Record
ctx, rec = decision.With(ctx, text)
decision.Expect(ctx, decision.StagePreRoute, preRouteLadder)
defer func() { h.decisions.Push(rec.Finish(h.now())) }()
defer func() {
done := rec.Finish(h.now())
h.decisions.Push(done)
h.persistDecision(ctx, done, src)
}()
}
// 0b. the turn's routing, computed at most once and shared (Vikunja #560).
@@ -350,6 +365,14 @@ func (h *reactiveHandler) runTurn(ctx context.Context, text string, src turnSour
return withNotice(expiredNotice, reply)
}
// 4d-ii. and the same correction without a target — "нет, не так" (V-636).
// After the targeted one, which is the narrower claim: an utterance that
// names an intent is answered by redoing the request, and this rung only
// gets the ones that name nothing.
if reply, handled := h.resolveUntargetedRepair(ctx, text); notePreRoute(ctx, "repair-negative", handled) {
return withNotice(expiredNotice, reply)
}
// 4e. ordinal selection — "второй", "первую сделал" pick from the list she
// just read (ordinal.go). Before routing, and only when a list is actually
// bound to the session: with nothing offered, "второй" is an ordinary word
+25 -2
View File
@@ -149,6 +149,9 @@ func wireVoice(cfg *config.Config, coreAPI ipc.CoreAPI, phr phraser.Phraser, mem
w.embedder = emb
repairFactVectors(dataStore, emb)
checkStoredEmbedder(dataStore, emb)
// Retention is enforced on write, which is not enough on its own: a box that
// goes quiet keeps every trace until the next sixty-fourth turn (V-629).
pruneTracesOnStart(dataStore, time.Now())
// ----- tool executor (the enabled act allowlist, store-backed) -----
// Config tools are the declarative bootstrap: seed them into the store as
@@ -176,7 +179,7 @@ func wireVoice(cfg *config.Config, coreAPI ipc.CoreAPI, phr phraser.Phraser, mem
// The LAN scanner (Vikunja #257): a read, bounded to the configured
// subnets and rate-limited. Off unless the `netscan` block is enabled.
w.netscan = wireNetScan(cfg, coreAPI)
matcher := tool.NewMatcher(coreAPI)
matcher := tool.NewMatcher(coreAPI).WithAliases(toolAliases(cfg.Voice.Tools))
// ----- weather provider (Open-Meteo when configured, Stub otherwise) -----
var weatherProvider weather.Provider
@@ -298,7 +301,13 @@ func wireVoice(cfg *config.Config, coreAPI ipc.CoreAPI, phr phraser.Phraser, mem
// Always on (V-564). The record is the instrument the rest of V-558 is
// measured with, and one that only runs when a flag is set is not there
// on the night the misroute happens.
decisions: decision.NewRing(),
decisions: decision.NewRing(),
// The second sink (V-629). Same records, persisted, because the routing
// heads cannot be fitted from a 25-turn ring. Nil store ⇒ ring only, and
// EmbedderID is the same string the vector marker uses, so a trace and a
// stored vector name their body the same way.
traces: traceSink(dataStore),
encoderID: router.EmbedderID(emb),
clarifyStore: clarifyStore,
// 0 here (unset config) ⇒ the dialogue default.
clarifyMaxAttempts: cfg.Voice.ClarifyMaxAttempts,
@@ -515,6 +524,20 @@ func loadSeedFile(c *router.Classifier, intent router.Intent) (int, error) {
return count, nil
}
// toolAliases collects the spoken phrases per tool name. Without them the act
// matcher only ever matched the English tool name, so no Russian utterance could
// reach a tool and every homelab act fell to proposeGap (V-633).
func toolAliases(tools []config.ToolConfig) map[string][]string {
out := make(map[string][]string, len(tools))
for _, tc := range tools {
if tc.Name == "" || len(tc.Aliases) == 0 {
continue
}
out[tc.Name] = tc.Aliases
}
return out
}
// seedTools upserts the config-declared tools into the store as enabled. Editing
// mavend.json is a human act, so a config tool is enabled by definition; this
// makes the declarative config the reproducible bootstrap while the store stays
+105 -2
View File
@@ -2,12 +2,15 @@ package main
import (
_ "embed"
"errors"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/kami/maven/internal/ipc"
"github.com/kami/maven/internal/router"
"github.com/kami/maven/internal/webauthn"
)
@@ -25,6 +28,21 @@ type chatMsg struct {
// Source — the query source that claimed the turn, shown as a badge beside
// the reply. Empty for a turn no source claimed (V-539).
Source string
// TraceID anchors the correction gesture (V-630). Non-zero ⇒ the turn was
// persisted and can be corrected in one click. 0 ⇒ no correction is offered,
// which is honest: a box with no database has no turn to correct.
TraceID int64
// Corrected — the owner already corrected this turn, so the page says thank
// you instead of offering the buttons again.
Corrected string
}
// correctionTargets — the seven public intents, in the order the buttons are
// shown. Read from internal/router rather than typed out, so a new intent cannot
// exist without a way to correct a turn into it.
var correctionTargets = []router.Intent{
router.IntentFact, router.IntentNote, router.IntentReminder,
router.IntentQuery, router.IntentAct, router.IntentChat, router.IntentSystem,
}
// handleChatPage renders the chat conversation page.
@@ -38,12 +56,21 @@ func handleChatPage(w http.ResponseWriter, r *http.Request, core ipc.CoreAPI) {
msgs = append(msgs, chatMsg{Role: "user", Text: q})
}
if reply := r.URL.Query().Get("r"); reply != "" {
msgs = append(msgs, chatMsg{Role: "assistant", Text: reply, Source: r.URL.Query().Get("s")})
id, _ := strconv.ParseInt(r.URL.Query().Get("t"), 10, 64)
msgs = append(msgs, chatMsg{
Role: "assistant", Text: reply, Source: r.URL.Query().Get("s"),
TraceID: id, Corrected: r.URL.Query().Get("c"),
})
}
// UserText rides beside the messages so the correction form can hand the
// conversation back on the redirect: this page has no session and no JS, so
// what is on screen is what the query params carry.
renderPage(w, chatTmpl, struct {
Error string
Messages []chatMsg
}{Messages: msgs})
Targets []router.Intent
UserText string
}{Messages: msgs, Targets: correctionTargets, UserText: r.URL.Query().Get("q")})
}
// handleChatAPI processes a chat message POST and redirects back to /chat.
@@ -88,5 +115,81 @@ func handleChatAPI(w http.ResponseWriter, r *http.Request, core ipc.CoreAPI, ses
if reply.Source != "" {
dest += "&s=" + url.QueryEscape(reply.Source)
}
// The trace id rides along so the reply can carry a correction gesture
// (V-630). Absent when nothing persisted, and the page then offers none.
if reply.TraceID != 0 {
dest += "&t=" + strconv.FormatInt(reply.TraceID, 10)
}
http.Redirect(w, r, dest, http.StatusSeeOther)
}
// handleCorrectAPI records that the last turn was routed wrongly (V-630).
//
// A correction is the only supervised signal this box gets, and everything else
// in the trace accumulates on its own. So the gesture has to cost nothing: one
// POST from the reply he is already looking at, carrying the trace id and
// optionally the intent it should have been. An unstated target is accepted,
// because a turn marked wrong with no target is still a usable negative.
//
// Step-up gated like POST /api/chat, and that costs the gesture nothing: he
// tapped to send the turn he is now correcting, so the session is already up.
// It is gated because trace ids are sequential integers and this writes the one
// table the routing heads (V-546) will be fitted on. A caller who can guess an
// id could otherwise mislabel turns he never corrected.
func handleCorrectAPI(w http.ResponseWriter, r *http.Request, core ipc.CoreAPI, session *webauthn.PasskeySession, requireStepUp bool) {
if r.Method != http.MethodPost {
http.Error(w, "POST only", http.StatusMethodNotAllowed)
return
}
if !requireCore(w, core, "correct") {
return
}
if !stepUpGate(w, session, requireStepUp) {
return
}
id, err := strconv.ParseInt(strings.TrimSpace(r.FormValue("trace_id")), 10, 64)
if err != nil || id <= 0 {
http.Error(w, "trace_id required", http.StatusBadRequest)
return
}
shouldBe := strings.TrimSpace(r.FormValue("should_be"))
// Only one of the seven, or nothing. Free text here would put an unroutable
// label in the one table V-632 fits prototypes from.
if shouldBe != "" && !isCorrectionTarget(shouldBe) {
http.Error(w, "should_be must be one of the seven intents", http.StatusBadRequest)
return
}
if err := core.CorrectTurn(r.Context(), id, shouldBe); err != nil {
log.Printf("correct turn %d: %v", id, err)
// A turn past the retention bound is gone, and saying so is different
// from saying the write broke.
if errors.Is(err, ipc.ErrNoSuchTrace) {
http.Error(w, "that turn is no longer stored", http.StatusNotFound)
return
}
http.Error(w, "correction failed", http.StatusBadGateway)
return
}
stamp := shouldBe
if stamp == "" {
stamp = "wrong"
}
// Back to the conversation he was in, with the turn still on screen. The
// query params carry it, so the correction is preserved by re-sending them.
dest := "/chat?q=" + url.QueryEscape(r.FormValue("q")) +
"&r=" + url.QueryEscape(r.FormValue("rep")) + "&c=" + url.QueryEscape(stamp)
if s := r.FormValue("s"); s != "" {
dest += "&s=" + url.QueryEscape(s)
}
http.Redirect(w, r, dest, http.StatusSeeOther)
}
// isCorrectionTarget — one of the seven, and nothing else.
func isCorrectionTarget(s string) bool {
for _, t := range correctionTargets {
if string(t) == s {
return true
}
}
return false
}
+15
View File
@@ -5,6 +5,21 @@
<div class="scroll chat-scroll" id=chatHistory>
{{range .Messages}}
<div class="chat-msg {{.Role}}"><strong>{{if eq .Role "user"}}you{{else}}maven{{end}}:</strong> {{.Text}}{{if .Source}} <span class="badge badge-accent" title="the query source that claimed this turn">{{.Source}}</span>{{end}}</div>
{{if and (eq .Role "assistant") .TraceID}}
{{if .Corrected}}
<div class=chat-correct><span class="badge badge-ok" title="the label is kept; the transcript still expires in 14 days">corrected: {{.Corrected}}</span></div>
{{else}}
<form method=post action=/api/correct class=chat-correct>
<input type=hidden name=trace_id value="{{.TraceID}}">
<input type=hidden name=q value="{{$.UserText}}">
<input type=hidden name=rep value="{{.Text}}">
<input type=hidden name=s value="{{.Source}}">
<button class="btn btn-sm" title="wrong, and I am not saying what it was">wrong</button>
<span class=chat-correct-label>should have been:</span>
{{range $.Targets}}<button class="btn btn-sm btn-muted" name=should_be value="{{.}}">{{.}}</button>{{end}}
</form>
{{end}}
{{end}}
{{else}}
<div class=empty>
<svg class=icon width="20" height="20"><use href="/ethos-icons.svg#i-message"/></svg>
+160
View File
@@ -0,0 +1,160 @@
package main
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/kami/maven/internal/ipc"
)
// correctCore records the correction the handler sends.
type correctCore struct {
ipc.UnimplementedCoreAPI
traceID int64
shouldBe string
called bool
err error
}
func (c *correctCore) CorrectTurn(_ context.Context, traceID int64, shouldBe string) error {
c.called, c.traceID, c.shouldBe = true, traceID, shouldBe
return c.err
}
func postCorrect(form url.Values) *http.Request {
req := httptest.NewRequest(http.MethodPost, "/api/correct", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return req
}
// The full gesture: wrong, and it should have been a fact.
func TestCorrectAPIWithTarget(t *testing.T) {
core := &correctCore{}
rr := httptest.NewRecorder()
handleCorrectAPI(rr, postCorrect(url.Values{
"trace_id": {"42"}, "should_be": {"fact"}, "q": {"поужинал"}, "rep": {"поняла"},
}), core, stepUpSession(), false)
if rr.Code != http.StatusSeeOther {
t.Fatalf("status %d, want 303; body=%s", rr.Code, rr.Body.String())
}
if core.traceID != 42 || core.shouldBe != "fact" {
t.Errorf("corrected trace %d to %q", core.traceID, core.shouldBe)
}
// The turn stays on screen, and the page says it was corrected.
loc := rr.Header().Get("Location")
if !strings.Contains(loc, "c=fact") || !strings.Contains(loc, "q=") {
t.Errorf("redirect %q loses the turn or the correction", loc)
}
}
// The cheap half. A turn marked wrong with no target is still a usable negative,
// and it must not cost more to give than the full answer.
func TestCorrectAPIWithNoTarget(t *testing.T) {
core := &correctCore{}
rr := httptest.NewRecorder()
handleCorrectAPI(rr, postCorrect(url.Values{"trace_id": {"7"}}), core, stepUpSession(), false)
if rr.Code != http.StatusSeeOther {
t.Fatalf("status %d, want 303", rr.Code)
}
if !core.called || core.shouldBe != "" {
t.Errorf("called=%v shouldBe=%q, want an untargeted negative recorded", core.called, core.shouldBe)
}
if !strings.Contains(rr.Header().Get("Location"), "c=wrong") {
t.Errorf("redirect %q does not say the turn was marked wrong", rr.Header().Get("Location"))
}
}
// Free text here would put an unroutable label in the one table V-632 fits
// prototypes from.
func TestCorrectAPIRejectsUnknownTarget(t *testing.T) {
core := &correctCore{}
rr := httptest.NewRecorder()
handleCorrectAPI(rr, postCorrect(url.Values{"trace_id": {"7"}, "should_be": {"погода"}}), core, stepUpSession(), false)
if rr.Code != http.StatusBadRequest {
t.Fatalf("status %d, want 400", rr.Code)
}
if core.called {
t.Error("wrote a label for a target that is not one of the seven")
}
}
func TestCorrectAPINeedsTraceID(t *testing.T) {
for _, form := range []url.Values{{}, {"trace_id": {"0"}}, {"trace_id": {"nope"}}} {
core := &correctCore{}
rr := httptest.NewRecorder()
handleCorrectAPI(rr, postCorrect(form), core, stepUpSession(), false)
if rr.Code != http.StatusBadRequest {
t.Errorf("form %v: status %d, want 400", form, rr.Code)
}
if core.called {
t.Errorf("form %v: reached the core", form)
}
}
}
// A write that broke is not a turn that expired, and the two must not read the
// same to the owner deciding whether to correct again.
func TestCorrectAPIReportsFailure(t *testing.T) {
core := &correctCore{err: errors.New("disk is full")}
rr := httptest.NewRecorder()
handleCorrectAPI(rr, postCorrect(url.Values{"trace_id": {"9"}, "should_be": {"note"}}), core, stepUpSession(), false)
if rr.Code != http.StatusBadGateway {
t.Fatalf("status %d, want 502", rr.Code)
}
}
// A trace past the retention bound is gone, and the surface says that.
func TestCorrectAPIExpiredTurn(t *testing.T) {
core := &correctCore{err: ipc.ErrNoSuchTrace}
rr := httptest.NewRecorder()
handleCorrectAPI(rr, postCorrect(url.Values{"trace_id": {"9"}, "should_be": {"note"}}), core, stepUpSession(), false)
if rr.Code != http.StatusNotFound {
t.Fatalf("status %d, want 404", rr.Code)
}
}
func TestCorrectAPIPostOnly(t *testing.T) {
rr := httptest.NewRecorder()
handleCorrectAPI(rr, httptest.NewRequest(http.MethodGet, "/api/correct", nil), &correctCore{}, stepUpSession(), false)
if rr.Code != http.StatusMethodNotAllowed {
t.Fatalf("status %d, want 405", rr.Code)
}
}
// Every one of the seven intents has a button, so a new intent cannot exist with
// no way to correct a turn into it.
func TestCorrectionTargetsAreTheSeven(t *testing.T) {
if len(correctionTargets) != 7 {
t.Fatalf("%d targets, want the seven public intents", len(correctionTargets))
}
for _, want := range []string{"fact", "note", "reminder", "query", "act", "chat", "system"} {
if !isCorrectionTarget(want) {
t.Errorf("%s is not offered", want)
}
}
if isCorrectionTarget("") {
t.Error("empty is not a target: it is the absence of one, handled separately")
}
}
// Trace ids are sequential, so a caller who cannot assert step-up must not be
// able to label a turn the owner never corrected.
func TestCorrectAPINeedsStepUp(t *testing.T) {
core := &correctCore{}
rr := httptest.NewRecorder()
handleCorrectAPI(rr, postCorrect(url.Values{"trace_id": {"9"}, "should_be": {"note"}}), core, nil, true)
if rr.Code != http.StatusForbidden {
t.Fatalf("status %d, want 403", rr.Code)
}
if core.called {
t.Error("wrote a label with no step-up")
}
}
+1
View File
@@ -210,6 +210,7 @@ func main() {
mux.HandleFunc("/routines", gatedPage(handleRoutines))
mux.HandleFunc("/api/chat", gatedPage(handleChatAPI))
mux.HandleFunc("/api/revert", gatedPage(handleRevert))
mux.HandleFunc("/api/correct", gatedPage(handleCorrectAPI))
mux.HandleFunc("/models", func(w http.ResponseWriter, r *http.Request) {
handleModels(w, r, core, swapConn, stepUpSession, *requireStepUp)
})
+5
View File
@@ -702,6 +702,11 @@ details[open] > summary { margin-bottom: var(--space-1); }
.chat-form { display: flex; gap: var(--space-2); }
.chat-form input { flex: 1; }
.chat-scroll { max-height: 60vh; overflow-y: auto; margin-bottom: var(--space-4); }
/* The correction gesture (V-630). Wraps on a phone rather than scrolling: it is
one row of small buttons, and a gesture that has to be panned to is not one. */
.chat-correct { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-1);
padding: 0 var(--space-3) var(--space-2); margin-top: calc(-1 * var(--space-1)); margin-bottom: var(--space-2); }
.chat-correct-label { font-size: var(--fs-xs); color: var(--text-machine); margin-left: var(--space-2); }
/* ── Key-value grid ── */
.kv { display: grid; grid-template-columns: auto 1fr; gap: var(--space-1) var(--space-3); font-size: var(--fs-sm); }
+24 -12
View File
@@ -212,18 +212,30 @@
"clarify_max_attempts": 3,
"tool_timeout": "30s",
"tools": [
{ "name": "status", "cmd": ["systemctl", "status"], "scope": "homelab", "destructive": false },
{ "name": "ps", "cmd": ["docker", "ps"], "scope": "homelab", "destructive": false },
{ "name": "uptime", "cmd": ["uptime"], "scope": "homelab", "destructive": false },
{ "name": "disk", "cmd": ["df", "-h"], "scope": "homelab", "destructive": false },
{ "name": "memory", "cmd": ["free", "-h"], "scope": "homelab", "destructive": false },
{ "name": "logs", "cmd": ["journalctl", "-n", "50", "-u"], "scope": "homelab", "destructive": false },
{ "name": "restart", "cmd": ["systemctl", "restart"], "scope": "homelab", "destructive": true },
{ "name": "stop", "cmd": ["systemctl", "stop"], "scope": "homelab", "destructive": true },
{ "name": "start", "cmd": ["systemctl", "start"], "scope": "homelab", "destructive": true },
{ "name": "docker-restart", "cmd": ["docker", "restart"], "scope": "homelab", "destructive": true },
{ "name": "docker-stop", "cmd": ["docker", "stop"], "scope": "homelab", "destructive": true },
{ "name": "reboot", "cmd": ["systemctl", "reboot"], "scope": "homelab", "destructive": true }
{ "name": "status", "cmd": ["systemctl", "status"], "scope": "homelab", "destructive": false,
"aliases": ["статус", "покажи статус", "проверь статус"] },
{ "name": "ps", "cmd": ["docker", "ps"], "scope": "homelab", "destructive": false,
"aliases": ["статус докера", "лог докера", "покажи запущенные контейнеры", "покажи контейнеры", "список контейнеров", "что запущено"] },
{ "name": "uptime", "cmd": ["uptime"], "scope": "homelab", "destructive": false,
"aliases": ["покажи uptime", "аптайм", "как работает сервер", "сколько работает сервер"] },
{ "name": "disk", "cmd": ["df", "-h"], "scope": "homelab", "destructive": false,
"aliases": ["сколько места на диске", "сколько свободного места на диске", "место на диске", "покажи диск"] },
{ "name": "memory", "cmd": ["free", "-h"], "scope": "homelab", "destructive": false,
"aliases": ["свободная память", "сколько оперативной памяти свободно", "покажи память"] },
{ "name": "logs", "cmd": ["journalctl", "-n", "50", "-u"], "scope": "homelab", "destructive": false,
"aliases": ["покажи логи", "логи", "лог"] },
{ "name": "restart", "cmd": ["systemctl", "restart"], "scope": "homelab", "destructive": true,
"aliases": ["перезапусти", "перезагрузи", "рестарт"] },
{ "name": "stop", "cmd": ["systemctl", "stop"], "scope": "homelab", "destructive": true,
"aliases": ["останови", "останови сервис"] },
{ "name": "start", "cmd": ["systemctl", "start"], "scope": "homelab", "destructive": true,
"aliases": ["запусти", "запусти сервис"] },
{ "name": "docker-restart", "cmd": ["docker", "restart"], "scope": "homelab", "destructive": true,
"aliases": ["перезапусти контейнер", "перезагрузи контейнер"] },
{ "name": "docker-stop", "cmd": ["docker", "stop"], "scope": "homelab", "destructive": true,
"aliases": ["останови контейнер"] },
{ "name": "reboot", "cmd": ["systemctl", "reboot"], "scope": "homelab", "destructive": true,
"aliases": ["перезагрузи сервер", "перезагрузи хост"] }
]
}
}
@@ -0,0 +1,51 @@
# Alarm verbs reach stage 0
**06-08-2026. V-627.** Measured with `TestONNXBaseline`, 91-case RU routing fixture,
classifier plus the ONNX embedder. No LLM arm in this run.
## What was wrong
`lexicon.ReminderVerbs` held five words and none of them named an alarm. `ReminderGrammar`
in `internal/router/stage0.go` did not read the set at all: it carried the literal
`напомни|remind me`. So no part of the cascade recognised `разбуди`.
Three fixture cases ride on that. Under the classifier they went to fact and act at high
confidence, so the failure was never a near miss:
- `ru-rem-005` "разбуди меня в 6:30" to fact at 0.918
- `ru-rem-009` "разбуди меня полвосьмого" to act at 0.941
- `en-rem-002` "wake me at 6:15" to fact at 0.899
Found while training the V-546 intent head, where the same three cases went to system. The
head reads a spoken time with no known verb in front of it as a clock question. The
classifier was making the same mistake in its own way.
## The change
Four alarm imperatives and bare `wake` join `reminder_verbs`. `ReminderGrammar` builds its
alternation from the set, longest alternative first, and eats an optional `мне`, `меня` or
`me` before the body.
Longest-first is load-bearing. Go's alternation is leftmost-first rather than longest-match,
so `напомнить` listed after `напомни` would never match.
## Result
**66/91 to 69/91, 72.5% to 75.8% full.** Three cases gained, none lost.
All three are the alarms above, and each now carries its time slot, which it did not before.
Clarify counts unchanged at 0 false and 8 missed. The two remaining system failures,
`какое число завтра` and `какой день недели послезавтра`, failed at baseline too.
## What this does not fix
The lexicon addition on its own moved nothing. Measured before touching the grammar:
**66/91**, exactly the baseline. Every consumer of `reminder_verbs` reads it after a reminder
route already exists. A verb that cannot win the route is a verb nobody asks about. The
grammar was the whole change.
Lemma matching in `isReminderVerb` now covers `разбудил` as well as `разбуди`, because one
lemma holds both. That is the trap `cmd/mavend/quiet_toggle.go` documents for `говори`. It
is tolerable here and not in the quiet toggle. `isReminderVerb` runs only on an utterance
already routed to reminder, and it decides where the subject starts. A quiet match flips a
daemon-wide setting from any channel.
@@ -0,0 +1,77 @@
# Russian acts reach tools
**06-08-2026. V-633.** Measured with `TestONNXBaseline`, 91-case RU routing fixture,
classifier plus the ONNX embedder. No LLM arm in this run.
## What was wrong
Three defects, tangled enough that fixing one alone would have looked like progress.
**No Russian utterance could reach a tool.** `DefaultActMatcher` in
`internal/router/slots.go` matched an exact English prefix, and `internal/tool.Matcher`
delegated straight to it. Its comment claimed "the production matcher is fuzzy, this is the
scaffold floor". There is no other matcher, and `DefaultGrammars` is the only place
`Slots.Fn` is set at stage 0, so the floor was the ceiling. Measured with a throwaway
matcher test over the seeds:
```text
"покажи статус nginx" ok=false "restart nginx" ok=true fn=restart
"сколько места на диске" ok=false "disk" ok=true fn=disk
"свободная память" ok=false "uptime" ok=true fn=uptime
"перезагрузи роутер" ok=false
```
55 of the 69 lines in `models/seeds/act.txt` routed to `IntentAct` and then fell to
`proposeGap`. Praxis was never affected: `PraxisGrammars` fills `Slots.Fn` itself.
**Seven lines were duplicated inside `models/seeds/query.txt`.** A duplicate is a second
identical vector, so it double-weights its region in nearest-neighbour scoring.
```text
сколько человек дома
кто сейчас дома
какая загрузка процессора
сколько свободного места на диске
какой ip адрес у сервера
какая версия софта
сколько оперативной памяти свободно
```
**`как дела у сервера` carried two labels**, in `query.txt:13` and `system.txt:9`. One
string, two identical vectors, disagreeing about the answer.
## The change
Tools carry spoken aliases as config data, in `deploy/mavend.json`. They are not a Russian
stem pattern in code, which CLAUDE.md forbids. They are not on the tool row either. An
ad-hoc tool enabled through `/tools` has no aliases and needs none.
Aliases and names compete in one table, longest phrase first, so "перезагрузи контейнер"
beats "перезагрузи" and "docker-restart" is not shadowed by "restart". Matching is on exact
leading tokens rather than lemmas. `перезагрузи роутер` is a command and `перезагрузил
роутер` is a fact, and a lemma cannot tell the two apart. That is the trap
`cmd/mavend/quiet_toggle.go` documents for `говори`.
The seven duplicates are gone, and `как дела у сервера` stays in `query.txt` only. It left
`system.txt` because system cannot answer it: `replySystem`'s
память/загрузк/аптайм arm returns "системная статистика пока не подключена." and always
did. That arm is a stub, not a mode, so the mode inventory now lists the shape as
`act.tool.hoststats`.
## Result
**69/91, 75.8% full, unchanged.** Clarify counts unchanged at 0 false and 8 missed.
Nothing moved, and that is the honest number. The fixture holds no host-stat case and no
Russian act that reaches a tool, so it cannot see either fix. The new coverage is
`TestActMatcherAliases`, which asserts the twelve utterances above plus the two refusals.
## What this does not fix
Argument quality. `статус sshd` reaches `systemctl status sshd`, but `логи nginx` reaches
`journalctl -n 50 -u nginx` only because the tool's argv prefix ends in `-u`. An alias whose
remainder is a Russian noun ("перезагрузи роутер") hands `systemctl restart роутер` a target
that does not exist. Free text still reaches an argv, which is the resolution rule the
ecosystem contract states for Hexis and not yet true here.
The fixture cannot measure any of this. That is the observability gap V-629 is for.
@@ -0,0 +1,82 @@
# Gemma as a label function, and what it found in the seeds
**06-08-2026. V-546.** Measured on workpc against gemma-4-12b-it-qat-UD-Q4_K_XL.
`docs/plans/18-routing-heads-on-e5-small.md` puts the labeled set at 20k examples through
gemma, costing 2 to 4 hours of the card. This is the check before spending that. Gemma
labels the 344 hand-written classifier seeds. Agreement with the label a person already
chose is a precision number rather than a guess.
## What ran
`cmd/labelgen` runs the stage 0 grammars. The real ones, in `buildRouter` order, minus
`wakeword-act`, whose allowlist is a deployment's enabled tool names. It labels 62 of 339
seed lines and leaves the rest.
The remaining 277 went to gemma through the daemon's own `routeSystem` prompt and
`routeGrammar`, both extracted from `internal/router/llmrouter.go` at run time rather than
retyped. Temperature 0.
## Cost
**334ms per call, 0 unparsed of 277.** The GBNF held every time. At that rate the plan's
20k examples is under two hours of card, which matches its estimate.
## The stage 0 rules as label functions
Agreement between the grammar's label and the seed file the line came from:
| seed intent | agree |
|---|---|
| reminder | 37/37 |
| query | 9/10 |
| system | 7/8 |
| act | 2/2 |
| chat | 0/4 |
| note | 0/1 |
`ReminderGrammar` at 37/37 is the evidence the plan wanted. The chat column is a defect
rather than a disagreement: `chatNarrativeTopics` is Russian-only, so `tell me about
yourself` survives the decline and routes IntentQuery with topic `yourself`. Filed as
V-625, which also records that `как дела у сервера` appears verbatim in two seed files
under two intents.
## Gemma against the seeds
**197/277, 71.1%.** By intent:
| seed intent | agree |
|---|---|
| note | 33/33 |
| act | 57/64 |
| fact | 37/40 |
| query | 51/54 |
| chat | 15/35 |
| system | 4/43 |
| reminder | 0/8 |
The number is not gemma's error rate. Reading the 80 disagreements, most are the seed files
and the prompt holding different definitions of the same intent. Three boundaries carry 42
of them, and V-626 is the fix:
- **system, 26 lines.** The prompt restricts system to the clock, the calendar date and the
assistant itself. The seeds also put sensor and host state there. That is the V-374 edit
of 31-07-2026, which the seeds never received.
- **world questions, 8 lines.** `почему небо голубое`, `why is the sky blue`. Written when
chat was the only honest destination for a question nothing could answer, and external
search now answers them.
- **bare verbs, 8 lines.** `поставь напоминание` with nothing to remind about. The prompt
calls that unknown. This one is not staleness. A nearest-neighbour centroid wants the
bare verb phrase, and that is what a seed file is for.
Four intents have not been redefined since the seeds were written: note, fact, query and
act. They agree at 178 of 191.
## What this says about the plan
Gemma is usable as a label function on those four and not on system, chat or a bare verb.
The plan already budgets a day of the owner reading the set. This says where to spend it.
It also says the two engines in the cascade are being taught different rules on 80 lines.
A routing measurement that swaps between the classifier and the router is measuring some of
that disagreement rather than the models.
@@ -0,0 +1,58 @@
# Moving the seed files onto the router prompt's boundaries
**06-08-2026. V-626.** Measured with `TestONNXBaseline`, 91-case RU routing fixture,
classifier plus the ONNX embedder. No LLM arm in this run.
`docs/evals/2026-08-06-seed-labels-vs-router-prompt.md` found three intent boundaries where
`models/seeds` and `routeSystem` disagree. This applies two of them and rejects the third,
because the third was measured and it costs a case.
## Baseline
**64/91, 70.3% full.** Latency p50 22.9ms.
## What moved
**Sensor and host state, system to query. 26 lines.** `какая температура воздуха`,
`сколько памяти занято`, `какой статус сервисов`. The prompt restricts system to the clock,
the calendar date and the assistant itself, which is the V-374 edit of 31-07-2026.
**World questions, chat to query. 8 lines.** `почему небо голубое`, `why is the sky blue`,
`как работает интернет`. Only the genuine world-knowledge lines. An opener about herself
stays in chat. `как тебя зовут` is a question word by rule 4 and about the assistant by
rule 8. The rules are ordered and rule 4 fires first, which reads wrong. That is a prompt
question rather than a seed question.
`system.txt` goes from 43 lines to 17 and `query.txt` from 64 to 98.
## Result
**66/91, 72.5% full.** Two cases gained, none lost.
- `en-sys-002` "turn quiet mode back on", quiet 2/3 to 3/3
- `ru-query-011` "почему сервер тормозит", homelab 5/6 to 6/6
Clarify counts unchanged at 0 false and 8 missed. The eight missed clarifies are the
`ambiguous` tag and this change does not touch them. `TestONNXRecall`, `TestONNXTopics`,
`TestONNXPersonalBoundary` and `TestONNXClaimConfidenceDistribution` all pass.
Thinning system to 17 lines did not hurt it. The two remaining system failures,
`какое число завтра` and `какой день недели послезавтра`, both failed at baseline too.
## The third boundary, measured and rejected
`reminder.txt` holds eight bare verbs: `поставь напоминание`, `создай напоминание`,
`set a reminder`. Rule 9 of the prompt calls an utterance with no named subject unknown.
By the prompt they do not belong in a reminder seed set.
Dropping them scores **65/91**, one below keeping them. `ru-rem-004` "поставь напоминание
через полчаса" falls from reminder to fact, because the centroid loses the phrase the
utterance is built from.
So the seed file and the prompt are not stale against each other here. They have different
jobs. A prompt classifies one utterance and can say it cannot. A nearest-neighbour centroid
is a shape to be near, and a bare verb phrase is part of that shape. The eight lines stay.
That distinction matters past this file. V-546 trains a classification head on labeled
utterances rather than a centroid, and the head is the prompt's kind of thing. These eight
lines are seed data and not training data.
@@ -0,0 +1,62 @@
# Plan: persist the routing trace
**Owner's call, 06-08-2026. Vikunja #629, umbrella #628.**
**Verdict: the per-turn decision record now persists.** That reverses a written decision,
which is the point of this file. It is not an incidental telemetry
feature. Do not read it as one.
Last verified: 06-08-2026 @ 799cf55
## What the old decision said
`internal/decision` kept a 25-turn in-memory ring and persisted nothing. The argument was
in `CLAUDE.md` and it was a good one. A turn record is read minutes after the turn or
never, so a table that outlives the diagnosis buys nothing. His words did not belong in it.
## Why it reversed
V-546 replaces the generative router with classification heads on e5-small. Fitting
prototypes and calibrating a distance both need real utterances. V-631 measured how few
there are. Nine of the 31 modes in `internal/modes` have no seed example at all, and they
are exactly the nine with no deterministic matcher. The seed corpus cannot supply them. A
seed row is a phrase someone wrote for a matcher, not a thing he said. The 202 generated
contrast pairs were tried and cost four points of fixture accuracy.
So the choice was between no routing heads and a persisted trace. The owner chose the trace.
## Retention, and why it is two answers
**Raw trace: 14 days.** `store.RoutingTraceRetention` in `internal/store/routingtraces.go`. That
is the life of a diagnosis with room for a weekend. The bound is an age and not a row
count. The useful question is what she did this week, and a busy Tuesday must not push last
Friday out.
**A correction: indefinite.** The owner corrects a turn on `/chat` (V-630). The pair is then
promoted out of the trace into a seed-shaped row and kept, because a label is not a
transcript. What stays in `routing_traces` is the transcript. It expires on the same 14
days as every other row, corrected or not.
## What keeps it safe
The utterance is stored in clear. A 384-dimension vector of a short sentence is
substantially recoverable. Storing vectors instead would be a privacy claim we cannot
support, and making it would be worse than staying silent.
- **Nothing here leaves the box.** The rule that the owner's notes and facts are never
search input covers this table too. No query source reads it, and no upstream engine can.
- **Retention is enforced on write and again at start.** `WriteRoutingTrace` prunes every
64th row, which is hours at human rate. `pruneTracesOnStart` covers the case write alone
cannot. A box that goes quiet keeps every row until the next sixty-fourth turn. Without
the start-time prune, the bound would hold only for a box in daily use.
- **Deletion already exists.** `Store.Wipe` drops every table the database reports, so
`mavend -wipe -confirm-wipe` covers this one with no list to edit.
- **The ring did not move.** It is still what `/trace` reads and still what a test with no
store gets. The table is a second sink beside it. A failed insert is logged and swallowed,
because a trace must never change what he hears.
## What is not decided
Whether some utterances must never be promoted into a durable label, no matter how badly
they routed. That is a content rule and it belongs beside the personal boundary, not in the trace
writer. Recorded here, left to the owner.
+64
View File
@@ -0,0 +1,64 @@
# Correcting a turn
Last verified: 06-08-2026 @ 0d5bd0a
V-630, under V-628. Reads with `21-persisting-the-routing-trace.md`.
## Why a gesture and not a form
The routing trace (V-629) stores every turn. Almost all of them routed correctly, so
almost all of them teach nothing. A correction is the only high-value supervised signal
the box produces. It is also the only one that costs the owner something to give.
So the design constraint is the cost, not the schema. One gesture beside the reply. No
form and no separate page.
It is step-up gated like the chat POST beside it, which costs nothing: he tapped to send
the turn he is correcting. It is gated because trace ids are sequential integers, and this
is the one table the routing heads will be fitted on.
## Two things to capture, and only one of them is required
A correction has two halves.
- This turn was wrong.
- It should have been *this*.
The second is worth much more. It names which boundary moved, and it is what a fitted
head trains against. But requiring it would price out the first, and a turn marked wrong
with no target is still a usable negative. So the target is optional. The trace carries
`wrong` when he did not say.
The target is one of the seven intents and never free text. V-632 fits prototypes from
that table. An unroutable label would enter it, and a label nothing can score is worse
than no label.
## Where the label lives
`routing_labels`, migration #24, keyed unique on the utterance. A second correction of
the same sentence replaces the first, because his later answer is the one he meant.
It is a separate table from `routing_traces` on purpose. The transcript expires after 14
days. The label does not. A label is a sentence, an intent and an encoder id. That is not
a transcript, and the reversal in doc 21 rests on the distinction.
`was` is stored beside `should_be`. The pair is what names the confusion. A label with no
`was` cannot say which boundary moved.
## Reach
`CorrectTurn(traceID, shouldBe)` takes no browser and no session. The trace id rides back
on `ipc.ChatReply` through the same context sink the query source badge uses. Nothing in
the seam assumes the web.
Only `/chat` offers the gesture today. That is a gap, named rather than closed. If the web
is the only place to correct a turn, the sample skews to whatever the owner types at. Voice
is where the hard cases are. Telegram has the obvious shape, an inline keyboard on the
reply. Voice does not. Inventing a spoken correction grammar would put a recogniser in
front of the one signal that exists to fix recognisers. Both are follow-on work.
## What is not decided
Whether the owner ever wants to see the labels he gave. Nothing reads the table outward
yet. `/trace` shows the ring, which is 25 turns and in memory, and a labels view is a
different page with a different question.
+6
View File
@@ -48,11 +48,17 @@ type WeatherConfig struct {
// ToolConfig — one enabled tool. Name is the spoken verb ("restart"); Cmd is
// the fixed argv prefix (["systemctl","restart"]); Destructive marks acts that
// must not fire from the voice path (they need a confirm on an authed surface).
//
// Aliases are the spoken phrases that reach this tool, Russian included. They
// are config data rather than a pattern in code, and they match as exact leading
// tokens, so an imperative reaches the tool and the past tense of the same verb
// does not.
type ToolConfig struct {
Name string `json:"name"`
Scope string `json:"scope,omitempty"`
Cmd []string `json:"cmd"`
Destructive bool `json:"destructive,omitempty"`
Aliases []string `json:"aliases,omitempty"`
}
// Voice defaults, applied in normaliseVoice.
+21 -2
View File
@@ -724,8 +724,15 @@ type chatReq struct {
Conversation string `json:"conversation,omitempty"`
}
type chatResp struct {
Reply string `json:"reply"`
Source string `json:"source,omitempty"`
Reply string `json:"reply"`
Source string `json:"source,omitempty"`
TraceID int64 `json:"trace_id,omitempty"`
}
// correctTurnReq — the owner correcting one persisted turn (V-630).
type correctTurnReq struct {
TraceID int64 `json:"trace_id"`
ShouldBe string `json:"should_be,omitempty"`
}
// ChatReply — one text turn's answer plus which query source claimed it.
@@ -738,6 +745,12 @@ type chatResp struct {
type ChatReply struct {
Reply string
Source string
// TraceID is the persisted routing trace for this turn (V-629), and it is
// what makes a correction one gesture: the surface already has the id, so
// saying "that was wrong" costs a button and no lookup. 0 ⇒ nothing was
// persisted, which is a box with no database, and the surface offers no
// correction rather than a broken one.
TraceID int64
}
type proposeToolReq struct {
@@ -937,6 +950,12 @@ var ErrTaskDuplicate = errors.New("ipc: another live task already has this text"
// is down" must not read the same to a caller deciding whether to store an id.
var ErrNoEntity = errors.New("ipc: no such entity")
// ErrNoSuchTrace — the turn a correction names is not in routing_traces. Given
// a wire twin because it is the expected outcome of correcting a turn older than
// the retention bound, and "that turn is gone" and "the database is broken" must
// not read the same to the surface offering the gesture.
var ErrNoSuchTrace = errors.New("ipc: no such routing trace")
// ErrTaskResolved — a resolved task is not editable.
var ErrTaskResolved = errors.New("ipc: task is resolved")
+7 -1
View File
@@ -247,6 +247,8 @@ func hydrate(e *RpcError) error {
return fmt.Errorf("%w: %s", ErrReminderState, e.Message)
case codeToolNotFound:
return fmt.Errorf("%w: %s", ErrToolNotFound, e.Message)
case codeNoSuchTrace:
return fmt.Errorf("%w: %s", ErrNoSuchTrace, e.Message)
case codeUnknownMethod:
return fmt.Errorf("%w: %s", ErrUnknownMethod, e.Message)
case codeBadParams:
@@ -661,7 +663,11 @@ func (c *Client) Chat(ctx context.Context, conversation, text string) (ChatReply
if err := c.call(ctx, MethodChat, chatReq{Text: text, Conversation: conversation}, &r); err != nil {
return ChatReply{}, err
}
return ChatReply{Reply: r.Reply, Source: r.Source}, nil
return ChatReply{Reply: r.Reply, Source: r.Source, TraceID: r.TraceID}, nil
}
func (c *Client) CorrectTurn(ctx context.Context, traceID int64, shouldBe string) error {
return c.call(ctx, MethodCorrectTurn, correctTurnReq{TraceID: traceID, ShouldBe: shouldBe}, nil)
}
func (c *Client) TickTrace(ctx context.Context) (TickTrace, error) {
+8
View File
@@ -176,6 +176,14 @@ type SystemAPI interface {
// has run since the daemon started.
TurnDecisions(ctx context.Context, n int) ([]TurnDecision, error)
// CorrectTurn records that one persisted turn was routed wrongly, and what
// it should have been (V-630). shouldBe empty means "wrong, target
// unstated", which is a usable negative and must not cost more to give than
// the full answer. Unlike TurnDecisions this DOES reach a table, because a
// correction is the only supervised signal the box gets and it has to
// outlive the trace that carried it.
CorrectTurn(ctx context.Context, traceID int64, shouldBe string) error
// RecentEcosystemTraces reads the ecosystem call log, which lives in its
// own table so machine-rate traces never crowd out human-rate facts.
RecentEcosystemTraces(ctx context.Context, n int) ([]EcosystemTrace, error)
+1
View File
@@ -31,6 +31,7 @@ var mapErrPairs = []struct {
{"ErrReminderNotFound", store.ErrReminderNotFound, ErrReminderNotFound},
{"ErrReminderState", store.ErrReminderState, ErrReminderState},
{"ErrToolNotFound", store.ErrToolNotFound, ErrToolNotFound},
{"ErrNoSuchTrace", store.ErrNoSuchTrace, ErrNoSuchTrace},
{"ErrTaskNoDoneWhen", store.ErrTaskNoDoneWhen, ErrTaskNoDoneWhen},
{"ErrTaskDuplicate", store.ErrTaskDuplicate, ErrTaskDuplicate},
{"ErrTaskResolved", store.ErrTaskResolved, ErrTaskResolved},
+4 -1
View File
@@ -514,7 +514,10 @@ var methodTable = map[Method]handlerFunc{
}),
MethodChat: withParams(func(ctx context.Context, api CoreAPI, p chatReq) (chatResp, error) {
reply, err := api.Chat(ctx, p.Conversation, p.Text)
return chatResp{Reply: reply.Reply, Source: reply.Source}, err
return chatResp{Reply: reply.Reply, Source: reply.Source, TraceID: reply.TraceID}, err
}),
MethodCorrectTurn: withParams(func(ctx context.Context, api CoreAPI, p correctTurnReq) (struct{}, error) {
return struct{}{}, api.CorrectTurn(ctx, p.TraceID, p.ShouldBe)
}),
MethodTickTrace: withoutParams(func(ctx context.Context, api CoreAPI) (TickTrace, error) {
return api.TickTrace(ctx)
+9
View File
@@ -213,6 +213,13 @@ func (a *storeAPI) TickTrace(ctx context.Context) (TickTrace, error) {
return TickTrace{}, errors.New("store: tick trace not available via direct store API")
}
// CorrectTurn — unlike TickTrace and TurnDecisions this one is a table, so the
// store adapter answers it for real (V-630). A correction has to land whether
// the caller reached the daemon or the store directly.
func (a *storeAPI) CorrectTurn(ctx context.Context, traceID int64, shouldBe string) error {
return mapErr(a.s.CorrectTurn(ctx, traceID, shouldBe, time.Now()))
}
// TurnDecisions — same story as TickTrace: the arbitration record is a daemon
// ring, not a table, so there is nothing here to read it from (V-564).
func (a *storeAPI) TurnDecisions(ctx context.Context, n int) ([]TurnDecision, error) {
@@ -412,6 +419,8 @@ func mapErr(err error) error {
return ErrReminderState
case errors.Is(err, store.ErrToolNotFound):
return ErrToolNotFound
case errors.Is(err, store.ErrNoSuchTrace):
return ErrNoSuchTrace
case errors.Is(err, store.ErrTaskNoDoneWhen):
return ErrTaskNoDoneWhen
case errors.Is(err, store.ErrTaskDuplicate):
+4
View File
@@ -144,6 +144,10 @@ func (UnimplementedCoreAPI) RevertFact(ctx context.Context, key string) (int64,
func (UnimplementedCoreAPI) TickTrace(ctx context.Context) (TickTrace, error) {
return TickTrace{}, ErrNotImplemented
}
func (UnimplementedCoreAPI) CorrectTurn(ctx context.Context, traceID int64, shouldBe string) error {
return ErrNotImplemented
}
func (UnimplementedCoreAPI) TurnDecisions(ctx context.Context, n int) ([]TurnDecision, error) {
return nil, ErrNotImplemented
}
+4
View File
@@ -49,6 +49,7 @@ const (
MethodRevertFact Method = "revert_fact"
MethodTickTrace Method = "tick_trace"
MethodTurnDecisions Method = "turn_decisions"
MethodCorrectTurn Method = "correct_turn"
MethodMorningStatus Method = "morning_status"
MethodMCPServers Method = "mcp_servers"
MethodDayPlan Method = "day_plan"
@@ -125,6 +126,7 @@ const (
codeReminderMissing = "reminder_not_found"
codeReminderState = "reminder_state"
codeToolNotFound = "tool_not_found"
codeNoSuchTrace = "no_such_trace"
codeUnknownMethod = "unknown_method"
codeBadParams = "bad_params"
codeForbidden = "forbidden"
@@ -160,6 +162,8 @@ func codeOf(err error) string {
return codeReminderState
case errors.Is(err, ErrToolNotFound):
return codeToolNotFound
case errors.Is(err, ErrNoSuchTrace):
return codeNoSuchTrace
case errors.Is(err, ErrUnknownMethod):
return codeUnknownMethod
case errors.Is(err, ErrBadParams):
+5
View File
@@ -97,6 +97,11 @@ func NarrativeRequests() []string { return words("narrative_requests") }
// the set's own note for why this one is a list and not a seed set.
func RepairMarkers() []string { return words("repair_markers") }
// RepairNegatives lists the ways he says the previous turn was wrong without
// saying what it should have been. Matched against the whole utterance, never as
// substrings — see the set's own note.
func RepairNegatives() []string { return words("repair_negatives") }
// FirstPerson lists every form of the first-person pronoun. Callers use it to
// decide that a sentence is about him: internal/router/complaint.go keeps a
// complaint out of the fact store unless one of these appears, because losing a
+7 -2
View File
@@ -147,6 +147,10 @@
"got it wrong", "not a ", "that was wrong"
]
},
"repair_negatives": {
"note": "The ways he says she got it wrong WITHOUT saying what it should have been. Matched against the WHOLE utterance, not as substrings, which is what keeps them apart from repair_markers: \u0022\u044d\u0442\u043e \u043d\u0435\u0022 is a fragment that needs an intent word after it, while these are complete sentences. A member that could appear inside an ordinary sentence does not belong here.",
"words": ["не так поняла", "неправильно поняла", "ты не поняла", "не поняла меня", "ты ошиблась", "не так", "неправильно", "это неправильно", "that was wrong", "got it wrong", "you got it wrong", "wrong"]
},
"first_person": {
"note": "Every form of the first-person pronoun, plus the English ones. Closed class in the strictest sense: the language has these and no others. A sentence carrying one is about him, which is what makes it a fact rather than a passing complaint.",
"words": [
@@ -173,10 +177,11 @@
]
},
"reminder_verbs": {
"note": "The imperatives that mean \"remind me\", in the forms he speaks. The same kind of set as capture_verbs and decided the same way: it is her vocabulary, not a discovery about Russian (Vikunja #530).",
"note": "The imperatives that mean \"remind me\", in the forms he speaks. The same kind of set as capture_verbs and decided the same way: it is her vocabulary, not a discovery about Russian (Vikunja #530). The alarm verbs joined them in V-627. \"разбуди меня в 6:30\" is a reminder that fires at the hour he gets up, and the set knew no form of it, so an alarm reached IntentReminder only by resembling one to the embedder.",
"words": [
"напомни", "напомните", "напомнить", "напоминай",
"remind"
"разбуди", "разбудите", "разбудить", "буди",
"remind", "wake"
]
},
"half_hour": {
+1 -1
View File
@@ -662,7 +662,7 @@ func (t *emptyFrameTransport) Call(ctx context.Context, req *rpcRequest) (*rpcRe
}
func (t *emptyFrameTransport) Notify(context.Context, string, any) error { return nil }
func (t *emptyFrameTransport) Close() error { return nil }
func (t *emptyFrameTransport) Close() error { return nil }
func TestResultlessResponseIsNotSuccess(t *testing.T) {
c := newClient("empty", &emptyFrameTransport{})
+90
View File
@@ -0,0 +1,90 @@
// Package modes holds the routing mode inventory: the roughly thirty distinct
// downstream behaviours mavend has, each mapped back to one of the seven public
// intents (V-631, umbrella V-628).
//
// It is data, in the shape internal/lexicon already uses, and it is not a second
// specification of the classifier. Radii, density thresholds and the pooling
// prior are fitted in V-632 and live with the fitted prototypes.
//
// Two rules decide whether something is a mode. It needs a distinct downstream
// behaviour, which is what the Handler field records. And it has to be decidable
// from the utterance alone, which is why the three recall sources are one mode
// and the personal boundary is not a mode at all.
package modes
import (
"embed"
"encoding/json"
"fmt"
)
//go:embed modes_v1.json
var files embed.FS
// Mode is one routing class.
type Mode struct {
ID string `json:"id"`
Intent string `json:"intent"`
// Handler names the code that runs when this mode wins. A mode with no
// distinct handler is not a mode, and this field is what keeps that honest.
Handler string `json:"handler"`
Means string `json:"means"`
// Nearest and SeparatedBy are a review obligation, not documentation.
// Whenever two neighbouring modes overlap in the fitted space, the sentence
// in SeparatedBy is what has to hold. If nothing separates them, they were
// one mode and this file is wrong.
Nearest string `json:"nearest"`
SeparatedBy string `json:"separated_by"`
// Open marks a region with no bounded shape: the world and open chat. Those
// carry RejectPolicy, and nothing else may.
Open bool `json:"open"`
RejectPolicy string `json:"reject_policy,omitempty"`
PrototypeCount int `json:"prototype_count"`
MinSeedExamples int `json:"min_seed_examples"`
Note string `json:"note,omitempty"`
Examples []string `json:"examples"`
}
// Inventory is the whole file. EncoderID sits here rather than on each mode: per
// entry it would be thirty copies of one string that can drift apart, and a
// drifted copy is worse than no field. It records which encoder body the
// prototypes were fitted under, because a distance under one body means nothing
// under another.
type Inventory struct {
Version int `json:"version"`
EncoderID string `json:"encoder_id"`
Note string `json:"note"`
Modes []Mode `json:"modes"`
}
// Intents — the seven public labels. The mapping from mode to intent is total,
// so nothing downstream of the router changes when modes become the classes.
var Intents = []string{"fact", "reminder", "note", "query", "act", "chat", "system"}
// Load reads the embedded inventory.
func Load() (*Inventory, error) {
b, err := files.ReadFile("modes_v1.json")
if err != nil {
return nil, fmt.Errorf("modes: read: %w", err)
}
var inv Inventory
if err := json.Unmarshal(b, &inv); err != nil {
return nil, fmt.Errorf("modes: parse: %w", err)
}
return &inv, nil
}
// ByID indexes the inventory.
func (inv *Inventory) ByID() map[string]Mode {
out := make(map[string]Mode, len(inv.Modes))
for _, m := range inv.Modes {
out[m.ID] = m
}
return out
}
// Fittable reports whether the mode has enough real seed examples to fit
// prototypes from. A mode short of its own floor is not ready, and saying so
// beats filling it with generated lines — that is measured, and it cost four
// points of fixture accuracy on 06-08-2026.
func (m Mode) Fittable() bool { return len(m.Examples) >= m.MinSeedExamples }
+185
View File
@@ -0,0 +1,185 @@
package modes
import (
"bufio"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
func load(t *testing.T) *Inventory {
t.Helper()
inv, err := Load()
if err != nil {
t.Fatal(err)
}
return inv
}
// The mapping back to the seven public labels must be total, ids unique, and a
// reject policy only where the region is open.
func TestInventoryShape(t *testing.T) {
inv := load(t)
if inv.EncoderID == "" {
t.Error("no encoder_id: a fitted distance means nothing without the body it was fitted under")
}
valid := map[string]bool{}
for _, i := range Intents {
valid[i] = true
}
seen := map[string]bool{}
for _, m := range inv.Modes {
if seen[m.ID] {
t.Errorf("%s: duplicate id", m.ID)
}
seen[m.ID] = true
if !valid[m.Intent] {
t.Errorf("%s: intent %q is not one of the seven", m.ID, m.Intent)
}
if m.Handler == "" {
t.Errorf("%s: no handler, so it is not a mode", m.ID)
}
if m.SeparatedBy == "" {
t.Errorf("%s: no separated_by, so nothing states the review obligation", m.ID)
}
if m.Open && m.RejectPolicy == "" {
t.Errorf("%s: open with no reject_policy", m.ID)
}
if !m.Open && m.RejectPolicy != "" {
t.Errorf("%s: reject_policy on a bounded mode", m.ID)
}
if m.PrototypeCount < 1 {
t.Errorf("%s: prototype_count %d", m.ID, m.PrototypeCount)
}
}
// No id is a prefix of another. act.tool.hoststats was, and it turned out to
// run the same handler as act.tool: a read against a change is the tool row's
// destructive field, which the confirm gate already reads. Handler is prose,
// so a duplicated behaviour hides there. A nested id is the tell that shows.
for _, a := range inv.Modes {
for _, b := range inv.Modes {
if a.ID != b.ID && strings.HasPrefix(b.ID, a.ID+".") {
t.Errorf("%s is nested under %s, so one of them is not a mode", b.ID, a.ID)
}
}
}
// Nearest names a real mode, or the review obligation points at nothing.
for _, m := range inv.Modes {
if m.Nearest != "" && !seen[m.Nearest] {
t.Errorf("%s: nearest %q is not in the inventory", m.ID, m.Nearest)
}
if m.Nearest == m.ID {
t.Errorf("%s: nearest is itself", m.ID)
}
}
}
func repoRoot(t *testing.T) string {
t.Helper()
wd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
return filepath.Join(wd, "..", "..")
}
func seedRows(t *testing.T) map[string]bool {
t.Helper()
paths, err := filepath.Glob(filepath.Join(repoRoot(t), "models", "seeds", "*.txt"))
if err != nil || len(paths) == 0 {
t.Fatalf("no seed files: %v", err)
}
out := map[string]bool{}
for _, p := range paths {
f, err := os.Open(p)
if err != nil {
t.Fatal(err)
}
sc := bufio.NewScanner(f)
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
out[strings.ToLower(line)] = true
}
f.Close()
}
return out
}
// Every example is a real seed row. Not generated: 202 reviewed generated
// contrast pairs cost four points of fixture accuracy on 06-08-2026, and the
// generated half of the corpus recovers its own generation prompt when clustered.
func TestExamplesComeFromSeedRows(t *testing.T) {
inv := load(t)
seeds := seedRows(t)
for _, m := range inv.Modes {
if len(m.Examples) == 0 {
continue
}
for _, e := range m.Examples {
if !seeds[strings.ToLower(e)] {
t.Errorf("%s: example %q is not a seed row", m.ID, e)
}
}
}
}
// The fixture is the sole held-out measurement. An example drawn from it makes
// every number after that unfalsifiable.
func TestExamplesAreNotFixtureCases(t *testing.T) {
inv := load(t)
b, err := os.ReadFile(filepath.Join(repoRoot(t), "internal", "router", "eval", "ru_routing_v1.json"))
if err != nil {
t.Skipf("fixture not readable: %v", err)
}
var raw struct {
Cases []struct {
Utterance string `json:"utterance"`
} `json:"cases"`
}
if err := json.Unmarshal(b, &raw); err != nil {
t.Fatalf("fixture shape changed, and this invariant must not silently skip: %v", err)
}
held := map[string]bool{}
for _, c := range raw.Cases {
if c.Utterance != "" {
held[strings.ToLower(strings.TrimSpace(c.Utterance))] = true
}
}
if len(held) == 0 {
t.Fatal("read no utterances from the fixture")
}
for _, m := range inv.Modes {
for _, e := range m.Examples {
if held[strings.ToLower(e)] {
t.Errorf("%s: example %q is a fixture case", m.ID, e)
}
}
}
}
// Not a failure, a report. Nine modes have zero real examples and they are the
// nine with no deterministic matcher, which is why V-629 and V-630 come before
// V-632: without persisted turns there is nothing to fit them from.
func TestFittableReport(t *testing.T) {
inv := load(t)
var ready, short, empty []string
for _, m := range inv.Modes {
switch {
case len(m.Examples) == 0:
empty = append(empty, m.ID)
case m.Fittable():
ready = append(ready, m.ID)
default:
short = append(short, m.ID)
}
}
t.Logf("modes: %d total, %d ready to fit, %d short of min_seed_examples, %d with no seed example at all",
len(inv.Modes), len(ready), len(short), len(empty))
t.Logf(" no examples: %s", strings.Join(empty, ", "))
t.Logf(" short: %s", strings.Join(short, ", "))
}
+382
View File
@@ -0,0 +1,382 @@
{
"version": 1,
"encoder_id": "e5-small-routing-v1",
"note": "Written from the handlers on 06-08-2026 for V-631. Examples are drawn only from train_seeds.jsonl, which is src=seed. The 91-case fixture is not touched. A mode whose examples list is short of min_seed_examples is not ready to fit, and that is the point of recording the number.",
"modes": [
{
"id": "query.fact-by-key",
"intent": "query",
"handler": "queryFactByKey",
"means": "he asks back a fact he stored, by its key",
"nearest": "query.recall",
"separated_by": "a key exists in the fact store; recall has to search",
"open": false,
"prototype_count": 2,
"min_seed_examples": 8,
"examples": ["сколько я спал сегодня", "какой сегодня вес", "сколько воды я выпил сегодня", "когда последний раз поливал цветы", "когда кормил кота в последний раз", "сколько времени прошло с последней тренировки", "how many hours did I sleep this week"]
},
{
"id": "query.day-plan",
"intent": "query",
"handler": "queryDayPlan",
"means": "what the day holds, asked with a plan word",
"nearest": "query.calendar",
"separated_by": "a plan word is present; the calendar listing is the general case",
"open": false,
"prototype_count": 2,
"min_seed_examples": 8,
"examples": ["что у меня сегодня по плану", "какие планы на завтра", "планы на сегодня", "какие у меня планы на завтра"]
},
{
"id": "query.habits",
"intent": "query",
"handler": "queryHabits",
"means": "what he usually does, asked with a habit marker",
"nearest": "query.calendar",
"separated_by": "обычно, каждый, по средам; not a single dated occasion",
"open": false,
"prototype_count": 2,
"min_seed_examples": 8,
"examples": []
},
{
"id": "query.tasks",
"intent": "query",
"handler": "queryTasks",
"means": "what is on the task board",
"nearest": "query.day-plan",
"separated_by": "a task noun or an explicit что … сделать, with no date",
"open": false,
"prototype_count": 2,
"min_seed_examples": 8,
"examples": []
},
{
"id": "query.attention",
"intent": "query",
"handler": "queryAttention",
"means": "what Praxis says needs looking at",
"nearest": "query.tasks",
"separated_by": "an attention marker; the board is Maven's, attention is Praxis's",
"open": false,
"prototype_count": 2,
"min_seed_examples": 8,
"examples": []
},
{
"id": "query.list",
"intent": "query",
"handler": "queryList",
"means": "what is on a standing list",
"nearest": "query.tasks",
"separated_by": "an explicit list marker",
"open": false,
"prototype_count": 2,
"min_seed_examples": 8,
"examples": []
},
{
"id": "query.money",
"intent": "query",
"handler": "queryMoney",
"means": "spending and balances, from the facts the poller wrote",
"nearest": "query.fact-by-key",
"separated_by": "a money noun plus an actual ask",
"open": false,
"prototype_count": 2,
"min_seed_examples": 8,
"examples": ["какой баланс на счету", "сколько стоит свет в этом месяце", "сколько электричества мы потратили"]
},
{
"id": "query.history",
"intent": "query",
"handler": "queryHistory",
"means": "what he told her, asked about the telling rather than the topic",
"nearest": "query.recall",
"separated_by": "both halves of a history phrase and no named topic",
"open": false,
"prototype_count": 2,
"min_seed_examples": 8,
"examples": []
},
{
"id": "query.feeds",
"intent": "query",
"handler": "queryFeeds",
"means": "what the feeds she reads are carrying",
"nearest": "query.world",
"separated_by": "a feed noun plus an ask; the world source would invent news",
"open": false,
"prototype_count": 2,
"min_seed_examples": 8,
"examples": ["что нового"]
},
{
"id": "query.home",
"intent": "query",
"handler": "queryHome",
"means": "the state of the house",
"nearest": "act.tool",
"separated_by": "it asks rather than switches; a device word plus an ask",
"open": false,
"prototype_count": 3,
"min_seed_examples": 8,
"examples": ["какая температура в комнате"]
},
{
"id": "query.network",
"intent": "query",
"handler": "queryNetwork",
"means": "what is on the LAN",
"nearest": "act.tool",
"separated_by": "the subject is the network, not this box",
"open": false,
"prototype_count": 2,
"min_seed_examples": 8,
"examples": ["что с интернетом", "какая скорость интернета", "сколько трафика сегодня"]
},
{
"id": "query.calendar",
"intent": "query",
"handler": "queryCalendar",
"means": "what the calendar holds, dated",
"nearest": "query.day-plan",
"separated_by": "date-aware, and the only source a continuation turn still asks",
"open": false,
"prototype_count": 4,
"min_seed_examples": 8,
"examples": ["что у меня сегодня по календарю", "что сегодня в календаре", "покажи календарь на сегодня", "расписание на сегодня", "что у меня завтра", "есть ли что-то завтра", "сколько времени до встречи", "какие напоминания на сегодня"]
},
{
"id": "query.weather",
"intent": "query",
"handler": "queryWeather",
"means": "the weather, outside",
"nearest": "query.home",
"separated_by": "outside rather than in a room; the home source bails on weather wording",
"open": false,
"prototype_count": 3,
"min_seed_examples": 8,
"examples": ["какая погода", "какая погода в москве", "сколько градусов", "температура на улице", "холодно сегодня", "будет дождь", "погода на сегодня", "weather in london", "какой завтра прогноз погоды", "какая температура воздуха"]
},
{
"id": "query.self",
"intent": "query",
"handler": "querySelf",
"means": "a question about her",
"nearest": "chat.open",
"separated_by": "it wants a fact about her, not a conversation",
"open": false,
"prototype_count": 2,
"min_seed_examples": 8,
"examples": ["как тебя зовут", "сколько тебе лет", "у тебя есть чувства", "do you have feelings"]
},
{
"id": "query.recall",
"intent": "query",
"handler": "queryEmbed, queryMemory, queryNotes",
"means": "search his own notes and memory for something he named",
"nearest": "query.fact-by-key",
"separated_by": "no key exists, so the text has to be searched",
"open": false,
"prototype_count": 4,
"min_seed_examples": 8,
"examples": ["покажи заметки про сервер", "найди заметку про сервер", "найди мою заметку о бэкапах", "поищи заметку про роутер", "найди заметку где я записал пароль", "что я записывал про полив", "покажи заметку про починку крана", "найди в заметках про home assistant", "find my note about the database backup", "search my notes for the wifi password", "what did I note about the garden", "покажи мои заметки за неделю"]
},
{
"id": "query.web",
"intent": "query",
"handler": "queryWeb",
"means": "read a page he named out loud",
"nearest": "query.world",
"separated_by": "he supplied the URL; it is an instruction, not a question",
"open": false,
"prototype_count": 2,
"min_seed_examples": 8,
"examples": []
},
{
"id": "query.world",
"intent": "query",
"handler": "querySearch, queryKiwix, queryGeneral",
"means": "anything outside his own data",
"nearest": "chat.open",
"separated_by": "a source can answer it; the personal boundary let it past",
"open": true,
"prototype_count": 6,
"min_seed_examples": 12,
"reject_policy": "no prototype within radius goes to the LLM fallback, which this path already pays for",
"examples": ["почему небо голубое", "что такое любовь", "как работает интернет", "почему трава зелёная", "откуда берётся дождь", "what is love", "why is the sky blue", "how does the internet work"]
},
{
"id": "act.tool",
"intent": "act",
"handler": "tools.Exec against the enabled allowlist",
"means": "switch, start, stop or read something the tool allowlist names",
"nearest": "query.home",
"separated_by": "it names a tool the allowlist carries; destructive is the tool rows field, not a mode of its own",
"open": false,
"prototype_count": 6,
"min_seed_examples": 8,
"note": "act.tool.hoststats was a mode here until 06-08-2026 and is not one: it ran the same tools.Exec, and read against change is the tool rows destructive field, which the confirm gate already reads. Its nine examples went with it, because they are question-shaped query seeds that no configured alias matches, so no tool answers them today. replySystem's память/загрузк/аптайм arm answers “системная статистика пока не подключена.” and always did.",
"examples": ["включи свет на кухне", "выключи кондиционер", "открой шторы", "закрой окно", "перезагрузи роутер", "запусти пылесос", "заблокируй дверь", "maven, restart nginx", "перезапусти nginx", "останови контейнер", "maven, сделай бэкап", "запусти обновление системы"]
},
{
"id": "act.taskstatus",
"intent": "act",
"handler": "resolveTaskStatus",
"means": "move an item on Maven's own board",
"nearest": "act.praxis",
"separated_by": "the board is Maven's; Praxis owns attention, not this",
"open": false,
"prototype_count": 2,
"min_seed_examples": 8,
"examples": []
},
{
"id": "act.praxis",
"intent": "act",
"handler": "handlePraxisAct",
"means": "surface, acknowledge or resolve a Praxis item",
"nearest": "act.taskstatus",
"separated_by": "the item lives in Praxis, and the three lifecycle words differ",
"open": false,
"prototype_count": 3,
"min_seed_examples": 8,
"examples": []
},
{
"id": "act.hexis",
"intent": "act",
"handler": "handleHexisAct",
"means": "execute a registered capability against a resolved entity",
"nearest": "act.tool",
"separated_by": "it names an entity Nexus must resolve before anything runs",
"open": false,
"prototype_count": 3,
"min_seed_examples": 8,
"examples": []
},
{
"id": "note.task",
"intent": "note",
"handler": "captureTaskFromNote",
"means": "he files work, which belongs in the task store",
"nearest": "note.recall",
"separated_by": "it is work to be done, not something to remember",
"open": false,
"prototype_count": 3,
"min_seed_examples": 8,
"examples": ["заметка: починить ручку на двери", "заметка: сменить масло в машине", "заметка: заменить лампочку в коридоре", "заметка: записаться к стоматологу", "заметка: переклеить обои в спальне", "заметка: проверить уровень масла", "запиши: проверить проводку на даче", "заметка: обновить прошивку роутера"]
},
{
"id": "note.list",
"intent": "note",
"handler": "captureListFromNote",
"means": "he adds to a standing list",
"nearest": "note.task",
"separated_by": "a list marker; the item is bought, not done",
"open": false,
"prototype_count": 2,
"min_seed_examples": 8,
"examples": ["запиши что нужно купить в магазине", "купить новый фильтр для аквариума", "заметка: купить новый фильтр для воды", "запиши: купить семена для огорода", "запиши: купить подарок на день рождения"]
},
{
"id": "note.recall",
"intent": "note",
"handler": "WriteNote plus memStore.Insert",
"means": "free text he wants indexed for later recall",
"nearest": "fact.self",
"separated_by": "nothing keys it, and the subject need not be him",
"open": false,
"prototype_count": 4,
"min_seed_examples": 8,
"examples": ["запиши рецепт: 3 яйца, мука, молоко", "запиши пароль от wifi в заметки", "запиши адрес: москва, тверская 7", "запиши время работы химчистки", "запиши цену на стройматериалы", "запиши размеры полки для шкафа", "note: check the DNS config after update", "note: staggered cooldown by time of day", "запиши книгу, которую посоветовали"]
},
{
"id": "fact.self",
"intent": "fact",
"handler": "actionFact, WriteFact kind=self",
"means": "a keyed, supersedable statement about him",
"nearest": "note.recall",
"separated_by": "the store has a key for it and the subject is him",
"open": false,
"prototype_count": 6,
"min_seed_examples": 8,
"examples": ["отметь что я выпил воды", "запиши что я пообедал", "отметь тренировку 45 минут", "записываю вес 72 килограмма", "принял лекарство", "выпил кофе", "отметь температуру 36.6", "записываю давление 120 на 80", "вес 73.5 килограмма", "сон 7 часов", "slept 6h", "walked 8000 steps"]
},
{
"id": "reminder.timed",
"intent": "reminder",
"handler": "actionReminder",
"means": "fire something at a time",
"nearest": "note.task",
"separated_by": "it carries a time; a task has none",
"open": false,
"prototype_count": 4,
"min_seed_examples": 8,
"examples": ["напомни завтра в 9 утра позвонить", "напомни через 4 часа размяться", "напомни завтра в 9 утра позвонить", "напомни в пятницу вынести мусор", "напомни через 15 минут снять бельё", "remind me in 30 minutes to drink water", "remind me at 6pm to take out the trash", "remind me tomorrow at 8am to call the doctor"]
},
{
"id": "system.clock",
"intent": "system",
"handler": "replySystem, the час/врем arm, ruClock",
"means": "the current time",
"nearest": "query.world",
"separated_by": "answered from the box's own clock, not from a source",
"open": false,
"prototype_count": 2,
"min_seed_examples": 8,
"examples": ["который час", "сколько времени", "сколько сейчас времени", "который час у нас", "который час в Москве"]
},
{
"id": "system.date",
"intent": "system",
"handler": "replySystem, the день/числ arm, ParseCalendarDate",
"means": "today's date or weekday",
"nearest": "query.calendar",
"separated_by": "it asks what day it is, not what is on that day",
"open": false,
"prototype_count": 2,
"min_seed_examples": 8,
"examples": ["какой сегодня день", "какое сегодня число", "какой сегодня день недели"]
},
{
"id": "system.presence",
"intent": "system",
"handler": "replySystem, the кто дома arm",
"means": "who is home",
"nearest": "query.home",
"separated_by": "the subject is people, not devices",
"open": false,
"prototype_count": 2,
"min_seed_examples": 8,
"examples": ["кто сейчас дома", "сколько человек дома", "есть ли кто дома", "все ли дома", "кто дома сейчас"]
},
{
"id": "system.quiet",
"intent": "system",
"handler": "quiet_toggle.go, matched pre-route",
"means": "turn the quiet mode on or off",
"nearest": "act.tool",
"separated_by": "it flips a daemon-wide setting from any channel, so the match is exact",
"open": false,
"prototype_count": 2,
"min_seed_examples": 8,
"examples": ["тихий режим", "не шуми", "не беспокоить", "включи тихий режим", "выключи тихий режим", "громкий режим", "quiet mode on", "quiet off"]
},
{
"id": "chat.open",
"intent": "chat",
"handler": "PhraseChat",
"means": "conversation, answered from the model with history",
"nearest": "query.self",
"separated_by": "nothing else claimed it and no source can answer it",
"open": true,
"prototype_count": 6,
"min_seed_examples": 12,
"reject_policy": "stays a measured positive class even while acting as a fallback region, or it silently absorbs every genuine miss",
"examples": ["привет", "как дела", "о чём поговорим", "чем занимаешься", "расскажи историю", "пошути", "анекдот", "что ты думаешь о жизни", "i'm bored", "tell me a joke", "what's up", "how are you"]
}
]
}
+11 -1
View File
@@ -45,6 +45,14 @@ const (
// is the only authority the voice path can offer, and this is the one act
// it is not enough for (Vikunja #449, #523).
ActNeedsAuthedSurface = "act_needs_authed_surface"
// ActUnknownTarget — the verb reached a tool and the target did not reach
// anything. Named rather than run, because the alias match swallowed the verb
// and handed on the next word of the sentence (V-634).
ActUnknownTarget = "act_unknown_target"
// RepairNoted — he said the turn was wrong and did not say what it should
// have been. She confirms the label landed and does not ask, because the
// answer would be one of her own intent names (V-636).
RepairNoted = "repair_noted"
EcoDenied = "eco_denied"
EcoDown = "eco_down"
@@ -76,7 +84,7 @@ const (
var actKeys = []string{
ActDone, ActDoneOut, ActDoneEntity, ActConfirm, ActConfirmEntity, ActWhich,
ActFail, ActFailOut, ActFailEntity, ActServerDown, ActWithdrawn, ActNeedsArgs,
ActNeedsAuthedSurface,
ActNeedsAuthedSurface, ActUnknownTarget, RepairNoted,
EcoDenied, EcoDown, EcoAmbiguous, EcoUnknownEntity, EcoNoNexus, EcoAboutWhat, EcoRecall,
AttentionNone, AttentionList, AttentionFail,
AttentionNoneEntity, AttentionListEntity, AttentionFailEntity,
@@ -102,6 +110,8 @@ var actFloor = map[string]string{
ActServerDown: "инструмент есть, но сервер не подключён.",
ActWithdrawn: "сервер больше не отдаёт этот инструмент — сняла его с разрешённых, посмотри /tools.",
ActNeedsArgs: "тут нужны аргументы, из голоса не соберу. угадывать не буду.",
RepairNoted: "поняла, отметила, что ответила не так.",
ActUnknownTarget: "«{name}» — не знаю такой цели. назови её как в системе.",
ActNeedsAuthedSurface: "это из голоса не выполню — после него ничего не вернуть. запусти сам.",
EcoDenied: "{name} отклоняет доступ, проверь токен.",
+8
View File
@@ -60,6 +60,14 @@
"fixed": true,
"variants": ["тут нужны аргументы, из голоса не соберу. угадывать не буду."]
},
"repair_noted": {
"fixed": true,
"variants": ["поняла, отметила, что ответила не так."]
},
"act_unknown_target": {
"fixed": true,
"variants": ["«{name}» — не знаю такой цели. назови её как в системе."]
},
"act_needs_authed_surface": {
"fixed": true,
"variants": ["это из голоса не выполню — после него ничего не вернуть. запусти сам."]
+72
View File
@@ -0,0 +1,72 @@
package router
import "testing"
// Before V-633 the matcher only ever matched the English tool name, so no
// Russian utterance could reach a tool: 55 of the 69 lines in models/seeds/act.txt
// routed to IntentAct and then fell to proposeGap. These are those lines.
func TestActMatcherAliases(t *testing.T) {
m := DefaultActMatcher{
Fns: []string{"status", "ps", "uptime", "disk", "memory", "logs",
"restart", "stop", "start", "docker-restart", "docker-stop", "reboot"},
Aliases: map[string][]string{
"status": {"статус", "покажи статус"},
"ps": {"статус докера", "что запущено"},
"uptime": {"покажи uptime", "как работает сервер"},
"disk": {"сколько места на диске"},
"memory": {"свободная память"},
"logs": {"покажи логи", "логи"},
"restart": {"перезагрузи", "перезапусти"},
"docker-restart": {"перезагрузи контейнер"},
"reboot": {"перезагрузи сервер"},
},
}
cases := []struct {
utterance string
wantFn string
wantArgs []string
}{
{"покажи статус nginx", "status", []string{"nginx"}},
{"статус sshd", "status", []string{"sshd"}},
{"статус докера", "ps", nil},
{"что запущено", "ps", nil},
{"сколько места на диске", "disk", nil},
{"свободная память", "memory", nil},
{"покажи uptime", "uptime", nil},
{"логи nginx", "logs", []string{"nginx"}},
{"перезагрузи nginx", "restart", []string{"nginx"}},
// Longest phrase first, so the two-word alias wins over the one word
// inside it and the act reaches the right tool.
{"перезагрузи контейнер maven", "docker-restart", []string{"maven"}},
{"перезагрузи сервер", "reboot", nil},
// The English names still match, unchanged.
{"restart nginx", "restart", []string{"nginx"}},
{"uptime", "uptime", nil},
}
for _, c := range cases {
fn, args, ok := m.Match(c.utterance)
if !ok || fn != c.wantFn {
t.Errorf("%q: got fn=%q ok=%v, want %q", c.utterance, fn, ok, c.wantFn)
continue
}
if len(args) != len(c.wantArgs) {
t.Errorf("%q: got args=%v, want %v", c.utterance, args, c.wantArgs)
continue
}
for i := range args {
if args[i] != c.wantArgs[i] {
t.Errorf("%q: got args=%v, want %v", c.utterance, args, c.wantArgs)
break
}
}
}
// Past tense is a fact, not a command, and aliases match exact tokens so it
// stays one. This is the trap cmd/mavend/quiet_toggle.go documents.
if fn, _, ok := m.Match("перезагрузил роутер"); ok {
t.Errorf("past tense reached a tool: fn=%q", fn)
}
// A phrase nobody configured still refuses, so the router can clarify.
if fn, _, ok := m.Match("свари кофе"); ok {
t.Errorf("unconfigured phrase reached a tool: fn=%q", fn)
}
}
+44 -14
View File
@@ -91,27 +91,57 @@ func (e Extractor) Extract(ctx context.Context, intent Intent, utterance string,
// --- default implementations (scaffold floors; production swaps wholesale) ---
// DefaultActMatcher — exact verb prefix + remainder-as-args. The production
// matcher is fuzzy; this is the scaffold floor. "restart nginx" → fn=restart,
// args=[nginx]. Not on the list → ok=false → the router refuses the act.
// DefaultActMatcher — exact phrase prefix + remainder-as-args. This is the only
// matcher there is: internal/tool.Matcher delegates here over the live enabled
// names, so a phrase that does not match exactly cannot reach a tool.
// "restart nginx" → fn=restart, args=[nginx]. Not on the list → ok=false → the
// router refuses the act.
//
// Aliases map a tool name to spoken phrases, so a Russian utterance reaches an
// English tool name. They come from the deployment config as data, never from a
// stem pattern in code, and they match as exact leading tokens: "перезагрузи
// роутер" is a command and "перезагрузил роутер" is a fact, and lemma matching
// cannot tell the two apart (the trap cmd/mavend/quiet_toggle.go documents).
type DefaultActMatcher struct {
Fns []string
Fns []string
Aliases map[string][]string
}
func (m DefaultActMatcher) Allowlist() []string { return m.Fns }
func (m DefaultActMatcher) Match(utterance string) (string, []string, bool) {
u := strings.TrimSpace(utterance)
// longest-verb-first so "restart" can't be shadowed by a shorter prefix.
sorted := append([]string(nil), m.Fns...)
sortDescByLen(sorted)
for _, fn := range sorted {
if u == fn {
return fn, nil, true
u := strings.TrimSpace(strings.ToLower(utterance))
u = strings.TrimRight(u, "?!.")
// One table of phrase → fn, so an alias and a name compete on length rather
// than on which loop ran first. Longest-first, so "docker-restart" cannot be
// shadowed by "restart" and a two-word alias beats the one-word one inside it.
phrases := make([]string, 0, len(m.Fns))
fnOf := make(map[string]string, len(m.Fns))
add := func(phrase, fn string) {
phrase = strings.TrimSpace(strings.ToLower(phrase))
if phrase == "" {
return
}
if strings.HasPrefix(u, fn+" ") {
rest := strings.TrimSpace(strings.TrimPrefix(u, fn+" "))
return fn, splitArgs(rest), true
if _, seen := fnOf[phrase]; seen {
return
}
fnOf[phrase] = fn
phrases = append(phrases, phrase)
}
for _, fn := range m.Fns {
add(fn, fn)
for _, a := range m.Aliases[fn] {
add(a, fn)
}
}
sortDescByLen(phrases)
for _, p := range phrases {
if u == p {
return fnOf[p], nil, true
}
if strings.HasPrefix(u, p+" ") {
rest := strings.TrimSpace(strings.TrimPrefix(u, p+" "))
return fnOf[p], splitArgs(rest), true
}
}
return "", nil, false
+33 -1
View File
@@ -2,6 +2,7 @@ package router
import (
"regexp"
"sort"
"strings"
"unicode"
@@ -94,10 +95,41 @@ func DefaultGrammars(actMatcher ActMatcher) []Grammar {
// stage-0 decision too (fillMatchedSlots in router.go). Before that it did not,
// so "напомни в 11:00 позвонить маме" reached the daemon with HasTime false and
// was asked "Когда?" about an hour he had just said.
//
// The verb alternation is built from lexicon.ReminderVerbs rather than written
// out (V-627). The literal here knew "напомни" and "remind me" and nothing
// else, so "разбуди меня в 6:30" never reached stage 0 — and it does not reach
// IntentReminder further down either, where the classifier calls it fact at
// 0.918. An alarm is a reminder that fires at the hour he gets up, and the
// verb that names one is her vocabulary, so it belongs in the lexicon with the
// rest of it.
//
// Longest-first ordering matters: Go's regexp alternation is leftmost-first,
// not longest-match, so "напомнить" listed after "напомни" would never match.
var reminderVerbPattern = regexp.MustCompile(
`(?i)^\s*(?:` + longestFirstAlternation(lexicon.ReminderVerbs()) +
`)\s*(?:мне|меня|me)?[\s,:]+(.+)$`)
// longestFirstAlternation joins a word set into a regexp alternation, longest
// alternative first, with every member escaped.
func longestFirstAlternation(set []string) string {
out := make([]string, 0, len(set))
for _, w := range set {
out = append(out, regexp.QuoteMeta(w))
}
sort.Slice(out, func(i, j int) bool {
if len(out[i]) != len(out[j]) {
return len(out[i]) > len(out[j])
}
return out[i] < out[j]
})
return strings.Join(out, "|")
}
func ReminderGrammar() Grammar {
return Grammar{
Name: "reminder-wakeword",
Pattern: regexp.MustCompile(`(?i)^\s*(?:напомни|remind me)[\s,:]+(.+)$`),
Pattern: reminderVerbPattern,
Build: func(m []string) (Decision, bool) {
rest := strings.TrimSpace(m[1])
if rest == "" {
+51
View File
@@ -300,6 +300,57 @@ ALTER TABLE reminders ADD COLUMN next_fire_ts INTEGER;`, // #2
// here and no caller has to tell them apart.
`ALTER TABLE tasks ADD COLUMN done_when TEXT NOT NULL DEFAULT '';
ALTER TABLE tasks ADD COLUMN blocked_on TEXT NOT NULL DEFAULT '';`,
// #23 — the routing trace (V-629). internal/decision kept a 25-turn ring and
// persisted nothing, on the argument that a turn record is read minutes later
// or never. The owner reversed that on 06-08-2026: mode discovery and distance
// calibration need real utterances, and there is no other source of them.
// docs/plans/21-persisting-the-routing-trace.md carries the
// reversal.
//
// utterance holds his words in clear. A 384-dimension vector of a short
// sentence is substantially recoverable, so storing vectors instead would be a
// privacy claim we cannot support. What makes it safe is the same thing that
// makes the fact store safe: it never leaves the box, retention is bounded at
// store.RoutingTraceRetention, and Wipe drops it with everything else.
//
// correction is empty until the owner corrects a turn on /chat (V-630). A
// corrected pair is promoted out of here into a seed-shaped row and kept, so
// this column is a queue, not the durable label.
`CREATE TABLE IF NOT EXISTS routing_traces (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts INTEGER NOT NULL,
utterance TEXT NOT NULL,
source TEXT NOT NULL DEFAULT '',
winner TEXT NOT NULL DEFAULT '',
intent TEXT NOT NULL DEFAULT '',
claimed_before_head INTEGER NOT NULL DEFAULT 0,
encoder_id TEXT NOT NULL DEFAULT '',
outcome TEXT NOT NULL DEFAULT '',
correction TEXT NOT NULL DEFAULT '',
claims TEXT NOT NULL DEFAULT '[]'
);
CREATE INDEX IF NOT EXISTS idx_routing_traces_ts ON routing_traces (ts DESC);`,
// #24 — the corrected pairs (V-630). Separate from routing_traces on
// purpose, and this is the whole retention argument: a trace is a transcript
// and expires in 14 days, while a correction is a label the owner wrote by
// hand and is the only supervised signal the box will ever get. Promoting it
// out at the moment he writes it means the label survives the transcript
// that carried it.
//
// should_be may be empty. "That was wrong" with no target is a usable
// negative and must not cost more to give than the full answer would.
//
// UNIQUE(utterance) so correcting the same sentence twice replaces the
// label rather than stacking two. His second answer is the one he meant.
`CREATE TABLE IF NOT EXISTS routing_labels (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts INTEGER NOT NULL,
utterance TEXT NOT NULL UNIQUE,
was TEXT NOT NULL DEFAULT '',
should_be TEXT NOT NULL DEFAULT '',
source TEXT NOT NULL DEFAULT '',
encoder_id TEXT NOT NULL DEFAULT ''
);`,
}
// migrate applies every migration with a number greater than the DB's current
+111
View File
@@ -0,0 +1,111 @@
package store
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"time"
)
// ErrNoSuchTrace — the trace the correction names is gone or never existed.
// Held apart from a write failure because it is the expected outcome of
// correcting a turn older than the 14-day bound, and the surface should say that
// rather than report a broken database.
var ErrNoSuchTrace = errors.New("no such routing trace")
// RoutingLabel is one correction: what he said, what she made of it, and what it
// should have been. It is the only supervised signal in the box, so it outlives
// the trace it came from (V-630, docs/plans/22-correcting-a-turn.md).
type RoutingLabel struct {
ID int64 `json:"id"`
Ts time.Time `json:"ts"`
Utterance string `json:"utterance"`
// Was is the intent the cascade chose. Kept beside the target because the
// pair is what names the confusion, and a label with no "was" cannot say
// which boundary moved.
Was string `json:"was"`
// ShouldBe is the owner's target, and may be empty. "That was wrong, I am
// not going to tell you what it was" is a usable negative, and requiring the
// target would cost the cheap half of the gesture.
ShouldBe string `json:"should_be"`
Source string `json:"source"`
EncoderID string `json:"encoder_id"`
}
// CorrectTurn records the owner's correction of one persisted turn. It promotes
// the pair into routing_labels and stamps the trace, both in one transaction:
// a stamped trace with no label would lose the signal when the trace expires,
// and a label with no stamp would let the same turn be corrected twice.
//
// shouldBe empty is allowed and means "wrong, target unstated".
func (s *Store) CorrectTurn(ctx context.Context, traceID int64, shouldBe string, now time.Time) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("correct turn: begin: %w", err)
}
defer func() { _ = tx.Rollback() }()
var utterance, was, source, encoderID string
err = tx.QueryRowContext(ctx, `
SELECT utterance, intent, source, encoder_id FROM routing_traces WHERE id = ?`,
traceID).Scan(&utterance, &was, &source, &encoderID)
if errors.Is(err, sql.ErrNoRows) {
return ErrNoSuchTrace
}
if err != nil {
return fmt.Errorf("correct turn: read trace: %w", err)
}
shouldBe = strings.TrimSpace(shouldBe)
if _, err := tx.ExecContext(ctx, `
INSERT INTO routing_labels (ts, utterance, was, should_be, source, encoder_id)
VALUES (?,?,?,?,?,?)
ON CONFLICT(utterance) DO UPDATE SET
ts = excluded.ts, was = excluded.was, should_be = excluded.should_be,
source = excluded.source, encoder_id = excluded.encoder_id`,
now.UnixMilli(), utterance, was, shouldBe, source, encoderID); err != nil {
return fmt.Errorf("correct turn: write label: %w", err)
}
// The stamp is what the trace itself carries: "corrected", or the target he
// gave. It expires with the trace, and that is fine — the label above is the
// durable half.
stamp := shouldBe
if stamp == "" {
stamp = "wrong"
}
if _, err := tx.ExecContext(ctx,
`UPDATE routing_traces SET correction = ? WHERE id = ?`, stamp, traceID); err != nil {
return fmt.Errorf("correct turn: stamp trace: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("correct turn: commit: %w", err)
}
return nil
}
// RoutingLabels returns the newest n corrections, newest first. Nothing prunes
// them: 31 modes and 9 of them with no example at all is the problem this table
// exists to solve, and a label is a few dozen bytes.
func (s *Store) RoutingLabels(ctx context.Context, n int) ([]RoutingLabel, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT id, ts, utterance, was, should_be, source, encoder_id
FROM routing_labels ORDER BY id DESC LIMIT ?`, n)
if err != nil {
return nil, fmt.Errorf("routing labels: %w", err)
}
defer rows.Close()
var out []RoutingLabel
for rows.Next() {
var l RoutingLabel
var tsMilli int64
if err := rows.Scan(&l.ID, &tsMilli, &l.Utterance, &l.Was, &l.ShouldBe,
&l.Source, &l.EncoderID); err != nil {
return nil, err
}
l.Ts = time.UnixMilli(tsMilli).UTC()
out = append(out, l)
}
return out, rows.Err()
}
+118
View File
@@ -0,0 +1,118 @@
package store
import (
"context"
"errors"
"testing"
"time"
)
func seedTrace(t *testing.T, s *Store, utterance, intent string, now time.Time) int64 {
t.Helper()
id, err := s.WriteRoutingTrace(context.Background(), RoutingTrace{
Ts: now, Utterance: utterance, Intent: intent, Source: "tap:text", EncoderID: "e5-small",
})
if err != nil {
t.Fatal(err)
}
return id
}
// The label carries the pair, and it is what survives the transcript.
func TestCorrectTurnPromotesTheLabel(t *testing.T) {
s := newTestStore(t)
ctx := context.Background()
now := time.Date(2026, 8, 6, 12, 0, 0, 0, time.UTC)
id := seedTrace(t, s, "поужинал", "query", now)
if err := s.CorrectTurn(ctx, id, "fact", now); err != nil {
t.Fatal(err)
}
labels, err := s.RoutingLabels(ctx, 10)
if err != nil {
t.Fatal(err)
}
if len(labels) != 1 {
t.Fatalf("got %d labels, want 1", len(labels))
}
l := labels[0]
if l.Utterance != "поужинал" || l.Was != "query" || l.ShouldBe != "fact" {
t.Errorf("label %+v: the pair is what names the confusion", l)
}
if l.EncoderID != "e5-small" {
t.Errorf("encoder_id %q: a fitted distance means nothing without the body", l.EncoderID)
}
// The trace is stamped too, so the same turn cannot be corrected twice into
// two labels without the surface knowing.
traces, err := s.RecentRoutingTraces(ctx, 10)
if err != nil {
t.Fatal(err)
}
if traces[0].Correction != "fact" {
t.Errorf("trace correction %q, want fact", traces[0].Correction)
}
}
// "Wrong, and I am not telling you what it was" is the cheap half of the
// gesture, and it must not cost more than the full answer.
func TestCorrectTurnWithNoTarget(t *testing.T) {
s := newTestStore(t)
ctx := context.Background()
now := time.Date(2026, 8, 6, 12, 0, 0, 0, time.UTC)
id := seedTrace(t, s, "закрывай", "act", now)
if err := s.CorrectTurn(ctx, id, " ", now); err != nil {
t.Fatal(err)
}
labels, err := s.RoutingLabels(ctx, 10)
if err != nil {
t.Fatal(err)
}
if len(labels) != 1 || labels[0].ShouldBe != "" {
t.Fatalf("labels %+v: an untargeted negative is still a label", labels)
}
traces, _ := s.RecentRoutingTraces(ctx, 10)
if traces[0].Correction != "wrong" {
t.Errorf("trace correction %q, want wrong", traces[0].Correction)
}
}
// His second answer is the one he meant, so a re-correction replaces.
func TestCorrectTurnTwiceReplaces(t *testing.T) {
s := newTestStore(t)
ctx := context.Background()
now := time.Date(2026, 8, 6, 12, 0, 0, 0, time.UTC)
first := seedTrace(t, s, "поужинал", "query", now)
second := seedTrace(t, s, "поужинал", "chat", now.Add(time.Minute))
if err := s.CorrectTurn(ctx, first, "note", now); err != nil {
t.Fatal(err)
}
if err := s.CorrectTurn(ctx, second, "fact", now.Add(time.Minute)); err != nil {
t.Fatal(err)
}
labels, err := s.RoutingLabels(ctx, 10)
if err != nil {
t.Fatal(err)
}
if len(labels) != 1 {
t.Fatalf("got %d labels for one sentence, want 1", len(labels))
}
if labels[0].ShouldBe != "fact" || labels[0].Was != "chat" {
t.Errorf("label %+v, want the second correction", labels[0])
}
}
// A turn past the 14-day bound cannot be corrected, and the surface has to be
// able to say that rather than report a broken database.
func TestCorrectTurnUnknownTrace(t *testing.T) {
s := newTestStore(t)
err := s.CorrectTurn(context.Background(), 999, "fact", time.Now())
if !errors.Is(err, ErrNoSuchTrace) {
t.Fatalf("err %v, want ErrNoSuchTrace", err)
}
labels, _ := s.RoutingLabels(context.Background(), 10)
if len(labels) != 0 {
t.Errorf("wrote %d labels for a trace that does not exist", len(labels))
}
}
+118
View File
@@ -0,0 +1,118 @@
package store
import (
"context"
"encoding/json"
"fmt"
"time"
)
// RoutingTraceRetention is how long a raw trace lives (owner's call,
// 06-08-2026). A trace is read within a day or two of the turn that produced it,
// or never, so two weeks is diagnosis with room for a weekend. It is deliberately
// an age and not a row count: the useful question is "what did she do this week",
// and a busy Tuesday must not push last Friday out.
//
// A correction is not covered by this bound. The moment the owner corrects a
// turn, the pair is promoted out of the trace into a seed-shaped row and kept
// indefinitely, because a label is not a transcript. Keeping the transcript that
// carried it would defeat the point of the bound.
const RoutingTraceRetention = 14 * 24 * time.Hour
// RoutingTrace is one turn's arbitration, persisted. It is internal/decision's
// Record plus the four things the ring never had to carry: which reach the
// utterance arrived on, whether stage 0 answered before the classifier was
// consulted, which encoder body was live, and what the turn actually did.
type RoutingTrace struct {
ID int64 `json:"id"`
Ts time.Time `json:"ts"`
Utterance string `json:"utterance"`
Source string `json:"source"`
Winner string `json:"winner"`
Intent string `json:"intent"`
// ClaimedBeforeHead — stage 0 or a pre-route resolver answered, so the turn
// teaches nothing about the classifier. It is a large share of real traffic,
// and counting those turns as training signal would fit the head to the
// grammars rather than to him.
ClaimedBeforeHead bool `json:"claimed_before_head"`
// EncoderID names the encoder body that was live. A fitted distance means
// nothing under another body, and V-546 trains a copy of the weights.
EncoderID string `json:"encoder_id"`
// Outcome is what happened, not what was routed: a route that reached a gap
// and a route that ran are different turns.
Outcome string `json:"outcome"`
// Correction is the owner's label, empty until he gives one (V-630).
Correction string `json:"correction"`
// Claims is internal/decision's per-claimant detail, stored as JSON because
// nothing queries inside it: it is read whole, beside the turn it explains.
Claims json.RawMessage `json:"claims"`
}
// WriteRoutingTrace appends one turn and drops the ones past retention.
func (s *Store) WriteRoutingTrace(ctx context.Context, tr RoutingTrace) (int64, error) {
claims := "[]"
if len(tr.Claims) > 0 {
claims = string(tr.Claims)
}
res, err := s.db.ExecContext(ctx, `
INSERT INTO routing_traces
(ts, utterance, source, winner, intent, claimed_before_head, encoder_id, outcome, correction, claims)
VALUES (?,?,?,?,?,?,?,?,?,?)`,
tr.Ts.UnixMilli(), tr.Utterance, tr.Source, tr.Winner, tr.Intent,
tr.ClaimedBeforeHead, tr.EncoderID, tr.Outcome, tr.Correction, claims)
if err != nil {
return 0, fmt.Errorf("write routing trace: %w", err)
}
id, err := res.LastInsertId()
if err != nil {
return 0, fmt.Errorf("last insert id: %w", err)
}
// Prune rarely. Turns arrive at human rate, so the bound is a ceiling and
// paying for a delete on every one of them buys nothing. 64 turns is hours.
if id%64 == 0 {
if err := s.PruneRoutingTraces(ctx, tr.Ts.Add(-RoutingTraceRetention)); err != nil {
return id, err
}
}
return id, nil
}
// PruneRoutingTraces deletes every trace older than before. A corrected turn is
// deleted with the rest: the label was promoted out when the owner wrote it, so
// what is left here is the transcript, and the transcript is what expires.
func (s *Store) PruneRoutingTraces(ctx context.Context, before time.Time) error {
if _, err := s.db.ExecContext(ctx,
`DELETE FROM routing_traces WHERE ts < ?`, before.UnixMilli()); err != nil {
return fmt.Errorf("prune routing traces: %w", err)
}
return nil
}
// RecentRoutingTraces returns the newest n turns, newest first.
func (s *Store) RecentRoutingTraces(ctx context.Context, n int) ([]RoutingTrace, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT id, ts, utterance, source, winner, intent, claimed_before_head,
encoder_id, outcome, correction, claims
FROM routing_traces
ORDER BY id DESC
LIMIT ?`, n)
if err != nil {
return nil, fmt.Errorf("recent routing traces: %w", err)
}
defer rows.Close()
var out []RoutingTrace
for rows.Next() {
var tr RoutingTrace
var tsMilli int64
var claims string
if err := rows.Scan(&tr.ID, &tsMilli, &tr.Utterance, &tr.Source, &tr.Winner,
&tr.Intent, &tr.ClaimedBeforeHead, &tr.EncoderID, &tr.Outcome,
&tr.Correction, &claims); err != nil {
return nil, err
}
tr.Ts = time.UnixMilli(tsMilli).UTC()
tr.Claims = json.RawMessage(claims)
out = append(out, tr)
}
return out, rows.Err()
}
+75
View File
@@ -0,0 +1,75 @@
package store
import (
"context"
"testing"
"time"
)
func TestRoutingTraceRoundTrip(t *testing.T) {
s := newTestStore(t)
ctx := context.Background()
now := time.Date(2026, 8, 6, 12, 0, 0, 0, time.UTC)
in := RoutingTrace{
Ts: now,
Utterance: "напомни в 11:00 позвонить маме",
Source: "tap:voice",
Winner: "stage0:reminder-grammar",
Intent: "reminder",
ClaimedBeforeHead: true,
EncoderID: "e5-small",
Outcome: "reminder",
Claims: []byte(`[{"stage":"stage0","claimant":"reminder-grammar","outcome":"won"}]`),
}
if _, err := s.WriteRoutingTrace(ctx, in); err != nil {
t.Fatal(err)
}
got, err := s.RecentRoutingTraces(ctx, 10)
if err != nil {
t.Fatal(err)
}
if len(got) != 1 {
t.Fatalf("got %d traces, want 1", len(got))
}
// The utterance is stored in clear on purpose: a vector is not redaction.
if got[0].Utterance != in.Utterance {
t.Errorf("utterance %q, want %q", got[0].Utterance, in.Utterance)
}
if !got[0].ClaimedBeforeHead {
t.Error("claimed_before_head lost, and V-632 needs exactly that share")
}
if got[0].EncoderID != in.EncoderID {
t.Errorf("encoder_id %q, want %q", got[0].EncoderID, in.EncoderID)
}
if string(got[0].Claims) != string(in.Claims) {
t.Errorf("claims %s, want %s", got[0].Claims, in.Claims)
}
if got[0].Correction != "" {
t.Errorf("correction %q on an uncorrected turn", got[0].Correction)
}
}
// The bound is an age, not a row count: the useful question is what she did this
// week, and a busy Tuesday must not push last Friday out.
func TestPruneRoutingTracesByAge(t *testing.T) {
s := newTestStore(t)
ctx := context.Background()
now := time.Date(2026, 8, 6, 12, 0, 0, 0, time.UTC)
for _, age := range []time.Duration{0, 13 * 24 * time.Hour, 15 * 24 * time.Hour} {
if _, err := s.WriteRoutingTrace(ctx, RoutingTrace{Ts: now.Add(-age), Utterance: "привет"}); err != nil {
t.Fatal(err)
}
}
if err := s.PruneRoutingTraces(ctx, now.Add(-RoutingTraceRetention)); err != nil {
t.Fatal(err)
}
got, err := s.RecentRoutingTraces(ctx, 10)
if err != nil {
t.Fatal(err)
}
if len(got) != 2 {
t.Fatalf("kept %d traces, want the two inside 14 days", len(got))
}
}
+84 -3
View File
@@ -39,6 +39,7 @@ import (
"os/exec"
"strings"
"time"
"unicode"
"github.com/kami/maven/internal/ipc"
"github.com/kami/maven/internal/mcp"
@@ -73,8 +74,27 @@ var (
// confirm turn that would help: asking again would imply the second answer
// changes the outcome.
ErrNeedsAuthedSurface = errors.New("tool is irreversible and voice may not authorise it")
// ErrUnknownTarget — the act matched a tool and the target it carries cannot
// be one. A process row's args become argv for a real program, and a unit,
// container or host is named in ASCII on this box, so a Cyrillic tail is a
// word from the sentence rather than a target. Held apart from every failure
// above because the command never ran: forwarding it would spend a confirm
// turn on an act that cannot succeed, and then report the program's own
// confusion as if she had tried something sensible (V-634).
ErrUnknownTarget = errors.New("the act names a target the system cannot have")
)
// UnknownTargetError carries the word the executor could not place, because the
// reply names it: "«роутер» — не знаю такой цели" is actionable and "не
// получилось" sends him to the log. errors.Is(err, ErrUnknownTarget) holds.
type UnknownTargetError struct{ Target string }
func (e *UnknownTargetError) Error() string {
return fmt.Sprintf("%s: %q", ErrUnknownTarget, e.Target)
}
func (e *UnknownTargetError) Unwrap() error { return ErrUnknownTarget }
// MCPCaller is the seam for an act that is an MCP tool call rather than a
// process (Vikunja #251). internal/mcp.Manager satisfies it via CallPositional.
// nil ⇒ MCP is not configured, and an MCP row refuses to run rather than
@@ -144,6 +164,16 @@ func (e *Executor) Exec(ctx context.Context, name string, args []string, confirm
if t.Status != "enabled" {
return "", ErrNotEnabled
}
// A process row's args become argv, so the target has to be able to exist.
// Checked before the confirm gate below, because asking "выполнить X?" about
// an act that cannot run spends a turn on nothing (V-634). The other two
// dispatches are exempt: an MCP tool may take Russian text as an argument,
// since a task title is not a target, and a house row drops the spoken args.
if !isMCPRow(t.Cmd) && !isHouseRow(t.Cmd) {
if bad, ok := firstUnknownTarget(args); !ok {
return "", &UnknownTargetError{Target: bad}
}
}
// The tier decides, not the column (Vikunja #449). RiskOf reads the row and
// answers the three questions the boolean never did: which acts are
// destructive, whether a confirm sticks (it never does), and what an
@@ -222,11 +252,23 @@ func runProcess(ctx context.Context, argv []string) (string, error) {
// router's default prefix logic over the current names. The interface's Match
// has no ctx, so it queries with a background context — an in-process sqlite
// read on the daemon.
type Matcher struct{ api API }
// Aliases are spoken phrases per tool name, wired from the deployment config so
// a Russian utterance can reach an English tool name. They are not stored on the
// tool row: an ad-hoc tool enabled through /tools has no aliases and needs none.
type Matcher struct {
api API
aliases map[string][]string
}
// NewMatcher builds a store-backed act matcher.
func NewMatcher(api API) *Matcher { return &Matcher{api: api} }
// WithAliases returns the matcher carrying spoken aliases per tool name.
func (m *Matcher) WithAliases(a map[string][]string) *Matcher {
m.aliases = a
return m
}
func (m *Matcher) names() []string {
ts, err := m.api.ListTools(context.Background(), "enabled")
if err != nil {
@@ -243,7 +285,46 @@ func (m *Matcher) names() []string {
// Allowlist — the enabled verbs (for stage-0 grammar wiring / introspection).
func (m *Matcher) Allowlist() []string { return m.names() }
// Match — longest-verb-first prefix match over the live enabled allowlist.
// Match — longest-phrase-first prefix match over the live enabled allowlist and
// its configured aliases.
func (m *Matcher) Match(utterance string) (string, []string, bool) {
return router.DefaultActMatcher{Fns: m.names()}.Match(utterance)
return router.DefaultActMatcher{Fns: m.names(), Aliases: m.aliases}.Match(utterance)
}
// firstUnknownTarget reports whether every arg could name something on this box,
// and returns the first that could not.
//
// The check is the script, not a word list: this is not a fourth Russian
// mechanism (CLAUDE.md § "Russian patterns"). A systemd unit, a container, a
// host and a path are written in ASCII, so a non-ASCII rune in an argv element
// means the alias match swallowed the verb and handed on the next word of the
// sentence. "перезагрузи роутер" is the case: restart is a real tool and
// "роутер" is a real word, and `systemctl restart роутер` is neither.
//
// Every process row this box enables takes a system identifier (systemctl,
// docker, journalctl, df). A process row that legitimately wanted Russian text
// would want a different dispatch, not a hole in this check.
//
// It deliberately does not try to guess the right target. Identity is Nexus's
// (CLAUDE.md § "The ecosystem"), and a target Nexus resolves reaches Hexis
// through handleHexisAct before this executor is asked.
func firstUnknownTarget(args []string) (string, bool) {
for _, a := range args {
for _, r := range a {
if r > unicode.MaxASCII {
return a, false
}
}
}
return "", true
}
func isMCPRow(cmd []string) bool {
_, _, ok := mcp.ParseCmd(cmd)
return ok
}
func isHouseRow(cmd []string) bool {
_, _, ok := smarthome.ParseCmd(cmd)
return ok
}
+53
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"reflect"
"strings"
"testing"
"time"
@@ -320,3 +321,55 @@ func TestExecEmptyCmdRefuses(t *testing.T) {
t.Fatal("a row with no cmd ran a program named by the utterance")
}
}
// V-634. The alias match resolves the verb and hands on the next word of the
// sentence, so "перезагрузи роутер" became `systemctl restart роутер`: a real
// tool, a real word, and a target that cannot exist on this box.
func TestExecRefusesATargetTheSystemCannotHave(t *testing.T) {
api := fakeAPI{tools: map[string]ipc.Tool{
"restart": {Name: "restart", Cmd: []string{"systemctl", "restart"}, Status: "enabled"},
"drop": {Name: "drop", Cmd: []string{"dropdb"}, Destructive: true, Status: "enabled"},
}}
ran := false
e := NewExecutor(api, 0)
e.run = func(context.Context, []string) (string, error) { ran = true; return "ok", nil }
_, err := e.Exec(context.Background(), "restart", []string{"роутер"}, false)
if !errors.Is(err, ErrUnknownTarget) {
t.Fatalf("err = %v, want ErrUnknownTarget", err)
}
if ran {
t.Fatal("the program was called with a target that cannot exist")
}
// The word is in the error, because a reply naming no word sends him to the log.
if !strings.Contains(err.Error(), "роутер") {
t.Errorf("err %v does not name the word she could not place", err)
}
// Ahead of the confirm gate: asking about an act that cannot run spends a
// turn on nothing.
if _, err := e.Exec(context.Background(), "drop", []string{"база"}, false); !errors.Is(err, ErrUnknownTarget) {
t.Errorf("destructive row: err = %v, want ErrUnknownTarget before ErrNeedsConfirm", err)
}
// An ASCII target still runs, unchanged.
if _, err := e.Exec(context.Background(), "restart", []string{"nginx"}, false); err != nil {
t.Errorf("restart nginx: %v", err)
}
}
// An MCP argument is not a target. A task title is Russian and always was.
func TestExecMCPRowKeepsRussianArgs(t *testing.T) {
api := fakeAPI{tools: map[string]ipc.Tool{
"vikunja_create": {
Name: "vikunja_create", Status: "enabled",
Cmd: []string{"mcp", "vikunja", "create_task"},
},
}}
m := &fakeMCP{out: "создала"}
e := NewExecutor(api, time.Second).WithMCP(m)
if _, err := e.Exec(context.Background(), "vikunja_create", []string{"купить хлеб"}, false); err != nil {
t.Fatalf("exec: %v", err)
}
if len(m.args) != 1 || m.args[0] != "купить хлеб" {
t.Fatalf("args = %v, want the Russian title forwarded", m.args)
}
}
-8
View File
@@ -8,12 +8,9 @@
как прошёл день
расскажи про себя
ты мне нравишься
почему небо голубое
о чём поговорим
у тебя есть чувства
что такое любовь
расскажи историю
как работает интернет
шутка
анекдот
пошути
@@ -24,8 +21,6 @@
что нового
думаешь о чём-то
расскажи про космос
почему трава зелёная
откуда берётся дождь
что было интересного сегодня
как тебя зовут
сколько тебе лет
@@ -37,7 +32,4 @@ i'm bored
what's up
tell me a joke
do you have feelings
what is love
tell me about yourself
why is the sky blue
how does the internet work
+27
View File
@@ -62,3 +62,30 @@ what did I note about the garden
будет дождь
погода на сегодня
weather in london
сколько времени осталось до вечера
какая температура воздуха
есть ли кто дома
кто дома сейчас
все ли дома
сколько памяти занято
всё ли работает
сколько сервер работает без перезагрузки
когда сервер запускался
сколько аптайм
какой статус сервисов
все ли сервисы работают
что с интернетом
когда последний раз перезагружался
сколько трафика сегодня
какая скорость интернета
сколько процессов запущено
как загрузка системы
какая температура процессора
почему небо голубое
что такое любовь
как работает интернет
почему трава зелёная
откуда берётся дождь
what is love
why is the sky blue
how does the internet work
+1 -28
View File
@@ -5,36 +5,9 @@
который час в Москве
сколько сейчас времени
который час у нас
сколько времени осталось до вечера
какой сегодня день недели
какая температура воздуха
сколько человек дома
кто сейчас дома
есть ли кто дома
кто дома сейчас
все ли дома
сколько памяти занято
какая загрузка процессора
сколько свободного места на диске
какой ip адрес у сервера
как дела у сервера
всё ли работает
сколько сервер работает без перезагрузки
когда сервер запускался
какая версия софта
сколько аптайм
какой статус сервисов
все ли сервисы работают
что с интернетом
интернет работает
когда последний раз перезагружался
сколько трафика сегодня
какая скорость интернета
загрузка сети
сколько процессов запущено
как загрузка системы
сколько оперативной памяти свободно
какая температура процессора
тихий режим
тихо
не шуми
@@ -48,4 +21,4 @@
quiet mode on
quiet mode off
quiet on
quiet off
quiet off