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
m 5fb616310d Merge remote-tracking branch 'origin/main' into codex/household-time-reply-priority
CI / test (push) Successful in 1m18s
CI / test (pull_request) Successful in 1m24s
2026-08-25 19:08:15 +03:00
m 5a9cf7a22d Preserve direct time difference replies
CI / test (push) Failing after 51s
CI / test (pull_request) Failing after 48s
2026-08-25 19:06:51 +03:00
m d649f79ca4 Merge pull request 'Preserve remembered preference identity' (#366) from codex/household-checklist-live-preference-fix into main
CI / test (push) Successful in 1m58s
Reviewed-on: #366
2026-08-25 16:00:08 +00:00
m ffce659332 Merge remote-tracking branch 'origin/main' into codex/household-checklist-live-preference-fix
CI / test (push) Successful in 1m10s
CI / test (pull_request) Successful in 1m24s
2026-08-25 18:57:06 +03:00
m 24b30bf669 Preserve remembered preference identity
CI / test (push) Failing after 51s
CI / test (pull_request) Failing after 50s
2026-08-25 18:55:33 +03:00
m 1bd9137761 Merge pull request 'Add executable 50-point household checklist' (#365) from codex/household-media-queue-isolation into main
CI / test (push) Successful in 1m39s
Reviewed-on: #365
2026-08-25 15:49:39 +00:00
m f895c5a104 Merge remote-tracking branch 'origin/main' into codex/household-media-queue-isolation
CI / test (push) Successful in 1m10s
CI / test (pull_request) Successful in 1m14s
2026-08-25 18:46:10 +03:00
m d0074709aa Add executable 50-point household checklist
CI / test (push) Failing after 49s
CI / test (pull_request) Failing after 50s
2026-08-25 18:44:49 +03:00
m 982eb6f49b Merge pull request 'Do not block image generation on general cognition' (#364) from codex/household-media-queue-isolation into main
CI / test (push) Successful in 1m24s
Reviewed-on: #364
2026-08-25 15:28:35 +00:00
m b1ee085de4 Merge remote-tracking branch 'origin/main' into codex/household-media-queue-isolation
CI / test (push) Successful in 1m12s
CI / test (pull_request) Successful in 1m15s
2026-08-25 18:25:37 +03:00
m 2c66a44910 Do not block media routes on general cognition
CI / test (push) Failing after 1m6s
CI / test (pull_request) Failing after 57s
2026-08-25 18:22:38 +03:00
m b95714a71e Merge pull request 'Isolate media cancellation and improve travel answers' (#363) from codex/household-media-queue-isolation into main
CI / test (push) Successful in 1m19s
Reviewed-on: #363
2026-08-25 15:18:22 +00:00
m 6183d811f1 Merge remote-tracking branch 'origin/main' into codex/household-media-queue-isolation
CI / test (push) Successful in 1m12s
CI / test (pull_request) Successful in 1m10s
2026-08-25 18:14:52 +03:00
m 6a2ed287ba Keep flight formatting within task scope
CI / test (push) Failing after 51s
CI / test (pull_request) Failing after 49s
2026-08-25 18:12:39 +03:00
m d342728b46 Improve nearest flight research answers
CI / test (push) Failing after 51s
2026-08-25 18:12:13 +03:00
m f121445f24 Preserve media failures and enrich nearest flight searches
CI / test (push) Failing after 52s
2026-08-25 18:08:48 +03:00
m 124871da76 Cancel only the owned ComfyUI prompt
CI / test (push) Failing after 54s
2026-08-25 18:02:59 +03:00
m 2062094228 Merge pull request 'Route creative image requests to media generation' (#362) from codex/household-scenario-audit into main
CI / test (push) Successful in 1m42s
Reviewed-on: #362
2026-08-25 14:42:39 +00:00
23 changed files with 1095 additions and 101 deletions
+39
View File
@@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"net/textproto"
@@ -275,6 +276,20 @@ func (c ComfyImageGenerationClient) Generate(ctx context.Context, model, prompt,
if accepted.PromptID == "" {
return GeneratedImage{}, ErrEmptyResult
}
// A caller timeout must remove only this prompt. ComfyUI's global
// /interrupt endpoint can otherwise stop unrelated users' work and leave
// queued requests in an ambiguous state.
defer func() {
if ctx.Err() != nil {
cancelCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := c.cancelPrompt(cancelCtx, accepted.PromptID); err != nil {
// The original context error is more useful to the caller; the
// provider cleanup failure remains observable in the server log.
log.Printf("comfy prompt cleanup failed for %s: %v", accepted.PromptID, err)
}
}
}()
interval := c.PollInterval
if interval <= 0 {
@@ -306,6 +321,30 @@ func (c ComfyImageGenerationClient) Generate(ctx context.Context, model, prompt,
}
}
func (c ComfyImageGenerationClient) cancelPrompt(ctx context.Context, promptID string) error {
if strings.TrimSpace(promptID) == "" {
return errors.New("comfy prompt id is empty")
}
payload, err := json.Marshal(map[string][]string{"delete": {promptID}})
if err != nil {
return err
}
request, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(c.BaseURL, "/")+"/queue", bytes.NewReader(payload))
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/json")
response, err := c.client().Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode > 299 {
return fmt.Errorf("comfy prompt cleanup status %d", response.StatusCode)
}
return nil
}
func (c ComfyImageGenerationClient) historyImage(ctx context.Context, promptID string) (GeneratedImage, bool, error) {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(c.BaseURL, "/")+"/history/"+url.PathEscape(promptID), nil)
if err != nil {
+40
View File
@@ -3,6 +3,7 @@ package multimodal
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
@@ -167,3 +168,42 @@ func TestComfyImageGenerationClientRunsWorkflowAndReturnsImage(t *testing.T) {
t.Fatalf("image=%+v err=%v", image, err)
}
}
func TestComfyImageGenerationClientDeletesOnlyCancelledPrompt(t *testing.T) {
var deleted []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/prompt":
_ = json.NewEncoder(w).Encode(map[string]string{"prompt_id": "cancel-me"})
case "/history/cancel-me":
<-r.Context().Done()
case "/queue":
var payload struct {
Delete []string `json:"delete"`
}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
t.Fatal(err)
}
deleted = append(deleted, payload.Delete...)
w.WriteHeader(http.StatusNoContent)
default:
http.NotFound(w, r)
}
}))
defer server.Close()
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() {
_, err := (ComfyImageGenerationClient{BaseURL: server.URL, Client: server.Client(), PollInterval: time.Millisecond, PollTimeout: time.Minute}).Generate(ctx, "", "red bird", "256x256")
done <- err
}()
time.Sleep(10 * time.Millisecond)
cancel()
if err := <-done; !errors.Is(err, context.Canceled) {
t.Fatalf("err=%v", err)
}
if len(deleted) != 1 || deleted[0] != "cancel-me" {
t.Fatalf("deleted=%v", deleted)
}
}
+37 -1
View File
@@ -2,6 +2,7 @@ package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
@@ -38,7 +39,8 @@ func (g multimodalGateway) handler(operation capability.MultimodalOperation) htt
http.Error(w, "local image generation capability unavailable", http.StatusBadGateway)
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) == "" {
logMultimodalFailure(operation, err)
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) {
// Keep provider details in server diagnostics; never return them to chat.
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) {
server := multimodalGateway{now: time.Now}
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
}
// 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)
}
}
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
// into a natural answer. The draft remains the safe fallback when cognition is
// 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()
if err != nil {
return "", err
}
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.Path = "/v1/advisories"
payload, err := json.Marshal(cognitive.GatewayAdvisoryRequest{
Version: cognitive.CreatorAdvisoryV1, RequestID: cognitive.RequestID(requestID),
ActorID: session.ActorID, PrincipalID: session.PrincipalID,
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{
SpeechAct: "RESPONSE_REVIEW",
CapabilityHints: meaning.CapabilityHints,
@@ -25,6 +25,9 @@ func TestReviewResponseUsesCognitiveGatewayAndReturnsOnlyDraftAnswer(t *testing.
if request.Message == "" || request.Meaning.SpeechAct == "" {
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")
_ = 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 {
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 {
t.Fatal(err)
}
@@ -0,0 +1,25 @@
package main
import (
"testing"
"git.cin.su/m/Assistant/contracts/interaction"
)
func TestSpecializedInformationReplyIsNotOverwrittenByResearch(t *testing.T) {
for _, kind := range []interaction.InformationRequestKind{
interaction.InformationRequestMemoryInventory,
interaction.InformationRequestTimeDifference,
interaction.InformationRequestCapabilityInventory,
interaction.InformationRequestCognitiveModelInventory,
interaction.InformationRequestCognitiveChannelStatus,
interaction.InformationRequestCognitiveRecovery,
} {
if shouldRunGeneralResearch(kind) {
t.Fatalf("specialized information request %q must bypass general research", kind)
}
}
if !shouldRunGeneralResearch("") {
t.Fatal("ordinary research requests must still use general research")
}
}
+149 -13
View File
@@ -511,6 +511,7 @@ func main() {
}
var effectiveTaskMessage = interactiondomain.StripAssistantVocative(utterance.Content)
creativeUserRequest := interactiondomain.IsCreativeRequest(utterance.Content)
locationReply := interactiondomain.LocationContextReply(utterance.Content)
continuationMessage := ""
travelContinuation := false
var previousTask *interaction.HumanUtterance
@@ -532,7 +533,12 @@ func main() {
log.Printf("interaction principal history loaded: %d utterances", len(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 != "" {
continuationMessage = continuation
effectiveTaskMessage = continuation
@@ -540,6 +546,10 @@ func main() {
continuationMessage = continuation
travelContinuation = true
effectiveTaskMessage = continuation
} else if continuation := interactiondomain.ContinueTravelDate(effectiveTaskMessage, conversationHistory); continuation != "" {
continuationMessage = continuation
travelContinuation = true
effectiveTaskMessage = continuation
}
}
if request.ConversationID != "" && interactiondomain.IsRetryRequest(utterance.Content) {
@@ -566,7 +576,11 @@ func main() {
continuedSemantic, continuedErr := interactiondomain.InterpretUtterance(continuedUtterance, projects, previousFocus, now)
if continuedErr == nil {
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
}
}
@@ -599,8 +613,11 @@ func main() {
}
}
}
locationReply := interactiondomain.LocationContextReply(utterance.Content)
if locationReply != "" {
continuationMessage = ""
travelContinuation = false
effectiveTaskMessage = interactiondomain.StripAssistantVocative(utterance.Content)
previousTask = nil
semantic.Reply = locationReply
semantic.NeedsCognition = false
semantic.Interpretation.NeedsCognition = false
@@ -616,6 +633,7 @@ func main() {
assistantName = latestAssistantName(conversationHistory)
}
identityReply := ""
memoryInstructionReply := ""
log.Printf("interaction identity context: name=%q history=%d", assistantName, len(conversationHistory))
if interactiondomain.IsIdentityInquiry(utterance.Content) && assistantName != "" {
identityReply = "Меня зовут " + assistantName + ". Я Домовой, ваш помощник."
@@ -625,14 +643,30 @@ func main() {
semantic.Interpretation.Applicability = interaction.SemanticApplicable
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
deterministicReply := semantic.Reply
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
cognitiveAvailable := true
semanticInterpretationRequested := shouldRequestSemanticInterpretation(semantic)
semanticReflexAudit := shouldAuditDeterministicReflex(semantic, string(utterance.ID), now)
if identityReply != "" {
// A selected specialized route already has an executable semantic outcome.
// Do not block it on the general cognitive channel: research and image
// generation must reach their own adapters even when cognition is degraded.
if specializedRouteBypassesGeneralInterpretation(routePlan) {
semanticInterpretationRequested = false
semanticReflexAudit = false
}
if identityReply != "" || memoryInstructionReply != "" {
semanticReflexAudit = false
}
if semanticInterpretationRequested || semanticReflexAudit {
@@ -744,6 +778,9 @@ func main() {
case interaction.InformationRequestTimeDifference:
planningReply = humanTimeDifferenceReply(effectiveTaskMessage)
needsCognition = false
case interaction.InformationRequestResearchFailureExplanation:
planningReply = "Я не выдаю предположение как факт, если не получил согласованных проверяемых данных. Могу повторить поиск, уточнить запрос или проверить другой источник."
needsCognition = false
case interaction.InformationRequestCapabilityInventory:
kinds, err := capabilityRepository.AvailableCapabilityKinds(r.Context(), session.PrincipalID)
if err == nil && len(kinds) > 0 {
@@ -752,17 +789,24 @@ func main() {
planningReply = "Я умею общаться, сохранять контекст, искать проверяемую информацию и работать с подключёнными моделями. Дополнительные действия подключаются отдельно."
}
needsCognition = false
case interaction.InformationRequestLocalCapabilityInventory:
planningReply = "Без внешних моделей я могу поддерживать разговор, хранить контекст, вести цели и напоминания, а также честно сообщать состояние подключённых возможностей."
needsCognition = false
case interaction.InformationRequestCognitiveModelInventory:
candidates, inventoryErr := capabilityRepository.LoadCognitiveCandidates(r.Context(), capability.CapabilityID("creator-advisory"), session.PrincipalID)
planningReply = humanCognitiveModelInventory(candidates, inventoryErr)
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:
health, healthErr := capabilityRepository.LoadHealth(r.Context(), capability.CapabilityID("cognitive-proposal"))
planningReply = humanCognitiveChannelReply(semantic.InformationRequestKind, semantic.Interpretation.SpeechAct, health, healthErr)
needsCognition = false
}
researchBacked := false
if hasChatRoute(routePlan, chatRouteResearch) && semantic.Interpretation.Clarification != interaction.ClarificationRequired {
if hasChatRoute(routePlan, chatRouteResearch) && semantic.Interpretation.Clarification != interaction.ClarificationRequired && shouldRunGeneralResearch(semantic.InformationRequestKind) {
if planID, idErr := ids.New(); idErr == nil {
parts := interactiondomain.IndependentRequestParts(effectiveTaskMessage)
replies := make([]string, 0, len(parts))
@@ -771,10 +815,13 @@ func main() {
replies = append(replies, "По запросу «"+part+"»: "+clarification)
continue
}
learnedLexicon := interactiondomain.TaskLexiconFromHistory(conversationHistory)
searchQuery := interactiondomain.SearchQueryWithLexicon(part, learnedLexicon)
searchQuery = interactiondomain.TravelResearchQuery(searchQuery, conversationHistory, now)
researchCtx, cancelResearch := context.WithTimeout(r.Context(), 8*time.Second)
result, researchErr := researchClient.SearchWeb(researchCtx, epistemics.WebSearchRequest{
Plan: epistemics.ResearchPlan{ID: epistemics.ResearchPlanID(fmt.Sprintf("plan:%s:%d", planID, index)), Question: part, SourceClasses: []string{"web-search"}, FreshnessPolicy: "current"},
PropositionKey: fmt.Sprintf("question:%s:%d", utterance.ID, index), Query: part,
Plan: epistemics.ResearchPlan{ID: epistemics.ResearchPlanID(fmt.Sprintf("plan:%s:%d", planID, index)), Question: searchQuery, SourceClasses: []string{"web-search"}, FreshnessPolicy: "current"},
PropositionKey: fmt.Sprintf("question:%s:%d", utterance.ID, index), Query: searchQuery,
})
cancelResearch()
reply, backed := renderResearchReply(part, result, researchErr)
@@ -821,7 +868,9 @@ func main() {
var reminder *continuity.ProspectiveItem
var generatedImage capability.MultimodalResponse
mediaHandled := false
mediaAttempted := false
if hasChatRoute(routePlan, chatRouteMedia) && semantic.Interpretation.Clarification != interaction.ClarificationRequired {
mediaAttempted = true
imageCtx, cancelImage := context.WithTimeout(r.Context(), 15*time.Minute)
generatedImage, err = cognitiveClient.GenerateImage(imageCtx, effectiveTaskMessage, "")
cancelImage()
@@ -910,9 +959,13 @@ func main() {
planningReply = identityReply
needsCognition = false
}
if memoryInstructionReply != "" {
planningReply = memoryInstructionReply
needsCognition = false
}
if strings.TrimSpace(planningReply) != "" {
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),
CapabilityHints: toCapabilityKinds(semantic.CapabilityHints),
RequestedOutcome: semantic.Interpretation.RequestedOutcome,
@@ -920,7 +973,7 @@ func main() {
ConfidenceMillis: semantic.Interpretation.ConfidenceMillis,
})
cancelReview()
stableSemanticReply := mediaHandled || 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 {
log.Printf("cognitive response review unavailable: %v", reviewErr)
} else if !stableSemanticReply && (!researchBacked || reviewPreservesResearchEvidence(reviewedReply, planningReply)) {
@@ -929,7 +982,7 @@ func main() {
log.Printf("cognitive response review proposed stable semantic rewrite; preserving semantic reply")
}
}
if !mediaHandled && identityReply == "" && creativeReply == "" && creativeFallbackReply == "" {
if !mediaAttempted && !mediaHandled && identityReply == "" && creativeReply == "" && creativeFallbackReply == "" {
stableAct := interactiondomain.ClassifySpeechAct(utterance.Content, utterance.CorrectsUtteranceID)
travelClarification := ""
if !creativeRequest {
@@ -945,6 +998,11 @@ func main() {
needsCognition = false
planningReply = identityReply
}
if memoryInstructionReply != "" {
semantic.Reply = memoryInstructionReply
needsCognition = false
planningReply = memoryInstructionReply
}
if creativeReply != "" {
semantic.Reply = creativeReply
needsCognition = false
@@ -1579,6 +1637,10 @@ func main() {
}
}
func shouldRunGeneralResearch(kind interaction.InformationRequestKind) bool {
return kind == ""
}
func creatorSessionHandler(bootstrapToken, creatorUsername, creatorPassword string, sessionKey []byte, now func() time.Time) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
authenticated := identitydomain.BootstrapMatches(bootstrapToken, bearerToken(r))
@@ -1699,13 +1761,16 @@ func renderResearchReply(query string, result epistemics.ResearchResult, researc
return "Сейчас не удалось получить данные из подключённого источника. Попробую снова через доступный маршрут.", false
}
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) == "" {
continue
}
if !researchFindingMatchesIntent(query, finding) {
continue
}
excerpt := humanResearchExcerpt(query, finding.Excerpt.Text)
limit := 180
if index > 0 {
if len(lines) > 0 {
limit = 100
}
if len([]rune(excerpt)) > limit {
@@ -1719,6 +1784,12 @@ func renderResearchReply(query string, result epistemics.ResearchResult, researc
if len(lines) == 0 {
return "Проверяемых данных пока не найдено. Могу повторить поиск или уточнить, что именно проверить.", false
}
if isInternetStatusQuery(query) {
return "Интернет работает: Домовой получил ответ от внешних источников.\n\n" + strings.Join(lines, "\n\n"), true
}
if nearestFlightQuery(query) && !containsFlightTimeEvidence(strings.Join(lines, " ")) {
return "Нашёл расписание по маршруту, но точное время ближайшего вылета в доступных фрагментах не указано. Откройте источник и выберите ближайший рейс:\n\n" + strings.Join(lines, "\n\n"), true
}
reply := "Нашёл проверяемые данные:\n\n" + strings.Join(lines, "\n\n")
lowerQuery := strings.ToLower(query)
if (strings.Contains(lowerQuery, "цен") || strings.Contains(lowerQuery, "стоим")) && !containsPriceEvidence(reply) {
@@ -1727,6 +1798,45 @@ func renderResearchReply(query string, result epistemics.ResearchResult, researc
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 {
lower := strings.ToLower(query)
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 {
return regexp.MustCompile(`(?m)\b(?:[01]?\d|2[0-3]):[0-5]\d\b`).MatchString(value)
}
func humanResearchExcerpt(query, raw string) string {
text := strings.Join(strings.Fields(strings.TrimSpace(raw)), " ")
if text == "" {
@@ -1774,7 +1884,13 @@ func humanMemoryInventory(history []interaction.HumanUtterance, assistantName st
lower := strings.ToLower(message)
if (strings.Contains(lower, "нравится") || strings.Contains(lower, "люблю")) && utterance.ReceivedAtUnixMillis >= latestPreferenceAt {
latestPreferenceAt = utterance.ReceivedAtUnixMillis
latestPreference = message
latestPreference = strings.TrimSpace(message)
for _, prefix := range []string{"запомни:", "запомни", "помни:"} {
if strings.HasPrefix(strings.ToLower(latestPreference), prefix) {
latestPreference = strings.TrimSpace(latestPreference[len(prefix):])
break
}
}
}
}
if latestPreference != "" {
@@ -1975,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 {
if strings.TrimSpace(message) == "" {
return "Сейчас не удалось обработать запрос."
+42
View File
@@ -11,6 +11,7 @@ import (
"time"
"git.cin.su/m/Assistant/contracts/capability"
"git.cin.su/m/Assistant/contracts/epistemics"
"git.cin.su/m/Assistant/contracts/interaction"
interactiondomain "git.cin.su/m/Assistant/modules/interaction/domain"
)
@@ -22,6 +23,29 @@ func TestHumanResearchExcerptRemovesSearchResultHeading(t *testing.T) {
}
}
func TestNearestFlightEvidenceDoesNotClaimMissingDepartureTime(t *testing.T) {
if !nearestFlightQuery("ближайший рейс Москва Казань сегодня") {
t.Fatal("nearest flight query was not recognized")
}
if containsFlightTimeEvidence("Казань составляет 1 ч 25 мин. График вылетов доступен онлайн") {
t.Fatal("duration was mistaken for a departure time")
}
if !containsFlightTimeEvidence("Ближайший вылет в 18:40") {
t.Fatal("departure time was not recognized")
}
}
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) {
request := httptest.NewRequest("GET", "/", nil)
request.Header.Set("Authorization", "Basic value")
@@ -64,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) {
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") {
@@ -71,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) {
reply := humanCognitiveChannelReply(interaction.InformationRequestCognitiveRecovery, interaction.SpeechActDirective, capability.Health{State: capability.HealthUnavailable}, nil)
if reply != "Канал мышления недоступен. Домовой остаётся на связи." {
+5 -1
View File
@@ -28,7 +28,11 @@ import (
const (
maxRequestBytes = 8 << 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
+20
View File
@@ -1,6 +1,7 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
@@ -13,6 +14,25 @@ import (
"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) {
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 != "Текущий проект: Домовой" {
+48 -45
View File
@@ -27,51 +27,54 @@ type SemanticCandidateSelectionState string
type InformationRequestKind string
const (
ChannelWebChat Channel = "WEB_CHAT"
ConversationOpen ConversationState = "OPEN"
ConversationArchived ConversationState = "ARCHIVED"
SpeechActDirective SpeechAct = "DIRECTIVE"
SpeechActAssertion SpeechAct = "ASSERTION"
SpeechActDecision SpeechAct = "DECISION"
SpeechActPreference SpeechAct = "PREFERENCE"
SpeechActQuestion SpeechAct = "QUESTION"
SpeechActHypothesis SpeechAct = "HYPOTHESIS"
SpeechActCorrection SpeechAct = "CORRECTION"
SpeechActRequestToInvestigate SpeechAct = "REQUEST_TO_INVESTIGATE"
SpeechActConfirmation SpeechAct = "CONFIRMATION"
SpeechActRejection SpeechAct = "REJECTION"
SpeechActCancellation SpeechAct = "CANCELLATION"
SpeechActConversational SpeechAct = "CONVERSATIONAL"
SpeechActUnknown SpeechAct = "UNKNOWN"
InterpretationRecorded InterpretationState = "RECORDED"
InterpretationInterpreted InterpretationState = "INTERPRETED"
RelationCorrects InteractionRelationKind = "CORRECTS"
RelationRespondsTo InteractionRelationKind = "RESPONDS_TO"
RelationRequestsCognition InteractionRelationKind = "REQUESTS_COGNITION"
RelationCognitionFallback InteractionRelationKind = "COGNITION_FALLBACK"
RelationSupersedes InteractionRelationKind = "SUPERSEDES"
RelationClarifies InteractionRelationKind = "CLARIFIES"
ProjectRolePrimary ProjectReferenceRole = "PRIMARY"
ProjectRoleRelated ProjectReferenceRole = "RELATED"
ProjectRoleReferenceSource ProjectReferenceRole = "REFERENCE_SOURCE"
ClarificationNotRequired ClarificationState = "NOT_REQUIRED"
ClarificationRequired ClarificationState = "REQUIRED"
SemanticApplicable SemanticApplicability = "APPLICABLE"
SemanticLowConfidence SemanticApplicability = "LOW_CONFIDENCE"
SemanticMixedIntent SemanticApplicability = "MIXED_INTENT"
SemanticNeedsBroaderInterpret SemanticApplicability = "NEEDS_BROADER_INTERPRETATION"
SemanticCandidateClarify SemanticApplicability = "CLARIFICATION_REQUIRED"
CandidateSourceDeterministic SemanticCandidateSource = "DETERMINISTIC_V2"
CandidateSourceCognitive SemanticCandidateSource = "COGNITIVE_V1"
CandidateSelected SemanticCandidateSelectionState = "SELECTED"
CandidateObserved SemanticCandidateSelectionState = "OBSERVED"
CandidateRejected SemanticCandidateSelectionState = "REJECTED"
InformationRequestCapabilityInventory InformationRequestKind = "CAPABILITY_INVENTORY"
InformationRequestCognitiveModelInventory InformationRequestKind = "COGNITIVE_MODEL_INVENTORY"
InformationRequestCognitiveChannelStatus InformationRequestKind = "COGNITIVE_CHANNEL_STATUS"
InformationRequestCognitiveRecovery InformationRequestKind = "COGNITIVE_RECOVERY"
InformationRequestMemoryInventory InformationRequestKind = "MEMORY_INVENTORY"
InformationRequestTimeDifference InformationRequestKind = "TIME_DIFFERENCE"
ChannelWebChat Channel = "WEB_CHAT"
ConversationOpen ConversationState = "OPEN"
ConversationArchived ConversationState = "ARCHIVED"
SpeechActDirective SpeechAct = "DIRECTIVE"
SpeechActAssertion SpeechAct = "ASSERTION"
SpeechActDecision SpeechAct = "DECISION"
SpeechActPreference SpeechAct = "PREFERENCE"
SpeechActQuestion SpeechAct = "QUESTION"
SpeechActHypothesis SpeechAct = "HYPOTHESIS"
SpeechActCorrection SpeechAct = "CORRECTION"
SpeechActRequestToInvestigate SpeechAct = "REQUEST_TO_INVESTIGATE"
SpeechActConfirmation SpeechAct = "CONFIRMATION"
SpeechActRejection SpeechAct = "REJECTION"
SpeechActCancellation SpeechAct = "CANCELLATION"
SpeechActConversational SpeechAct = "CONVERSATIONAL"
SpeechActUnknown SpeechAct = "UNKNOWN"
InterpretationRecorded InterpretationState = "RECORDED"
InterpretationInterpreted InterpretationState = "INTERPRETED"
RelationCorrects InteractionRelationKind = "CORRECTS"
RelationRespondsTo InteractionRelationKind = "RESPONDS_TO"
RelationRequestsCognition InteractionRelationKind = "REQUESTS_COGNITION"
RelationCognitionFallback InteractionRelationKind = "COGNITION_FALLBACK"
RelationSupersedes InteractionRelationKind = "SUPERSEDES"
RelationClarifies InteractionRelationKind = "CLARIFIES"
ProjectRolePrimary ProjectReferenceRole = "PRIMARY"
ProjectRoleRelated ProjectReferenceRole = "RELATED"
ProjectRoleReferenceSource ProjectReferenceRole = "REFERENCE_SOURCE"
ClarificationNotRequired ClarificationState = "NOT_REQUIRED"
ClarificationRequired ClarificationState = "REQUIRED"
SemanticApplicable SemanticApplicability = "APPLICABLE"
SemanticLowConfidence SemanticApplicability = "LOW_CONFIDENCE"
SemanticMixedIntent SemanticApplicability = "MIXED_INTENT"
SemanticNeedsBroaderInterpret SemanticApplicability = "NEEDS_BROADER_INTERPRETATION"
SemanticCandidateClarify SemanticApplicability = "CLARIFICATION_REQUIRED"
CandidateSourceDeterministic SemanticCandidateSource = "DETERMINISTIC_V2"
CandidateSourceCognitive SemanticCandidateSource = "COGNITIVE_V1"
CandidateSelected SemanticCandidateSelectionState = "SELECTED"
CandidateObserved SemanticCandidateSelectionState = "OBSERVED"
CandidateRejected SemanticCandidateSelectionState = "REJECTED"
InformationRequestCapabilityInventory InformationRequestKind = "CAPABILITY_INVENTORY"
InformationRequestLocalCapabilityInventory InformationRequestKind = "LOCAL_CAPABILITY_INVENTORY"
InformationRequestCognitiveModelInventory InformationRequestKind = "COGNITIVE_MODEL_INVENTORY"
InformationRequestCognitiveCurrentModel InformationRequestKind = "COGNITIVE_CURRENT_MODEL"
InformationRequestCognitiveChannelStatus InformationRequestKind = "COGNITIVE_CHANNEL_STATUS"
InformationRequestCognitiveRecovery InformationRequestKind = "COGNITIVE_RECOVERY"
InformationRequestMemoryInventory InformationRequestKind = "MEMORY_INVENTORY"
InformationRequestTimeDifference InformationRequestKind = "TIME_DIFFERENCE"
InformationRequestResearchFailureExplanation InformationRequestKind = "RESEARCH_FAILURE_EXPLANATION"
)
type Conversation struct {
+63 -14
View File
@@ -128,6 +128,9 @@ func FallbackText(act interaction.SpeechAct) string {
// of the same request.
func PreferredAssistantName(message string) string {
tokens := semanticTokens(message)
if !hasAssistantNamingTarget(tokens) {
return ""
}
for index, token := range tokens {
if !containsStem(token, "называ", "назов", "зов", "имен") {
continue
@@ -170,6 +173,15 @@ func IsIdentityInquiry(message string) bool {
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 {
id, _ := ids.New()
tokens := semanticTokens(message)
@@ -250,6 +262,9 @@ func semanticScores(tokens []string, hasQuestionMark bool, explicitCorrection bo
if explicitCorrection {
scores[interaction.SpeechActCorrection] += 6
}
if containsStemInTokens(tokens, "опечат", "ошибк", "исправлен") && containsStemInTokens(tokens, "исправ", "поправ") {
scores[interaction.SpeechActCorrection] += 6
}
first := ""
if len(tokens) > 0 {
first = tokens[0]
@@ -301,6 +316,10 @@ func semanticScores(tokens []string, hasQuestionMark bool, explicitCorrection bo
scores[interaction.SpeechActPreference] += 8
scores[interaction.SpeechActAssertion] = 0
}
if containsToken(tokens, "запомни") && containsStemInTokens(tokens, "нрав", "люб", "предпочит") {
scores[interaction.SpeechActPreference] += 6
scores[interaction.SpeechActAssertion] = 0
}
if len(tokens) >= 2 && tokens[0] == "я" && containsStemInTokens(tokens[1:], "настро", "сдела", "исправ", "удал", "созда", "перезапуст", "поменя", "добави") {
scores[interaction.SpeechActAssertion] += 5
}
@@ -355,6 +374,9 @@ func semanticScores(tokens []string, hasQuestionMark bool, explicitCorrection bo
}
func preferredNameFromTokens(tokens []string) bool {
if !hasAssistantNamingTarget(tokens) {
return false
}
for index, token := range tokens {
if !containsStem(token, "называ", "назов", "зов", "имен") {
continue
@@ -369,6 +391,10 @@ func preferredNameFromTokens(tokens []string) bool {
return false
}
func hasAssistantNamingTarget(tokens []string) bool {
return containsToken(tokens, "тебя") || containsToken(tokens, "тебе") || containsToken(tokens, "ты")
}
// IsRetryRequest identifies a short continuation that asks Domovoy to repeat
// the previous task. It deliberately carries no subject-specific knowledge;
// the conversation owner supplies the previous task when available.
@@ -496,19 +522,35 @@ func capabilityHintsFor(primary, secondary interaction.SpeechAct, tokens []strin
add("WEB_RESEARCH")
}
if isCreativeRequestTokens(tokens) {
if isImageCreationRequestTokens(tokens) {
// A correction that quotes a creative phrase is still a correction;
// do not execute the quoted phrase as a side effect.
if isImageCreationRequestTokens(tokens) && primary != interaction.SpeechActCorrection && secondary != interaction.SpeechActCorrection {
add("IMAGE_GENERATION")
} else {
add("COGNITIVE_REASONING")
}
}
if containsStemInTokens(tokens, "голосов", "аудио", "послуш") {
add("SPEECH_TO_TEXT")
}
if containsStemInTokens(tokens, "фотограф", "фото", "картин", "изображ") && containsStemInTokens(tokens, "прочит", "текст", "надпис") {
add("OCR")
} else if containsStemInTokens(tokens, "фотограф", "фото", "картин", "изображ") {
add("IMAGE_UNDERSTANDING")
}
if containsStemInTokens(tokens, "видео", "ролик") {
add("VIDEO_UNDERSTANDING")
}
if containsToken(tokens, "напомни") || containsToken(tokens, "напомин") {
add("SCHEDULE_REMINDER")
}
if containsStemInTokens(tokens, "поставь", "создай", "добавь") && containsStemInTokens(tokens, "цел", "задач", "план") {
add("COGNITIVE_REASONING")
}
if isExplicitEmailAction(tokens) {
add("SEND_EMAIL")
}
if containsToken(tokens, "код") || containsToken(tokens, "патч") || containsToken(tokens, "текст") || containsToken(tokens, "главной") || containsToken(tokens, "чате") {
if containsToken(tokens, "код") || containsToken(tokens, "патч") || containsToken(tokens, "текст") || containsToken(tokens, "главной") || containsToken(tokens, "чате") || containsToken(tokens, "проект") || containsStemInTokens(tokens, "тест") {
if primary == interaction.SpeechActDirective || primary == interaction.SpeechActRequestToInvestigate || secondary == interaction.SpeechActDirective {
add("MODIFY_CODE")
add("RUN_TESTS")
@@ -529,6 +571,9 @@ func capabilityHintsFor(primary, secondary interaction.SpeechAct, tokens []strin
if containsInterrogative(tokens) && containsArithmetic(tokens) {
add("COGNITIVE_REASONING")
}
if isCreativeRequestTokens(tokens) && containsStemInTokens(tokens, "погод", "ресторан", "кафе", "билет", "рейс", "цен", "найд", "узнай", "проверь") {
add("WEB_RESEARCH")
}
if containsToken(tokens, "свободно") || containsToken(tokens, "гб") {
add("VERIFY_FACT")
}
@@ -567,8 +612,9 @@ func sourceDependentQuestion(primary, secondary interaction.SpeechAct, tokens []
currentCue := containsStemInTokens(tokens, "сейчас", "сегодня", "текущ", "актуаль", "последн", "прямо")
observedStateCue := containsStemInTokens(tokens, "погод", "температур", "осад", "ветер", "курс", "цен", "стоим", "новост", "распис", "событ", "статус", "доступен", "работает", "запущен", "срок") || approximateToken(tokens, "погод", 2)
placeSearchCue := containsStemInTokens(tokens, "ресторан", "кафе", "отел", "магаз", "мест", "ближ", "адрес", "организац", "бренд", "товар", "артикул", "продавец", "маркетплейс", "wildberries", "wb")
travelSearchCue := containsStemInTokens(tokens, "билет", "рейс", "поезд", "автобус", "перелет", "перелёт", "отправлен", "прибыт")
return currentCue || observedStateCue || placeSearchCue || travelSearchCue
travelSearchCue := containsStemInTokens(tokens, "билет", "рейс", "самолет", "самолёт", "вылет", "поезд", "автобус", "перелет", "перелёт", "отправлен", "прибыт", "расстоян", "километр", "добрат", "маршрут")
timeDifferenceCue := containsStemInTokens(tokens, "разниц") && containsStemInTokens(tokens, "времен", "час")
return currentCue || observedStateCue || placeSearchCue || travelSearchCue || timeDifferenceCue
}
// approximateToken catches ordinary keyboard slips without turning routing
@@ -624,15 +670,24 @@ func informationRequestKind(message string, candidate interaction.SemanticCandid
if containsStemInTokens(tokens, "разниц") && containsStemInTokens(tokens, "времен", "час") {
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
cognitiveSubject := containsStemInTokens(tokens, "модел", "ии", "ai", "локальн", "когнитив", "канал")
if cognitiveSubject && inquiry && containsStemInTokens(tokens, "какая", "какой", "текущ", "сейчас", "отвеч") && containsStemInTokens(tokens, "модел") {
return interaction.InformationRequestCognitiveCurrentModel
}
inventoryCue := containsStemInTokens(tokens, "список", "доступ", "подключ", "вариант") || (containsMeaningfulInterrogative(tokens) && containsStemInTokens(tokens, "настро"))
inventoryRequest := inquiry || containsStemInTokens(tokens, "напиш", "покаж", "перечисл", "сообщ", "вывед", "предостав")
inventoryRequest := inquiry || containsStemInTokens(tokens, "назов", "напиш", "покаж", "перечисл", "сообщ", "вывед", "предостав")
if cognitiveSubject && inventoryRequest && inventoryCue {
return interaction.InformationRequestCognitiveModelInventory
}
capabilitySubject := containsStemInTokens(tokens, "уме", "возможност", "способн", "capabilit")
capabilitySubject := containsStemInTokens(tokens, "уме", "возможност", "способн", "capabilit") || (containsMeaningfulInterrogative(tokens) && containsToken(tokens, "можешь"))
if inquiry && capabilitySubject {
if containsStemInTokens(tokens, "без", "внешн", "локальн") && containsStemInTokens(tokens, "модел", "ии", "ai") {
return interaction.InformationRequestLocalCapabilityInventory
}
return interaction.InformationRequestCapabilityInventory
}
recoveryCue := containsStemInTokens(tokens, "восстанов", "исправ", "почин", "подключ", "настро", "недоступ", "нет")
@@ -646,14 +701,8 @@ func informationRequestKind(message string, candidate interaction.SemanticCandid
}
func LocationContextReply(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]) + "."
}
if location := personalCurrentLocation(message); location != "" {
return "Запомнил: сейчас вы в " + location + "."
}
return ""
}
+41
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) {
cases := []struct {
message string
@@ -118,6 +125,10 @@ func TestInformationRequestsAreClassifiedOnceByInteraction(t *testing.T) {
kind interaction.InformationRequestKind
}{
{"какие модели доступны?", interaction.InformationRequestCognitiveModelInventory},
{"назови доступные модели", interaction.InformationRequestCognitiveModelInventory},
{"какая модель отвечает?", interaction.InformationRequestCognitiveCurrentModel},
{"почему ты не смог найти ответ?", interaction.InformationRequestResearchFailureExplanation},
{"что ты можешь сделать без внешних моделей?", interaction.InformationRequestLocalCapabilityInventory},
{"что ты умеешь?", interaction.InformationRequestCapabilityInventory},
{"проверь состояние локального канала", interaction.InformationRequestCognitiveChannelStatus},
{"нет связи с ИИ, восстанови канал", 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) {
lexicon := TaskLexicon{ObjectAliases: []TaskLexiconEntry{{Alias: "медвед", Value: "IMAGE"}}}
got := DecomposeTaskWithLexicon("нарисуй бурого медведя", lexicon)
@@ -240,9 +259,21 @@ func TestNamingPreferenceIsSemanticAndProducesNaturalAcceptance(t *testing.T) {
if name := PreferredAssistantName("давай переименуем тебя в фею. теперь тебя зовут фея"); 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("как тебя зовут") {
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) {
@@ -254,6 +285,16 @@ func TestMemoryInventoryRequestIsSemantic(t *testing.T) {
}
}
func TestRememberedPreferenceIsNotRenderedAsIdentity(t *testing.T) {
result := BuildDeterministicCandidate("запомни: мне нравится красный цвет", "", time.Unix(10, 0).UnixMilli())
if result.PrimarySpeechAct != interaction.SpeechActPreference {
t.Fatalf("expected remembered preference, got %+v", result)
}
if got := semanticReply("запомни: мне нравится красный цвет", SemanticResult{Interpretation: interaction.UtteranceInterpretation{SpeechAct: result.PrimarySpeechAct}}, nil); got != "Хорошо, учту это дальше." {
t.Fatalf("unexpected preference reply %q", got)
}
}
func TestCreativeRequestsDoNotRouteToWebResearch(t *testing.T) {
for _, message := range []string{"нарисуй круг", "расскажи сказку о колобке"} {
candidate := BuildDeterministicCandidate(message, "", time.Now().UnixMilli())
@@ -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) {
if got := TravelSearchClarification("Найди билеты", nil); got == "" {
t.Fatal("underspecified travel request must ask for missing route and date")
@@ -149,6 +162,61 @@ func TestTravelSearchClarification(t *testing.T) {
}
}
func TestTravelSearchQueryCarriesNearestFlightDate(t *testing.T) {
now := time.Date(2026, time.August, 25, 18, 0, 0, 0, time.UTC)
if got := TravelSearchQuery("какой ближайший рейс из Москвы в Казань", now); got != "какой ближайший рейс из Москвы в Казань сегодня 25.08.2026" {
t.Fatalf("nearest flight query=%q", got)
}
if got := TravelSearchQuery("рейс из Москвы в Казань завтра", now); got != "рейс из Москвы в Казань завтра" {
t.Fatalf("explicit date was changed: %q", got)
}
}
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) {
result := interpretForTest(t, "Поменяй базу на УПО1.", activeFocus("upo", "УПО"), "")
if result.Interpretation.SpeechAct != interaction.SpeechActDirective {
@@ -2,6 +2,8 @@ package domain
import "strings"
import "git.cin.su/m/Assistant/contracts/interaction"
// TaskDecomposition is the small, typed intermediate representation used
// 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
@@ -38,6 +40,51 @@ func DecomposeTask(message string) TaskDecomposition {
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
// intentionally an input: a remembered alias may be revalidated or replaced
// without changing the parser or shipping a new hard-coded branch.
+121 -24
View File
@@ -2,10 +2,60 @@ package domain
import (
"strings"
"time"
"git.cin.su/m/Assistant/contracts/interaction"
)
// TravelSearchQuery carries the implicit current-day meaning of a nearest
// flight request into the research adapter.
func TravelSearchQuery(message string, now time.Time) string {
cleaned := strings.TrimSpace(StripAssistantVocative(message))
tokens := semanticTokens(cleaned)
if !travelCue(tokens) || !containsStemInTokens(tokens, "ближ") || isTravelDateSpecified(tokens) {
return cleaned
}
if now.IsZero() {
return cleaned + " сегодня"
}
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.
// The original utterance remains the historical source; this value is only for
// interpretation, cognitive prompts and external queries.
@@ -138,6 +188,34 @@ func ContinueTravelOrigin(message string, history []interaction.HumanUtterance)
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
// instead of reducing it to an unrelated generic web search.
func TravelSearchClarification(message string, history []interaction.HumanUtterance) string {
@@ -159,7 +237,7 @@ func TravelSearchClarification(message string, history []interaction.HumanUttera
}
origin := containsStemInTokens(current, "из", "откуда", "от")
destination := containsStemInTokens(current, "в", "куда", "до")
date := containsStemInTokens(current, "сегодня", "завтра", "послезавтр", "январ", "феврал", "март", "апрел", "мая", "июн", "июл", "август", "сентябр", "октябр", "ноябр", "декабр")
date := isTravelDateSpecified(current)
if containsStemInTokens(current, "ближ") {
date = true
}
@@ -171,13 +249,7 @@ func TravelSearchClarification(message string, history []interaction.HumanUttera
}
}
}
if origin && destination && date {
return ""
}
ticketRequest := containsStemInTokens(current, "билет", "рейс", "самолет", "самолёт", "вылет")
if !ticketRequest && origin && destination {
return ""
}
if !destination {
if contextDestination := travelContextDestination(history); contextDestination != "" {
destination = true
@@ -194,6 +266,9 @@ func TravelSearchClarification(message string, history []interaction.HumanUttera
origin = true
}
}
if origin && destination && (date || !ticketRequest) {
return ""
}
if destination && !origin && !date {
if !ticketRequest {
return "Из какого города выезжать в " + destinationLabel(current, history) + "? Подберу самолёт, поезд, автобус или машину."
@@ -204,11 +279,26 @@ func TravelSearchClarification(message string, history []interaction.HumanUttera
return "Из какого города вылетать?"
}
if destination && !date {
if !ticketRequest {
return ""
}
return "На какую дату нужны билеты?"
}
return "Уточните маршрут и дату: откуда, куда и на какой день нужны билеты?"
}
func isTravelDateSpecified(tokens []string) bool {
if containsStemInTokens(tokens, "сегодня", "завтра", "послезавтр", "январ", "феврал", "март", "апрел", "мая", "июн", "июл", "август", "сентябр", "октябр", "ноябр", "декабр") {
return true
}
for _, token := range tokens {
if hasDigit(token) {
return true
}
}
return false
}
func isTravelDateWord(value string) bool {
return containsStem(value, "сегодня", "завтра", "послезавтр", "январ", "феврал", "март", "апрел", "мая", "июн", "июл", "август", "сентябр", "октябр", "ноябр", "декабр")
}
@@ -225,9 +315,23 @@ func destinationLabel(current []string, history []interaction.HumanUtterance) st
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 {
for index := len(history) - 1; index >= 0; index-- {
tokens := semanticTokens(history[index].Content)
latestAt := int64(-1)
latest := ""
for _, utterance := range history {
tokens := semanticTokens(utterance.Content)
if !travelContextCue(tokens) {
continue
}
@@ -236,26 +340,19 @@ func travelContextDestination(history []interaction.HumanUtterance) string {
continue
}
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 {
for index := len(history) - 1; index >= 0; index-- {
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 ""
return CompilePersonalMemory(history).CurrentLocation()
}
func travelContextCue(tokens []string) bool {
@@ -271,7 +368,7 @@ func capitalizeWord(value string) string {
}
func travelCue(tokens []string) bool {
return containsStemInTokens(tokens, "билет", "рейс", "поезд", "автобус", "перелет", "перелёт")
return containsStemInTokens(tokens, "билет", "рейс", "самолет", "самолёт", "вылет", "поезд", "автобус", "перелет", "перелёт")
}
func travelFollowUpCue(tokens []string) bool {
@@ -0,0 +1,52 @@
[
{"id":"HH50-001","kind":"question","message":"ты кто?","outcome":"identity"},
{"id":"HH50-002","kind":"question","message":"как тебя зовут?","outcome":"identity"},
{"id":"HH50-003","kind":"task","message":"я назову тебя Дед, запомни","outcome":"memory"},
{"id":"HH50-004","kind":"task","message":"теперь тебя зовут Фея","outcome":"memory"},
{"id":"HH50-005","kind":"question","message":"что ты умеешь?","outcome":"conversation"},
{"id":"HH50-006","kind":"task","message":"запомни: мне нравится красный цвет","outcome":"memory"},
{"id":"HH50-007","kind":"question","message":"что ты помнишь обо мне?","outcome":"memory"},
{"id":"HH50-008","kind":"question","message":"выведи мою память таблицей","outcome":"memory"},
{"id":"HH50-009","kind":"question","message":"какая сейчас погода в Казани?","outcome":"research"},
{"id":"HH50-010","kind":"question","message":"какая разница во времени между Москвой и Шанхаем?","outcome":"research"},
{"id":"HH50-011","kind":"assertion","message":"я сейчас в Москве","outcome":"memory"},
{"id":"HH50-012","kind":"question","message":"сколько километров до Сочи?","outcome":"research"},
{"id":"HH50-013","kind":"question","message":"как можно добраться до Сочи?","outcome":"research"},
{"id":"HH50-014","kind":"question","message":"какой ближайший рейс до Казани?","outcome":"research"},
{"id":"HH50-015","kind":"question","message":"найди ближайший ресторан в Сочи","outcome":"research"},
{"id":"HH50-016","kind":"question","message":"назови доступные модели","outcome":"conversation"},
{"id":"HH50-017","kind":"question","message":"какая модель отвечает?","outcome":"conversation"},
{"id":"HH50-018","kind":"question","message":"что ты можешь сделать без внешних моделей?","outcome":"conversation"},
{"id":"HH50-019","kind":"question","message":"проверь, работает ли интернет","outcome":"research"},
{"id":"HH50-020","kind":"question","message":"почему ты не смог найти ответ?","outcome":"conversation"},
{"id":"HH50-021","kind":"question","message":"найди на WB бренд marka-wear","outcome":"research"},
{"id":"HH50-022","kind":"question","message":"проверь цену на видеокарту RTX 4090","outcome":"research"},
{"id":"HH50-023","kind":"question","message":"найди билеты до Ялты","outcome":"research"},
{"id":"HH50-024","kind":"question","message":"покажи ближайшие рейсы до Сочи","outcome":"research"},
{"id":"HH50-025","kind":"question","message":"какой ближайший самолёт из Москвы в Казань сегодня?","outcome":"research"},
{"id":"HH50-026","kind":"question","message":"нарисуй птицу","outcome":"media"},
{"id":"HH50-027","kind":"task","message":"нарисуй зелёную птицу","outcome":"media"},
{"id":"HH50-028","kind":"task","message":"нарисуй коня","outcome":"media"},
{"id":"HH50-029","kind":"task","message":"нарисуй бурого медведя","outcome":"media"},
{"id":"HH50-030","kind":"task","message":"нарисуй птицу в HD","outcome":"media"},
{"id":"HH50-031","kind":"task","message":"нарисуй круг","outcome":"media"},
{"id":"HH50-032","kind":"question","message":"расскажи сказку о Колобке","outcome":"conversation"},
{"id":"HH50-033","kind":"task","message":"придумай короткую шутку","outcome":"conversation"},
{"id":"HH50-034","kind":"task","message":"исправь опечатку: нарисуй прицу","outcome":"conversation"},
{"id":"HH50-035","kind":"task","message":"поставь цель подготовиться к поездке","outcome":"action"},
{"id":"HH50-036","kind":"task","message":"напомни завтра в 10 купить билет","outcome":"action"},
{"id":"HH50-037","kind":"question","message":"что осталось сделать по цели?","outcome":"action"},
{"id":"HH50-038","kind":"task","message":"проверь погоду в Казани и найди рядом кафе","outcome":"multi"},
{"id":"HH50-039","kind":"task","message":"узнай погоду в Сочи и нарисуй птицу","outcome":"multi"},
{"id":"HH50-040","kind":"task","message":"напомни вечером позвонить и проверь погоду","outcome":"multi"},
{"id":"HH50-041","kind":"question","message":"послушай это голосовое сообщение","outcome":"audio"},
{"id":"HH50-042","kind":"question","message":"что на этой фотографии?","outcome":"vision"},
{"id":"HH50-043","kind":"question","message":"прочитай текст на фотографии","outcome":"ocr"},
{"id":"HH50-044","kind":"question","message":"что происходит на этом видео?","outcome":"video"},
{"id":"HH50-045","kind":"assertion","message":"источники противоречат друг другу","outcome":"conversation"},
{"id":"HH50-046","kind":"question","message":"основной runtime сейчас недоступен","outcome":"research"},
{"id":"HH50-047","kind":"task","message":"купи билет до Казани","outcome":"confirmation"},
{"id":"HH50-048","kind":"task","message":"отправь письмо о поездке","outcome":"confirmation"},
{"id":"HH50-049","kind":"task","message":"измени проект и запусти тесты","outcome":"agent"},
{"id":"HH50-050","kind":"question","message":"не получилось ли действие?","outcome":"conversation"}
]
@@ -0,0 +1,90 @@
package household_scenarios
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.cin.su/m/Assistant/contracts/capability"
interactiondomain "git.cin.su/m/Assistant/modules/interaction/domain"
)
type checklistItem struct {
ID string `json:"id"`
Kind string `json:"kind"`
Message string `json:"message"`
Outcome string `json:"outcome"`
}
func TestHouseholdChecklist50ReachesPositiveSemanticReaction(t *testing.T) {
data, err := os.ReadFile(filepath.Join("checklist_50.json"))
if err != nil {
t.Fatal(err)
}
var items []checklistItem
if err := json.Unmarshal(data, &items); err != nil {
t.Fatal(err)
}
if len(items) != 50 {
t.Fatalf("checklist has %d items, want exactly 50", len(items))
}
seen := map[string]bool{}
for _, item := range items {
if item.ID == "" || item.Kind == "" || strings.TrimSpace(item.Message) == "" || item.Outcome == "" {
t.Fatalf("incomplete checklist item: %+v", item)
}
if seen[item.ID] {
t.Fatalf("duplicate checklist item %q", item.ID)
}
seen[item.ID] = true
checkSemanticReaction(t, item)
}
}
func checkSemanticReaction(t *testing.T, item checklistItem) {
t.Helper()
candidate := interactiondomain.BuildDeterministicCandidate(item.Message, "", time.Unix(10, 0).UnixMilli())
has := func(kind capability.CapabilityKind) bool {
for _, hint := range candidate.CapabilityHints {
if capability.CapabilityKind(hint) == kind {
return true
}
}
return false
}
switch item.Outcome {
case "identity", "memory", "conversation", "confirmation":
if has(capability.CapabilityKindWebResearch) || has(capability.CapabilityKindImageGeneration) {
t.Errorf("%s %q routed unrelated capability for %s: %+v", item.ID, item.Message, item.Outcome, candidate)
}
case "research":
if !has(capability.CapabilityKindWebResearch) {
t.Errorf("%s %q did not select research route: %+v", item.ID, item.Message, candidate)
}
case "media":
if !has(capability.CapabilityKindImageGeneration) {
t.Errorf("%s %q did not select image route: %+v", item.ID, item.Message, candidate)
}
case "action":
if !has(capability.CapabilityKindScheduleReminder) && !has(capability.CapabilityKindCognitiveReasoning) && !candidate.NeedsCognition {
t.Errorf("%s %q has no action route or cognitive handoff: %+v", item.ID, item.Message, candidate)
}
case "agent":
if !candidate.NeedsCognition && len(candidate.CapabilityHints) == 0 {
t.Errorf("%s %q has no agent route or cognitive handoff: %+v", item.ID, item.Message, candidate)
}
case "multi":
if len(candidate.CapabilityHints) < 2 {
t.Errorf("%s %q was not decomposed into multiple capabilities: %+v", item.ID, item.Message, candidate)
}
case "audio", "vision", "ocr", "video":
if len(candidate.CapabilityHints) == 0 && !candidate.NeedsCognition {
t.Errorf("%s %q has no modality route or cognitive handoff: %+v", item.ID, item.Message, candidate)
}
default:
t.Fatalf("%s uses unknown outcome %q", item.ID, item.Outcome)
}
}