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.
This commit is contained in:
+59
-38
@@ -175,58 +175,69 @@ 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.
|
||||
//
|
||||
// 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
|
||||
// understand. She never drops the request in silence.
|
||||
// isOwnRequest reports whether an utterance asks for something in its own
|
||||
// right, which is what a clarify answer never does. Two offline tests over
|
||||
// tokens, both already written for other callers: a question shape, and a
|
||||
// capture verb. Cheap on purpose — this runs on the answer to every parked
|
||||
// question, and it must not cost a model call.
|
||||
//
|
||||
// It is not a general relevance test. A bare noun that answers nothing ("синий"
|
||||
// after "Что сделать?") is still treated as an answer and still re-asked, and
|
||||
// that is the intended shape: only an utterance that carries its own request
|
||||
// wins over the question in front of it.
|
||||
func isOwnRequest(text string) bool {
|
||||
return router.IsQuestionShaped(text) || router.CarriesCaptureVerb(text)
|
||||
}
|
||||
// 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 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 {
|
||||
return "", false
|
||||
}
|
||||
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())
|
||||
merged := q.Answer(text, toDialogueSlots(answer))
|
||||
// He moved on. A parked question used to swallow whatever came next, so one
|
||||
// act she could not fulfil ate the following three turns: "выключи свет в
|
||||
// спальне" asked "Что сделать?", and "кто изобрёл телефон" was scored as an
|
||||
// answer to it, then "как дела" after that (Vikunja #554). Nothing checked
|
||||
// whether the words could be an answer at all.
|
||||
//
|
||||
// Deliberately narrow. It only fires where the answer filled nothing, so a
|
||||
// turn that closes the gap is still an answer whatever shape it has, and
|
||||
// the retry budget is untouched — the count was never the problem. Dropping
|
||||
// the question and routing the utterance as itself is what he meant either
|
||||
// way: if he really was answering, he can say it again, and if he was not,
|
||||
// he gets the thing he asked for instead of being asked a third time.
|
||||
if len(dialogue.StillMissing(q.Missing, merged)) > 0 && isOwnRequest(text) {
|
||||
|
||||
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))
|
||||
log.Printf("voice: clarify — %q is its own request, not an answer to %v; dropping the question", text, q.Missing)
|
||||
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
|
||||
// as the reminder payload — so a reminder clarified out of a bare "напомни"
|
||||
@@ -262,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
|
||||
|
||||
@@ -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...)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
+13
-16
@@ -268,6 +268,14 @@ func (h *reactiveHandler) runTurn(ctx context.Context, text string, src turnSour
|
||||
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
|
||||
@@ -298,6 +306,10 @@ func (h *reactiveHandler) runTurn(ctx context.Context, text string, src turnSour
|
||||
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
|
||||
@@ -343,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.
|
||||
|
||||
@@ -124,6 +124,16 @@ func TaskDoneWords() []string { return words("task_done_words") }
|
||||
// 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.
|
||||
|
||||
@@ -197,6 +197,26 @@
|
||||
"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"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user