Compare commits

...
Author SHA1 Message Date
m fc00a57942 Merge pull request 'Observe chat context route decisions' (#387) from codex/household-travel-query-fix into main
CI / test (push) Successful in 1m15s
Reviewed-on: #387
2026-08-25 20:30:19 +00:00
m 1b21888e8b Observe chat context route decisions
CI / test (push) Successful in 1m27s
CI / test (pull_request) Failing after 1m1s
2026-08-25 23:29:39 +03:00
m 012f5efafe Merge pull request 'Compile personal facts for contextual assistance' (#386) from codex/household-travel-query-fix into main
CI / test (push) Successful in 1m12s
Reviewed-on: #386
2026-08-25 19:51:47 +00:00
m eb842e24ff Compile personal facts for contextual assistance
CI / test (push) Successful in 1m15s
CI / test (pull_request) Failing after 50s
2026-08-25 22:50:37 +03:00
m 13bbcdf747 Preserve specialized research routes
CI / test (push) Successful in 1m19s
2026-08-25 22:46:20 +03:00
m c00b9b1549 Merge pull request 'Route plane requests through verified research' (#385) from codex/household-travel-query-fix into main
CI / test (push) Successful in 1m15s
Reviewed-on: #385
2026-08-25 19:42:26 +00:00
m 2d88d488f4 Route plane requests through verified research
CI / test (push) Successful in 1m34s
CI / test (pull_request) Failing after 58s
2026-08-25 22:42:03 +03:00
m 72c9cfc893 Merge pull request 'Validate flight research by route meaning' (#384) from codex/household-travel-query-fix into main
CI / test (push) Successful in 1m22s
Reviewed-on: #384
2026-08-25 19:35:41 +00:00
m 0b619bdc08 Validate flight research by route meaning
CI / test (push) Successful in 1m28s
CI / test (pull_request) Failing after 58s
2026-08-25 22:35:21 +03:00
m db23e984da Merge pull request 'Forward large generated images to chat' (#383) from codex/household-travel-query-fix into main
CI / test (push) Successful in 1m14s
Reviewed-on: #383
2026-08-25 19:31:17 +00:00
m f0c8f39986 Forward large generated images to chat
CI / test (push) Successful in 1m28s
CI / test (pull_request) Failing after 53s
2026-08-25 22:30:50 +03:00
m 5d8ec1995a Merge pull request 'Honor requested image quality' (#382) from codex/household-travel-query-fix into main
CI / test (push) Successful in 1m30s
Reviewed-on: #382
2026-08-25 19:14:21 +00:00
m 75d707e960 Honor requested image quality
CI / test (push) Successful in 1m22s
CI / test (pull_request) Successful in 1m25s
2026-08-25 22:12:44 +03:00
m 89b053b7bf Merge pull request 'Require assistant target for renaming' (#381) from codex/household-travel-query-fix into main
CI / test (push) Successful in 1m16s
Reviewed-on: #381
2026-08-25 18:32:39 +00:00
m e90aded6d3 Require assistant target for renaming
CI / test (push) Successful in 1m25s
CI / test (pull_request) Failing after 54s
2026-08-25 21:32:20 +03:00
m 8456ecd237 Merge pull request 'Continue ticket search with date follow-up' (#380) from codex/household-travel-query-fix into main
CI / test (push) Successful in 1m13s
Reviewed-on: #380
2026-08-25 18:21:30 +00:00
m b89fdef1d9 Merge remote-tracking branch 'origin/main' into codex/household-travel-query-fix
CI / test (push) Failing after 57s
CI / test (pull_request) Failing after 55s
2026-08-25 21:21:12 +03:00
m 6f3d576602 Continue ticket search with date follow-up
CI / test (push) Failing after 50s
CI / test (pull_request) Failing after 1m9s
2026-08-25 21:20:36 +03:00
m b026ec151e Merge pull request 'Preserve explicit memory confirmations' (#379) from codex/household-travel-query-fix into main
CI / test (push) Successful in 1m25s
Reviewed-on: #379
2026-08-25 18:16:05 +00:00
m 5d4c3877b1 Preserve explicit memory confirmations
CI / test (push) Successful in 1m14s
CI / test (pull_request) Successful in 1m26s
2026-08-25 21:13:26 +03:00
m 113c5ab965 Merge pull request 'Apply learned source aliases to research' (#378) from codex/household-travel-query-fix into main
CI / test (push) Successful in 1m14s
Reviewed-on: #378
2026-08-25 18:02:29 +00:00
m bce7993a6a Apply learned source aliases to research
CI / test (push) Successful in 1m30s
CI / test (pull_request) Failing after 52s
2026-08-25 21:02:07 +03:00
m 3bbf416c20 Merge pull request 'Explain missing research evidence' (#377) from codex/household-travel-query-fix into main
CI / test (push) Successful in 1m14s
Reviewed-on: #377
2026-08-25 17:56:42 +00:00
m b62b3b0dc3 Explain missing research evidence
CI / test (push) Failing after 59s
CI / test (pull_request) Failing after 1m2s
2026-08-25 20:56:21 +03:00
m 7e72474b0a Merge pull request 'Summarize verified internet connectivity' (#376) from codex/household-travel-query-fix into main
CI / test (push) Successful in 1m33s
Reviewed-on: #376
2026-08-25 17:53:22 +00:00
m b05081328e Recognize network connection wording
CI / test (push) Failing after 1m1s
CI / test (pull_request) Failing after 50s
2026-08-25 20:53:00 +03:00
m 0e7d1a7a50 Summarize verified internet connectivity
CI / test (push) Failing after 58s
2026-08-25 20:52:41 +03:00
m 2aaa73bb2a Merge pull request 'Describe local Domovoy capabilities' (#375) from codex/household-travel-query-fix into main
CI / test (push) Successful in 1m13s
Reviewed-on: #375
2026-08-25 17:50:03 +00:00
m 9000d90d72 Describe local Domovoy capabilities
CI / test (push) Successful in 1m29s
CI / test (pull_request) Failing after 1m0s
2026-08-25 20:49:39 +03:00
m 4afcfd3846 Merge pull request 'Recognize self capability questions' (#374) from codex/household-travel-query-fix into main
CI / test (push) Successful in 1m19s
Reviewed-on: #374
2026-08-25 16:54:32 +00:00
m 6ba8265686 Recognize self capability questions
CI / test (push) Failing after 58s
CI / test (pull_request) Failing after 54s
2026-08-25 19:54:06 +03:00
m 21583528c0 Merge pull request 'Explain current cognitive response route' (#373) from codex/household-travel-query-fix into main
CI / test (push) Successful in 1m18s
Reviewed-on: #373
2026-08-25 16:51:27 +00:00
m b1bb48f5b5 Explain current cognitive response route
CI / test (push) Successful in 1m40s
CI / test (pull_request) Failing after 54s
2026-08-25 19:51:03 +03:00
m 88f5f6e8f8 Merge pull request 'Recognize named model inventory requests' (#372) from codex/household-travel-query-fix into main
CI / test (push) Successful in 1m16s
Reviewed-on: #372
2026-08-25 16:48:12 +00:00
m 5439db2cc3 Recognize named model inventory requests
CI / test (push) Successful in 1m14s
CI / test (pull_request) Failing after 54s
2026-08-25 19:47:25 +03:00
m 208cb18ee0 Merge pull request 'Preserve latest travel context' (#371) from codex/household-travel-query-fix into main
CI / test (push) Successful in 1m32s
Reviewed-on: #371
2026-08-25 16:43:43 +00:00
m 5d19becdaf Preserve latest travel context
CI / test (push) Successful in 1m10s
CI / test (pull_request) Successful in 1m14s
2026-08-25 19:36:49 +03:00
m 4cd3ecdf15 Merge pull request 'Normalize contextual travel research' (#370) from codex/household-travel-query-fix into main
CI / test (push) Successful in 1m13s
Reviewed-on: #370
2026-08-25 16:29:58 +00:00
m 8e26f529f7 Merge remote-tracking branch 'origin/codex/household-travel-query-fix' into codex/household-travel-query-fix
CI / test (push) Failing after 1m3s
CI / test (pull_request) Failing after 54s
2026-08-25 19:28:11 +03:00
m 3cc636d6b7 Normalize contextual travel research 2026-08-25 19:27:59 +03:00
m 14dc439c82 Merge pull request 'Improve semantic travel research queries' (#369) from codex/household-travel-query-fix into main
CI / test (push) Successful in 1m14s
Reviewed-on: #369
2026-08-25 16:26:24 +00:00
m 21887988b2 Merge branch 'main' into codex/household-travel-query-fix
CI / test (push) Failing after 57s
CI / test (pull_request) Failing after 54s
2026-08-25 16:25:54 +00:00
m 232a57eed4 Improve semantic travel research queries
CI / test (push) Failing after 53s
CI / test (pull_request) Failing after 54s
2026-08-25 19:25:00 +03:00
m d1fd70e436 Merge pull request 'Preserve location context for travel follow-ups' (#368) from codex/household-travel-context-fix into main
CI / test (push) Successful in 1m30s
Reviewed-on: #368
2026-08-25 16:22:04 +00:00
m 1d73162df1 Merge remote-tracking branch 'origin/main' into codex/household-travel-context-fix
CI / test (push) Successful in 1m14s
CI / test (pull_request) Successful in 1m24s
2026-08-25 19:17:59 +03:00
m 7788cf4b44 Preserve location context for travel follow-ups
CI / test (push) Failing after 58s
CI / test (pull_request) Failing after 50s
2026-08-25 19:17:34 +03:00
m d9dcddbdbb Merge pull request 'Preserve direct time difference replies' (#367) from codex/household-time-reply-priority into main
CI / test (push) Successful in 2m3s
Reviewed-on: #367
2026-08-25 16:11:36 +00:00
18 changed files with 727 additions and 97 deletions
+37 -1
View File
@@ -2,6 +2,7 @@ package main
import ( import (
"encoding/json" "encoding/json"
"fmt"
"io" "io"
"log" "log"
"net/http" "net/http"
@@ -38,7 +39,8 @@ func (g multimodalGateway) handler(operation capability.MultimodalOperation) htt
http.Error(w, "local image generation capability unavailable", http.StatusBadGateway) http.Error(w, "local image generation capability unavailable", http.StatusBadGateway)
return return
} }
image, err := g.imageGenerator.Generate(r.Context(), g.imageModel, r.FormValue("prompt"), r.FormValue("size")) prompt := r.FormValue("prompt")
image, err := g.imageGenerator.Generate(r.Context(), g.imageModel, prompt, imageRequestSize(prompt, r.FormValue("size")))
if err != nil || strings.TrimSpace(image.DataBase64) == "" { if err != nil || strings.TrimSpace(image.DataBase64) == "" {
logMultimodalFailure(operation, err) logMultimodalFailure(operation, err)
http.Error(w, "local image generation capability unavailable", http.StatusBadGateway) http.Error(w, "local image generation capability unavailable", http.StatusBadGateway)
@@ -96,6 +98,40 @@ func (g multimodalGateway) handler(operation capability.MultimodalOperation) htt
} }
} }
// imageRequestSize is a transport-level normalization for the local image
// capability. An explicit, valid size always wins. When the caller only
// expresses a conventional output-quality target, the capability translates it
// to a supported provider size without exposing provider workflow details to
// the interaction core. This policy is deliberately local and replaceable
// with the image capability implementation.
func imageRequestSize(prompt, requested string) string {
if isImageSize(requested) {
return strings.TrimSpace(requested)
}
words := strings.Fields(strings.ToLower(prompt))
for index, word := range words {
switch word {
case "4k", "uhd":
return "2048x2048"
case "hd":
return "1024x1024"
case "ultra":
if index+1 < len(words) && words[index+1] == "hd" {
return "2048x2048"
}
}
}
return ""
}
func isImageSize(value string) bool {
var width, height int
if _, err := fmt.Sscanf(strings.TrimSpace(value), "%dx%d", &width, &height); err != nil {
return false
}
return width >= 256 && height >= 256 && width <= 2048 && height <= 2048
}
func logMultimodalFailure(operation capability.MultimodalOperation, err error) { func logMultimodalFailure(operation capability.MultimodalOperation, err error) {
// Keep provider details in server diagnostics; never return them to chat. // Keep provider details in server diagnostics; never return them to chat.
log.Printf("multimodal operation %s failed: %v", operation, err) log.Printf("multimodal operation %s failed: %v", operation, err)
+21
View File
@@ -47,6 +47,27 @@ func TestMultimodalImageGenerationFailsClosedWhenSkillIsUnbound(t *testing.T) {
} }
} }
func TestImageRequestSizeUsesExplicitSizeOrQualityTarget(t *testing.T) {
for _, test := range []struct {
name string
prompt string
requested string
want string
}{
{name: "explicit", prompt: "нарисуй птицу", requested: "768x512", want: "768x512"},
{name: "hd", prompt: "нарисуй птицу в HD", want: "1024x1024"},
{name: "uhd", prompt: "draw a bird in UHD", want: "2048x2048"},
{name: "ordinary", prompt: "нарисуй птицу", want: ""},
{name: "invalid explicit", prompt: "нарисуй птицу", requested: "100x100", want: ""},
} {
t.Run(test.name, func(t *testing.T) {
if got := imageRequestSize(test.prompt, test.requested); got != test.want {
t.Fatalf("imageRequestSize(%q, %q) = %q, want %q", test.prompt, test.requested, got, test.want)
}
})
}
}
func TestMultimodalVideoUnderstandingFailsClosedWhenSkillIsUnbound(t *testing.T) { func TestMultimodalVideoUnderstandingFailsClosedWhenSkillIsUnbound(t *testing.T) {
server := multimodalGateway{now: time.Now} server := multimodalGateway{now: time.Now}
request := multipartRequest(t, "/v1/multimodal/video-understand", "clip.mp4", []byte("video")) request := multipartRequest(t, "/v1/multimodal/video-understand", "clip.mp4", []byte("video"))
+8
View File
@@ -72,3 +72,11 @@ func hasChatRoute(routes []chatRoute, kind chatRouteKind) bool {
} }
return false return false
} }
// specializedRouteBypassesGeneralInterpretation keeps a concrete capability
// route stable. General cognition may still be used later to assess evidence,
// but it must not replace an executable research or media route with a vague
// conversational clarification before the capability is attempted.
func specializedRouteBypassesGeneralInterpretation(routes []chatRoute) bool {
return hasChatRoute(routes, chatRouteMedia) || hasChatRoute(routes, chatRouteResearch)
}
@@ -39,3 +39,15 @@ func TestBuildChatRoutePlanAlwaysKeepsLocalConversationRoute(t *testing.T) {
t.Fatalf("unexpected local route: %+v", planned) t.Fatalf("unexpected local route: %+v", planned)
} }
} }
func TestSpecializedRouteBypassesGeneralInterpretation(t *testing.T) {
if !specializedRouteBypassesGeneralInterpretation([]chatRoute{{Kind: chatRouteResearch}}) {
t.Fatal("research route must execute before general cognition")
}
if !specializedRouteBypassesGeneralInterpretation([]chatRoute{{Kind: chatRouteMedia}}) {
t.Fatal("media route must execute before general cognition")
}
if specializedRouteBypassesGeneralInterpretation([]chatRoute{{Kind: chatRouteConversation}}) {
t.Fatal("conversation-only route must retain general cognition")
}
}
+6 -2
View File
@@ -31,19 +31,23 @@ type cognitiveInterpretationClient struct {
// ReviewResponse asks the cognitive gateway to turn a locally assembled draft // ReviewResponse asks the cognitive gateway to turn a locally assembled draft
// into a natural answer. The draft remains the safe fallback when cognition is // into a natural answer. The draft remains the safe fallback when cognition is
// unavailable; the model does not mutate canonical state or execute actions. // unavailable; the model does not mutate canonical state or execute actions.
func (c cognitiveInterpretationClient) ReviewResponse(ctx context.Context, session identity.CreatorSession, userMessage, draft string, meaning cognitive.TaskMeaning) (string, error) { func (c cognitiveInterpretationClient) ReviewResponse(ctx context.Context, session identity.CreatorSession, userMessage, draft, personalMemory string, meaning cognitive.TaskMeaning) (string, error) {
requestID, err := ids.New() requestID, err := ids.New()
if err != nil { if err != nil {
return "", err return "", err
} }
prompt := "Ты редактор ответа Домового. Проверь черновик по смыслу и подготовь естественный ответ человеку. Учитывай весь запрос, включая недостающие параметры для конкретного результата. Если данных не хватает, задай один короткий полезный уточняющий вопрос, например откуда и куда ехать. Не выдавай поисковые сниппеты как выполненное действие и не показывай служебные URL поисковой выдачи. Сохрани проверяемые факты, названия источников, прямые ссылки и ограничения. Не выдумывай факты и не утверждай невыполненные действия. Верни только готовый ответ без разбора проверки, служебных слов и упоминания моделей. Если черновик уже адекватен, верни его без лишних добавлений.\n\nСообщение пользователя:\n" + userMessage + "\n\nЧерновик ответа:\n" + draft prompt := "Ты редактор ответа Домового. Проверь черновик по смыслу и подготовь естественный ответ человеку. Учитывай весь запрос, включая недостающие параметры для конкретного результата. Если данных не хватает, задай один короткий полезный уточняющий вопрос, например откуда и куда ехать. Не выдавай поисковые сниппеты как выполненное действие и не показывай служебные URL поисковой выдачи. Сохрани проверяемые факты, названия источников, прямые ссылки и ограничения. Не выдумывай факты и не утверждай невыполненные действия. Верни только готовый ответ без разбора проверки, служебных слов и упоминания моделей. Если черновик уже адекватен, верни его без лишних добавлений.\n\nСообщение пользователя:\n" + userMessage + "\n\nЧерновик ответа:\n" + draft
context := []cognitive.ContextExcerpt{}
if strings.TrimSpace(personalMemory) != "" {
context = append(context, cognitive.ContextExcerpt{ID: "personal-memory", SourceKind: "derived-personal-memory", SourceID: "interaction:human-utterances", Revision: 1, Sensitivity: cognitive.SensitivityPrivateAllowed, Text: personalMemory})
}
target := *c.baseURL target := *c.baseURL
target.Path = "/v1/advisories" target.Path = "/v1/advisories"
payload, err := json.Marshal(cognitive.GatewayAdvisoryRequest{ payload, err := json.Marshal(cognitive.GatewayAdvisoryRequest{
Version: cognitive.CreatorAdvisoryV1, RequestID: cognitive.RequestID(requestID), Version: cognitive.CreatorAdvisoryV1, RequestID: cognitive.RequestID(requestID),
ActorID: session.ActorID, PrincipalID: session.PrincipalID, ActorID: session.ActorID, PrincipalID: session.PrincipalID,
ScopeID: authority.ScopeID("domovoy-global-scope"), Message: prompt, ScopeID: authority.ScopeID("domovoy-global-scope"), Message: prompt,
Locale: "ru", MaxOutputBytes: 2048, DataPolicy: capability.DataPolicyLocalOnly, Context: context, Locale: "ru", MaxOutputBytes: 2048, DataPolicy: capability.DataPolicyLocalOnly,
Meaning: cognitive.TaskMeaning{ Meaning: cognitive.TaskMeaning{
SpeechAct: "RESPONSE_REVIEW", SpeechAct: "RESPONSE_REVIEW",
CapabilityHints: meaning.CapabilityHints, CapabilityHints: meaning.CapabilityHints,
@@ -25,6 +25,9 @@ func TestReviewResponseUsesCognitiveGatewayAndReturnsOnlyDraftAnswer(t *testing.
if request.Message == "" || request.Meaning.SpeechAct == "" { if request.Message == "" || request.Meaning.SpeechAct == "" {
t.Fatalf("review request did not carry semantic context: %+v", request) t.Fatalf("review request did not carry semantic context: %+v", request)
} }
if len(request.Context) != 1 || !strings.Contains(request.Context[0].Text, "красный цвет") {
t.Fatalf("review request did not carry compact personal memory: %+v", request.Context)
}
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(cognitive.GatewayAdvisoryResponse{Version: cognitive.CreatorAdvisoryV1, RequestID: request.RequestID, AdvisoryText: "Меня зовут Дед. Я Домовой.", FinishReason: cognitive.FinishCompleted}) _ = json.NewEncoder(w).Encode(cognitive.GatewayAdvisoryResponse{Version: cognitive.CreatorAdvisoryV1, RequestID: request.RequestID, AdvisoryText: "Меня зовут Дед. Я Домовой.", FinishReason: cognitive.FinishCompleted})
})) }))
@@ -33,7 +36,7 @@ func TestReviewResponseUsesCognitiveGatewayAndReturnsOnlyDraftAnswer(t *testing.
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
reviewed, err := client.ReviewResponse(context.Background(), identity.CreatorSession{ActorID: "actor", PrincipalID: "principal"}, "кто ты?", "Я — Домовой.", cognitive.TaskMeaning{SpeechAct: "QUESTION"}) reviewed, err := client.ReviewResponse(context.Background(), identity.CreatorSession{ActorID: "actor", PrincipalID: "principal"}, "кто ты?", "Я — Домовой.", "Предпочтение пользователя (его сообщение): красный цвет", cognitive.TaskMeaning{SpeechAct: "QUESTION"})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
+117 -13
View File
@@ -511,6 +511,7 @@ func main() {
} }
var effectiveTaskMessage = interactiondomain.StripAssistantVocative(utterance.Content) var effectiveTaskMessage = interactiondomain.StripAssistantVocative(utterance.Content)
creativeUserRequest := interactiondomain.IsCreativeRequest(utterance.Content) creativeUserRequest := interactiondomain.IsCreativeRequest(utterance.Content)
locationReply := interactiondomain.LocationContextReply(utterance.Content)
continuationMessage := "" continuationMessage := ""
travelContinuation := false travelContinuation := false
var previousTask *interaction.HumanUtterance var previousTask *interaction.HumanUtterance
@@ -532,7 +533,12 @@ func main() {
log.Printf("interaction principal history loaded: %d utterances", len(recentUserHistory)) log.Printf("interaction principal history loaded: %d utterances", len(recentUserHistory))
} }
conversationHistory = append(conversationHistory, recentUserHistory...) conversationHistory = append(conversationHistory, recentUserHistory...)
if !creativeUserRequest { personalMemory := interactiondomain.CompilePersonalMemory(conversationHistory)
// Context selection must stay observable without logging the user's
// message or personal fact values. These flags let an operator distinguish
// a missing derived fact from a later routing or clarification decision.
personalMemoryHasCurrentLocation := personalMemory.CurrentLocation() != ""
if !creativeUserRequest && locationReply == "" {
if continuation := interactiondomain.ContinueLocalSearch(effectiveTaskMessage, conversationHistory); continuation != "" { if continuation := interactiondomain.ContinueLocalSearch(effectiveTaskMessage, conversationHistory); continuation != "" {
continuationMessage = continuation continuationMessage = continuation
effectiveTaskMessage = continuation effectiveTaskMessage = continuation
@@ -540,6 +546,10 @@ func main() {
continuationMessage = continuation continuationMessage = continuation
travelContinuation = true travelContinuation = true
effectiveTaskMessage = continuation effectiveTaskMessage = continuation
} else if continuation := interactiondomain.ContinueTravelDate(effectiveTaskMessage, conversationHistory); continuation != "" {
continuationMessage = continuation
travelContinuation = true
effectiveTaskMessage = continuation
} }
} }
if request.ConversationID != "" && interactiondomain.IsRetryRequest(utterance.Content) { if request.ConversationID != "" && interactiondomain.IsRetryRequest(utterance.Content) {
@@ -566,7 +576,11 @@ func main() {
continuedSemantic, continuedErr := interactiondomain.InterpretUtterance(continuedUtterance, projects, previousFocus, now) continuedSemantic, continuedErr := interactiondomain.InterpretUtterance(continuedUtterance, projects, previousFocus, now)
if continuedErr == nil { if continuedErr == nil {
continuedSemantic.Interpretation.Source = "CONVERSATION_CONTINUATION" continuedSemantic.Interpretation.Source = "CONVERSATION_CONTINUATION"
continuedSemantic.Interpretation.SelectionReason = "location follow-up completed the previous local-search task" if travelContinuation {
continuedSemantic.Interpretation.SelectionReason = "travel follow-up completed the previous travel task"
} else {
continuedSemantic.Interpretation.SelectionReason = "location follow-up completed the previous local-search task"
}
semantic = continuedSemantic semantic = continuedSemantic
} }
} }
@@ -599,8 +613,11 @@ func main() {
} }
} }
} }
locationReply := interactiondomain.LocationContextReply(utterance.Content)
if locationReply != "" { if locationReply != "" {
continuationMessage = ""
travelContinuation = false
effectiveTaskMessage = interactiondomain.StripAssistantVocative(utterance.Content)
previousTask = nil
semantic.Reply = locationReply semantic.Reply = locationReply
semantic.NeedsCognition = false semantic.NeedsCognition = false
semantic.Interpretation.NeedsCognition = false semantic.Interpretation.NeedsCognition = false
@@ -616,6 +633,7 @@ func main() {
assistantName = latestAssistantName(conversationHistory) assistantName = latestAssistantName(conversationHistory)
} }
identityReply := "" identityReply := ""
memoryInstructionReply := ""
log.Printf("interaction identity context: name=%q history=%d", assistantName, len(conversationHistory)) log.Printf("interaction identity context: name=%q history=%d", assistantName, len(conversationHistory))
if interactiondomain.IsIdentityInquiry(utterance.Content) && assistantName != "" { if interactiondomain.IsIdentityInquiry(utterance.Content) && assistantName != "" {
identityReply = "Меня зовут " + assistantName + ". Я Домовой, ваш помощник." identityReply = "Меня зовут " + assistantName + ". Я Домовой, ваш помощник."
@@ -625,21 +643,30 @@ func main() {
semantic.Interpretation.Applicability = interaction.SemanticApplicable semantic.Interpretation.Applicability = interaction.SemanticApplicable
semantic.Interpretation.Clarification = interaction.ClarificationNotRequired semantic.Interpretation.Clarification = interaction.ClarificationNotRequired
} }
if identityReply == "" && interactiondomain.IsExplicitMemoryInstruction(utterance.Content) {
memoryInstructionReply = "Запомнил."
semantic.Reply = memoryInstructionReply
semantic.NeedsCognition = false
semantic.CapabilityHints = nil
semantic.Interpretation.Applicability = interaction.SemanticApplicable
semantic.Interpretation.Clarification = interaction.ClarificationNotRequired
}
deterministicSpeechAct := semantic.Interpretation.SpeechAct deterministicSpeechAct := semantic.Interpretation.SpeechAct
deterministicReply := semantic.Reply deterministicReply := semantic.Reply
routePlan := buildChatRoutePlan(semantic) routePlan := buildChatRoutePlan(semantic)
log.Printf("chat context state: current_location=%t research_route=%t clarification=%s", personalMemoryHasCurrentLocation, hasChatRoute(routePlan, chatRouteResearch), semantic.Interpretation.Clarification)
cognitiveAttempted := false cognitiveAttempted := false
cognitiveAvailable := true cognitiveAvailable := true
semanticInterpretationRequested := shouldRequestSemanticInterpretation(semantic) semanticInterpretationRequested := shouldRequestSemanticInterpretation(semantic)
semanticReflexAudit := shouldAuditDeterministicReflex(semantic, string(utterance.ID), now) semanticReflexAudit := shouldAuditDeterministicReflex(semantic, string(utterance.ID), now)
// A selected specialized media route already has an executable semantic // A selected specialized route already has an executable semantic outcome.
// outcome. Do not block it on the general cognitive channel: image // Do not block it on the general cognitive channel: research and image
// generation must reach its own adapter even when cognition is degraded. // generation must reach their own adapters even when cognition is degraded.
if hasChatRoute(routePlan, chatRouteMedia) { if specializedRouteBypassesGeneralInterpretation(routePlan) {
semanticInterpretationRequested = false semanticInterpretationRequested = false
semanticReflexAudit = false semanticReflexAudit = false
} }
if identityReply != "" { if identityReply != "" || memoryInstructionReply != "" {
semanticReflexAudit = false semanticReflexAudit = false
} }
if semanticInterpretationRequested || semanticReflexAudit { if semanticInterpretationRequested || semanticReflexAudit {
@@ -751,6 +778,9 @@ func main() {
case interaction.InformationRequestTimeDifference: case interaction.InformationRequestTimeDifference:
planningReply = humanTimeDifferenceReply(effectiveTaskMessage) planningReply = humanTimeDifferenceReply(effectiveTaskMessage)
needsCognition = false needsCognition = false
case interaction.InformationRequestResearchFailureExplanation:
planningReply = "Я не выдаю предположение как факт, если не получил согласованных проверяемых данных. Могу повторить поиск, уточнить запрос или проверить другой источник."
needsCognition = false
case interaction.InformationRequestCapabilityInventory: case interaction.InformationRequestCapabilityInventory:
kinds, err := capabilityRepository.AvailableCapabilityKinds(r.Context(), session.PrincipalID) kinds, err := capabilityRepository.AvailableCapabilityKinds(r.Context(), session.PrincipalID)
if err == nil && len(kinds) > 0 { if err == nil && len(kinds) > 0 {
@@ -759,10 +789,17 @@ func main() {
planningReply = "Я умею общаться, сохранять контекст, искать проверяемую информацию и работать с подключёнными моделями. Дополнительные действия подключаются отдельно." planningReply = "Я умею общаться, сохранять контекст, искать проверяемую информацию и работать с подключёнными моделями. Дополнительные действия подключаются отдельно."
} }
needsCognition = false needsCognition = false
case interaction.InformationRequestLocalCapabilityInventory:
planningReply = "Без внешних моделей я могу поддерживать разговор, хранить контекст, вести цели и напоминания, а также честно сообщать состояние подключённых возможностей."
needsCognition = false
case interaction.InformationRequestCognitiveModelInventory: case interaction.InformationRequestCognitiveModelInventory:
candidates, inventoryErr := capabilityRepository.LoadCognitiveCandidates(r.Context(), capability.CapabilityID("creator-advisory"), session.PrincipalID) candidates, inventoryErr := capabilityRepository.LoadCognitiveCandidates(r.Context(), capability.CapabilityID("creator-advisory"), session.PrincipalID)
planningReply = humanCognitiveModelInventory(candidates, inventoryErr) planningReply = humanCognitiveModelInventory(candidates, inventoryErr)
needsCognition = false needsCognition = false
case interaction.InformationRequestCognitiveCurrentModel:
health, healthErr := capabilityRepository.LoadHealth(r.Context(), capability.CapabilityID("cognitive-proposal"))
planningReply = humanCurrentCognitiveModelReply(health, healthErr)
needsCognition = false
case interaction.InformationRequestCognitiveChannelStatus, interaction.InformationRequestCognitiveRecovery: case interaction.InformationRequestCognitiveChannelStatus, interaction.InformationRequestCognitiveRecovery:
health, healthErr := capabilityRepository.LoadHealth(r.Context(), capability.CapabilityID("cognitive-proposal")) health, healthErr := capabilityRepository.LoadHealth(r.Context(), capability.CapabilityID("cognitive-proposal"))
planningReply = humanCognitiveChannelReply(semantic.InformationRequestKind, semantic.Interpretation.SpeechAct, health, healthErr) planningReply = humanCognitiveChannelReply(semantic.InformationRequestKind, semantic.Interpretation.SpeechAct, health, healthErr)
@@ -778,7 +815,9 @@ func main() {
replies = append(replies, "По запросу «"+part+"»: "+clarification) replies = append(replies, "По запросу «"+part+"»: "+clarification)
continue continue
} }
searchQuery := interactiondomain.TravelSearchQuery(part, now) learnedLexicon := interactiondomain.TaskLexiconFromHistory(conversationHistory)
searchQuery := interactiondomain.SearchQueryWithLexicon(part, learnedLexicon)
searchQuery = interactiondomain.TravelResearchQuery(searchQuery, conversationHistory, now)
researchCtx, cancelResearch := context.WithTimeout(r.Context(), 8*time.Second) researchCtx, cancelResearch := context.WithTimeout(r.Context(), 8*time.Second)
result, researchErr := researchClient.SearchWeb(researchCtx, epistemics.WebSearchRequest{ result, researchErr := researchClient.SearchWeb(researchCtx, epistemics.WebSearchRequest{
Plan: epistemics.ResearchPlan{ID: epistemics.ResearchPlanID(fmt.Sprintf("plan:%s:%d", planID, index)), Question: searchQuery, SourceClasses: []string{"web-search"}, FreshnessPolicy: "current"}, Plan: epistemics.ResearchPlan{ID: epistemics.ResearchPlanID(fmt.Sprintf("plan:%s:%d", planID, index)), Question: searchQuery, SourceClasses: []string{"web-search"}, FreshnessPolicy: "current"},
@@ -920,9 +959,13 @@ func main() {
planningReply = identityReply planningReply = identityReply
needsCognition = false needsCognition = false
} }
if memoryInstructionReply != "" {
planningReply = memoryInstructionReply
needsCognition = false
}
if strings.TrimSpace(planningReply) != "" { if strings.TrimSpace(planningReply) != "" {
reviewContext, cancelReview := context.WithTimeout(r.Context(), 12*time.Second) reviewContext, cancelReview := context.WithTimeout(r.Context(), 12*time.Second)
reviewedReply, reviewErr := cognitiveClient.ReviewResponse(reviewContext, session, utterance.Content, planningReply, cognitive.TaskMeaning{ reviewedReply, reviewErr := cognitiveClient.ReviewResponse(reviewContext, session, utterance.Content, planningReply, personalMemory.ContextText(), cognitive.TaskMeaning{
SpeechAct: string(semantic.Interpretation.SpeechAct), SpeechAct: string(semantic.Interpretation.SpeechAct),
CapabilityHints: toCapabilityKinds(semantic.CapabilityHints), CapabilityHints: toCapabilityKinds(semantic.CapabilityHints),
RequestedOutcome: semantic.Interpretation.RequestedOutcome, RequestedOutcome: semantic.Interpretation.RequestedOutcome,
@@ -930,7 +973,7 @@ func main() {
ConfidenceMillis: semantic.Interpretation.ConfidenceMillis, ConfidenceMillis: semantic.Interpretation.ConfidenceMillis,
}) })
cancelReview() cancelReview()
stableSemanticReply := mediaAttempted || identityReply != "" || creativeReply != "" || (creativeFallbackReply != "" && !cognitiveAvailable) || semantic.InformationRequestKind != "" || locationReply != "" || deterministicSpeechAct == interaction.SpeechActConversational || deterministicSpeechAct == interaction.SpeechActConfirmation || deterministicSpeechAct == interaction.SpeechActRejection stableSemanticReply := mediaAttempted || identityReply != "" || memoryInstructionReply != "" || creativeReply != "" || (creativeFallbackReply != "" && !cognitiveAvailable) || semantic.InformationRequestKind != "" || locationReply != "" || deterministicSpeechAct == interaction.SpeechActConversational || deterministicSpeechAct == interaction.SpeechActConfirmation || deterministicSpeechAct == interaction.SpeechActRejection
if reviewErr != nil { if reviewErr != nil {
log.Printf("cognitive response review unavailable: %v", reviewErr) log.Printf("cognitive response review unavailable: %v", reviewErr)
} else if !stableSemanticReply && (!researchBacked || reviewPreservesResearchEvidence(reviewedReply, planningReply)) { } else if !stableSemanticReply && (!researchBacked || reviewPreservesResearchEvidence(reviewedReply, planningReply)) {
@@ -955,6 +998,11 @@ func main() {
needsCognition = false needsCognition = false
planningReply = identityReply planningReply = identityReply
} }
if memoryInstructionReply != "" {
semantic.Reply = memoryInstructionReply
needsCognition = false
planningReply = memoryInstructionReply
}
if creativeReply != "" { if creativeReply != "" {
semantic.Reply = creativeReply semantic.Reply = creativeReply
needsCognition = false needsCognition = false
@@ -1713,13 +1761,16 @@ func renderResearchReply(query string, result epistemics.ResearchResult, researc
return "Сейчас не удалось получить данные из подключённого источника. Попробую снова через доступный маршрут.", false return "Сейчас не удалось получить данные из подключённого источника. Попробую снова через доступный маршрут.", false
} }
lines := make([]string, 0, 2) lines := make([]string, 0, 2)
for index, finding := range result.Findings { for _, finding := range result.Findings {
if finding.State != epistemics.FindingSupported || strings.TrimSpace(finding.Excerpt.Text) == "" || strings.TrimSpace(finding.Source.Locator) == "" { if finding.State != epistemics.FindingSupported || strings.TrimSpace(finding.Excerpt.Text) == "" || strings.TrimSpace(finding.Source.Locator) == "" {
continue continue
} }
if !researchFindingMatchesIntent(query, finding) {
continue
}
excerpt := humanResearchExcerpt(query, finding.Excerpt.Text) excerpt := humanResearchExcerpt(query, finding.Excerpt.Text)
limit := 180 limit := 180
if index > 0 { if len(lines) > 0 {
limit = 100 limit = 100
} }
if len([]rune(excerpt)) > limit { if len([]rune(excerpt)) > limit {
@@ -1733,6 +1784,9 @@ func renderResearchReply(query string, result epistemics.ResearchResult, researc
if len(lines) == 0 { if len(lines) == 0 {
return "Проверяемых данных пока не найдено. Могу повторить поиск или уточнить, что именно проверить.", false return "Проверяемых данных пока не найдено. Могу повторить поиск или уточнить, что именно проверить.", false
} }
if isInternetStatusQuery(query) {
return "Интернет работает: Домовой получил ответ от внешних источников.\n\n" + strings.Join(lines, "\n\n"), true
}
if nearestFlightQuery(query) && !containsFlightTimeEvidence(strings.Join(lines, " ")) { if nearestFlightQuery(query) && !containsFlightTimeEvidence(strings.Join(lines, " ")) {
return "Нашёл расписание по маршруту, но точное время ближайшего вылета в доступных фрагментах не указано. Откройте источник и выберите ближайший рейс:\n\n" + strings.Join(lines, "\n\n"), true return "Нашёл расписание по маршруту, но точное время ближайшего вылета в доступных фрагментах не указано. Откройте источник и выберите ближайший рейс:\n\n" + strings.Join(lines, "\n\n"), true
} }
@@ -1744,11 +1798,41 @@ func renderResearchReply(query string, result epistemics.ResearchResult, researc
return reply, true return reply, true
} }
func isInternetStatusQuery(query string) bool {
lower := strings.ToLower(query)
return (strings.Contains(lower, "интернет") || strings.Contains(lower, "сет")) &&
(strings.Contains(lower, "работает") || strings.Contains(lower, "доступ") || strings.Contains(lower, "проверь") || strings.Contains(lower, "связ"))
}
func nearestFlightQuery(query string) bool { func nearestFlightQuery(query string) bool {
lower := strings.ToLower(query) lower := strings.ToLower(query)
return strings.Contains(lower, "ближ") && (strings.Contains(lower, "рейс") || strings.Contains(lower, "самолет") || strings.Contains(lower, "самолёт") || strings.Contains(lower, "вылет")) return strings.Contains(lower, "ближ") && (strings.Contains(lower, "рейс") || strings.Contains(lower, "самолет") || strings.Contains(lower, "самолёт") || strings.Contains(lower, "вылет"))
} }
// researchFindingMatchesIntent is a final relevance check over evidence
// already obtained by the read-only research route. It prevents unrelated
// search-engine snippets from becoming a human-facing answer when a search
// term has a common non-travel meaning.
func researchFindingMatchesIntent(query string, finding epistemics.ResearchFinding) bool {
if !nearestFlightQuery(query) {
return true
}
evidence := strings.ToLower(strings.Join([]string{
finding.Source.Title,
finding.Source.Publisher,
finding.Source.Locator,
finding.Statement,
finding.Excerpt.Text,
}, " "))
return strings.Contains(evidence, "рейс") ||
strings.Contains(evidence, "вылет") ||
strings.Contains(evidence, "авиабил") ||
strings.Contains(evidence, "аэропорт") ||
strings.Contains(evidence, "самолет") ||
strings.Contains(evidence, "самолёт") ||
strings.Contains(evidence, "расписан")
}
func containsFlightTimeEvidence(value string) bool { func containsFlightTimeEvidence(value string) bool {
return regexp.MustCompile(`(?m)\b(?:[01]?\d|2[0-3]):[0-5]\d\b`).MatchString(value) return regexp.MustCompile(`(?m)\b(?:[01]?\d|2[0-3]):[0-5]\d\b`).MatchString(value)
} }
@@ -2007,6 +2091,26 @@ func humanCognitiveChannelReply(kind interaction.InformationRequestKind, act int
} }
} }
// humanCurrentCognitiveModelReply answers about the route that produced this
// reply. It intentionally does not infer a provider/model name from health:
// that would claim a model was used when this direct status path did not call it.
func humanCurrentCognitiveModelReply(health capability.Health, healthErr error) string {
base := "Этот ответ сформирован встроенным режимом Домового; внешняя модель для него не использовалась."
if healthErr != nil {
return base + " Состояние канала мышления сейчас не удалось проверить."
}
switch health.State {
case capability.HealthAvailable:
return base + " Канал мышления доступен для следующих задач."
case capability.HealthDegraded:
return base + " Канал мышления работает с ограничениями."
case capability.HealthUnavailable:
return base + " Канал мышления сейчас недоступен."
default:
return base + " Состояние канала мышления пока не подтверждено."
}
}
func humanCognitiveDegradedReply(message string) string { func humanCognitiveDegradedReply(message string) string {
if strings.TrimSpace(message) == "" { if strings.TrimSpace(message) == "" {
return "Сейчас не удалось обработать запрос." return "Сейчас не удалось обработать запрос."
+30
View File
@@ -11,6 +11,7 @@ import (
"time" "time"
"git.cin.su/m/Assistant/contracts/capability" "git.cin.su/m/Assistant/contracts/capability"
"git.cin.su/m/Assistant/contracts/epistemics"
"git.cin.su/m/Assistant/contracts/interaction" "git.cin.su/m/Assistant/contracts/interaction"
interactiondomain "git.cin.su/m/Assistant/modules/interaction/domain" interactiondomain "git.cin.su/m/Assistant/modules/interaction/domain"
) )
@@ -34,6 +35,17 @@ func TestNearestFlightEvidenceDoesNotClaimMissingDepartureTime(t *testing.T) {
} }
} }
func TestNearestFlightReplyFiltersUnrelatedSearchSnippets(t *testing.T) {
result := epistemics.ResearchResult{Findings: []epistemics.ResearchFinding{
{State: epistemics.FindingSupported, Source: epistemics.Source{Locator: "https://naidy.example", Title: "Мебельная фурнитура"}, Excerpt: epistemics.SourceExcerpt{Text: "Комплектующие для мебели оптом и в розницу."}},
{State: epistemics.FindingSupported, Source: epistemics.Source{Locator: "https://rasp.example", Title: "Рейсы Москва — Казань"}, Excerpt: epistemics.SourceExcerpt{Text: "Расписание самолётов Москва — Казань, время вылета и прилёта."}},
}}
reply, backed := renderResearchReply("найди ближайший самолет до Казани сегодня пункт отправления: Москва", result, nil)
if !backed || !strings.Contains(reply, "Рейсы Москва") || strings.Contains(reply, "Мебельная") {
t.Fatalf("unrelated source leaked into flight reply: %q", reply)
}
}
func TestBearerTokenRequiresBearerScheme(t *testing.T) { func TestBearerTokenRequiresBearerScheme(t *testing.T) {
request := httptest.NewRequest("GET", "/", nil) request := httptest.NewRequest("GET", "/", nil)
request.Header.Set("Authorization", "Basic value") request.Header.Set("Authorization", "Basic value")
@@ -76,6 +88,17 @@ func TestContainsPriceEvidenceDistinguishesLinksFromPrices(t *testing.T) {
} }
} }
func TestInternetStatusQueryRecognizesConnectionChecks(t *testing.T) {
for _, query := range []string{"проверь, работает ли интернет", "есть доступ к сети?"} {
if !isInternetStatusQuery(query) {
t.Fatalf("connection check was not recognized: %q", query)
}
}
if isInternetStatusQuery("найди интернет-магазин") {
t.Fatal("ordinary search must not be treated as a connectivity check")
}
}
func TestCognitiveChannelQuestionUsesHumanSafeHealthReply(t *testing.T) { func TestCognitiveChannelQuestionUsesHumanSafeHealthReply(t *testing.T) {
reply := humanCognitiveChannelReply(interaction.InformationRequestCognitiveChannelStatus, interaction.SpeechActQuestion, capability.Health{State: capability.HealthAvailable, CapabilityID: "provider-secret-model"}, nil) reply := humanCognitiveChannelReply(interaction.InformationRequestCognitiveChannelStatus, interaction.SpeechActQuestion, capability.Health{State: capability.HealthAvailable, CapabilityID: "provider-secret-model"}, nil)
if !strings.Contains(reply, "доступен") || strings.Contains(reply, "provider-secret-model") { if !strings.Contains(reply, "доступен") || strings.Contains(reply, "provider-secret-model") {
@@ -83,6 +106,13 @@ func TestCognitiveChannelQuestionUsesHumanSafeHealthReply(t *testing.T) {
} }
} }
func TestCurrentModelReplyDoesNotInventProvider(t *testing.T) {
reply := humanCurrentCognitiveModelReply(capability.Health{State: capability.HealthDegraded, CapabilityID: "provider-secret-model"}, nil)
if !strings.Contains(reply, "встроенным режимом") || !strings.Contains(reply, "ограничениями") || strings.Contains(reply, "provider-secret-model") {
t.Fatalf("unexpected current-model reply: %q", reply)
}
}
func TestCognitiveConfigurationRequestDoesNotPretendToMutate(t *testing.T) { func TestCognitiveConfigurationRequestDoesNotPretendToMutate(t *testing.T) {
reply := humanCognitiveChannelReply(interaction.InformationRequestCognitiveRecovery, interaction.SpeechActDirective, capability.Health{State: capability.HealthUnavailable}, nil) reply := humanCognitiveChannelReply(interaction.InformationRequestCognitiveRecovery, interaction.SpeechActDirective, capability.Health{State: capability.HealthUnavailable}, nil)
if reply != "Канал мышления недоступен. Домовой остаётся на связи." { if reply != "Канал мышления недоступен. Домовой остаётся на связи." {
+5 -1
View File
@@ -28,7 +28,11 @@ import (
const ( const (
maxRequestBytes = 8 << 10 maxRequestBytes = 8 << 10
maxAdvisoryRequestBytes = 20 << 10 maxAdvisoryRequestBytes = 20 << 10
maxResponseBytes = 1 << 20 // Chat responses may contain a locally generated image encoded as base64.
// Keep the gateway limit aligned with the bounded media transport (32 MiB),
// otherwise a successfully generated image is incorrectly surfaced as an
// unavailable runtime to the human.
maxResponseBytes = 32 << 20
) )
//go:embed static //go:embed static
+20
View File
@@ -1,6 +1,7 @@
package main package main
import ( import (
"bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
@@ -13,6 +14,25 @@ import (
"git.cin.su/m/Assistant/contracts/interaction" "git.cin.su/m/Assistant/contracts/interaction"
) )
func TestMaxResponseBytesAcceptsGeneratedImagePayload(t *testing.T) {
// A 1024px PNG can exceed the former 1 MiB gateway limit once base64
// encoded. The browser gateway must forward that successful core response.
payload, err := json.Marshal(interaction.ChatMessageResponse{
GeneratedImageContentType: "image/png",
GeneratedImageBase64: strings.Repeat("A", 2<<20),
})
if err != nil {
t.Fatal(err)
}
var decoded interaction.ChatMessageResponse
if err := decodeStrictJSON(bytes.NewReader(payload), maxResponseBytes, &decoded); err != nil {
t.Fatalf("generated image response must fit gateway limit: %v", err)
}
if len(decoded.GeneratedImageBase64) != 2<<20 {
t.Fatalf("generated image payload was truncated: %d", len(decoded.GeneratedImageBase64))
}
}
func TestLocalChatContextIncludesDomovoyIdentityAndOptionalActiveProject(t *testing.T) { func TestLocalChatContextIncludesDomovoyIdentityAndOptionalActiveProject(t *testing.T) {
context := localChatContext(interaction.ChatMessageResponse{AssistantName: "Фея", ActiveProjectName: "Домовой"}) context := localChatContext(interaction.ChatMessageResponse{AssistantName: "Фея", ActiveProjectName: "Домовой"})
if len(context) != 2 || context[0].SourceID != "domovoy" || !strings.Contains(context[0].Text, "Ты — Фея") || !strings.Contains(context[0].Text, "Меня зовут Фея") || context[1].Text != "Текущий проект: Домовой" { if len(context) != 2 || context[0].SourceID != "domovoy" || !strings.Contains(context[0].Text, "Ты — Фея") || !strings.Contains(context[0].Text, "Меня зовут Фея") || context[1].Text != "Текущий проект: Домовой" {
+48 -45
View File
@@ -27,51 +27,54 @@ type SemanticCandidateSelectionState string
type InformationRequestKind string type InformationRequestKind string
const ( const (
ChannelWebChat Channel = "WEB_CHAT" ChannelWebChat Channel = "WEB_CHAT"
ConversationOpen ConversationState = "OPEN" ConversationOpen ConversationState = "OPEN"
ConversationArchived ConversationState = "ARCHIVED" ConversationArchived ConversationState = "ARCHIVED"
SpeechActDirective SpeechAct = "DIRECTIVE" SpeechActDirective SpeechAct = "DIRECTIVE"
SpeechActAssertion SpeechAct = "ASSERTION" SpeechActAssertion SpeechAct = "ASSERTION"
SpeechActDecision SpeechAct = "DECISION" SpeechActDecision SpeechAct = "DECISION"
SpeechActPreference SpeechAct = "PREFERENCE" SpeechActPreference SpeechAct = "PREFERENCE"
SpeechActQuestion SpeechAct = "QUESTION" SpeechActQuestion SpeechAct = "QUESTION"
SpeechActHypothesis SpeechAct = "HYPOTHESIS" SpeechActHypothesis SpeechAct = "HYPOTHESIS"
SpeechActCorrection SpeechAct = "CORRECTION" SpeechActCorrection SpeechAct = "CORRECTION"
SpeechActRequestToInvestigate SpeechAct = "REQUEST_TO_INVESTIGATE" SpeechActRequestToInvestigate SpeechAct = "REQUEST_TO_INVESTIGATE"
SpeechActConfirmation SpeechAct = "CONFIRMATION" SpeechActConfirmation SpeechAct = "CONFIRMATION"
SpeechActRejection SpeechAct = "REJECTION" SpeechActRejection SpeechAct = "REJECTION"
SpeechActCancellation SpeechAct = "CANCELLATION" SpeechActCancellation SpeechAct = "CANCELLATION"
SpeechActConversational SpeechAct = "CONVERSATIONAL" SpeechActConversational SpeechAct = "CONVERSATIONAL"
SpeechActUnknown SpeechAct = "UNKNOWN" SpeechActUnknown SpeechAct = "UNKNOWN"
InterpretationRecorded InterpretationState = "RECORDED" InterpretationRecorded InterpretationState = "RECORDED"
InterpretationInterpreted InterpretationState = "INTERPRETED" InterpretationInterpreted InterpretationState = "INTERPRETED"
RelationCorrects InteractionRelationKind = "CORRECTS" RelationCorrects InteractionRelationKind = "CORRECTS"
RelationRespondsTo InteractionRelationKind = "RESPONDS_TO" RelationRespondsTo InteractionRelationKind = "RESPONDS_TO"
RelationRequestsCognition InteractionRelationKind = "REQUESTS_COGNITION" RelationRequestsCognition InteractionRelationKind = "REQUESTS_COGNITION"
RelationCognitionFallback InteractionRelationKind = "COGNITION_FALLBACK" RelationCognitionFallback InteractionRelationKind = "COGNITION_FALLBACK"
RelationSupersedes InteractionRelationKind = "SUPERSEDES" RelationSupersedes InteractionRelationKind = "SUPERSEDES"
RelationClarifies InteractionRelationKind = "CLARIFIES" RelationClarifies InteractionRelationKind = "CLARIFIES"
ProjectRolePrimary ProjectReferenceRole = "PRIMARY" ProjectRolePrimary ProjectReferenceRole = "PRIMARY"
ProjectRoleRelated ProjectReferenceRole = "RELATED" ProjectRoleRelated ProjectReferenceRole = "RELATED"
ProjectRoleReferenceSource ProjectReferenceRole = "REFERENCE_SOURCE" ProjectRoleReferenceSource ProjectReferenceRole = "REFERENCE_SOURCE"
ClarificationNotRequired ClarificationState = "NOT_REQUIRED" ClarificationNotRequired ClarificationState = "NOT_REQUIRED"
ClarificationRequired ClarificationState = "REQUIRED" ClarificationRequired ClarificationState = "REQUIRED"
SemanticApplicable SemanticApplicability = "APPLICABLE" SemanticApplicable SemanticApplicability = "APPLICABLE"
SemanticLowConfidence SemanticApplicability = "LOW_CONFIDENCE" SemanticLowConfidence SemanticApplicability = "LOW_CONFIDENCE"
SemanticMixedIntent SemanticApplicability = "MIXED_INTENT" SemanticMixedIntent SemanticApplicability = "MIXED_INTENT"
SemanticNeedsBroaderInterpret SemanticApplicability = "NEEDS_BROADER_INTERPRETATION" SemanticNeedsBroaderInterpret SemanticApplicability = "NEEDS_BROADER_INTERPRETATION"
SemanticCandidateClarify SemanticApplicability = "CLARIFICATION_REQUIRED" SemanticCandidateClarify SemanticApplicability = "CLARIFICATION_REQUIRED"
CandidateSourceDeterministic SemanticCandidateSource = "DETERMINISTIC_V2" CandidateSourceDeterministic SemanticCandidateSource = "DETERMINISTIC_V2"
CandidateSourceCognitive SemanticCandidateSource = "COGNITIVE_V1" CandidateSourceCognitive SemanticCandidateSource = "COGNITIVE_V1"
CandidateSelected SemanticCandidateSelectionState = "SELECTED" CandidateSelected SemanticCandidateSelectionState = "SELECTED"
CandidateObserved SemanticCandidateSelectionState = "OBSERVED" CandidateObserved SemanticCandidateSelectionState = "OBSERVED"
CandidateRejected SemanticCandidateSelectionState = "REJECTED" CandidateRejected SemanticCandidateSelectionState = "REJECTED"
InformationRequestCapabilityInventory InformationRequestKind = "CAPABILITY_INVENTORY" InformationRequestCapabilityInventory InformationRequestKind = "CAPABILITY_INVENTORY"
InformationRequestCognitiveModelInventory InformationRequestKind = "COGNITIVE_MODEL_INVENTORY" InformationRequestLocalCapabilityInventory InformationRequestKind = "LOCAL_CAPABILITY_INVENTORY"
InformationRequestCognitiveChannelStatus InformationRequestKind = "COGNITIVE_CHANNEL_STATUS" InformationRequestCognitiveModelInventory InformationRequestKind = "COGNITIVE_MODEL_INVENTORY"
InformationRequestCognitiveRecovery InformationRequestKind = "COGNITIVE_RECOVERY" InformationRequestCognitiveCurrentModel InformationRequestKind = "COGNITIVE_CURRENT_MODEL"
InformationRequestMemoryInventory InformationRequestKind = "MEMORY_INVENTORY" InformationRequestCognitiveChannelStatus InformationRequestKind = "COGNITIVE_CHANNEL_STATUS"
InformationRequestTimeDifference InformationRequestKind = "TIME_DIFFERENCE" InformationRequestCognitiveRecovery InformationRequestKind = "COGNITIVE_RECOVERY"
InformationRequestMemoryInventory InformationRequestKind = "MEMORY_INVENTORY"
InformationRequestTimeDifference InformationRequestKind = "TIME_DIFFERENCE"
InformationRequestResearchFailureExplanation InformationRequestKind = "RESEARCH_FAILURE_EXPLANATION"
) )
type Conversation struct { type Conversation struct {
+33 -11
View File
@@ -128,6 +128,9 @@ func FallbackText(act interaction.SpeechAct) string {
// of the same request. // of the same request.
func PreferredAssistantName(message string) string { func PreferredAssistantName(message string) string {
tokens := semanticTokens(message) tokens := semanticTokens(message)
if !hasAssistantNamingTarget(tokens) {
return ""
}
for index, token := range tokens { for index, token := range tokens {
if !containsStem(token, "называ", "назов", "зов", "имен") { if !containsStem(token, "называ", "назов", "зов", "имен") {
continue continue
@@ -170,6 +173,15 @@ func IsIdentityInquiry(message string) bool {
return containsToken(tokens, "зовут") || containsToken(tokens, "имя") return containsToken(tokens, "зовут") || containsToken(tokens, "имя")
} }
// IsExplicitMemoryInstruction recognizes a direct request to retain the
// following human-provided context. It deliberately does not interpret the
// content as a verified fact: the conversation owner keeps the original
// utterance and its provenance.
func IsExplicitMemoryInstruction(message string) bool {
tokens := semanticTokens(message)
return len(tokens) > 0 && containsStem(tokens[0], "запомни", "помни")
}
func BuildDeterministicCandidate(message string, corrects interaction.HumanUtteranceID, millis int64) interaction.SemanticCandidate { func BuildDeterministicCandidate(message string, corrects interaction.HumanUtteranceID, millis int64) interaction.SemanticCandidate {
id, _ := ids.New() id, _ := ids.New()
tokens := semanticTokens(message) tokens := semanticTokens(message)
@@ -362,6 +374,9 @@ func semanticScores(tokens []string, hasQuestionMark bool, explicitCorrection bo
} }
func preferredNameFromTokens(tokens []string) bool { func preferredNameFromTokens(tokens []string) bool {
if !hasAssistantNamingTarget(tokens) {
return false
}
for index, token := range tokens { for index, token := range tokens {
if !containsStem(token, "называ", "назов", "зов", "имен") { if !containsStem(token, "называ", "назов", "зов", "имен") {
continue continue
@@ -376,6 +391,10 @@ func preferredNameFromTokens(tokens []string) bool {
return false return false
} }
func hasAssistantNamingTarget(tokens []string) bool {
return containsToken(tokens, "тебя") || containsToken(tokens, "тебе") || containsToken(tokens, "ты")
}
// IsRetryRequest identifies a short continuation that asks Domovoy to repeat // IsRetryRequest identifies a short continuation that asks Domovoy to repeat
// the previous task. It deliberately carries no subject-specific knowledge; // the previous task. It deliberately carries no subject-specific knowledge;
// the conversation owner supplies the previous task when available. // the conversation owner supplies the previous task when available.
@@ -593,7 +612,7 @@ func sourceDependentQuestion(primary, secondary interaction.SpeechAct, tokens []
currentCue := containsStemInTokens(tokens, "сейчас", "сегодня", "текущ", "актуаль", "последн", "прямо") currentCue := containsStemInTokens(tokens, "сейчас", "сегодня", "текущ", "актуаль", "последн", "прямо")
observedStateCue := containsStemInTokens(tokens, "погод", "температур", "осад", "ветер", "курс", "цен", "стоим", "новост", "распис", "событ", "статус", "доступен", "работает", "запущен", "срок") || approximateToken(tokens, "погод", 2) observedStateCue := containsStemInTokens(tokens, "погод", "температур", "осад", "ветер", "курс", "цен", "стоим", "новост", "распис", "событ", "статус", "доступен", "работает", "запущен", "срок") || approximateToken(tokens, "погод", 2)
placeSearchCue := containsStemInTokens(tokens, "ресторан", "кафе", "отел", "магаз", "мест", "ближ", "адрес", "организац", "бренд", "товар", "артикул", "продавец", "маркетплейс", "wildberries", "wb") placeSearchCue := containsStemInTokens(tokens, "ресторан", "кафе", "отел", "магаз", "мест", "ближ", "адрес", "организац", "бренд", "товар", "артикул", "продавец", "маркетплейс", "wildberries", "wb")
travelSearchCue := containsStemInTokens(tokens, "билет", "рейс", "поезд", "автобус", "перелет", "перелёт", "отправлен", "прибыт", "расстоян", "километр", "добрат", "маршрут") travelSearchCue := containsStemInTokens(tokens, "билет", "рейс", "самолет", "самолёт", "вылет", "поезд", "автобус", "перелет", "перелёт", "отправлен", "прибыт", "расстоян", "километр", "добрат", "маршрут")
timeDifferenceCue := containsStemInTokens(tokens, "разниц") && containsStemInTokens(tokens, "времен", "час") timeDifferenceCue := containsStemInTokens(tokens, "разниц") && containsStemInTokens(tokens, "времен", "час")
return currentCue || observedStateCue || placeSearchCue || travelSearchCue || timeDifferenceCue return currentCue || observedStateCue || placeSearchCue || travelSearchCue || timeDifferenceCue
} }
@@ -651,15 +670,24 @@ func informationRequestKind(message string, candidate interaction.SemanticCandid
if containsStemInTokens(tokens, "разниц") && containsStemInTokens(tokens, "времен", "час") { if containsStemInTokens(tokens, "разниц") && containsStemInTokens(tokens, "времен", "час") {
return interaction.InformationRequestTimeDifference return interaction.InformationRequestTimeDifference
} }
if containsStemInTokens(tokens, "почему", "зачем") && containsStemInTokens(tokens, "смог", "неполуч", "нашел", "нашёл") && containsStemInTokens(tokens, "ответ", "данн", "найт") {
return interaction.InformationRequestResearchFailureExplanation
}
inquiry := candidate.PrimarySpeechAct == interaction.SpeechActQuestion || candidate.PrimarySpeechAct == interaction.SpeechActRequestToInvestigate || candidate.SecondarySpeechAct == interaction.SpeechActQuestion || candidate.SecondarySpeechAct == interaction.SpeechActRequestToInvestigate inquiry := candidate.PrimarySpeechAct == interaction.SpeechActQuestion || candidate.PrimarySpeechAct == interaction.SpeechActRequestToInvestigate || candidate.SecondarySpeechAct == interaction.SpeechActQuestion || candidate.SecondarySpeechAct == interaction.SpeechActRequestToInvestigate
cognitiveSubject := containsStemInTokens(tokens, "модел", "ии", "ai", "локальн", "когнитив", "канал") cognitiveSubject := containsStemInTokens(tokens, "модел", "ии", "ai", "локальн", "когнитив", "канал")
if cognitiveSubject && inquiry && containsStemInTokens(tokens, "какая", "какой", "текущ", "сейчас", "отвеч") && containsStemInTokens(tokens, "модел") {
return interaction.InformationRequestCognitiveCurrentModel
}
inventoryCue := containsStemInTokens(tokens, "список", "доступ", "подключ", "вариант") || (containsMeaningfulInterrogative(tokens) && containsStemInTokens(tokens, "настро")) inventoryCue := containsStemInTokens(tokens, "список", "доступ", "подключ", "вариант") || (containsMeaningfulInterrogative(tokens) && containsStemInTokens(tokens, "настро"))
inventoryRequest := inquiry || containsStemInTokens(tokens, "напиш", "покаж", "перечисл", "сообщ", "вывед", "предостав") inventoryRequest := inquiry || containsStemInTokens(tokens, "назов", "напиш", "покаж", "перечисл", "сообщ", "вывед", "предостав")
if cognitiveSubject && inventoryRequest && inventoryCue { if cognitiveSubject && inventoryRequest && inventoryCue {
return interaction.InformationRequestCognitiveModelInventory return interaction.InformationRequestCognitiveModelInventory
} }
capabilitySubject := containsStemInTokens(tokens, "уме", "возможност", "способн", "capabilit") capabilitySubject := containsStemInTokens(tokens, "уме", "возможност", "способн", "capabilit") || (containsMeaningfulInterrogative(tokens) && containsToken(tokens, "можешь"))
if inquiry && capabilitySubject { if inquiry && capabilitySubject {
if containsStemInTokens(tokens, "без", "внешн", "локальн") && containsStemInTokens(tokens, "модел", "ии", "ai") {
return interaction.InformationRequestLocalCapabilityInventory
}
return interaction.InformationRequestCapabilityInventory return interaction.InformationRequestCapabilityInventory
} }
recoveryCue := containsStemInTokens(tokens, "восстанов", "исправ", "почин", "подключ", "настро", "недоступ", "нет") recoveryCue := containsStemInTokens(tokens, "восстанов", "исправ", "почин", "подключ", "настро", "недоступ", "нет")
@@ -673,14 +701,8 @@ func informationRequestKind(message string, candidate interaction.SemanticCandid
} }
func LocationContextReply(message string) string { func LocationContextReply(message string) string {
tokens := semanticTokens(message) if location := personalCurrentLocation(message); location != "" {
if len(tokens) < 4 || tokens[0] != "я" || !containsStemInTokens(tokens, "сейчас", "нахож", "жив") { return "Запомнил: сейчас вы в " + location + "."
return ""
}
for index, token := range tokens {
if (token == "в" || token == "на") && index+1 < len(tokens) {
return "Запомнил: сейчас вы в " + capitalizeWord(tokens[index+1]) + "."
}
} }
return "" return ""
} }
+31
View File
@@ -49,6 +49,13 @@ func TestNewHumanUtteranceClassifiesReminderAndCapabilityConnectionAsDirective(t
} }
} }
func TestPlaneRequestReceivesTravelResearchCapability(t *testing.T) {
candidate := BuildDeterministicCandidate("найди ближайший самолет до Казани", "", 100)
if !containsToken(candidate.CapabilityHints, "WEB_RESEARCH") {
t.Fatalf("plane request did not select web research: %+v", candidate)
}
}
func TestDeterministicCandidateIsInvariantToMissingQuestionMarkForIdentityAndArithmetic(t *testing.T) { func TestDeterministicCandidateIsInvariantToMissingQuestionMarkForIdentityAndArithmetic(t *testing.T) {
cases := []struct { cases := []struct {
message string message string
@@ -118,6 +125,10 @@ func TestInformationRequestsAreClassifiedOnceByInteraction(t *testing.T) {
kind interaction.InformationRequestKind kind interaction.InformationRequestKind
}{ }{
{"какие модели доступны?", interaction.InformationRequestCognitiveModelInventory}, {"какие модели доступны?", interaction.InformationRequestCognitiveModelInventory},
{"назови доступные модели", interaction.InformationRequestCognitiveModelInventory},
{"какая модель отвечает?", interaction.InformationRequestCognitiveCurrentModel},
{"почему ты не смог найти ответ?", interaction.InformationRequestResearchFailureExplanation},
{"что ты можешь сделать без внешних моделей?", interaction.InformationRequestLocalCapabilityInventory},
{"что ты умеешь?", interaction.InformationRequestCapabilityInventory}, {"что ты умеешь?", interaction.InformationRequestCapabilityInventory},
{"проверь состояние локального канала", interaction.InformationRequestCognitiveChannelStatus}, {"проверь состояние локального канала", interaction.InformationRequestCognitiveChannelStatus},
{"нет связи с ИИ, восстанови канал", interaction.InformationRequestCognitiveRecovery}, {"нет связи с ИИ, восстанови канал", interaction.InformationRequestCognitiveRecovery},
@@ -200,6 +211,14 @@ func TestDecomposeUsesRememberedAliasesAcrossWordings(t *testing.T) {
} }
} }
func TestTaskLexiconFromHistoryFeedsSearchQueryWithoutCoreAlias(t *testing.T) {
history := []interaction.HumanUtterance{{Content: "запомни: WB — это Wildberries, источник для поиска"}}
lexicon := TaskLexiconFromHistory(history)
if got := SearchQueryWithLexicon("найди на WB бренд marka-wear", lexicon); got != "найди на WB бренд marka-wear wildberries" {
t.Fatalf("learned source was not applied to search: %q", got)
}
}
func TestDecomposeCreativeRequestDoesNotInventResearch(t *testing.T) { func TestDecomposeCreativeRequestDoesNotInventResearch(t *testing.T) {
lexicon := TaskLexicon{ObjectAliases: []TaskLexiconEntry{{Alias: "медвед", Value: "IMAGE"}}} lexicon := TaskLexicon{ObjectAliases: []TaskLexiconEntry{{Alias: "медвед", Value: "IMAGE"}}}
got := DecomposeTaskWithLexicon("нарисуй бурого медведя", lexicon) got := DecomposeTaskWithLexicon("нарисуй бурого медведя", lexicon)
@@ -240,9 +259,21 @@ func TestNamingPreferenceIsSemanticAndProducesNaturalAcceptance(t *testing.T) {
if name := PreferredAssistantName("давай переименуем тебя в фею. теперь тебя зовут фея"); name != "Фея" { if name := PreferredAssistantName("давай переименуем тебя в фею. теперь тебя зовут фея"); name != "Фея" {
t.Fatalf("rename phrase returned %q", name) t.Fatalf("rename phrase returned %q", name)
} }
if name := PreferredAssistantName("назови доступные модели"); name != "" {
t.Fatalf("model inventory request was mistaken for a name: %q", name)
}
if result := BuildDeterministicCandidate("назови доступные модели", "", time.Unix(10, 0).UnixMilli()); result.PrimarySpeechAct == interaction.SpeechActPreference {
t.Fatalf("model inventory request was mistaken for a preference: %+v", result)
}
if !IsIdentityInquiry("ты кто?") || !IsIdentityInquiry("как тебя зовут") { if !IsIdentityInquiry("ты кто?") || !IsIdentityInquiry("как тебя зовут") {
t.Fatal("identity variants should be recognized") t.Fatal("identity variants should be recognized")
} }
if !IsExplicitMemoryInstruction("запомни: сокращение — это источник для поиска") {
t.Fatal("explicit memory instruction was not recognized")
}
if IsExplicitMemoryInstruction("что ты помнишь обо мне?") {
t.Fatal("memory inventory question must not be treated as an instruction")
}
} }
func TestMemoryInventoryRequestIsSemantic(t *testing.T) { func TestMemoryInventoryRequestIsSemantic(t *testing.T) {
@@ -0,0 +1,127 @@
package domain
import (
"sort"
"strings"
"git.cin.su/m/Assistant/contracts/interaction"
)
// PersonalMemory is a rebuildable context projection. Its source of truth is
// the append-only human utterance history; it is deliberately not a second
// canonical store. Each fact retains the source utterance and confidence so a
// later cognitive or capability route can distinguish a human statement from
// an externally verified fact.
type PersonalMemory struct {
Facts []PersonalMemoryFact
}
type PersonalMemoryFact struct {
Kind string
Value string
ConfidenceMillis int64
SourceUtteranceID interaction.HumanUtteranceID
ObservedAtUnixMillis int64
}
const personalMemoryCurrentLocation = "CURRENT_LOCATION"
// CompilePersonalMemory turns direct, first-person human statements into a
// small typed context. It deliberately preserves preferences as statements
// rather than pretending that an arbitrary preference is a verified fact.
func CompilePersonalMemory(history []interaction.HumanUtterance) PersonalMemory {
latestLocation := PersonalMemoryFact{}
preferences := make([]PersonalMemoryFact, 0, 4)
for _, utterance := range history {
if location := personalCurrentLocation(utterance.Content); location != "" {
fact := PersonalMemoryFact{
Kind: personalMemoryCurrentLocation,
Value: location,
ConfidenceMillis: 950,
SourceUtteranceID: utterance.ID,
ObservedAtUnixMillis: utterance.ReceivedAtUnixMillis,
}
if fact.ObservedAtUnixMillis >= latestLocation.ObservedAtUnixMillis {
latestLocation = fact
}
}
if preference := personalPreference(utterance.Content); preference != "" {
preferences = append(preferences, PersonalMemoryFact{
Kind: "PREFERENCE",
Value: preference,
ConfidenceMillis: 900,
SourceUtteranceID: utterance.ID,
ObservedAtUnixMillis: utterance.ReceivedAtUnixMillis,
})
}
}
result := PersonalMemory{Facts: make([]PersonalMemoryFact, 0, 1+len(preferences))}
if latestLocation.Kind != "" {
result.Facts = append(result.Facts, latestLocation)
}
sort.SliceStable(preferences, func(left, right int) bool {
return preferences[left].ObservedAtUnixMillis > preferences[right].ObservedAtUnixMillis
})
if len(preferences) > 8 {
preferences = preferences[:8]
}
result.Facts = append(result.Facts, preferences...)
return result
}
func (m PersonalMemory) CurrentLocation() string {
for _, fact := range m.Facts {
if fact.Kind == personalMemoryCurrentLocation {
return fact.Value
}
}
return ""
}
// ContextText is compact, source-aware context for a cognitive or skill
// request. It contains facts rather than a copied chat transcript.
func (m PersonalMemory) ContextText() string {
lines := make([]string, 0, len(m.Facts))
for _, fact := range m.Facts {
value := strings.TrimSpace(fact.Value)
if value == "" {
continue
}
switch fact.Kind {
case personalMemoryCurrentLocation:
lines = append(lines, "Текущее место пользователя (его сообщение): "+value)
case "PREFERENCE":
lines = append(lines, "Предпочтение пользователя (его сообщение): "+value)
}
}
return strings.Join(lines, "\n")
}
func personalCurrentLocation(message string) string {
tokens := semanticTokens(message)
if len(tokens) < 4 || tokens[0] != "я" || !containsStemInTokens(tokens, "сейчас", "нахож", "жив") {
return ""
}
for index, token := range tokens {
if (token == "в" || token == "на") && index+1 < len(tokens) {
return capitalizeWord(tokens[index+1])
}
}
return ""
}
func personalPreference(message string) string {
lower := strings.ToLower(strings.TrimSpace(message))
for _, cue := range []string{"мне нравится", "я люблю"} {
index := strings.Index(lower, cue)
if index < 0 {
continue
}
value := strings.TrimSpace(lower[index+len(cue):])
value = strings.Trim(value, " .,!?:;—-")
if len([]rune(value)) >= 2 {
return value
}
}
return ""
}
@@ -0,0 +1,30 @@
package domain
import (
"strings"
"testing"
"git.cin.su/m/Assistant/contracts/interaction"
)
func TestCompilePersonalMemoryKeepsLatestLocationAndPreferences(t *testing.T) {
memory := CompilePersonalMemory([]interaction.HumanUtterance{
{ID: "location-old", Content: "я сейчас в Санкт-Петербурге", ReceivedAtUnixMillis: 100},
{ID: "color", Content: "мне нравится красный цвет", ReceivedAtUnixMillis: 200},
{ID: "location-new", Content: "я сейчас в Москве", ReceivedAtUnixMillis: 300},
})
if got := memory.CurrentLocation(); got != "Москве" {
t.Fatalf("current location = %q", got)
}
context := memory.ContextText()
if !strings.Contains(context, "Москве") || !strings.Contains(context, "красный цвет") || strings.Contains(context, "Санкт-Петербурге") {
t.Fatalf("unexpected compact memory context: %q", context)
}
}
func TestCompilePersonalMemoryDoesNotTreatThirdPartyStatementAsPersonalFact(t *testing.T) {
memory := CompilePersonalMemory([]interaction.HumanUtterance{{Content: "Погода сейчас в Москве", ReceivedAtUnixMillis: 100}})
if memory.CurrentLocation() != "" || memory.ContextText() != "" {
t.Fatalf("ordinary factual question became personal memory: %+v", memory)
}
}
@@ -108,6 +108,19 @@ func TestContinueTravelOrigin(t *testing.T) {
} }
} }
func TestContinueTravelDate(t *testing.T) {
history := []interaction.HumanUtterance{{Content: "Найди билеты до Ялты", ReceivedAtUnixMillis: 100}}
if got := ContinueTravelDate("сегодня", history); got != "Найди билеты до Ялты сегодня" {
t.Fatalf("date answer did not complete ticket search: %q", got)
}
if got := ContinueTravelDate("завтра", []interaction.HumanUtterance{{Content: "Найди билеты до Ялты сегодня", ReceivedAtUnixMillis: 100}}); got != "" {
t.Fatalf("dated ticket search must not be continued again: %q", got)
}
if got := ContinueTravelDate("сегодня", []interaction.HumanUtterance{{Content: "Какая погода в Ялте?", ReceivedAtUnixMillis: 100}}); got != "" {
t.Fatalf("date answer must not create travel work without travel context: %q", got)
}
}
func TestTravelSearchClarification(t *testing.T) { func TestTravelSearchClarification(t *testing.T) {
if got := TravelSearchClarification("Найди билеты", nil); got == "" { if got := TravelSearchClarification("Найди билеты", nil); got == "" {
t.Fatal("underspecified travel request must ask for missing route and date") t.Fatal("underspecified travel request must ask for missing route and date")
@@ -159,6 +172,51 @@ func TestTravelSearchQueryCarriesNearestFlightDate(t *testing.T) {
} }
} }
func TestTravelResearchQueryUsesKnownOriginForDistance(t *testing.T) {
history := []interaction.HumanUtterance{{Content: "я сейчас в Москве"}}
got := TravelResearchQuery("сколько километров до Сочи?", history, time.Time{})
if got != "расстояние между Москве и Сочи в километрах по прямой и по дороге" {
t.Fatalf("distance query lost route context: %q", got)
}
}
func TestTravelRouteWithKnownOriginDoesNotAskForTicketDate(t *testing.T) {
history := []interaction.HumanUtterance{{Content: "я сейчас в Москве"}}
if got := TravelSearchClarification("как можно добраться до Сочи?", history); got != "" {
t.Fatalf("general route was incorrectly reduced to ticket clarification: %q", got)
}
got := TravelResearchQuery("как можно добраться до Сочи?", history, time.Time{})
if got != "способы добраться из Москве в Сочи: самолет поезд автобус автомобиль" {
t.Fatalf("general route query lost known route context: %q", got)
}
}
func TestTravelContextUsesNewestLocationRegardlessOfRepositoryOrder(t *testing.T) {
history := []interaction.HumanUtterance{
{Content: "я сейчас в Санкт-Петербурге", ReceivedAtUnixMillis: 200},
{Content: "я сейчас в Москве", ReceivedAtUnixMillis: 300},
{Content: "я сейчас в Казани", ReceivedAtUnixMillis: 100},
}
if got := TravelSearchClarification("какой ближайший рейс до Сочи?", history); got != "" {
t.Fatalf("newest remembered origin was not applied: %q", got)
}
if got := TravelResearchQuery("какой ближайший рейс до Сочи?", history, time.Time{}); !strings.Contains(got, "пункт отправления: Москве") {
t.Fatalf("newest origin missing from travel research query: %q", got)
}
}
func TestNearestPlaneUsesTravelContextAndCurrentDay(t *testing.T) {
now := time.Date(2026, time.August, 25, 18, 0, 0, 0, time.UTC)
history := []interaction.HumanUtterance{{Content: "я сейчас в Москве", ReceivedAtUnixMillis: 100}}
query := TravelResearchQuery("найди ближайший самолет до Казани", history, now)
if !strings.Contains(query, "сегодня 25.08.2026") || !strings.Contains(query, "пункт отправления: Москве") {
t.Fatalf("nearest plane query lost current context: %q", query)
}
if got := TravelSearchClarification("найди ближайший самолет до Казани", history); got != "" {
t.Fatalf("known origin and nearest-time meaning should proceed, got %q", got)
}
}
func TestInterpretUtteranceDirectiveRecordsOutcomeWithoutExecution(t *testing.T) { func TestInterpretUtteranceDirectiveRecordsOutcomeWithoutExecution(t *testing.T) {
result := interpretForTest(t, "Поменяй базу на УПО1.", activeFocus("upo", "УПО"), "") result := interpretForTest(t, "Поменяй базу на УПО1.", activeFocus("upo", "УПО"), "")
if result.Interpretation.SpeechAct != interaction.SpeechActDirective { if result.Interpretation.SpeechAct != interaction.SpeechActDirective {
@@ -2,6 +2,8 @@ package domain
import "strings" import "strings"
import "git.cin.su/m/Assistant/contracts/interaction"
// TaskDecomposition is the small, typed intermediate representation used // TaskDecomposition is the small, typed intermediate representation used
// before a capability is called. It separates the user's goal from the // before a capability is called. It separates the user's goal from the
// object, source and target instead of treating the whole sentence as a // object, source and target instead of treating the whole sentence as a
@@ -38,6 +40,51 @@ func DecomposeTask(message string) TaskDecomposition {
return DecomposeTaskWithLexicon(message, TaskLexicon{}) return DecomposeTaskWithLexicon(message, TaskLexicon{})
} }
// TaskLexiconFromHistory rebuilds learned search-source aliases from ordinary
// human utterances. The fact remains user-owned conversational memory; core
// code never embeds mutable marketplace or provider names.
//
// A source fact has the deliberately explicit form:
// "запомни: <alias> — это <source>, источник для поиска".
func TaskLexiconFromHistory(history []interaction.HumanUtterance) TaskLexicon {
lexicon := TaskLexicon{}
for _, utterance := range history {
message := strings.TrimSpace(utterance.Content)
lower := strings.ToLower(message)
if !strings.Contains(lower, "источник") || !strings.Contains(lower, "поиск") || !strings.Contains(lower, "это") {
continue
}
before, after, found := strings.Cut(lower, "это")
if !found {
continue
}
alias := strings.TrimSpace(strings.TrimPrefix(before, "запомни:"))
alias = strings.Trim(alias, " \t—-:;,")
value := strings.TrimSpace(after)
if index := strings.IndexAny(value, ",;."); index >= 0 {
value = strings.TrimSpace(value[:index])
}
if len([]rune(alias)) < 2 || len([]rune(value)) < 2 {
continue
}
lexicon.SourceAliases = append(lexicon.SourceAliases, TaskLexiconEntry{Alias: alias, Value: value})
}
return lexicon
}
// SearchQueryWithLexicon keeps a learned source in the external query without
// turning its alias into core vocabulary.
func SearchQueryWithLexicon(message string, lexicon TaskLexicon) string {
decomposition := DecomposeTaskWithLexicon(message, lexicon)
if decomposition.Intent == TaskIntentSearch && decomposition.Source != "" {
if decomposition.Target != "" {
return decomposition.Target + " " + decomposition.Source
}
return strings.TrimSpace(message) + " " + decomposition.Source
}
return strings.TrimSpace(message)
}
// DecomposeTaskWithLexicon performs a cheap semantic pass. The lexicon is // DecomposeTaskWithLexicon performs a cheap semantic pass. The lexicon is
// intentionally an input: a remembered alias may be revalidated or replaced // intentionally an input: a remembered alias may be revalidated or replaced
// without changing the parser or shipping a new hard-coded branch. // without changing the parser or shipping a new hard-coded branch.
+93 -23
View File
@@ -21,6 +21,41 @@ func TravelSearchQuery(message string, now time.Time) string {
return cleaned + " сегодня " + now.Format("02.01.2006") return cleaned + " сегодня " + now.Format("02.01.2006")
} }
// TravelResearchQuery keeps route and distance questions tied to a known
// origin before they reach a generic web search. The history is semantic
// context, not a list of example-specific answers.
func TravelResearchQuery(message string, history []interaction.HumanUtterance, now time.Time) string {
query := TravelSearchQuery(message, now)
tokens := semanticTokens(StripAssistantVocative(message))
if containsStemInTokens(tokens, "расстоян", "километр") {
origin := travelContextOrigin(history)
destination := travelContextDestinationFromTokens(tokens)
if origin != "" && destination != "" {
return "расстояние между " + origin + " и " + destination + " в километрах по прямой и по дороге"
}
if origin != "" && !containsStemInTokens(tokens, "из", "откуда", "от") {
query += " точка отправления: " + origin
}
query += " расстояние по прямой и по дороге"
} else if containsStemInTokens(tokens, "добрат", "маршрут") {
origin := travelContextOrigin(history)
destination := travelContextDestinationFromTokens(tokens)
if origin != "" && destination != "" {
return "способы добраться из " + origin + " в " + destination + ": самолет поезд автобус автомобиль"
}
if origin != "" && !containsStemInTokens(tokens, "из", "откуда", "от") {
query += " отправление из " + origin
}
} else if travelCue(tokens) && !containsStemInTokens(tokens, "из", "откуда", "от") {
if origin := travelContextOrigin(history); origin != "" {
// Preserve the remembered location as an explicit search parameter
// instead of guessing its grammatical form in the user's language.
query += " пункт отправления: " + origin
}
}
return query
}
// StripAssistantVocative removes a leading assistant name used as an address. // StripAssistantVocative removes a leading assistant name used as an address.
// The original utterance remains the historical source; this value is only for // The original utterance remains the historical source; this value is only for
// interpretation, cognitive prompts and external queries. // interpretation, cognitive prompts and external queries.
@@ -153,6 +188,34 @@ func ContinueTravelOrigin(message string, history []interaction.HumanUtterance)
return strings.TrimSpace(previous + preposition + location) return strings.TrimSpace(previous + preposition + location)
} }
// ContinueTravelDate completes the most recent unfinished ticket search with
// a short date answer. The date is still the human's original wording, so the
// later route and research stages retain its provenance and can interpret it
// relative to the current time.
func ContinueTravelDate(message string, history []interaction.HumanUtterance) string {
current := strings.TrimSpace(StripAssistantVocative(message))
currentTokens := semanticTokens(current)
if len(currentTokens) == 0 || len(currentTokens) > 6 || !isTravelDateSpecified(currentTokens) {
return ""
}
latestAt := int64(-1)
latest := ""
for _, utterance := range history {
tokens := semanticTokens(utterance.Content)
if !travelCue(tokens) || isTravelDateSpecified(tokens) || containsStemInTokens(tokens, "ближ") {
continue
}
if utterance.ReceivedAtUnixMillis >= latestAt {
latestAt = utterance.ReceivedAtUnixMillis
latest = strings.TrimSpace(StripAssistantVocative(utterance.Content))
}
}
if latest == "" {
return ""
}
return strings.TrimSpace(latest + " " + current)
}
// TravelSearchClarification keeps an incomplete travel request in dialogue // TravelSearchClarification keeps an incomplete travel request in dialogue
// instead of reducing it to an unrelated generic web search. // instead of reducing it to an unrelated generic web search.
func TravelSearchClarification(message string, history []interaction.HumanUtterance) string { func TravelSearchClarification(message string, history []interaction.HumanUtterance) string {
@@ -186,13 +249,7 @@ func TravelSearchClarification(message string, history []interaction.HumanUttera
} }
} }
} }
if origin && destination && date {
return ""
}
ticketRequest := containsStemInTokens(current, "билет", "рейс", "самолет", "самолёт", "вылет") ticketRequest := containsStemInTokens(current, "билет", "рейс", "самолет", "самолёт", "вылет")
if !ticketRequest && origin && destination {
return ""
}
if !destination { if !destination {
if contextDestination := travelContextDestination(history); contextDestination != "" { if contextDestination := travelContextDestination(history); contextDestination != "" {
destination = true destination = true
@@ -209,6 +266,9 @@ func TravelSearchClarification(message string, history []interaction.HumanUttera
origin = true origin = true
} }
} }
if origin && destination && (date || !ticketRequest) {
return ""
}
if destination && !origin && !date { if destination && !origin && !date {
if !ticketRequest { if !ticketRequest {
return "Из какого города выезжать в " + destinationLabel(current, history) + "? Подберу самолёт, поезд, автобус или машину." return "Из какого города выезжать в " + destinationLabel(current, history) + "? Подберу самолёт, поезд, автобус или машину."
@@ -219,6 +279,9 @@ func TravelSearchClarification(message string, history []interaction.HumanUttera
return "Из какого города вылетать?" return "Из какого города вылетать?"
} }
if destination && !date { if destination && !date {
if !ticketRequest {
return ""
}
return "На какую дату нужны билеты?" return "На какую дату нужны билеты?"
} }
return "Уточните маршрут и дату: откуда, куда и на какой день нужны билеты?" return "Уточните маршрут и дату: откуда, куда и на какой день нужны билеты?"
@@ -252,9 +315,23 @@ func destinationLabel(current []string, history []interaction.HumanUtterance) st
return "пункт назначения" return "пункт назначения"
} }
func travelContextDestinationFromTokens(tokens []string) string {
for index, token := range tokens {
if token != "до" && token != "в" && token != "к" {
continue
}
if index+1 < len(tokens) && len([]rune(tokens[index+1])) >= 3 {
return capitalizeWord(tokens[index+1])
}
}
return ""
}
func travelContextDestination(history []interaction.HumanUtterance) string { func travelContextDestination(history []interaction.HumanUtterance) string {
for index := len(history) - 1; index >= 0; index-- { latestAt := int64(-1)
tokens := semanticTokens(history[index].Content) latest := ""
for _, utterance := range history {
tokens := semanticTokens(utterance.Content)
if !travelContextCue(tokens) { if !travelContextCue(tokens) {
continue continue
} }
@@ -263,26 +340,19 @@ func travelContextDestination(history []interaction.HumanUtterance) string {
continue continue
} }
if tokenIndex+1 < len(tokens) && len([]rune(tokens[tokenIndex+1])) >= 3 { if tokenIndex+1 < len(tokens) && len([]rune(tokens[tokenIndex+1])) >= 3 {
return capitalizeWord(tokens[tokenIndex+1]) if utterance.ReceivedAtUnixMillis >= latestAt {
latestAt = utterance.ReceivedAtUnixMillis
latest = capitalizeWord(tokens[tokenIndex+1])
}
break
} }
} }
} }
return "" return latest
} }
func travelContextOrigin(history []interaction.HumanUtterance) string { func travelContextOrigin(history []interaction.HumanUtterance) string {
for index := len(history) - 1; index >= 0; index-- { return CompilePersonalMemory(history).CurrentLocation()
tokens := semanticTokens(history[index].Content)
if len(tokens) < 3 || tokens[0] != "я" || !containsStemInTokens(tokens, "сейчас", "нахож", "жив") {
continue
}
for tokenIndex, token := range tokens {
if (token == "в" || token == "из") && tokenIndex+1 < len(tokens) {
return capitalizeWord(tokens[tokenIndex+1])
}
}
}
return ""
} }
func travelContextCue(tokens []string) bool { func travelContextCue(tokens []string) bool {
@@ -298,7 +368,7 @@ func capitalizeWord(value string) string {
} }
func travelCue(tokens []string) bool { func travelCue(tokens []string) bool {
return containsStemInTokens(tokens, "билет", "рейс", "поезд", "автобус", "перелет", "перелёт") return containsStemInTokens(tokens, "билет", "рейс", "самолет", "самолёт", "вылет", "поезд", "автобус", "перелет", "перелёт")
} }
func travelFollowUpCue(tokens []string) bool { func travelFollowUpCue(tokens []string) bool {