Compare commits

...

107 Commits

Author SHA1 Message Date
claude 70b32af8a7 Merge: a reminder said whole is not asked about (#214)
V-572. "напомни в 11:00 позвонить маме" answered "Когда?". ReminderGrammar
builds its slots by hand and the extractor never ran over a stage 0 decision,
so HasTime was false however clearly the hour was spoken, and missingFor read
the silence as absence.

fillMatchedSlots in internal/router/router.go now runs the stage 2 extractor
over every stage 0 decision and fills only what the grammar left empty. A
matched value always wins. The LLM path had the same hole and the same fix, so
both share one function rather than ten grammars re-implementing extraction.

Slots.Text is deliberately not filled. A grammar that left Text empty meant
it: agendaQueryBuild hands the query chain the sentence itself. Filling it
would also make SlotText unaskable, which is the bug V-383 fixed on the LLM
side.

Enabled for all ten grammars and inert for nine. Extract fills Time for a
reminder, Fn for an act and Key for a fact, and nothing for query, system,
note or chat. Benchmarked at 20000x with the real date parser: every stage 0
shape stays inside the noise, and the reminder rule gains, because
actionReminder was already running that same parse one layer down.

TestONNXBaseline 64/91 before and after, no case regressed. The fixture's own
"slots deferred to daemon" line went 6 to 0. On the box: "хорошо, напомню
сегодня в 11:00."

Conflict in internal/router/router.go resolved by hand: V-564's grammar-outcome
note and V-572's slot fill both belong, fill first. Full -race suite green.

--no-verify: the pre-commit hook refuses master, and the owner asked for
straight-to-master merges for this unattended run.
2026-08-06 01:15:04 +04:00
claude fffd0cb5fa Merge: a confirm answer is a whole word, not a substring (#213)
V-567, severe. classifyConfirm was strings.Contains over bare stems, so
"погода" contained "да" and "покажи" contained "ок". resolveConfirm runs
before routing, so asking the weather while a confirm was parked executed the
destructive tool or the bound Hexis capability. Measured on the box before the
fix: "какая погода" ran the parked act.

Second defect found while fixing: an unrecognised utterance also disarmed the
confirm, because claim() cleared the pending slot before the verdict was read.
An utterance that is not an answer is not a cancellation either.

The yes and no words are now two closed sets in internal/lexicon, matched as
whole tokens, phrases longest-first so "не надо" is read before "нет", and
negatives before positives. The whole utterance must be answer words plus
filler, so "давай посмотрим погоду" is unknown and leaves the confirm parked.
"хорошо", "ладно" and "точно" are deliberately absent: they open a sentence
about something else as often as they answer one.

Conflict in lexicon_ru_v1.json resolved by hand: V-560's slot_value_frame and
dialogue_cancel and V-567's confirm_yes and confirm_no all belong. 22 sets,
JSON validated, lexicon, mavend, router and router/eval green with -race.

--no-verify: the pre-commit hook refuses master, and the owner asked for
straight-to-master merges for this unattended run.
2026-08-06 01:12:18 +04:00
claude 77a7c994d7 Merge: route first, then decide the turn role (#212)
Conflict in cmd/mavend/voice.go resolved by hand: V-564's decision record
install and V-560's memoised turn route both belong at the top of runTurn, as
steps 0 and 0b. Full -race suite green over ./internal/... ./cmd/... after the
resolution, 64 packages, no failures.

--no-verify: the pre-commit hook refuses master, and the owner asked for
straight-to-master merges for this unattended run.
2026-08-06 01:08:58 +04:00
claude 63812af920 CLAUDE.md: stage 0 is slot-extracted now (V-572) 2026-08-06 01:08:55 +04:00
claude 869580c913 a reminder said whole no longer asks "Когда?" (V-572)
"напомни в 11:00 позвонить маме" answered "Когда?" about an hour he had
just said. ReminderGrammar builds its slots by hand and the router ran no
extraction over a stage-0 decision, so HasTime was false however plainly
the hour was spoken; missingFor read the silence as absence.

The fix runs the stage-2 extractor over every stage-0 decision, filling
only the slots the grammar left empty. A matched value always wins: the
rule read a literal pattern, the extractor guesses. This is the same hole
the LLM path already had, so fillSlots and the new stage-0 call share one
fillMatchedSlots.

Enabled for all ten grammars rather than a chosen few, because for every
intent but reminder it is inert. Extract fills Time for a reminder, Fn for
an act and Key for a fact, and nothing at all for query, system, note or
chat — which is what the clock, agenda, feed, list, task, Praxis-adjacent
and narrative rules emit. The two act rules, wakeword-act and the Praxis
ones, already carry an Fn or they do not match, so the matcher has nothing
left to fill. Measured rather than asserted: benchmarked at 20000x, a
stage-0 query is 3.7µs against 3.9µs before and a clock or act rule is
0.7µs either way, both inside the noise. The reminder rule is the one that
gains, and its date parse is not new spend — actionReminder was already
running exactly that parse one layer down, and now skips it.

Slots.Text is deliberately not filled. Extract sets it to the raw
utterance, and a grammar that left it empty meant it: agendaQueryBuild
hands the query chain the sentence itself, and narrativeQueryBuild's Text
is the topic.

Fixture unchanged at 64/91 (70.3%) on TestONNXBaseline, no case regressed,
no new false clarify. What moved is the line the fixture calls "slots
deferred to daemon": 6 to 0.

Verified on homesrv: "напомни в 11:00 позвонить маме" now answers
"хорошо, напомню сегодня в 11:00."
2026-08-06 01:08:38 +04:00
claude 31deb7d565 confirm answers match whole words from the lexicon (V-567)
classifyConfirm was a substring test over bare stems, so "погода",
"дальше", "надо" and "давление" all read as "да", and "покажи" and
"около" read as "ок". resolveConfirm runs before routing, so a question
about the weather executed a parked destructive act. Reproduced on the box:
with "restart nonexistent-xyz" parked, "какая погода" answered "не
получилось выполнить команду".

The yes and no answers are now two closed sets in internal/lexicon, matched
as whole tokens longest-first, and the WHOLE utterance must be answer words
and filler — a leading "давай" does not make "давай посмотрим погоду" an
answer. Anything else is confirmUnknown, which now leaves the confirm parked
instead of disarming it: an utterance that is not an answer is not a
cancellation either.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 01:05:50 +04:00
claude 1338ec6e2a Merge: an infrastructure error does not claim the turn (#211)
V-568. queryEmbed claimed the turn on an EmbedQuery error and answered
QueryFailAnswer from position 12 of querySources, above memory, notes, the
personal boundary, search, Kiwix and general knowledge. So one failing embed
call made every question below it answer "не смогла ответить", including the
ones search and Kiwix would have answered without the embedder at all.

The notes source had the same bug one position lower, on a QueryNotes error.
Both now log once and pass. Both also gained an empty-vector guard, because
scores off a nil vector are not a "there is nothing" answer.

The distinction the audit used: a source that looked and found nothing may
claim, a source that could not look must pass. day-plan, habits, feeds,
calendar, weather, home, network and web keep claiming, because each already
matched a question about his own data and nothing below can answer it.
Answering a personal question with a paragraph about the world is V-474 and
V-479.
2026-08-06 00:58:46 +04:00
claude 7843728174 Merge the common unit for claims (#210)
V-565. internal/claim holds Claim{Claimant, Intent, Filled, Consumed,
Unexplained, Band, Veto} and imports nothing from Maven, so the dialogue to
router edge stays impossible. internal/router/claim.go builds one from a
Decision. Additive: nothing in Route calls it and Decision.Confidence is
untouched.

Measured first, on the 91-case fixture. Stage 0 emits 1.0 always and is right
20/20. The classifier cosine spans 0.859 to 0.942 and is right 62% of the
time, with 62% correct below its median and 62% above, so the number carries
no signal about correctness. The top1 to top2 margin is worse: p50 0.009, 68
of 71 cases under 0.02. A calibrated float is not cheaply available from the
classifier, which is what the task's ledger asked to be checked.

So four ordinal bands, highest first: anchored, structural, nearest, vetoed,
with unknown at the bottom so a builder that forgot cannot outrank a measured
claim. Anchored against nearest is 100% against 62% on the same utterances.
Nearest is one band and not a scale because the cosine is flat.

Coverage decides before the band does. That is what fixes Rome: the pending
claimant ate the question while explaining one token of it.

No fixture number moved. TestONNXBaseline is 64/91.
2026-08-06 00:58:34 +04:00
claude a3ad9b5040 an embedder error passes instead of ending the turn (V-568)
queryEmbed claimed the turn on a failed EmbedQuery and returned
QueryFailAnswer. It sits above memory, notes, the personal boundary,
search, Kiwix, the named page and general knowledge, so one ONNX error
answered every question below it with "не получилось найти ответ",
including the ones search and Kiwix answer without an embedder at all.

It now logs and passes, the shape turnVector already had. The two recall
sources below pass on an empty vector rather than searching on one, and
queryNotes passes on a store error too: a source that could not look is
not a source that looked and found nothing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 00:56:29 +04:00
claude cb0a3a4f20 voice: tests for the turn role and the Rome pair (V-560)
The measured failure of 2026-08-05 end to end through the real cascade, plus
the content test the classifier rests on, the call-off, the cost bound, and the
persona checks over the two new lines.
2026-08-06 00:56:06 +04:00
claude 6abd2768e8 voice: clarify routes first and isOwnRequest is gone (V-560)
resolveClarifyAnswer now decides what the utterance IS before deciding what to
do with it: route, classify the role, then answer, cancel, or step aside. The
side_query and new_request arms drop the parked question and say so — nothing
may die in silence — and V-561 turns the first of those into a suspend.

isOwnRequest is deleted rather than extended. It only ran where the answer
filled nothing, which is why the greedy 'сейчас' in a weather question walked
straight past it and set a reminder for a time nobody asked for.
2026-08-06 00:56:06 +04:00
claude 6e6f73da35 voice: the turn is routed once and the decision is shared (V-560)
turnRoute memoises this turn's routing, so the resolver that reads it to
classify a role and the pipeline that acts on it cannot end up with two
different decisions, and the extra route is paid once. needsRoute is the fast
path: an utterance with no content of its own reaches the same role without the
model.
2026-08-06 00:55:54 +04:00
claude 1a64c30427 voice: the turn role, read off the routed decision (V-560)
The turn role — answer, correction, side_query, new_request, cancel, plus the
not_applicable a resolver may return — decided from what the router made of the
utterance instead of from whatever the extractor found inside it.

The content gate in front of the evidence is what separates a hedged slot value
from a question: 'а что если в 11:00' leaves nothing of its own behind and
'какая сейчас погода в Риме' leaves the weather and Rome. Nothing calls it yet.
2026-08-06 00:55:53 +04:00
claude 5753f90752 lexicon: the frame around a slot value, and the call-off words (V-560)
Two closed sets the turn-role classifier reads. slot_value_frame is what can
stand around a bare value without making the utterance a request — strip it
and the numbers and whatever is left is the utterance's own content.
dialogue_cancel is how he calls off a request she is still assembling, which
is not what task_drop_words means.
2026-08-06 00:55:29 +04:00
claude 4d94277836 build a claim from a Decision, beside the existing path (V-565)
router.ClaimOf maps a Decision onto the common unit. Stage 0 is anchored,
the LLM path is structural, the classifier is nearest, and anything with a
structural hole is vetoed whoever produced it.

The veto recovers the reason gateLLMDecision throws away. Folding three
named holes into llmThinConfidence leaves 0.3, which says something was
wrong and never which thing, so the same conditions are read here as
sentences a trace can print.

Nothing in Route calls this. Decision.Confidence keeps its float and keeps
working, because r.threshold and gateLLMDecision read it and the classifier
is the failure floor. TestClaimOfLeavesTheDecisionAlone asserts that.
TestONNXBaseline is unchanged at 64/91.
2026-08-06 00:54:55 +04:00
claude 530c3ff395 claim tests: band order, coverage, the Rome case (V-565)
TestCoverageBeatsBand is the V-558 failure as an ordering assertion. The
weather claim explains the whole utterance and the pending reminder explains
one token of it, so coverage settles it before the band is consulted.

TestBandOrder asserts the order rather than trusting the iota, and pins
BandUnknown at the bottom: a builder that forgot to set a band is a bug and
must not outrank a measured claim.
2026-08-06 00:54:43 +04:00
claude e031f8f5f5 a claim carries evidence, not a verdict (V-565)
internal/claim holds the common unit: who wants the turn, the intent, the
slots it would fill, the tokens it explains, the tokens it declines, and why
it should not win. Specificity reads Consumed against Unexplained and
negative constraint reads Veto, so neither needs a float.

Four ordinal bands where a number is unavoidable, argued from measurement in
docs/plans/19-dialogue-arbitration.md. Anchored, structural, nearest,
vetoed. Nearest is one band and not a scale because the classifier's cosine
measured flat against correctness.

MoreSpecificThan puts coverage first and the band second. That is the fix
for the failure V-558 opened with: a pending reminder ate the Rome weather
question while explaining none of it.

The package imports nothing from the rest of Maven. internal/dialogue must
not import internal/router, so Intent is a plain string.
2026-08-06 00:54:34 +04:00
claude 6c24e19b83 Merge the decision trace (#209)
V-564. One decision.Record per turn: the utterance, the winner, and a Claim
per claimant carrying its stage, name, the intent it would have made the turn,
the score it reported, the outcome and the reason. HasScore is separate from
the score so a real 0.0 is not read as no score. Outcomes are won, declined,
lost_on_order, lost_on_score, thinned, merged, never_asked.

Every stage declares its roster up front, so Finish names everyone who never
reported. NEVER ASKED is explicit rather than an absence, which is the fact
the hardcoded ordering hides.

Covered: the seven pre-route resolvers, eleven stage 0 grammar sets, the LLM
router and the classifier with which arm of gateLLMDecision thinned a route,
the classifier runners-up, the follow-up merge, 27 query sources, and a
terminal action-handler or clarify-ask claim.

On by default, no flag. It rides the context like querysource.go and is
installed in runTurn, so mic, telegram and web leave the same trail. Storage
is a 25-turn in-memory ring: no write on the answer path, no migration, and
none of his words outlive the diagnosis. Readable on /trace.

TestRecordingDoesNotChangeTheReply answers the same utterances with and
without the ring.
2026-08-06 00:54:18 +04:00
claude 934a28d67c measure what each claimant on an utterance reports (V-565)
Two reporting tests over the 91-case RU fixture, no ratchet: a ratchet here
would freeze a number nobody has decided to hold.

TestStage0Contention runs the 21 grammars one at a time instead of stopping
at the first match. One case of 91 draws two, ru-query-019, where
calendar-query beats agenda-query by list position alone.

TestONNXClaimConfidenceDistribution buckets the reported confidence by the
layer that produced it. Stage 0 is 20/20 at a hardcoded 1.0. The classifier
scores 62% below its median and 62% above, across a cosine range of 0.859
to 0.942, with a top-two margin of p50 0.009. The float is not a confidence.

newBaselineClassifier and baselineGrammars split out of newBaselineRouter so
the measurement runs the same rules the daemon runs. TestONNXBaseline is
unchanged at 64/91.
2026-08-06 00:54:13 +04:00
claude cf28f6fdf0 qa reads /trace for the query chain again (V-564) 2026-08-06 00:52:59 +04:00
claude eec3d9bed2 /trace grows a turn-decisions table under the rule trace (V-564)
Both tables answer the same question, who won and who lost, one about nudges
and the other about utterances, so they share a page rather than splitting the
nav. A turn is one collapsible row; never_asked is coloured like a block,
because it usually is one. A read failure is logged and the rule trace above it
still renders: a daemon too old to know the method is the ordinary case during
a rolling deploy.
2026-08-06 00:52:58 +04:00
claude a5b245dbf5 the ring reads out over ipc as turn decisions (V-564)
Same shape as TickTrace and RecentEvents: a bounded daemon ring, so the store
adapter refuses rather than pretending a table exists. No voice wiring means an
empty list and not an error, because a box with no voice path has had no turns
to arbitrate.
2026-08-06 00:52:48 +04:00
claude 3e6a427e85 a turn names its winner, its losers, and who never looked (V-564) 2026-08-06 00:52:48 +04:00
claude 5ac7347c38 the resolver ladder and the query chain report their claims (V-564)
The two claimant sets that live in the daemon are where the arbitration is
least visible: both are a hardcoded order of functions that each answer 'is
this mine?' alone. The ladder declares its roster up front, so a rung that
never ran is named rather than omitted, and the query chain does the same for
the sources below the one that claimed.

Recording is installed in runTurn and not in the IPC entry point, so the mic,
telegram and the web leave the same trail. A record only the web produced would
be missing exactly the turns that are hardest to reproduce.
2026-08-06 00:52:39 +04:00
claude 5417692566 the cascade says which grammar declined and which never ran (V-564)
Stage 0 records every grammar it reached, keeping a pattern that never matched
apart from a Build that refused the content, and names the ones after the
winner as never asked. The routing arm records the classifier's runners-up and
which arm of gateLLMDecision cut the confidence, because thinned alone is not
enough to act on.
2026-08-06 00:52:28 +04:00
claude b56e0e6248 the record's own tests: never-asked, bounds, fan-out (V-564) 2026-08-06 00:52:28 +04:00
claude 0558dfed0f a turn record holds every claim, not only the winner (V-564)
Arbitration between the claimants on the utterance stream is order, hardcoded
in three places, and a log that names the winner cannot explain a loss. The new
package holds one record per turn: who claimed, what it would have made the
turn, the score it reported, and why the rest did not get it. Being explicit
that a claimant was never asked is the point: that silence is what the
hardcoded ordering hides.

The record rides the context, the seam querysource.go already uses, so no claim
site can change a route and a context with no record costs nothing. The ring is
memory and bounded: a turn record is read minutes later or never, and his words
do not belong in a table that outlives the diagnosis.
2026-08-06 00:52:19 +04:00
claude 13a5ef0100 Merge the dialogue contract tests (#208)
V-563. cmd/mavend/dialogue_contract_test.go holds twelve whole multi-turn
traces. Each turn asserts the reply, what is parked afterwards including the
attempt count, and the end state: reminders with payload and fire time, fact
keys, note count, task texts.

Six traces pass today. Six carry the correct expectation and skip, naming the
task that makes them green: the owner's transcript and its parseable twin
(V-561), cancel and a correction under a parked question (V-560), a whole
reminder still being asked about and a short correction (V-562).
MAVEN_DIALOGUE_NO_SKIP=1 runs the skipped rows, so a fixer sees their row turn
green and a stale skip is caught.

Offline: hash embedder, no llama-server, no ONNX. Failures print a claimant
trace derived from the daemon's log lines, so a wrong claimant reads
differently from wrong copy.
2026-08-06 00:51:02 +04:00
claude ac78f83406 dialogue contract tests: the six traces that do not (V-563)
Each carries the correct expectation and is skipped with the task that
will unskip it, because a weakened expectation would pin the bug as the
contract. MAVEN_DIALOGUE_NO_SKIP=1 runs them.

V-561: the owner's transcript, and the same shape in words the offline
date parser reads — a side query drops the parked question instead of
suspending it, so Rome is never answered and the reminder is never set.
V-560: a cancel is scored as a failed answer and spends a retry; clarify
pre-empts the repair marker, so no correction can be spoken mid-flow.
V-562: a stage-0 reminder never meets the extractor, so a reminder said
whole with its hour in it is still asked about; and finishClarified goes
straight to applyAction, so a repaired decision that lands short answers
with a parse error instead of asking.
2026-08-06 00:49:47 +04:00
claude 40c59aa275 dialogue contract tests: the traces that hold today (V-563)
Six whole traces through the real cascade with no model: a reminder and a
fact each completed over two turns, an answer that arrives past the TTL,
three unclear answers and the give-up line, a correction of the previous
turn, and an abandoned flow. Each asserts the reply, what is parked after
every turn, and the end state of the store.
2026-08-06 00:47:27 +04:00
claude 84a75274bf dialogue contract tests: the trace vocabulary (V-563)
First slice: the types a multi-turn trace is written in, and the claimant
trace read out of the daemon's own log lines. No rows yet.
2026-08-06 00:46:57 +04:00
claude da2d11dab6 plan: the claim unit and its four bands, measured (V-565)
Measures what each claimant on an utterance reports across the 91-case RU
fixture, then argues an ordinal band set from that distribution.

The classifier's cosine is flat against correctness: 62% correct below its
median and 62% above, over a spread only 0.083 wide, with every case above
the 0.55 gate. Its top-two margin is p50 0.009 and never reaches 0.03. So a
calibrated float is not cheaply available and the ledger's assumption holds.

Stage 0 is 20/20 on the cases it claims and asserts 1.0 for all of them. The
LLM router emits two values, and the lower one is a self-veto with a reason
flattened into a number.
2026-08-06 00:46:50 +04:00
claude de3f2b5fc2 Merge the typed pending action and the dialogue stack (#207)
V-559. internal/dialogue gains PendingAction: capability, slots, missing
slots, TTL and attempt cap, with CapabilityFor as the one intent to
capability map. PendingQuestion derives its action rather than storing a
second copy, so the TTL and attempt rules have one implementation.

The clarify store now holds a bounded stack, MaxStackDepth 2. Behaviour is
identical: Put replaces the top, nothing calls Push, so the daemon runs at
depth one. Push returns what the bound evicted, so nothing dies silently.

Groundwork for V-560 and V-561.
2026-08-06 00:37:56 +04:00
claude e8f4baf407 dialogue: stack tests — push, peek, pop, the bound and expiry (V-559)
Push/peek/pop including that a peek does not consume and that the flow
under a popped entry survives; that a popped entry stays gone; that a push
past MaxStackDepth returns the evicted entry rather than dropping it
silently; that Put keeps the depth at one; that an expired top takes the
stack with it and is reported once by TakeExpired; and that two dialogue
ids do not read each other's stack.
2026-08-06 00:37:01 +04:00
claude 92eb6cf6e1 dialogue: the clarify store holds a bounded stack (V-559)
One parked question per dialogue id meant a side query could only destroy
the flow it interrupted. The store now keeps a stack per id, newest last,
with Push, Peek, Pop, Depth and Delete as drop-all. MaxStackDepth is 2:
one flow plus the thing he interrupted it with, because spoken
conversation does not nest deeper, and because every level she keeps is a
level she has to be able to speak when it dies.

Behaviour is unchanged. Put still replaces the top rather than growing the
stack — a re-ask is another question about the same action — and nothing
calls Push yet, so the daemon runs at depth one exactly as before. Get is
Peek under the name the callers already use. An expired top takes the
stack with it and TakeExpired reports it, so no parked action dies without
a word; Push returns the entry the depth bound forced out for the same
reason.

PendingQuestion.IsExpired and CanAsk now answer through PendingAction, so
the TTL and attempt-cap rules have one copy and the widening cannot drift.
2026-08-06 00:37:01 +04:00
claude 6759ff6003 dialogue: a typed pending action behind the parked question (V-559)
A parked clarify said what she heard (an intent) and not what she was
about to do, so the resolver had to infer the action from conversational
history instead of reading it off an object. PendingAction names the
capability being assembled in the ecosystem's dotted form
(reminder.create, fact.write, act.run), the slots it has, the slots it
still wants, when it was asked, attempts and TTL.

Gaps() computes the missing slots from the slots rather than trusting
Missing, because Missing is what she asked and the slots are what she
got. CapabilityFor maps every dialogue.Intent, so the mapping lives here
and dialogue still does not import router (the cycle rule).

Nothing reads it yet: this is the widening V-560 to V-562 build on.
2026-08-06 00:36:33 +04:00
claude 39284cd851 Merge: a missing slot asks, whatever the confidence (#206) 2026-08-06 00:08:53 +04:00
claude ea0eb167fd a missing slot asks, whatever the confidence (V-557)
The clarify path was gated on dec.Clarify, so a turn the cascade routed
confidently but incompletely skipped it. "напомни позвонить" reached applyAction,
failed on the missing time and parked nothing, and the "в семь вечера" that
followed was routed as a world question and web-searched.

The gate now also fires when missingFor names a required slot. A bare capture
verb gets a stage-0 rule of its own: it was reaching the resident model as chat,
which answered by agreeing to a wording change nobody asked for.
2026-08-06 00:08:43 +04:00
claude b6305f1b6e Merge: an unrecognized act says so and lists nothing (#205) 2026-08-05 23:43:22 +04:00
claude 5bd1406c7a an unrecognized act says so and lists nothing (V-556)
Reciting the allowlist answered a question he did not ask. She says the command
is not one she knows, once, and parks nothing.
2026-08-05 23:43:22 +04:00
claude d988154063 Merge: an act with nothing on the other end says so (#204) 2026-08-05 23:34:33 +04:00
claude 1b76fa8205 an act with nothing on the other end says so (V-556)
askClarify parked "Что сделать?" whatever was on the other end. With an empty
allowlist that question has no answer: she asks, fails, asks again and gives up,
three turns spent on a request she could have declined in the first one.

Empty allowlist now names the gap and parks nothing. A non-empty one still asks,
and names what she can run, capped at six, so the question is answerable.
2026-08-05 23:34:25 +04:00
claude e87088afb8 Merge V-515: workpc is the client machine (#203) 2026-08-05 23:22:57 +04:00
claude 1b8d2c60d3 workpc is the client machine the voice loop was waiting for (V-515)
Three durable stores said no client machine existed. That was written
when the workstation was only a model host. It is where he sits most of
the day and it has the microphone.

The verdict is unchanged and so is the seam. What changes is the size of
the remaining work: deploying two daemons and asking mavend to listen on
TCP, not acquiring hardware. Note that deploying them does not by itself
prove a wake word — mavwaked gates on energy and has no keyword model
(V-487).
2026-08-05 23:22:57 +04:00
claude 12667fd3b8 Merge V-555: the self prompt asks for the present tense (#202) 2026-08-05 23:06:48 +04:00
claude e4fd6140a9 the self prompt asks for the present tense (V-555)
Measured on the box: "глаголы в прошедшем времени с окончанием -ла",
copied from the query prompt where it fixes her gender, was read by the
resident model as an instruction to use the past tense throughout. She
answered "я вела заметки" and "если ты разрешил, я управляла домом",
which makes a live capability sound finished.

The gender rule stays, without the example.
2026-08-05 23:06:48 +04:00
claude 2ba5d0a60e Merge V-555 tail: she does not look herself up (#201) 2026-08-05 23:05:09 +04:00
claude c6b11a6d1d she does not look herself up (V-555)
Two defects found probing the new source on the box.

"кто ты" was answered from one of his notes. The self source sat below
memory and notes, which match by proximity and have no idea the subject
is her. It belongs above all three: a question about her has no answer
in his data either.

And PhraseQuery opens every answer with "вот что я нашла: ", which is
deliberate — it marks the answer as a lookup. Her own description is the
one subject she did not look up, so this is PhraseSelf instead, same
read-only discipline and its own opener. The Stub reads the description
out as it stands, which needs no fallback: it is already her voice.
2026-08-05 23:05:09 +04:00
claude 45622eff3d Merge V-555: a question about herself has an answer (#200) 2026-08-05 23:00:03 +04:00
claude 5815f0b8f3 a question about herself has an answer (V-555)
"что ты умеешь" reached the personal boundary, which claimed it as his
and said "не знаю — не нашла у тебя такой записи" about her own
description. Letting it past would be no better: SearXNG answers about
somebody else's assistant.

A self query source above the boundary, reading one frozen description.
It is NOT a note — notes are his, and a note about her would come back
for "что я записал", would be fed to the digestion worker as something
he said, and would be recalled by proximity for questions that are not
about her.

The description names only what this box does. Everything that depends
on config — the house, the LAN, the feeds, the list, weather, telegram —
is named as depending on what he allowed, and a test pins that split:
inventing a capability here is the same defect as inventing a fact.

topicSelf is scored like every other topic, with a narrow keyword floor
for the no-embedder case. "что ты умеешь" moved off topicOther, where it
had been sitting so an attention question had something to lose to — a
phrasing on two sides never clears the margin. TestONNXTopics 38/38 ->
43/43 on held-out utterances.
2026-08-05 22:59:56 +04:00
claude f68d49d9e2 Merge V-554 tail: a device's history is not a scan request (#199) 2026-08-05 22:45:10 +04:00
claude 36bc603f52 a device's history is not a scan request (V-554)
Found verifying the three fixes on the box: "кто изобрёл телефон" ran a
LAN scan and answered "нашла 3 устройства". The network seed set opens
with "кто в сети сейчас" and names devices throughout, so a "кто ..."
question about any device noun landed there.

Three topicOther seeds, same shape as the V-553 fix. TestONNXTopics
34/34 -> 38/38 on held-out utterances, and a real scan is still a scan.
2026-08-05 22:45:10 +04:00
claude 59214b4fdd Merge V-554: three defects that made an ordinary conversation go wrong (#198) 2026-08-05 22:40:38 +04:00
claude e94c868160 a chat prompt says which turn to answer (V-554)
Prior turns were joined with newlines and nothing else, so the model got
four unlabelled lines and no way to tell which one was the question. It
answered an earlier one: asked "как дела" after a question about the
telephone, she carried on about the telephone. Four turns live for
fifteen minutes, so the line she answered was often minutes old.

One user message still, because the template constraint that forced the
flattening is real. The turns are labelled as his own earlier words and
the current utterance is named as the one to answer. With no history
the message is the utterance alone, unchanged.
2026-08-05 22:40:28 +04:00
claude de4c47459a the personal boundary lets a narrative world question through (V-554)
"расскажи про Байкал" was refused as his by 0.0052. Every world seed
opened with an interrogative, so a world question phrased as an order
landed nearer "я тебе рассказывал об этом?" — the same verb about his
own words. Four narrative seeds on the world side.

TestONNXPersonalBoundary 25/25 -> 29/29 on held-out utterances, and the
control "я рассказывал тебе про байкал?" is still his. TestONNXTopics
unchanged at 34/34.
2026-08-05 22:36:10 +04:00
claude 27bb9119fb clarify steps aside when the next turn is its own request (V-554)
A parked question consumed whatever came next. One act she could not
fulfil ate three turns: "выключи свет в спальне" asked "Что сделать?",
and "кто изобрёл телефон" was scored as an answer to it, then "как
дела" after that. Nothing tested whether the words could be an answer.

The test is two offline token checks that already existed for other
callers: a question shape, or a capture verb. It fires only where the
answer filled nothing, so an answer that closes the gap still lands
whatever shape it has, and the retry budget is untouched — the count
was never the problem.
2026-08-05 22:34:01 +04:00
claude 0ab5dc1482 Merge the personal boundary day-word seeds (#197) 2026-08-05 21:57:32 +04:00
claude 35ae1f41da the personal boundary reads the day-word frame too (V-553)
The topic seeds let "какой сегодня праздник" and "что интересного
произошло сегодня в мире" past the weather source, and the personal
boundary refused them one source further down: "не знаю — не нашла у
тебя такой записи" about a public holiday.

Same defect, same mechanism, one layer lower. "что у меня сегодня" is a
personal seed and worldSeeds had nothing in that frame. Two seeds fix it.

TestONNXPersonalBoundary 22/22 -> 25/25, nothing regressed.
2026-08-05 21:57:32 +04:00
claude a9db82b04c Merge the day-word topic seeds (#196) 2026-08-05 21:54:38 +04:00
claude 278eeeffdf the world question that names a day is not weather and not his (V-553)
Two recognisers claimed world questions naming a day, both by the same
mechanism and neither by its keyword floor.

topics: weather was the only topic whose seeds carry a day word, four of
eight. So every "какой сегодня X" landed nearest it. "какой сегодня
курс доллара" cleared the margin by 0.0220 and "какой сегодня
праздник" by 0.0398, against 0.0883 for a real weather question, and the
gate asked "для какого города?" about the dollar.

The margin was not the knob: 0.0398 is not a coin flip, and raising the
bar far enough would take real weather with it. topicOther was missing
the negative class. Six seeds, four naming a day and two carrying the
"какой сегодня X" frame itself — a frame both topics use has to sit on
both sides, or the side that owns it wins every noun it has never seen.

personal boundary: the same shape one layer down. "что у меня сегодня"
and "когда моя встреча" put "when does a thing happen" on the
personal side and no world seed answered it, so "во сколько закат
сегодня" was refused as his. Three world seeds, each carrying сегодня,
which is the half of the frame that does the pulling — without it they
caught nothing.

Measured, both opt-in against the ONNX embedder homesrv runs:
  TestONNXTopics           27/27 -> 34/34 (7 new cases, none regressed)
  TestONNXPersonalBoundary 19/19 -> 22/22 (3 new cases, none regressed)

The control matters as much as the fix: "во сколько у меня встреча" is
the same frame about something that IS his, and it holds at +0.0842,
unchanged from before the seeds moved.
2026-08-05 21:54:28 +04:00
claude b23596f54f Merge the calendar narrowing (#195) 2026-08-05 21:41:00 +04:00
claude 6e3bb3be97 each agenda grammar is tested against its own example (V-552)
Replaces a test whose name promised more than its body checked: it
looped the grammars asserting Pattern != nil, which regexp.MustCompile
already guarantees at init. Asserting the grammars pass IsAgendaQuestion
would be true by construction, since the first arm is that same loop.

A hand-written example per grammar name catches what neither does: a
grammar edited until it no longer matches the case its comment gives,
and a new grammar nobody wrote an example for.
2026-08-05 21:40:49 +04:00
claude aa7ef33bbf the calendar answers his day, not any day (V-552)
queryCalendar matched on a day word and stepped aside only on weather
wording. Every world question naming a day was claimed by it and answered
with an empty schedule: "какой сегодня курс доллара" replied "на
05.08.2026 ничего нет", which reads as an answer about a subject she
never looked at. All four probe utterances have an answer in search, and
search sits below the calendar.

V-474 fixed one instance of the class. Sunset, holidays, exchange rates
and world news are the same class and weather wording does not cover them.

router.IsAgendaQuestion is the narrowing. Its first arm reuses
AgendaQueryGrammars, so the rule that routes a question to the query
chain and the rule that lets the calendar answer it cannot drift. The
second reads a scheduled-thing noun, wider than the grammars because
"какие встречи завтра" carries no possessive. The third claims a
question that names no subject of its own.

A continuation is exempt: "а завтра?" cannot name an agenda, and this
is the only date-aware source there is.
2026-08-05 21:40:15 +04:00
claude f2851b3729 Merge the routing re-measurement (#194)
V-320 items 2 and 3. Cascade + resident model is 75.8% full / 80.2%
intent-only at p50 1.19s on the 91-case fixture.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SoL7EBdYC5Mhz3DJd49GJy
2026-08-05 21:31:31 +04:00
claude d49067f7dd eval: score and time the resident model as router (V-320)
Item 2 was blocked because the resident llama-server binds --port 0 inside the
container, so no host process can reach it. Cleared by taking the first of the
three ways out the task listed: a second llama-server on the same gguf, on a
fixed host port.

Cascade + resident model scores 75.8% full and 80.2% intent-only at p50 1.19s
and p95 1.65s, on the fixture as it now stands at 91 cases. That is a new
baseline rather than a movement: 14 cases were added since the 77-case number
in CLAUDE.md.

The model alone scores 37.4% full against 61.5% intent-only. The gap is slots,
not routing. Every reminder case leaves the time to the daemon, which is what
the contract asks of it, and the cascade fills them.

Item 3: the ~6s figure recorded in the task was one sample through the whole
of POST /api/chat, not the router, and is not comparable.

Item 4 is still not run. Killing the resident llama-server needs a permission
this session does not have, and it now has a second half anyway, since with the
workstation up only killing both proves the classifier answers.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SoL7EBdYC5Mhz3DJd49GJy
2026-08-05 21:31:31 +04:00
claude b528a8f5c9 Merge the bare-hour fix (#193)
V-551. "завтра в семь" booked the reminder for the current clock. dateparser
needs the colon, so the script gives it one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SoL7EBdYC5Mhz3DJd49GJy
2026-08-05 21:17:30 +04:00
claude 44320ee496 dates: a bare hour after a day word is an hour, not the current clock (V-551)
At 21:12 "напомни мне завтра в семь позвонить маме" confirmed a reminder for
21:12 tomorrow. The hour was dropped and the wall clock carried onto the named
day. She did not ask; she named a time nobody gave her, on a path that fires.
A bare "напомни в семь" declines correctly, so adding "завтра" turned a decline
into an invented answer.

dateparser only reads a bare hour when it carries a qualifier or a colon.
"завтра в 7" keeps the current clock and "завтра в 7 часов" is read as seven
hours from now, which moves the day as well. English "at 7" fails identically,
so this is not a Russian defect and both prepositions are rewritten.

The script now gives it the colon: "в 7", "в 7 часов" and "at 7" become
"в 07:00" beside the existing утра/вечера rewrites. A duration is untouched,
because "через 2 часа" has no preposition to match, and so are "в 7:30",
"в 30 минут" and "в 2026 году".

The stub parser has always read the token after the day word, so the floor was
right and the production parser was not. No test on the stub could have caught
this. The four new cases are in TestPythonDateParser, which runs where
dateparser is installed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SoL7EBdYC5Mhz3DJd49GJy
2026-08-05 21:17:21 +04:00
claude 337a777d2e Merge the reach measurement with the resident model (#192)
V-517. The model alone reaches Praxis 0/12, so the V-516 stage-0 grammars are
the only path there. Cascade+llm is 28/30.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SoL7EBdYC5Mhz3DJd49GJy
2026-08-05 21:03:23 +04:00
claude 576dfd8b4c eval: the resident model never reaches Praxis either (V-517)
V-405 measured reach with the classifier only, and the LLM router is the
deployed default, so 16/30 was the floor rather than the shipped behaviour.
TestReachWithLLMRouter scores the same 30 cases with the model, gated on
MAVEN_LLM_URL like TestLLMRouterBaseline.

The open question was whether the model writes a literal Praxis capability
into the fn slot and reaches a service the classifier structurally cannot. It
does not. Praxis is 0/12 with the model alone, exactly what the classifier
alone scores, and all twelve fail the same way: local, empty fn. Nothing in the
router prompt names a Praxis capability, so there is no string for it to write.

So V-516's stage-0 grammars are the only path to Praxis, not a determinism
argument. Through the cascade the model scores 28/30 with praxis 11/12, one
point above the classifier baseline. Hexis is 10/10 either way.

Overreach is 1 in both configurations, under the 4 the harness asserts.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SoL7EBdYC5Mhz3DJd49GJy
2026-08-05 21:03:05 +04:00
claude ed9db8dc44 Merge the history side fix (#191)
V-456. A question about what she recorded is answered as her turn, not his.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SoL7EBdYC5Mhz3DJd49GJy
2026-08-05 20:54:20 +04:00
claude a8710c859b history: answer the side of the question that was asked (V-456)
"что ты записала сегодня?" was recognised as a history question and then
answered with "ты говорил: …". The rows are right — a tapped fact is one act
seen from two sides — but the sentence hands the question back instead of
answering it.

historyAsks returns which side was asked and queryHistory phrases from it,
including the nothing-found reply. His side is tested first, because "отмечать"
is on both verb lists and "что я отметил" is not a question about her.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SoL7EBdYC5Mhz3DJd49GJy
2026-08-05 20:54:11 +04:00
claude 1bacbb7952 Merge the wipe (#190)
V-494 part 1. Store.Wipe drops every table and rebuilds from the migrations;
mavend -wipe is a dry run and -confirm-wipe deletes. QA isolation and
onboarding are the remaining two thirds.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SoL7EBdYC5Mhz3DJd49GJy
2026-08-05 20:51:55 +04:00
claude 82d9a3324e wipe: one command empties the box and leaves it standing (V-494)
There was no documented way to repair a poisoned box. Two invented facts
written during QA disabled world answering for every later turn (V-470), and
revert voids the SQL row while leaving the vector behind (V-493). This is the
operation that undoes both.

Store.Wipe drops every table sqlite_master reports and rebuilds from schema.sql
plus the migrations, rather than deleting from a hand-written list. A list has
to be edited whenever a table is added, and the once it is not, the wipe leaves
personal data behind while reporting success. It vacuums afterwards, because
free pages still hold readable text.

mavend -wipe prints every table and its row count and exits. That alone is a
dry run and answers what a QA session actually asks: what is on this box. It
deletes only with -confirm-wipe. Two flags, because the destructive reading of
one flag is the reading a mistyped command gets.

Nothing outside the database moves. Config, models, passkeys.json and the
encryption key are files.

QA isolation and onboarding are the other two thirds of V-494 and are not here.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SoL7EBdYC5Mhz3DJd49GJy
2026-08-05 20:51:46 +04:00
claude 03d48ab789 Merge the intake form on /tasks (#189)
V-511. Confirming a candidate asks for a definition of done, resolves a
blocked-on name against nexus, and books a reminder when a date is set.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SoL7EBdYC5Mhz3DJd49GJy
2026-08-05 20:46:44 +04:00
claude 570b204571 board: /tasks confirms a candidate into an open task (V-511)
The candidate row is now an intake form, not a button. Confirming asks for a
definition of done and refuses without one, takes an optional blocked-on name,
and carries the date and the importance through.

The blocked-on is a name in the form and a canonical nexus id in the store.
promoteCandidate resolves it over the new ipc.ResolveEntity seam and stops the
confirmation on an ambiguous or unplaceable name rather than picking.

A date set here books a reminder for 09:00 that morning. That is the only
unprompted delivery the persona allows, because the owner set the date himself.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SoL7EBdYC5Mhz3DJd49GJy
2026-08-05 20:46:35 +04:00
claude cb350efb19 a surface can ask Nexus for the id behind a name (V-511)
blocked_on stores a canonical entity id, so the form that fills it needs a way
to turn "Kate" into one. ipc.ResolveEntity is that seam: the store adapter
refuses it, because identity is not the store's to answer, and the daemon
overrides it with the Nexus client the voice path already holds.

Three outcomes are kept apart, because a caller deciding whether to store an
id has to tell them apart. No nexus block is ErrNotImplemented. A miss is
ErrNoEntity. Several matches come back Ambiguous with the names, and the
caller asks — picking one is how a task ends up blocked on the wrong person
with nobody able to see it happened.

An outage stays the transport error. "There is no such person" and "Nexus is
down" must not read the same.
2026-08-05 20:42:28 +04:00
claude 43b0c32154 Merge the task edit path (#188) 2026-08-05 20:39:29 +04:00
claude b95a0278a4 /tasks edits a task in place (V-509)
The open list carries the text, the date and the importance as an inline form
with a save button. The status is not in it: that ladder is one-way and has
its own two buttons.

The step-up gate was re-argued rather than inherited, which is what the task
asked for, and edit stays ungated. It rewrites a line on a list he reads
himself, the same blast radius drop already has here, and the store refuses
the two edits that would cost something. A collision is named ("another open
task already says this"), not merged.

A weight outside the three rungs keeps its own option in the select, or
saving an unrelated edit would silently reset it to normal.
2026-08-05 20:39:22 +04:00
claude a6b17ada8b a live task can be edited, a resolved one cannot (V-509)
SetTaskStatus was the only mutation on a task row, so a typo in a dictated
task was permanent and a deadline could not move. EditTask rewrites the three
fields capture set — text, due date and weight — and nothing else. Status
stays the one-way ladder SetTaskStatus owns.

Two things the task asked to settle.

A text edit re-normalises the dedupe key and can collide with another live
row. That is ErrTaskDuplicate, a refusal rather than a merge: two live rows
carry two provenances, two capture times and possibly two external
identities, and merging picks a winner for all three with nobody asked. The
surface names the row that holds the text.

A resolved task is refused outright (ErrTaskResolved). Its text is the record
of what was finished, and rewriting it rewrites history.

due nil clears the date, because clearing has to be sayable — an absent date
and "remove the date" cannot be one argument.
2026-08-05 20:39:11 +04:00
claude 92949e886f Merge the Vikunja MCP preload note (#187) 2026-08-05 20:29:47 +04:00
claude 6b2667b7af CLAUDE.md: load the Vikunja MCP schemas in one call (V-445)
The four schemas are deferred, so a session that looks them up on first use
spends four round trips on tools it always needs. One ToolSearch line at the
start covers them.

Also records the update_task quirk: a call carrying a description resets done
to false, so closing a task with a write-up takes two calls.
2026-08-05 20:29:47 +04:00
claude 494a7721e0 Merge the CLAUDE.md pronoun fix (#186) 2026-08-05 20:26:22 +04:00
claude 46b58f0278 CLAUDE.md names the owner instead of saying "he" (V-550)
The third person here leaked into answers addressed to him, where it reads as
talking about the person reading the reply. Six lines now say "the owner".

"you" is not available in this file: CLAUDE.md addresses the agent, so "you"
there means the agent.

One "him" stays, in the persona block. That line states that Maven must never
say "он"/"его" about the owner, which is a fact about required Russian output
rather than a reference.
2026-08-05 20:26:22 +04:00
claude a88c984d16 Merge the definition of done and the blocker (#185) 2026-08-05 20:17:38 +04:00
claude 496559c9dd tasks carry a definition of done and a blocker (V-510)
Migration #22 adds done_when and blocked_on to tasks, both NOT NULL DEFAULT
''. "He has not written one" and "there is nothing to write" are the same
state here, so no caller has to tell NULL from empty.

blocked_on is a canonical Nexus entity id, never a name. It names a person
and identity lives in Nexus, so free text here would be a second answer to a
question Nexus already owns. The caller resolves before it writes.

Both columns round-trip through ipc.TaskAPI: on ipc.Task, settable at intake
through CaptureTaskReq, and writable afterwards through the new
SetTaskFields, which is deliberately not one-way — he may sharpen a
criterion, and a blocker clears when the person answers.

SetTaskStatus now refuses candidate → open when done_when is empty
(ErrTaskNoDoneWhen, mapped across the wire), the same refusal
ParseTaskCapture makes for a capture marker with nothing after it: confirming
work whose finish line nobody wrote is how a board fills with rows that can
never leave it. Dropping such a candidate stays legal, and the /tasks confirm
button now says what is missing instead of surfacing a not-found.

One caller skips the gate. CaptureTask promoting a candidate he stated out
loud would otherwise be denied intake rather than asked for a criterion, and
a direct open capture never carried one either. The gate belongs to the
deliberate promotion on /tasks, where V-511 puts a form.
2026-08-05 20:17:30 +04:00
claude d21b4a65da Merge the board status change and the stall counts (#184) 2026-08-05 19:54:21 +04:00
claude be62660be9 /tasks counts stall shapes, and assesses none of them (V-512)
Step 5 of the board build. internal/tasks/stall.go counts three shapes —
overdue, sitting longer than StallDays, waiting for confirmation — and states
nothing about what any of them means. That is the line
internal/memory/behavior.go already drew for habits, and the reason is the
same: a 1.7B asked to judge will agree fluently and launder a guess into a
decision. A test asserts the wording carries no assessment.

Sitting is measured from created_ts, the only clock a live row carries: the
store stamps resolved_ts and nothing else. So "no state change in eleven days"
is exactly "captured eleven days ago and still live", which is narrower than
the plan's wording and is the claim the data supports. A candidate is never
counted as overdue, because its due date is Maven's reading of a mail rather
than a deadline he set.

Not a nag. No tick rule reads the counts; they go on /tasks and into the list
reply when he asks, and tickLoop.dayPlan still does not read tasks at all. The
empty case renders as nothing: "ничего не залежалось" appended to every list
read is a nag with a friendly face.

Three say entries, so the page and the spoken list cannot word it differently.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SoL7EBdYC5Mhz3DJd49GJy
2026-08-05 19:54:21 +04:00
claude cd6549fa51 the daemon moves the task he named, or says which part it cannot (V-512)
The other half of the stage-0 rule. actionAct intercepts task_status ahead of
both ecosystem clients, because the board is Maven's own store and reaching a
capability registry would answer a question about his task list with a gap.

Three answers besides the move, and none of them guesses. No match says so.
More than one match asks which, since closing the wrong task marks work he
never finished as done. No task named asks which too, because the router claims
the turn without the referent and the list lives here.

Matching is normalised containment either direction, over the same
store.NormalizeTaskText key capture dedupes on — he shortens what he said as
often as he pads it. Deliberately not fuzzy: a ranked best guess always returns
exactly one answer, and the one thing this has to be able to say is that it is
not sure.

A candidate he says is done takes both legal store moves. The store refuses
candidate → done, and saying it out loud IS the confirmation the candidate was
waiting for.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SoL7EBdYC5Mhz3DJd49GJy
2026-08-05 19:53:47 +04:00
claude c259ed6c73 a spoken status change reaches the board at stage 0 (V-512)
Step 4 of the board build (docs/plans/15-board-surface.md). Naming a task
instead of its position reached nothing: "закрой задачу купить молоко" routed
act, found no allowlisted fn, and the gate asked "Что сделать?". The position
path already worked through resolveCandidate, but only in the two turns after
she read the list out.

TaskStatusGrammar is the same shape TaskCaptureGrammar uses — matches broadly,
decides in Build, no eighth intent — and fills the fn slot with task_status,
which is neither a Hexis capability nor a Praxis one. Three conditions, all
required: the board noun, so no ordinary sentence claims a turn; exactly one
status class, since "готово, убери" names two and asking beats picking; and a
status word matched as an imperative exactly or a stative by lemma. So a bare
"готово" and a bare "закрой" are not this rule's, and the second belongs to
Praxis, which claims it already.

Two lexicon sets rather than one with a value. The store records which of the
two transitions happened and /tasks shows it: work he chose to stop is not work
he did.

Measured on the fixture, two new cases (ru-act-020, ru-act-021). Classifier +
ONNX 62/89 (69.7%) → 64/91 (70.3%); cascade+llm 67/89 (75.3%) → 69/91 (75.8%,
80.2% intent-only) at p50 1.225s. Both new cases claimed at stage 0, no case
regressed, clarify counts unchanged at 3 false / 1 missed.

The task's own warning stands: every such grammar runs its parser ahead of the
resident model on every turn, so this is the last one that is free.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SoL7EBdYC5Mhz3DJd49GJy
2026-08-05 19:53:20 +04:00
claude 8f2377d27d Merge the subjectless reminder gate (#183) 2026-08-05 19:36:29 +04:00
claude d850f1f5fd a bare "напомни" asks instead of failing to parse (V-548)
The subjectless-reminder gate has been dead since V-383. It tested
`d.Slots.Text == ""`, and that slot is never empty: fillSlots hands it the
utterance when the model names nothing narrower. Measured on the box on
05-08-2026 — "напомни" alone routed to IntentReminder with Text:напомни,
reached actionReminder, and answered "не получилось разобрать время
напоминания." A parse error for a request he never finished asking about.
"ну напомни же" did the same.

The test is now what the slot CONTAINS. reminderHasSubject discounts the
reminder verb by lemma and the filler particles, and asks whether anything
is left. A day or an hour counts as a subject, which is why this does not
reuse cmd/mavend/reminderbody.go — that one strips the time words too.

filler_particles is the lexicon's 16th set. Not a stopword list: every word
in it is one that cannot BE a reminder's subject.

Measured against the 87-case fixture with and without the change: 65/87
both ways, identical clarify counts, because no case exercised the shape.
So amb-007 "напомни" and amb-008 "ну напомни же" were added, both
want_clarify. At 89 cases the cascade scores 67/89 (75.3% full, 79.8%
intent-only), 3 false clarifies / 1 missed, p50 1.199s — the two new cases
clarify, and nothing else moved. The classifier path still guesses both
(62/89, 8 missed clarify); the gate is on the LLM arm only.

The box needs a rebuild for this to take effect.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SoL7EBdYC5Mhz3DJd49GJy
2026-08-05 19:36:29 +04:00
claude 4ed951040f Merge the scriptable chat path (#182) 2026-08-05 19:13:39 +04:00
claude 8d2c1b6f99 the simulator can script a chat reply (V-542)
Item 4. actionChat calls h.phraser.PhraseChat, and LLMPhraser posts raw
HTTP to /v1/chat/completions rather than going through the llm client
scriptedLLM stands in for. The simulator wired phraser.NewStub() anyway,
so no scenario could assert what she says on a chat turn: every reply came
back as a pick from fallbacks_ru_v1.json, four variants deep, and the same
scenario returned "тут я пас." one run and "не знаю, честно." the next.

scriptedPhraser embeds the Stub and overrides PhraseChat only, reading the
same script entries the router reads. A reply is accepted in either shape
the phrasing contract allows, the {"response","mood"} object or plain text,
so a scenario writes one thing for both paths.

An unscripted chat turn returns an error rather than a fallback, matching
scriptedLLM: actionChat logs it and uses ChatFallback(), so scenarios that
never meant to assert a chat reply behave as before.

conversation_anaphora turn 4 now pins its text — the reply that asks which
device he means, which is the recorded defect in the box's own words.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-05 19:13:39 +04:00
claude ee4c26f13c Merge the conversation fixture (#181) 2026-08-05 19:02:32 +04:00
claude 49cadcf1b7 a conversation about one object has a fixture (V-542)
Five Russian turns, one monitor, four questions that say "он" and never
name it again. Item 3 of the task: the shape had nowhere to fail, because
the routing fixture scores one utterance at a time and a conversation that
breaks on turn 2 cannot lose a point there.

Routes are scripted exactly as the box produced them on 05-08-2026. Turn 1
files a fact despite "давай поболтаем", the questions go to query, turn 4
goes to chat, and none of the five replies names the monitor. Four steps
assert the reply LACKS "монитор" and are marked WRONG in their notes with
what each must become.

The absence assertion is forced, not chosen. The simulator wires
phraser.NewStub(), and PhraseChat posts raw HTTP to /v1/chat/completions
rather than through the llm client the harness scripts, so a chat reply
cannot be scripted at all. The wrong replies come from
fallbacks_ru_v1.json, which picks between four variants per turn, so
asserting a string would pin the picker. Missing referent holds whichever
variant she reaches for.

Items 1 and 2 stay open: they are owner decisions about which store a
referent comes from and whether "давай поболтаем" claims a turn.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-05 19:02:32 +04:00
claude 988c2ae981 Merge the topic query vector fix (#180) 2026-08-05 18:51:50 +04:00
claude 982c25118a topic seeds get a query vector to score (V-547)
turnIsAbout scored t.vec, and t.vec was set in one place: queryEmbed, the
source at actions_query.go:125. Every topic source sits above it — attention,
list, feeds, home, network, weather. So best was handed an empty slice on every
deployed turn, returned ok=false, and all six recognisers ran on their keyword
floors. The seeds have decided nothing outside the tests since the mechanism
landed.

TestONNXTopics passes because it embeds each utterance itself and calls best
directly. That is the shape that hid this for a month: it measures the scorer
and never the wiring. Found on the box instead — "что мне нужно купить" was
answered from an old note about a monitor, and the seeds place it as the list by
0.0841.

turnVector computes the vector on first ask and caches it on the turn;
queryEmbed returns early when it is already set. Chosen over moving the embed
source up the list, because the cost is then paid only by turns that ask a
topic source, and the order of querySources keeps meaning what its comments
argue for.

One scenario assertion moved, and it is a behaviour change rather than a bent
test. morning_missed step 5 pinned "не знаю" for "что я пропустил?" with an
unresolved Praxis item on the board. isAttentionQuery does not match that
phrasing and the topicAttend seeds carry "что важное я пропустил" almost
verbatim, so she reads the item back now. Reading a surfaced item aloud is not
inventing a morning summary, so the floor that step exists for still holds;
what moved is which source answers.
2026-08-05 18:51:42 +04:00
claude de10d7664f Merge the list read-back seeds (#179) 2026-08-05 18:43:19 +04:00
claude a08403087f list read-back asks the seeds; add and clear keep their tables (V-522)
internal/router/list.go was the last file on the sweep, and the answer is a
split rather than one mechanism. What the four paths need is different, and the
V-529 comment in the file already had half of the argument.

Reading a list back needs one bit — is this about the list — so topicList joins
the subjects in cmd/mavend/topics.go and queryList calls turnIsAbout.
listQueryPrefixes stays as the offline floor. Which list he named is a noun in
the dictionary either way, through the new router.ListNamedIn, which scans the
whole utterance: the seeds claim a read-back without eating a prefix, so "что
мне нужно в аптеке" has nothing for takeListTag to read the front of.

The other three keep their phrase tables, and the header says why. Add and
remove have to know WHERE the item starts, and a cosine over a whole utterance
does not say which byte the milk begins at. Clear deletes the list, so a false
claim loses rows he cannot get back — that is not the trade a margin makes.

Measured on TestONNXTopics, four held-out cases added: 27/27, no case
regressed. Two existing margins moved by under a hundredth because the new
seeds became the runner-up, both still far clear of topicMargin.
2026-08-05 18:43:13 +04:00
claude 3e87ad7eb6 Merge the feed topic seeds (#178) 2026-08-05 18:37:46 +04:00
claude 47128bb1ca feed questions ask the seeds, not a stem list (V-522)
Whether a turn is about the feeds is a question about meaning, and
internal/router/feeds.go was deciding it with three word lists. Their own
comments admit the shape: vagueNouns exists because "что нового?" is the most
common opener in the language and it matched a feed noun, so a daemon with no
feeds block answered a greeting with a configuration status.

So topicFeed joins the four subjects in cmd/mavend/topics.go and queryFeeds
calls turnIsAbout. The word lists stay as the offline floor, reached through
feedFloor, and they are allowed to stay narrow now that they are not the only
answer. The category is not a recogniser — a topic is marked by a preposition —
so it comes out of the utterance either way, through the new
router.FeedCategoryOf.

The greeting is handled by the shape rather than by a bail-out list. "что
нового" is a topicOther seed, close enough to the feed seeds that a bare
"что нового?" cannot clear topicMargin, and a thin call goes to
ParseFeedQuery, which declines a vague noun with no topic beside it.

Measured on TestONNXTopics, four held-out cases added: 23/23, and no case that
passed before it regressed. One seed pair was added during the measurement,
because "какие сегодня заголовки" first read as weather — "какая сегодня
погода" was the nearest thing in the whole set carrying "сегодня".
2026-08-05 18:37:38 +04:00
claude 8e3b288858 Merge the ordinal lexicon change (#177) 2026-08-05 18:17:03 +04:00
claude 52a4772962 ordinal selection asks the lexicon, and declines a half hour (V-522)
Group 1 of the sweep listed cmd/mavend/ordinal.go, and it was still
picking a position by stem prefix: {"перв", 1}, {"втор", 2}. The lexicon
already carries every form with its position and "последний" as -1, up to
twelve rather than five, so parseOrdinal reads that instead. "вторым" and
"седьмую" were missed before and now land.

A wider set opens one hole the stems did not have. Russian names a half
hour with the genitive ordinal of the hour it is entering, so "в половине
восьмого" would read as the eighth thing she read out. The forms of
"половина" move into the lexicon as half_hour, where the clock rewrite in
internal/router/halfpast.go and this refusal read one copy, and
parseOrdinal skips an ordinal standing behind one.

Six new parseOrdinal cases. cmd/mavend, internal/router, internal/lexicon
and internal/calendar all pass.
2026-08-05 18:16:54 +04:00
claude 52d80394ec Merge the audio-in routing measurement (#176) 2026-08-05 17:06:05 +04:00
claude 42a7bd88b2 offload: speech-to-text stays two stages (V-486)
The one-call audio path is refused by measurement, so the inventory says
so where a future caller would read it.
2026-08-05 17:06:05 +04:00
claude b789676244 audio-in routing measured: transcribe then route (V-486)
Four paths on the same 72 RU cases with the daemon's own router prompt.
Text in scores 90.3% intent-only. Whisper then route scores 84.7% at p50
1372ms. The workstation transcribing then routing scores 83.3% at p50 997ms.
One call from audio straight to a route scores 54.2%.

The one-call number is not a transcription failure. Four clips it
transcribes word for word it then routes wrong or refuses, and the emitted
slot holds the tail of the sentence with the interrogative head gone. A
3.5k-character classification prompt and an audio part compete for
attention, so transcription needs its own call with a short instruction.

The two speech-to-text paths differ by one case, which is noise on 72, so
the choice is latency and transcript quality. The workstation wins both.
mavgpud.json on the workstation is restored to its text-only args.
2026-08-05 17:04:45 +04:00
claude b621c477a0 Merge the e5-small routing plan (#175) 2026-08-05 16:23:22 +04:00
105 changed files with 7827 additions and 266 deletions
+73 -12
View File
@@ -43,7 +43,7 @@ are the work.
Both halves are wired as of 2026-08-03. Routing and replies prefer the workstation silently
through `modelSeam`; nudge and reminder phrasing prefer it silently inside the phraser. A
world question goes through `LLMPhraser.PhraseWorld` and names the gap when the card is not
free — `worldGap` in `cmd/mavend/worldmodel.go`, which he hears instead of an invented
free — `worldGap` in `cmd/mavend/worldmodel.go`, which the owner hears instead of an invented
answer. A box with no `workstation` block behaves exactly as it did before the seam: naming
a gap requires a gap. The offload table in `docs/offload.md` says which caller is which.
@@ -90,11 +90,18 @@ protocol; the config in `deploy/mavend.json` (with `${VAR}` env expansion from g
**Seven of the nine run on homesrv. `mavwaked` and `mavenclient` do not, and that is the
decision, not an oversight** (Vikunja #463, `docs/plans/17-where-the-voice-loop-runs.md`).
homesrv has a microphone — it is a laptop — but it is in the wrong room, so a wake-word
daemon there listens to nobody. They belong on a client machine where he is standing.
`ipc.Dial` already takes `tcp://host:port?token=...` through the netaddr seam, so nothing
needs building to allow it, but no such machine exists yet. **The consequence: the wake
word and the VAD gate are covered by unit tests and by nothing else, and no amount of
sitting at the box changes that.** Push-to-talk through `/dash` is what QA actually covers.
daemon there listens to nobody. They belong on a client machine where the owner is standing.
**That machine is workpc** (owner's correction, 2026-08-05). This section used to say no
such machine existed, which was written when the workstation was only a model host. It is
where he sits most of the day and it has the microphone. `ipc.Dial` already takes
`tcp://host:port?token=...` through the netaddr seam, so the two daemons need deploying,
not building. V-515 is that deployment.
Until they are deployed, **the wake word and the VAD gate are covered by unit tests and by
nothing else**, and push-to-talk through `/dash` is what QA actually covers. Note that
deploying them does not by itself prove a wake word: `mavwaked` gates on energy and has no
keyword model (V-487), so the loop runs open until that lands.
## The ecosystem: Nexus, Praxis, Hexis
@@ -155,6 +162,19 @@ on in deploy** — this section used to say it was wired `nil`, which stopped be
Cascade order: `stage0.go` exact-match fast-path → LLM router (when non-nil) → classifier
fallback. Any LLM error falls through to the classifier so a turn never breaks on the model.
**A stage-0 decision is slot-extracted too, since 06-08-2026** (V-572). `fillMatchedSlots`
in `router.go` runs the stage-2 extractor over whatever a grammar built and fills only the
slots it left empty — a matched value always wins, because the rule read a literal pattern
and the extractor guesses. It did not run before, so `ReminderGrammar` handed the daemon
`HasTime: false` for "напомни в 11:00 позвонить маме" and `missingFor` read the silence as
absence and asked "Когда?". It applies to every grammar and is inert for all but the
reminder: `Extract` fills Time, Fn and Key and nothing else, and the query, clock, agenda,
feed, list, task and narrative rules all emit intents with no such slot. Benchmarked at
20000x, a stage-0 query costs 3.7µs against 3.9µs before. **`Slots.Text` is deliberately not
filled** — a grammar that left it empty meant it, and `agendaQueryBuild` hands the query
chain the utterance itself. Fixture unchanged at 64/91, with "slots deferred to daemon"
6 → 0.
Measured on the 77-case RU fixture. **Re-measured 2026-08-02: the classifier scores 68.8%
full accuracy at p50 16.6µs**, not the 36.8% at p50 31ms that stood here from
`docs/evals/2026-07-31-model-bakeoff.md`. That older figure predates the stage 0 rules and the
@@ -165,6 +185,15 @@ that stood here until 2026-08-02 was contention, not the model.** See `docs/eval
p50 825ms / p95 1.2s / max 3.0s and the full cascade at p50 0.80-1.04s. Do not plan latency
work off the bakeoff table.
**Re-measured 2026-08-05 on the fixture as it now stands, 91 cases** (V-320 item 2,
`docs/evals/2026-08-05-routing-resident-model.md`): cascade + resident model scores
**75.8% full / 80.2% intent-only at p50 1.19s / p95 1.65s**. That is a new baseline and not
a movement, because 14 cases were added since the 77-case number above. The model alone
scores 37.4% full against 61.5% intent-only, and the gap is slots rather than routing: it
routes `reminder` and leaves the time to the daemon, which is what the contract asks. To
re-run it, start a **second** llama-server on a fixed host port — the resident one binds
`--port 0` inside the container and no host process can reach it.
**The numbers above are the homesrv floor, not the ceiling.** With the workstation up, routing
completes through `llm.Pair` against gemma-4-12b and scores **84.4% full / 93.5% intent-only at
p50 329ms** — better than the resident model and about 2.5× faster (`docs/evals/2026-08-02-workstation-gemma4-12b.md`,
@@ -227,7 +256,13 @@ llama-server in that run), so judge it again before quoting a cascade number.
Praxis taken off the model, 05-08-2026 (V-516). `PraxisGrammars()`
(`internal/router/praxis.go`, wired in `buildRouter` before the capture marker because
"отметь" is a capture verb) fills `Slots.Fn` with a Praxis capability name. Praxis reach
"отметь" is a capture verb) fills `Slots.Fn` with a Praxis capability name.
**These grammars are the only path to Praxis, not a faster one.** Measured
2026-08-05 with the resident model as router (V-517,
`docs/evals/2026-08-05-reach-llm-router.md`): the model alone reaches Praxis
**0/12**, the same as the classifier alone, because nothing in the router
prompt names a Praxis capability and there is no string for it to write.
Through the cascade it is 11/12. Deleting these rules costs every point. Praxis reach
was **0/12 and structurally so**: `handlePraxisAct` compares `Slots.Fn` to a capability
alias, and that slot is filled from the deployment's enabled tool names, which no Praxis
alias is on. Measured **16/30 → 27/30 overall, praxis 0/12 → 11/12, lifecycle 0/5 → 5/5**
@@ -239,6 +274,22 @@ of the house. A demonstrative ("отметь это как сделанное")
`h.surfacedItems` only when exactly one item was spoken. Otherwise the turn goes back to
the cascade rather than transitioning the wrong item.
**Who claimed a turn is now recorded, and so is who did not** (V-564, umbrella
V-558). Arbitration between the claimants on the utterance stream is order,
hardcoded in the pre-route resolver ladder, in `buildRouter` and in
`querySources`. `internal/decision` records one `Record` per turn: every
claimant, what it would have made the turn, the score it reported, and whether
it won, declined, lost on score, was thinned by a gate or was **never asked**.
The record rides the context, the same seam `querysource.go` uses, so a claim
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
in `runTurn` means adding its name to `preRouteLadder` in
`cmd/mavend/decisiontrace.go`, or that rung is silently missing from the record.
## LLM output contract
All phrasing paths emit `{"response":"...","mood":"..."}` (parsed in `replier_llm.go` and
@@ -281,7 +332,7 @@ Seeds are scoring data. Editing one moves a recogniser and must be re-measured a
Not a nag, not autonomous. Maven's persona is **feminine** — Russian
self-reference must use feminine forms — `рада`, not `рад`; `поняла`, not `понял`. The owner
is male and is addressed informally: "ты", singular, never "вы"/"ваш" and never "он"/"его"
(she talks TO him, not about him). Pet names ("милый", "дорогой") are forbidden; his name
(she talks TO the owner, not about the owner). Pet names ("милый", "дорогой") are forbidden; the name
("Ками") is not. The eval enforces this: `CheckAddress`, `CheckFeminine` and `CheckCringe` in
`internal/phraser/eval/checks.go`, scored by `make eval-phrasing`.
@@ -291,7 +342,7 @@ world questions, so she needs to read external sources. What replaces it:
- **No telemetry, no cloud model, no third-party account.** That part never changes. Nothing
about Maven is reported to anyone, and inference stays on the box.
- **His data first, then the world.** Every source that reads his facts, notes, calendar,
- **The owner's data first, then the world.** Every source that reads the owner's facts, notes, calendar,
tasks or house runs before anything outside, and the personal boundary sits between them.
Reading beats recalling for a small model.
- **In the world, live search leads and the ZIMs are the fallback** (owner's call,
@@ -299,7 +350,7 @@ world questions, so she needs to read external sources. What replaces it:
homesrv answer when the search is empty, unreachable, or the line is down.
**Verified with the line down on 2026-08-05** (V-508,
`docs/evals/2026-08-05-kiwix-offline-fallback.md`): a stopped SearXNG costs nothing,
the ZIM answers in the same turn budget. A blackholed host cost 8 seconds he waited
the ZIM answers in the same turn budget. A blackholed host cost 8 seconds the owner waited
through. So the connect phase alone is capped at `dialTimeout` (1.5s), while a slow
instance that did connect keeps the full 8. **A Russian question reads
`wikipedia_ru_all_maxi_2026-02` verbatim** through `kiwix.book_ru`. The RU→EN rewriter
@@ -318,8 +369,8 @@ world questions, so she needs to read external sources. What replaces it:
capabilities. The code default is still off. `deploy/mavend.json` now ships a `search`
block (owner's call, 2026-08-02), so it is on for this box and deleting the block turns
it off again.
- **His notes and facts are never search input.** Looking up why the sky is blue and sending
his stored personal notes to an upstream engine are different acts. Only the utterance goes
- **The owner's notes and facts are never search input.** Looking up why the sky is blue and
sending the owner's stored personal notes to an upstream engine are different acts. Only the utterance goes
out, never the persona block, history, or matched notes.
## Web UI conventions
@@ -341,6 +392,16 @@ Vikunja is the durable task store. A task holds the goal, the constraints and th
assumption ledger. Work without a task id is work nobody can resume, so a session that
has no id asks for one before it starts.
The MCP tool schemas are deferred, so load the four you actually use in ONE call at the
start of a session rather than one lookup per first use:
```text
ToolSearch("select:mcp__vikunja__list_tasks,mcp__vikunja__get_task_details,mcp__vikunja__create_task,mcp__vikunja__update_task")
```
`update_task` carrying a `description` resets `done` to false, so closing a task with a
write-up takes two calls: the description, then `done: true`.
## Session workflow
`~/.local/bin/task` owns the branch, the commit identity and the PR. One task, one
+8
View File
@@ -24,6 +24,14 @@ func (h *reactiveHandler) actionAct(ctx context.Context, dec router.Decision) st
}
}
// The board is Maven's own store, so a spoken status change is answered here
// and never offered to an ecosystem client (Vikunja #512). First, because
// task_status is on no allowlist and no capability registry: reaching either
// of them would answer a turn about his own task list with a gap.
if dec.Slots.Fn == router.TaskStatusFn {
return h.resolveTaskStatus(ctx, dec)
}
// Praxis ecosystem tools: intercept before the system command executor.
if h.ecosystem != nil && h.ecosystem.praxis != nil && dec.Slots.HasFn {
if reply := h.handlePraxisAct(ctx, dec); reply != "" {
+13 -2
View File
@@ -95,6 +95,12 @@ func (h *reactiveHandler) removeListItem(ctx context.Context, cap router.ListCap
return "", false
}
// listFloor — the keyword test behind topicList, in the shape turnIsAbout takes.
func listFloor(u string) bool {
_, ok := router.ParseListQuery(u)
return ok
}
// queryList — "что в списке покупок?", "что мне купить?".
//
// A query source, so it sits in querySources and either claims the turn or
@@ -102,10 +108,15 @@ func (h *reactiveHandler) removeListItem(ctx context.Context, cap router.ListCap
// source is: the notes pass would otherwise answer a list question with
// whatever note is nearest.
func (h *reactiveHandler) queryList(ctx context.Context, t *queryTurn) (string, bool) {
list, ok := router.ParseListQuery(t.dec.Utterance)
if !ok || h.dataStore == nil {
if h.dataStore == nil {
return "", false
}
// The seeds decide the subject and listQueryPrefixes is the floor behind
// them (V-522). Which list he named is a noun lookup either way.
if !h.turnIsAbout(ctx, t, topicList, listFloor) {
return "", false
}
list := router.ListNamedIn(t.dec.Utterance)
items, err := h.dataStore.ListItems(ctx, list, "")
if err != nil {
log.Printf("voice: list items: %v", err)
+84 -7
View File
@@ -11,6 +11,7 @@ import (
"unicode"
"github.com/kami/maven/internal/crawl"
"github.com/kami/maven/internal/decision"
"github.com/kami/maven/internal/ipc"
"github.com/kami/maven/internal/memory"
"github.com/kami/maven/internal/morning"
@@ -122,6 +123,12 @@ var querySources = []querySource{
{name: "network", answer: (*reactiveHandler).queryNetwork},
{name: "calendar", answer: (*reactiveHandler).queryCalendar, dateAware: true},
{name: "weather", answer: (*reactiveHandler).queryWeather},
// A question about her, above the three sources that search his own data
// (Vikunja #555). It has no answer anywhere else: below the boundary
// SearXNG answers about somebody else's assistant, and above it his notes
// answer by proximity — "кто ты" came back from a note of his, measured on
// the box, because the recall index has no idea the subject is her.
{name: "self", answer: (*reactiveHandler).querySelf},
{name: "embed", answer: (*reactiveHandler).queryEmbed},
{name: "memory", answer: (*reactiveHandler).queryMemory},
{name: "notes", answer: (*reactiveHandler).queryNotes},
@@ -152,8 +159,17 @@ var querySources = []querySource{
func (h *reactiveHandler) actionQuery(ctx context.Context, dec router.Decision) string {
t := &queryTurn{dec: dec}
// The roster, so the record can say which sources were never reached rather
// than leaving them out and letting a reader assume they looked and passed
// (V-564). Finish names everyone below the winner.
decision.Expect(ctx, decision.StageQuery, querySourceNames())
rec := decision.From(ctx)
for _, src := range querySources {
if dec.Continued && !src.dateAware {
rec.Note(decision.Claim{
Stage: decision.StageQuery, Claimant: src.name, Outcome: decision.NeverAsked,
Reason: "a continuation turn only asks the date-aware sources",
})
continue
}
if reply, ok := src.answer(h, ctx, t); ok {
@@ -166,8 +182,16 @@ func (h *reactiveHandler) actionQuery(ctx context.Context, dec router.Decision)
// caller asked for one, so /chat can show it (V-539).
log.Printf("voice: query claimed by source %q", src.name)
noteQuerySource(ctx, src.name)
rec.Note(decision.Claim{
Stage: decision.StageQuery, Claimant: src.name,
Intent: string(dec.Intent), Outcome: decision.Won,
})
return reply
}
rec.Note(decision.Claim{
Stage: decision.StageQuery, Claimant: src.name, Outcome: decision.Declined,
Reason: "it had no answer for this turn",
})
}
if dec.Continued {
// The previous question cannot be re-asked for another day. Saying so
@@ -292,6 +316,14 @@ const (
feedReadOut = 3
)
// feedFloor — the keyword test behind topicFeed, in the one-string shape
// turnIsAbout takes. router.ParseFeedQuery returns the category too, which the
// gate has no use for; the caller reads it separately.
func feedFloor(u string) bool {
_, ok := router.ParseFeedQuery(u)
return ok
}
// queryFeeds — "что нового в лентах?", "что нового по технологиям?"
// (Vikunja #258).
//
@@ -299,10 +331,13 @@ const (
// never speaks; asking is the trigger. If that ever changes, the thing that
// changed is "Maven is not a nag", not a detail of this file.
func (h *reactiveHandler) queryFeeds(ctx context.Context, t *queryTurn) (string, bool) {
q, ok := router.ParseFeedQuery(t.dec.Utterance)
if !ok {
// The seeds decide the subject; router.ParseFeedQuery is the floor behind
// them (V-522). The category still comes from the utterance either way,
// because a topic is marked by a preposition and needs no recogniser.
if !h.turnIsAbout(ctx, t, topicFeed, feedFloor) {
return "", false
}
category := router.FeedCategoryOf(t.dec.Utterance)
if !h.feedsOn {
// Claim only when nothing below can read the world. The reason this
// source used to claim unconditionally was that general knowledge would
@@ -327,7 +362,7 @@ func (h *reactiveHandler) queryFeeds(ctx context.Context, t *queryTurn) (string,
}
var picked []string
for _, n := range notes {
if !router.CategoryMatches(rss.NoteCategory(n.Text), q.Category) {
if !router.CategoryMatches(rss.NoteCategory(n.Text), category) {
continue
}
// The note carries title, summary, category tag and link; she reads the
@@ -339,7 +374,7 @@ func (h *reactiveHandler) queryFeeds(ctx context.Context, t *queryTurn) (string,
}
}
if len(picked) == 0 {
if q.Category != "" {
if category != "" {
return phraser.Q(phraser.QueryFeedsTopic, nil), true
}
return phraser.Q(phraser.QueryFeedsEmpty, nil), true
@@ -360,6 +395,19 @@ func (h *reactiveHandler) queryCalendar(ctx context.Context, t *queryTurn) (stri
if isWeatherQuery(t.dec.Utterance) {
return "", false
}
// Weather was one instance of a wider class (Vikunja #552). Naming a day
// does not make a question his agenda: "какой сегодня курс доллара" and
// "во сколько закат сегодня" both answered "ничего нет", which reads as an
// answer about a subject she never looked at. All of them have an answer
// in search, and search sits below this source. So the question must ask
// about his schedule, not merely name a day.
//
// A continuation is exempt. "а завтра?" names no agenda and cannot: the
// subject was in the turn before it, and this is the only date-aware
// source there is.
if !t.dec.Continued && !router.IsAgendaQuestion(t.dec.Utterance) {
return "", false
}
date, ok := router.ParseCalendarDate(t.dec.Utterance, h.now())
if !ok {
return "", false
@@ -455,12 +503,27 @@ func (h *reactiveHandler) queryWeather(ctx context.Context, t *queryTurn) (strin
// queryEmbed isn't an answer source — it's the shared cost the two recall
// sources below both need, run once, in the position it always ran in. It
// only claims the turn when the embedder fails.
// never claims the turn.
//
// It used to claim on an embedder error, and that made a RAG hint a hard gate
// over everything below it (V-568): one failing EmbedQuery and the memory, the
// notes, the boundary, the search, the ZIMs, the named page and the model all
// answered "не смогла ответить", including the questions search and Kiwix
// would have answered without ever touching the embedder. A failed embed means
// this source cannot claim, not that the turn is over — same shape as
// turnVector in topics.go, which had it right.
func (h *reactiveHandler) queryEmbed(ctx context.Context, t *queryTurn) (string, bool) {
// A topic source above already paid for this one; see turnVector.
if len(t.vec) > 0 {
return "", false
}
vec, err := router.EmbedQuery(ctx, h.recall.embedder, t.dec.Utterance)
if err != nil {
// Logged once, here, and the chain walks on. The two recall sources
// below read the empty vector and pass; the boundary drops to its
// offline floor.
log.Printf("voice: embed query: %v", err)
return phraser.Q(phraser.QueryFailAnswer, nil), true
return "", false
}
t.vec = vec
return "", false
@@ -480,6 +543,12 @@ func (h *reactiveHandler) queryMemory(ctx context.Context, t *queryTurn) (string
if h.recall.memStore == nil {
return "", false
}
if len(t.vec) == 0 {
// No query vector: the embed above failed or there is no embedder.
// Searching on an empty vector is not a search, and its scores are not
// a "there is nothing" answer — pass rather than gate the chain.
return "", false
}
hits, herr := h.recall.memStore.Search(ctx, t.vec, 3)
if herr != nil {
log.Printf("voice: memory search: %v", herr)
@@ -526,10 +595,18 @@ func (h *reactiveHandler) queryMemory(ctx context.Context, t *queryTurn) (string
// band. See memory.Confident. Failing the gate passes the turn on to general
// knowledge, which is what "don't read back the runner-up" means here.
func (h *reactiveHandler) queryNotes(ctx context.Context, t *queryTurn) (string, bool) {
if len(t.vec) == 0 {
// Same reason as queryMemory above (V-568): with no query vector this
// source could not look, and could-not-look passes.
return "", false
}
notes, err := h.api.QueryNotes(ctx, t.vec, 5)
if err != nil {
// The store failed, so this source could not look either. It used to
// claim here, which stopped the search, the ZIMs and the model from
// answering a question that never needed a note (V-568).
log.Printf("voice: query notes: %v", err)
return phraser.Q(phraser.QueryFailAnswer, nil), true
return "", false
}
t.notes = notes
noteScores := make([]float64, len(notes))
+90 -1
View File
@@ -3,6 +3,7 @@ package main
import (
"context"
"log"
"strings"
"github.com/kami/maven/internal/dialogue"
"github.com/kami/maven/internal/ipc"
@@ -81,7 +82,95 @@ func (h *reactiveHandler) queryTasks(ctx context.Context, t *queryTurn) (string,
cands = append(cands, dialogue.Candidate{Kind: "task", Ref: r.ID, Label: r.Text})
}
h.offerCandidates(ctx, cands)
return tasks.FormatRU(ranked), true
reply := tasks.FormatRU(ranked)
// The counted shapes, after the list and only when there are any (V-512).
// They answer "what is going wrong with this list" without assessing any of
// it, and they are said here rather than announced: no tick rule reads them.
if stalls := tasks.StallsRU(tasks.Stalls(taskItems(live), h.now())); stalls != "" {
if !strings.HasSuffix(reply, ".") {
reply += "."
}
reply += " " + stalls
}
return reply, true
}
// resolveTaskStatus moves a task he named out loud (Vikunja #512).
//
// The position path already worked: resolveCandidate answers "первую сделал"
// against the list she just read. This is the other half — naming the task
// instead of its position, which reached no code at all before the stage-0 rule
// in internal/router/taskstatus.go filled the fn slot.
//
// Three answers besides the move, and none of them guesses. No match says so. A
// match on more than one asks which, because closing the wrong task is work he
// never finished being marked done. No task named asks which too, since the
// router claims the turn without the referent and the list lives here.
func (h *reactiveHandler) resolveTaskStatus(ctx context.Context, dec router.Decision) string {
live, err := h.api.ListTasks(ctx, "live")
if err != nil {
log.Printf("voice: task status: list: %v", err)
return "не получилось посмотреть задачи."
}
if dec.Slots.Text == "" {
return "какую задачу?"
}
match := matchTaskText(live, dec.Slots.Text)
switch len(match) {
case 0:
return "не нашла такой задачи."
case 1:
default:
return "у тебя несколько подходящих — какую именно?"
}
pick := match[0]
status := dec.Slots.Value
// A candidate is work Maven proposed and he never confirmed, and the store
// refuses candidate → done: the legal move is to open it first. Saying it is
// done IS the confirmation, so both writes happen rather than the turn
// naming a gap about a distinction he did not make.
if pick.Status == store.TaskCandidate && status == store.TaskDone {
if err := h.api.SetTaskStatus(ctx, pick.ID, store.TaskOpen, h.now(), string(sourceVoice)); err != nil {
log.Printf("voice: task status: promote %d: %v", pick.ID, err)
return "не получилось изменить задачу."
}
}
if err := h.api.SetTaskStatus(ctx, pick.ID, status, h.now(), string(sourceVoice)); err != nil {
log.Printf("voice: task status: %d → %s: %v", pick.ID, status, err)
return "не получилось изменить задачу."
}
log.Printf("voice: task %d (%q) → %s", pick.ID, pick.Text, status)
if status == store.TaskDropped {
return "убрала: " + pick.Text
}
return "закрыла: " + pick.Text
}
// matchTaskText finds the live tasks he could have meant.
//
// Normalised containment, either direction, over store.NormalizeTaskText — the
// same key capture dedupes on, so a task he can file twice is a task he can name
// twice. Either direction because he shortens what he said ("молоко" for
// "купить молоко") as often as he pads it.
//
// Deliberately not fuzzy. A ranked best guess would always return exactly one
// answer, and the one thing this must be able to say is that it is not sure.
func matchTaskText(live []ipc.Task, named string) []ipc.Task {
want := store.NormalizeTaskText(named)
if want == "" {
return nil
}
var out []ipc.Task
for _, t := range live {
have := store.NormalizeTaskText(t.Text)
if have == "" {
continue
}
if strings.Contains(have, want) || strings.Contains(want, have) {
out = append(out, t)
}
}
return out
}
// taskItems maps wire rows onto the ranker's input. Written here rather than in
+87
View File
@@ -26,6 +26,9 @@ type taskAPI struct {
tasks []ipc.Task
listArg string
listErr error
moved []setStatusCall
moveErr error
}
func (a *taskAPI) CaptureTask(_ context.Context, req ipc.CaptureTaskReq) (ipc.CaptureTaskResp, error) {
@@ -253,3 +256,87 @@ func TestCaptureTaskFromNoteAcknowledgesAPromotion(t *testing.T) {
}
}
}
// setStatusCall — one SetTaskStatus the arm made, in order, so a candidate he
// says is done can be shown to take both legal moves.
type setStatusCall struct {
id int64
status string
by string
}
func (a *taskAPI) SetTaskStatus(_ context.Context, id int64, status string, _ time.Time, by string) error {
a.moved = append(a.moved, setStatusCall{id: id, status: status, by: by})
return a.moveErr
}
func TestResolveTaskStatusMovesTheNamedTask(t *testing.T) {
api := &taskAPI{tasks: []ipc.Task{
{ID: 7, Text: "купить молоко", Status: "open"},
{ID: 8, Text: "оплатить интернет", Status: "open"},
}}
h := taskHandler(api)
reply := h.resolveTaskStatus(context.Background(), router.Decision{
Intent: router.IntentAct,
Slots: router.Slots{Fn: router.TaskStatusFn, HasFn: true, Value: "done", Text: "молоко"},
})
if api.listArg != "live" {
t.Errorf("listed %q, want live — a resolved task cannot be resolved again", api.listArg)
}
if len(api.moved) != 1 {
t.Fatalf("moved %d tasks, want 1: %+v", len(api.moved), api.moved)
}
if api.moved[0].id != 7 || api.moved[0].status != "done" {
t.Errorf("moved %+v, want id 7 → done", api.moved[0])
}
if !strings.Contains(reply, "купить молоко") {
t.Errorf("reply = %q, want the task named back", reply)
}
}
func TestResolveTaskStatusRefusesToGuess(t *testing.T) {
cases := []struct {
name string
tasks []ipc.Task
named string
want string
}{
{"no match", []ipc.Task{{ID: 7, Text: "купить молоко", Status: "open"}}, "позвонить маме", "не нашла"},
{"two matches", []ipc.Task{
{ID: 7, Text: "купить молоко", Status: "open"},
{ID: 8, Text: "купить молоко и хлеб", Status: "open"},
}, "купить молоко", "несколько"},
{"none named", []ipc.Task{{ID: 7, Text: "купить молоко", Status: "open"}}, "", "какую"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
api := &taskAPI{tasks: c.tasks}
h := taskHandler(api)
reply := h.resolveTaskStatus(context.Background(), router.Decision{
Slots: router.Slots{Fn: router.TaskStatusFn, HasFn: true, Value: "done", Text: c.named},
})
if len(api.moved) != 0 {
t.Errorf("moved %+v — closing the wrong task is the failure this arm exists to avoid", api.moved)
}
if !strings.Contains(reply, c.want) {
t.Errorf("reply = %q, want it to contain %q", reply, c.want)
}
})
}
}
func TestResolveTaskStatusOpensACandidateFirst(t *testing.T) {
// The store refuses candidate → done. Saying it is done is the confirmation
// the candidate was waiting for, so the arm makes both legal moves.
api := &taskAPI{tasks: []ipc.Task{{ID: 9, Text: "продлить домен", Status: "candidate"}}}
h := taskHandler(api)
h.resolveTaskStatus(context.Background(), router.Decision{
Slots: router.Slots{Fn: router.TaskStatusFn, HasFn: true, Value: "done", Text: "продлить домен"},
})
if len(api.moved) != 2 {
t.Fatalf("moved %+v, want open then done", api.moved)
}
if api.moved[0].status != "open" || api.moved[1].status != "done" {
t.Errorf("moved %+v, want open then done", api.moved)
}
}
+61
View File
@@ -0,0 +1,61 @@
package main
import (
"context"
"testing"
"github.com/kami/maven/internal/router"
)
// TestCalendarStepsAsideForTheWorld — the defect (Vikunja #552). Weather was
// one instance of a wider class, and V-474 fixed only that instance. Every one
// of these answered "на 05.08.2026 ничего нет" on the deployed daemon, and
// every one of them has an answer in search, which sits below the calendar.
func TestCalendarStepsAsideForTheWorld(t *testing.T) {
h, api := contQueryHandler()
for _, u := range []string{
"во сколько закат сегодня",
"какой сегодня курс доллара",
"какой сегодня праздник",
"что интересного произошло сегодня в мире",
} {
if reply, ok := h.queryCalendar(context.Background(), &queryTurn{
dec: router.Decision{Intent: router.IntentQuery, Utterance: u},
}); ok {
t.Errorf("the calendar claimed %q with %q", u, reply)
}
}
if api.events != 0 {
t.Errorf("CalendarEvents called %d times for world questions, want 0", api.events)
}
}
// The other half of the same narrowing: a question about his own day still
// reaches the calendar, including the one that names no subject at all.
func TestCalendarStillAnswersHisDay(t *testing.T) {
for _, u := range []string{
"что у меня сегодня",
"во сколько у меня встреча сегодня",
"какие встречи завтра",
"что в календаре на завтра",
"что сегодня?",
} {
h, _ := contQueryHandler()
if _, ok := h.queryCalendar(context.Background(), &queryTurn{
dec: router.Decision{Intent: router.IntentQuery, Utterance: u},
}); !ok {
t.Errorf("the calendar passed on %q", u)
}
}
}
// A continuation carries its subject in the turn before it, and the calendar
// is the only date-aware source, so the narrowing must not reach it.
func TestCalendarStillAnswersAContinuation(t *testing.T) {
h, _ := contQueryHandler()
if _, ok := h.queryCalendar(context.Background(), &queryTurn{
dec: router.Decision{Intent: router.IntentQuery, Utterance: "а завтра?", Continued: true},
}); !ok {
t.Error("the calendar passed on a continuation")
}
}
+65 -8
View File
@@ -156,6 +156,11 @@ func (h *reactiveHandler) askClarify(ctx context.Context, dec router.Decision) (
if !ok {
return "", false
}
// An act she could not resolve is a refusal, not a question (Vikunja #556).
if slot == dialogue.SlotFn {
log.Printf("voice: clarify — act %q matched no capability; saying so instead of asking", dec.Utterance)
return actNotRecognized, true
}
h.clarifyStore.Put(dialogueIDOf(ctx), &dialogue.PendingQuestion{
Intent: dialogue.Intent(dec.Intent),
Slots: toDialogueSlots(dec.Slots),
@@ -170,14 +175,31 @@ func (h *reactiveHandler) askClarify(ctx context.Context, dec router.Decision) (
return question, true
}
// resolveClarifyAnswer reads an utterance as the answer to a parked question.
// Returns ("", false) when no live question is parked (or it expired), so the
// caller routes the utterance normally as a fresh request. Sibling of
// resolveConfirm and checked in the same place.
// clarifyCancelled — he called the half-built request off. Said out loud, like
// every other way it can end: a silent drop reads as "done". Feminine
// self-reference ("отменила"), as everywhere.
const clarifyCancelled = "Хорошо, отменила."
// clarifyDropped — he asked for something else instead, so the parked request
// is gone. Glued in front of the answer to what he actually asked, because
// nothing may be dropped in silence. V-561 suspends and resumes it instead of
// letting it go, and this line goes away with it.
const clarifyDropped = "Прошлую просьбу отпускаю."
// resolveClarifyAnswer reads an utterance against the parked question and
// decides what it IS before deciding what to do with it. Returns ("", false)
// when the turn is not this resolver's — nothing parked, or the utterance turned
// out to be a request of its own — so the caller dispatches it normally.
//
// The answer is parsed with the same extractor the router uses, for the intent
// she parked — no second parser. If it still does not fill the gap she asks
// again, up to MaxAttempts; after that she says out loud that she did not
// The order is the point (Vikunja #560). The utterance is ROUTED first, and the
// role is read off that decision: a routed decision that stands on its own is
// not an answer, whatever the extractor found inside it. Before this the
// extractor decided, so "какая сейчас погода в Риме?" became the time of a
// reminder on the strength of the word "сейчас".
//
// The answer itself is parsed with the same extractor the router uses, for the
// intent she parked — no second parser. If it still does not fill the gap she
// asks again, up to MaxAttempts; after that she says out loud that she did not
// understand. She never drops the request in silence.
func (h *reactiveHandler) resolveClarifyAnswer(ctx context.Context, text string) (string, bool) {
if h.clarifyStore == nil {
@@ -185,11 +207,36 @@ func (h *reactiveHandler) resolveClarifyAnswer(ctx context.Context, text string)
}
q := h.clarifyStore.Get(dialogueIDOf(ctx), h.now())
if q == nil {
return "", false
return "", false // not_applicable: nothing is pending
}
intent := router.Intent(q.Intent)
answer := h.extractor.Extract(ctx, intent, text, h.now())
var (
routed router.Decision
routedOK bool
)
if needsRoute(text) {
routed, routedOK = h.routeForRole(ctx, text)
}
role := classifyTurnRole(q, text, toDialogueSlots(answer), routed, routedOK)
log.Printf("voice: clarify — %q is a %s against %s (routed=%v)", text, role, dialogue.CapabilityFor(q.Intent), routedOK)
switch role {
case roleCancel:
h.clarifyStore.Delete(dialogueIDOf(ctx))
return clarifyCancelled, true
case roleSideQuery, roleNewRequest:
// He moved on. A parked question used to swallow whatever came next, so
// one act she could not fulfil ate the following three turns (Vikunja
// #554) and a world question set a reminder for a time nobody asked for
// (#558). Drop the question, say so, and let these words be themselves.
h.clarifyStore.Delete(dialogueIDOf(ctx))
h.noteDropped(ctx)
return "", false
}
merged := q.Answer(text, toDialogueSlots(answer))
// Fold a newly answered subject into the raw utterance. Downstream actions
// phrase from Utterance, not from the text slot — actionReminder stores it
@@ -226,6 +273,16 @@ func (h *reactiveHandler) resolveClarifyAnswer(ctx context.Context, text string)
return h.finishClarified(ctx, dec), true
}
// noteDropped records that the parked request was let go this turn, so runTurn
// can say it in front of whatever these words are answered with. Nothing to
// record outside runTurn — a unit test calling one resolver has no turn to glue
// a notice onto.
func (h *reactiveHandler) noteDropped(ctx context.Context) {
if rt := turnRouteFrom(ctx); rt != nil {
rt.dropped = clarifyDropped
}
}
// foldAnswerIntoUtterance appends an answered subject to the original words,
// unless they already carry it. "напомни" + "позвонить маме" reads as the
// request he would have made in one breath. Nothing is appended when the
+184 -25
View File
@@ -10,6 +10,7 @@ import (
"github.com/kami/maven/internal/dialogue"
"github.com/kami/maven/internal/ipc"
"github.com/kami/maven/internal/memory"
"github.com/kami/maven/internal/phraser/eval"
"github.com/kami/maven/internal/router"
"github.com/kami/maven/internal/store"
@@ -231,34 +232,35 @@ func TestClarifyRestatedAnswerWins(t *testing.T) {
}
}
// TestClarifiedActOffAllowlistIsStillRefused — clarification fills in an
// argument, it never grants authority.
func TestClarifiedActOffAllowlistIsStillRefused(t *testing.T) {
// TestActOffAllowlistIsStillRefused — naming a capability is not being granted
// one. Since Vikunja #556 an unresolved act no longer parks a question, so this
// goes through applyAction, which is the only way an act runs.
func TestActOffAllowlistIsStillRefused(t *testing.T) {
ctx := context.Background()
h, st, _ := newClarifyHandler(t)
marker := filepath.Join(t.TempDir(), "not-allowed-ran")
if err := st.EnableTool(ctx, "uptime", []string{"true"}, false, "test", h.now()); err != nil {
t.Fatal(err)
}
if _, asked := h.askClarify(ctx, clarifyDec(router.IntentAct, router.Slots{Text: "сделай это"}, "сделай это")); !asked {
t.Fatal("an act with no fn should be asked about")
}
reply, handled := h.resolveClarifyAnswer(ctx, "rm "+marker)
if !handled {
t.Fatal("the answer should be consumed")
}
reply := h.applyAction(ctx, router.Decision{
Utterance: "rm " + marker,
Intent: router.IntentAct,
Slots: router.Slots{Fn: "rm " + marker, HasFn: true},
})
if strings.Contains(reply, "готово") {
t.Fatalf("an act that is not on the allowlist must not report success: %q", reply)
}
if _, err := os.Stat(marker); !os.IsNotExist(err) {
t.Fatalf("a clarified act off the allowlist ran anyway: %v", err)
}
if tools, err := st.ListTools(ctx, "enabled"); err != nil || len(tools) != 0 {
t.Fatalf("clarify must not enable a tool: tools=%+v err=%v", tools, err)
if tools, err := st.ListTools(ctx, "enabled"); err != nil || len(tools) != 1 {
t.Fatalf("an act must not enable a tool: tools=%+v err=%v", tools, err)
}
}
// TestClarifiedDestructiveActStillNeedsConfirm — the confirm gate survives the
// clarify path.
func TestClarifiedDestructiveActStillNeedsConfirm(t *testing.T) {
// TestDestructiveActStillNeedsConfirm — the confirm gate stands on the act path.
func TestDestructiveActStillNeedsConfirm(t *testing.T) {
ctx := context.Background()
h, st, _ := newClarifyHandler(t)
marker := filepath.Join(t.TempDir(), "destructive-ran")
@@ -266,18 +268,16 @@ func TestClarifiedDestructiveActStillNeedsConfirm(t *testing.T) {
t.Fatal(err)
}
if _, asked := h.askClarify(ctx, clarifyDec(router.IntentAct, router.Slots{Text: "сделай это"}, "сделай это")); !asked {
t.Fatal("expected a question")
}
reply, handled := h.resolveClarifyAnswer(ctx, "delete_backups")
if !handled {
t.Fatal("the answer should be consumed")
}
reply := h.applyAction(ctx, router.Decision{
Utterance: "delete_backups",
Intent: router.IntentAct,
Slots: router.Slots{Fn: "delete_backups", HasFn: true},
})
if !strings.Contains(reply, "да") || h.pending == nil {
t.Fatalf("a clarified destructive act must still park a confirm: reply=%q pending=%+v", reply, h.pending)
t.Fatalf("a destructive act must park a confirm: reply=%q pending=%+v", reply, h.pending)
}
if _, err := os.Stat(marker); !os.IsNotExist(err) {
t.Fatalf("a clarified destructive act ran before confirmation: %v", err)
t.Fatalf("a destructive act ran before confirmation: %v", err)
}
}
@@ -419,7 +419,7 @@ func TestClarifyProseHoldsThePersona(t *testing.T) {
eval.CheckAddress: true,
eval.CheckCringe: true,
}
lines := append([]string{clarifyGaveUp}, clarifyExpiredVariants...)
lines := append([]string{clarifyGaveUp, clarifyCancelled, clarifyDropped}, clarifyExpiredVariants...)
lines = append(lines, clarifyMissedVariants...)
for _, variants := range clarifyQuestionVariants {
lines = append(lines, variants...)
@@ -564,3 +564,162 @@ func TestARestartExpiresTheParkedQuestion(t *testing.T) {
t.Fatalf("notice = %q, want silence: nothing survived to expire", notice)
}
}
// TestClarifyStepsAsideForItsOwnRequest — Vikunja #554. An act she could not
// fulfil parked "Что сделать?", and the three turns after it were scored as
// answers to that question: a world question, then "как дела", then the give-up
// line. None of them was ever an answer.
func TestClarifyStepsAsideForItsOwnRequest(t *testing.T) {
ctx := context.Background()
h, _, _ := newClarifyHandler(t)
// A reminder, not the act this bug was found on: since Vikunja #556 an act
// no longer parks anything, so it can no longer eat the turn after it.
if _, asked := h.askClarify(ctx, clarifyDec(router.IntentReminder, router.Slots{Text: "напомни позвонить маме"}, "напомни позвонить маме")); !asked {
t.Fatal("a reminder with no time should be asked about")
}
if reply, handled := h.resolveClarifyAnswer(ctx, "кто изобрёл телефон"); handled {
t.Fatalf("a world question must route as itself, got %q", reply)
}
if h.clarifyStore.Get(voiceDialogueID, h.now()) != nil {
t.Error("the parked question must be dropped, not left to eat the turn after this one")
}
}
// TestClarifyStillRetriesOnAnAnswerThatMissed — the other half of #554, and the
// reason the test above is narrow. A bare noun answers nothing either, but it
// carries no request of its own, so she asks again as before.
func TestClarifyStillRetriesOnAnAnswerThatMissed(t *testing.T) {
ctx := context.Background()
h, _, _ := newClarifyHandler(t)
if _, asked := h.askClarify(ctx, clarifyDec(router.IntentReminder, router.Slots{Text: "напомни позвонить маме"}, "напомни позвонить маме")); !asked {
t.Fatal("expected the time question")
}
reply, handled := h.resolveClarifyAnswer(ctx, "ага")
if !handled || reply == "" {
t.Fatalf("a missed answer must still be re-asked, handled=%v reply=%q", handled, reply)
}
if h.clarifyStore.Get(voiceDialogueID, h.now()) == nil {
t.Error("the question must survive a missed answer")
}
}
// TestClarifyQuestionShapedAnswerThatFillsTheGapStillLands — the guard runs only
// where nothing was filled. "во сколько?" is question-shaped and is also how a
// time gets said back, so an answer that closes the gap wins whatever its shape.
func TestClarifyQuestionShapedAnswerThatFillsTheGapStillLands(t *testing.T) {
ctx := context.Background()
h, st, _ := newClarifyHandler(t)
if _, asked := h.askClarify(ctx, clarifyDec(router.IntentReminder, router.Slots{Text: "напомни позвонить маме"}, "напомни позвонить маме")); !asked {
t.Fatal("expected the time question")
}
if reply, handled := h.resolveClarifyAnswer(ctx, "а что если в 11:00"); !handled || reply == clarifyGaveUp {
t.Fatalf("an answer that fills the gap must land, handled=%v reply=%q", handled, reply)
}
if reminders, err := st.DueReminders(ctx, h.now().Add(48*time.Hour)); err != nil || len(reminders) != 1 {
t.Fatalf("reminder was not created: reminders=%v err=%v", reminders, err)
}
}
// TestUnresolvedActSaysItDoesNotKnowTheCommand — Vikunja #556. "Что сделать?"
// has no answer he can give, so an act that matched no capability is refused in
// one line and nothing is parked. It does not recite what she can do instead.
func TestUnresolvedActSaysItDoesNotKnowTheCommand(t *testing.T) {
ctx := context.Background()
h, st, _ := newClarifyHandler(t)
// Enabled tools change nothing here: this act matched none of them.
if err := st.EnableTool(ctx, "uptime", []string{"true"}, false, "test", h.now()); err != nil {
t.Fatal(err)
}
reply, spoken := h.askClarify(ctx, clarifyDec(router.IntentAct, router.Slots{Text: "выключи свет"}, "выключи свет"))
if !spoken || reply != actNotRecognized {
t.Fatalf("reply = %q spoken=%v, want %q", reply, spoken, actNotRecognized)
}
if strings.Contains(reply, "uptime") {
t.Errorf("reply = %q, want no list of capabilities he did not ask about", reply)
}
if h.clarifyStore.Get(voiceDialogueID, h.now()) != nil {
t.Error("nothing to ask about, so nothing may be parked")
}
}
// newRoutingClarifyHandler wires the real cascade (hash embedder, no model) onto
// the clarify handler, so a test can drive handleText end to end and see which
// gate claimed the turn.
func newRoutingClarifyHandler(t *testing.T) (*reactiveHandler, *store.Store) {
t.Helper()
h, st, _ := newClarifyHandler(t)
h.router = buildRouter(router.NewHashEmbedder(1024), h.matcher, 0.55, nil)
h.recall = recallWiring{embedder: router.NewHashEmbedder(1024), memStore: memory.NewInMemoryStore()}
return h, st
}
// TestIncompleteReminderAsksInsteadOfFailing — Vikunja #557. "напомни позвонить"
// is routed confidently and is still half a request. It used to reach applyAction,
// fail on the missing time and park nothing, so the "в семь вечера" that followed
// was routed as a world question and web-searched.
func TestIncompleteReminderAsksInsteadOfFailing(t *testing.T) {
ctx := context.Background()
h, st := newRoutingClarifyHandler(t)
reply := h.handleText(ctx, "web", "напомни позвонить маме")
want, _ := clarifyQuestionFor(dialogue.SlotTime, 1)
if reply != want {
t.Fatalf("reply = %q, want the time question %q", reply, want)
}
if h.clarifyStore.Get(dialogueIDFor(sourceText, "web"), h.now()) == nil {
t.Fatal("the request must be parked, or the answer has nowhere to land")
}
if reply := h.handleText(ctx, "web", "в семь вечера"); strings.Contains(reply, "нашла") {
t.Fatalf("the answer to her own question must not be looked up: %q", reply)
}
if reminders, err := st.DueReminders(ctx, h.now().Add(48*time.Hour)); err != nil || len(reminders) != 1 {
t.Fatalf("the answer did not complete the reminder: reminders=%v err=%v", reminders, err)
}
}
// TestBareCaptureVerbAsksWhatToRecord — the other half of #557. A bare "запиши"
// went to the resident model as chat, which agreed to a wording change nobody
// asked for. It is a fact with no key, and that gap has a question.
func TestBareCaptureVerbAsksWhatToRecord(t *testing.T) {
ctx := context.Background()
h, _ := newRoutingClarifyHandler(t)
reply := h.handleText(ctx, "web", "запиши")
want, _ := clarifyQuestionFor(dialogue.SlotKey, 1)
if reply != want {
t.Fatalf("reply = %q, want %q", reply, want)
}
if h.clarifyStore.Get(dialogueIDFor(sourceText, "web"), h.now()) == nil {
t.Fatal("the request must be parked so the next utterance completes it")
}
}
// TestACompleteTurnStillDoesNotAsk — the gate reads a missing slot, not any
// slot, so a request she can act on must never turn into a question. Checked on
// the decision rather than through the cascade: what is at stake is the gate's
// condition, and driving it through the hash embedder would measure routing.
func TestACompleteTurnStillDoesNotAsk(t *testing.T) {
ctx := context.Background()
h, _, _ := newClarifyHandler(t)
complete := []router.Decision{
{Intent: router.IntentReminder, Slots: router.Slots{Text: "позвонить маме", HasTime: true}, Utterance: "напомни в 11 позвонить маме"},
{Intent: router.IntentFact, Slots: router.Slots{Key: "water", Value: "выпил", HasKey: true}, Utterance: "я выпил воды"},
{Intent: router.IntentNote, Slots: router.Slots{Text: "купить хлеб"}, Utterance: "запиши купить хлеб"},
{Intent: router.IntentQuery, Slots: router.Slots{Text: "что у меня сегодня"}, Utterance: "что у меня сегодня"},
}
for _, dec := range complete {
if gaps := missingFor(dec); len(gaps) > 0 {
t.Errorf("%q reads as incomplete: %v", dec.Utterance, gaps)
}
if reply, asked := h.askClarify(ctx, dec); asked {
t.Errorf("%q was answered with a question: %q", dec.Utterance, reply)
}
}
}
+14
View File
@@ -40,6 +40,9 @@ var clarifyQuestionVariants = map[dialogue.Slot][]string{
"Что именно отметить?",
"Назови, что записать — например, «выпил воды».",
},
// Not spoken since Vikunja #556: askClarify answers actNotRecognized for a
// missing capability rather than asking. Kept because clarifyQuestion still
// reports the gap, and a re-ask deck with a hole in it is harder to read.
dialogue.SlotFn: {
"Что сделать?",
"Какое действие выполнить?",
@@ -47,6 +50,17 @@ var clarifyQuestionVariants = map[dialogue.Slot][]string{
},
}
// actNotRecognized is what an act she cannot run gets (Vikunja #556).
//
// The deck used to ask "Что сделать?" instead. That question has no answer he
// can give: he already said what he wanted, and nothing he repeats will match a
// capability that is not there. So she asked, failed, asked again and gave up —
// three turns spent on one refusal. She says it once now, and parks nothing.
//
// It does not recite the allowlist. A list of names he did not ask about is not
// an answer to the thing he did ask about.
const actNotRecognized = "Такую команду я не знаю."
// clarifyQuestionFor picks the wording for this attempt. attempt is 1-based, as
// PendingQuestion.Attempts counts it; anything past the list uses the last and
// most explicit phrasing rather than wrapping round to the short one, because
+98 -21
View File
@@ -3,9 +3,13 @@ package main
import (
"context"
"log"
"slices"
"sort"
"strings"
"time"
"unicode"
"github.com/kami/maven/internal/lexicon"
"github.com/kami/maven/internal/phraser"
"github.com/kami/maven/internal/router"
)
@@ -57,10 +61,18 @@ func (h *reactiveHandler) park(fn string, args []string, phrase string) {
// resolveConfirm interprets an utterance as the answer to a parked destructive
// act OR a parked routine proposal. Returns (reply, true) when it consumed the
// utterance as a y/n answer; ("", false) when there's nothing pending (or the
// parked act expired), so the caller routes the utterance normally. An
// unrecognised answer cancels the pending and routes normally — a confirm that
// can't be answered clearly is safer abandoned than left armed.
// parked act expired), so the caller routes the utterance normally.
//
// An utterance that is not clearly yes or no is not an answer at all, so it is
// handed straight back and the pending stays parked until it expires (V-567).
// This resolver runs before routing and holds the most dangerous trigger on the
// box; it may only claim a turn it is certain about.
func (h *reactiveHandler) resolveConfirm(ctx context.Context, text string) (string, bool) {
verdict := classifyConfirm(text)
if verdict == confirmUnknown {
return "", false
}
h.mu.Lock()
defer h.mu.Unlock()
@@ -68,16 +80,12 @@ func (h *reactiveHandler) resolveConfirm(ctx context.Context, text string) (stri
if !r.claim() {
continue
}
// The slot is already cleared by claim(): every branch below drops the
// pending, including the unclear one — a confirm that can't be
// answered clearly is safer abandoned than left armed.
switch classifyConfirm(text) {
// The slot is already cleared by claim().
switch verdict {
case confirmYes:
return r.yes(), true
case confirmNo:
return r.no(), true
default:
return "", false
return r.no(), true
}
}
return "", false
@@ -194,23 +202,92 @@ const (
confirmNo
)
// classifyConfirm reads a short ru/en yes-or-no answer. Substring match on the
// stems so inflections/fillers ("да, давай", "нет, отмени") still land.
// confirmWords are the two closed sets, tokenized once and ordered
// longest-first so "не надо" is read before "нет" could claim any of it.
var (
confirmYesPhrases = confirmPhrases(lexicon.ConfirmYes())
confirmNoPhrases = confirmPhrases(lexicon.ConfirmNo())
)
// confirmPhrases splits each lexicon member into tokens and sorts the result
// longest-first, so a walk that tries them in order matches the longest member
// that fits.
func confirmPhrases(words []string) [][]string {
out := make([][]string, 0, len(words))
for _, w := range words {
if toks := confirmTokens(w); len(toks) > 0 {
out = append(out, toks)
}
}
sort.SliceStable(out, func(i, j int) bool { return len(out[i]) > len(out[j]) })
return out
}
// confirmTokens splits an utterance into lowercase word tokens. Punctuation and
// spacing are separators; an apostrophe is not, because "don't" is one word.
func confirmTokens(text string) []string {
return strings.FieldsFunc(strings.ToLower(text), func(r rune) bool {
if r == '\'' || r == '' {
return false
}
return !unicode.IsLetter(r) && !unicode.IsDigit(r)
})
}
// classifyConfirm reads a short ru/en yes-or-no answer to a parked confirm.
//
// The whole utterance must consist of confirmation words and filler, matched as
// whole tokens against the closed lexicon sets. Anything else is
// confirmUnknown, which leaves the confirm parked and routes the turn — see
// resolveConfirm. Both halves of that are the fix for V-567: this used to be a
// substring test over bare stems, so "погода", "дальше", "надо" and "давление"
// all read as "да", and "покажи" and "около" read as "ок". A parked destructive
// act fired on a question about the weather.
//
// Requiring the WHOLE utterance is the second half. A leading confirm word does
// not make a sentence an answer: "давай посмотрим погоду" opens a request, and
// the only safe reading of a sentence that carries its own subject is that he
// moved on. Guessing wrong here executes something; guessing wrong the other way
// asks again.
func classifyConfirm(text string) confirmVerdict {
t := strings.ToLower(strings.TrimSpace(text))
// negatives first — "не надо" contains no "да", but check no-stems before
// yes so a leading "нет" isn't shadowed.
for _, no := range []string{"нет", "не надо", "отмен", "стоп", "no", "cancel", "stop", "don't"} {
if strings.Contains(t, no) {
tokens := confirmTokens(text)
if len(tokens) == 0 {
return confirmUnknown
}
verdict := confirmUnknown
for i := 0; i < len(tokens); {
// Negatives first: "не надо" and "не хочу" open with a token that is
// not itself an answer, and a yes hit must never shadow them.
if n := matchConfirm(confirmNoPhrases, tokens[i:]); n > 0 {
return confirmNo
}
if n := matchConfirm(confirmYesPhrases, tokens[i:]); n > 0 {
verdict, i = confirmYes, i+n
continue
}
if lexicon.IsFillerParticle(tokens[i]) {
i++
continue
}
// A word that is neither an answer nor filler carries a subject of its
// own, so this utterance is not an answer to her question.
return confirmUnknown
}
for _, yes := range []string{"да", "ага", "давай", "подтвер", "конечно", "yes", "yeah", "yep", "confirm", "ок", "okay", "ok"} {
if strings.Contains(t, yes) {
return confirmYes
return verdict
}
// matchConfirm reports the length of the longest phrase matching at the head of
// tokens, or 0.
func matchConfirm(phrases [][]string, tokens []string) int {
for _, p := range phrases {
if len(p) > len(tokens) {
continue
}
if slices.Equal(p, tokens[:len(p)]) {
return len(p)
}
}
return confirmUnknown
return 0
}
// actPhrase renders "fn arg1 arg2" for the confirm prompt.
+103
View File
@@ -0,0 +1,103 @@
package main
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/kami/maven/internal/ipc"
"github.com/kami/maven/internal/tool"
)
// TestClassifyConfirmRejectsSubstrings — V-567. The old matcher tested bare
// stems with strings.Contains, so every word below answered a question she had
// asked about something else: "погода", "дальше", "надо" and "давление" carry
// "да"; "покажи", "около" and "окно" carry "ок". A parked destructive act fired
// on a question about the weather.
func TestClassifyConfirmRejectsSubstrings(t *testing.T) {
for _, text := range []string{
"погода",
"какая погода",
"что дальше",
"надо ещё",
"покажи заметки",
"около окна",
"давление",
"давай посмотрим погоду",
"не забудь купить хлеб",
"окно открыто",
"стоит ли брать зонт",
"",
} {
if got := classifyConfirm(text); got != confirmUnknown {
t.Errorf("classifyConfirm(%q) = %v, want confirmUnknown", text, got)
}
}
}
// TestClassifyConfirmAcceptsAnswers keeps every genuine answer the substring
// matcher accepted, and pins the pair the fix could most easily get wrong:
// "надо" is not an answer and "не надо" is the opposite of one.
func TestClassifyConfirmAcceptsAnswers(t *testing.T) {
yes := []string{"да", "Да!", "ага", "давай", "да, давай", "конечно", "подтверждаю", "ну да", "yes", "yeah", "ok", "okay", "confirm"}
no := []string{"нет", "Нет.", "не надо", "не нужно", "не сейчас", "отмена", "отмени", "стоп", "нет, отмени", "no", "nope", "cancel", "stop", "don't"}
for _, text := range yes {
if got := classifyConfirm(text); got != confirmYes {
t.Errorf("classifyConfirm(%q) = %v, want confirmYes", text, got)
}
}
for _, text := range no {
if got := classifyConfirm(text); got != confirmNo {
t.Errorf("classifyConfirm(%q) = %v, want confirmNo", text, got)
}
}
}
// TestUnrelatedTurnLeavesConfirmParked — the whole point of V-567. An utterance
// that is not an answer must not execute the parked act, must not consume the
// turn, and must not disarm the confirm either: the answer he has not given yet
// is still answerable until it expires.
func TestUnrelatedTurnLeavesConfirmParked(t *testing.T) {
ctx := context.Background()
st := newTestStore(t)
api := ipc.NewStoreAPI(st)
now := time.Date(2026, 8, 6, 9, 0, 0, 0, time.UTC)
h := &reactiveHandler{
api: api,
dataStore: st,
now: func() time.Time { return now },
tools: tool.NewExecutor(api, time.Second),
}
marker := filepath.Join(t.TempDir(), "destructive-tool-ran")
if err := st.EnableTool(ctx, "delete_backups", []string{"touch", marker}, true, "test", h.now()); err != nil {
t.Fatal(err)
}
h.park("delete_backups", nil, "delete_backups")
if reply, handled := h.resolveConfirm(ctx, "какая погода"); handled {
t.Fatalf("the weather question was consumed as a confirm: %q", reply)
}
if _, err := os.Stat(marker); !os.IsNotExist(err) {
t.Fatalf("the parked destructive command ran on an unrelated turn: %v", err)
}
if h.pending == nil {
t.Fatal("the confirm was disarmed by a turn that did not answer it")
}
// It is still answerable, and answering it still runs the act.
reply, handled := h.resolveConfirm(ctx, "да")
if !handled || !strings.Contains(reply, "готово") {
t.Fatalf("the still-parked confirm did not resolve: handled=%v reply=%q", handled, reply)
}
if _, err := os.Stat(marker); err != nil {
t.Fatalf("confirmed destructive command did not run: %v", err)
}
if h.pending != nil {
t.Fatal("the confirm stayed parked after being answered")
}
}
+132
View File
@@ -0,0 +1,132 @@
// mavend/decisiontrace.go — the daemon's half of the per-turn decision record.
//
// V-564. The router says what the cascade did (internal/router/decisiontrace.go);
// this file covers the two claimant sets that live in the daemon: the stateful
// resolvers that run BEFORE routing and pre-empt it unconditionally, and the
// query source chain that runs after. Those two are where the arbitration is
// least visible, because both are a hardcoded order of functions that each
// answer "is this mine?" alone and none of which answers "is this more mine
// than yours?" (V-558).
//
// Recording changes no route. Every helper here is a no-op on a context with no
// record, which is what every test that does not ask for one gets.
package main
import (
"context"
"github.com/kami/maven/internal/decision"
"github.com/kami/maven/internal/ipc"
"github.com/kami/maven/internal/router"
)
// preRouteLadder — the resolvers runTurn offers the utterance to before the
// router sees it, in the order they get their say. Kept here as a roster rather
// than derived from the code, so a resolver that returns early and skips the
// rest still leaves the rest NAMED in the record: a claimant that never looked
// and one that looked and passed are the distinction the ordering hides, and
// they are the difference between a bug in the ladder and a bug in a resolver.
//
// Adding a step to runTurn means adding its name here. Nothing enforces that,
// 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",
}
// notePreRoute records one rung of that ladder and passes its verdict through
// unchanged, so the call site stays the single `if handled` it already was.
func notePreRoute(ctx context.Context, name string, handled bool) bool {
rec := decision.From(ctx)
if rec == nil {
return handled
}
if handled {
rec.Note(decision.Claim{
Stage: decision.StagePreRoute, Claimant: name, Outcome: decision.Won,
Reason: "it pre-empted routing, so the router never saw this turn",
})
return handled
}
rec.Note(decision.Claim{
Stage: decision.StagePreRoute, Claimant: name, Outcome: decision.Declined,
Reason: "nothing of its own was pending",
})
return handled
}
// noteTerminal records whoever actually produced the reply, but only if the
// turn is still unclaimed. A route decides the intent; it does not answer, and
// on a thinned route or a plain act nothing downstream keeps a scoreboard. So
// the record would otherwise close with an empty winner, which reads as a lost
// turn instead of an asked question.
func noteTerminal(ctx context.Context, claimant string, intent router.Intent, reason string) {
decision.From(ctx).NoteIfUnclaimed(decision.Claim{
Stage: decision.StageAction, Claimant: claimant,
Intent: string(intent), Reason: reason,
})
}
// noteMerge records the follow-up merge, which is the one claimant that edits
// the winning decision instead of taking the turn from it. It is compared on
// the four slots the merge can fill, because a Decision holds a slice and is
// not comparable.
func noteMerge(ctx context.Context, before, after router.Decision) {
rec := decision.From(ctx)
if rec == nil {
return
}
changed := before.Slots.HasTime != after.Slots.HasTime ||
before.Slots.HasKey != after.Slots.HasKey ||
before.Slots.HasFn != after.Slots.HasFn ||
before.Slots.Text != after.Slots.Text ||
before.Intent != after.Intent
if !changed {
rec.Note(decision.Claim{
Stage: decision.StageMerge, Claimant: "follow-up-merge", Outcome: decision.Declined,
Reason: "no slot of this turn was left for a previous one to fill",
})
return
}
rec.Note(decision.Claim{
Stage: decision.StageMerge, Claimant: "follow-up-merge", Intent: string(after.Intent),
Outcome: decision.Merged, Reason: "filled this turn's gaps from the previous turn",
})
}
// turnDecisionsFn — the reader mavweb gets, or nil when voice was never wired.
// Same shape as intakeEventsFn: the daemon holds the ring, the IPC layer only
// converts it.
func turnDecisionsFn(w *voiceWiring) func(int) []ipc.TurnDecision {
if w == nil || w.handler == nil || w.handler.decisions == nil {
return nil
}
ring := w.handler.decisions
return func(n int) []ipc.TurnDecision {
recs := ring.Recent(n)
out := make([]ipc.TurnDecision, 0, len(recs))
for _, rec := range recs {
claims := make([]ipc.TurnClaim, 0, len(rec.Claims))
for _, c := range rec.Claims {
claims = append(claims, ipc.TurnClaim{
Stage: c.Stage, Claimant: c.Claimant, Intent: c.Intent,
Score: c.Score, HasScore: c.HasScore,
Outcome: c.Outcome, Reason: c.Reason,
})
}
out = append(out, ipc.TurnDecision{
Ts: rec.Ts, Utterance: rec.Utterance, Winner: rec.Winner, Claims: claims,
})
}
return out
}
}
// querySourceNames — the query chain's roster, in chain order.
func querySourceNames() []string {
names := make([]string, len(querySources))
for i, src := range querySources {
names[i] = src.name
}
return names
}
+163
View File
@@ -0,0 +1,163 @@
package main
import (
"context"
"strings"
"testing"
"time"
"github.com/kami/maven/internal/decision"
"github.com/kami/maven/internal/ipc"
"github.com/kami/maven/internal/memory"
"github.com/kami/maven/internal/router"
"github.com/kami/maven/internal/tool"
"github.com/kami/maven/internal/voice"
)
// traceHandler — a handler with the decision ring wired, the same shape the
// daemon builds in wireVoice.
func traceHandler(t *testing.T, ring *decision.Ring) *reactiveHandler {
t.Helper()
st := newTestStore(t)
api := ipc.NewStoreAPI(st)
now := time.Now()
emb := router.NewHashEmbedder(1024)
return &reactiveHandler{
api: api,
recall: recallWiring{embedder: emb, memStore: memory.NewInMemoryStore()},
router: buildRouter(emb, tool.NewMatcher(api), 0.55, nil),
replier: voice.NewStubReplier(),
now: func() time.Time { return now },
dataStore: st,
decisions: ring,
}
}
// findClaim — the first claim for a claimant, or nil.
func findClaim(rec *decision.Record, claimant string) *decision.Claim {
for i := range rec.Claims {
if rec.Claims[i].Claimant == claimant {
return &rec.Claims[i]
}
}
return nil
}
// TestTurnRecordNamesWinnerAndLosers — the point of V-564. A turn a stage-0
// grammar claims must leave a record naming that grammar as the winner, naming
// a pre-route resolver that declined, and naming the routing engines that were
// never reached at all. The last of those is the fact the hardcoded ordering
// hides: "classifier" absent from the record and "classifier" never asked read
// the same to a human, and only one of them is the truth.
func TestTurnRecordNamesWinnerAndLosers(t *testing.T) {
ring := decision.NewRing()
h := traceHandler(t, ring)
reply := h.handleText(context.Background(), "web", "сколько сейчас времени")
if reply == "" {
t.Fatal("turn produced no reply")
}
recs := ring.Recent(5)
if len(recs) != 1 {
t.Fatalf("want 1 record, got %d", len(recs))
}
rec := recs[0]
if rec.Utterance != "сколько сейчас времени" {
t.Errorf("utterance = %q", rec.Utterance)
}
if !strings.HasPrefix(rec.Winner, "stage0:") {
t.Errorf("want a stage-0 grammar as the winner, got %q", rec.Winner)
}
// A loser that examined the turn: the confirm resolver ran first and had
// nothing pending.
confirm := findClaim(rec, "confirm")
if confirm == nil || confirm.Outcome != decision.Declined {
t.Errorf("confirm claim = %+v, want a decline", confirm)
}
// A loser that never looked: stage 0 answered, so neither routing engine
// was reached.
for _, name := range []string{"llm-router", "classifier"} {
c := findClaim(rec, name)
if c != nil && c.Outcome == decision.Won {
t.Errorf("%s cannot have won a stage-0 turn: %+v", name, c)
}
}
// And every rung of the ladder below the winner is named, not omitted.
for _, name := range preRouteLadder {
if findClaim(rec, name) == nil {
t.Errorf("ladder rung %q is missing from the record", name)
}
}
}
// TestRecordingDoesNotChangeTheReply — instrumentation, so a turn with the ring
// wired and the same turn without it must answer identically. If this ever
// fails, a claim site is doing more than noting.
func TestRecordingDoesNotChangeTheReply(t *testing.T) {
for _, utt := range []string{
"сколько сейчас времени",
"запиши что я пил воду",
"что у меня сегодня",
} {
withRing := traceHandler(t, decision.NewRing()).handleText(context.Background(), "web", utt)
without := traceHandler(t, nil).handleText(context.Background(), "web", utt)
if withRing != without {
t.Errorf("%q: recorded reply %q != unrecorded %q", utt, withRing, without)
}
}
}
// TestQueryChainRecordsWhoWasNeverAsked — a query source below the claimant is
// never consulted, and the record must say so rather than leave it out. This is
// the arm that would have explained the Rome misroute in one read.
func TestQueryChainRecordsWhoWasNeverAsked(t *testing.T) {
ring := decision.NewRing()
h := traceHandler(t, ring)
h.handleText(context.Background(), "web", "что у меня сегодня")
rec := ring.Recent(1)[0]
var asked, never int
for _, c := range rec.Claims {
if c.Stage != decision.StageQuery {
continue
}
if c.Outcome == decision.NeverAsked {
never++
} else {
asked++
}
}
if asked == 0 {
t.Fatal("no query source reported at all")
}
if never == 0 {
t.Fatal("no query source was recorded as never asked; the chain cannot have run to the end")
}
if got := len(querySourceNames()); asked+never != got {
t.Errorf("record covers %d of %d query sources", asked+never, got)
}
}
// TestTurnDecisionsFnConvertsTheRing — the IPC read path. Nil when voice was
// never wired, because a box with no turns is an empty page and not an error.
func TestTurnDecisionsFnConvertsTheRing(t *testing.T) {
if fn := turnDecisionsFn(nil); fn != nil {
t.Error("no wiring should mean no reader")
}
ring := decision.NewRing()
h := traceHandler(t, ring)
h.handleText(context.Background(), "web", "сколько сейчас времени")
fn := turnDecisionsFn(&voiceWiring{handler: h})
if fn == nil {
t.Fatal("wired handler produced no reader")
}
out := fn(10)
if len(out) != 1 || out[0].Winner == "" || len(out[0].Claims) == 0 {
t.Fatalf("conversion lost the record: %+v", out)
}
}
+556
View File
@@ -0,0 +1,556 @@
package main
import (
"bytes"
"context"
"log"
"os"
"strings"
"testing"
"time"
"github.com/kami/maven/internal/dialogue"
"github.com/kami/maven/internal/memory"
"github.com/kami/maven/internal/router"
"github.com/kami/maven/internal/store"
)
// Dialogue contract tests (V-563, child of V-558).
//
// Every other clarify test is single-shot: one ask, one answer, one assertion.
// Three bugs of the same family shipped in two days that way — V-554 (a parked
// question ate the three turns after it), V-557 (a confidently routed but
// incomplete reminder parked nothing, so the answer was web-searched) and the
// Rome case in V-558 (a side question was eaten as the time answer). None of
// them is visible in one turn. The dialogue path is a state machine, so it can
// be enumerated instead: whole traces, each with a per-turn expectation and an
// expected END state — what was written to the store, and what is still parked.
//
// Two rules for the rows below.
//
// Where today's behaviour is correct, it is asserted. Where it is WRONG, the row
// carries the CORRECT expectation and is skipped with the Vikunja id that will
// unskip it. A weakened expectation would be worse than no row: it would pin the
// bug as the contract.
//
// Everything runs on the offline floor — hash embedder, no llama-server, no
// ONNX, StubDateTimeParser. That has one consequence worth knowing before
// reading a fire time here: the stub reads "в 11:00" and "через час" and does
// not read "на 9" or "на завтра", so a trace that needs those is noted where it
// sits.
// claim — which claimant consumed an utterance. Not asserted: it is derived from
// the log lines the daemon already emits and printed on every failure, because
// "the reply differed" does not distinguish a wrong claimant from wrong copy,
// and that distinction is the whole point of V-558.
type claim struct {
utterance string
steps []string
}
func (c claim) String() string { return c.utterance + " ⇒ " + strings.Join(c.steps, " → ") }
// claimMarkers — log fragment to claimant name, in the order runTurn checks
// them. The fragments are the daemon's own words (clarify.go, repair.go,
// voice.go); a rename there shows up here as an "unclaimed" step rather than a
// silent mislabel.
var claimMarkers = []struct{ fragment, name string }{
{"parked question expired", "clarify:expired"},
{"is its own request", "clarify:stepped-aside"},
{"gave up on", "clarify:gave-up"},
{"did not fill", "clarify:re-ask"},
{"one gap filled", "clarify:ask-second-gap"},
{"asked about", "clarify:ask"},
{"repair —", "repair"},
{"route result: intent=", "route"},
}
// claimsOf reads the turn's log output and names the claimants that touched it.
func claimsOf(utterance, logged string) claim {
c := claim{utterance: utterance}
for _, line := range strings.Split(logged, "\n") {
for _, m := range claimMarkers {
if strings.Contains(line, m.fragment) {
name := m.name
if m.name == "route" {
name = "route:" + intentInLine(line)
}
c.steps = append(c.steps, name)
break
}
}
}
if len(c.steps) == 0 {
c.steps = []string{"unclaimed"}
}
return c
}
func intentInLine(line string) string {
_, rest, ok := strings.Cut(line, "intent=")
if !ok {
return "?"
}
intent, _, _ := strings.Cut(rest, " ")
return intent
}
// parkedWant — the question that must be armed after a turn. Attempt matters:
// a claimant that spends a retry on an utterance that was never an answer is
// exactly the V-554 shape, and the count is the only place it shows.
type parkedWant struct {
slot dialogue.Slot
attempt int
// carries — a substring the parked utterance must still hold, so a re-park
// that lost the answered subject fails here rather than three turns later.
carries string
}
// turn — one utterance and everything that must be true right after it.
type turn struct {
say string
// wait — the clock moves this far BEFORE the utterance. The only way to
// reach the TTL without sleeping.
wait time.Duration
// question — the reply must be exactly this clarify question, worded for
// this attempt. Zero slot ⇒ not checked.
question dialogue.Slot
attempt int
contains []string
notContain []string
// noQuestion — the reply must not be any clarify question. Used where the
// correct behaviour is known but her wording for it is not written yet: a
// cancel must not be answered with another question, whatever it does say.
noQuestion bool
expired bool // the reply must open with the TTL notice
// parked — what is armed after the turn. nil ⇒ nothing may be armed.
parked *parkedWant
}
// endState — what the store holds once the trace is over. Counts and
// substrings, not rows: a trace is about who claimed what, and a payload
// substring is enough to catch a request landing under the wrong words.
type endState struct {
reminders []reminderWant
factKeys []string
notes int
tasks []string
}
type reminderWant struct {
payload string // substring of the stored payload
fireAt string // "2006-01-02 15:04" in UTC, "" ⇒ not checked
}
// trace — a named conversation, its turns, and the end state.
type trace struct {
name string
skip string // non-empty ⇒ t.Skip: today's behaviour is wrong, this names the fix
turns []turn
end endState
}
// newDialogueHandler — the offline floor with the real cascade and a movable
// clock: newClarifyHandler's wiring (stub date parser, real fact parser, tool
// matcher) plus the router newRoutingClarifyHandler builds, and the `now`
// pointer so a turn can carry a wait.
func newDialogueHandler(t *testing.T) (*reactiveHandler, *store.Store, *time.Time) {
t.Helper()
h, st, now := newClarifyHandler(t)
h.router = buildRouter(router.NewHashEmbedder(1024), h.matcher, 0.55, nil)
h.recall = recallWiring{embedder: router.NewHashEmbedder(1024), memStore: memory.NewInMemoryStore()}
return h, st, now
}
// runTrace drives one trace through handleText and checks every turn, then the
// end state. Every failure carries the decision trace so far, so a wrong
// claimant reads differently from wrong copy.
func runTrace(t *testing.T, tr trace) {
t.Helper()
// MAVEN_DIALOGUE_NO_SKIP=1 runs the rows that fail today. That is how
// whoever lands V-560, V-561 or V-562 sees their row go green before
// deleting its skip, and it is also the check that a skip is still earned:
// a row that passes with the skip in place is a fix nobody noticed.
if tr.skip != "" && os.Getenv("MAVEN_DIALOGUE_NO_SKIP") == "" {
t.Skip(tr.skip)
}
ctx := context.Background()
h, st, now := newDialogueHandler(t)
const conversation = "web"
id := dialogueIDFor(sourceText, conversation)
var claims []claim
fail := func(turnIdx int, format string, args ...any) {
t.Helper()
lines := make([]string, 0, len(claims))
for _, c := range claims {
lines = append(lines, " "+c.String())
}
t.Fatalf("turn %d: "+format+"\n who claimed what:\n%s",
append([]any{turnIdx}, append(args, strings.Join(lines, "\n"))...)...)
}
for i, tn := range tr.turns {
if tn.wait > 0 {
*now = now.Add(tn.wait)
}
var logged bytes.Buffer
prev := log.Writer()
log.SetOutput(&logged)
reply := h.handleText(ctx, conversation, tn.say)
log.SetOutput(prev)
claims = append(claims, claimsOf(tn.say, logged.String()))
body := reply
if tn.expired {
if !isClarifyExpired(reply) {
fail(i, "reply %q must open with the expiry notice", reply)
}
body = trimClarifyExpired(reply)
// The notice is glued in front of this turn's reply, and both halves
// have to survive: the words he just said are routed fresh, and
// answering only "I let the old one go" drops them.
if body == "" {
fail(i, "the notice was the whole reply; the fresh words were never answered")
}
} else if isClarifyExpired(reply) {
fail(i, "reply %q announced an expiry nothing asked for", reply)
}
if tn.question != "" {
want, ok := clarifyQuestionFor(tn.question, tn.attempt)
if !ok {
fail(i, "no question exists for slot %s attempt %d", tn.question, tn.attempt)
}
if body != want {
fail(i, "reply %q, want the %s question worded for attempt %d, %q", body, tn.question, tn.attempt, want)
}
}
if tn.noQuestion && isAnyClarifyQuestion(body) {
fail(i, "reply %q is another question; this turn is not something to ask about", body)
}
for _, want := range tn.contains {
if !strings.Contains(body, want) {
fail(i, "reply %q does not carry %q", body, want)
}
}
for _, unwanted := range tn.notContain {
if strings.Contains(body, unwanted) {
fail(i, "reply %q carries %q and must not", body, unwanted)
}
}
checkParked(t, fail, i, h.clarifyStore.Get(id, h.now()), tn.parked)
}
checkEnd(t, ctx, st, h, tr.end, claims)
}
// isAnyClarifyQuestion — is this reply one of her clarify questions, at any
// attempt wording? Reads the templates rather than a list of its own.
func isAnyClarifyQuestion(reply string) bool {
for _, variants := range clarifyQuestionVariants {
for _, v := range variants {
if reply == v {
return true
}
}
}
return false
}
func checkParked(t *testing.T, fail func(int, string, ...any), i int, got *dialogue.PendingQuestion, want *parkedWant) {
t.Helper()
if want == nil {
if got != nil {
fail(i, "a question about %v is still armed and nothing should be: %+v", got.Missing, got.Slots)
}
return
}
if got == nil {
fail(i, "nothing is armed, want a question about %s (attempt %d)", want.slot, want.attempt)
return
}
if len(got.Missing) != 1 || got.Missing[0] != want.slot {
fail(i, "armed question is about %v, want %s", got.Missing, want.slot)
}
if got.Attempts != want.attempt {
fail(i, "armed question is on attempt %d, want %d — a retry spent on something that was never an answer is the V-554 shape", got.Attempts, want.attempt)
}
if want.carries != "" && !strings.Contains(got.Utterance, want.carries) {
fail(i, "the parked request no longer carries %q: %q", want.carries, got.Utterance)
}
}
func checkEnd(t *testing.T, ctx context.Context, st *store.Store, h *reactiveHandler, want endState, claims []claim) {
t.Helper()
lines := make([]string, 0, len(claims))
for _, c := range claims {
lines = append(lines, " "+c.String())
}
trace := "\n who claimed what:\n" + strings.Join(lines, "\n")
reminders, err := st.DueReminders(ctx, h.now().Add(14*24*time.Hour))
if err != nil {
t.Fatalf("DueReminders: %v", err)
}
if len(reminders) != len(want.reminders) {
t.Fatalf("end state: %d reminder(s), want %d: %+v%s", len(reminders), len(want.reminders), reminders, trace)
}
for i, w := range want.reminders {
if !strings.Contains(reminders[i].Payload, w.payload) {
t.Fatalf("end state: reminder %d payload %q does not carry %q%s", i, reminders[i].Payload, w.payload, trace)
}
if w.fireAt != "" {
if got := reminders[i].FireTs.UTC().Format("2006-01-02 15:04"); got != w.fireAt {
t.Fatalf("end state: reminder %d fires at %s, want %s%s", i, got, w.fireAt, trace)
}
}
}
facts, err := st.RecentFacts(ctx, 20)
if err != nil {
t.Fatalf("RecentFacts: %v", err)
}
if len(facts) != len(want.factKeys) {
t.Fatalf("end state: %d fact(s), want %d: %+v%s", len(facts), len(want.factKeys), facts, trace)
}
for i, key := range want.factKeys {
if facts[i].Key != key {
t.Fatalf("end state: fact %d is %q, want %q%s", i, facts[i].Key, key, trace)
}
}
notes, err := st.RecentNotes(ctx, 20)
if err != nil {
t.Fatalf("RecentNotes: %v", err)
}
if len(notes) != want.notes {
t.Fatalf("end state: %d note(s), want %d%s", len(notes), want.notes, trace)
}
tasks, err := st.ListTasks(ctx, store.TaskOpen)
if err != nil {
t.Fatalf("ListTasks: %v", err)
}
if len(tasks) != len(want.tasks) {
t.Fatalf("end state: %d open task(s), want %d: %+v%s", len(tasks), len(want.tasks), tasks, trace)
}
for i, text := range want.tasks {
if !strings.Contains(tasks[i].Text, text) {
t.Fatalf("end state: task %d is %q, want it to carry %q%s", i, tasks[i].Text, text, trace)
}
}
}
func TestDialogueTraces(t *testing.T) {
for _, tr := range dialogueTraces() {
tr := tr
t.Run(tr.name, func(t *testing.T) { runTrace(t, tr) })
}
}
// dialogueTraces — the fixture. Order is the order the shapes were found, not a
// dependency: each trace builds its own handler and store.
func dialogueTraces() []trace {
return []trace{
// The plain two-turn shape, and the one every other row is a deviation
// from: she asks for the time, he gives it, the reminder lands with the
// subject he said in the FIRST turn.
{
name: "reminder completed over two turns",
turns: []turn{
{say: "напомни позвонить маме", question: dialogue.SlotTime, attempt: 1,
parked: &parkedWant{slot: dialogue.SlotTime, attempt: 1, carries: "маме"}},
{say: "в 11:00", contains: []string{"11:00"}, notContain: []string{"?"}},
},
end: endState{reminders: []reminderWant{{payload: "позвонить маме", fireAt: "2026-07-31 11:00"}}},
},
// The same shape on the fact path, where the answer carries both halves
// of what was missing — the key and the value — in one breath.
{
name: "fact completed over two turns",
turns: []turn{
{say: "запиши", question: dialogue.SlotKey, attempt: 1,
parked: &parkedWant{slot: dialogue.SlotKey, attempt: 1}},
{say: "пил воду", contains: []string{"water"}},
},
end: endState{factKeys: []string{"water"}},
},
// An answer past the TTL is a new request, not an answer (V-385). She
// says the old one is gone and routes the words fresh. A bare time on
// its own carries no request, so the fresh routing lands on the canned
// reply — the point of the row is that NOTHING is created: a reminder
// here would fire with the subject of a request she had already let go.
{
name: "answer arrives after the TTL",
turns: []turn{
{say: "напомни позвонить маме", question: dialogue.SlotTime, attempt: 1,
parked: &parkedWant{slot: dialogue.SlotTime, attempt: 1}},
{say: "в 11:00", wait: clarifyTTL + time.Second, expired: true},
},
end: endState{},
},
// Three questions is the budget, and running out is SPOKEN: a mute
// give-up reads as "done" and he would wait for a reminder that was
// never set. The wording changes with the attempt (V-457).
{
name: "three unclear answers then the give-up line",
turns: []turn{
{say: "напомни позвонить маме", question: dialogue.SlotTime, attempt: 1,
parked: &parkedWant{slot: dialogue.SlotTime, attempt: 1}},
{say: "ну не знаю", question: dialogue.SlotTime, attempt: 2,
parked: &parkedWant{slot: dialogue.SlotTime, attempt: 2}},
{say: "ну не знаю", question: dialogue.SlotTime, attempt: 3,
parked: &parkedWant{slot: dialogue.SlotTime, attempt: 3}},
{say: "ну не знаю", contains: []string{clarifyGaveUp}, noQuestion: true},
},
end: endState{},
},
// A correction points at the previous ACTED turn (repair.go): she redoes
// it under the intent he names and says so out loud, because a
// correction he cannot see is indistinguishable from one that was
// dropped. The task she filed first stays filed — repair redoes, it does
// not retract, and V-455 decided that deliberately.
//
// The corrected-to intent has to differ from the one she used, or repair
// declines: teaching the classifier the label it already produced is
// worse than doing nothing.
{
name: "correction of the previous turn",
turns: []turn{
{say: "добавь в задачи купить молоко", contains: []string{"купить молоко"}},
{say: "нет, это был вопрос", contains: []string{"поняла, это вопрос"}},
},
end: endState{tasks: []string{"купить молоко"}},
},
// He walks away from his own request: a question is parked, the next
// utterance is an unrelated request of its own, and nothing follows.
// V-554's fix is what makes this row pass — the question steps aside
// rather than scoring "добавь в задачи" as the time. The reminder is
// dropped in silence and that is the decision: if he meant it he says it
// again, and a question left armed eats the turn after next.
{
name: "abandoned flow: parked, then an unrelated request",
turns: []turn{
{say: "напомни позвонить маме", question: dialogue.SlotTime, attempt: 1,
parked: &parkedWant{slot: dialogue.SlotTime, attempt: 1}},
{say: "добавь в задачи купить молоко", contains: []string{"купить молоко"}},
{say: "спасибо"},
},
end: endState{tasks: []string{"купить молоко"}},
},
// ---- rows below carry the CORRECT expectation and fail today ----
// The owner's target transcript, V-561. He asks for a reminder, she asks
// when, he asks something else entirely, and then comes back to her
// question. On the box this created a reminder at 00:12 and never
// answered Rome; on the offline floor the side question is recognised as
// its own request and the flow is dropped instead, so the wrong reminder
// is not made and the right one is not either.
//
// Both are the same defect: there is no suspend and resume. The correct
// shape is the middle turn answered on its own and the parked question
// still standing, on the same attempt — a side query is not a failed
// answer and must not spend a retry.
//
// Unskipping this needs more than V-561. "на 9" and "на завтра" are not
// read by StubDateTimeParser, which is what the offline floor runs, so
// the row below it is the same shape in words the floor can parse and is
// the one to watch first.
{
name: "the owner's transcript from V-561",
skip: "V-561: a parked question is not suspended for a side query and never resumes",
turns: []turn{
{say: "напомни позвонить маме", question: dialogue.SlotTime, attempt: 1,
parked: &parkedWant{slot: dialogue.SlotTime, attempt: 1}},
{say: "какая сейчас погода в Риме?",
parked: &parkedWant{slot: dialogue.SlotTime, attempt: 1, carries: "маме"}},
{say: "а, да, прости - на 9.",
parked: &parkedWant{slot: dialogue.SlotTime, attempt: 1, carries: "маме"}},
{say: "на завтра."},
},
end: endState{reminders: []reminderWant{{payload: "позвонить маме", fireAt: "2026-08-01 09:00"}}},
},
// The same shape said in words StubDateTimeParser reads, so this row
// turns green on V-561 alone. Same three claims: Rome is answered, the
// question survives the side query on the same attempt, and the answer
// after it completes the reminder he actually asked for.
{
name: "nested question: a parked question, then one of his own",
skip: "V-561: a side query drops the parked question instead of suspending it",
turns: []turn{
{say: "напомни позвонить маме", question: dialogue.SlotTime, attempt: 1,
parked: &parkedWant{slot: dialogue.SlotTime, attempt: 1}},
{say: "какая сейчас погода в Риме?",
parked: &parkedWant{slot: dialogue.SlotTime, attempt: 1, carries: "маме"}},
{say: "в 11:00", contains: []string{"11:00"}},
},
end: endState{reminders: []reminderWant{{payload: "позвонить маме", fireAt: "2026-07-31 11:00"}}},
},
// A cancel is one of the five turn roles V-560 names, and today it is
// none of them: "неважно" fills no slot and carries no request of its
// own, so it reads as a failed answer and spends a retry. Two turns
// later she is still asking about a reminder he called off.
//
// The row asserts what is knowable — nothing armed, nothing written, and
// not another question — rather than her wording for it, which is not
// written yet and is not this task's to invent.
{
name: "cancel: a parked question, then never mind",
skip: "V-560: a cancel is scored as a failed answer, not as a cancel",
turns: []turn{
{say: "напомни позвонить маме", question: dialogue.SlotTime, attempt: 1,
parked: &parkedWant{slot: dialogue.SlotTime, attempt: 1}},
{say: "неважно", noQuestion: true},
},
end: endState{},
},
// Order in runTurn is the whole arbitration (V-558), and this is what it
// costs: the clarify answer is checked at step 3 and the repair marker at
// step 4d, so while a question is parked no correction can be made. She
// scores "нет, это была заметка" as a bad time answer and asks again.
{
name: "correction while a question is parked",
skip: "V-560: clarify pre-empts the repair marker, so a correction cannot be spoken mid-flow",
turns: []turn{
{say: "добавь в задачи купить молоко", contains: []string{"купить молоко"}},
{say: "напомни позвонить маме", question: dialogue.SlotTime, attempt: 1,
parked: &parkedWant{slot: dialogue.SlotTime, attempt: 1}},
{say: "нет, это был вопрос", contains: []string{"поняла, это вопрос"},
parked: &parkedWant{slot: dialogue.SlotTime, attempt: 1, carries: "маме"}},
},
end: endState{tasks: []string{"купить молоко"}},
},
// A reminder said whole, in one breath, with the hour in it — and she
// asks when. ReminderGrammar (stage0.go) builds its slots by hand and
// never runs the extractor, so a stage-0 reminder carries no time
// whatever the sentence says, and the clarify gate reads the gap as
// real. It costs a turn on the commonest reminder shape there is.
//
// Hermetic despite the date parser: stage 0 calls no parser at all, so
// this fails the same way with or without python dateparser installed.
{
name: "a reminder said whole is not asked about",
skip: "V-562: a stage-0 decision never meets the extractor, so its slots are never validated",
turns: []turn{
{say: "напомни в 11:00 позвонить маме", contains: []string{"11:00"}, noQuestion: true},
},
end: endState{reminders: []reminderWant{{payload: "позвонить маме", fireAt: "2026-07-31 11:00"}}},
},
// The same gap on the repair path. A correction redoes the request
// through finishClarified, which goes straight to applyAction — it never
// passes the clarify gate — so a redo that lands short answers with the
// parse error V-557 removed from the routing path: "не поняла, на когда
// напомнить." She should ask, exactly as she does for a fresh reminder
// with no time.
{
name: "a correction that lands short asks rather than failing",
skip: "V-562: finishClarified skips the clarify gate, so a repaired decision is never checked for gaps",
turns: []turn{
{say: "добавь в задачи купить молоко", contains: []string{"купить молоко"}},
{say: "нет, это было напоминание", contains: []string{"поняла, это напоминание"},
parked: &parkedWant{slot: dialogue.SlotTime, attempt: 1}},
},
end: endState{tasks: []string{"купить молоко"}},
},
}
}
+40 -7
View File
@@ -54,30 +54,56 @@ var historyMarkersEn = [][2]string{
// answers a topic far better than a list of the last five facts does.
var historyRecall = []string{" про ", " об ", " о ", " about "}
// historySide — whose turn the question asks about. The rows read are the same
// either way, because a tapped fact is one act seen from two sides, but the
// sentence is not: answering "что ты записала сегодня?" with "ты говорил…"
// hands the question back instead of answering it (Vikunja #456).
type historySide int
const (
historyAskedHim historySide = iota // "что я тебе говорил"
historyAskedHer // "что ты записала сегодня"
)
// isHistoryQuery reports whether he is asking what he told her.
func isHistoryQuery(u string) bool {
_, ok := historyAsks(u)
return ok
}
// historyAsks reports whether this is a history question, and whose turn it is
// about.
func historyAsks(u string) (historySide, bool) {
s := " " + strings.ToLower(strings.TrimSpace(u)) + " "
if s == " " {
return false
return historyAskedHim, false
}
for _, r := range historyRecall {
if strings.Contains(s, r) {
return false
return historyAskedHim, false
}
}
for _, pair := range historyMarkersEn {
if strings.Contains(s, pair[0]) && strings.Contains(s, pair[1]) {
return true
if strings.Contains(pair[0], "you") {
return historyAskedHer, true
}
return historyAskedHim, true
}
}
toks := historyTokens(s)
if !hasAny(toks, "что", "чего") {
return false
return historyAskedHim, false
}
// His side is tested first: "отмечать" is on both verb lists, so "что я
// отметил" must not read as a question about her.
if hasAny(toks, firstPersonSubjects...) && hasVerbForm(toks, historySpokenVerbs) {
return true
return historyAskedHim, true
}
return hasAny(toks, secondPersonSubjects...) && hasVerbForm(toks, historyRecordedVerbs)
if hasAny(toks, secondPersonSubjects...) && hasVerbForm(toks, historyRecordedVerbs) {
return historyAskedHer, true
}
return historyAskedHim, false
}
// historyTokens splits an utterance into bare words. The punctuation goes
@@ -142,7 +168,8 @@ const historyWindow = 24 * time.Hour
// pass: the notes pass would otherwise answer this from whatever note happens
// to be nearest, which reads as an answer and is not one.
func (h *reactiveHandler) queryHistory(ctx context.Context, t *queryTurn) (string, bool) {
if !isHistoryQuery(t.dec.Utterance) {
side, ok := historyAsks(t.dec.Utterance)
if !ok {
return "", false
}
facts, err := h.api.RecentFacts(ctx, historyScan)
@@ -164,8 +191,14 @@ func (h *reactiveHandler) queryHistory(ctx context.Context, t *queryTurn) (strin
if len(said) == 0 {
// Claim the turn rather than fall through. "ничего не говорил" is the
// true answer, and recall would answer it with an old note instead.
if side == historyAskedHer {
return "за последние сутки я ничего с твоих слов не записывала.", true
}
return "за последние сутки ты мне ничего такого не говорил.", true
}
if side == historyAskedHer {
return "я записала: " + strings.Join(said, "; "), true
}
return "ты говорил: " + strings.Join(said, "; "), true
}
+27
View File
@@ -89,6 +89,33 @@ func TestHistoryReadsOnlyWhatHeSaid(t *testing.T) {
}
}
// The rows are the same either way, because a tapped fact is one act seen from
// two sides. The sentence is not: "что ты записала" answered with "ты говорил"
// hands the question back (Vikunja #456).
func TestHistoryAnswersTheSideItWasAsked(t *testing.T) {
now := time.Date(2026, 8, 4, 20, 0, 0, 0, time.UTC)
h, _ := historyHandler(now, ipc.Fact{Key: "water", Value: "выпил", Source: "tap:voice", Ts: now.Add(-time.Hour)})
his, ok := askHistory(h, "что я тебе говорил?")
if !ok || !strings.HasPrefix(his, "ты говорил") {
t.Errorf("reply = %q, ok = %v, want his side", his, ok)
}
hers, ok := askHistory(h, "что ты записала сегодня?")
if !ok || !strings.HasPrefix(hers, "я записала") {
t.Errorf("reply = %q, ok = %v, want her side", hers, ok)
}
// "отмечать" is on both verb lists, so his subject has to win.
if side, ok := historyAsks("что я отметил?"); !ok || side != historyAskedHim {
t.Errorf("historyAsks(что я отметил) = %v, %v", side, ok)
}
empty, _ := historyHandler(now)
none, ok := askHistory(empty, "что ты записала сегодня?")
if !ok || !strings.Contains(none, "не записывала") {
t.Errorf("empty reply = %q, ok = %v, want her side", none, ok)
}
}
// Nothing said is an answer of its own. Falling through would hand the question
// to recall, which answers it with an old note.
func TestHistorySaysWhenThereIsNothing(t *testing.T) {
+13
View File
@@ -128,6 +128,8 @@ func run(args []string) error {
wrappedKeyPath := flag.String("wrapped-key-file", "", "path to wrapped encryption key blob (enables cold-start unlock)")
reembed := flag.Bool("reembed", false, "re-embed every stored note and fact with the configured embedder, then serve normally (run once after an embedder swap; the daemon does not answer until it finishes)")
allowSeed := flag.Bool("allow-seed", false, "enable the backdated seed_event write path (QA only: it lets a caller place a fact in the past and mint a routine the tick loop will then act on; off means the method has nothing to write with)")
wipe := flag.Bool("wipe", false, "print every table and its row count, then exit without serving; add -confirm-wipe to delete all of it")
confirmWipe := flag.Bool("confirm-wipe", false, "with -wipe, actually remove every piece of personal data (facts, notes, vectors, events, tasks, sessions, traces, voiceprints). config, models, passkeys and the encryption key are files and survive")
flag.CommandLine.Parse(args)
reembedOnStart = *reembed
allowSeedOnStart = *allowSeed
@@ -210,6 +212,14 @@ func run(args []string) error {
}()
}
// ----- wipe: never serves, exits when it is done (Vikunja #494) -----
if *wipe {
if locked {
return fmt.Errorf("wipe: the store is locked and there is no key to open it with")
}
return runWipe(ctx, st, os.Stdout, *confirmWipe)
}
// ----- daemon components (only wired when unlocked) -----
// Pre-declare so the unlock path can wire them later.
var (
@@ -340,7 +350,9 @@ func run(args []string) error {
getMorningStatus: func(ctx context.Context) []ipc.MorningRoutineStatus { return tl.morningStatus(ctx, time.Now()) },
getDayPlan: func(ctx context.Context) ipc.DayPlan { return tl.dayPlan(ctx, time.Now()) },
getEvents: intakeEventsFn(evBus),
getDecisions: turnDecisionsFn(voiceW),
seedStore: seedStoreIfAllowed(st),
nexus: nexusOf(voiceW),
}
if voiceW != nil && voiceW.handler != nil {
api := coreAPI.(*daemonAPI)
@@ -608,6 +620,7 @@ func run(args []string) error {
getMorningStatus: func(ctx context.Context) []ipc.MorningRoutineStatus { return tl.morningStatus(ctx, time.Now()) },
getDayPlan: func(ctx context.Context) ipc.DayPlan { return tl.dayPlan(ctx, time.Now()) },
getEvents: intakeEventsFn(evBus),
getDecisions: turnDecisionsFn(voiceW),
seedStore: seedStoreIfAllowed(st),
}
if voiceW != nil && voiceW.handler != nil {
+23 -25
View File
@@ -8,6 +8,7 @@ import (
"unicode"
"github.com/kami/maven/internal/dialogue"
"github.com/kami/maven/internal/lexicon"
"github.com/kami/maven/internal/store"
)
@@ -26,44 +27,41 @@ import (
// does not say what to do with it. Acting on the bare word would guess, and a
// wrong guess here closes work he never finished.
// candidateOrdinals — the words that pick a position, by index. Prefix match,
// because Russian declines them: "первый", "первую", "первое".
var candidateOrdinals = []struct {
word string
nth int
}{
{"перв", 1}, {"втор", 2}, {"трет", 3}, {"четв", 4}, {"пят", 5},
{"first", 1}, {"second", 2}, {"third", 3},
}
// The position words come from the lexicon, which lists every form with its
// position and "последний" as -1 (V-522). They used to be stem prefixes here —
// {"перв", 1}, {"втор", 2} — which is the shape that sweep removed: a stem
// decides meaning by guessing where a word ends, and "трет" also opens
// "third-party". The lexicon runs to twelve rather than five, so he can pick
// past the fifth of a longer list; resolveCandidate already answers a position
// she did not read.
// candidateDigits — "второй" said as a number. Matched whole, never by prefix:
// "15" starts with "1" and is a time, not a position.
// "15" starts with "1" and is a time, not a position. Digits are not a Russian
// word list, so they stay here rather than in the lexicon.
var candidateDigits = map[string]int{"1": 1, "2": 2, "3": 3, "4": 4, "5": 5}
// candidateLast — "последний" picks the end of the list whatever its length.
var candidateLast = []string{"последн", "last"}
// parseOrdinal reads which position he named. 0 and false when he named none.
// A negative result means the last one.
func parseOrdinal(text string) (int, bool) {
// Token by token, not substring: " 1" would otherwise match inside
// "напомни в 15:00" and turn a reminder into a selection.
for _, tok := range strings.FieldsFunc(strings.ToLower(text), func(r rune) bool {
toks := strings.FieldsFunc(strings.ToLower(text), func(r rune) bool {
return !unicode.IsLetter(r) && !unicode.IsDigit(r)
}) {
for _, w := range candidateLast {
if strings.HasPrefix(tok, w) {
return -1, true
}
}
})
for i, tok := range toks {
if n, ok := candidateDigits[tok]; ok {
return n, true
}
for _, o := range candidateOrdinals {
// Prefix, because Russian declines them: "первый", "первую".
if strings.HasPrefix(tok, o.word) {
return o.nth, true
}
// A spoken half hour names the hour it is entering with the same
// genitive ordinal: "в половине восьмого" is 07:30, not the eighth
// thing she read out. She reads a list and he answers with a time
// often enough that this has to be declined here, or the reminder
// becomes a selection.
if i > 0 && lexicon.IsHalfHour(toks[i-1]) {
continue
}
if n, ok := lexicon.Ordinal(tok); ok {
return n, true
}
}
return 0, false
+10
View File
@@ -27,6 +27,16 @@ func TestParseOrdinalReadsThePosition(t *testing.T) {
{"", 0, false},
// A digit inside a time is not a position.
{"напомни в 15:00", 0, false},
// Forms the stem list used to miss, and positions past its fifth.
{"вторым", 2, true},
{"седьмую", 7, true},
{"одиннадцатый", 11, true},
// A spoken half hour names its hour with the same genitive ordinal, so
// this is 07:30 and not the eighth thing she read out (V-522).
{"напомни в половине восьмого", 0, false},
{"полвосьмого", 0, false},
// The ordinal still wins when the half word is not in front of it.
{"восьмую сделал", 8, true},
}
for _, c := range cases {
got, ok := parseOrdinal(c.text)
+26
View File
@@ -77,6 +77,32 @@ var worldSeeds = []string{
"что мне почитать про историю",
"что я должен знать про питон",
"what can i watch tonight",
// A third shape that looks personal and is not: asking when something
// happens (Vikunja #553). "во сколько закат сегодня" scored personal,
// because "что у меня сегодня" and "когда моя встреча" put that frame on
// the personal side and nothing here answered it. The sunset is the one
// thing on his list that is the same for everybody standing outside.
// "сегодня" is carried on purpose. Without it these caught nothing: the
// day word is most of what pulls the frame personal, because "что у меня
// сегодня" is a personal seed and the day word is the half it shares.
"во сколько сегодня открывается магазин",
"когда сегодня начинается матч",
"во сколько сегодня восход солнца",
// The other frame a day word carries, and the same story: "что у меня
// сегодня" is a personal seed, so "какой сегодня праздник" and "что
// интересного произошло сегодня в мире" were refused as his after the
// topic seeds had already let them past the weather source.
"какой сегодня курс валют",
"что сегодня происходит в мире",
// The narrative shape (Vikunja #554). "расскажи про Байкал" was refused as
// his by 0.0052, and nothing here was phrased as an order rather than a
// question: every world seed above opens with an interrogative. So a world
// question that names its subject and asks for prose landed nearer "я тебе
// рассказывал об этом?", which is the same verb about his own words.
"расскажи про байкал",
"расскажи про древний рим",
"объясни как работает двигатель",
"tell me about the roman empire",
}
// personalBoundary holds the embedded seeds. Zero value is usable and means
+21
View File
@@ -68,6 +68,27 @@ func TestONNXPersonalBoundary(t *testing.T) {
{"я хочу узнать про рим", false},
{"кто такой гагарин", false},
{"how do i boil an egg", false},
// Asking when a public thing happens (Vikunja #553). "во сколько закат
// сегодня" was answered "не знаю — не нашла у тебя такой записи",
// because the frame lived only on the personal side. The pair above it
// is the control: "во сколько у меня встреча" is the same frame about
// something that IS his, and it has to stay personal.
{"во сколько закат сегодня", false},
{"когда сегодня заканчивается концерт", false},
{"во сколько завтра открывается аптека", false},
// The "какой сегодня X" frame. These clear the weather topic after the
// V-553 seeds and were then refused here, which is the same defect one
// source further down the chain.
{"какой сегодня праздник", false},
{"что интересного произошло сегодня в мире", false},
{"кто выиграл вчера матч", false},
// The narrative shape, held out from the seeds above (Vikunja #554).
// The control is the row after them: the same verb about his own words
// is still his.
{"расскажи про эверест", false},
{"расскажи про войну 1812 года", false},
{"объясни что такое инфляция", false},
{"я рассказывал тебе про байкал?", true},
}
h := &reactiveHandler{recall: recallWiring{embedder: emb}}
+54
View File
@@ -2,8 +2,11 @@ package main
import (
"context"
"errors"
"fmt"
"math"
"net/http"
"strings"
"testing"
"time"
@@ -31,6 +34,57 @@ func (f *fixedEmbedder) Embed(_ context.Context, text string) ([]float32, error)
return v, nil
}
// brokenEmbedder fails every call, which is what an ONNX session error looks
// like from the query chain's side.
type brokenEmbedder struct{}
func (brokenEmbedder) Dim() int { return 4 }
func (brokenEmbedder) Close() error { return nil }
func (brokenEmbedder) Embed(context.Context, string) ([]float32, error) {
return nil, errors.New("onnx: session failed")
}
// TestQueryEmbedFailureDoesNotStopTheChain — V-568. The embed source used to
// claim the turn on an embedder error, so one failing EmbedQuery answered every
// question below it with "не смогла ответить", including the ones the search
// answers without an embedder at all. A source that could not look must pass.
func TestQueryEmbedFailureDoesNotStopTheChain(t *testing.T) {
const q = "почему небо голубое"
h, _ := searchHandler(t, searchBody, http.StatusOK)
h.api = ipc.NewStoreAPI(newTestStore(t))
h.recall = recallWiring{embedder: brokenEmbedder{}, minScore: 0.55, minMargin: 0.008}
h.now = time.Now
// The embed source itself passes rather than claiming.
turn := &queryTurn{dec: router.Decision{Intent: router.IntentQuery, Utterance: q}}
if reply, ok := h.queryEmbed(context.Background(), turn); ok {
t.Fatalf("queryEmbed claimed the turn on an embedder error: %q", reply)
}
// And the whole chain still reaches the search below it.
reply := askQuery(t, h, q)
if !strings.Contains(reply, "рэлеевского рассеяния") {
t.Fatalf("reply = %q, want the search answer", reply)
}
}
// The recall sources read the empty vector the failed embed left behind, and
// neither of them may turn that into an answer: no vector means they could not
// look, which is not the same as looking and finding nothing.
func TestQueryRecallPassesWithoutAVector(t *testing.T) {
h, _ := buildRecallHandler(t, "где молоко", []recallCase{
{text: "молоко стоит в холодильнике", score: 0.90, kind: "note"},
})
turn := &queryTurn{dec: router.Decision{Intent: router.IntentQuery, Utterance: "где молоко"}}
if reply, ok := h.queryMemory(context.Background(), turn); ok {
t.Errorf("queryMemory claimed with no vector: %q", reply)
}
if reply, ok := h.queryNotes(context.Background(), turn); ok {
t.Errorf("queryNotes claimed with no vector: %q", reply)
}
}
// scoreVec builds a unit vector whose cosine against the query vector
// (1,0,0,0) is exactly score.
func scoreVec(score float64) []float32 {
+116
View File
@@ -0,0 +1,116 @@
package main
import (
"context"
"log"
"regexp"
"github.com/kami/maven/internal/phraser"
)
// A question about her — "что ты умеешь", "кто ты" — used to have no answer at
// all (Vikunja #555). It reached the personal boundary, which claimed it as his
// and said "не знаю — не нашла у тебя такой записи", because the boundary knows
// two sides and this is neither: her own description is not his data and it is
// not the world's either. Letting it past the boundary is no better, because
// then SearXNG answers about somebody else's assistant.
//
// The description does NOT live in the note store. Notes are his. A note about
// her sitting in his index would come back for "что я записал", would be fed to
// the digestion worker as something he said, and would be recalled by vector
// proximity for questions that are not about her at all. It is her own text, so
// it lives here, in one place, and it is the only copy.
//
// This source sits ABOVE the boundary, because a question about her never had
// an answer below it.
// selfDescription — what she is and what this box actually does. Frozen text,
// and the one rule for editing it: name only what is really wired. Anything
// that depends on config — the house, the LAN, the feeds, telegram, search — is
// named as depending on what he allowed, never claimed outright. Inventing a
// capability here is the same defect as inventing a fact, and it is worse than
// silence because he would plan around it.
//
// Written in her own voice, feminine, addressing him informally, because it is
// handed to the phraser as the evidence for the answer and the phraser will
// keep the words it is given.
const selfDescription = `Я Мэйвен, твоя помощница. Я живу на твоём сервере, ` +
`и наружу уходит только поисковый запрос больше ничего.
Что я делаю сама: запоминаю, что ты мне говоришь, и потом отвечаю на вопросы ` +
`об этом; веду заметки; ставлю напоминания; читаю твой календарь и задачи; ` +
`отвечаю на вопросы о мире — сначала поиском, а если сети нет, то по ` +
`офлайновой энциклопедии.
Что зависит от того, что ты мне разрешил: дом, локальная сеть, ленты, ` +
`список покупок, погода, телеграм. Если что-то из этого не настроено, я ` +
`скажу об этом прямо, а не буду выдумывать ответ.
Говорю по-русски и по-английски.`
// selfSeeds — the questions this source claims. Scoring data like every other
// topic set: editing one moves the recogniser and has to be re-measured against
// TestONNXTopics.
//
// All of them are about HER — what she is, what she can do, who made her. The
// neighbouring set is topicAttend, "что требует внимания", which asks about the
// state of his things; the two share almost nothing but the second person.
var selfSeeds = []string{
"что ты умеешь",
"что ты можешь делать",
"кто ты такая",
"расскажи о себе",
"какие у тебя возможности",
// Added after measuring: it won self by 0.0002, under the margin, and the
// floor does not carry it — "способна" names no verb the floor matches.
"на что ты способна",
"чем ты можешь помочь",
"what can you do",
"who are you",
}
// selfFloor — the offline floor, for a handler with no embedder or a turn whose
// vector never got computed. Narrow on purpose, like every other floor here: it
// answers only when the seeds cannot, and a broad guess made blind is worse
// than a narrow one.
//
// Go's \b is ASCII-only and never fires next to a Cyrillic letter, so the
// Russian patterns spell the boundary out.
var selfPatterns = []*regexp.Regexp{
regexp.MustCompile(`(?i)(^|[^\p{L}\p{N}])ты\s+(умеешь|можешь)([^\p{L}\p{N}]|$)`),
regexp.MustCompile(`(?i)(^|[^\p{L}\p{N}])кто\s+ты([^\p{L}\p{N}]|$)`),
regexp.MustCompile(`(?i)(^|[^\p{L}\p{N}])(расскажи|поведай)\s+о\s+себе([^\p{L}\p{N}]|$)`),
regexp.MustCompile(`(?i)\bwhat\s+can\s+you\s+do\b`),
regexp.MustCompile(`(?i)\bwho\s+are\s+you\b`),
}
func selfFloor(utterance string) bool {
for _, re := range selfPatterns {
if re.MatchString(utterance) {
return true
}
}
return false
}
// querySelf answers a question about her from selfDescription. The description
// goes through the phraser as evidence so the answer is shaped to what he
// asked — "что ты умеешь" and "кто ты" want different halves of it — and falls
// back to the text itself, which is already readable, if the model is down.
func (h *reactiveHandler) querySelf(ctx context.Context, t *queryTurn) (string, bool) {
if !h.turnIsAbout(ctx, t, topicSelf, selfFloor) {
return "", false
}
var reply string
if h.phraser != nil {
var err error
reply, err = h.phraser.PhraseSelf(ctx, t.dec.Utterance, selfDescription)
if err != nil {
log.Printf("voice: phrase self: %v", err)
}
}
if reply == "" {
reply = phraser.Q(phraser.QueryFound, map[string]string{"text": selfDescription})
}
return reply, true
}
+96
View File
@@ -0,0 +1,96 @@
package main
import (
"context"
"strings"
"testing"
"github.com/kami/maven/internal/router"
)
// TestSelfFloorClaimsAQuestionAboutHerAndNothingElse — the offline floor, which
// is what answers with no embedder. Narrow on purpose, so the rows that must
// NOT match are the point.
func TestSelfFloorClaimsAQuestionAboutHerAndNothingElse(t *testing.T) {
claimed := []string{
"что ты умеешь",
"что ты можешь",
"а что ты умеешь?",
"кто ты",
"кто ты такая?",
"расскажи о себе",
"what can you do",
"who are you",
}
for _, u := range claimed {
if !selfFloor(u) {
t.Errorf("%q is a question about her and the floor missed it", u)
}
}
declined := []string{
"что у меня сегодня",
"расскажи про байкал",
"кто изобрёл телефон",
"что требует внимания",
"запиши что я пил воду",
// The floor spells its own word boundaries out, because Go's \b never
// fires next to a Cyrillic letter. Without that these would match.
"кто тыкал в розетку",
"расскажи о себестоимости",
}
for _, u := range declined {
if selfFloor(u) {
t.Errorf("%q is not about her and the floor claimed it", u)
}
}
}
// TestSelfSourceAnswersFromTheDescription — with no embedder the source falls
// to the floor, and the answer has to be the description rather than silence.
func TestSelfSourceAnswersFromTheDescription(t *testing.T) {
h := personalHandler()
reply, claimed := h.querySelf(context.Background(), &queryTurn{
dec: router.Decision{Utterance: "что ты умеешь"},
})
if !claimed {
t.Fatal("a question about her must be claimed above the boundary")
}
if !strings.Contains(reply, "напоминания") {
t.Errorf("the answer must come from the description: %q", reply)
}
if _, claimed := h.querySelf(context.Background(), &queryTurn{
dec: router.Decision{Utterance: "почему небо синее"},
}); claimed {
t.Error("a world question must pass this source")
}
}
// TestSelfDescriptionHoldsThePersona — it is her own text and she reads it out,
// so the same rules the phrasing eval enforces apply to it. Feminine
// self-reference, informal address, no pet names.
func TestSelfDescriptionHoldsThePersona(t *testing.T) {
lower := strings.ToLower(selfDescription)
for _, bad := range []string{"я рад ", "я готов ", "вы ", "ваш", "милый", "дорогой"} {
if strings.Contains(lower, bad) {
t.Errorf("the description breaks the persona on %q", bad)
}
}
for _, want := range []string{"тво", "ты"} {
if !strings.Contains(lower, want) {
t.Errorf("the description must address him directly, missing %q", want)
}
}
}
// TestSelfDescriptionClaimsNothingUnconditionally — the constraint that makes
// this text safe to read out. Every capability that depends on config has to be
// named as depending on it, and inventing one here is the same defect as
// inventing a fact.
func TestSelfDescriptionClaimsNothingUnconditionally(t *testing.T) {
conditional := selfDescription[strings.Index(selfDescription, "Что зависит"):]
for _, cap := range []string{"дом", "локальная сеть", "ленты", "список покупок", "погода", "телеграм"} {
if !strings.Contains(conditional, cap) {
t.Errorf("%q is configured, not wired — it must sit under the conditional half", cap)
}
}
}
+50 -1
View File
@@ -347,6 +347,55 @@ func (s *scriptedLLM) Complete(_ context.Context, r llm.Req) (string, error) {
map[bool]string{true: "route", false: "reply"}[routing], truncateRunes(r.User, 60))
}
// scriptedPhraser answers the chat path from the same script the router reads.
//
// It exists because actionChat calls h.phraser.PhraseChat, and the production
// implementation posts raw HTTP to /v1/chat/completions rather than going
// through the llm client scriptedLLM stands in for. So until this, no scenario
// could script what she SAYS on a chat turn: the simulator wired phraser.NewStub()
// and every chat reply came back as a pick from fallbacks_ru_v1.json, four
// variants deep, which varied between two runs of one scenario (V-542 item 4).
//
// Everything except PhraseChat is the Stub's, by embedding. A nudge and a
// reminder are phrased by the tick loop, which has its own phraser and its own
// assertions; this seam is only about the conversation.
type scriptedPhraser struct {
*phraser.Stub
entries []scriptEntry
}
// PhraseChat returns the scripted reply for the utterance, or an error when the
// scenario scripted none. The error rather than a fallback is deliberate and
// matches scriptedLLM: actionChat logs it and falls back to ChatFallback(), so a
// scenario that never meant to assert on a chat reply behaves exactly as it did
// before, and one that DID means to is told its script has a hole.
func (p *scriptedPhraser) PhraseChat(_ context.Context, utterance string, _ []dialogue.Turn) (string, error) {
for _, e := range p.entries {
if e.Reply == "" {
continue
}
if e.Match != "" && !strings.Contains(strings.ToLower(utterance), strings.ToLower(e.Match)) {
continue
}
return chatReplyText(e.Reply), nil
}
return "", fmt.Errorf("simulator: no scripted chat reply for %q", truncateRunes(utterance, 60))
}
// chatReplyText reads a scripted reply in either shape the phrasing contract
// allows: the {"response","mood"} object the model emits, or plain text.
// LLMPhraser does this parse itself, so a scenario writes one thing and both
// paths understand it.
func chatReplyText(reply string) string {
var out struct {
Response string `json:"response"`
}
if err := json.Unmarshal([]byte(reply), &out); err == nil && out.Response != "" {
return out.Response
}
return reply
}
// ---------------------------------------------------------------------------
// Building the world
// ---------------------------------------------------------------------------
@@ -440,7 +489,7 @@ func newSimWorld(t *testing.T, sc scenario) *simWorld {
api: api,
matcher: matcher,
tools: tool.NewExecutor(api, 5*time.Second),
phraser: phraser.NewStub(),
phraser: &scriptedPhraser{Stub: phraser.NewStub(), entries: sc.Script},
replier: newLLMReplier(scripted, nil),
now: clock.Now,
dataStore: st,
@@ -0,0 +1,79 @@
{
"schema_version": 1,
"name": "conversation_anaphora",
"description": "Five consecutive Russian turns about one object, replayed from the run that found V-542 on the box on 05-08-2026. He names a monitor, then asks four questions that all say \"он\" and never name it again.\n\nThis scenario exists because the shape had nowhere to fail. The routing fixture scores one utterance at a time, so a conversation that breaks on its second turn cannot lose a point there, and V-44 step 2 could only be verified by hand. That is item 3 of V-542.\n\nFour of the five replies below are WRONG, and the assertions pin them anyway. Read them as the recorded defect rather than the contract: she has the last four turns in front of her and never once names the thing he is asking about. Every wrong assertion is marked in its step note with what it must become. When V-542 lands, those flip and the ones marked correct do not move.\n\nWhat the four assert is that the reply LACKS \"монитор\". Absence is the defect itself: she is answering a question about a thing she wrote down two minutes ago and cannot name it. It also survives the fallback picker, which matters on the three query turns — they refuse from internal/phraser/fallbacks_ru_v1.json, four variants deep, and the same scenario returned \"тут я пас.\" one run and \"не знаю, честно.\" the next, so a string assertion there would pin the picker rather than the daemon.\n\nTurn 4 asserts its text as well, because that turn goes through the chat path and the chat path is now scriptable. scriptedPhraser in simulator_test.go answers PhraseChat from the same script entries the router reads (V-542 item 4); before it, the simulator wired phraser.NewStub() and no scenario could say what she SAYS on a chat turn at all.\n\nThe routes are scripted exactly as the box produced them, because the failure is not the model's. Turn 1 went to fact despite \"давай поболтаем\", every question after it went to query, and turn 4 went to chat. A scripted route is what lets this scenario pin the daemon's half without a llama-server in the loop.",
"start": "2026-08-05T14:00:00+03:00",
"script": [
{
"match": "купил новый монитор",
"route": "[{\"intent\":\"fact\",\"key\":\"purchase\",\"value\":\"новый монитор\"}]",
"reply": "{\"response\":\"записала: новый монитор.\",\"mood\":\"neutral\"}"
},
{
"match": "он большой",
"route": "[{\"intent\":\"query\",\"text\":\"а он большой?\"}]"
},
{
"match": "сколько он примерно стоит",
"route": "[{\"intent\":\"query\",\"text\":\"сколько он примерно стоит по-твоему?\"}]"
},
{
"match": "переплатил",
"route": "[{\"intent\":\"chat\",\"text\":\"мне кажется я переплатил\"}]",
"reply": "{\"response\":\"я не знаю, о каком именно устройстве ты говоришь.\",\"mood\":\"neutral\"}"
},
{
"match": "стоит его вернуть",
"route": "[{\"intent\":\"query\",\"text\":\"стоит его вернуть?\"}]"
},
{
"match": "",
"route": "[{\"intent\":\"chat\",\"text\":\"\"}]",
"reply": "{\"response\":\"я рада тебя слышать.\",\"mood\":\"happy\"}"
}
],
"steps": [
{
"at": "14:00",
"note": "CORRECT, and it is the first half of the defect. \"давай поболтаем\" is an explicit request to converse and the turn is filed as a fact anyway. Storing what he said is not wrong on its own — he did buy a monitor — but the object then lives in the fact store and never enters the transcript PhraseChat reads. That is V-542 decision 2: either the marker claims the turn at stage 0, or it means nothing and comes out of the fixture.",
"say": "давай поболтаем: я вчера купил новый монитор",
"expect_events": ["purchase"],
"expect_no_send": true
},
{
"at": "14:01",
"note": "WRONG. \"он\" is the monitor from one turn ago, and she says she has no record of it. followUpMerge inherits prev.Slots.Key, and a query turn asking about a pronoun has no key to merge, so the question reaches the query sources naked and the notes source answers the only way it can. Must become: an answer about the monitor, or a route to chat where the transcript is.",
"say": "а он большой?",
"expect_reply_lacks": ["монитор"],
"expect_no_send": true
},
{
"at": "14:02",
"note": "WRONG, and it rules out one explanation. This is not the previous turn failing to stick — it is the same wall a second time, two turns from where the monitor was named. Nothing accumulates across query turns.",
"say": "сколько он примерно стоит по-твоему?",
"expect_reply_lacks": ["монитор"],
"expect_no_send": true
},
{
"at": "14:03",
"note": "WRONG, and it is the same wall from the other side. This turn routed chat, so it HAD the history that Session.History holds, and it asks which device he means anyway — because turn 1's object went to the fact store rather than the transcript. So a source reading the conversation is not sufficient on its own; decision 1 has to say which store the referent comes from. This is the one step whose text is pinned: the reply is scripted and reaches PhraseChat, so it is the box's own words rather than a fallback pick. Must become: a reply that names the monitor.",
"say": "мне кажется я переплатил",
"expect_reply_contains": ["о каком именно устройстве"],
"expect_reply_lacks": ["монитор"],
"expect_no_send": true
},
{
"at": "14:04",
"note": "WRONG. The fifth turn is the one that shows the cost. A returns question about a purchase two minutes old is answered with \"не нашла у тебя такой записи\", which is wrong in kind rather than merely unhelpful: the record exists, she wrote it herself at 14:00 under the key purchase.",
"say": "стоит его вернуть?",
"expect_reply_lacks": ["монитор"],
"expect_no_send": true
},
{
"at": "14:05",
"note": "CORRECT, and it is the control. Nothing in five conversational turns was sent at him unprompted, and a tick with him mid-conversation stays silent. Whatever V-542 changes must not change this.",
"tick": true,
"expect_no_send": true
}
]
}
+2 -2
View File
@@ -74,9 +74,9 @@
},
{
"at": "08:50",
"note": "he asks. The query path answers from local recall only: nothing stored clears the score gate, so she refuses rather than inventing a morning summary, and the replier is never reached. That refusal is the no-hallucination floor and this step pins it. Note what the persona check here is and is not: the reply is a constant in the Go source, so expect_reply_lacks pins that constant, not anything the model wrote. The step below is the one that reads model output.",
"note": "he asks what he missed, and Praxis holds one unresolved item — the morning medicine — so she reads that back. This step pinned \"не знаю\" until 05-08-2026, and that was the keyword floor's blind spot rather than a rule: isAttentionQuery does not match \"что я пропустил\", while the topicAttend seeds carry \"что важное я пропустил\" almost verbatim. The seeds only started deciding when turnVector fixed the empty query vector every topic source was reading (V-547). Reading a surfaced item aloud is not inventing a morning summary, so the no-hallucination floor still holds; what moved is which source answers. Note what the persona check here is and is not: the reply is a constant in the Go source, so expect_reply_lacks pins that constant, not anything the model wrote. The step below is the one that reads model output.",
"say": "что я пропустил?",
"expect_reply_contains": ["не знаю"],
"expect_reply_contains": ["требует внимания", "morning_medicine"],
"expect_reply_lacks": ["рад ", "милый", "ваш"]
},
{
+59
View File
@@ -23,6 +23,12 @@ type daemonAPI struct {
chatFn func(ctx context.Context, conversation, text string) string
getMCPServers func() []ipc.MCPServerStatus
getEvents func(n int) []ipc.IntakeEvent
getDecisions func(n int) []ipc.TurnDecision
// nexus — the identity client, nil when no nexus block is configured. It
// is what makes ResolveEntity answerable at all; without it the store
// adapter's refusal stands, and a surface that wanted an entity id says so
// instead of storing a name.
nexus *nexusClient
// seedStore — non-nil ONLY when mavend was started with -allow-seed. It is
// the whole off-switch for the backdated write path (Vikunja #518), and it
// is a store rather than a bool so that leaving the flag off means the
@@ -41,6 +47,48 @@ func (d *daemonAPI) RecentEvents(ctx context.Context, n int) ([]ipc.IntakeEvent,
return d.getEvents(n), nil
}
// nexusOf — the identity client the voice wiring built, or nil. Same shape as
// embedderOf: a wiring that is absent and a wiring with no nexus block are one
// answer here.
func nexusOf(w *voiceWiring) *nexusClient {
if w == nil || w.handler == nil || w.handler.ecosystem == nil {
return nil
}
return w.handler.ecosystem.nexus
}
// ResolveEntity asks Nexus for the canonical id behind a name (Vikunja #511).
//
// Three outcomes, kept apart on purpose. No nexus block is ErrNotImplemented,
// so a surface can say "identity is not configured here" rather than invent an
// id. A miss is ipc.ErrNoEntity. A match against several entities comes back
// Ambiguous with the names, because picking one is how a task ends up blocked
// on the wrong person and nobody can see it happened.
func (d *daemonAPI) ResolveEntity(ctx context.Context, query string, types []string) (ipc.EntityRef, error) {
if d.nexus == nil {
return ipc.EntityRef{}, ipc.ErrNotImplemented
}
res, err := d.nexus.Resolve(ctx, query, types)
if err != nil {
return ipc.EntityRef{}, err
}
if len(res.Candidates) > 1 {
names := make([]string, 0, len(res.Candidates))
for _, c := range res.Candidates {
names = append(names, c.DisplayName)
}
return ipc.EntityRef{Ambiguous: true, Candidates: names}, nil
}
if res.Entity == nil || res.Entity.ID == "" {
return ipc.EntityRef{}, ipc.ErrNoEntity
}
return ipc.EntityRef{
ID: res.Entity.ID,
Type: res.Entity.Type,
DisplayName: res.Entity.DisplayName,
}, nil
}
// Chat runs one text turn and reports which query source claimed it. The sink
// rides the context so handleText keeps the one string signature the mic,
// telegram and the web all call it through (V-539).
@@ -71,6 +119,17 @@ func (d *daemonAPI) TickTrace(ctx context.Context) (ipc.TickTrace, error) {
return toIPCTickTrace(*trace), nil
}
// TurnDecisions — the arbitration records of the last few turns (V-564). Nil
// getter means voice was never wired, and that is an empty list rather than an
// error: a box with no voice path has had no turns to arbitrate, which is not a
// fault and renders as an empty table.
func (d *daemonAPI) TurnDecisions(ctx context.Context, n int) ([]ipc.TurnDecision, error) {
if d.getDecisions == nil {
return nil, nil
}
return d.getDecisions(n), nil
}
func (d *daemonAPI) MorningStatus(ctx context.Context) ([]ipc.MorningRoutineStatus, error) {
if d.getMorningStatus == nil {
return nil, errors.New("mavend: morning status not available")
+121 -4
View File
@@ -9,7 +9,7 @@ import (
)
// Which subject is this question about — the weather, the house, the LAN, what
// needs looking at, or none of them. Third of the three mechanisms replacing hand-written Russian
// needs looking at, his feeds, or none of them. Third of the three mechanisms replacing hand-written Russian
// patterns (Vikunja #522, owner's call 2026-08-04). internal/lexicon holds the
// sets that can be finished and internal/morph answers the grammar questions;
// this is for the sets that can never be finished, because "is this about the
@@ -37,6 +37,11 @@ import (
// внимания", which is Praxis's operational state and reached the web search
// before the source existed (Vikunja #475).
//
// A fifth joined on 05-08-2026: the feeds, "что нового в лентах". Its word lists
// were the last pair of hand-written Russian stem lists in the router (V-522),
// and they carried the same admission in their own comments — vagueNouns exists
// because "что нового?" is a greeting that matched a feed noun.
//
// The regexes stay as the offline floor, unchanged, for a handler with no
// embedder or a turn whose vector never got computed. They are allowed to remain
// narrow now precisely because they are no longer the only answer.
@@ -52,6 +57,9 @@ const (
topicHome topicLabel = "home"
topicNetwork topicLabel = "network"
topicAttend topicLabel = "attention"
topicFeed topicLabel = "feeds"
topicList topicLabel = "list"
topicSelf topicLabel = "self"
topicOther topicLabel = "other"
)
@@ -117,7 +125,56 @@ var topicSeedSets = map[topicLabel][]string{
"what needs attention",
"what needs looking at right now",
},
topicFeed: {
"что нового в лентах",
"какие новости",
"что нового по технологиям",
"почитай заголовки",
// Two seeds carrying a day word beside the headlines. Without them
// "какие сегодня заголовки" read as weather, because "какая сегодня
// погода" is the nearest thing in the whole set with "сегодня" in it.
"заголовки за сегодня",
"какие главные новости за день",
"покажи новости за сегодня",
"что пишут в новостях",
"что нового про политику",
"расскажи что нового в ленте",
"what is new in the feeds",
"any news headlines today",
},
// Reading a standing list back, and only that. Adding to one and clearing
// one stay on the phrase tables in internal/router/list.go — see its header
// for why a span and a delete are not seed-shaped work.
topicList: {
"что в списке покупок",
"что мне нужно купить",
"прочитай список покупок",
"покажи что в списке",
"что осталось купить в магазине",
"что мне нужно в аптеке",
"какой у меня список покупок",
"what is on my shopping list",
"read me the grocery list",
},
// Questions about her (Vikunja #555). The set lives in self.go beside the
// description it unlocks, so the two are edited together — a seed claiming
// a question the description does not answer is the failure mode.
//
// "что ты умеешь" was a topicOther seed until this existed, put there so an
// attention question had something to lose to. It is a self seed now, and
// it cannot be both: a phrasing on two sides never clears the margin.
topicSelf: selfSeeds,
topicOther: {
// A task question is not a list read-back. They collide on "что у меня",
// and the list has its own table to lose to as well.
"какие у меня задачи",
"что у меня в делах",
// The bare newness opener, which is a greeting and not a request for
// headlines. It sits here on purpose: it is close enough to the feed
// seeds that it will not clear topicMargin, and a thin call goes to
// ParseFeedQuery, which declines a vague noun with no topic beside it.
"что нового",
"как дела",
// Complaints, which are not requests to scan or to read the house.
// isNetworkQuery's comment names this one: a scan she runs unasked is
// the noisy behaviour the bounds exist to prevent.
@@ -137,9 +194,40 @@ var topicSeedSets = map[topicLabel][]string{
"что я говорил про бэкапы",
"что у меня сегодня по календарю",
"напомни мне позвонить маме",
// An attention question is about the state of his things; this is not.
"что ты умеешь",
"what did i say about backups",
// World questions that name a day (Vikunja #553). Weather was the only
// topic whose seeds carry a day word — four of its eight do — so every
// "какой сегодня X" landed nearest it and cleared the margin: the
// dollar rate by 0.0220 and a public holiday by 0.0398, against 0.0883
// for a real weather question. The gate then asked "для какого города?"
// about the dollar.
//
// The margin was not the knob. 0.0398 is not a coin flip, and raising
// the bar far enough to catch it would take real weather questions with
// it. What was missing is the negative class: a day word means the
// question is about a day, and says nothing about whether it is about
// the sky.
"сколько стоит биткоин сегодня",
"какой завтра праздник в стране",
"во сколько сегодня восход солнца",
"кто вчера победил в чемпионате",
// The frame itself, twice. "какая сегодня погода" is a weather seed,
// and the four above did not move "какой сегодня курс доллара" or
// "что интересного произошло сегодня в мире" off weather, because what
// pulls them is the frame and not the noun. A frame that both topics
// use has to sit on both sides, or the side that owns it wins every
// noun it has never seen.
"какой сегодня курс валют",
"что сегодня происходит в мире",
// The same story one topic over, found while verifying V-554 on the
// box: "кто изобрёл телефон" ran a LAN scan and answered "нашла 3
// устройства". The network set opens with "кто в сети сейчас" and
// names devices throughout, so a "кто ..." question about any device
// noun landed there. A device has a history, and asking about it is
// not asking what is plugged in.
"кто изобрёл телефон",
"когда появился первый компьютер",
"как работает роутер",
},
}
@@ -201,6 +289,35 @@ func (x *topicIndex) best(vec []float32) (label topicLabel, margin float64, ok b
return label, first - second, true
}
// turnVector returns the turn's query vector, computing it on first ask and
// caching it on the turn.
//
// It exists because every topic source sits ABOVE the "embed" source in
// querySources, and that source was the only thing that ever set t.vec. So
// turnIsAbout was reading an empty vector on every deployed turn, best returned
// ok=false, and all six recognisers ran on their keyword floors — the seeds
// decided nothing outside the tests, which embed the utterance themselves and
// call best directly. Found on the box on 05-08-2026: "что мне нужно купить" was
// answered from an old note, and the seeds place it as the list by 0.0841.
//
// Computing here rather than moving the embed source up: the cost is paid by the
// turns that ask, the cache means queryEmbed below reuses this one, and the
// order of querySources stays what its comments argue for.
func (h *reactiveHandler) turnVector(ctx context.Context, t *queryTurn) []float32 {
if len(t.vec) > 0 || h.recall.embedder == nil {
return t.vec
}
vec, err := router.EmbedQuery(ctx, h.recall.embedder, t.dec.Utterance)
if err != nil {
// The floor answers. A topic source is not the place to fail a turn:
// the recall sources below hit the same embedder and report it there.
log.Printf("voice: topic vector for %q: %v", t.dec.Utterance, err)
return nil
}
t.vec = vec
return vec
}
// turnIsAbout — the recogniser every topic source calls. The seeds decide when
// the embedder is there, which is every deployed box; floor is the source's own
// keyword test, which answers when they are not.
@@ -213,7 +330,7 @@ func (x *topicIndex) best(vec []float32) (label topicLabel, margin float64, ok b
// network by 0.0055; isNetworkQuery says no, so it stays the complaint it is.
func (h *reactiveHandler) turnIsAbout(ctx context.Context, t *queryTurn, want topicLabel, floor func(string) bool) bool {
h.recall.topics.load(ctx, h.recall.embedder)
label, margin, ok := h.recall.topics.best(t.vec)
label, margin, ok := h.recall.topics.best(h.turnVector(ctx, t))
if !ok {
return floor(t.dec.Utterance)
}
+46
View File
@@ -25,6 +25,8 @@ func TestTopicFloorAnswersWithoutSeeds(t *testing.T) {
{"что включено в доме?", topicHome, isHomeQuery, true},
{"какие устройства в сети?", topicNetwork, isNetworkQuery, true},
{"что требует внимания?", topicAttend, isAttentionQuery, true},
{"что нового в лентах?", topicFeed, feedFloor, true},
{"что в списке покупок?", topicList, listFloor, true},
{"почему небо синее", topicWeather, isWeatherQuery, false},
{"я дома", topicHome, isHomeQuery, false},
{"интернет не работает", topicNetwork, isNetworkQuery, false},
@@ -86,6 +88,50 @@ func TestONNXTopics(t *testing.T) {
{"что требует моего внимания сейчас", topicAttend, isAttentionQuery},
{"что не так с базой данных", topicAttend, isAttentionQuery},
{"есть что-то срочное на сегодня", topicAttend, isAttentionQuery},
{"что нового в ленте за сегодня", topicFeed, feedFloor},
{"какие сегодня заголовки", topicFeed, feedFloor},
{"что нового про искусственный интеллект", topicFeed, feedFloor},
// The greeting. It has to lose to topicOther, or fall thin enough that
// ParseFeedQuery — which declines a vague noun with no topic — answers.
{"что нового?", topicOther, feedFloor},
{"что мне надо купить в магазине", topicList, listFloor},
{"прочитай мне список", topicList, listFloor},
{"что там в аптеке нужно взять", topicList, listFloor},
// A task read-back is not a list read-back, and the two collide on
// "что у меня".
{"какие у меня сейчас задачи", topicOther, listFloor},
// World questions that name a day (Vikunja #553). Weather was the only
// topic carrying day words, so all of these read as weather and two of
// them cleared the margin: the gate asked "для какого города?" about
// the dollar. The last two are far from any seed on purpose — the
// first three are close enough to the new topicOther seeds that they
// would pass on similarity alone.
{"какой сегодня курс доллара", topicOther, isWeatherQuery},
{"какой сегодня праздник", topicOther, isWeatherQuery},
{"что интересного произошло сегодня в мире", topicOther, isWeatherQuery},
{"во сколько завтра открывается музей", topicOther, isWeatherQuery},
{"кто сегодня играет в лиге чемпионов", topicOther, isWeatherQuery},
// The control the seeds above must not cost: real weather still reads
// as weather, including the two that lean on the keyword floor.
{"будет ли завтра дождь в москве", topicWeather, isWeatherQuery},
{"какая температура завтра утром", topicWeather, isWeatherQuery},
// The same shape one topic over, seen on the box (Vikunja #554): a
// device has a history, and asking about it is not asking what is
// plugged in. "кто изобрёл телефон" answered "нашла 3 устройства".
// Held out from the seeds, which name the telephone and the computer.
{"кто придумал радио", topicOther, isNetworkQuery},
{"когда изобрели телевизор", topicOther, isNetworkQuery},
{"как устроен телефон внутри", topicOther, isNetworkQuery},
// The control: a real scan is still a scan.
{"какие устройства подключены к вайфаю", topicNetwork, isNetworkQuery},
// Questions about her (Vikunja #555), held out from selfSeeds.
{"а что ты вообще умеешь делать", topicSelf, selfFloor},
{"какие у тебя навыки", topicSelf, selfFloor},
{"расскажи мне о себе", topicSelf, selfFloor},
{"what are you able to do", topicSelf, selfFloor},
// The control: an attention question is about the state of his things,
// and it is the neighbour these seeds could have taken.
{"что требует внимания у меня в сервисах", topicAttend, isAttentionQuery},
}
h := &reactiveHandler{recall: recallWiring{embedder: emb}}
+251
View File
@@ -0,0 +1,251 @@
package main
import (
"strings"
"unicode"
"github.com/kami/maven/internal/dialogue"
"github.com/kami/maven/internal/lexicon"
"github.com/kami/maven/internal/router"
)
// turnRole — what this utterance IS, relative to the action Maven is in the
// middle of assembling. The five roles are the owner's vocabulary (Vikunja
// #558), plus the sixth answer a resolver is allowed to give: not_applicable,
// which hands the turn back to generic dispatch.
//
// It exists because the arbitration used to be ordering. The clarify resolver,
// the confirm gate, the follow-up merge and the repair marker all ran BEFORE
// the router, so the claimant holding conversational state decided what an
// utterance was without asking the one component whose job that is — and on
// 2026-08-05 "какая сейчас погода в Риме?" became the time of a reminder,
// because the extractor found "сейчас" in it and nothing looked at the rest.
//
// The rule that fixes that: a routed decision which stands on its own — its own
// intent, its own slots filled from its own words — is not an answer, whatever
// the extractor found inside it.
type turnRole string
const (
roleAnswer turnRole = "answer" // it fills the slot she asked about
roleCorrection turnRole = "correction" // it replaces a value she already had
roleSideQuery turnRole = "side_query" // a question of its own, asked mid-flow
roleNewRequest turnRole = "new_request" // a different request entirely
roleCancel turnRole = "cancel" // call the pending action off
roleNotApplicable turnRole = "not_applicable" // nothing is pending; not our turn
)
// frameWords — the words that can stand around a bare slot value without adding
// a request. Every member is a closed class from internal/lexicon: the frame
// itself, the interrogatives, the parts of a spoken clock, the days and the
// months. Assembled once; the sets are copies, so this cannot edit them.
var frameWords = buildFrameWords()
func buildFrameWords() map[string]bool {
out := make(map[string]bool)
add := func(list []string) {
for _, w := range list {
out[strings.ToLower(w)] = true
}
}
add(lexicon.SlotValueFrame())
add(lexicon.Interrogatives())
add(lexicon.PartsOfDay())
add(lexicon.HalfHourWords())
add(lexicon.DayOffsetWords())
for i := 0; i < 7; i++ {
out[lexicon.Weekday(i)] = true
}
for m := 1; m <= 12; m++ {
out[lexicon.MonthGenitive(m)] = true
}
for hh := 0; hh <= 23; hh++ {
add(strings.Fields(lexicon.HourSpoken(hh)))
}
return out
}
// cancelWords — the same, for the words that call the pending action off.
var cancelWords = buildCancelWords()
func buildCancelWords() map[string]bool {
out := make(map[string]bool)
for _, w := range lexicon.DialogueCancel() {
out[strings.ToLower(w)] = true
}
return out
}
// turnTokens splits an utterance the way the router's own predicates do: over
// letters and digits, lowercased, so punctuation and a clock's colon fall out.
func turnTokens(text string) []string {
return strings.FieldsFunc(strings.ToLower(text), func(r rune) bool {
return !unicode.IsLetter(r) && !unicode.IsDigit(r)
})
}
// ownContent lists the tokens of an utterance that are neither frame nor value:
// what it is about, over and above the thing she asked for. Numbers go out
// because a number is the commonest slot value there is, and the closed number
// and day lexicons go out with them.
//
// Empty ⇒ the utterance is a slot value and nothing else, however it is dressed
// up. That is the whole test, and it is what separates "а что если в 11:00" —
// which is a time, hedged — from "какая сейчас погода в Риме?", which leaves
// "погода" and "риме" behind and is therefore about something.
func ownContent(text string) []string {
var out []string
for _, tok := range turnTokens(text) {
if frameWords[tok] || lexicon.IsFillerParticle(tok) {
continue
}
if _, ok := lexicon.Cardinal(tok); ok {
continue
}
if _, ok := lexicon.Ordinal(tok); ok {
continue
}
if isNumeric(tok) {
continue
}
out = append(out, tok)
}
return out
}
func isNumeric(tok string) bool {
for _, r := range tok {
if !unicode.IsDigit(r) {
return false
}
}
return tok != ""
}
// isCancel reports whether the utterance is nothing but a call-off. Every
// content token has to be a cancel word, so "забудь" ends the exchange and
// "забудь купить молоко" does not.
func isCancel(text string) bool {
content := ownContent(text)
if len(content) == 0 {
return false
}
for _, tok := range content {
if !cancelWords[tok] {
return false
}
}
return true
}
// carriesOwnRequest reads the ROUTED decision for the thing that decides this:
// does the utterance ask for something in its own right? Each intent is asked
// the question in its own terms, because "its own slots filled from its own
// words" means a different field for each of them.
//
// A query or a system question needs no further evidence — the router already
// read a question in these words. The write intents need the verb or the slot
// that names the request, so a bare value the router guessed a home for does
// not count as one.
func carriesOwnRequest(dec router.Decision, text string) bool {
if dec.Clarify {
// The router itself was unsure. An utterance she could not route is
// not an utterance that outranks the question in front of it.
return false
}
switch dec.Intent {
case router.IntentQuery, router.IntentSystem:
return true
case router.IntentReminder:
return carriesReminderVerb(text)
case router.IntentFact, router.IntentNote:
return router.CarriesCaptureVerb(text)
case router.IntentAct:
// An act that resolved to a capability is a command. One that did not
// is words she cannot execute anyway, so it stays an answer and gets
// re-asked — the same thing that happens to it today.
return dec.Slots.HasFn
default: // chat
return false
}
}
// carriesReminderVerb — "напомни" and its forms, matched over tokens. The
// reminder verbs are a closed lexicon and are not capture verbs, so
// CarriesCaptureVerb never sees them.
func carriesReminderVerb(text string) bool {
toks := turnTokens(text)
for _, v := range lexicon.ReminderVerbs() {
for _, t := range toks {
if t == strings.ToLower(v) {
return true
}
}
}
return false
}
// offlineOwnRequest is the shape half of the evidence: the offline token tests,
// which cost nothing and never depend on the model that produced the routing.
// It is also the whole answer when there is no route to read — the classifier
// is the failure floor and a turn must never break on the model.
func offlineOwnRequest(text string) bool {
return router.IsQuestionShaped(text) || router.CarriesCaptureVerb(text) || carriesReminderVerb(text)
}
// classifyTurnRole decides what this utterance is against the pending action.
//
// The fast path is the first line and it is a fast path to the SAME answer, not
// a second decision procedure: an utterance with no content of its own can
// never be a request of its own, so it can never be anything but an answer, and
// the route below would spend a second on the resident model to say so. Every
// other utterance is routed first, and the role is read off the decision.
//
// `routed` is the turn's routing, already computed; ok is false when there was
// none to compute (no router wired, or the route failed). A failed route falls
// to the offline shape tests rather than breaking the turn.
func classifyTurnRole(q *dialogue.PendingQuestion, text string, answer dialogue.Slots, routed router.Decision, ok bool) turnRole {
if isCancel(text) {
return roleCancel
}
// Two pieces of evidence, and the content gate in front of both. The shape
// tests are the floor and answer for free; the route is what sees a request
// with no shape to it — "погода в риме" asks a question and carries neither
// a question mark nor an interrogative, and only the router knows that.
own := false
if len(ownContent(text)) > 0 {
own = offlineOwnRequest(text) || (ok && carriesOwnRequest(routed, text))
}
if !own {
if replacesFilledSlot(q, answer) {
return roleCorrection
}
return roleAnswer
}
if router.IsQuestionShaped(text) || (ok && (routed.Intent == router.IntentQuery || routed.Intent == router.IntentSystem)) {
return roleSideQuery
}
return roleNewRequest
}
// replacesFilledSlot reports whether the utterance overwrites something the
// pending action already had, rather than filling the gap she asked about —
// "нет, на девять" while she is waiting for the subject. Both are handled the
// same way (dialogue.Answer already prefers the newer value), so this only
// names the turn honestly for the log and for the decision trace V-564 adds.
func replacesFilledSlot(q *dialogue.PendingQuestion, answer dialogue.Slots) bool {
if q == nil {
return false
}
asked := make(map[dialogue.Slot]bool, len(q.Missing))
for _, s := range q.Missing {
asked[s] = true
}
if answer.HasTime && q.Slots.HasTime && !asked[dialogue.SlotTime] && !answer.Time.Equal(q.Slots.Time) {
return true
}
if answer.HasKey && q.Slots.HasKey && !asked[dialogue.SlotKey] && answer.Key != q.Slots.Key {
return true
}
return false
}
+233
View File
@@ -0,0 +1,233 @@
package main
import (
"context"
"strings"
"testing"
"time"
"github.com/kami/maven/internal/dialogue"
"github.com/kami/maven/internal/router"
)
// TestOwnContentSeparatesAValueFromAQuestion pins the test the whole role
// classifier rests on: after the frame, the numbers and the closed time sets
// come out, does anything of his own remain? A hedged time leaves nothing. A
// question about the weather leaves the weather.
func TestOwnContentSeparatesAValueFromAQuestion(t *testing.T) {
cases := []struct {
text string
own bool
}{
{"в 11:00", false},
{"в семь вечера", false},
{"нет, в 15:00", false},
{"а что если в 11:00", false},
{"на 9", false},
{"а, да, прости — на 9", false},
{"завтра", false},
{"в половине восьмого", false},
{"какая сейчас погода в Риме?", true},
{"кто изобрёл телефон", true},
{"напомни в 11:00", true},
{"позвонить маме", true},
{"запиши что я пил воду", true},
}
for _, tc := range cases {
if got := len(ownContent(tc.text)) > 0; got != tc.own {
t.Errorf("ownContent(%q) = %v, want own content = %v", tc.text, ownContent(tc.text), tc.own)
}
}
}
// TestCancelIsTheWholeUtterance — a call-off calls the request off, and a
// sentence that merely contains the word does not.
func TestCancelIsTheWholeUtterance(t *testing.T) {
for _, yes := range []string{"отмена", "забудь", "неважно", "проехали", "cancel", "ой, отмена"} {
if !isCancel(yes) {
t.Errorf("isCancel(%q) = false, want true", yes)
}
}
for _, no := range []string{"забудь купить молоко", "в 11:00", "позвонить маме", ""} {
if isCancel(no) {
t.Errorf("isCancel(%q) = true, want false", no)
}
}
}
// TestTurnRoleReadsTheRoutedDecision — the inversion itself. The same utterance
// gets a different role depending on what the router made of it, which is the
// evidence the old guard never had.
func TestTurnRoleReadsTheRoutedDecision(t *testing.T) {
q := &dialogue.PendingQuestion{
Intent: dialogue.Intent(router.IntentReminder),
Missing: []dialogue.Slot{dialogue.SlotTime},
}
dec := func(in router.Intent, s router.Slots) router.Decision {
return router.Decision{Intent: in, Slots: s}
}
cases := []struct {
name string
text string
routed router.Decision
ok bool
answer dialogue.Slots
want turnRole
}{
{
// The measured defect. The extractor finds "сейчас" and would have
// closed the gap with it; the route says this is a question of its
// own, and the question wins.
name: "a world question mid-flow is a side query",
text: "какая сейчас погода в Риме?",
routed: dec(router.IntentQuery, router.Slots{Text: "какая сейчас погода в Риме?"}),
ok: true,
answer: dialogue.Slots{HasTime: true, Time: time.Now()},
want: roleSideQuery,
},
{
name: "a hedged time is an answer even routed as a query",
text: "а что если в 11:00",
routed: dec(router.IntentQuery, router.Slots{Text: "а что если в 11:00"}),
ok: true,
answer: dialogue.Slots{HasTime: true, Time: time.Now()},
want: roleAnswer,
},
{
name: "a fresh reminder is a new request",
text: "напомни завтра позвонить маме",
routed: dec(router.IntentReminder, router.Slots{Text: "позвонить маме", HasTime: true}),
ok: true,
want: roleNewRequest,
},
{
name: "a capture is a new request",
text: "запиши что я пил воду",
routed: dec(router.IntentFact, router.Slots{Key: "water", HasKey: true}),
ok: true,
want: roleNewRequest,
},
{
name: "an act that resolved to a capability is a new request",
text: "выключи свет в спальне",
routed: dec(router.IntentAct, router.Slots{Fn: "light_off", HasFn: true}),
ok: true,
want: roleNewRequest,
},
{
// She could not route it. An utterance she did not understand does
// not outrank the question in front of it.
name: "a clarify decision is not a request of its own",
text: "выключи свет",
routed: router.Decision{Intent: router.IntentAct, Slots: router.Slots{Fn: "light_off", HasFn: true}, Clarify: true},
ok: true,
want: roleAnswer,
},
{
name: "a bare noun that answers nothing is still an answer",
text: "ага",
ok: false,
want: roleAnswer,
},
{
name: "no route to read falls back to the shape",
text: "кто изобрёл телефон",
ok: false,
want: roleSideQuery,
},
{
name: "a call-off needs no route at all",
text: "отмена",
ok: false,
want: roleCancel,
},
}
for _, tc := range cases {
if got := classifyTurnRole(q, tc.text, tc.answer, tc.routed, tc.ok); got != tc.want {
t.Errorf("%s: classifyTurnRole(%q) = %s, want %s", tc.name, tc.text, got, tc.want)
}
}
}
// TestTurnRoleNamesACorrection — the answer overwrites a slot she was not
// asking about. Handled like an answer, named as what it is.
func TestTurnRoleNamesACorrection(t *testing.T) {
nine := time.Date(2026, 8, 6, 9, 0, 0, 0, time.UTC)
q := &dialogue.PendingQuestion{
Intent: dialogue.Intent(router.IntentReminder),
Missing: []dialogue.Slot{dialogue.SlotText},
Slots: dialogue.Slots{HasTime: true, Time: nine.Add(2 * time.Hour)},
}
got := classifyTurnRole(q, "нет, на 9", dialogue.Slots{HasTime: true, Time: nine}, router.Decision{}, false)
if got != roleCorrection {
t.Fatalf("role = %s, want %s", got, roleCorrection)
}
}
// TestRomeIsAnsweredAndTheReminderIsNotInvented — the measured failure of
// 2026-08-05, end to end through the real cascade. "напомни позвонить маме"
// parks the time question; the weather question that follows must not become
// its answer, must not create a reminder for a time nobody asked for, and must
// not be dropped in silence.
func TestRomeIsAnsweredAndTheReminderIsNotInvented(t *testing.T) {
ctx := context.Background()
h, st := newRoutingClarifyHandler(t)
if reply := h.handleText(ctx, "web", "напомни позвонить маме"); !strings.Contains(reply, "?") {
t.Fatalf("expected the time question, got %q", reply)
}
reply := h.handleText(ctx, "web", "какая сейчас погода в Риме?")
if strings.Contains(reply, "напомню") {
t.Fatalf("the question was eaten as the reminder's time again: %q", reply)
}
if !strings.HasPrefix(reply, clarifyDropped) {
t.Fatalf("the parked request died without a word: %q", reply)
}
if reminders, err := st.DueReminders(ctx, h.now().Add(48*time.Hour)); err != nil || len(reminders) != 0 {
t.Fatalf("a reminder was invented for a time nobody asked for: %v err=%v", reminders, err)
}
if h.clarifyStore.Get(dialogueIDFor(sourceText, "web"), h.now()) != nil {
t.Fatal("the parked question must be gone, not left to eat the next turn")
}
}
// TestClarifyCancelEndsTheExchange — "отмена" while she is waiting calls the
// half-built request off, out loud, and creates nothing.
func TestClarifyCancelEndsTheExchange(t *testing.T) {
ctx := context.Background()
h, st := newRoutingClarifyHandler(t)
if reply := h.handleText(ctx, "web", "напомни позвонить маме"); !strings.Contains(reply, "?") {
t.Fatalf("expected the time question, got %q", reply)
}
if reply := h.handleText(ctx, "web", "отмена"); reply != clarifyCancelled {
t.Fatalf("reply = %q, want %q", reply, clarifyCancelled)
}
if reminders, err := st.DueReminders(ctx, h.now().Add(48*time.Hour)); err != nil || len(reminders) != 0 {
t.Fatalf("a cancelled request still landed: %v err=%v", reminders, err)
}
if h.clarifyStore.Get(dialogueIDFor(sourceText, "web"), h.now()) != nil {
t.Fatal("a cancelled exchange must leave nothing parked")
}
}
// TestTheTurnIsRoutedOnce — the cost bound. A turn with a question parked pays
// for one extra route and not two: the clarify resolver and the pipeline read
// the same memo.
func TestTheTurnIsRoutedOnce(t *testing.T) {
h, _ := newRoutingClarifyHandler(t)
rt := h.newTurnRoute("какая сейчас погода в Риме?", h.now())
ctx := withTurnRoute(withDialogueID(context.Background(), voiceDialogueID), rt)
first, ok := h.routeForRole(ctx, rt.text)
if !ok {
t.Fatal("the cascade must produce a decision to classify against")
}
second, _, _, err := rt.resolve(ctx)
if err != nil {
t.Fatalf("resolve: %v", err)
}
if second.Intent != first.Intent || second.Utterance != first.Utterance {
t.Fatalf("the pipeline routed again and got something else: %+v vs %+v", second, first)
}
}
+104
View File
@@ -0,0 +1,104 @@
package main
import (
"context"
"log"
"sync"
"time"
"github.com/kami/maven/internal/dialogue"
"github.com/kami/maven/internal/router"
)
// turnRoute is this turn's routing, computed at most once.
//
// It exists because the arbitration was inverted (Vikunja #560): the clarify
// resolver now reads the routed decision before deciding what the utterance is,
// and the pipeline then acts on that same decision. Routing twice would cost a
// second on the resident model and — worse — could disagree with itself, which
// is exactly the class of bug this task is about.
type turnRoute struct {
h *reactiveHandler
text string
now time.Time
once sync.Once
dec router.Decision
cont bool
prev *dialogue.Session
err error
// dropped — what she let go of this turn and must say out loud. A parked
// request that dies without a word leaves him thinking it landed.
dropped string
}
type turnRouteKey struct{}
func (h *reactiveHandler) newTurnRoute(text string, now time.Time) *turnRoute {
return &turnRoute{h: h, text: text, now: now}
}
func withTurnRoute(ctx context.Context, rt *turnRoute) context.Context {
return context.WithValue(ctx, turnRouteKey{}, rt)
}
// turnRouteFrom returns the turn's memo, or nil when the caller is not inside
// runTurn — a unit test calling one resolver directly, most often.
func turnRouteFrom(ctx context.Context) *turnRoute {
rt, _ := ctx.Value(turnRouteKey{}).(*turnRoute)
return rt
}
// resolve does the routing exactly as step 5 of runTurn does it: an elliptical
// follow-up is answered from the previous turn, everything else goes to the
// router. One copy of that, so the pre-route the clarify resolver reads and the
// decision the pipeline acts on cannot drift apart.
func (r *turnRoute) resolve(ctx context.Context) (router.Decision, bool, *dialogue.Session, error) {
r.once.Do(func() {
if r.h.dialogueSessions != nil {
r.prev = r.h.dialogueSessions.Get(dialogueIDOf(ctx), r.now)
}
if dec, cont := continuationDecision(r.prev, r.text, r.now); cont {
log.Printf("voice: continuation of %s from the previous turn", dec.Intent)
r.dec, r.cont = dec, true
return
}
if r.h.router == nil {
r.err = router.ErrNoIntents
return
}
r.dec, r.err = r.h.router.Route(ctx, r.text, r.now)
})
return r.dec, r.cont, r.prev, r.err
}
// routeForRole gives the role classifier the turn's routed decision. The second
// return is false when there is no usable decision — no router wired, or the
// route failed — and the classifier falls back to its offline tests then. A
// turn must never break on the model, so the error is logged and swallowed
// here; step 5 reads the same memo and reports it the way it always has.
func (h *reactiveHandler) routeForRole(ctx context.Context, text string) (router.Decision, bool) {
rt := turnRouteFrom(ctx)
if rt == nil {
rt = h.newTurnRoute(text, h.now())
}
dec, _, _, err := rt.resolve(ctx)
if err != nil {
log.Printf("voice: role — no route to classify against (%v), falling back to the offline tests", err)
return router.Decision{}, false
}
return dec, true
}
// needsRoute reports whether classifying this utterance's role is worth a
// route. It is not: an utterance with no content of its own carries no request
// of its own, so the classifier reaches the same answer without the model. A
// call-off is the same — it is read off a closed lexicon and nothing else.
//
// This is a fast path to the SAME answer and must stay one. If it ever needs a
// rule the classifier does not have, it has become a second decision procedure
// and it is the thing V-560 deleted.
func needsRoute(text string) bool {
return !isCancel(text) && len(ownContent(text)) > 0
}
+58 -28
View File
@@ -53,6 +53,7 @@ import (
"github.com/kami/maven/internal/audio"
"github.com/kami/maven/internal/crawl"
"github.com/kami/maven/internal/decision"
"github.com/kami/maven/internal/dialogue"
"github.com/kami/maven/internal/ipc"
"github.com/kami/maven/internal/lexicon"
@@ -137,6 +138,13 @@ type reactiveHandler struct {
// slot per reach, not one for the box. nil ⇒ no carry-over.
dialogueSessions *dialogue.SessionStore
// decisions holds the last few turns' arbitration records (V-564): who
// claimed the turn, who lost it and who was never asked. In memory and
// bounded, because a turn record is read minutes later or never, and none
// of his words belong in a table that outlives the diagnosis. nil ⇒ nothing
// is recorded, which is what a test that did not ask for one gets.
decisions *decision.Ring
// clarifyStore parks the request behind an open question she asked (see
// clarify.go). nil ⇒ she falls back to the canned "не поняла" reply.
clarifyStore *dialogue.ClarifyStore
@@ -248,6 +256,26 @@ const (
//
// The ordering is load-bearing — see the step comments.
func (h *reactiveHandler) runTurn(ctx context.Context, text string, src turnSource) string {
// 0. the decision record (V-564). Installed here rather than in the IPC
// entry point, so the mic, telegram and the web all leave the same trail —
// a record only the web produced would be missing exactly the turns that
// are hardest to reproduce. It rides the context, costs a few dozen structs
// on a human-rate path, and no claim site can change a route with it.
if h.decisions != nil {
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())) }()
}
// 0b. the turn's routing, computed at most once and shared (Vikunja #560).
// The clarify resolver reads it to decide what this utterance IS before
// claiming it, and step 5 acts on the same decision — routing twice would
// cost a second on the resident model and could disagree with itself.
now := h.now()
rt := h.newTurnRoute(text, now)
ctx = withTurnRoute(ctx, rt)
// 1. expired clarify — a question was parked but its TTL ran out, so the
// request behind it is gone. Say that out loud (see clarify.go) and carry
// on: these words are still routed as a fresh utterance below, with the
@@ -263,7 +291,7 @@ func (h *reactiveHandler) runTurn(ctx context.Context, text string, src turnSour
// 2. confirm turn — if a destructive act is parked, this utterance is its
// y/n answer, not a fresh command. Handled before routing so "да" doesn't
// get classified as some other intent.
if reply, handled := h.resolveConfirm(ctx, text); handled {
if reply, handled := h.resolveConfirm(ctx, text); notePreRoute(ctx, "confirm", handled) {
return withNotice(expiredNotice, reply)
}
@@ -275,15 +303,19 @@ func (h *reactiveHandler) runTurn(ctx context.Context, text string, src turnSour
// so the notice is empty here in practice. withNotice anyway: every exit
// from runTurn carries it, and that is what stops the next one from
// forgetting.
if reply, handled := h.resolveClarifyAnswer(ctx, text); handled {
if reply, handled := h.resolveClarifyAnswer(ctx, text); notePreRoute(ctx, "clarify-answer", handled) {
return withNotice(expiredNotice, reply)
}
// It did not claim the turn. If it let a parked request go to get out of the
// way, that has to be said in front of whatever these words are answered
// with — carried on the same notice, so every exit below keeps it.
expiredNotice = withNotice(expiredNotice, rt.dropped)
// 4. quiet-hours toggle — keyword match, not classifier-dependent.
// "тихий режим" / "quiet on" would route through the classifier
// unreliably (it's a command, not a free-form query), so we match it
// before routing. Same pattern as the confirm turn above.
if reply, handled := h.resolveQuietToggle(ctx, text, src); handled {
if reply, handled := h.resolveQuietToggle(ctx, text, src); notePreRoute(ctx, "quiet-toggle", handled) {
return withNotice(expiredNotice, reply)
}
@@ -291,14 +323,14 @@ func (h *reactiveHandler) runTurn(ctx context.Context, text string, src turnSour
// sent. Only handled when a pending nudge is actually inside the window
// (snooze.go); otherwise the words route normally, because "потом" is an
// ordinary word and eating every one of them would break real sentences.
if reply, handled := h.resolveSnooze(ctx, text, src); handled {
if reply, handled := h.resolveSnooze(ctx, text, src); notePreRoute(ctx, "snooze", handled) {
return withNotice(expiredNotice, reply)
}
// 4c. spoken ack — "готово" closes that same nudge as `acted`. Only the
// contentless form is intercepted here; "выпил воды" keeps routing and
// closes the nudge after its fact lands (ackFromFact, step 8b).
if reply, handled := h.resolveAck(ctx, text, src); handled {
if reply, handled := h.resolveAck(ctx, text, src); notePreRoute(ctx, "ack", handled) {
return withNotice(expiredNotice, reply)
}
@@ -306,7 +338,7 @@ func (h *reactiveHandler) runTurn(ctx context.Context, text string, src turnSour
// turn and names what it should have been (repair.go). Before routing,
// like the confirm and clarify turns: routing the correction as a fresh
// utterance files the correction itself instead of fixing anything.
if reply, handled := h.resolveRepair(ctx, text); handled {
if reply, handled := h.resolveRepair(ctx, text); notePreRoute(ctx, "repair", handled) {
return withNotice(expiredNotice, reply)
}
@@ -314,7 +346,7 @@ func (h *reactiveHandler) runTurn(ctx context.Context, text string, src turnSour
// just read (ordinal.go). Before routing, and only when a list is actually
// bound to the session: with nothing offered, "второй" is an ordinary word
// and keeps routing.
if reply, handled := h.resolveCandidate(ctx, text, src); handled {
if reply, handled := h.resolveCandidate(ctx, text, src); notePreRoute(ctx, "ordinal", handled) {
return withNotice(expiredNotice, reply)
}
@@ -323,22 +355,7 @@ func (h *reactiveHandler) runTurn(ctx context.Context, text string, src turnSour
// missing, so no amount of routing recovers it, and the model's guess
// costs seconds to obtain and is close to a coin flip. Everything else
// goes to the router.
var (
dec router.Decision
err error
prev *dialogue.Session
)
now := h.now()
if h.dialogueSessions != nil {
prev = h.dialogueSessions.Get(dialogueIDOf(ctx), now)
}
cont := false
if dec, cont = continuationDecision(prev, text, now); cont {
log.Printf("voice: continuation of %s from the previous turn", dec.Intent)
}
if !cont {
dec, err = h.router.Route(ctx, text, now)
}
dec, cont, prev, err := rt.resolve(ctx)
if err != nil {
// ErrNoIntents ⇒ classifier unseeded (cold boot). reply with a
// "still warming up" rather than a wire error.
@@ -359,21 +376,31 @@ func (h *reactiveHandler) runTurn(ctx context.Context, text string, src turnSour
// ("а завтра?" … "а послезавтра?") keeps working.
if h.dialogueSessions != nil {
if !cont {
dec = followUpMerge(prev, dec, now)
merged := followUpMerge(prev, dec, now)
noteMerge(ctx, dec, merged)
dec = merged
}
if !dec.Clarify {
h.rememberTurn(ctx, prev, dec, now)
}
}
// 7. clarify — she is not sure. If one named thing is missing, ask about it
// and park the request (clarify.go); otherwise the replier's canned reply
// stands.
if dec.Clarify {
// 7. clarify — something she needs is missing. If one named thing is missing,
// ask about it and park the request (clarify.go); otherwise the replier's
// canned reply stands.
//
// Not gated on dec.Clarify alone (Vikunja #557). A turn the cascade routed
// confidently but incompletely skipped this entirely: "напомни позвонить"
// reached applyAction, failed on the missing time, parked nothing, and the
// "в семь вечера" that followed was web-searched as a world question. A
// required slot that missingFor names is a gap whatever the confidence.
if dec.Clarify || len(missingFor(dec)) > 0 {
if reply := h.hexisBeforeClarify(ctx, dec); reply != "" {
return withNotice(expiredNotice, reply)
}
if question, asked := h.askClarify(ctx, dec); asked {
noteTerminal(ctx, "clarify-ask", dec.Intent,
"the route was below the threshold, so she asked instead of acting")
return withNotice(expiredNotice, question)
}
}
@@ -390,6 +417,9 @@ func (h *reactiveHandler) runTurn(ctx context.Context, text string, src turnSour
// the round-trip stays alive.
replyText := h.applyAction(ctx, dec)
log.Printf("voice: applyAction returned: %q", replyText)
// A query turn was already claimed by a source inside the chain; every other
// intent has no chain and no scoreboard, so the handler is the winner.
noteTerminal(ctx, "action-handler", dec.Intent, "")
// 8b. a fact that answers a live nudge closes it as `acted` (ack.go).
// Silent: the fact reply stands, she does not congratulate him for it.
+14 -1
View File
@@ -11,6 +11,7 @@ import (
"time"
"github.com/kami/maven/internal/config"
"github.com/kami/maven/internal/decision"
"github.com/kami/maven/internal/delivery"
"github.com/kami/maven/internal/delivery/voicesink"
"github.com/kami/maven/internal/dialogue"
@@ -293,7 +294,11 @@ func wireVoice(cfg *config.Config, coreAPI ipc.CoreAPI, phr phraser.Phraser, mem
},
dataStore: dataStore,
dialogueSessions: dialogueSessions,
clarifyStore: clarifyStore,
// 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(),
clarifyStore: clarifyStore,
// 0 here (unset config) ⇒ the dialogue default.
clarifyMaxAttempts: cfg.Voice.ClarifyMaxAttempts,
extractor: router.Extractor{Time: timeParser, Acts: matcher, Facts: router.DefaultFactParser{}},
@@ -400,6 +405,14 @@ func buildRouter(emb router.Embedder, acts router.ActMatcher, threshold float64,
// explicit capture marker beats the model, which called it an act and
// rewrote the task text (Vikunja #467). After the rules above because a
// marker never collides with a clock or agenda question.
// After Praxis, whose bare "закрой" claim this rule cannot reach (it needs the
// board noun), and before the capture marker, which would otherwise read
// "убери из задач купить молоко" as a new task (Vikunja #512).
grammars = append(grammars, router.TaskStatusGrammar())
// Before the capture markers, which all need an object. A capture verb
// alone is a fact with no key, and the clarify path asks for it rather than
// letting the model invent an answer (Vikunja #557).
grammars = append(grammars, router.BareCaptureGrammar()...)
grammars = append(grammars, router.TaskCaptureGrammar())
// After the capture marker, so "запиши" still wins over "расскажи", and
// last overall because it matches on the first word alone: "расскажи про
+45
View File
@@ -0,0 +1,45 @@
package main
import (
"context"
"fmt"
"io"
"github.com/kami/maven/internal/store"
)
// runWipe implements the -wipe flag: it prints what the database holds, and
// removes it only when the operator also passed -confirm-wipe (Vikunja #494).
//
// Two flags rather than one, because the destructive reading of a single flag
// is the reading a mistyped command gets. Without the confirmation this is a
// dry run that costs nothing and answers the question a QA session actually
// has — what is on this box right now.
//
// It runs before any daemon component is wired, so nothing is writing while
// the tables go. The daemon exits afterwards rather than serving a store it
// just emptied, because every component that read the old rows at boot would
// still be holding them.
func runWipe(ctx context.Context, st *store.Store, out io.Writer, confirmed bool) error {
counts, err := st.WipeCounts(ctx)
if err != nil {
return fmt.Errorf("wipe: read counts: %w", err)
}
total := 0
for _, c := range counts {
total += c.Rows
fmt.Fprintf(out, " %-24s %d\n", c.Table, c.Rows)
}
fmt.Fprintf(out, " %-24s %d rows in %d tables\n", "TOTAL", total, len(counts))
if !confirmed {
fmt.Fprintln(out, "\nnothing was deleted. pass -confirm-wipe to delete all of it.")
fmt.Fprintln(out, "config, models, passkeys and the encryption key are files and are never touched.")
return nil
}
if err := st.Wipe(ctx); err != nil {
return err
}
fmt.Fprintf(out, "\nwiped. %d rows gone, the schema is intact, mavend knows nobody.\n", total)
return nil
}
+40
View File
@@ -65,6 +65,7 @@ type fakeCore struct {
// for handleTrace tests
tickTrace ipc.TickTrace
traceErr error
turns []ipc.TurnDecision
// for handleChatAPI tests
chatText string
@@ -173,6 +174,10 @@ func (f *fakeCore) RevertFact(_ context.Context, key string) (int64, error) {
return f.revertNewID, nil
}
func (f *fakeCore) TurnDecisions(_ context.Context, _ int) ([]ipc.TurnDecision, error) {
return f.turns, nil
}
func (f *fakeCore) TickTrace(_ context.Context) (ipc.TickTrace, error) {
if f.traceErr != nil {
return ipc.TickTrace{}, f.traceErr
@@ -825,6 +830,41 @@ func TestHandleTrace(t *testing.T) {
t.Error("rendered 'nothing fired' but a winner was set")
}
})
// The turn arbitration shares this page (V-564). A reader must see the
// winner, a loser and the claimants that were never asked, because the last
// of those is what the hardcoded ordering hides.
t.Run("renders the turn decision record", func(t *testing.T) {
core := &fakeCore{turns: []ipc.TurnDecision{{
Ts: time.Date(2025, 6, 1, 12, 0, 0, 0, time.UTC),
Utterance: "какая погода в риме",
Winner: "query:weather",
Claims: []ipc.TurnClaim{
{Stage: "query", Claimant: "weather", Intent: "query", Outcome: "won"},
{Stage: "query", Claimant: "calendar", Outcome: "declined", Reason: "no answer"},
{Stage: "query", Claimant: "kiwix", Outcome: "never_asked"},
},
}}}
rr := httptest.NewRecorder()
handleTrace(rr, httptest.NewRequest(http.MethodGet, "/trace", nil), core)
body := rr.Body.String()
for _, want := range []string{"какая погода в риме", "query:weather", "calendar", "kiwix", "never_asked"} {
if !strings.Contains(body, want) {
t.Errorf("rendered page is missing %q", want)
}
}
})
t.Run("no turns renders the empty note, not an error", func(t *testing.T) {
rr := httptest.NewRecorder()
handleTrace(rr, httptest.NewRequest(http.MethodGet, "/trace", nil), &fakeCore{})
if rr.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rr.Code)
}
if !strings.Contains(rr.Body.String(), "no turn has run") {
t.Error("empty ring did not render its note")
}
})
}
// --- handleRevert ---
+204 -23
View File
@@ -883,14 +883,19 @@ type taskRow struct {
Created string
Resolved string
ResolvedBy string
// DueValue and Weight are the raw values the edit form posts back
// (Vikunja #509). Due above is for reading and says "—" for no date; a
// date input needs "2026-08-07" or the empty string.
DueValue string
Weight int
// Why — the ranker's reason for this row's position (Vikunja #129), in
// Russian, empty when nothing distinguished the task. Blank is the honest
// rendering: he never said this one mattered more.
Why string
}
// handleTasks serves the task review surface (GET) and the four writes it
// offers (POST): add, confirm, done, drop.
// handleTasks serves the task review surface (GET) and the five writes it
// offers (POST): add, edit, confirm, done, drop.
//
// Not step-up gated, unlike /tools and /routines, and the difference is the
// point: enabling a tool defines argv Maven will execute, and accepting a
@@ -900,6 +905,13 @@ type taskRow struct {
// still sits behind whatever transport auth fronts mavweb, like every other
// page.
//
// "edit" was re-argued on the same terms rather than inheriting the exemption
// (Vikunja #509), and it stays ungated. It rewrites a line on a list he reads
// himself, the same blast radius "drop" already has on this page, and the store
// refuses the two edits that would cost something: a resolved task keeps the
// text it was finished under, and a text collision with another live row is
// named instead of merged.
//
// "confirm" is the only interesting move: it promotes a candidate Maven derived
// from something she read into work he owns. That review step is why derived
// tasks are captured as candidates in the first place.
@@ -965,6 +977,7 @@ func handleTasks(w http.ResponseWriter, r *http.Request, core ipc.CoreAPI) {
ID: t.ID, Text: t.Text, Source: t.Source, Evidence: t.Evidence,
Status: t.Status, Created: fmtTaskTime(&t.CreatedTs),
Due: fmtTaskDate(t.Due), Resolved: fmtTaskTime(t.Resolved),
DueValue: fmtTaskDateValue(t.Due), Weight: t.Weight,
Why: r.Reason,
}
if t.Status == "candidate" {
@@ -979,11 +992,12 @@ func handleTasks(w http.ResponseWriter, r *http.Request, core ipc.CoreAPI) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := tasksTmpl.Execute(w, struct {
Msg, Err string
Stalls []tasks.Stall
Candidates []taskRow
Open []taskRow
Resolved []taskRow
ResolvedMore bool
}{msg, errMsg, cands, open, resolved, resolvedTotal > len(resolved)}); err != nil {
}{msg, errMsg, tasks.Stalls(live, now()), cands, open, resolved, resolvedTotal > len(resolved)}); err != nil {
log.Printf("tasks render: %v", err)
}
}
@@ -999,27 +1013,16 @@ func applyTaskPost(ctx context.Context, core ipc.CoreAPI, r *http.Request) (stri
return "", errors.New("empty task text")
}
req := ipc.CaptureTaskReq{Text: text, Source: "tap:web", Status: "open", Ts: now()}
// Importance is his, stated on the form. Out-of-range values are
// clamped rather than rejected — a bad select is not worth a 400.
if v := r.FormValue("weight"); v != "" {
// strconv, not Sscanf: Sscanf("3junk", "%d") succeeds with 3, and a
// form value is not a place to accept trailing garbage.
wgt, err := strconv.Atoi(v)
if err != nil || wgt < 0 {
return "", fmt.Errorf("bad weight %q", v)
}
if wgt > tasks.MaxWeight {
wgt = tasks.MaxWeight
}
req.Weight = wgt
wgt, err := formWeight(r)
if err != nil {
return "", err
}
if d := r.FormValue("due"); d != "" {
due, err := time.ParseInLocation("2006-01-02", d, now().Location())
if err != nil {
return "", fmt.Errorf("bad due date %q", d)
}
req.Due = &due
req.Weight = wgt
due, err := formDue(r, now())
if err != nil {
return "", err
}
req.Due = due
resp, err := core.CaptureTask(ctx, req)
if err != nil {
return "", err
@@ -1037,6 +1040,44 @@ func applyTaskPost(ctx context.Context, core ipc.CoreAPI, r *http.Request) (stri
if err != nil {
return "", errors.New("invalid id")
}
if action == "promote" {
msg, err := promoteCandidate(ctx, core, r, id)
if err != nil {
return "", err
}
return msg, nil
}
if action == "edit" {
// The three fields capture set, and only those (Vikunja #509). Status
// is not editable here: that ladder is one-way and has its own buttons.
text := strings.TrimSpace(r.FormValue("text"))
if text == "" {
return "", errors.New("empty task text")
}
wgt, err := formWeight(r)
if err != nil {
return "", err
}
due, err := formDue(r, now())
if err != nil {
return "", err
}
switch err := core.EditTask(ctx, id, text, due, wgt); {
case err == nil:
return "saved task", nil
case errors.Is(err, ipc.ErrTaskDuplicate):
// Naming the collision instead of merging: two live rows carry two
// provenances, and picking one is not the page's call.
return "", errors.New("another open task already says this — drop one of the two")
case errors.Is(err, ipc.ErrTaskResolved):
return "", errors.New("a resolved task keeps the text it was finished under")
default:
return "", err
}
}
var status, msg string
switch action {
case "confirm":
@@ -1049,11 +1090,134 @@ func applyTaskPost(ctx context.Context, core ipc.CoreAPI, r *http.Request) (stri
return "", fmt.Errorf("unknown action %q", action)
}
if err := core.SetTaskStatus(ctx, id, status, now(), "tap:web"); err != nil {
if errors.Is(err, ipc.ErrTaskNoDoneWhen) {
// The refusal has to name what is missing, or the button looks
// broken. The field it asks for arrives with the intake form
// (Vikunja #511).
return "", errors.New("write a definition of done before confirming this candidate")
}
return "", err
}
return msg, nil
}
// fmtTaskDateValue renders a due date the way <input type=date> requires, or
// "" for no date. Separate from fmtTaskDate, which renders it for reading.
// promoteCandidate turns a candidate into open work with the three things the
// board needs (Vikunja #511): a definition of done, an optional blocker, and an
// optional date.
//
// The definition of done is required, and the refusal is the store's — this
// only reaches it in a readable order. The blocker is a NAME here and an entity
// id in the row: identity lives in Nexus, so the name is resolved first and a
// name Nexus cannot resolve stops the promotion instead of being stored.
//
// A date set here writes a reminder, which is the one unprompted delivery the
// persona allows: he asked to be told, on a day he named.
func promoteCandidate(ctx context.Context, core ipc.CoreAPI, r *http.Request, id int64) (string, error) {
doneWhen := strings.TrimSpace(r.FormValue("done_when"))
if doneWhen == "" {
return "", errors.New("write a definition of done — what has to be true for this to be finished")
}
text := strings.TrimSpace(r.FormValue("text"))
if text == "" {
return "", errors.New("empty task text")
}
due, err := formDue(r, now())
if err != nil {
return "", err
}
blockedOn := ""
if name := strings.TrimSpace(r.FormValue("blocked_on")); name != "" {
ref, err := core.ResolveEntity(ctx, name, []string{"person"})
switch {
case errors.Is(err, ipc.ErrNotImplemented):
return "", errors.New("no identity service here, so blocked-on cannot be stored — leave it empty")
case errors.Is(err, ipc.ErrNoEntity):
return "", fmt.Errorf("nexus does not know %q", name)
case err != nil:
return "", fmt.Errorf("resolving %q: %w", name, err)
case ref.Ambiguous:
// Asking, not picking: a task blocked on the wrong person is a
// mistake nobody can see afterwards.
return "", fmt.Errorf("%q matches %s — say which", name, strings.Join(ref.Candidates, ", "))
}
blockedOn = ref.ID
}
if err := core.SetTaskFields(ctx, id, doneWhen, blockedOn); err != nil {
return "", err
}
if due != nil {
wgt, err := formWeight(r)
if err != nil {
return "", err
}
if err := core.EditTask(ctx, id, text, due, wgt); err != nil {
return "", err
}
}
if err := core.SetTaskStatus(ctx, id, "open", now(), "tap:web"); err != nil {
if errors.Is(err, ipc.ErrTaskNoDoneWhen) {
return "", errors.New("write a definition of done before confirming this candidate")
}
return "", err
}
if due == nil {
return "confirmed", nil
}
// A date-only field has no hour. Nine in the morning, because the reminder
// is about a day's work and being told at midnight is being told the night
// before.
fire := time.Date(due.Year(), due.Month(), due.Day(), 9, 0, 0, 0, due.Location())
if _, err := core.CreateReminder(ctx, fire, text, ""); err != nil {
// The task IS promoted; only the reminder failed. Saying "confirmed"
// and nothing else would leave him expecting a nudge that will not come.
return "", fmt.Errorf("confirmed, but the reminder did not save: %w", err)
}
return "confirmed, and maven will remind you that morning", nil
}
// formWeight reads the importance select. Out-of-range clamps rather than
// rejects — a bad select is not worth a 400 — but trailing garbage is refused,
// because strconv is not Sscanf and "3junk" is not a 3.
func formWeight(r *http.Request) (int, error) {
v := r.FormValue("weight")
if v == "" {
return 0, nil
}
wgt, err := strconv.Atoi(v)
if err != nil || wgt < 0 {
return 0, fmt.Errorf("bad weight %q", v)
}
if wgt > tasks.MaxWeight {
wgt = tasks.MaxWeight
}
return wgt, nil
}
// formDue reads the date input. An empty field is nil, which on an edit means
// "clear the date" — the form has no other way to say it.
func formDue(r *http.Request, now time.Time) (*time.Time, error) {
d := r.FormValue("due")
if d == "" {
return nil, nil
}
due, err := time.ParseInLocation("2006-01-02", d, now.Location())
if err != nil {
return nil, fmt.Errorf("bad due date %q", d)
}
return &due, nil
}
func fmtTaskDateValue(t *time.Time) string {
if t == nil || t.IsZero() {
return ""
}
return t.Local().Format("2006-01-02")
}
func fmtTaskTime(t *time.Time) string {
if t == nil || t.IsZero() {
return "—"
@@ -1251,12 +1415,29 @@ func handleTrace(w http.ResponseWriter, r *http.Request, core ipc.CoreAPI) {
http.Error(w, "core read failed", http.StatusBadGateway)
return
}
// The turn records share this page rather than getting one of their own
// (V-564): both answer the same question — who won, who lost and why — and
// one is about nudges while the other is about utterances. A read failure
// here is not fatal to the page: the rule trace above it still renders, and
// a daemon too old to know the method is the ordinary case during a rolling
// deploy.
turns, err := core.TurnDecisions(ctx, 25)
if err != nil {
log.Printf("trace: turn decisions: %v", err)
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := traceTmpl.Execute(w, trace); err != nil {
if err := traceTmpl.Execute(w, traceData{Tick: trace, Turns: turns}); err != nil {
log.Printf("trace render: %v", err)
}
}
// traceData — what trace.html renders: the last tick's rule arbitration and the
// last turns' claim arbitration.
type traceData struct {
Tick ipc.TickTrace
Turns []ipc.TurnDecision
}
func handleMorning(w http.ResponseWriter, r *http.Request, core ipc.CoreAPI) {
if core == nil {
http.Error(w, "morning disabled (no -core)", http.StatusServiceUnavailable)
+44 -6
View File
@@ -21,20 +21,43 @@
</form>
</section>
{{if .Stalls}}
<section class=card>
<h2 class=card-title>shapes</h2>
<!-- Counts, and nothing about what they mean (V-512). Whether a task should be
dropped is his call and Maven does not have an opinion to show here. -->
<div class=scroll><table>
<tr><th>count</th><th>shape</th></tr>
{{range .Stalls}}<tr><td>{{.N}}</td><td>{{.Line}}</td></tr>{{end}}
</table></div>
</section>
{{end}}
{{if .Candidates}}
<section class=card>
<h2 class=card-title>found, not confirmed <span class=badge>{{len .Candidates}}</span></h2>
<div class=hint>maven derived these from something she read. nothing counts as your work until you confirm it.</div>
<div class=hint>confirming asks for a definition of done: what has to be true for this to be finished. a task without one can never leave the board. a date here also books a reminder that morning.</div>
<div class=scroll><table>
<tr><th>task</th><th>where from</th><th>due</th><th>captured</th><th></th><th></th></tr>
<tr><th>task</th><th>where from</th><th>captured</th><th>confirm</th><th></th></tr>
{{range .Candidates}}<tr>
<td class=text-max>{{.Text}}</td>
<td class=hint>{{.Source}}{{if .Evidence}} — {{.Evidence}}{{end}}</td>
<td>{{.Due}}</td>
<td class=muted>{{.Created}}</td>
<td><form method=post action=/tasks class=inline-form>
<input type=hidden name=id value="{{.ID}}">
<input type=hidden name=action value=confirm>
<input type=hidden name=action value=promote>
<input type=hidden name=text value="{{.Text}}">
<input type=text name=done_when placeholder="готово, когда…" size=26 required>
<!-- A name, not an id. It is resolved against nexus before anything is
stored, and a name nexus cannot place stops the confirmation. -->
<input type=text name=blocked_on placeholder="ждёт кого-то" size=14>
<input type=date name=due value="{{.DueValue}}" title="due date">
<select name=weight title=importance>
<option value=0 {{if eq .Weight 0}}selected{{end}}>normal</option>
<option value=2 {{if eq .Weight 2}}selected{{end}}>важно</option>
<option value=3 {{if eq .Weight 3}}selected{{end}}>срочно</option>
</select>
<button class=btn>confirm</button></form></td>
<td><form method=post action=/tasks class=inline-form>
<input type=hidden name=id value="{{.ID}}">
@@ -48,12 +71,27 @@
<h2 class=card-title>open <span class=badge>{{len .Open}}</span></h2>
<div class=hint>most pressing first — by the deadlines and the urgency you gave. nothing about a task is guessed; the only signal that is not yours is age, which lifts anything sitting here for weeks.</div>
{{if .Open}}<div class=scroll><table>
<tr><th>task</th><th>why</th><th>from</th><th>due</th><th>captured</th><th></th><th></th></tr>
<tr><th>task</th><th>why</th><th>from</th><th>captured</th><th></th><th></th></tr>
{{range .Open}}<tr>
<td class=text-max>{{.Text}}</td>
<!-- The text, the date and the importance are editable in place (V-509): a
dictated task can carry a typo, and a deadline moves. The status is not
here — that ladder is one-way and has its own two buttons. -->
<td class=text-max><form method=post action=/tasks class=inline-form>
<input type=hidden name=id value="{{.ID}}">
<input type=hidden name=action value=edit>
<input type=text name=text value="{{.Text}}" size=30 required>
<input type=date name=due value="{{.DueValue}}" title="due date">
<select name=weight title=importance>
<!-- Any weight that is not one of the three rungs keeps its own option, or
saving an unrelated edit would silently reset it to normal. -->
{{if and (ne .Weight 0) (ne .Weight 2) (ne .Weight 3)}}<option value={{.Weight}} selected>{{.Weight}}</option>{{end}}
<option value=0 {{if eq .Weight 0}}selected{{end}}>normal</option>
<option value=2 {{if eq .Weight 2}}selected{{end}}>важно</option>
<option value=3 {{if eq .Weight 3}}selected{{end}}>срочно</option>
</select>
<button class="btn btn-muted">save</button></form></td>
<td class=hint>{{.Why}}</td>
<td class=hint>{{.Source}}</td>
<td>{{.Due}}</td>
<td class=muted>{{.Created}}</td>
<td><form method=post action=/tasks class=inline-form>
<input type=hidden name=id value="{{.ID}}">
+6 -2
View File
@@ -77,10 +77,14 @@ func TestHandleTasksSplitsCandidatesFromOpen(t *testing.T) {
t.Errorf("body missing %q", want)
}
}
// The candidate must offer confirm, and the open task must not.
if !strings.Contains(body, "value=confirm") {
// The candidate must offer the intake form, and it asks for a definition of
// done before it will confirm anything (V-511).
if !strings.Contains(body, "value=promote") {
t.Error("candidate row has no confirm action")
}
if !strings.Contains(body, "name=done_when") {
t.Error("the confirm form does not ask for a definition of done")
}
}
func TestHandleTasksAddCaptures(t *testing.T) {
+22 -2
View File
@@ -1,9 +1,9 @@
{{template "shellTop" "trace"}}
<h1>Rule Trace</h1>
<div class="hint mb-4">{{.Now | ago}} — winner: <strong>{{if .Winner}}{{.Winner}}{{else}}nothing fired{{end}}</strong></div>
<div class="hint mb-4">{{.Tick.Now | ago}} — winner: <strong>{{if .Tick.Winner}}{{.Tick.Winner}}{{else}}nothing fired{{end}}</strong></div>
<div class=scroll><table class=mono>
<tr><th>rule<th>sev<th>predicate<th>gate<th>blocked by<th>detail<th>selected<th>lost to</tr>
{{range .Rules}}<tr>
{{range .Tick.Rules}}<tr>
<td>{{.RuleName}}</td>
<td>{{.Severity}}</td>
<td class={{if .PredicateResult}}green{{else}}gray{{end}}>{{.PredicateResult}}</td>
@@ -21,5 +21,25 @@
<td>{{.LostTo}}</td>
</tr>{{end}}
</table></div>
<h1 class=mt-4>Turn Decisions</h1>
<div class="hint mb-4">Who claimed each utterance, who lost it, and who was never asked. In memory, newest first, cleared on restart.</div>
{{if not .Turns}}<div class=hint>no turn has run since the daemon started</div>{{end}}
{{range .Turns}}
<details class=mb-4>
<summary><span class=mono>{{.Utterance}}</span><strong>{{if .Winner}}{{.Winner}}{{else}}nobody{{end}}</strong> <span class=hint>{{.Ts | ago}}</span></summary>
<div class=scroll><table class=mono>
<tr><th>stage<th>claimant<th>would have been<th>score<th>outcome<th>why</tr>
{{range .Claims}}<tr>
<td>{{.Stage}}</td>
<td>{{.Claimant}}</td>
<td>{{if .Intent}}{{.Intent}}{{else}}—{{end}}</td>
<td>{{if .HasScore}}{{printf "%.3f" .Score}}{{else}}—{{end}}</td>
<td class={{if eq .Outcome "won"}}green{{else if eq .Outcome "never_asked"}}red{{else}}gray{{end}}>{{.Outcome}}</td>
<td>{{.Reason}}</td>
</tr>{{end}}
</table></div>
</details>
{{end}}
{{template "shellBottom"}}
</html>
+93
View File
@@ -0,0 +1,93 @@
# Routing from audio: four paths, one fixture
**05-08-2026. Vikunja #486.** Workstation `gemma-4-12B-it-qat-UD-Q4_K_XL` with
`mmproj-F16.gguf`, homesrv whisper `ggml-small`, piper `ru_RU-irina-medium`.
**Verdict: transcribe, then route.** One call from audio straight to a route loses 36
points, so it is not a candidate. Moving speech-to-text to the workstation buys 375ms and
better transcripts at no measurable accuracy cost. So #486 proceeds on the two-call shape.
## The numbers
72 Russian cases from `internal/router/eval/ru_routing_v1.json`, rendered by piper at
16kHz mono, 153.9s of audio, mean 2.14s per clip. Every path used the daemon's own
`routeSystem` prompt and `routeGrammar`, read out of `internal/router/llmrouter.go` at run
time, at `temperature 0` and `enable_thinking:false`.
| Path | Intent-only | Verbatim transcripts | p50 | p95 |
|---|---|---|---|---|
| text in, the ceiling | **90.3%** (65/72) | — | 361ms | 495ms |
| whisper on homesrv, then route | **84.7%** (61/72) | 29/72 | 1372ms | 1546ms |
| workstation transcribes, then routes | **83.3%** (60/72) | 48/72 | 997ms | 1177ms |
| workstation, one call from audio | **54.2%** (39/72) | — | 425ms | 756ms |
The 90.3% ceiling is the same model on the same 72 cases with the utterance as text. It is
not the 93.5% in `docs/evals/2026-08-02-workstation-gemma4-12b.md`, which scored all 87
cases including the English ones.
The two speech-to-text paths differ by one case, which is noise on 72. So the choice
between them is latency and transcript quality, and the workstation wins both.
## One call from audio is not a transcription failure
The obvious reading of 54.2% is that the audio encoder cannot hear Russian. It can. Eight
of the failing clips were sent back with a transcribe instruction instead of the router
prompt:
| Clip | Said | Heard, transcribing | Routing from audio |
|---|---|---|---|
| ru-sys-002 | какое число завтра | Какое число завтра? | `unknown` |
| ru-sys-003 | переходи в тихий режим | Переходи в тихий режим. | `unknown` |
| ru-query-001 | сколько воды я выпил с утра | Сколько воды я выпил с утра? | `fact`, value "выпил с утра" |
| ru-act-002 | выключи свет в спальне | Выключи свет в спальне. | `fact`, value "включен" |
Four clips it transcribes word for word, and routes wrong or refuses. The `ru-query-001`
row shows the mechanism: the emitted slot holds the tail of the sentence and the
interrogative head is gone. The model is not deaf, it stops attending to the audio once it
is also holding a 3.5k-character classification prompt.
That pattern decides the whole task. A long system prompt and an audio part compete, so the
transcription has to be its own call with a short instruction. It also means the number
would not be rescued by a better prompt, a longer clip, or a bigger `mmproj`.
The failures cluster where the head of the sentence carries the intent: `ru-act` 1/6,
`ru-sys` 2/5, `ru-query` 12/25. Reminders scored 10/10, because "напомни" is the first word
and nothing after it changes the answer.
## Transcript quality and routing accuracy come apart
The workstation transcribes 48 of 72 verbatim against whisper's 29, and routes one case
worse. Both directions of that appear in the same run:
- `ru-chat-002`: whisper heard "Кто думаешь про переезд", the workstation heard "Что ты
думаешь про переезд". The correct transcript routed to `chat`, the broken one to `query`.
- `ru-query-020`: whisper heard "Кто дальше?", the workstation heard the correct "Что
дальше?". The **broken** transcript routed correctly and the correct one missed.
A word error rate is not a proxy for routing accuracy here. Judge a speech-to-text change
on the routing fixture, not on transcripts.
Three cases only the text path gets right. No speech-to-text path recovers them, so they
are lost in the rendering rather than in the model.
## Latency
Whisper `ggml-small` on homesrv CPU costs p50 998ms for a 2.14s clip, which is nearly
all of that path's 1372ms. The workstation does the same job inside its 997ms end-to-end
total for two calls. So the transfer is worth about 375ms per turn at p50, and more at p95.
Both are above the one-call 425ms, and that is the trade the table settles: 29 points of
accuracy for 572ms.
## Notes for the next run
- `--mmproj /mnt/D/AI/gemma4/mmproj-F16.gguf` has to be in `llama_args` in
`~/.config/mavgpud.json`, or `/props` reports `modalities.audio: false` and every audio
part is dropped silently. It was added for this measurement and removed afterwards, so
the box is back to the text-only config.
- `enable_thinking:false` is mandatory. It was set for all 224 calls here.
- The degenerate `<|channel>thought` output recorded against #486 did not reproduce, in 80
transcribe calls or in 144 routing calls.
- Piper renders at 22050Hz mono. Every clip was resampled with
`ffmpeg -ar 16000 -ac 1 -c:a pcm_s16le`, because 16kHz is what `audio.PCM16kMono`
declares and what the earlier measurement used.
+70
View File
@@ -0,0 +1,70 @@
# Ecosystem reach with the resident model as router
Date: 2026-08-05. Vikunja #517, split out of #405.
Fixture: `internal/router/eval/ru_ecosystem_v1.json`, 30 held-out Russian cases.
Model: Qwen3-1.7B-UD-Q4_K_XL, llama-server on the host at 127.0.0.1:8899.
Harness: `TestReachWithLLMRouter` in `internal/router/eval/llmrouter_test.go`.
## The numbers
| configuration | reached the right place | praxis | hexis | none |
|---|---|---|---|---|
| classifier + hash (V-405 floor) | 16/30 | 0/12 | — | — |
| classifier + ONNX, after the V-516 grammars | 27/30 | 11/12 | — | — |
| **llm-only** (resident model alone) | **17/30 (56.7%)** | **0/12** | 10/10 | 7/8 |
| **cascade + llm** + hash fallback | **28/30 (93.3%)** | **11/12** | 10/10 | 7/8 |
Latency: llm-only p50 1.29s, p95 1.65s. Cascade p50 1.11s, p95 1.64s.
No case errored in either configuration.
## The open question is answered: the model never reaches Praxis
The route grammar lets the model write any string into the `fn` slot. So it
could in principle emit a literal Praxis capability name, and reach a service
the classifier structurally cannot. It does not. **Praxis is 0/12 with the
model alone.** That is exactly what the classifier alone scores. Every one of
the twelve fails the same way: the utterance stays local with an empty `fn`.
So the stage-0 Praxis grammars from V-516 are not a determinism argument. They
are the only path to Praxis that exists. Deleting them takes reach from 11/12
back to 0/12 whichever engine is answering.
The failure is not that the model routes these badly in its own terms. It
spreads them across `query`, `fact`, `system` and `chat`. Those are reasonable
readings of "что требует внимания" and "готово, закрывай" for a model that has
never been told Praxis exists. Nothing in the prompt names a Praxis capability,
so there is no string for it to write.
## What the model does buy
Hexis is 10/10 with the model alone, and the mutating tag is 10/15 llm-only
against 15/15 through the cascade. The model reaches everything Hexis owns
without help, which is the half the act allowlist already names in the prompt.
Cascade + llm scores one point above the classifier baseline: 28/30 against
27/30, the difference being one attention case. That is the same shape as the
routing fixture, where the router buys about 4 points rather than a doubling.
## The two that still miss
- `eco-ru-021 "что там с нексусом"`. Routes `query`, stays local, wants Praxis.
Asking after a named service reads as a question about a thing, and no
grammar claims a service name.
- `eco-ru-029 "сделай это"`. Routes `act` and reaches Hexis. The fixture wants
nothing reached, because "это" names no target. This is the overreach case
and it is the one direction worth failing on. The confirmation binding
downstream still resolves a canonical entity id before anything executes.
The fixture is right that the turn should have asked.
Overreach is 1 in both configurations, under the 4 the harness asserts.
## How to re-run
```sh
MAVEN_LLM_URL=http://127.0.0.1:8899 \
deps/go/go/bin/go test -v -count=1 -timeout 40m \
-run TestReachWithLLMRouter ./internal/router/eval/
```
The host `http_proxy` answers 503 for 127.0.0.1. `noProxyLoopback` in the test
excludes it. A run that scores every case as a route error measured the proxy.
@@ -0,0 +1,69 @@
# Routing with the resident model, re-measured
Date: 2026-08-05. Vikunja #320 items 2 and 3.
Fixture: `internal/router/eval/ru_routing_v1.json`, now **91 cases** (76 ru, 15 en).
Model: Qwen3-1.7B-UD-Q4_K_XL, llama-server on the host at 127.0.0.1:8899.
Harness: `TestLLMRouterBaseline`, `make eval-models`.
## How the block was cleared
Item 2 was blocked because the resident llama-server binds `--host 127.0.0.1
--port 0` inside `maven-mavend-1`. The port is kernel-assigned, scraped from
stderr and never published, so no `go test` on the host can reach it. The task
listed three ways out. This run took the first: a **second** llama-server on
the same gguf, on a fixed host port. The Vega takes the second copy of a 1.7B
without complaint.
## The numbers
| configuration | full | intent-only | p50 | p95 |
|---|---|---|---|---|
| llm-only | 34/91 (37.4%) | 61.5% | 1.24s | 1.65s |
| cascade + llm + hash fallback | 69/91 (75.8%) | 80.2% | 1.19s | 1.65s |
By language, through the cascade: ru 57/76, en 12/15.
Clarify: 3 false, 1 missed. No errors. Six slots deferred to the daemon.
For comparison, the figures that stood in CLAUDE.md were 72.7% full and 77.9%
intent-only, measured on 77 cases. The fixture has grown by 14 cases since, so
this is a new baseline rather than a movement.
## llm-only is low for a reason that is not routing
37.4% full against 61.5% intent-only is the gap, and it is almost entirely
slots. Every reminder case fails with "no time slot, want one". The model
routes `reminder` correctly and leaves the time to the daemon, which is what
the contract asks of it. The cascade fills those slots. That is why the same
model scores 38 points higher inside it.
Three cases errored in the llm-only arm and none in the cascade, which is the
fallback working as designed.
## Item 3: latency
Router p50 1.19s, p95 1.65s, max 1.79s through the cascade. The one earlier
data point in the task, roughly 6s wall clock for `привет` through
`POST /api/chat`, was the whole path and not the router. It is not comparable
and should not be quoted as a routing number.
These numbers are the homesrv floor. With the workstation up, routing completes
against gemma-4-12b at p50 329ms, measured separately in
`docs/evals/2026-08-02-workstation-gemma4-12b.md`.
## What still misses
The confusion is concentrated in one direction: `query→fact ×4`,
`query→note ×3`, `query→system ×3`. A question about his own rows that carries
no interrogative reads as a statement to the model. Ten of the twenty-two
failures are that shape, including "я сегодня вообще пил воду" and "чем я
занимался в среду". This is the case V-546's three-head classifier is aimed at.
The two `разбуди меня` cases clarify at 0.300 instead of routing `reminder`.
## Item 4 is still not run
Killing the resident llama-server to confirm the classifier floor needs a
permission this session does not have. The test is otherwise ready. It now has
a second half. With the workstation up, killing the resident server should
still complete a turn through `modelSeam`. Only killing both proves the
classifier answers.
+8 -1
View File
@@ -1,6 +1,6 @@
# Offloading model work to the workstation
*Last verified: 2026-08-03 @ 12530c8. Living doc: correct it in place, do not append.*
*Last verified: 2026-08-05 @ b789676. Living doc: correct it in place, do not append.*
Owner's call, 2026-08-02. Vikunja #483 is the umbrella. Tasks #484 to #487 are the
work, and this file holds the shape and the rules all four must obey.
@@ -149,6 +149,13 @@ flips. It is wired anyway: `PhraseReminder` is on the same transport and is on.
Then the embedder above, **whisper.cpp** in `mavsttd`, and **piper** in `mavttsd`.
`mavwaked` uses no model at all: an energy-threshold VAD over 30ms frames.
Speech-to-text stays two stages when it moves. One call carrying both a clip and the router
prompt was measured on 05-08-2026. It scores 54.2% intent-only against 84.7% for whisper on
homesrv, on the same 72 cases. The model transcribes clips it then routes wrong, so a long
classification prompt and an audio part compete for attention. Transcribing on the
workstation and routing the text scores 83.3% at p50 997ms. So the transfer buys 375ms and
cleaner transcripts, not accuracy. See `docs/evals/2026-08-05-audio-in-routing.md`.
## Order
1. **Transport** (#484). Nothing else is possible until a seam can cross a host.
+7 -1
View File
@@ -47,7 +47,13 @@ for.
QA session 1 step 2 should say what it actually covers, which is push-to-talk through
`/dash`. It should not read as though it covers the voice loop. The wake path is checked
on the client machine or it is not checked, and today there is no client machine.
on the client machine or it is not checked.
**Correction, 2026-08-05.** This plan said there was no client machine. There is: workpc,
where he sits most of the day and where the microphone is. The sentence was written when
the workstation was only a model host. The verdict above is unchanged, and so is
everything about the seam. What changes is the size of the remaining work: deploying two
daemons and asking mavend to listen on TCP, not acquiring hardware.
That is the honest state, and it is worse than the task suggests: this is not a
configuration gap that a compose entry closes. Until a machine with a microphone runs
+135
View File
@@ -0,0 +1,135 @@
# Plan: dialogue arbitration, one channel and many claimants
Umbrella V-558. This file collects the design for its children.
Last verified: 06-08-2026 @ b6305f1
## A common unit for claims on an utterance (V-565)
**Verdict: four ordinal bands, and the band is the tie-break rather than the decision.
Coverage decides first.** The measurement below says no claimant Maven has today can produce
a graded confidence. A float would be an invention either way. What is available is the KIND
of evidence a claimant holds, and there are exactly four kinds.
### What the claimants report today
Measured 06-08-2026 on the 91-case RU fixture (`internal/router/eval`), through the deployed
cascade with the quantized multilingual-e5-small embedder. The harness is
`TestONNXClaimConfidenceDistribution` and `TestStage0Contention` in
`internal/router/eval/claims_test.go`. Correct means the right intent, or a refusal where the
fixture wants one. Slots are excluded, because a slot miss is a parser question and would
blur what the number is being asked to predict.
| Claimant | Values it can emit | Distribution on the fixture | Correct |
|---|---|---|---|
| Stage 0 grammars, 21 of them | `1.0`, always | claimed 20 of 91 cases | 20/20 (100%) |
| Classifier, cosine | continuous in principle | observed range 0.859 to 0.942 over 71 cases | 44/71 (62%) |
| LLM router | `1.0` or `0.3`, nothing between | not run here, no llama-server | see below |
| Query sources, 22 of them | a bool | not routed by the fixture | n/a |
| Stateful four | nothing at all | n/a | n/a |
Four findings, and each one constrains the band set.
**The classifier's cosine carries no signal about correctness.** It scores 62% below the
median and 62% above it. That is 13/21 in 0.8 to 0.9, and 31/50 in 0.9 to 1.0. The spread is
0.083 wide. Every case sits above the 0.55 threshold, so the gate never fires here. A number
flat against correctness, which never crosses its own gate, is not a confidence.
**Nor does the margin between its top two intents.** Top1 minus top2 is min 0.000, p50
0.009, max 0.025. Sixty-eight of the 71 classified cases sit under 0.02 and score 60%. Three
clear 0.02 and score 3/3, which is a sample of three. So the ledger's question is answered:
a calibrated float is NOT cheaply available from the classifier alone. Nearest-centroid over
frozen seeds ranks intents, and the ranking is decided in the third decimal place. It can say
which intent is nearest. It cannot say how near.
**Stage 0 asserts 1.0 by fiat, and on this fixture the fiat is right.** Twenty of twenty.
That is not evidence that a hand-written anchored pattern is always right. It is evidence
that anchored and nearest are different kinds of claim, and must not share a scale. The gap
is 100% against 62% on the same 91 utterances.
**Stage 0 contention is rarer than the list order suggests.** Exactly one case of 91 draws
two grammars. That is `ru-query-019`, where `calendar-query` and `agenda-query` both match,
and `calendar-query` wins because it is earlier in `buildRouter`. Both would route
`IntentQuery`, so the ordering costs nothing there. The finding is not that ordering is
harmless. It is that the fixture barely exercises what V-558 is about. Part of what a claim
object buys is making the contention countable.
**The LLM router emits two values, and one of them is not a confidence.** `llmFullConfidence`
is 1.0 and `llmThinConfidence` is 0.3. `gateLLMDecision` moves a decision to 0.3 through
three named arms. A fact with no key, an act with no allowlisted fn, a reminder with no
subject. Each is a self-veto with a reason, flattened into a number that then loses the
reason. Both values are meaningful only against `config.DefaultRouterThreshold`. 0.3 is below
0.55 and 1.0 is above it, and nothing anywhere reads any other property of either.
### The band set
Four bands, ordinal, highest first. They name the kind of evidence, because that is the one
thing every claimant can report without inventing it.
**`BandAnchored`.** A literal pattern anchored in the utterance matched, and the matched span
is what decides the intent. Stage 0 grammars and query-source matchers. The claimant is
certain about the shape of the sentence. That is not the same as being certain about the
answer. Measured 20/20.
**`BandStructural`.** A claimant read the whole sentence and produced a complete route. Every
slot the intent requires is filled. The LLM router at `llmFullConfidence` sits here, and so
does a stateful claimant holding a pending question. Not anchored, because nothing in the
utterance is pointed at.
**`BandNearest`.** The claim rests only on resemblance to something else. No anchor in the
utterance, no structural check behind it. The classifier. One band rather than a graded
scale, and the measurement is the argument. 62% at both ends of the cosine range, and a
top-two margin that never reaches 0.03.
**`BandVetoed`.** The claimant will take the turn only if nobody else will, and says why it
should not. The three arms of `gateLLMDecision` land here with their reason preserved. A
vetoed claim is still a claim. Maven asking "о чём напомнить?" beats silence.
There is no fifth band, and that is a measurement result rather than a preference. No
claimant in the cascade today can report what a fifth band would carry. V-546 lands a softmax
head whose max probability is a calibrated number. That one gets read as a number, not
squeezed into these four.
### Coverage decides before the band does
The band is the tie-break. The first question is how much of the utterance a claim explains,
and that is `Consumed` against `Unexplained` on the claim object. Two reasons.
It is the fix for the failure that opened V-558. "какая сейчас погода в Риме?" arrived while
a reminder was pending. The pending claimant ate the whole utterance as a time answer while
explaining none of it. Not "погода", not "Риме", not the question mark. A weather claim
explains all of it. Coverage-first arbitration prefers the weather claim without knowing that
a pending reminder is less trustworthy than a grammar. The pending question then survives to
be asked again.
It also keeps the stateful four out of the top slot without special-casing them. They sit at
`BandStructural`, below any anchored claim. That is the whole V-558 complaint about the
highest-priority claimants being the least informed, expressed as one rule.
### The claim object
```go
type Claim struct {
Claimant string // who wants the turn
Intent string // plain string: internal/dialogue must not import internal/router
Filled []string // the slots this claim would fill
Consumed []string // utterance tokens this claim explains
Unexplained []string // the rest, in order
Band Band
Veto string // why this claim should NOT win, empty when there is none
}
```
`Intent` is a plain `string` rather than `router.Intent` on purpose. `internal/dialogue` must
not import `internal/router`, so the claim package must not either, and a shared string costs
one conversion at each edge.
`Unexplained` is carried rather than derived at read time. A claimant can then decline to
explain a span it did match.
### What this task does not do
`router.Decision.Confidence` stays and keeps its float. `r.threshold` and `gateLLMDecision`
read it, and the classifier is the failure floor. A rewire that broke either would trade a
measured floor for an unmeasured design. V-565 lands the type and the builder beside the
existing path. The arbiter that reads claims is V-560.
+17 -8
View File
@@ -1,6 +1,6 @@
# QA plan: checking Maven properly
*Last verified: 2026-08-04 @ 8d816f4. Living doc: correct it in place, do not append.*
*Last verified: 2026-08-05 @ 12667fd. Living doc: correct it in place, do not append.*
Written 2026-08-01, after the 35-PR stack landed and the box came back up.
Refreshed 2026-08-02 against the live list, after PRs #85-#90.
@@ -255,8 +255,13 @@ room — **463**, written up in `docs/plans/17-where-the-voice-loop-runs.md`.
So the wake word and the VAD gate are covered by their unit tests and by
nothing else, and no session at this box changes that. Checking them needs a
machine with a microphone running both binaries against a TCP-listening mavend.
`ipc.Dial` already speaks `tcp://host:port?token=...`, so the work is a machine
and a config line, not protocol work. Until then, **287** can only be
`ipc.Dial` already speaks `tcp://host:port?token=...`, so the work is not
protocol work.
That machine is workpc (owner's correction, 05-08-2026). This section used to
call it a machine Maven does not have. That was written when the workstation
was only a model host. So the remaining work is deploying two daemons and
asking mavend to listen on TCP. Until that is done, **287** can only be
half-answered, and step 2 above is push-to-talk, not the voice loop.
**319's single-token bug is fixed** (01-08-2026). Single-word Russian utterances no longer come
@@ -418,11 +423,15 @@ something only a ZIM answers, with the search block on. Live search leads and th
ZIMs are the fallback since 02-08-2026. **286**'s remaining half is doc and
git ingestion, which is build work, not a check.
**Do not read `/trace` for this.** `/trace` is the nudge-rule trace: rule,
severity, predicate, gate, selected. No query-source field exists anywhere in the
codebase. The only evidence of which query source claimed a turn is the
`voice: search:` and `voice: kiwix:` lines in `docker compose logs mavend`
(`actions_query.go:589` and `:660`).
**Read `/trace` for this.** It carries two tables since 06-08-2026 (V-564). The
nudge-rule trace it always had, and below it the **turn decisions**: one
collapsible record per utterance. Each names every claimant, what it would have
made the turn, the score it reported, and whether it won, declined, lost or was
**never asked**. That last one answers "did Kiwix pass, or was it never
reached". The log lines cannot tell you that. The ring holds the last 25 turns
in daemon memory and is empty after a restart, so read it in the same sitting.
`/chat` still shows the claiming source as a badge, and the `voice: query
claimed by source` line is still in `docker compose logs mavend`.
Run 02-08-2026, 20 turns. **Search leads and the personal boundary holds.** Every
world question that reached the boundary was claimed by search. All three
+192
View File
@@ -0,0 +1,192 @@
// Package claim is the common unit for the many claimants that compete for one
// utterance (V-565, umbrella V-558, design in
// docs/plans/19-dialogue-arbitration.md).
//
// Maven's cascade has roughly ten stage-0 grammars, seven router intents,
// twenty-two query sources and four stateful pre-emptors, and every one of them
// answers "is this mine?" alone. None can answer "is this more mine than
// yours?", because their scores are not comparable: stage 0 asserts 1.0 by
// fiat, the classifier reports a cosine, the LLM router derives one from
// structure. So list order is the whole arbitration.
//
// A Claim carries evidence rather than a verdict. Two things read that evidence
// and neither needs a float:
//
// - specificity — a claim explaining more of the utterance is preferred, and
// that is Consumed against Unexplained;
// - negative constraint — a claimant may veto itself and say why, and that is
// Veto.
//
// Where a number is unavoidable, it is an ordinal Band and not a probability.
// The band set is argued from measurement in the plan doc: the classifier's
// cosine is flat against correctness (62% at both ends of a spread 0.083 wide)
// and its top-two margin is p50 0.009, so no claimant Maven has today can
// produce a graded confidence.
//
// This package deliberately imports nothing from the rest of Maven.
// internal/dialogue must not import internal/router, so a shared unit that
// pulled in router.Intent would smuggle that edge back in. Intent is a plain
// string and the conversion happens at each edge.
package claim
import "strings"
// Band — the kind of evidence behind a claim, ordinal and comparable. Higher
// wins a tie. Four values, because four is what the claimants can report.
type Band int
const (
// BandUnknown — the zero value. A claim that never set a band is a bug in
// its builder, not a weak claim, so it must not silently rank as one.
BandUnknown Band = iota
// BandVetoed — the claimant will take the turn only if nobody else will,
// and Veto says why it should not. The three arms of gateLLMDecision (a
// fact with no key, an act with no allowlisted fn, a reminder with no
// subject) land here. Still a claim: asking "о чём напомнить?" beats
// silence.
BandVetoed
// BandNearest — the claim rests only on resemblance to something else,
// with no anchor in the utterance and no structural check behind it. The
// nearest-centroid classifier. One band and not a graded scale, because
// the cosine measured flat against correctness.
BandNearest
// BandStructural — the claimant read the whole sentence and produced a
// complete route, every slot its intent requires filled. The LLM router at
// full confidence, and a stateful claimant holding a pending question.
// Below BandAnchored on purpose: the four stateful claimants pre-empt
// unconditionally today, and that is the V-558 defect.
BandStructural
// BandAnchored — a literal pattern anchored in the utterance matched, and
// the matched span is what decides the intent. Stage 0 grammars and
// query-source matchers. Certainty about the shape of the sentence, which
// is not certainty about the answer.
BandAnchored
)
// String — the band's name, for a trace line and for a test failure that has to
// say which band it got.
func (b Band) String() string {
switch b {
case BandVetoed:
return "vetoed"
case BandNearest:
return "nearest"
case BandStructural:
return "structural"
case BandAnchored:
return "anchored"
default:
return "unknown"
}
}
// Claim — one claimant's bid for one utterance.
type Claim struct {
// Claimant — who wants the turn. A grammar name, a query source name, a
// stage label. Read by the trace and by a test naming a loser.
Claimant string
// Intent — the route this claim would take. A plain string and not
// router.Intent: see the package comment.
Intent string
// Filled — the slot names this claim would fill ("time", "fn", "key",
// "text"). Names and not values, because arbitration compares shape.
Filled []string
// Consumed — the utterance tokens this claim explains, in the order they
// appear. The numerator of specificity.
Consumed []string
// Unexplained — the tokens this claim does not explain, in order. Carried
// rather than derived, so a claimant may decline a span it did match.
Unexplained []string
// Band — the kind of evidence. The tie-break, after coverage.
Band Band
// Veto — why this claim should NOT win, empty when there is none. A
// non-empty Veto and a Band above BandVetoed is legal: a claim can be
// well-evidenced and still name a reason to prefer somebody else.
Veto string
}
// Coverage — the fraction of the utterance this claim explains, in [0,1]. A
// claim with no tokens either way covers nothing; it is not division by zero
// and it is not a full claim.
func (c Claim) Coverage() float64 {
total := len(c.Consumed) + len(c.Unexplained)
if total == 0 {
return 0
}
return float64(len(c.Consumed)) / float64(total)
}
// Vetoed reports whether the claimant named a reason against itself.
func (c Claim) Vetoed() bool { return c.Veto != "" }
// MoreSpecificThan — the ordering V-560's arbiter will read. Coverage first,
// because that is what fixes the failure this program opened with: a pending
// reminder ate "какая сейчас погода в Риме?" as a time answer while explaining
// none of it. Band only breaks a coverage tie.
//
// Deliberately NOT wired into the cascade by V-565. It is here so the ordering
// is one function with tests on it, rather than a rule restated at each of the
// sites that will eventually call it.
func (c Claim) MoreSpecificThan(other Claim) bool {
cc, oc := c.Coverage(), other.Coverage()
if cc != oc {
return cc > oc
}
return c.Band > other.Band
}
// Tokens — the utterance split for coverage accounting. Whitespace, then
// trailing and leading punctuation, then lowercased.
//
// This is tokenization over the raw string and not a Russian pattern: it
// contains no word list, and its output is a count rather than a fact or a
// route (CLAUDE.md § Russian patterns). Lowercasing is Unicode-aware, so
// Cyrillic folds the same way Latin does.
func Tokens(utterance string) []string {
fields := strings.FieldsFunc(utterance, func(r rune) bool {
return r == ' ' || r == '\t' || r == '\n' || r == '\r'
})
out := make([]string, 0, len(fields))
for _, f := range fields {
t := strings.Trim(strings.ToLower(f), ".,!?;:()\"'«»…-–—")
if t == "" {
continue
}
out = append(out, t)
}
return out
}
// Split partitions the utterance's tokens into the ones a claim explains and
// the rest, preserving order in both. A token is explained when it appears in
// one of the spans the claimant filled (a slot value, a matched substring).
//
// Duplicates are handled by membership and not by count: "напомни напомни
// позвонить" with span "напомни" explains both copies. The alternative is a
// multiset, and no claimant Maven has can say which copy it meant.
func Split(utterance string, spans ...string) (consumed, unexplained []string) {
explained := map[string]bool{}
for _, s := range spans {
for _, t := range Tokens(s) {
explained[t] = true
}
}
for _, t := range Tokens(utterance) {
if explained[t] {
consumed = append(consumed, t)
} else {
unexplained = append(unexplained, t)
}
}
return consumed, unexplained
}
+120
View File
@@ -0,0 +1,120 @@
package claim
import (
"reflect"
"testing"
)
func TestTokensStripsPunctuationAndCase(t *testing.T) {
got := Tokens("Какая сейчас погода в Риме?")
want := []string{"какая", "сейчас", "погода", "в", "риме"}
if !reflect.DeepEqual(got, want) {
t.Errorf("Tokens = %q, want %q", got, want)
}
}
// The dash forms matter: an STT transcript routinely carries "а, да, прости -
// на 9", and a stray dash counted as a token would dilute every coverage score
// in the sentence.
func TestTokensDropsBareDashes(t *testing.T) {
got := Tokens("а, да, прости — на 9")
want := []string{"а", "да", "прости", "на", "9"}
if !reflect.DeepEqual(got, want) {
t.Errorf("Tokens = %q, want %q", got, want)
}
}
func TestSplitPartitionsInOrder(t *testing.T) {
consumed, unexplained := Split("напомни позвонить маме", "позвонить маме")
if want := []string{"позвонить", "маме"}; !reflect.DeepEqual(consumed, want) {
t.Errorf("consumed = %q, want %q", consumed, want)
}
if want := []string{"напомни"}; !reflect.DeepEqual(unexplained, want) {
t.Errorf("unexplained = %q, want %q", unexplained, want)
}
}
func TestCoverageIsZeroWithoutTokens(t *testing.T) {
if got := (Claim{}).Coverage(); got != 0 {
t.Errorf("Coverage of an empty claim = %v, want 0", got)
}
}
func TestCoverageFraction(t *testing.T) {
c := Claim{Consumed: []string{"a", "b", "c"}, Unexplained: []string{"d"}}
if got := c.Coverage(); got != 0.75 {
t.Errorf("Coverage = %v, want 0.75", got)
}
}
// The band order is load-bearing, so it is asserted rather than assumed from
// the iota. BandUnknown must sit at the bottom: a claim whose builder forgot to
// set a band is a bug and must not outrank a measured one.
func TestBandOrder(t *testing.T) {
ordered := []Band{BandUnknown, BandVetoed, BandNearest, BandStructural, BandAnchored}
for i := 1; i < len(ordered); i++ {
if !(ordered[i-1] < ordered[i]) {
t.Errorf("%v is not below %v", ordered[i-1], ordered[i])
}
}
for _, b := range ordered {
if b.String() == "" {
t.Errorf("band %d has no name", b)
}
}
if BandUnknown.String() != "unknown" {
t.Errorf("BandUnknown.String() = %q", BandUnknown.String())
}
}
// The failure V-558 opened with, as an ordering test. A pending reminder eats
// "какая сейчас погода в Риме?" as a time answer and explains none of it; the
// weather source explains all of it. Coverage decides, and the band never gets
// consulted, which is the point: the pending claimant is structural and the
// weather claim is anchored, but even if the bands were equal the weather claim
// wins.
func TestCoverageBeatsBand(t *testing.T) {
utterance := "какая сейчас погода в Риме?"
pendingConsumed, pendingRest := Split(utterance, "сейчас")
pending := Claim{
Claimant: "reminder-followup", Intent: "reminder",
Consumed: pendingConsumed, Unexplained: pendingRest,
Band: BandStructural,
}
weatherConsumed, weatherRest := Split(utterance, utterance)
weather := Claim{
Claimant: "weather", Intent: "query",
Consumed: weatherConsumed, Unexplained: weatherRest,
Band: BandNearest,
}
if !weather.MoreSpecificThan(pending) {
t.Errorf("weather (%v cover) did not beat pending (%v cover)",
weather.Coverage(), pending.Coverage())
}
if pending.MoreSpecificThan(weather) {
t.Error("pending beat weather, so the ordering is not asymmetric")
}
}
// Where coverage ties, the band decides. Two grammars claiming the same
// utterance is the stage-0 contention case (ru-query-019 on the fixture), and
// today list order settles it with nothing recorded.
func TestBandBreaksACoverageTie(t *testing.T) {
anchored := Claim{Claimant: "calendar-query", Consumed: []string{"a"}, Band: BandAnchored}
nearest := Claim{Claimant: "classifier", Consumed: []string{"a"}, Band: BandNearest}
if !anchored.MoreSpecificThan(nearest) {
t.Error("anchored did not beat nearest on equal coverage")
}
if nearest.MoreSpecificThan(anchored) {
t.Error("nearest beat anchored on equal coverage")
}
}
func TestVetoed(t *testing.T) {
if (Claim{}).Vetoed() {
t.Error("a claim with no veto reports itself vetoed")
}
if !(Claim{Veto: "fact with no key"}).Vetoed() {
t.Error("a claim with a veto reason does not report itself vetoed")
}
}
+185
View File
@@ -0,0 +1,185 @@
// Package decision records who claimed one turn and who lost it (V-564).
//
// Arbitration between the claimants on the utterance stream is order, hardcoded
// in the resolver ladder, in buildRouter and in querySources (V-558). Order is
// invisible in a log: the daemon says which intent won and which query source
// answered, never who else wanted the turn, with what score, or why it did not
// get it. The Rome misroute took a probe, a log read and a code read to explain,
// which is one diagnosis too many for a defect family already three deep.
//
// The record rides the context, the same seam querysource.go uses and for the
// same reason: a turn answers through one string that the mic, telegram and the
// web all share, so a second return value is not threadable. A context with no
// recorder notes nothing, so every Note here is free in a test or a tool that
// did not ask for one.
//
// The most important thing it holds is not a loss but a silence. A claimant
// that was NEVER ASKED — because something earlier in the ladder returned
// first — looks identical to one that examined the turn and declined, and it is
// that confusion the hardcoded ordering hides. So a stage declares its roster
// up front and Finish names everyone who never reported.
package decision
import (
"context"
"sync"
"time"
)
// Stages, in the order a turn passes through them.
const (
StagePreRoute = "pre-route" // clarify, confirm, repair and their siblings
StageZero = "stage0" // grammar rules
StageRoute = "route" // LLM router, classifier
StageMerge = "merge" // the follow-up merge, which edits rather than claims
StageQuery = "query" // the query source chain
StageAction = "action" // whoever actually produced the reply
)
// Outcomes. Coarse on purpose: the record answers "who wanted this turn and
// what happened to their claim", not "re-derive the branch".
const (
Won = "won" // this claimant produced the turn
Declined = "declined" // it looked at the turn and said not mine
LostOnOrder = "lost_on_order" // it wanted the turn, something earlier had it
LostOnScore = "lost_on_score" // it was scored against a rival and scored lower
Thinned = "thinned" // it claimed, and a gate cut its confidence
Merged = "merged" // it changed the winning claim without owning it
NeverAsked = "never_asked" // it never got to look at all
)
// Claim is one claimant's say on one turn.
type Claim struct {
Stage string `json:"stage"`
Claimant string `json:"claimant"`
Intent string `json:"intent,omitempty"` // what it would have made the turn
Score float64 `json:"score,omitempty"` // only meaningful with HasScore
HasScore bool `json:"has_score,omitempty"`
Outcome string `json:"outcome"`
Reason string `json:"reason,omitempty"` // why it lost, in its own terms
}
// Record is one turn's arbitration. Utterance is held because a record with no
// utterance is unreadable, and this store is diagnostics with a short life —
// unlike the facts table, which is the audit trail.
type Record struct {
Ts time.Time `json:"ts"`
Utterance string `json:"utterance"`
Winner string `json:"winner"`
Claims []Claim `json:"claims"`
mu sync.Mutex
rosters []roster
}
type roster struct {
stage string
names []string
}
// Expect declares the claimants a stage could have asked, so Finish can tell a
// decline from a silence. The slice is held, not copied: every caller passes a
// package-level table.
func (r *Record) Expect(stage string, names []string) {
if r == nil {
return
}
r.mu.Lock()
defer r.mu.Unlock()
r.rosters = append(r.rosters, roster{stage: stage, names: names})
}
// Note appends one claim. The winner is whoever noted Won last, which is the
// claimant that actually returned the reply.
func (r *Record) Note(c Claim) {
if r == nil {
return
}
r.mu.Lock()
defer r.mu.Unlock()
r.Claims = append(r.Claims, c)
if c.Outcome == Won {
r.Winner = c.Stage + ":" + c.Claimant
}
}
// NoteIfUnclaimed records a win only when nobody has claimed the turn yet. It
// is what closes a record whose route was decided but whose reply came from
// somewhere with no scoreboard — a clarify question, or an action handler with
// no chain in front of it. Without it a thinned route leaves the record with no
// winner at all, which reads as a lost turn rather than an asked question.
func (r *Record) NoteIfUnclaimed(c Claim) {
if r == nil {
return
}
r.mu.Lock()
claimed := r.Winner != ""
r.mu.Unlock()
if claimed {
return
}
c.Outcome = Won
r.Note(c)
}
// Finish fills in the never-asked claimants and returns the record. Called once
// by whoever installed the recorder, after the turn has answered.
func (r *Record) Finish(now time.Time) *Record {
if r == nil {
return nil
}
r.mu.Lock()
defer r.mu.Unlock()
r.Ts = now
reported := map[string]bool{}
for _, c := range r.Claims {
reported[c.Stage+":"+c.Claimant] = true
}
for _, ros := range r.rosters {
for _, name := range ros.names {
if !reported[ros.stage+":"+name] {
r.Claims = append(r.Claims, Claim{
Stage: ros.stage, Claimant: name, Outcome: NeverAsked,
})
}
}
}
return r
}
// --- the context seam ---
type recorderKey struct{}
// With returns a context carrying a fresh record, and the record to read after
// the turn has answered.
func With(ctx context.Context, utterance string) (context.Context, *Record) {
rec := &Record{Utterance: utterance}
return context.WithValue(ctx, recorderKey{}, rec), rec
}
// From returns the record on the context, or nil. Every method on *Record is
// nil-safe, so a caller does not have to check.
func From(ctx context.Context) *Record {
rec, _ := ctx.Value(recorderKey{}).(*Record)
return rec
}
// Note is the shorthand every claim site uses: a no-op when nobody is recording.
func Note(ctx context.Context, c Claim) {
From(ctx).Note(c)
}
// Expect is the roster shorthand, likewise a no-op with no recorder.
func Expect(ctx context.Context, stage string, names []string) {
From(ctx).Expect(stage, names)
}
// Scored is a claim carrying a confidence, kept as a constructor so a caller
// cannot forget HasScore and have a real 0.0 read as "no score".
func Scored(stage, claimant, intent string, score float64, outcome, reason string) Claim {
return Claim{
Stage: stage, Claimant: claimant, Intent: intent,
Score: score, HasScore: true, Outcome: outcome, Reason: reason,
}
}
+98
View File
@@ -0,0 +1,98 @@
package decision
import (
"context"
"sync"
"testing"
"time"
)
func TestFinishNamesTheNeverAsked(t *testing.T) {
ctx, rec := With(context.Background(), "какая погода в риме?")
Expect(ctx, StageQuery, []string{"calendar", "weather", "search", "kiwix"})
Note(ctx, Claim{Stage: StageQuery, Claimant: "calendar", Outcome: Declined})
Note(ctx, Claim{Stage: StageQuery, Claimant: "weather", Outcome: Won})
rec.Finish(time.Now())
outcomes := map[string]string{}
for _, c := range rec.Claims {
outcomes[c.Claimant] = c.Outcome
}
if outcomes["weather"] != Won || rec.Winner != StageQuery+":weather" {
t.Errorf("winner = %q, weather = %q", rec.Winner, outcomes["weather"])
}
if outcomes["calendar"] != Declined {
t.Errorf("calendar = %q, want a decline", outcomes["calendar"])
}
// The two below the winner never looked, and saying so is the whole point.
for _, name := range []string{"search", "kiwix"} {
if outcomes[name] != NeverAsked {
t.Errorf("%s = %q, want %q", name, outcomes[name], NeverAsked)
}
}
}
// A real 0.0 confidence must not read as "this claimant has no score".
func TestScoredKeepsAZeroScore(t *testing.T) {
c := Scored(StageRoute, "classifier", "chat", 0, LostOnScore, "")
if !c.HasScore || c.Score != 0 {
t.Errorf("claim = %+v", c)
}
}
func TestNoteIfUnclaimedYieldsToARealWinner(t *testing.T) {
ctx, rec := With(context.Background(), "x")
Note(ctx, Claim{Stage: StageQuery, Claimant: "weather", Outcome: Won})
rec.NoteIfUnclaimed(Claim{Stage: StageAction, Claimant: "action-handler"})
if rec.Winner != StageQuery+":weather" {
t.Errorf("winner = %q, want the query source", rec.Winner)
}
}
// A context with no record must cost nothing and crash nothing: that is what
// makes the claim sites safe to leave in every test and every fixture run.
func TestNoRecorderIsANoOp(t *testing.T) {
ctx := context.Background()
Note(ctx, Claim{Claimant: "x", Outcome: Won})
Expect(ctx, StageQuery, []string{"y"})
if From(ctx) != nil {
t.Error("bare context reported a record")
}
From(ctx).NoteIfUnclaimed(Claim{Claimant: "z"})
if rec := From(ctx).Finish(time.Now()); rec != nil {
t.Error("finishing a nil record produced one")
}
}
func TestRingIsBoundedAndNewestFirst(t *testing.T) {
r := NewRing()
for i := 0; i < ringSize+5; i++ {
r.Push(&Record{Utterance: string(rune('a' + i))})
}
got := r.Recent(ringSize + 10)
if len(got) != ringSize {
t.Fatalf("kept %d records, want %d", len(got), ringSize)
}
if got[0].Utterance != string(rune('a'+ringSize+4)) {
t.Errorf("newest = %q", got[0].Utterance)
}
}
// A query source may fan out to goroutines of its own, so two of them noting at
// once must not race. Run under -race, which is where this earns its keep.
func TestConcurrentNotes(t *testing.T) {
ctx, rec := With(context.Background(), "x")
var wg sync.WaitGroup
for i := 0; i < 8; i++ {
wg.Add(1)
go func() {
defer wg.Done()
Note(ctx, Claim{Stage: StageQuery, Claimant: "fanout", Outcome: Declined})
}()
}
wg.Wait()
if len(rec.Claims) != 8 {
t.Errorf("recorded %d claims, want 8", len(rec.Claims))
}
}
+49
View File
@@ -0,0 +1,49 @@
package decision
import "sync"
// ringSize is how many turns are kept. Turns arrive at human rate, not machine
// rate, so the whole store is memory: no migration, no insert on the answer
// path, and nothing of his words survives a restart. That is what makes this
// cheap enough to leave on always (V-564). Ecosystem traces went to SQLite
// because one act writes several hops and they must outlive the turn; an
// arbitration record is read minutes later or never.
const ringSize = 25
// Ring holds the newest records, newest first on read.
type Ring struct {
mu sync.Mutex
recs []*Record
}
func NewRing() *Ring { return &Ring{} }
// Push adds one finished record and drops the oldest past the bound.
func (r *Ring) Push(rec *Record) {
if r == nil || rec == nil {
return
}
r.mu.Lock()
defer r.mu.Unlock()
r.recs = append(r.recs, rec)
if len(r.recs) > ringSize {
r.recs = r.recs[len(r.recs)-ringSize:]
}
}
// Recent returns up to n records, newest first.
func (r *Ring) Recent(n int) []*Record {
if r == nil || n <= 0 {
return nil
}
r.mu.Lock()
defer r.mu.Unlock()
if n > len(r.recs) {
n = len(r.recs)
}
out := make([]*Record, 0, n)
for i := 0; i < n; i++ {
out = append(out, r.recs[len(r.recs)-1-i])
}
return out
}
+137 -24
View File
@@ -38,21 +38,34 @@ type PendingQuestion struct {
MaxAttempts int
}
// maxAttempts is MaxAttempts with the default filled in.
func (q *PendingQuestion) maxAttempts() int {
if q.MaxAttempts <= 0 {
return DefaultMaxAttempts
// Action reads the parked question as the typed action it is assembling
// (pending.go). Derived rather than stored: the question's fields stay the one
// copy of the truth, so a caller that fills them the old way cannot end up with
// a capability that disagrees with the intent.
func (q *PendingQuestion) Action() PendingAction {
return PendingAction{
Capability: CapabilityFor(q.Intent),
Slots: q.Slots,
Missing: q.Missing,
Utterance: q.Utterance,
Asked: q.Asked,
TTL: q.TTL,
Attempts: q.Attempts,
MaxAttempts: q.MaxAttempts,
}
return q.MaxAttempts
}
// IsExpired and CanAsk answer through the action, so there is exactly one copy
// of the TTL and attempt-cap rules and the widening cannot drift from them.
func (q *PendingQuestion) IsExpired(now time.Time) bool {
return now.After(q.Asked.Add(q.TTL))
a := q.Action()
return a.IsExpired(now)
}
// CanAsk reports whether Maven may ask another question about this request.
func (q *PendingQuestion) CanAsk() bool {
return q.Attempts < q.maxAttempts()
a := q.Action()
return a.CanAsk()
}
// ClarifyStore holds the parked questions. Same shape and locking as
@@ -66,11 +79,26 @@ func (q *PendingQuestion) CanAsk() bool {
// next words route fresh, which is the right answer with or without a notice.
// Do not give this store a persister without re-arguing that.
type ClarifyStore struct {
mu sync.RWMutex
questions map[string]*PendingQuestion
mu sync.RWMutex
// stacks — one stack of parked questions per dialogue id, newest last. It
// was a single question per id until V-559; a side query has to be able to
// suspend the active flow and find it still there afterwards (V-561 does
// the suspending, this only holds the room for it).
stacks map[string][]*PendingQuestion
defaultTTL time.Duration
}
// MaxStackDepth — how many parked questions one dialogue id may hold.
//
// Two, not three. One is the flow he is in, one is the thing he interrupted it
// with, and out loud he does not nest deeper than that: a side query inside a
// side query is a shape typed conversation has and spoken conversation does
// not. The bound is also a promise — every level she keeps is a level she must
// be able to SPEAK when it dies (clarifyGaveUp, clarifyExpiredVariants), and
// two lines of "and the other thing I dropped" is already the limit of what a
// reply can carry.
const MaxStackDepth = 2
func NewClarifyStore(defaultTTL time.Duration) *ClarifyStore {
if defaultTTL <= 0 {
// Short, like confirmTTL in voice.go: a clarifying question is a
@@ -78,27 +106,58 @@ func NewClarifyStore(defaultTTL time.Duration) *ClarifyStore {
defaultTTL = 90 * time.Second
}
return &ClarifyStore{
questions: make(map[string]*PendingQuestion),
stacks: make(map[string][]*PendingQuestion),
defaultTTL: defaultTTL,
}
}
// Put parks a question. Called on a clarify decision (cmd/mavend/clarify.go).
// Put parks a question, replacing the one on top. Called on a clarify decision
// (cmd/mavend/clarify.go), and it is still what the daemon uses: re-asking the
// same request is a new question about the SAME action, so it overwrites rather
// than growing the stack. Push is the deeper one, and nothing calls it yet.
func (s *ClarifyStore) Put(id string, q *PendingQuestion) {
if q.TTL <= 0 {
q.TTL = s.defaultTTL
}
s.fillTTL(q)
s.mu.Lock()
s.questions[id] = q
s.mu.Unlock()
defer s.mu.Unlock()
stack := s.stacks[id]
if len(stack) == 0 {
s.stacks[id] = []*PendingQuestion{q}
return
}
stack[len(stack)-1] = q
}
// Get returns the live parked question, or nil when there is none.
func (s *ClarifyStore) Get(id string, now time.Time) *PendingQuestion {
// Push suspends whatever is parked and puts q on top. The returned question is
// one the depth bound forced out of the bottom of the stack, and the caller MUST
// tell him about it — a parked request that dies without a word leaves him
// thinking it landed, which is the whole reason clarifyGaveUp exists. nil is the
// ordinary case.
func (s *ClarifyStore) Push(id string, q *PendingQuestion) *PendingQuestion {
s.fillTTL(q)
s.mu.Lock()
defer s.mu.Unlock()
stack := append(s.stacks[id], q)
var dropped *PendingQuestion
if len(stack) > MaxStackDepth {
dropped = stack[0]
stack = stack[1:]
}
s.stacks[id] = stack
return dropped
}
// Peek returns the live question on top, or nil when there is none. Expired
// entries below it are left alone: TakeExpired is what reports those, and
// dropping one here would be the silent death this store is careful about.
func (s *ClarifyStore) Peek(id string, now time.Time) *PendingQuestion {
s.mu.RLock()
q, ok := s.questions[id]
stack := s.stacks[id]
var q *PendingQuestion
if len(stack) > 0 {
q = stack[len(stack)-1]
}
s.mu.RUnlock()
if !ok {
if q == nil {
return nil
}
if q.IsExpired(now) {
@@ -108,27 +167,81 @@ func (s *ClarifyStore) Get(id string, now time.Time) *PendingQuestion {
return q
}
// Get is Peek under the name every caller already uses. Kept because a clarify
// answer is always about the top of the stack, so the two are the same call.
func (s *ClarifyStore) Get(id string, now time.Time) *PendingQuestion {
return s.Peek(id, now)
}
// Pop takes the live question off the top and returns it, so the flow beneath
// becomes current again. nil when the top is empty or expired — an expired top
// is dropped along with the rest of the stack, exactly as Peek does, because the
// clock that killed it has been running for everything underneath too.
func (s *ClarifyStore) Pop(id string, now time.Time) *PendingQuestion {
s.mu.Lock()
stack := s.stacks[id]
if len(stack) == 0 {
s.mu.Unlock()
return nil
}
q := stack[len(stack)-1]
if q.IsExpired(now) {
delete(s.stacks, id)
s.mu.Unlock()
return nil
}
if len(stack) == 1 {
delete(s.stacks, id)
} else {
s.stacks[id] = stack[:len(stack)-1]
}
s.mu.Unlock()
return q
}
// Depth — how many questions are parked for this id, expired ones included.
// Diagnostic; the arbiter in V-560 reads it to know it is inside a flow.
func (s *ClarifyStore) Depth(id string) int {
s.mu.RLock()
defer s.mu.RUnlock()
return len(s.stacks[id])
}
// TakeExpired reports whether a question was parked here but its TTL ran out,
// and drops it. Get drops such a question silently, which leaves the user
// thinking his request is still alive — the caller uses this to tell him it is
// gone before treating his words as a fresh utterance.
//
// It looks at the top only, and drops the whole stack when that one is dead: one
// notice is what a reply can carry, and anything parked under a question that
// timed out has been waiting at least as long.
func (s *ClarifyStore) TakeExpired(id string, now time.Time) bool {
s.mu.Lock()
defer s.mu.Unlock()
q, ok := s.questions[id]
if !ok || !q.IsExpired(now) {
stack := s.stacks[id]
if len(stack) == 0 || !stack[len(stack)-1].IsExpired(now) {
return false
}
delete(s.questions, id)
delete(s.stacks, id)
return true
}
// Delete drops every question parked for this id. The old single-slot Delete
// under the old name: at depth one the two are the same, and a caller that means
// "this exchange is over" means all of it.
func (s *ClarifyStore) Delete(id string) {
s.mu.Lock()
delete(s.questions, id)
delete(s.stacks, id)
s.mu.Unlock()
}
// fillTTL applies the store default to a question parked without one.
func (s *ClarifyStore) fillTTL(q *PendingQuestion) {
if q.TTL <= 0 {
q.TTL = s.defaultTTL
}
}
// Answer merges the slots parsed from the user's answer into the parked ones.
// Only the slots listed in Missing are touched. Within those, a value the answer
// carries WINS over what was parked: she asked about this slot, so «нет, в пять»
+101
View File
@@ -0,0 +1,101 @@
package dialogue
import "time"
// Capability names the thing being assembled across a clarify exchange —
// "reminder.create", not "reminder". A router intent says what she heard; a
// capability says what she is about to do, and those are not the same word:
// three intents currently reach exactly one capability each, but a fact key
// that turns out to be a Hexis target does not. Named in the ecosystem's
// dotted form because that is what a confirmation binds (cmd/mavend/confirm.go)
// and what Hexis registers.
//
// This package must stay free of internal/router (the cycle rule that makes
// Slots a hand-kept copy), so the mapping from an intent lives here and reads
// off dialogue.Intent only.
type Capability string
const (
CapReminderCreate Capability = "reminder.create"
CapFactWrite Capability = "fact.write"
CapNoteWrite Capability = "note.write"
CapActRun Capability = "act.run"
CapQueryAnswer Capability = "query.answer"
CapChatReply Capability = "chat.reply"
CapSystemControl Capability = "system.control"
)
// intentCapability — the one place an intent becomes a capability. Every intent
// is listed, including the four that are never worth a clarifying question, so a
// parked action always knows what it is even when nothing asks it.
var intentCapability = map[Intent]Capability{
IntentReminder: CapReminderCreate,
IntentFact: CapFactWrite,
IntentNote: CapNoteWrite,
IntentAct: CapActRun,
IntentQuery: CapQueryAnswer,
IntentChat: CapChatReply,
IntentSystem: CapSystemControl,
}
// CapabilityFor maps a router intent (already narrowed to dialogue.Intent by
// the caller) to the capability being assembled. "" for an intent she does not
// recognise — an unknown intent must not silently become a real capability.
func CapabilityFor(in Intent) Capability {
return intentCapability[in]
}
// PendingAction is the action Maven is assembling, as an object rather than as
// conversational history: which capability, the slots it already has, the slots
// it is still missing, when she asked, how many questions that has cost and how
// long the answer stays welcome.
//
// It exists because the resolver used to have to infer all of that from a
// parked question plus the previous turn (Vikunja #558): "is this his answer or
// a new request" is answerable against an object and guessy against a
// transcript. PendingQuestion carries one of these and keeps its own flat
// fields, so this is a widening — nothing reads the capability yet.
type PendingAction struct {
Capability Capability
Slots Slots // what is filled so far
Missing []Slot // what she is waiting for, in the order to ask about
Utterance string // his original raw words, as the action's provenance
Asked time.Time
TTL time.Duration
Attempts int // questions already asked about this action
// MaxAttempts caps Attempts. 0 ⇒ DefaultMaxAttempts.
MaxAttempts int
}
// maxAttempts is MaxAttempts with the default filled in.
func (a *PendingAction) maxAttempts() int {
if a.MaxAttempts <= 0 {
return DefaultMaxAttempts
}
return a.MaxAttempts
}
// IsExpired — the answer came too late for this action to still be his answer.
func (a *PendingAction) IsExpired(now time.Time) bool {
return now.After(a.Asked.Add(a.TTL))
}
// CanAsk reports whether she may ask another question about this action.
func (a *PendingAction) CanAsk() bool {
return a.Attempts < a.maxAttempts()
}
// Gaps lists the slots this action asked for and still does not have. Computed
// from the slots rather than trusted from Missing, because Missing is what she
// asked about and the slots are what she got — an answer can fill a gap she
// never asked about, and a re-park must not ask again for something now filled.
func (a *PendingAction) Gaps() []Slot {
return StillMissing(a.Missing, a.Slots)
}
// Complete reports whether every slot this action was waiting for is filled, so
// it can run. Note that this is completeness against what she ASKED, not
// against the capability's whole schema — validating that is V-562.
func (a *PendingAction) Complete() bool {
return len(a.Gaps()) == 0
}
+117
View File
@@ -0,0 +1,117 @@
package dialogue
import (
"testing"
"time"
)
var pendingBase = time.Date(2026, 8, 6, 9, 0, 0, 0, time.UTC)
func TestCapabilityForCoversEveryIntent(t *testing.T) {
for _, in := range []Intent{
IntentAct, IntentReminder, IntentFact, IntentNote,
IntentQuery, IntentChat, IntentSystem,
} {
if CapabilityFor(in) == "" {
t.Errorf("intent %q maps to no capability", in)
}
}
if got := CapabilityFor(Intent("nonsense")); got != "" {
t.Errorf("unknown intent became capability %q, want empty", got)
}
}
// A parked question must read as the action it is assembling, without the
// caller having to name the capability twice.
func TestPendingQuestionActionDerivesCapability(t *testing.T) {
q := &PendingQuestion{
Intent: IntentReminder,
Slots: Slots{Text: "позвонить маме"},
Missing: []Slot{SlotTime},
Utterance: "напомни позвонить маме",
Asked: pendingBase,
TTL: time.Minute,
Attempts: 1,
MaxAttempts: 2,
}
a := q.Action()
if a.Capability != CapReminderCreate {
t.Errorf("capability = %q, want %q", a.Capability, CapReminderCreate)
}
if a.Utterance != q.Utterance || a.Attempts != 1 || a.MaxAttempts != 2 || !a.Asked.Equal(pendingBase) {
t.Errorf("action did not carry the question's fields: %+v", a)
}
}
func TestPendingActionGaps(t *testing.T) {
for _, tc := range []struct {
name string
action PendingAction
want []Slot
complete bool
}{
{
name: "time still missing",
action: PendingAction{Missing: []Slot{SlotTime}, Slots: Slots{Text: "позвонить маме"}},
want: []Slot{SlotTime},
complete: false,
},
{
name: "asked slot now filled",
action: PendingAction{Missing: []Slot{SlotTime}, Slots: Slots{Time: pendingBase, HasTime: true}},
want: nil,
complete: true,
},
{
name: "two gaps reported in ask order",
action: PendingAction{Missing: []Slot{SlotText, SlotTime}},
want: []Slot{SlotText, SlotTime},
complete: false,
},
{
name: "nothing asked is complete",
action: PendingAction{},
want: nil,
complete: true,
},
} {
t.Run(tc.name, func(t *testing.T) {
got := tc.action.Gaps()
if len(got) != len(tc.want) {
t.Fatalf("gaps = %v, want %v", got, tc.want)
}
for i := range got {
if got[i] != tc.want[i] {
t.Fatalf("gaps = %v, want %v", got, tc.want)
}
}
if tc.action.Complete() != tc.complete {
t.Errorf("Complete() = %v, want %v", tc.action.Complete(), tc.complete)
}
})
}
}
// The typed action must answer the TTL and attempt-cap questions the same way
// the parked question always did — this is a widening, not new behaviour.
func TestPendingActionTTLAndAttempts(t *testing.T) {
a := PendingAction{Asked: pendingBase, TTL: time.Minute}
if a.IsExpired(pendingBase.Add(30 * time.Second)) {
t.Error("expired inside the TTL")
}
if !a.IsExpired(pendingBase.Add(2 * time.Minute)) {
t.Error("not expired past the TTL")
}
a.Attempts = DefaultMaxAttempts - 1
if !a.CanAsk() {
t.Error("cannot ask with an attempt left")
}
a.Attempts = DefaultMaxAttempts
if a.CanAsk() {
t.Error("asked past the default cap")
}
a = PendingAction{Asked: pendingBase, TTL: time.Minute, MaxAttempts: 1, Attempts: 1}
if a.CanAsk() {
t.Error("asked past an explicit cap of 1")
}
}
+155
View File
@@ -0,0 +1,155 @@
package dialogue
import (
"testing"
"time"
)
func parked(text string, asked time.Time) *PendingQuestion {
return &PendingQuestion{
Intent: IntentReminder,
Missing: []Slot{SlotTime},
Utterance: text,
Asked: asked,
TTL: time.Minute,
}
}
func TestStackPushPeekPop(t *testing.T) {
s := NewClarifyStore(time.Minute)
if dropped := s.Push("voice", parked("напомни позвонить маме", pendingBase)); dropped != nil {
t.Fatalf("first push dropped %q", dropped.Utterance)
}
if dropped := s.Push("voice", parked("погода в риме", pendingBase)); dropped != nil {
t.Fatalf("second push dropped %q", dropped.Utterance)
}
if got := s.Depth("voice"); got != 2 {
t.Fatalf("depth = %d, want 2", got)
}
if got := s.Peek("voice", pendingBase); got == nil || got.Utterance != "погода в риме" {
t.Fatalf("peek = %+v, want the newest", got)
}
// Peek must not consume: two peeks are the same question.
if got := s.Peek("voice", pendingBase); got == nil || got.Utterance != "погода в риме" {
t.Fatalf("second peek = %+v, want the newest still", got)
}
got := s.Pop("voice", pendingBase)
if got == nil || got.Utterance != "погода в риме" {
t.Fatalf("pop = %+v, want the newest", got)
}
// The flow underneath survived the one on top of it.
if got := s.Peek("voice", pendingBase); got == nil || got.Utterance != "напомни позвонить маме" {
t.Fatalf("after pop, peek = %+v, want the suspended flow", got)
}
if got := s.Pop("voice", pendingBase); got == nil {
t.Fatal("pop of the last entry returned nil")
}
if s.Peek("voice", pendingBase) != nil || s.Depth("voice") != 0 {
t.Error("stack not empty after popping everything")
}
if s.Pop("voice", pendingBase) != nil {
t.Error("pop of an empty stack returned something")
}
}
// A popped entry is gone: it must not come back on the next peek.
func TestStackPoppedEntryIsGone(t *testing.T) {
s := NewClarifyStore(time.Minute)
s.Push("voice", parked("напомни", pendingBase))
s.Pop("voice", pendingBase)
if got := s.Peek("voice", pendingBase); got != nil {
t.Errorf("peek after pop = %+v, want nil", got)
}
}
// Past MaxStackDepth the oldest entry comes back to the caller instead of
// vanishing — it is the caller's job to say it was dropped.
func TestStackDepthBoundReturnsTheDroppedEntry(t *testing.T) {
s := NewClarifyStore(time.Minute)
for i := 0; i < MaxStackDepth; i++ {
if dropped := s.Push("voice", parked("first", pendingBase)); dropped != nil {
t.Fatalf("push %d dropped early", i)
}
}
dropped := s.Push("voice", parked("newest", pendingBase))
if dropped == nil {
t.Fatal("push past the bound dropped an entry silently")
}
if dropped.Utterance != "first" {
t.Errorf("dropped %q, want the oldest", dropped.Utterance)
}
if got := s.Depth("voice"); got != MaxStackDepth {
t.Errorf("depth = %d, want %d", got, MaxStackDepth)
}
if got := s.Peek("voice", pendingBase); got == nil || got.Utterance != "newest" {
t.Errorf("peek = %+v, want the newest", got)
}
}
// Put still replaces rather than stacks: a re-ask is another question about the
// same action, so the daemon's depth stays one.
func TestPutReplacesTopWithoutGrowing(t *testing.T) {
s := NewClarifyStore(time.Minute)
s.Put("voice", parked("напомни", pendingBase))
s.Put("voice", parked("напомни ещё раз", pendingBase))
if got := s.Depth("voice"); got != 1 {
t.Fatalf("depth = %d, want 1", got)
}
if got := s.Peek("voice", pendingBase); got == nil || got.Utterance != "напомни ещё раз" {
t.Fatalf("peek = %+v, want the replacement", got)
}
}
// An expired top takes the stack with it, and TakeExpired is what reports it —
// the whole exchange timed out, and one notice is what a reply can carry.
func TestStackExpiryDropsTheStackAndIsReported(t *testing.T) {
s := NewClarifyStore(time.Minute)
s.Push("voice", parked("напомни", pendingBase))
s.Push("voice", parked("погода", pendingBase))
late := pendingBase.Add(2 * time.Minute)
if s.Peek("voice", late) != nil {
t.Error("peek returned an expired question")
}
if s.Depth("voice") != 0 {
t.Error("expired stack survived a peek")
}
s.Push("voice", parked("напомни", pendingBase))
s.Push("voice", parked("погода", pendingBase))
if !s.TakeExpired("voice", late) {
t.Error("TakeExpired did not report the timed-out exchange")
}
if s.Depth("voice") != 0 {
t.Error("TakeExpired left entries behind")
}
if s.TakeExpired("voice", late) {
t.Error("TakeExpired reported twice")
}
// Pop of an expired top yields nothing rather than a dead action.
s.Push("voice", parked("напомни", pendingBase))
if s.Pop("voice", late) != nil {
t.Error("pop returned an expired question")
}
}
// Delete ends the exchange, every level of it.
func TestStackDeleteDropsAll(t *testing.T) {
s := NewClarifyStore(time.Minute)
s.Push("voice", parked("напомни", pendingBase))
s.Push("voice", parked("погода", pendingBase))
s.Delete("voice")
if s.Depth("voice") != 0 || s.Peek("voice", pendingBase) != nil {
t.Error("Delete left questions parked")
}
}
// Stacks are per dialogue id: the mic and the web must not read each other's.
func TestStacksAreIsolatedByID(t *testing.T) {
s := NewClarifyStore(time.Minute)
s.Push("voice", parked("напомни", pendingBase))
s.Push("web", parked("погода", pendingBase))
s.Delete("voice")
if got := s.Peek("web", pendingBase); got == nil || got.Utterance != "погода" {
t.Errorf("web stack = %+v, want its own question", got)
}
}
+96
View File
@@ -142,6 +142,11 @@ type Task struct {
Weight int `json:"weight,omitempty"`
Resolved *time.Time `json:"resolved,omitempty"`
ResolvedBy string `json:"resolved_by,omitempty"`
// DoneWhen — the acceptance criterion. Empty until he writes one, and a
// candidate with no criterion cannot be promoted to open (Vikunja #510).
DoneWhen string `json:"done_when,omitempty"`
// BlockedOn — a canonical Nexus entity id, never a name.
BlockedOn string `json:"blocked_on,omitempty"`
}
// CaptureTaskReq — THE INTAKE SEAM. Everything that captures a task goes
@@ -170,6 +175,11 @@ type CaptureTaskReq struct {
Due *time.Time `json:"due,omitempty"`
Weight int `json:"weight,omitempty"`
Ts time.Time `json:"ts"`
// DoneWhen and BlockedOn are optional at intake. A derived source leaves
// both empty: mail says what to do, not what finishing means, and guessing
// a criterion would put Maven's reading in the field he is meant to write.
DoneWhen string `json:"done_when,omitempty"`
BlockedOn string `json:"blocked_on,omitempty"`
}
// CaptureTaskResp — Created is false when the same live task already existed,
@@ -539,6 +549,51 @@ type setTaskStatusReq struct {
By string `json:"by,omitempty"`
}
// EntityRef — one canonical entity from Nexus. Maven never mints these: an id
// exists because Nexus resolved a name to it.
//
// Ambiguous is the answer when the name matched more than one entity. It is a
// separate state from "not found" because the surface handles them
// differently: an unknown name may be a typo, and an ambiguous one has to be
// asked about, never picked (ECOSYSTEM-SPEC, and the same rule the mutating
// Hexis path follows).
type EntityRef struct {
ID string `json:"id,omitempty"`
Type string `json:"type,omitempty"`
DisplayName string `json:"display_name,omitempty"`
Ambiguous bool `json:"ambiguous,omitempty"`
Candidates []string `json:"candidates,omitempty"`
}
type resolveEntityReq struct {
Query string `json:"query"`
Types []string `json:"types,omitempty"`
}
type resolveEntityResp struct {
Ref EntityRef `json:"ref"`
}
// editTaskReq — the rewrite of the three fields capture set (Vikunja #509).
// Due nil clears the date, so "no date given" and "remove the date" cannot be
// the same request.
type editTaskReq struct {
ID int64 `json:"id"`
Text string `json:"text"`
Due *time.Time `json:"due,omitempty"`
Weight int `json:"weight,omitempty"`
}
// setTaskFieldsReq — the write for the two board columns. Both are sent every
// time and both may be empty: clearing a blocker is as ordinary as setting one,
// so an omitted field cannot mean "leave it alone" without a second way to say
// "make it empty".
type setTaskFieldsReq struct {
ID int64 `json:"id"`
DoneWhen string `json:"done_when,omitempty"`
BlockedOn string `json:"blocked_on,omitempty"`
}
// idReq — methods keyed by a single id.
type idReq struct {
ID int64 `json:"id"`
@@ -781,6 +836,30 @@ type TickTrace struct {
Rules []RuleTrace `json:"rules"`
}
// --- Turn decision trace DTOs (V-564) ---
// TurnClaim — one claimant's say on one turn: who, at which stage, what it
// would have made the turn, the score it reported if it has one, and what
// happened to the claim. Same shape as RuleTrace above and for the same reason:
// a winner alone does not explain an arbitration, the losers do.
type TurnClaim struct {
Stage string `json:"stage"`
Claimant string `json:"claimant"`
Intent string `json:"intent,omitempty"`
Score float64 `json:"score,omitempty"`
HasScore bool `json:"has_score,omitempty"`
Outcome string `json:"outcome"`
Reason string `json:"reason,omitempty"`
}
// TurnDecision — one turn's arbitration, newest first when read as a list.
type TurnDecision struct {
Ts time.Time `json:"ts"`
Utterance string `json:"utterance"`
Winner string `json:"winner"`
Claims []TurnClaim `json:"claims"`
}
// MorningRoutineItem — one checklist entry's current state.
type MorningRoutineItem struct {
Key string `json:"key"`
@@ -847,6 +926,23 @@ type unlockReq struct {
// wire round-tripping via errors.Is).
var ErrToolNotFound = errors.New("ipc: tool not found")
// ErrTaskNoDoneWhen — a candidate cannot be promoted to open with no
// definition of done (Vikunja #510). Carried across the wire so the /tasks
// form can say which refusal it hit rather than "не найдено".
var ErrTaskNoDoneWhen = errors.New("ipc: task has no definition of done")
// ErrTaskDuplicate — an edit would collide with another live task's normalised
// text (Vikunja #509). The surface says which row holds it rather than merging.
var ErrTaskDuplicate = errors.New("ipc: another live task already has this text")
// ErrNoEntity — Nexus resolved the name to nothing. Distinct from an outage,
// which surfaces as the transport error: "there is no such person" and "Nexus
// is down" must not read the same to a caller deciding whether to store an id.
var ErrNoEntity = errors.New("ipc: no such entity")
// ErrTaskResolved — a resolved task is not editable.
var ErrTaskResolved = errors.New("ipc: task is resolved")
// callerKey — context key for the authenticated caller. Server sets it from
// SO_PEERCRED before dispatch; in-process callers omit it (the adapter treats
// a missing Caller as "trusted same-process", the equivalent of the socket's
+24
View File
@@ -515,6 +515,22 @@ func (c *Client) SetTaskStatus(ctx context.Context, id int64, status string, ts
return c.call(ctx, MethodSetTaskStatus, setTaskStatusReq{ID: id, Status: status, Ts: ts, By: by}, nil)
}
func (c *Client) ResolveEntity(ctx context.Context, query string, types []string) (EntityRef, error) {
var r resolveEntityResp
if err := c.call(ctx, MethodResolveEntity, resolveEntityReq{Query: query, Types: types}, &r); err != nil {
return EntityRef{}, err
}
return r.Ref, nil
}
func (c *Client) EditTask(ctx context.Context, id int64, text string, due *time.Time, weight int) error {
return c.call(ctx, MethodEditTask, editTaskReq{ID: id, Text: text, Due: due, Weight: weight}, nil)
}
func (c *Client) SetTaskFields(ctx context.Context, id int64, doneWhen, blockedOn string) error {
return c.call(ctx, MethodSetTaskFields, setTaskFieldsReq{ID: id, DoneWhen: doneWhen, BlockedOn: blockedOn}, nil)
}
// IngestMail hands one fetched message to core for extraction. ErrUnknownMethod
// means core has no email block configured — the caller should stop asking, not
// retry.
@@ -656,6 +672,14 @@ func (c *Client) TickTrace(ctx context.Context) (TickTrace, error) {
return t, nil
}
func (c *Client) TurnDecisions(ctx context.Context, n int) ([]TurnDecision, error) {
var d []TurnDecision
if err := c.call(ctx, MethodTurnDecisions, nReq{N: n}, &d); err != nil {
return nil, err
}
return d, nil
}
func (c *Client) RecentEvents(ctx context.Context, n int) ([]IntakeEvent, error) {
var e []IntakeEvent
if err := c.call(ctx, MethodRecentEvents, nReq{N: n}, &e); err != nil {
+24
View File
@@ -142,6 +142,23 @@ type TaskAPI interface {
// SetTaskStatus moves a task forward once: candidate→open|dropped,
// open→done|dropped. Any other move is refused.
SetTaskStatus(ctx context.Context, id int64, status string, ts time.Time, by string) error
// ResolveEntity asks Nexus for the canonical id behind a name. It is how a
// surface turns "Kate" into an entity id before storing one, because
// identity lives in Nexus and a local name is a second answer to a
// question Nexus already owns. ErrNotImplemented when no Nexus is
// configured, ErrNoEntity when the name matched nothing, and an Ambiguous
// ref when it matched several — the caller asks, it does not pick.
ResolveEntity(ctx context.Context, query string, types []string) (EntityRef, error)
// EditTask rewrites the three fields capture set: text, due date and
// weight. Status is not among them — that ladder is one-way and belongs to
// SetTaskStatus. A resolved task is refused, and a text edit that would
// duplicate another live task is refused rather than merged.
EditTask(ctx context.Context, id int64, text string, due *time.Time, weight int) error
// SetTaskFields writes the definition of done and the blocker. Not a
// status move, so it is not one-way: he may sharpen a criterion, and a
// blocker clears when the person answers. blockedOn is a canonical Nexus
// entity id or empty, never a name the caller had lying around.
SetTaskFields(ctx context.Context, id int64, doneWhen, blockedOn string) error
}
// SystemAPI — what the daemon knows about itself, plus the one method that
@@ -152,6 +169,13 @@ type SystemAPI interface {
// persisted — it's a daemon-level cache).
TickTrace(ctx context.Context) (TickTrace, error)
// TurnDecisions returns the newest turn arbitration records, newest first
// (V-564). Same shape as TickTrace and RecentEvents: a bounded in-memory
// ring on the daemon, so the store adapter returns an error rather than
// pretending a table exists. Empty is a normal answer — it means no turn
// has run since the daemon started.
TurnDecisions(ctx context.Context, n int) ([]TurnDecision, 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)
+3
View File
@@ -31,6 +31,9 @@ var mapErrPairs = []struct {
{"ErrReminderNotFound", store.ErrReminderNotFound, ErrReminderNotFound},
{"ErrReminderState", store.ErrReminderState, ErrReminderState},
{"ErrToolNotFound", store.ErrToolNotFound, ErrToolNotFound},
{"ErrTaskNoDoneWhen", store.ErrTaskNoDoneWhen, ErrTaskNoDoneWhen},
{"ErrTaskDuplicate", store.ErrTaskDuplicate, ErrTaskDuplicate},
{"ErrTaskResolved", store.ErrTaskResolved, ErrTaskResolved},
}
// unmappedStoreErrors — store sentinels that deliberately have no wire twin,
+20
View File
@@ -540,6 +540,19 @@ var methodTable = map[Method]handlerFunc{
MethodSetTaskStatus: withParamsVoid(func(ctx context.Context, api CoreAPI, p setTaskStatusReq) error {
return api.SetTaskStatus(ctx, p.ID, p.Status, p.Ts, p.By)
}),
MethodResolveEntity: withParams(func(ctx context.Context, api CoreAPI, p resolveEntityReq) (resolveEntityResp, error) {
ref, err := api.ResolveEntity(ctx, p.Query, p.Types)
if err != nil {
return resolveEntityResp{}, err
}
return resolveEntityResp{Ref: ref}, nil
}),
MethodEditTask: withParamsVoid(func(ctx context.Context, api CoreAPI, p editTaskReq) error {
return api.EditTask(ctx, p.ID, p.Text, p.Due, p.Weight)
}),
MethodSetTaskFields: withParamsVoid(func(ctx context.Context, api CoreAPI, p setTaskFieldsReq) error {
return api.SetTaskFields(ctx, p.ID, p.DoneWhen, p.BlockedOn)
}),
MethodListProposedRoutines: withoutParams(func(ctx context.Context, api CoreAPI) (listProposedRoutinesResp, error) {
out, err := api.ListProposedRoutines(ctx)
if err != nil {
@@ -570,6 +583,13 @@ var methodTable = map[Method]handlerFunc{
MethodTickTrace: withoutParams(func(ctx context.Context, api CoreAPI) (TickTrace, error) {
return api.TickTrace(ctx)
}),
MethodTurnDecisions: withParams(func(ctx context.Context, api CoreAPI, p nReq) ([]TurnDecision, error) {
d, err := api.TurnDecisions(ctx, p.N)
if d == nil {
d = []TurnDecision{}
}
return d, err
}),
// MorningStatus intentionally has no nil→[]T{} normalization here — the
// pre-table arm marshaled api.MorningStatus's result as-is (a nil slice
// serializes as JSON null), and this preserves that exact wire shape.
+31
View File
@@ -265,6 +265,12 @@ func (a *storeAPI) TickTrace(ctx context.Context) (TickTrace, error) {
return TickTrace{}, errors.New("store: tick trace not available via direct store API")
}
// 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) {
return nil, errors.New("store: turn decisions not available via direct store API")
}
// SeedEvent — same shape as MorningStatus: writing the fact is a store call,
// but extraction and detect-and-propose live in mavend, and a seed that wrote
// the fact without running them would be the one thing this seam must not be,
@@ -317,6 +323,8 @@ func (a *storeAPI) CaptureTask(ctx context.Context, req CaptureTaskReq) (Capture
Status: req.Status,
Due: req.Due,
Weight: req.Weight,
DoneWhen: req.DoneWhen,
BlockedOn: req.BlockedOn,
})
if err != nil {
return CaptureTaskResp{}, mapErr(err)
@@ -343,6 +351,8 @@ func (a *storeAPI) ListTasks(ctx context.Context, status string) ([]Task, error)
Weight: t.Weight,
Resolved: t.ResolvedTs,
ResolvedBy: t.ResolvedBy,
DoneWhen: t.DoneWhen,
BlockedOn: t.BlockedOn,
}
}
return out, nil
@@ -352,6 +362,21 @@ func (a *storeAPI) SetTaskStatus(ctx context.Context, id int64, status string, t
return mapErr(a.s.SetTaskStatus(ctx, id, status, ts, by))
}
// ResolveEntity is not the store's to answer: identity lives in Nexus and this
// adapter has no client. The daemon overrides it (cmd/mavend/tick_api.go), and
// a deployment with no nexus block keeps this refusal.
func (a *storeAPI) ResolveEntity(ctx context.Context, query string, types []string) (EntityRef, error) {
return EntityRef{}, ErrNotImplemented
}
func (a *storeAPI) EditTask(ctx context.Context, id int64, text string, due *time.Time, weight int) error {
return mapErr(a.s.EditTask(ctx, id, text, due, weight))
}
func (a *storeAPI) SetTaskFields(ctx context.Context, id int64, doneWhen, blockedOn string) error {
return mapErr(a.s.SetTaskFields(ctx, id, doneWhen, blockedOn))
}
func (a *storeAPI) ListProposedRoutines(ctx context.Context) ([]ProposedRoutine, error) {
rs, err := a.s.ListProposedRoutines(ctx)
if err != nil {
@@ -458,6 +483,12 @@ func mapErr(err error) error {
return ErrReminderState
case errors.Is(err, store.ErrToolNotFound):
return ErrToolNotFound
case errors.Is(err, store.ErrTaskNoDoneWhen):
return ErrTaskNoDoneWhen
case errors.Is(err, store.ErrTaskDuplicate):
return ErrTaskDuplicate
case errors.Is(err, store.ErrTaskResolved):
return ErrTaskResolved
}
return err
}
+12
View File
@@ -114,6 +114,15 @@ func (UnimplementedCoreAPI) ListTasks(ctx context.Context, status string) ([]Tas
func (UnimplementedCoreAPI) SetTaskStatus(ctx context.Context, id int64, status string, ts time.Time, by string) error {
return ErrNotImplemented
}
func (UnimplementedCoreAPI) ResolveEntity(ctx context.Context, query string, types []string) (EntityRef, error) {
return EntityRef{}, ErrNotImplemented
}
func (UnimplementedCoreAPI) EditTask(ctx context.Context, id int64, text string, due *time.Time, weight int) error {
return ErrNotImplemented
}
func (UnimplementedCoreAPI) SetTaskFields(ctx context.Context, id int64, doneWhen, blockedOn string) error {
return ErrNotImplemented
}
func (UnimplementedCoreAPI) ListProposedRoutines(ctx context.Context) ([]ProposedRoutine, error) {
return nil, ErrNotImplemented
}
@@ -135,6 +144,9 @@ func (UnimplementedCoreAPI) RevertFact(ctx context.Context, key string) (int64,
func (UnimplementedCoreAPI) TickTrace(ctx context.Context) (TickTrace, error) {
return TickTrace{}, ErrNotImplemented
}
func (UnimplementedCoreAPI) TurnDecisions(ctx context.Context, n int) ([]TurnDecision, error) {
return nil, ErrNotImplemented
}
func (UnimplementedCoreAPI) MorningStatus(ctx context.Context) ([]MorningRoutineStatus, error) {
return nil, ErrNotImplemented
}
+4
View File
@@ -48,6 +48,7 @@ const (
MethodAcceptProposedRoutine Method = "accept_proposed_routine"
MethodRevertFact Method = "revert_fact"
MethodTickTrace Method = "tick_trace"
MethodTurnDecisions Method = "turn_decisions"
MethodMorningStatus Method = "morning_status"
MethodMCPServers Method = "mcp_servers"
MethodDayPlan Method = "day_plan"
@@ -55,6 +56,9 @@ const (
MethodCaptureTask Method = "capture_task"
MethodListTasks Method = "list_tasks"
MethodSetTaskStatus Method = "set_task_status"
MethodSetTaskFields Method = "set_task_fields"
MethodEditTask Method = "edit_task"
MethodResolveEntity Method = "resolve_entity"
MethodIngestMail Method = "ingest_mail"
MethodSwapModel Method = "swap_model"
MethodModelStatus Method = "model_status"
+64 -1
View File
@@ -63,7 +63,9 @@ func mustLoad() lexiconFile {
for _, name := range []string{
"interrogatives", "capture_verbs", "narrative_requests", "cardinals", "ordinals",
"day_offsets", "weekdays", "months_genitive", "hours_spoken",
"not_place_after_v", "parts_of_day", "reminder_verbs",
"not_place_after_v", "parts_of_day", "reminder_verbs", "half_hour",
"filler_particles", "task_done_words", "task_drop_words",
"confirm_yes", "confirm_no",
} {
s, ok := f.Sets[name]
if !ok || (len(s.Words) == 0 && len(s.Values) == 0) {
@@ -112,6 +114,67 @@ func PartsOfDay() []string { return words("parts_of_day") }
// ReminderVerbs returns the imperatives that open a reminder.
func ReminderVerbs() []string { return words("reminder_verbs") }
// TaskDoneWords returns the words that finish a task, and TaskDropWords the
// words that abandon one. Two sets rather than one with a value, because the
// store records which of the two happened and the caller has to say so.
//
// Both mix moods on purpose, and the caller must match them the way the sets'
// notes say: an imperative exactly, a stative by lemma.
func TaskDoneWords() []string { return words("task_done_words") }
// ConfirmYes returns the words that answer a parked confirm with yes, and
// ConfirmNo the ones that answer it with no. Some members are multi-word ("не
// надо"), so a caller matches longest-first over tokens rather than looking up
// one word at a time. See the sets' notes for why neither may be matched as a
// substring.
func ConfirmYes() []string { return words("confirm_yes") }
// ConfirmNo — see ConfirmYes.
func ConfirmNo() []string { return words("confirm_no") }
// TaskDropWords — see TaskDoneWords.
func TaskDropWords() []string { return words("task_drop_words") }
// SlotValueFrame returns the words that can surround a bare slot value without
// making the utterance a request of its own. A caller strips these (along with
// the numbers and the other closed time sets) to see whether an utterance
// carries any content beside the value it was asked for. See the set's note.
func SlotValueFrame() []string { return words("slot_value_frame") }
// DialogueCancel returns the ways he calls off the request Maven is assembling.
// Distinct from TaskDropWords, which abandons an item that already exists.
func DialogueCancel() []string { return words("dialogue_cancel") }
// IsFillerParticle reports whether a word can never be the subject of a
// request: a particle, a politeness word, or the first-person object. See the
// set's own note for why this is not a stopword list.
func IsFillerParticle(word string) bool {
w := norm(word)
for _, p := range ru.Sets["filler_particles"].Words {
if w == p {
return true
}
}
return false
}
// HalfHourWords returns those forms, for a caller folding every time word into
// one set rather than asking about one word.
func HalfHourWords() []string { return words("half_hour") }
// IsHalfHour reports whether a word introduces a spoken half hour, so the
// ordinal after it is an hour rather than a position. One caller reads that
// ordinal as the hour and another has to decline it; both ask here.
func IsHalfHour(word string) bool {
w := norm(word)
for _, h := range ru.Sets["half_hour"].Words {
if w == h {
return true
}
}
return false
}
// Cardinal reports the value of a spoken number word. The word is compared
// lowercased and trimmed, because it arrives from a tokenizer that may not have
// done either.
+67
View File
@@ -166,6 +166,73 @@
"напомни", "напомните", "напомнить", "напоминай",
"remind"
]
},
"half_hour": {
"note": "The forms of \"половина\" that introduce a spoken half hour: \"в половине восьмого\", \"к половине\", the bare \"пол\" of \"полвосьмого\". The set matters to two callers and for opposite reasons (V-522). The clock rewrite reads the ordinal after one of these as the hour being entered, and the ordinal-selection turn has to REFUSE that ordinal, because \"в половине восьмого\" names a time and not the eighth thing she read out.",
"words": [
"половина", "половине", "половину", "половины", "пол",
"half"
]
},
"filler_particles": {
"note": "Words that carry no subject of their own: particles, the politeness words, and the first-person object he addresses her with. A caller asking \"did he say WHAT to remind him about\" has to discount these, or \"ну напомни же\" and \"напомни мне пожалуйста\" both read as a reminder whose subject is the particle. Closed in the sense that matters: these are function words, and the language is not adding any. Not a stopword list — a stopword list is a scoring convenience and may be as long as it likes, while every word here has to be one that cannot BE a reminder's subject.",
"words": [
"ну", "же", "уж", "там", "вот", "пожалуйста", "плиз", "ка",
"давай", "давай-ка", "а", "и", "бы", "мне", "меня", "мной",
"please", "just", "hey", "me"
]
},
"task_done_words": {
"note": "The ways he says a task is finished, split by mood the way the Praxis lifecycle words are (Vikunja #512). The imperatives are addressed to her and are matched exactly, because morph.SameWord makes \"закрой\" and \"закрыл\" one word and only one of them is an instruction. The statives report his own day and are matched by lemma, since \"сделано\", \"сделана\" and \"сделанную\" are one state. Closed because these are her vocabulary for one transition, not a discovery about Russian.",
"words": [
"закрой", "закройте", "закрыть", "заверши", "завершить", "close", "finish",
"сделано", "сделал", "сделала", "выполнено", "выполнил", "выполнила",
"готово", "готова", "закрыл", "закрыла", "done", "finished"
]
},
"task_drop_words": {
"note": "The ways he abandons a task rather than finishing it (Vikunja #512). Same two moods as task_done_words and the same matching rule. Separate from the done words because the store records which of the two happened and /tasks shows it: dropped work he chose to stop is not work he did.",
"words": [
"убери", "уберите", "убрать", "удали", "удалить", "отмени", "отменить",
"drop", "remove", "cancel",
"передумал", "передумала", "неактуально"
]
},
"slot_value_frame": {
"note": "The words that can stand around a bare slot value without making the utterance a request of its own (Vikunja #560). Prepositions, hedges and the nouns a spoken time is built from: strip these, the numbers, the interrogatives, the filler particles and the other time sets, and whatever is left is the utterance's OWN content. \"а что если в 11:00\" leaves nothing and is an answer; \"какая сейчас погода в Риме\" leaves \"погода\" and \"Риме\" and is not. Closed because each part of it is closed — Russian has a fixed list of prepositions, and a clock is built from a fixed list of nouns. It is not a stopword list: a word goes in only if it can never be the thing he is asking about.",
"words": [
"в", "во", "на", "к", "ко", "до", "с", "со", "за", "по", "под", "около", "через", "после", "перед", "от", "из", "у", "при", "про",
"at", "on", "in", "by", "to", "till", "until", "after", "before", "about", "for",
"нет", "не", "да", "ага", "угу", "ой", "ох", "тогда", "лучше", "может", "можно", "наверное", "наверно", "пожалуй", "точнее", "скорее", "если", "пусть", "прости", "извини", "слушай", "значит", "как-то", "типа", "вообще-то",
"no", "yes", "yeah", "ok", "okay", "sorry", "maybe", "actually", "rather", "then", "well",
"час", "часа", "часов", "часу", "часам", "минут", "минута", "минуты", "минуту", "минутах", "полдень", "полночь", "полдня",
"утра", "утро", "утру", "дня", "день", "днями", "вечера", "вечер", "вечеру", "ночи", "ночь", "ночью",
"сейчас", "теперь", "сегодняшний", "ближайший", "ближайшее",
"hour", "hours", "minute", "minutes", "noon", "midnight", "am", "pm", "oclock", "now"
]
},
"dialogue_cancel": {
"note": "The ways he calls off the request Maven is in the middle of assembling (Vikunja #560). Not task_drop_words: those abandon a Praxis item that exists, these abandon a question she has only just asked, and \"удали\" must never mean the second. Matched as the WHOLE utterance minus its frame, because \"забудь\" alone calls off the reminder and \"забудь купить молоко\" is a sentence with content of its own.",
"words": [
"отмена", "отмени", "отменить", "отставить", "забудь", "забей", "неважно", "проехали", "передумал", "передумала",
"cancel", "nevermind", "forget"
]
},
"confirm_yes": {
"note": "The whole vocabulary of saying yes to a parked confirm, Russian and English. Closed because it is her question that is being answered: she asked \"да или нет\", and the answers to that question can be listed. Matched as whole tokens and never as substrings — \"погода\", \"давление\" and \"дальше\" all contain \"да\", and a substring test executed a destructive act when he asked about the weather (V-567). Words that merely sound agreeable — \"хорошо\", \"ладно\", \"точно\" — are deliberately absent: they open a sentence about something else as often as they answer, and an unclear answer must route rather than execute.",
"words": [
"да", "ага", "угу", "давай", "давайте", "конечно",
"подтверждаю", "подтверди", "подтвердить", "выполняй", "валяй",
"yes", "yeah", "yep", "yup", "ok", "okay", "sure", "confirm", "affirmative"
]
},
"confirm_no": {
"note": "The answers that decline a parked confirm. Same matching rule as confirm_yes and the same reason. The multi-word members are here rather than assembled by a caller because \"надо\" alone is not an answer and \"не надо\" is the opposite of one: the two must land on opposite sides, and only the phrase says which. \"не\" on its own is NOT a member — \"не забудь купить хлеб\" is a reminder, not a refusal.",
"words": [
"нет", "неа", "нельзя", "отмена", "отмени", "отменить", "отставить",
"стоп", "стой", "не надо", "не нужно", "не стоит", "не сейчас", "не хочу",
"no", "nope", "nah", "negative", "cancel", "stop", "don't", "dont"
]
}
}
}
+64 -8
View File
@@ -512,19 +512,40 @@ func (p *LLMPhraser) PhraseQuery(ctx context.Context, utterance string, notes []
// message array from dialogue history + the current user utterance. On any LLM
// error it returns both ChatFallback and the error, on the same rule as
// PhraseQuery: the fallback keeps the turn alive, the error stays visible.
// chatUserMessage folds the prior turns and the current one into a single user
// message, because some chat templates (Ministral and others) reject two user
// turns in a row. That constraint is real; what was wrong is how it was met.
//
// The turns used to be joined with newlines and nothing else, so the model was
// handed four unlabelled lines and no way to tell which one it was answering
// (Vikunja #554). It answered an earlier one, or answered all of them at once:
// asked "как дела" after a question about the telephone, she carried on about
// the telephone. Four turns live for fifteen minutes, so the wrong line was
// often several minutes old.
//
// The history holds only his own utterances, never her replies, so the label
// says so and stays in the second person the persona requires. With no history
// the message is the utterance alone, which is the common case and unchanged.
func chatUserMessage(utterance string, history []dialogue.Turn) string {
prior := make([]string, 0, len(history))
for _, t := range history {
if s := strings.TrimSpace(t.Text); s != "" {
prior = append(prior, "- "+s)
}
}
if len(prior) == 0 {
return strings.TrimSpace(utterance)
}
return "Раньше ты говорил:\n" + strings.Join(prior, "\n") +
"\n\nОтветь только на то, что ты говоришь сейчас: " + strings.TrimSpace(utterance)
}
func (p *LLMPhraser) PhraseChat(ctx context.Context, utterance string, history []dialogue.Turn) (string, error) {
sys := chatSystemPrompt(p.cfg.ContextBlock)
msgs := []chatMsg{
{Role: "system", Content: sys},
}
// Combine history and current utterance into one user message.
// Some model chat templates (Ministral, etc.) reject consecutive user turns.
var combined string
for _, t := range history {
combined += t.Text + "\n"
}
combined += utterance
msgs = append(msgs, chatMsg{Role: "user", Content: strings.TrimSpace(combined)})
msgs = append(msgs, chatMsg{Role: "user", Content: chatUserMessage(utterance, history)})
resp, err := p.chatWithMessages(ctx, msgs, 768)
if err != nil {
@@ -920,6 +941,41 @@ func (p *LLMPhraser) knowledgePrompt(utterance string) (sys, user string) {
fmt.Sprintf("Пользователь спрашивает: \"%s\".", utterance)
}
// PhraseSelf answers a question about her from her own description. Same
// discipline as the evidence branch — say only what the text says — and a
// different opener, because "вот что я нашла: я — твоя помощница" says she
// looked herself up (Vikunja #555). She did not; this is the one subject she
// does not have to read about.
//
// On any error it reads the description out rather than ship a fragment. That
// is already a readable answer, which is why this needs no separate fallback.
func (p *LLMPhraser) PhraseSelf(ctx context.Context, utterance, description string) (string, error) {
sys := persona.Prepend(p.cfg.ContextBlock,
"Он спрашивает о тебе. Отвечай ТОЛЬКО по описанию, которое тебе дали: всё, что ты говоришь о себе, должно быть в нём. "+
"Не добавляй умений, которых там нет, и не догадывайся. Не начинай с \"вот что я нашла\" — ты говоришь о себе, а не о находке. "+
// The gender rule is stated WITHOUT the "-ла" example the other
// prompts carry. Measured on the box: a 1.7B reads that as an
// instruction to use the past tense and answers "я вела заметки,
// управляла домом" — she describes what she does, in the present,
// and the past tense makes a live capability sound finished.
"Отвечай по-русски, коротко и своими словами, в настоящем времени — ты описываешь, что делаешь сейчас. О себе говори в женском роде. "+
"Он мужчина, обращайся к нему на \"ты\". Отвечай ТОЛЬКО одним объектом JSON: {\"response\": \"...\", \"mood\": \"neutral\"}.")
prompt := fmt.Sprintf("Он спрашивает: %q\n\nТвоё описание:\n%s\n\nОтветь ему на то, что он спросил.", utterance, description)
resp, err := p.chatWithSystem(ctx, sys, prompt, 768)
text, _, perr := parseResponseMood(resp)
if err != nil || perr != nil {
cause := err
if cause == nil {
cause = perr
}
return description, fmt.Errorf("phrase self: %w", cause)
}
if text != "" {
return text, nil
}
return description, nil
}
// evidencePrompt — the sources branch: read these, add nothing. Shared with
// PhraseWorld for the same reason as knowledgePrompt.
func (p *LLMPhraser) evidencePrompt(utterance string, notes []string) (sys, user string) {
@@ -0,0 +1,42 @@
package phraser
import (
"strings"
"testing"
"github.com/kami/maven/internal/dialogue"
)
// TestChatUserMessageMarksWhichTurnToAnswer — Vikunja #554. Four prior turns
// were joined with newlines and nothing else, so nothing in the message said
// which line was the question.
func TestChatUserMessageMarksWhichTurnToAnswer(t *testing.T) {
got := chatUserMessage("как дела", []dialogue.Turn{
{Text: "кто изобрёл телефон"},
{Text: "а когда это было"},
})
if !strings.Contains(got, "кто изобрёл телефон") {
t.Error("the prior turns must survive — they are what anaphora reads")
}
now := strings.LastIndex(got, "как дела")
if now < strings.Index(got, "кто изобрёл телефон") {
t.Error("the current utterance must come last, after the turns it follows")
}
if !strings.Contains(got, "Раньше ты говорил") {
t.Errorf("the prior turns must be labelled as prior: %q", got)
}
if strings.Contains(got, " вы ") || strings.Contains(got, "Вы ") {
t.Errorf("the persona addresses him informally: %q", got)
}
}
// TestChatUserMessageWithNoHistoryIsJustTheUtterance — the common case must not
// grow a preamble that the model then has to see past.
func TestChatUserMessageWithNoHistoryIsJustTheUtterance(t *testing.T) {
if got := chatUserMessage(" привет ", nil); got != "привет" {
t.Errorf("chatUserMessage = %q, want %q", got, "привет")
}
if got := chatUserMessage("привет", []dialogue.Turn{{Text: " "}}); got != "привет" {
t.Errorf("a blank prior turn must not label anything: %q", got)
}
}
+10
View File
@@ -49,6 +49,9 @@ type Phraser interface {
PhraseNudge(ctx context.Context, c loop.Candidate) (delivery.PhrasedNudge, error)
PhraseReminder(ctx context.Context, d loop.ReminderDecision) (delivery.PhrasedReminder, error)
PhraseQuery(ctx context.Context, utterance string, notes []string) (string, error)
// PhraseSelf answers a question about her from her own description, which
// is not a source she read and must not be phrased as one (Vikunja #555).
PhraseSelf(ctx context.Context, utterance, description string) (string, error)
PhraseChat(ctx context.Context, utterance string, history []dialogue.Turn) (string, error)
Close() error
}
@@ -81,6 +84,13 @@ func (s *Stub) PhraseQuery(_ context.Context, _ string, notes []string) (string,
return SourcesFallback(strings.Join(notes, "; ")), nil
}
// PhraseSelf reads the description out as it stands. There is nothing to fall
// back to and nothing to shorten: the text is already written in her voice, and
// that is the whole reason it is a constant rather than a prompt.
func (s *Stub) PhraseSelf(_ context.Context, _, description string) (string, error) {
return description, nil
}
// Close implements Phraser.Close (no-op for the stub).
func (s *Stub) Close() error { return nil }
+57
View File
@@ -0,0 +1,57 @@
package router
import "regexp"
// IsAgendaQuestion answers whether an utterance asks about the owner's own
// schedule, as opposed to merely naming a day.
//
// It exists because the calendar query source used to match on a day word and
// nothing else (Vikunja #552). Every world question that happened to name a
// day was claimed by the calendar and answered with an empty schedule: "какой
// сегодня курс доллара" replied "на 05.08.2026 ничего нет", which reads as an
// answer about a subject she never looked at. V-474 had already fixed one
// instance of the class by teaching the calendar to step aside on weather
// wording. Sunset, holidays, exchange rates and world news are the same class
// and weather wording does not cover them.
//
// Three arms, and the order is only readability — any one of them is enough:
//
// - an agenda grammar already claims the phrasing. Reusing
// AgendaQueryGrammars means the rule that ROUTES a question to the query
// chain and the rule that lets the CALENDAR answer it cannot drift apart.
// - the utterance names a scheduled thing. Wider than the grammars on
// purpose: "какие встречи завтра" carries no possessive and no plan noun,
// so no grammar claims it, and it is plainly a calendar question.
// - the question names no subject of its own. "что сегодня?" is his agenda
// by default, because there is nothing else for it to be about. This is
// the same test the bare-imperative Praxis arm applies.
//
// Not a routing decision and not a fact, so a pattern is the right mechanism
// here: it selects which source answers, and every source below still runs
// when it returns false.
func IsAgendaQuestion(u string) bool {
for _, g := range AgendaQueryGrammars() {
if g.Pattern.MatchString(u) {
return true
}
}
return scheduledThing.MatchString(u) || subjectlessDayQuestion.MatchString(u)
}
// scheduledThing — the nouns that name something on a calendar. Closed in the
// sense that matters: these are the words for an appointment itself, not the
// words for what an appointment is about. The stems are the union of the ones
// AgendaQueryGrammars already carries, read here as a noun test rather than as
// part of a phrasing.
//
// Stems and not whole words, because Russian declines them and "какие встречи"
// and "на встречу" are one question.
var scheduledThing = regexp.MustCompile(`(?i)(календар|расписани|повестк|планёрк|планерк|встреч|созвон|митинг|совещани|приём|прием|собеседовани|тренировк|занятие|занятия)`)
// subjectlessDayQuestion — "что сегодня?", "что там на завтра", "что в среду".
// An interrogative, an optional preposition, a day word, and nothing else. The
// anchors at both ends are the whole point: the moment the sentence names what
// it is asking about, it stops being his agenda and this must not match.
var subjectlessDayQuestion = regexp.MustCompile(
`(?i)^\s*(что|чего|какие|сколько|what)\s+(там\s+|ещё\s+|еще\s+)?(на\s+|в\s+|во\s+)?` +
dayWordPattern + `\s*[?!.]*$`)
+66
View File
@@ -0,0 +1,66 @@
package router
import "testing"
// The four utterances in Vikunja #552 plus the ones that must keep reaching
// the calendar. The list is the whole point of the predicate: every "want
// false" row was answered "на 05.08.2026 ничего нет" on the deployed daemon.
func TestIsAgendaQuestionSeparatesHisDayFromTheWorld(t *testing.T) {
tests := []struct {
utterance string
want bool
}{
// His day.
{"что у меня сегодня", true},
{"во сколько у меня встреча сегодня", true},
{"что в календаре на завтра", true},
{"какие планы на завтра", true},
{"какие встречи завтра", true},
{"когда планёрка", true},
{"покажи расписание на среду", true},
{"что дальше?", true},
// No subject of its own, so his day by default.
{"что сегодня?", true},
{"что на завтра", true},
{"что там в среду?", true},
// The world, naming a day. Every one of these is #552.
{"во сколько закат сегодня", false},
{"какой сегодня курс доллара", false},
{"какой сегодня праздник", false},
{"что интересного произошло сегодня в мире", false},
{"кто выиграл вчера матч", false},
// A day word plus a subject is never subjectless, however short.
{"что за праздник сегодня", false},
}
for _, tt := range tests {
if got := IsAgendaQuestion(tt.utterance); got != tt.want {
t.Errorf("IsAgendaQuestion(%q) = %v, want %v", tt.utterance, got, tt.want)
}
}
}
// One hand-written utterance per agenda grammar, keyed by name. Asserting that
// the grammars pass IsAgendaQuestion would be true by construction, since the
// first arm is the loop over them. This asserts something else: that each
// grammar still matches the case its own comment gives, and that the set of
// grammars has not grown a member nobody wrote an example for.
func TestEachAgendaGrammarStillMatchesItsOwnExample(t *testing.T) {
examples := map[string]string{
"calendar-query": "что в календаре на завтра",
"agenda-query": "что у меня сегодня",
"plan-day-query": "какие планы на завтра",
"rest-of-day-query": "что дальше?",
"event-time-query": "когда планёрка",
}
for _, g := range AgendaQueryGrammars() {
u, ok := examples[g.Name]
if !ok {
t.Errorf("agenda grammar %q has no example here — add one", g.Name)
continue
}
if !g.Pattern.MatchString(u) {
t.Errorf("grammar %q no longer matches %q", g.Name, u)
}
}
}
+51
View File
@@ -0,0 +1,51 @@
package router
import (
"regexp"
"strings"
)
// BareCaptureGrammar — a capture verb with nothing after it is a fact she has
// yet to hear, not a conversation (Vikunja #557).
//
// A bare "запиши" reached the resident model as chat, and the model answered by
// agreeing to something nobody asked for: "Я поняла, теперь я буду говорить
// «записала» или «записала заметку»." It read its own instruction block as the
// subject of the turn. Whatever the routing, that reply is invented.
//
// The route this rule asks for is a fact with no key, which is a gap the clarify
// path already has copy for ("Что записать?"). So the rule does not answer the
// turn — it hands it to the one mechanism that asks.
//
// Wired before TaskCaptureGrammar, whose pattern needs an object, so it can
// never claim this shape. There is nothing to disambiguate: the whole utterance
// is one verb from a closed lexicon.
func BareCaptureGrammar() []Grammar {
return []Grammar{{
Name: "bare-capture",
Pattern: bareCapturePattern,
Build: bareCaptureBuild,
}}
}
// Anchored at both ends, so only the verb and punctuation are in the utterance.
// Trailing "-ка" and "пожалуйста" are the same request said politely.
var bareCapturePattern = regexp.MustCompile(`(?i)^\s*([\p{L}]+)(?:-ка)?[,\s]*(?:пожалуйста)?[\s.!?]*$`)
func bareCaptureBuild(m []string) (Decision, bool) {
word := strings.ToLower(strings.TrimSpace(m[1]))
for _, v := range captureVerbs {
if word != v {
continue
}
// No key, no text: she was told to record and not what. Confidence is
// 1.0 about the shape, which is all stage 0 ever claims — the gap is
// carried by the empty slots, not by a doubt.
return Decision{
Stage: 0,
Intent: IntentFact,
Confidence: 1.0,
}, true
}
return Decision{}, false
}
+37
View File
@@ -0,0 +1,37 @@
package router
import "testing"
// TestBareCaptureIsAFactWithNoKey — Vikunja #557. The whole point is the gap:
// she must route it as a fact she cannot write yet, so the clarify path asks.
func TestBareCaptureIsAFactWithNoKey(t *testing.T) {
for _, u := range []string{"запиши", "Запиши.", "запомни, пожалуйста", "отметь!", "note", "запиши-ка"} {
m := bareCapturePattern.FindStringSubmatch(u)
if m == nil {
t.Errorf("%q did not match the shape", u)
continue
}
dec, ok := bareCaptureBuild(m)
if !ok {
t.Errorf("%q should route as a fact with no key", u)
continue
}
if dec.Intent != IntentFact || dec.Slots.HasKey || dec.Slots.Text != "" {
t.Errorf("%q built %+v, want an empty fact", u, dec)
}
}
}
// TestBareCaptureDeclinesAnythingWithAnObject — the object cases belong to the
// capture markers and the cascade, and a lone non-capture word is not this rule.
func TestBareCaptureDeclinesAnythingWithAnObject(t *testing.T) {
for _, u := range []string{"запиши что я пил воду", "добавь задачу купить хлеб", "привет", "вода", "расскажи"} {
m := bareCapturePattern.FindStringSubmatch(u)
if m == nil {
continue // shape already declined it
}
if _, ok := bareCaptureBuild(m); ok {
t.Errorf("%q must not be claimed as a bare capture", u)
}
}
}
+113
View File
@@ -0,0 +1,113 @@
package router
import "github.com/kami/maven/internal/claim"
// ClaimOf — build a claim.Claim from a Decision (V-565, design in
// docs/plans/19-dialogue-arbitration.md).
//
// Additive and beside the existing path. Decision.Confidence keeps its float
// and keeps working: r.threshold and gateLLMDecision read it, and the
// classifier cascade is the failure floor. Nothing in Route calls this yet.
// The arbiter that reads claims is V-560.
//
// claimant names who produced the decision. The cascade does not record which
// stage-0 grammar matched, so the caller passes what it knows and the builder
// does not guess.
func ClaimOf(claimant string, d Decision) claim.Claim {
consumed, unexplained := claim.Split(d.Utterance, claimSpans(d)...)
return claim.Claim{
Claimant: claimant,
Intent: string(d.Intent),
Filled: filledSlots(d.Slots),
Consumed: consumed,
Unexplained: unexplained,
Band: bandOf(d),
Veto: vetoOf(d),
}
}
// claimSpans — the parts of the utterance the decision says it read. Slot
// values, not the utterance, because coverage is the question of how much of
// the sentence the claim actually explains.
//
// A stage-0 grammar reports whatever its Build put in the slots, which for the
// reminder rule is the text after "напомни" and not the verb itself. That
// under-reports coverage rather than over-reporting it, which is the safe
// direction: a claim that overstates what it explains wins arbitrations it
// should lose.
func claimSpans(d Decision) []string {
spans := []string{d.Slots.Text, d.Slots.Key, d.Slots.Value, d.Slots.Fn}
return append(spans, d.Slots.Args...)
}
// filledSlots — the slot names this decision would fill. Text counts only when
// it differs from the whole utterance: fillSlots backfills the raw utterance
// into Text for a note, a query and a chat turn, so a set Text is not by itself
// evidence that anything was extracted.
func filledSlots(s Slots) []string {
var out []string
if s.HasTime {
out = append(out, "time")
}
if s.HasFn {
out = append(out, "fn")
}
if s.HasKey {
out = append(out, "key")
}
if s.Text != "" {
out = append(out, "text")
}
return out
}
// bandOf — which kind of evidence this decision rests on.
//
// Stage 0 is anchored: a literal pattern matched and its span decided the
// intent. The LLM path (stage 1) is structural: the model read the whole
// sentence, and gateLLMDecision already checked the route for structural
// holes. The classifier (stages 2 and 3) is nearest, and the measurement is why
// it is one band rather than a scale — on the 91-case RU fixture its cosine
// spans 0.859 to 0.942 and scores 62% at both ends.
//
// A decision carrying a veto lands in BandVetoed regardless of who produced it.
// That is the point of the band: a self-vetoed claim should lose to any claim
// that is not, whatever machinery built it.
func bandOf(d Decision) claim.Band {
if vetoOf(d) != "" {
return claim.BandVetoed
}
switch d.Stage {
case 0:
return claim.BandAnchored
case 1:
return claim.BandStructural
default:
return claim.BandNearest
}
}
// vetoOf — why this decision should not win, recovered as a reason rather than
// a number.
//
// gateLLMDecision flattens three named structural holes into
// llmThinConfidence, and the reason is lost at that point: 0.3 tells a reader
// that something was wrong and never which thing. The same three conditions are
// checked here so the claim carries the sentence a trace can print and the
// owner can be told.
//
// Clarify is checked last and is the general case. A decision below threshold
// has already asked to be doubted, whichever path set it.
func vetoOf(d Decision) string {
switch {
case d.Intent == IntentFact && !d.Slots.HasKey:
return "fact with no key: nothing to write, or a confident write under the wrong key"
case d.Intent == IntentAct && !d.Slots.HasFn:
return "act with no allowlisted fn: running an unlisted command or silently doing nothing"
case d.Intent == IntentReminder && !reminderHasSubject(d.Slots.Text):
return "reminder with no subject: it would fire empty at the hour"
case d.Clarify:
return "below the confidence gate"
}
return ""
}
+160
View File
@@ -0,0 +1,160 @@
package router
import (
"context"
"reflect"
"testing"
"time"
"github.com/kami/maven/internal/claim"
)
func TestClaimOfBands(t *testing.T) {
cases := []struct {
name string
dec Decision
want claim.Band
}{
{
name: "stage 0 is anchored",
dec: Decision{
Utterance: "сколько времени", Stage: 0, Intent: IntentSystem,
Confidence: 1.0, Slots: Slots{Text: "сколько времени"},
},
want: claim.BandAnchored,
},
{
name: "the llm path is structural",
dec: Decision{
Utterance: "выпил воды", Stage: 1, Intent: IntentFact,
Confidence: llmFullConfidence,
Slots: Slots{Key: "water", Value: "1", HasKey: true, Text: "выпил воды"},
},
want: claim.BandStructural,
},
{
name: "the classifier is nearest",
dec: Decision{
Utterance: "что нового", Stage: 2, Intent: IntentQuery,
Confidence: 0.91, Slots: Slots{Text: "что нового"},
},
want: claim.BandNearest,
},
{
name: "a structural hole vetoes whoever found it",
dec: Decision{
Utterance: "запиши", Stage: 1, Intent: IntentFact,
Confidence: llmThinConfidence, Slots: Slots{Text: "запиши"},
},
want: claim.BandVetoed,
},
{
name: "clarify vetoes a classifier decision",
dec: Decision{
Utterance: "сделай это", Stage: 3, Intent: IntentNote,
Confidence: 0.2, Clarify: true, Slots: Slots{Text: "сделай это"},
},
want: claim.BandVetoed,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := ClaimOf("test", tc.dec)
if got.Band != tc.want {
t.Errorf("band = %v, want %v (veto %q)", got.Band, tc.want, got.Veto)
}
})
}
}
// The veto has to name the hole. Folding all three arms into llmThinConfidence
// is what lost the reason, and 0.3 tells a reader that something was wrong but
// never which thing.
func TestClaimOfVetoNamesTheHole(t *testing.T) {
cases := []struct {
name string
dec Decision
want string
}{
{"keyless fact", Decision{Intent: IntentFact}, "fact with no key"},
{"act with no fn", Decision{Intent: IntentAct}, "act with no allowlisted fn"},
{"subjectless reminder", Decision{Intent: IntentReminder, Slots: Slots{Text: "напомни"}}, "reminder with no subject"},
{"below the gate", Decision{Intent: IntentQuery, Clarify: true}, "below the confidence gate"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := ClaimOf("test", tc.dec)
if !got.Vetoed() {
t.Fatalf("no veto, want one about %q", tc.want)
}
if len(got.Veto) < len(tc.want) || got.Veto[:len(tc.want)] != tc.want {
t.Errorf("veto = %q, want it to start with %q", got.Veto, tc.want)
}
})
}
}
// A route with every slot filled must NOT be vetoed. The three arms are
// structural holes, not a tax on every decision.
func TestClaimOfCompleteRouteIsNotVetoed(t *testing.T) {
d := Decision{
Utterance: "напомни позвонить маме в семь", Stage: 1, Intent: IntentReminder,
Confidence: llmFullConfidence,
Slots: Slots{Text: "позвонить маме", Time: time.Now(), HasTime: true},
}
c := ClaimOf("llm", d)
if c.Vetoed() {
t.Errorf("complete reminder vetoed: %q", c.Veto)
}
if c.Band != claim.BandStructural {
t.Errorf("band = %v, want structural", c.Band)
}
}
func TestClaimOfCoverageAndFilledSlots(t *testing.T) {
d := Decision{
Utterance: "напомни позвонить маме", Stage: 0, Intent: IntentReminder,
Confidence: 1.0, Slots: Slots{Text: "позвонить маме"},
}
c := ClaimOf("reminder-wakeword", d)
// The grammar captures what follows the verb, so "напомни" itself is
// unexplained. Under-reporting is the safe direction.
if len(c.Consumed) != 2 || len(c.Unexplained) != 1 {
t.Errorf("consumed %q / unexplained %q, want 2 and 1", c.Consumed, c.Unexplained)
}
if got := c.Coverage(); got < 0.66 || got > 0.67 {
t.Errorf("coverage = %v, want about 2/3", got)
}
if c.Intent != string(IntentReminder) {
t.Errorf("intent = %q", c.Intent)
}
if len(c.Filled) != 1 || c.Filled[0] != "text" {
t.Errorf("filled = %q, want [text]", c.Filled)
}
if c.Claimant != "reminder-wakeword" {
t.Errorf("claimant = %q", c.Claimant)
}
}
// The point of V-565's "additive" constraint, asserted rather than trusted:
// building a claim reads a Decision and changes nothing about it, so the
// classifier floor and the two consumers of Confidence are untouched.
func TestClaimOfLeavesTheDecisionAlone(t *testing.T) {
r := New(Config{
Grammars: []Grammar{ReminderGrammar()},
Extractor: Extractor{},
Threshold: 0.55,
})
before, err := r.Route(context.Background(), "напомни полить цветы", time.Now())
if err != nil {
t.Fatalf("Route: %v", err)
}
after := before
_ = ClaimOf("reminder-wakeword", after)
if !reflect.DeepEqual(after, before) {
t.Errorf("ClaimOf mutated the decision: %+v vs %+v", after, before)
}
if before.Confidence != 1.0 {
t.Errorf("stage 0 confidence = %v, want 1.0 — the float still has to work", before.Confidence)
}
}
+7
View File
@@ -49,6 +49,13 @@ try:
text = re.sub(r'(\d+)\s+(?:час(?:а|ов)?\s+)?вечера\b', r'\1 pm', text, flags=re.IGNORECASE)
text = re.sub(r'(\d+)\s+(?:час(?:а|ов)?\s+)?дня\b', r'\1 pm', text, flags=re.IGNORECASE)
text = re.sub(r'(\d+)\s+(?:час(?:а|ов)?\s+)?ночи\b', r'\1 am', text, flags=re.IGNORECASE)
# A bare hour after a preposition is dropped on the floor by dateparser:
# "завтра в 7" resolves to tomorrow at the CURRENT clock, and "завтра в 7
# часов" is read as seven hours from now. Only a qualifier (already an
# am/pm above) or a colon makes it read the hour, so give it the colon.
# English "at 7" fails identically, so both prepositions are rewritten.
text = re.sub(r'(?<![\w:])(в|во|at)\s+([01]?\d|2[0-3])(?:\s+час(?:а|ов)?)?(?![\d:.\w])',
lambda m: '%s %02d:00' % (m.group(1), int(m.group(2))), text, flags=re.IGNORECASE)
settings = {'PREFER_DATES_FROM': 'future', 'RELATIVE_BASE': now}
# Two-step: search_dates finds the date substring in text,
# parse() gets the time right (search_dates mishandles AM/PM).
+47
View File
@@ -103,6 +103,53 @@ func TestPythonDateParser(t *testing.T) {
}
},
},
// A bare hour after a day word used to be dropped, and the current
// clock carried onto that day: at 21:12 "завтра в семь" confirmed a
// reminder for 21:12 tomorrow (Vikunja #551). She invented a time
// instead of asking, on a path that then fires.
{
name: "ru bare hour — завтра в семь",
text: "напомни мне завтра в семь позвонить маме",
wantOK: true,
checkT: func(t *testing.T, got, now time.Time) {
if got.Hour() != 7 || got.Minute() != 0 {
t.Errorf("завтра в семь: %02d:%02d, want 07:00", got.Hour(), got.Minute())
}
},
},
{
// "7 часов" was read as seven hours from now, which also moved the day.
name: "ru bare hour — завтра в 7 часов",
text: "напомни завтра в 7 часов позвонить",
wantOK: true,
checkT: func(t *testing.T, got, now time.Time) {
if got.Hour() != 7 || got.Minute() != 0 {
t.Errorf("завтра в 7 часов: %02d:%02d, want 07:00", got.Hour(), got.Minute())
}
},
},
{
name: "en bare hour — tomorrow at 7",
text: "remind me tomorrow at 7 to call mum",
wantOK: true,
checkT: func(t *testing.T, got, now time.Time) {
if got.Hour() != 7 || got.Minute() != 0 {
t.Errorf("tomorrow at 7: %02d:%02d, want 07:00", got.Hour(), got.Minute())
}
},
},
{
// The rewrite must not touch a duration: "через 2 часа" is not "в 2".
name: "ru duration is untouched — через 2 часа",
text: "напомни через 2 часа выпить воды",
wantOK: true,
checkT: func(t *testing.T, got, now time.Time) {
d := got.Sub(now)
if d < 110*time.Minute || d > 130*time.Minute {
t.Errorf("через 2 часа: got %v from now, want ~2h", d)
}
},
},
{
name: "no date — напомни мне",
text: "напомни мне",
+83
View File
@@ -0,0 +1,83 @@
// router/decisiontrace.go — what the cascade tells the per-turn decision record.
//
// The cascade's arbitration is order (V-558): the first grammar whose Build
// agrees wins, and the model and the classifier are only reached because nobody
// upstream did. None of that is visible afterwards, so V-564 has each stage say
// its piece into the record riding the context. Nothing here reads the record
// back and nothing here can change a route — a nil recorder is the normal case
// in the fixture runner and every router test.
package router
import (
"context"
"github.com/kami/maven/internal/decision"
)
// The two routing engines, named as claimants. They are one stage and not two,
// because only one of them ever runs: the classifier is reached when the model
// is absent or errored, never alongside it.
const (
claimantLLM = "llm-router"
claimantClassifier = "classifier"
)
// thinReason names which arm of gateLLMDecision cut the confidence. The gate
// has three structural holes and they are three different defects, so "thinned"
// alone is not enough to act on.
func thinReason(d *Decision) string {
switch {
case d.Intent == IntentFact && !d.Slots.HasKey:
return "a fact with no key even after the parser tried"
case d.Intent == IntentAct && !d.Slots.HasFn:
return "an act that never resolved to an allowlisted fn"
case d.Intent == IntentReminder && !reminderHasSubject(d.Slots.Text):
return "a reminder with no subject to say at the hour"
default:
return "below the clarify threshold"
}
}
// Reasons a stage-0 grammar did not take a turn. Kept apart because they are
// different defects: a pattern that never matched is a rule that does not know
// the shape, a Build that declined is a rule that knew the shape and refused
// the content (narrative-query and the wakeword acts do this by design), and a
// grammar after the winner was never consulted at all.
const (
reasonNoMatch = "pattern did not match"
reasonBuildDeclmn = "matched the shape, Build declined the content"
reasonEarlierClaim = "an earlier grammar claimed the turn"
)
// noteGrammarOutcomes records the stage-0 pass. examined is how many grammars
// were reached; declined holds the names whose Build said no; won is the winner
// or empty. Everything past the winner is named as never asked, because that
// silence is the thing the hardcoded order hides.
func (r *Router) noteGrammarOutcomes(ctx context.Context, examined int, declined map[int]bool, won string, intent Intent) {
rec := decision.From(ctx)
if rec == nil {
return
}
for i, g := range r.grammars {
switch {
case i >= examined:
rec.Note(decision.Claim{
Stage: decision.StageZero, Claimant: g.Name,
Outcome: decision.NeverAsked, Reason: reasonEarlierClaim,
})
case g.Name == won:
rec.Note(decision.Scored(decision.StageZero, g.Name, string(intent), 1.0,
decision.Won, ""))
case declined[i]:
rec.Note(decision.Claim{
Stage: decision.StageZero, Claimant: g.Name,
Outcome: decision.Declined, Reason: reasonBuildDeclmn,
})
default:
rec.Note(decision.Claim{
Stage: decision.StageZero, Claimant: g.Name,
Outcome: decision.Declined, Reason: reasonNoMatch,
})
}
}
}
+230
View File
@@ -0,0 +1,230 @@
package eval
import (
"context"
"fmt"
"os"
"path/filepath"
"sort"
"testing"
"github.com/kami/maven/internal/router"
)
// Package-level note for V-565. The cascade's arbitration is list order, and
// the reason is that no two claimants report a comparable number. These tests
// measure what each claimant actually reports across the 91-case RU fixture,
// so the ordinal band set in docs/plans/19-dialogue-arbitration.md is argued
// from a distribution rather than from taste. They report and never assert:
// a ratchet here would freeze a number nobody has decided to hold yet.
// TestStage0Contention — how often more than one stage-0 grammar matches the
// same utterance. Every one of them reports Confidence 1.0, so where two
// match, list order is the entire decision and nothing in the Decision says a
// second rule wanted the turn.
func TestStage0Contention(t *testing.T) {
f, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
grammars := baselineGrammars(router.DefaultActMatcher{Fns: actFns})
t.Logf("stage 0: %d grammars over %d cases", len(grammars), len(f.Cases))
matched, contended := 0, 0
pairs := map[string]int{}
for _, c := range f.Cases {
claimants := matchingGrammars(grammars, c.Utterance)
if len(claimants) == 0 {
continue
}
matched++
if len(claimants) < 2 {
continue
}
contended++
t.Logf(" contended %s %q: %v (winner %q by order)", c.ID, c.Utterance, claimants, claimants[0])
for _, loser := range claimants[1:] {
pairs[claimants[0]+" beats "+loser]++
}
}
t.Logf("stage 0 claimed %d/%d cases, %d of those with more than one claimant", matched, len(f.Cases), contended)
for _, k := range sortedKeys(pairs) {
t.Logf(" %s ×%d", k, pairs[k])
}
}
// matchingGrammars — every grammar whose pattern matches AND whose Build
// accepts, in the daemon's order. Route stops at the first; this does not.
func matchingGrammars(grammars []router.Grammar, utterance string) []string {
stripped, hadWake := router.StripWakeToken(utterance)
var out []string
for _, g := range grammars {
m := g.Pattern.FindStringSubmatch(utterance)
if m == nil && hadWake {
m = g.Pattern.FindStringSubmatch(stripped)
}
if m == nil {
continue
}
if _, ok := g.Build(m); !ok {
continue
}
out = append(out, g.Name)
}
return out
}
// TestClaimConfidenceDistributionHash — the confidence each claimant reports,
// on the deterministic hash embedder so it runs anywhere. The ONNX run below
// is the one whose cosines are the deployed numbers.
func TestClaimConfidenceDistributionHash(t *testing.T) {
reportConfidences(t, "hash", router.NewHashEmbedder(1024))
}
// TestONNXClaimConfidenceDistribution — the same measurement on the embedder
// homesrv runs, so the cosine column is the real one. Opt-in via
// MAVEN_ONNX_LIB, same as TestONNXBaseline, and one TestONNX* per process.
func TestONNXClaimConfidenceDistribution(t *testing.T) {
lib := os.Getenv("MAVEN_ONNX_LIB")
if lib == "" {
t.Skip("MAVEN_ONNX_LIB unset — see AGENTS.md § Embedder model for intent routing")
}
model := filepath.Join("../../..", "models/embedder/multilingual-e5-small/model_quantized.onnx")
tok := filepath.Join("../../..", "models/embedder/multilingual-e5-small/tokenizer.json")
for _, p := range []string{lib, model, tok} {
if _, err := os.Stat(p); err != nil {
t.Skipf("missing %s: %v", p, err)
}
}
emb, err := router.NewONNXEmbedder(model, tok, lib)
if err != nil {
t.Skipf("onnx embedder unavailable: %v", err)
}
defer emb.Close()
reportConfidences(t, "onnx", emb)
}
// reportConfidences runs the fixture through the deployed cascade and buckets
// the reported confidence by which layer produced it, then reports how well
// each bucket predicts a correct route. A band is only worth defining if the
// accuracy inside it differs from the accuracy outside it.
func reportConfidences(t *testing.T, name string, emb router.Embedder) {
t.Helper()
f, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
now, err := f.Now()
if err != nil {
t.Fatalf("Now: %v", err)
}
r := newBaselineRouter(t, emb, nil)
cls := newBaselineClassifier(t, emb)
type bucket struct{ n, correct int }
byValue := map[string]*bucket{}
byMargin := map[string]*bucket{}
var cosines, margins []float64
for _, c := range f.Cases {
d, err := r.Route(context.Background(), c.Utterance, now)
if err != nil {
t.Fatalf("%s: %v", c.ID, err)
}
layer := "classifier"
if d.Stage == 0 {
layer = "stage0"
} else {
cosines = append(cosines, d.Confidence)
}
key := fmt.Sprintf("%s conf=%.2f", layer, d.Confidence)
if layer == "classifier" {
key = fmt.Sprintf("%s conf=%.1f..%.1f", layer, floorTo(d.Confidence, 0.1), floorTo(d.Confidence, 0.1)+0.1)
}
b := byValue[key]
if b == nil {
b = &bucket{}
byValue[key] = b
}
ok := routeCorrect(c, d)
b.n++
if ok {
b.correct++
}
// The margin between the classifier's top two intents is the other
// float one could call a confidence. Measured on the same cases, so
// the ledger's "is a calibrated float available cheaply" question
// gets an answer instead of an assumption.
if layer != "classifier" {
continue
}
res, err := cls.Classify(context.Background(), c.Utterance)
if err != nil || len(res) < 2 {
continue
}
margin := res[0].Score - res[1].Score
margins = append(margins, margin)
mk := fmt.Sprintf("margin %.2f..%.2f", floorTo(margin, 0.02), floorTo(margin, 0.02)+0.02)
mb := byMargin[mk]
if mb == nil {
mb = &bucket{}
byMargin[mk] = mb
}
mb.n++
if ok {
mb.correct++
}
}
t.Logf("%s: confidence buckets over %d cases (correct = right intent, or clarified when the fixture wants a refusal)", name, len(f.Cases))
for _, k := range sortedKeys2(byValue) {
b := byValue[k]
t.Logf(" %-32s n=%2d correct=%2d (%.0f%%)", k, b.n, b.correct, 100*float64(b.correct)/float64(b.n))
}
if len(cosines) > 0 {
sort.Float64s(cosines)
t.Logf(" classifier cosine spread: min %.3f p25 %.3f p50 %.3f p75 %.3f max %.3f",
cosines[0], cosines[len(cosines)/4], cosines[len(cosines)/2],
cosines[3*len(cosines)/4], cosines[len(cosines)-1])
}
if len(margins) > 0 {
sort.Float64s(margins)
t.Logf(" classifier top1-top2 margin: min %.3f p50 %.3f max %.3f",
margins[0], margins[len(margins)/2], margins[len(margins)-1])
for _, k := range sortedKeys2(byMargin) {
b := byMargin[k]
t.Logf(" %-32s n=%2d correct=%2d (%.0f%%)", k, b.n, b.correct, 100*float64(b.correct)/float64(b.n))
}
}
}
// routeCorrect — the intent contract only. Slots are a parser question and
// would blur what the confidence number is being asked to predict.
func routeCorrect(c Case, d router.Decision) bool {
if c.WantClarify {
return d.Clarify
}
return d.Intent == c.Intent && !d.Clarify
}
func floorTo(v, step float64) float64 {
return float64(int(v/step)) * step
}
func sortedKeys(m map[string]int) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
sort.Strings(out)
return out
}
func sortedKeys2[T any](m map[string]T) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
sort.Strings(out)
return out
}
+32 -13
View File
@@ -216,6 +216,27 @@ func TestONNXBaseline(t *testing.T) {
func newBaselineRouter(t *testing.T, emb router.Embedder, llmR *router.LLMRouter) *router.Router {
t.Helper()
acts := router.DefaultActMatcher{Fns: actFns}
cls := newBaselineClassifier(t, emb)
return router.New(router.Config{
Grammars: baselineGrammars(acts),
Classifier: cls,
Extractor: router.Extractor{
Time: router.StubDateTimeParser{},
Acts: acts,
Facts: router.DefaultFactParser{},
},
// The deployed gate, not a test-local one: a fixture scored at a looser
// threshold reports an accuracy no real turn would see.
Threshold: config.DefaultRouterThreshold,
LLM: llmR,
})
}
// newBaselineClassifier — the seeded nearest-centroid classifier the cascade
// runs. Split out of newBaselineRouter so the claim measurement can ask it for
// its full ranking, not just the winner the Decision carries.
func newBaselineClassifier(t *testing.T, emb router.Embedder) *router.Classifier {
t.Helper()
cls := router.NewClassifier(emb)
ctx := context.Background()
seeds := seedsWithIntent(t)
@@ -231,6 +252,15 @@ func newBaselineRouter(t *testing.T, emb router.Embedder, llmR *router.LLMRouter
t.Fatalf("seed %q: %v", text, err)
}
}
return cls
}
// baselineGrammars — the stage-0 rule set in the daemon's order (buildRouter in
// cmd/mavend/voicewire.go). Split out of newBaselineRouter so the claim
// measurement can run the same rules one at a time and see which of them
// contend for the same utterance, which the cascade hides by stopping at the
// first match.
func baselineGrammars(acts router.ActMatcher) []router.Grammar {
grammars := router.DefaultGrammars(acts)
grammars = append(grammars, router.SystemTimeDateGrammars()...)
// Same order as buildRouter (voicewire.go). The fixture is only worth
@@ -243,23 +273,12 @@ func newBaselineRouter(t *testing.T, emb router.Embedder, llmR *router.LLMRouter
grammars = append(grammars, router.ListGrammars()...)
grammars = append(grammars, router.ReminderGrammar())
grammars = append(grammars, router.PraxisGrammars()...)
grammars = append(grammars, router.TaskStatusGrammar())
grammars = append(grammars, router.TaskCaptureGrammar())
// "расскажи про X" is a world question the model called a fact, and the
// rule goes last because it matches on the first word alone (Vikunja #498).
grammars = append(grammars, router.NarrativeQueryGrammars()...)
return router.New(router.Config{
Grammars: grammars,
Classifier: cls,
Extractor: router.Extractor{
Time: router.StubDateTimeParser{},
Acts: acts,
Facts: router.DefaultFactParser{},
},
// The deployed gate, not a test-local one: a fixture scored at a looser
// threshold reports an accuracy no real turn would see.
Threshold: config.DefaultRouterThreshold,
LLM: llmR,
})
return grammars
}
// seedOrder — fixed iteration order over the corpus. Not cosmetic: a few
+78
View File
@@ -112,6 +112,84 @@ func TestLLMRouterBaseline(t *testing.T) {
}
}
// TestReachWithLLMRouter — the reach fixture scored with the resident model as
// router (Vikunja #517). V-405 measured the classifier only, and the LLM router
// is the deployed default, so 16/30 with praxis 0/12 is the floor rather than
// the shipped behaviour.
//
// The question is specific. The route grammar lets the model write any string
// into the fn slot, so it *could* emit a literal Praxis capability name and
// reach a service the classifier structurally cannot. If it does, V-516's
// stage-0 Praxis grammars are a determinism argument. If it does not, they are
// the only path.
//
// Same gate and same two configurations as TestLLMRouterBaseline, for the same
// reason: "the LLM router" alone and the cascade that actually ships answer
// different questions.
func TestReachWithLLMRouter(t *testing.T) {
base := os.Getenv("MAVEN_LLM_URL")
if base == "" {
t.Skip("MAVEN_LLM_URL unset — start llama-server and point it here (see doc comment)")
}
noProxyLoopback(t)
f, err := LoadReach()
if err != nil {
t.Fatalf("LoadReach: %v", err)
}
client := llm.New(base, 60*time.Second)
if err := ping(context.Background(), client); err != nil {
t.Skipf("llama-server at %s unreachable: %v", base, err)
}
ctx := context.Background()
model, err := llm.ModelID(ctx, base)
if err != nil {
t.Logf("could not read model id from %s: %v — reports will say %q", base, err, llm.UnknownModel)
model = llm.UnknownModel
}
t.Logf("scoring reach with model %s at %s", model, base)
lr := router.NewLLMRouter(client)
m := router.DefaultActMatcher{Fns: actFns}
llmOnly := RouterFunc(func(ctx context.Context, u string, now time.Time) (router.Decision, error) {
d, ok, err := lr.Route(ctx, u, now)
if err != nil {
return d, err
}
if !ok {
return d, fmt.Errorf("llm router declined without an error")
}
return d, nil
})
repLLM, err := ScoreReach(ctx, "reach: llm-only ("+model+")", llmOnly, m, f)
if err != nil {
t.Fatalf("ScoreReach llm-only: %v", err)
}
t.Log("\n" + repLLM.String() + repLLM.Failures())
// Hash embedder for the classifier floor, so any lift is the model's and
// not the embedder's — the same control TestLLMRouterBaseline uses.
repCascade, err := ScoreReach(ctx, "reach: cascade+llm ("+model+") + hash fallback",
newBaselineRouter(t, router.NewHashEmbedder(1024), lr), m, f)
if err != nil {
t.Fatalf("ScoreReach cascade: %v", err)
}
t.Log("\n" + repCascade.String() + repCascade.Failures())
for _, rep := range []ReachReport{repLLM, repCascade} {
if rep.Errors == rep.Total {
t.Errorf("%s: all %d cases errored — harness fault, not a measurement", rep.Name, rep.Total)
}
}
// Overreach is the one direction worth failing on, for the reason
// TestReachBaselineHash gives: he never gets asked about it.
if repCascade.Overreach > 4 {
t.Errorf("%d utterances reached a service they should not have, want <= 4:\n%s",
repCascade.Overreach, repCascade.Failures())
}
}
func ping(ctx context.Context, c *llm.Client) error {
ctx, cancel := context.WithTimeout(ctx, 90*time.Second)
defer cancel()
+5 -1
View File
@@ -70,6 +70,8 @@
{ "id": "ru-act-004", "utterance": "включи вытяжку", "lang": "ru", "intent": "act", "want_fn": true },
{ "id": "ru-act-005", "utterance": "запусти бэкап сейчас", "lang": "ru", "intent": "act", "want_fn": true },
{ "id": "ru-act-006", "utterance": "закрой жалюзи", "lang": "ru", "intent": "act", "want_fn": true },
{ "id": "ru-act-020", "utterance": "закрой задачу купить молоко", "lang": "ru", "intent": "act", "want_fn": true, "tags": ["task", "status"], "note": "a spoken status change over the board. Routed act with no allowlisted fn until V-512, so the gate asked \"Что сделать?\"; TaskStatusGrammar fills the fn slot with task_status and actionAct answers it from Maven's own store" },
{ "id": "ru-act-021", "utterance": "убери из задач оплатить интернет", "lang": "ru", "intent": "act", "want_fn": true, "tags": ["task", "status"], "note": "the drop half of the same rule. Dropped work he chose to stop is not work he did, so the two status sets are separate lexicons" },
{ "id": "en-act-001", "utterance": "maven, restart the media server", "lang": "en", "intent": "act", "want_fn": true, "tags": ["wake-token"] },
{ "id": "en-act-002", "utterance": "turn off the kitchen light", "lang": "en", "intent": "act", "want_fn": true },
@@ -102,6 +104,8 @@
{ "id": "amb-003", "utterance": "ну это", "lang": "ru", "want_clarify": true, "tags": ["ambiguous", "filler"] },
{ "id": "amb-004", "utterance": "сделай это", "lang": "ru", "want_clarify": true, "tags": ["ambiguous", "anaphora"], "note": "unresolved anaphora with an imperative — must not guess an fn" },
{ "id": "amb-005", "utterance": "потом", "lang": "ru", "want_clarify": true, "tags": ["ambiguous", "filler"] },
{ "id": "amb-006", "utterance": "the thing from earlier", "lang": "en", "want_clarify": true, "tags": ["ambiguous", "anaphora"] }
{ "id": "amb-006", "utterance": "the thing from earlier", "lang": "en", "want_clarify": true, "tags": ["ambiguous", "anaphora"] },
{ "id": "amb-007", "utterance": "напомни", "lang": "ru", "want_clarify": true, "tags": ["ambiguous", "reminder"], "note": "the reminder verb and nothing else — she knows the shape of the request and not one thing about it. Answered 'не получилось разобрать время напоминания' on the box until V-548: the subjectless-reminder gate tested Slots.Text == \"\", and fillSlots had put the verb in that slot" },
{ "id": "amb-008", "utterance": "ну напомни же", "lang": "ru", "want_clarify": true, "tags": ["ambiguous", "reminder", "filler"], "note": "the same request wrapped in particles, which is why filler_particles is a lexicon set — without it the particles read as the subject" }
]
}
+17 -4
View File
@@ -5,10 +5,16 @@ import "strings"
// Feed queries — "что нового в лентах?", "что нового по технологиям?"
// (Vikunja #258).
//
// Deterministic matching, like the calendar, plan and habit matchers above it:
// the LLM router says this is a query, and this decides whether it is a question
// about the feeds. A model deciding that would occasionally answer "что нового?"
// out of world knowledge, which is the one thing a feed reader exists to avoid.
// This file is the OFFLINE FLOOR as of 05-08-2026 (V-522). Whether a turn is
// about the feeds is a question about meaning, so the frozen seeds decide it —
// topicFeed in cmd/mavend/topics.go, through turnIsAbout. The word lists below
// stay because they always answer: a box with no embedder, a turn whose vector
// never got computed, and any call that does not clear topicMargin. They are
// allowed to stay narrow now that they are not the only answer.
//
// What has not changed is that no generative model decides this. One would
// occasionally answer "что нового?" out of world knowledge, which is the one
// thing a feed reader exists to avoid.
// FeedQuery — a parsed "what's new" question. Category is the topic he named
// ("технологии"), empty when he asked about the feeds in general.
@@ -95,6 +101,13 @@ func ParseFeedQuery(text string) (FeedQuery, bool) {
// cannot be mistaken for anything else.
var categoryPreps = map[string]bool{"по": true, "об": true, "про": true, "about": true, "on": true}
// FeedCategoryOf reads the topic out of an utterance without deciding whether the
// turn is a feed question at all. The seeds answer that now (topicFeed in
// cmd/mavend/topics.go, V-522), and they answer it for phrasings the word lists
// here never held — but a claimed turn still needs its category, and a category
// is marked by a preposition rather than recognised.
func FeedCategoryOf(text string) string { return feedCategory(planTokens(text)) }
func feedCategory(toks []string) string {
for i, t := range toks {
if categoryPreps[t] && i+1 < len(toks) {
+4 -8
View File
@@ -24,13 +24,9 @@ import (
// had one and added when it did not, because the stub scans for "в" before a
// clock and the contracted "полвосьмого" carries no preposition at all.
// halfWords — the forms of "половина" a spoken time uses. "в половине",
// "половина", "к половине", "полвосьмого". Closed and tiny; the ordinal beside
// them is what carries the hour, and that comes from the lexicon.
var halfWords = map[string]bool{
"половина": true, "половине": true, "половину": true, "половины": true,
"пол": true, "half": true,
}
// The forms of "половина" a spoken time uses are a closed class and live in the
// lexicon as half_hour, because the ordinal-selection turn has to decline the
// same ordinal this file reads (V-522). Ask lexicon.IsHalfHour.
// minutesTo — the words that name the minutes in a "без X" hour. "четверти" is
// the only one that is not a number; the rest are cardinals and are read as
@@ -74,7 +70,7 @@ func halfPastAt(toks []string, i int) (hour, width int, ok bool) {
return h, 1, true
}
}
if !halfWords[head] || i+1 >= len(toks) {
if !lexicon.IsHalfHour(head) || i+1 >= len(toks) {
return 0, 0, false
}
h, ok := enteredHour(cleanWord(toks[i+1]))
+34
View File
@@ -17,6 +17,15 @@ import (
// The markers are deliberately explicit. "молоко закончилось" is an
// observation about the world and belongs in a note; only an instruction to
// put something on a list puts it there.
//
// The four paths split on 05-08-2026, and the split is by what the caller needs
// rather than by language (V-522). Reading a list back needs one bit — is this
// about the list — so the seeds decide it, topicList through turnIsAbout, and
// listQueryPrefixes below is the offline floor. The other three keep the tables
// as the answer. Add and remove need to know WHERE the item starts, and a
// cosine over a whole utterance does not say which byte the milk begins at.
// Clear DELETES the list, so it stays on exact phrases: a false claim there
// loses rows he cannot get back, which is not the trade a margin makes.
// listTags — the lists he can name, as one dictionary form each. Russian
// declines the tag ("список покупок", "в покупки", "в покупках"), and the
@@ -186,6 +195,31 @@ func ParseListQuery(text string) (string, bool) {
return list, true
}
// ListNamedIn reports which standing list an utterance names, anywhere in it,
// defaulting to покупки when it names none.
//
// takeListTag is not enough for a read-back, because it reads the FRONT of a
// remainder a prefix table has already eaten. The seeds claim a read-back
// without eating anything (topicList, cmd/mavend/topics.go, V-522), so "что мне
// нужно в аптеке" has to be scanned rather than trimmed. A list name is a noun
// in the dictionary, so this is a lookup and decides nothing about meaning.
func ListNamedIn(text string) string {
for _, f := range strings.Fields(strings.ToLower(text)) {
head := strings.Trim(f, listTrimCut)
for _, s := range listTags {
if morph.SameWord(head, s.word) {
return s.list
}
}
for _, s := range listTagsEN {
if head == s.word {
return s.list
}
}
}
return "покупки"
}
// ParseListClear reports whether an utterance crosses off a whole list.
func ParseListClear(text string) (string, bool) {
lower := strings.ToLower(strings.Trim(strings.TrimSpace(text), listTrimCut))
+18
View File
@@ -26,6 +26,24 @@ var (
captureVerbs = lexicon.CaptureVerbs()
)
// CarriesCaptureVerb reports whether text tells Maven to write something down.
// Sibling of IsQuestionShaped and matched over the same tokens, and the two do
// not overlap: IsQuestionShaped returns false for anything this returns true
// for, because "запиши что я пил воду" is a capture and not a question.
//
// Both exist together so a caller can ask "is this its own request?" — a
// clarify answer that asks a question or orders a capture is not an answer
// (Vikunja #554).
func CarriesCaptureVerb(text string) bool {
toks := planTokens(strings.TrimSpace(text))
for _, v := range captureVerbs {
if hasTok(toks, v) {
return true
}
}
return false
}
// IsQuestionShaped reports whether text asks for something rather than
// records it. It is a deterministic offline test over tokens, so it costs
// nothing and never depends on the model that produced the routing decision.
+62
View File
@@ -0,0 +1,62 @@
package router
import (
"strings"
"github.com/kami/maven/internal/lexicon"
"github.com/kami/maven/internal/morph"
)
// A reminder needs something to say at the hour, and the gate that checks for
// one was reading a slot that is never empty.
//
// gateLLMDecision has asked about a subjectless reminder since V-383, on the
// test `d.Slots.Text == ""`. Measured on the box on 05-08-2026: "напомни" alone
// routes to IntentReminder with `Text:напомни`, because fillSlots hands the text
// slot the utterance when the model names nothing narrower. So the slot was
// never empty, the gate never fired, and the turn reached actionReminder and
// answered "не получилось разобрать время напоминания." — a parse error for a
// request she never finished asking about. "ну напомни же" did the same.
//
// The fix is to ask what the text slot CONTAINS rather than whether it is set.
// Two closed classes answer that and no third mechanism is needed: the reminder
// verbs are her own vocabulary (lexicon.ReminderVerbs), and the particles and
// politeness words cannot be the subject of anything (lexicon.IsFillerParticle).
// A verb is matched by lemma through morph.SameWord, so "напоминай" and
// "напомнить" need no entry of their own.
//
// Deliberately NOT reusing cmd/mavend/reminderbody.go, which strips the same
// marker: that function also strips the time words, so "напомни завтра" would
// read as subjectless there. Asking is right when he named no subject, and wrong
// when he named a day — the reminder for tomorrow is the one whose subject she
// should ask about, not one she should treat as noise.
// reminderHasSubject reports whether a reminder's text names anything to say at
// the hour. False for "напомни", "напомни мне", "ну напомни же"; true for
// "напомни позвонить маме" and for "напомни завтра", where the day is a subject
// she can ask nothing better about.
func reminderHasSubject(text string) bool {
for _, f := range strings.Fields(strings.ToLower(text)) {
w := strings.Trim(f, " ,.;:!?—-«»\"'()")
if w == "" || lexicon.IsFillerParticle(w) {
continue
}
if isReminderVerb(w) {
continue
}
return true
}
return false
}
// isReminderVerb matches one of her reminder imperatives by lemma. Lemma and not
// prefix: "напоминание" is a noun he can perfectly well ask to be reminded
// about, and a stem test would eat it.
func isReminderVerb(word string) bool {
for _, v := range lexicon.ReminderVerbs() {
if word == v || morph.SameWord(word, v) {
return true
}
}
return false
}
+40
View File
@@ -0,0 +1,40 @@
package router
import "testing"
func TestReminderHasSubject(t *testing.T) {
cases := []struct {
text string
want bool
}{
// The three the box produced, and the reason this file exists.
{"напомни", false},
{"ну напомни же", false},
{"напомни мне", false},
{"напомни мне пожалуйста", false},
// Lemma, not literal: none of these forms is the one in the utterance
// the lexicon lists first.
{"напоминай", false},
{"напомнить", false},
{"remind me", false},
{"remind me please", false},
// A real subject, however short.
{"напомни позвонить маме", true},
{"напомни про таблетки", true},
{"напомни выпить воды", true},
{"remind me to call mom", true},
// A day is a subject she can ask nothing better about, so she does not
// ask. This is where reminderBody's stripping would disagree, on purpose.
{"напомни завтра", true},
{"напомни в семь", true},
// A noun that starts like the verb. A stem test would eat it.
{"напомни про напоминание", true},
// Empty is subjectless without asking the lexicon anything.
{"", false},
}
for _, c := range cases {
if got := reminderHasSubject(c.text); got != c.want {
t.Errorf("reminderHasSubject(%q) = %v, want %v", c.text, got, c.want)
}
}
}
+101 -7
View File
@@ -5,6 +5,8 @@ import (
"errors"
"log"
"time"
"github.com/kami/maven/internal/decision"
)
// Config — wires the cascade. Build via New; a zero-value Router is unusable.
@@ -67,7 +69,11 @@ func (r *Router) Route(ctx context.Context, utterance string, now time.Time) (De
// the STT often includes one (transcribed phonetically, any script) — try
// the wake-stripped utterance too so those grammars still fire.
stripped, hadWake := StripWakeToken(utterance)
for _, g := range r.grammars {
// declinedBuild — the grammars that matched the shape and refused the
// content, kept for the decision record (V-564) so a reader can tell that
// rule from one whose pattern never fired.
var declinedBuild map[int]bool
for i, g := range r.grammars {
m := g.Pattern.FindStringSubmatch(utterance)
if m == nil && hadWake {
m = g.Pattern.FindStringSubmatch(stripped)
@@ -77,11 +83,20 @@ func (r *Router) Route(ctx context.Context, utterance string, now time.Time) (De
}
d, ok := g.Build(m)
if !ok {
if declinedBuild == nil {
declinedBuild = map[int]bool{}
}
declinedBuild[i] = true
continue // grammar matched shape but not content → fall through
}
d.Utterance = utterance
// The grammar decided the intent; the extractor fills the slots it did
// not match (V-572). See fillMatchedSlots for why every grammar gets it.
r.fillMatchedSlots(ctx, &d, now)
r.noteGrammarOutcomes(ctx, i+1, declinedBuild, g.Name, d.Intent)
return d, nil
}
r.noteGrammarOutcomes(ctx, len(r.grammars), declinedBuild, "", "")
// stage 1a — LLM router (when wired). It reasons over the utterance instead
// of nearest-centroid guessing. On any error/parse-fail, fall through to the
@@ -90,11 +105,38 @@ func (r *Router) Route(ctx context.Context, utterance string, now time.Time) (De
if d, ok, err := r.llm.Route(ctx, utterance, now); err == nil && ok {
d.Utterance = utterance
r.fillSlots(ctx, &d, now)
before := d.Confidence
r.gateLLMDecision(&d)
// The classifier is the floor and it never ran, which is the whole
// reason a wrong LLM route reads as unexplainable (V-564).
decision.Note(ctx, decision.Claim{
Stage: decision.StageRoute, Claimant: claimantClassifier,
Outcome: decision.NeverAsked, Reason: "the LLM router answered",
})
outcome, reason := decision.Won, ""
if d.Confidence < before {
outcome, reason = decision.Thinned, thinReason(&d)
}
decision.Note(ctx, decision.Scored(decision.StageRoute, claimantLLM,
string(d.Intent), d.Confidence, outcome, reason))
return d, nil
} else if err != nil {
log.Printf("router: llm route fell back to classifier: %v", err)
decision.Note(ctx, decision.Claim{
Stage: decision.StageRoute, Claimant: claimantLLM,
Outcome: decision.Declined, Reason: "error: " + err.Error(),
})
} else {
decision.Note(ctx, decision.Claim{
Stage: decision.StageRoute, Claimant: claimantLLM,
Outcome: decision.Declined, Reason: "no parsable route in the reply",
})
}
} else {
decision.Note(ctx, decision.Claim{
Stage: decision.StageRoute, Claimant: claimantLLM,
Outcome: decision.NeverAsked, Reason: "no LLM router is wired",
})
}
// stage 1 — intent classifier.
@@ -103,6 +145,16 @@ func (r *Router) Route(ctx context.Context, utterance string, now time.Time) (De
return Decision{}, err
}
best := results[0]
// The runners-up are the interesting part: two intents a hundredth apart is
// a different defect from one that won outright (V-564). Two are enough to
// see that, and the rest of a seven-intent scoreboard is noise on the page.
if rec := decision.From(ctx); rec != nil {
for _, res := range results[1:min(len(results), 3)] {
rec.Note(decision.Scored(decision.StageRoute, claimantClassifier,
string(res.Intent), res.Score, decision.LostOnScore,
"lower similarity than "+string(best.Intent)))
}
}
// stage 2 — slot extraction for the winning intent.
d := Decision{
@@ -118,17 +170,46 @@ func (r *Router) Route(ctx context.Context, utterance string, now time.Time) (De
d.Stage = 3
d.Clarify = true
}
outcome, reason := decision.Won, ""
if d.Clarify {
outcome, reason = decision.Thinned, "below the clarify threshold, so she asks instead"
}
decision.Note(ctx, decision.Scored(decision.StageRoute, claimantClassifier,
string(d.Intent), d.Confidence, outcome, reason))
return d, nil
}
// fillSlots — run stage-2 extraction on an LLM decision and fill only the slots
// the model left empty. The LLM wins where it answered: it saw the sentence, the
// parsers are keyword tables. Extraction covers what the model cannot produce at
// all — a parsed reminder time and an allowlist fn.
// fillMatchedSlots — run stage-2 extraction over a decision some earlier
// claimant produced, and fill only the slots that claimant left empty. A
// matched value always wins: the claimant read the sentence, the extractor
// guesses from keyword tables.
//
// Shared by the stage-0 grammars and the LLM router, which had the same hole
// for the same reason. A grammar asserts an intent at confidence 1.0 and says
// nothing about the slots, so "напомни в 11:00 позвонить маме" arrived with
// HasTime false however plainly the hour was spoken, and the daemon read the
// silence as absence and asked "Когда?" (V-572). The alternative was ten
// grammars each re-implementing extraction.
//
// It is applied to every stage-0 decision rather than to a chosen few, because
// for every intent but reminder it is inert: Extract fills Time for a reminder,
// Fn for an act and Key for a fact, and nothing at all for query, system, note
// or chat, which is what the query, clock, agenda, feed, list, task and
// narrative rules emit. The act rules — wakeword-act and the Praxis ones —
// already carry an Fn or they do not match, so there is nothing left for the
// matcher to fill. The reminder rule is the one that gains, and its time parse
// is a cost the daemon was already paying one layer down in actionReminder.
//
// Slots.Text is deliberately NOT filled here. Extract sets it to the raw
// utterance, and a grammar that left it empty meant it: agendaQueryBuild hands
// the query chain the utterance itself, and narrativeQueryBuild's Text is the
// topic, not the sentence.
//
// If a reminder still has no time, leave it missing. The daemon then says it
// could not read the time; inventing one would set a wrong alarm.
func (r *Router) fillSlots(ctx context.Context, d *Decision, now time.Time) {
// Returns what the extractor read, so a caller that wants more of it does not
// pay for a second extraction — the reminder parser is the expensive one.
func (r *Router) fillMatchedSlots(ctx context.Context, d *Decision, now time.Time) Slots {
ex := r.extractor.Extract(ctx, d.Intent, d.Utterance, now)
if !d.Slots.HasTime && ex.HasTime {
d.Slots.Time, d.Slots.HasTime = ex.Time, ex.HasTime
@@ -139,6 +220,14 @@ func (r *Router) fillSlots(ctx context.Context, d *Decision, now time.Time) {
if !d.Slots.HasFn && ex.HasFn {
d.Slots.Fn, d.Slots.Args, d.Slots.HasFn = ex.Fn, ex.Args, ex.HasFn
}
return ex
}
// fillSlots — fillMatchedSlots for an LLM decision, plus the two backfills that
// only make sense there. The LLM wins where it answered: it saw the sentence,
// the parsers are keyword tables.
func (r *Router) fillSlots(ctx context.Context, d *Decision, now time.Time) {
ex := r.fillMatchedSlots(ctx, d, now)
// For an act the model returns the verb in Text ("restart nginx"), which is
// often cleaner than the raw utterance ("maven, could you restart nginx").
// Try it too when the utterance did not match the allowlist.
@@ -189,7 +278,12 @@ func (r *Router) gateLLMDecision(d *Decision) {
// A reminder with no subject: she knows when but not what to say then.
// Setting it anyway fires an empty reminder at the hour, which reads as a
// bug to him and cannot be repaired after the fact. Ask (Vikunja #383).
if d.Intent == IntentReminder && d.Slots.Text == "" && d.Confidence > llmThinConfidence {
//
// The test is what the text slot CONTAINS, not whether it is set. It was the
// latter until 05-08-2026, and the slot is never empty: fillSlots hands it
// the utterance, so "напомни" arrived here with Text:напомни and the gate
// never fired (V-457). See remindersubject.go.
if d.Intent == IntentReminder && !reminderHasSubject(d.Slots.Text) && d.Confidence > llmThinConfidence {
d.Confidence = llmThinConfidence
}
if d.Confidence < r.threshold {
+67
View File
@@ -121,6 +121,73 @@ func TestStage0GrammarFiresThroughCyrillicWakeWord(t *testing.T) {
}
}
// TestStage0ReminderCarriesTheHourHeSaid — "напомни в 11:00 позвонить маме" is
// the commonest reminder there is, and it used to reach the daemon with HasTime
// false, because ReminderGrammar builds its slots by hand and the router ran no
// extraction over a stage-0 decision. The daemon read the silence as absence and
// asked "Когда?" about an hour he had just said (V-572).
func TestStage0ReminderCarriesTheHourHeSaid(t *testing.T) {
r := newTestRouter(t, 0.0)
r.grammars = append(r.grammars, ReminderGrammar())
d, err := r.Route(context.Background(), "напомни в 11:00 позвонить маме", refNow())
if err != nil {
t.Fatalf("route: %v", err)
}
if d.Stage != 0 || d.Intent != IntentReminder {
t.Fatalf("want stage0 reminder, got %+v", d)
}
if !d.Slots.HasTime {
t.Fatalf("the hour was spoken, so the slot must be filled: %+v", d.Slots)
}
if got, want := d.Slots.Time.Format("15:04"), "11:00"; got != want {
t.Errorf("fire time = %s, want %s", got, want)
}
// The subject is the grammar's, not the extractor's: Slots.Text is what she
// says at the hour, and Extract would have overwritten it with the sentence.
if d.Slots.Text != "в 11:00 позвонить маме" {
t.Errorf("Text = %q, want the grammar's capture", d.Slots.Text)
}
}
// TestStage0MatchedSlotBeatsTheExtractor — a grammar that matched a literal
// pattern outranks a parser that guessed. The wake-word act names its fn from
// the remainder after the wake token; extraction over the raw utterance must not
// be able to replace it.
func TestStage0MatchedSlotBeatsTheExtractor(t *testing.T) {
r := newTestRouter(t, 0.0)
d, err := r.Route(context.Background(), "maven, restart nginx", refNow())
if err != nil {
t.Fatalf("route: %v", err)
}
if d.Slots.Fn != "restart" || len(d.Slots.Args) != 1 || d.Slots.Args[0] != "nginx" {
t.Fatalf("matched fn was overwritten: %+v", d.Slots)
}
if d.Slots.Text != "restart nginx" {
t.Errorf("Text = %q, want the grammar's remainder", d.Slots.Text)
}
}
// TestStage0QueryKeepsAnEmptyText — agendaQueryBuild deliberately leaves Text
// empty so the query chain reads the utterance itself. Extraction fills Time,
// Key and Fn and never Text, or every stage-0 query would start carrying the
// whole sentence in a slot that means something narrower.
func TestStage0QueryKeepsAnEmptyText(t *testing.T) {
r := newTestRouter(t, 0.0)
r.grammars = append(r.grammars, AgendaQueryGrammars()...)
d, err := r.Route(context.Background(), "что у меня сегодня", refNow())
if err != nil {
t.Fatalf("route: %v", err)
}
if d.Stage != 0 || d.Intent != IntentQuery {
t.Fatalf("want stage0 query, got %+v", d)
}
if d.Slots.Text != "" {
t.Errorf("Text = %q, want it left empty", d.Slots.Text)
}
}
// ----------------------------- stage 1 ---------------------------------------
func TestStage1ClassifiesAct(t *testing.T) {
+6 -5
View File
@@ -88,11 +88,12 @@ func DefaultGrammars(actMatcher ActMatcher) []Grammar {
// non-reminder time queries toward it, and the verb+action overlap pushes
// actual reminders toward fact — a double contamination. Stage 0 fixes both.
//
// The grammar captures the part after "напомни"/"remind me" into Slots.Text
// so the daemon's time parser can extract the fire time from it. The grammar
// itself does NOT parse time — that's the extractor's job (stage 2), but
// stage 0 skips the extractor. The daemon's applyAction fallback calls the
// time parser for stage-0 reminders that arrive without HasTime.
// The grammar captures the part after "напомни"/"remind me" into Slots.Text
// what she says at the hour. The grammar itself does NOT parse time; that is
// the extractor's job, and since V-572 the router runs the extractor over a
// 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.
func ReminderGrammar() Grammar {
return Grammar{
Name: "reminder-wakeword",
+178
View File
@@ -0,0 +1,178 @@
package router
import (
"regexp"
"strings"
"github.com/kami/maven/internal/lexicon"
"github.com/kami/maven/internal/morph"
"github.com/kami/maven/internal/store"
)
// A spoken status change over the task list (Vikunja #512, step 4 of
// docs/plans/15-board-surface.md).
//
// Capture and the list read were built; moving a task was only possible in the
// two turns after she read one out, through resolveCandidate — "первую сделал"
// against the bound list. Naming the task instead of its position reached
// nothing: "закрой задачу купить молоко" routed act, found no allowlisted fn,
// and the gate asked "Что сделать?".
//
// Same shape TaskCaptureGrammar uses, for the same reason: no eighth intent, so
// the grammar matches broadly and a deterministic parser inside Build decides.
// The task's own warning applies — every such grammar runs its parser ahead of
// the resident model on every turn, so this is the last one that is free.
//
// TaskStatusFn is the fn slot the daemon dispatches on. Not a Hexis capability
// and not a Praxis one: the board is Maven's own store, so actionAct intercepts
// this name before either ecosystem client sees it.
const TaskStatusFn = "task_status"
// TaskStatus — a parsed status change. Status is a store task status, and Text
// is the task he named, empty when he named none ("закрой задачу"), which is a
// turn the daemon claims and answers by asking which.
type TaskStatus struct {
Status string
Text string
}
// taskStatusNouns — the noun that makes this a board turn rather than ordinary
// speech. Required, and it is the whole reason this rule is safe to run on every
// utterance: "готово" alone is him reporting his day, "убери" alone is a request
// about the room, and neither names the list.
//
// "дело" is deliberately absent. "в чём дело" and "дело в том" are ordinary
// speech, and "список дел" is already a list query.
var taskStatusNouns = []string{"task", "tasks", "todo", "todos"}
// taskStatusFillers — the words to ignore when what is left over is the task he
// named. Prepositions and the possessive, because "убери из моих задач купить
// молоко" names the same task as "убери задачу купить молоко".
var taskStatusFillers = []string{"из", "в", "во", "с", "со", "мои", "моих", "моё", "мой", "моя", "мою", "my", "the", "from", "off", "as", "как"}
// ParseTaskStatus reads a status change over the board: which transition, and
// which task.
//
// Three conditions, all required. A task noun, so no ordinary sentence claims
// the turn. Exactly one status class, because "готово, убери" names two and
// asking beats picking. And a status word that is either an imperative in the
// exact form he said it or a stative by lemma — the trap quiet_toggle.go
// documents, where "закрой" and "закрыл" are one lemma and only one is a
// command.
func ParseTaskStatus(text string) (TaskStatus, bool) {
toks := praxisTokens(strings.ToLower(strings.TrimSpace(text)))
if len(toks) == 0 || !taskStatusNamesBoard(toks) {
return TaskStatus{}, false
}
status := ""
for _, c := range []struct {
status string
words []string
}{
{store.TaskDone, lexicon.TaskDoneWords()},
{store.TaskDropped, lexicon.TaskDropWords()},
} {
if !taskStatusHasWord(toks, c.words) {
continue
}
if status != "" {
// Two transitions in one sentence. They are different rows on the
// page, so this declines and the cascade answers.
return TaskStatus{}, false
}
status = c.status
}
if status == "" {
return TaskStatus{}, false
}
return TaskStatus{Status: status, Text: taskStatusReferent(toks)}, true
}
// taskStatusNamesBoard reports whether the sentence names the task list. The
// Russian noun is matched by lemma, because a noun means the same thing in every
// case and he says "из задач", "задачу", "задача" for one list.
func taskStatusNamesBoard(toks []string) bool {
for _, t := range toks {
if morph.SameWord(t, "задача") {
return true
}
for _, n := range taskStatusNouns {
if t == n {
return true
}
}
}
return false
}
// taskStatusHasWord matches a status word the way its set's note requires: an
// imperative exactly, a stative by lemma. It cannot tell the two columns apart
// from the data, so it tries the exact form first and then the lemma — which
// costs the imperative trap back, except that both columns of one set mean the
// SAME transition. "закрой" and "закрыл" are one lemma and, here, one status.
func taskStatusHasWord(toks, words []string) bool {
for _, t := range toks {
for _, w := range words {
if t == w || morph.SameWord(t, w) {
return true
}
}
}
return false
}
// taskStatusReferent is what is left after the status words, the board noun and
// the fillers: the task he named, or "" when he named none.
//
// Word order is kept, because the leftover is matched against stored task text
// and he says the task the way he first said it.
func taskStatusReferent(toks []string) string {
done, drop := lexicon.TaskDoneWords(), lexicon.TaskDropWords()
var out []string
for _, t := range toks {
switch {
case taskStatusHasWord([]string{t}, done), taskStatusHasWord([]string{t}, drop):
case morph.SameWord(t, "задача"), taskStatusIn(t, taskStatusNouns):
case taskStatusIn(t, taskStatusFillers), lexicon.IsFillerParticle(t):
default:
out = append(out, t)
}
}
return strings.Join(out, " ")
}
func taskStatusIn(tok string, words []string) bool {
for _, w := range words {
if tok == w {
return true
}
}
return false
}
// TaskStatusGrammar — stage 0 for a spoken status change. Wired after the Praxis
// rules and before the capture marker: Praxis claims a bare "закрой" and this
// rule requires the board noun, so the two cannot collide, and the capture
// marker must not read "убери из задач купить молоко" as a new task.
func TaskStatusGrammar() Grammar {
return Grammar{
Name: "task-status",
Pattern: regexp.MustCompile(`(?s)^\s*(.+)$`),
Build: func(m []string) (Decision, bool) {
c, ok := ParseTaskStatus(m[1])
if !ok {
return Decision{}, false
}
return Decision{
Stage: 0,
Intent: IntentAct,
Confidence: 1.0,
// Value carries the transition and Text the task he named,
// which is the pairing handlePraxisAct uses for an item and its
// reference. Empty Text is a claim, not a refusal: the daemon
// asks which task, having the list she does not.
Slots: Slots{Fn: TaskStatusFn, HasFn: true, Value: c.Status, Text: c.Text},
}, true
},
}
}
+68
View File
@@ -0,0 +1,68 @@
package router
import "testing"
func TestParseTaskStatus(t *testing.T) {
cases := []struct {
utterance string
ok bool
status string
text string
}{
// The shapes that reached nothing before this rule.
{"закрой задачу купить молоко", true, "done", "купить молоко"},
{"задачу купить молоко сделал", true, "done", "купить молоко"},
{"убери из задач купить молоко", true, "dropped", "купить молоко"},
{"убери из моих задач купить молоко", true, "dropped", "купить молоко"},
{"отмени задачу оплатить интернет", true, "dropped", "оплатить интернет"},
{"task buy milk done", true, "done", "buy milk"},
// The referent may be missing. The turn is still his, and the daemon has
// the list to ask about.
{"закрой задачу", true, "done", ""},
{"убери задачу", true, "dropped", ""},
// No board noun: ordinary speech, and every one of these means something
// else. "закрой" alone belongs to Praxis.
{"готово", false, "", ""},
{"закрой", false, "", ""},
{"убери со стола", false, "", ""},
{"я всё сделал", false, "", ""},
{"закрой шторы в комнате", false, "", ""},
// The board noun with no status word is a list query, not a move.
{"какие у меня задачи", false, "", ""},
{"добавь в задачи купить молоко", false, "", ""},
// Two transitions in one sentence. Asking beats picking.
{"задачу купить молоко готово убери", false, "", ""},
{"", false, "", ""},
}
for _, c := range cases {
got, ok := ParseTaskStatus(c.utterance)
if ok != c.ok {
t.Errorf("ParseTaskStatus(%q) ok = %v, want %v", c.utterance, ok, c.ok)
continue
}
if !ok {
continue
}
if got.Status != c.status || got.Text != c.text {
t.Errorf("ParseTaskStatus(%q) = %+v, want status %q text %q", c.utterance, got, c.status, c.text)
}
}
}
func TestTaskStatusGrammarFillsTheFnSlot(t *testing.T) {
g := TaskStatusGrammar()
m := g.Pattern.FindStringSubmatch("закрой задачу купить молоко")
if m == nil {
t.Fatal("pattern did not match")
}
dec, ok := g.Build(m)
if !ok {
t.Fatal("Build declined")
}
if dec.Intent != IntentAct || !dec.Slots.HasFn || dec.Slots.Fn != TaskStatusFn {
t.Fatalf("decision = %+v, want act with fn %q", dec, TaskStatusFn)
}
if dec.Slots.Value != "done" || dec.Slots.Text != "купить молоко" {
t.Fatalf("slots = %+v, want value done text \"купить молоко\"", dec.Slots)
}
}
+1 -1
View File
@@ -129,7 +129,7 @@ func buildTimeMarkers() map[string]bool {
m[w] = true
}
}
for w := range halfWords {
for _, w := range lexicon.HalfHourWords() {
m[w] = true
}
for w := range minutesTo {
+15
View File
@@ -36,6 +36,13 @@ const (
TasksFirst = "tasks_first"
TasksCandidates = "tasks_candidates"
// The counted stall shapes on /tasks and in the spoken list (V-512). Each
// one states a count and nothing about what it means: "лежит дольше десяти
// дней" is arithmetic, "стоит бросить" would be a judgement she may not make.
StallOverdue = "stall_overdue"
StallSitting = "stall_sitting"
StallUnconfirmed = "stall_unconfirmed"
ReasonOverdue = "reason_overdue"
ReasonOverdueDays = "reason_overdue_days"
ReasonToday = "reason_today"
@@ -64,6 +71,7 @@ const (
var summaryKeys = []string{
PlanRestEmpty, PlanDayEmpty, PlanDay, PlanUncertain,
TasksNone, TasksFirst, TasksCandidates,
StallOverdue, StallSitting, StallUnconfirmed,
ReasonOverdue, ReasonOverdueDays, ReasonToday, ReasonTomorrow,
ReasonInDays, ReasonImportant, ReasonUrgent, ReasonStale,
HabitWeekday, HabitWeekdaySame, HabitWeekdayNone,
@@ -86,6 +94,10 @@ var summaryFloor = map[string]string{
TasksFirst: "сначала: {items}",
TasksCandidates: "нашла ещё, но ты не подтверждал: {items}",
StallOverdue: "{n} {word} просрочено",
StallSitting: "{n} {word} лежит дольше {days} {dayword}",
StallUnconfirmed: "{n} {word} ждёт подтверждения",
ReasonOverdue: "просрочено",
ReasonOverdueDays: "просрочено на {n} {word}",
ReasonToday: "сегодня",
@@ -128,6 +140,9 @@ func LoadSummaries(src rand.Source) (*Summaries, error) {
{PlanDayEmpty, "{date}"}, {PlanDay, "{date}"}, {PlanDay, "{items}"},
{PlanUncertain, "{line}"},
{TasksFirst, "{items}"}, {TasksCandidates, "{items}"},
{StallOverdue, "{n}"}, {StallOverdue, "{word}"},
{StallSitting, "{n}"}, {StallSitting, "{days}"},
{StallUnconfirmed, "{n}"}, {StallUnconfirmed, "{word}"},
{ReasonOverdueDays, "{n}"}, {ReasonOverdueDays, "{word}"},
{ReasonInDays, "{n}"}, {ReasonInDays, "{word}"},
{HabitWeekday, "{day}"}, {HabitWeekday, "{items}"},
+13
View File
@@ -44,6 +44,19 @@
"variants": ["нашла ещё, но ты не подтверждал: {items}"]
},
"stall_overdue": {
"fixed": true,
"variants": ["{n} {word} просрочено"]
},
"stall_sitting": {
"fixed": true,
"variants": ["{n} {word} лежит дольше {days} {dayword}"]
},
"stall_unconfirmed": {
"fixed": true,
"variants": ["{n} {word} ждёт подтверждения"]
},
"reason_overdue": {
"fixed": true,
"variants": ["просрочено"]
+10
View File
@@ -290,6 +290,16 @@ ALTER TABLE reminders ADD COLUMN next_fire_ts INTEGER;`, // #2
ALTER TABLE nudges_new RENAME TO nudges;
CREATE INDEX IF NOT EXISTS idx_nudges_rule_ts ON nudges (rule, ts DESC);
CREATE INDEX IF NOT EXISTS idx_nudges_outcome ON nudges (outcome);`,
// #22 — the two columns that make tasks a work board rather than a to-do
// list (Vikunja #510). done_when is the acceptance criterion, and blocked_on
// is a canonical Nexus entity id: it names a person, identity lives in
// Nexus, and a local free-text name would be a second answer to a question
// Nexus already owns. Both default to empty rather than NULL, because "he
// has not written one" and "there is nothing to write" are the same state
// 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 '';`,
}
// migrate applies every migration with a number greater than the DB's current
+122 -6
View File
@@ -66,6 +66,16 @@ type Task struct {
Weight int
ResolvedTs *time.Time
ResolvedBy string
// DoneWhen — the acceptance criterion, in his words. It must be able to
// close on either outcome: "it already works" counts as complete, and a
// criterion only one result satisfies is a wish rather than a definition
// (Vikunja #510). Empty until he writes one.
DoneWhen string
// BlockedOn — a canonical Nexus entity id, never a name. Identity lives in
// Nexus, so storing "Саша" here would be a second answer to a question
// Nexus already owns. Empty when nothing blocks the task.
BlockedOn string
}
// CaptureResult — what CaptureTask did. Created is a new row. Promoted is an
@@ -82,6 +92,22 @@ var (
ErrTaskNotFound = errors.New("store: task not found")
ErrTaskEmpty = errors.New("store: task text is empty")
ErrTaskStatus = errors.New("store: invalid task status")
// ErrTaskNoDoneWhen — a candidate cannot be promoted to open without a
// definition of done (Vikunja #510). Same refusal ParseTaskCapture makes
// for a capture marker with nothing after it: confirming work whose
// finish line nobody wrote is how a board fills with rows that can never
// leave it. Dropping such a candidate stays legal.
ErrTaskNoDoneWhen = errors.New("store: task has no definition of done")
// ErrTaskDuplicate — an edit would give this task the normalised text of
// another live row (Vikunja #509). A refusal, not a merge: two live rows
// carry two provenances, two capture times and possibly two external
// identities, and merging picks a winner for all three silently. The
// surface tells the owner which row already holds the text and lets him
// drop one.
ErrTaskDuplicate = errors.New("store: another live task already has this text")
// ErrTaskResolved — a resolved task is not editable. Its text is the
// record of what was finished, and rewriting it rewrites history.
ErrTaskResolved = errors.New("store: task is resolved")
)
// liveTaskStatuses — the two statuses that count as outstanding work.
@@ -160,10 +186,10 @@ func (s *Store) CaptureTask(ctx context.Context, t Task) (CaptureResult, error)
// Untargeted DO NOTHING: either unique index may be the one that fires, and
// the lookup below sorts out which.
res, err := s.db.ExecContext(ctx,
`INSERT INTO tasks (created_ts, text, norm, source, evidence, ext_id, status, due_ts, weight)
VALUES (?,?,?,?,?,?,?,?,?)
`INSERT INTO tasks (created_ts, text, norm, source, evidence, ext_id, status, due_ts, weight, done_when, blocked_on)
VALUES (?,?,?,?,?,?,?,?,?,?,?)
ON CONFLICT DO NOTHING`,
created2.UnixMilli(), text, norm, t.Source, t.Evidence, ext, status, due, t.Weight)
created2.UnixMilli(), text, norm, t.Source, t.Evidence, ext, status, due, t.Weight, t.DoneWhen, t.BlockedOn)
if err != nil {
return CaptureResult{}, fmt.Errorf("capture task: %w", err)
}
@@ -194,7 +220,7 @@ func (s *Store) CaptureTask(ctx context.Context, t Task) (CaptureResult, error)
}
}
if status == TaskOpen && existing.Status == TaskCandidate {
if err := s.SetTaskStatus(ctx, existing.ID, TaskOpen, created2, t.Source); err != nil {
if err := s.setTaskStatus(ctx, existing.ID, TaskOpen, created2, t.Source, false); err != nil {
return CaptureResult{}, fmt.Errorf("capture task: promote candidate: %w", err)
}
return CaptureResult{ID: existing.ID, Promoted: true}, nil
@@ -231,7 +257,7 @@ func (s *Store) lookupLiveTaskByNorm(ctx context.Context, norm string) (Task, er
return t, nil
}
const taskSelect = `SELECT id, created_ts, text, source, evidence, COALESCE(ext_id,''), status, due_ts, weight, resolved_ts, resolved_by FROM tasks`
const taskSelect = `SELECT id, created_ts, text, source, evidence, COALESCE(ext_id,''), status, due_ts, weight, resolved_ts, resolved_by, done_when, blocked_on FROM tasks`
// LookupTask returns one task by id.
func (s *Store) LookupTask(ctx context.Context, id int64) (Task, error) {
@@ -304,6 +330,16 @@ func (s *Store) ListTasks(ctx context.Context, status string) ([]Task, error) {
// "tap:voice"). It is recorded on the row, so a task that turns up resolved
// says what resolved it.
func (s *Store) SetTaskStatus(ctx context.Context, id int64, status string, ts time.Time, by string) error {
return s.setTaskStatus(ctx, id, status, ts, by, true)
}
// setTaskStatus — the move, with the promotion gate optional.
//
// It is optional for exactly one caller: CaptureTask promoting a candidate he
// stated out loud (Vikunja #510). Refusing there would deny intake rather than
// ask for a criterion, and a direct open capture never had one either — the gate
// belongs to the deliberate promotion on /tasks, where there is a form to fill.
func (s *Store) setTaskStatus(ctx context.Context, id int64, status string, ts time.Time, by string, gateDoneWhen bool) error {
var from []string
switch status {
case TaskOpen:
@@ -329,6 +365,13 @@ func (s *Store) SetTaskStatus(ctx context.Context, id int64, status string, ts t
for _, f := range from {
args = append(args, f)
}
if status == TaskOpen && gateDoneWhen {
// Promotion needs an acceptance criterion. Checked in the same
// statement rather than read-then-write, so two callers confirming one
// candidate cannot race past it; the row is read afterwards only to say
// WHICH refusal this was.
q += ` AND done_when <> ''`
}
res, err := s.db.ExecContext(ctx, q, args...)
if err != nil {
return fmt.Errorf("set task status: %w", err)
@@ -338,11 +381,84 @@ func (s *Store) SetTaskStatus(ctx context.Context, id int64, status string, ts t
return fmt.Errorf("set task status: rows affected: %w", err)
}
if n == 0 {
if status == TaskOpen && gateDoneWhen {
if t, lookErr := s.LookupTask(ctx, id); lookErr == nil && t.Status == TaskCandidate && t.DoneWhen == "" {
return fmt.Errorf("%w: id=%d", ErrTaskNoDoneWhen, id)
}
}
return fmt.Errorf("%w: id=%d not in %v", ErrTaskNotFound, id, from)
}
return nil
}
// EditTask rewrites the three fields capture set and nothing else: text, due
// date and weight (Vikunja #509). Status stays the one-way ladder SetTaskStatus
// owns, and a resolved task is refused outright — its text is the record of
// what was finished.
//
// Editing text re-normalises the dedupe key, which can collide with another
// live row. That is ErrTaskDuplicate and it is a refusal: merging would pick
// one row's provenance, capture time and external identity over the other's
// with nobody asked.
//
// due nil clears the date. Clearing has to be sayable, so an absent date and
// "remove the date" cannot be the same argument.
func (s *Store) EditTask(ctx context.Context, id int64, text string, due *time.Time, weight int) error {
text = strings.TrimSpace(text)
if text == "" {
return ErrTaskEmpty
}
cur, err := s.LookupTask(ctx, id)
if err != nil {
return err
}
if cur.Status != TaskCandidate && cur.Status != TaskOpen {
return fmt.Errorf("%w: id=%d is %s", ErrTaskResolved, id, cur.Status)
}
norm := NormalizeTaskText(text)
if norm != NormalizeTaskText(cur.Text) {
if other, err := s.lookupLiveTaskByNorm(ctx, norm); err == nil && other.ID != id {
return fmt.Errorf("%w: id=%d holds it", ErrTaskDuplicate, other.ID)
} else if err != nil && !errors.Is(err, ErrTaskNotFound) {
return err
}
}
var dueVal sql.NullInt64
if due != nil {
dueVal = sql.NullInt64{Int64: due.UnixMilli(), Valid: true}
}
if _, err := s.db.ExecContext(ctx,
`UPDATE tasks SET text = ?, norm = ?, due_ts = ?, weight = ? WHERE id = ?`,
text, norm, dueVal, weight, id); err != nil {
return fmt.Errorf("edit task: %w", err)
}
return nil
}
// SetTaskFields writes the two board columns. Separate from SetTaskStatus
// because a status move is one-way and these are not: he may sharpen a
// definition of done, and a blocker clears when the person answers.
//
// blockedOn is a canonical Nexus entity id or empty. Free text does not belong
// here — identity lives in Nexus, and a local name would be a second answer to
// a question Nexus already owns. The caller resolves before it writes.
func (s *Store) SetTaskFields(ctx context.Context, id int64, doneWhen, blockedOn string) error {
res, err := s.db.ExecContext(ctx,
`UPDATE tasks SET done_when = ?, blocked_on = ? WHERE id = ?`,
strings.TrimSpace(doneWhen), strings.TrimSpace(blockedOn), id)
if err != nil {
return fmt.Errorf("set task fields: %w", err)
}
n, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("set task fields: rows affected: %w", err)
}
if n == 0 {
return fmt.Errorf("%w: id=%d", ErrTaskNotFound, id)
}
return nil
}
// NormalizeTaskText is the dedupe key: lowercased, punctuation dropped,
// whitespace collapsed. Exported because the intake seam (and its tests) needs
// to reason about what will and will not be treated as the same task.
@@ -372,7 +488,7 @@ func scanTask(sc scanner) (Task, error) {
var t Task
var created int64
var due, resolved sql.NullInt64
if err := sc.Scan(&t.ID, &created, &t.Text, &t.Source, &t.Evidence, &t.ExternalID, &t.Status, &due, &t.Weight, &resolved, &t.ResolvedBy); err != nil {
if err := sc.Scan(&t.ID, &created, &t.Text, &t.Source, &t.Evidence, &t.ExternalID, &t.Status, &due, &t.Weight, &resolved, &t.ResolvedBy, &t.DoneWhen, &t.BlockedOn); err != nil {
return Task{}, err
}
t.CreatedTs = time.UnixMilli(created).UTC()

Some files were not shown because too many files have changed in this diff Show More