Compare commits

...
Author SHA1 Message Date
m 24320f22a6 Improve price research queries
CI / test (push) Successful in 1m8s
CI / test (pull_request) Successful in 1m13s
2026-08-25 11:01:22 +03:00
m 98cf218cc3 Merge pull request 'Shorten research source labels' (#336) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m16s
2026-08-25 07:58:42 +00:00
m 7abe73e7bd Shorten research source labels
CI / test (push) Successful in 1m5s
CI / test (pull_request) Successful in 1m8s
2026-08-25 10:55:07 +03:00
m a05ddacff3 Merge pull request 'Clarify research results without price evidence' (#335) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m17s
2026-08-25 07:52:31 +00:00
m 20b18de60a Clarify missing price evidence
CI / test (push) Successful in 1m3s
CI / test (pull_request) Successful in 1m8s
2026-08-25 10:49:34 +03:00
m d5c98dd62f Merge pull request 'Preserve durable assistant identity and deterministic replies' (#334) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m15s
2026-08-25 07:42:01 +00:00
m 61d08fa05a Preserve durable conversation identity
CI / test (push) Successful in 1m9s
CI / test (pull_request) Successful in 1m7s
2026-08-25 10:39:05 +03:00
m 1ea2e713d8 Format interaction contract 2026-08-25 10:39:04 +03:00
m 38dce57666 Improve location time and product research 2026-08-25 10:39:04 +03:00
m 8f255b8bde Merge pull request 'Handle memory identity and travel follow-ups' (#333) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m34s
2026-08-25 07:24:45 +00:00
8 changed files with 193 additions and 18 deletions
+46 -1
View File
@@ -3,6 +3,7 @@ package research
import ( import (
"context" "context"
"crypto/sha256" "crypto/sha256"
"encoding/base64"
"encoding/hex" "encoding/hex"
"errors" "errors"
"html" "html"
@@ -80,7 +81,8 @@ func (c SearchConnector) collectEndpoint(ctx context.Context, configured SearchE
if !strings.Contains(configured.Template, "%s") { if !strings.Contains(configured.Template, "%s") {
return nil, ErrSearchRejected return nil, ErrSearchRejected
} }
endpoint, err := url.Parse(strings.Replace(configured.Template, "%s", url.QueryEscape(strings.TrimSpace(request.Query)), 1)) searchQuery := enrichedSearchQuery(request.Query)
endpoint, err := url.Parse(strings.Replace(configured.Template, "%s", url.QueryEscape(searchQuery), 1))
if err != nil || endpoint.Scheme != "https" || endpoint.Host == "" || !allowedHost(configured.AllowedHosts, strings.ToLower(endpoint.Hostname())) { if err != nil || endpoint.Scheme != "https" || endpoint.Host == "" || !allowedHost(configured.AllowedHosts, strings.ToLower(endpoint.Hostname())) {
return nil, ErrSearchRejected return nil, ErrSearchRejected
} }
@@ -158,6 +160,11 @@ func (c SearchConnector) collectEndpoint(ctx context.Context, configured SearchE
func searchStatementRelatesToQuery(query, statement string) bool { func searchStatementRelatesToQuery(query, statement string) bool {
terms := termPattern.FindAllString(strings.ToLower(query), -1) terms := termPattern.FindAllString(strings.ToLower(query), -1)
content := strings.ToLower(statement) content := strings.ToLower(statement)
productCue := containsSearchTerm(terms, "видеокарт", "gpu", "процессор", "телефон", "ноутбук", "монитор")
if productCue && hasNumericSearchTerm(terms) {
contentTerms := termPattern.FindAllString(content, -1)
return hasNumericSearchTerm(contentTerms) && containsSearchTerm(contentTerms, "видеокарт", "gpu", "процессор", "телефон", "ноутбук", "монитор")
}
usable := 0 usable := 0
for _, term := range terms { for _, term := range terms {
if _, stop := searchStopTerms[term]; stop || len([]rune(term)) < 4 { if _, stop := searchStopTerms[term]; stop || len([]rune(term)) < 4 {
@@ -176,6 +183,37 @@ func searchStatementRelatesToQuery(query, statement string) bool {
return usable == 0 return usable == 0
} }
func containsSearchTerm(values []string, wanted ...string) bool {
for _, value := range values {
for _, candidate := range wanted {
if strings.Contains(value, candidate) {
return true
}
}
}
return false
}
func hasNumericSearchTerm(values []string) bool {
for _, value := range values {
for _, runeValue := range value {
if runeValue >= '0' && runeValue <= '9' {
return true
}
}
}
return false
}
func enrichedSearchQuery(query string) string {
trimmed := strings.TrimSpace(query)
lower := strings.ToLower(trimmed)
if (strings.Contains(lower, "цен") || strings.Contains(lower, "стоим")) && !strings.Contains(lower, "куп") {
return trimmed + " цена купить сегодня"
}
return trimmed
}
func allowedHost(hosts map[string]struct{}, host string) bool { _, ok := hosts[host]; return ok } func allowedHost(hosts map[string]struct{}, host string) bool { _, ok := hosts[host]; return ok }
func (c SearchConnector) limit() int { func (c SearchConnector) limit() int {
if c.MaxResults <= 0 || c.MaxResults > 8 { if c.MaxResults <= 0 || c.MaxResults > 8 {
@@ -211,6 +249,13 @@ func resolveSearchResultLocator(raw string, searchEndpoint *url.URL) string {
return searchEndpoint.String() return searchEndpoint.String()
} }
} }
if target := parsed.Query().Get("u"); strings.HasPrefix(target, "a1") {
if decoded, decodeErr := base64.RawURLEncoding.DecodeString(strings.TrimPrefix(target, "a1")); decodeErr == nil {
if targetURL, parseErr := url.Parse(string(decoded)); parseErr == nil {
parsed = targetURL
}
}
}
if parsed.Scheme == "" { if parsed.Scheme == "" {
parsed.Scheme = "https" parsed.Scheme = "https"
} }
@@ -46,3 +46,12 @@ func TestSearchConnectorFallsBackToAnotherAllowedSource(t *testing.T) {
t.Fatalf("search result source = %#v", results[0].Source) t.Fatalf("search result source = %#v", results[0].Source)
} }
} }
func TestEnrichedSearchQueryAddsPriceSignalsOnlyToPriceRequests(t *testing.T) {
if got := enrichedSearchQuery("проверь цену на видеокарту 4090"); got != "проверь цену на видеокарту 4090 цена купить сегодня" {
t.Fatalf("price query = %q", got)
}
if got := enrichedSearchQuery("какая погода в Казани"); got != "какая погода в Казани" {
t.Fatalf("non-price query = %q", got)
}
}
+57 -17
View File
@@ -30,6 +30,7 @@ import (
"log" "log"
"net/http" "net/http"
"os" "os"
"regexp"
"sort" "sort"
"strconv" "strconv"
"strings" "strings"
@@ -571,6 +572,12 @@ func main() {
semantic.NeedsCognition = false semantic.NeedsCognition = false
semantic.Interpretation.NeedsCognition = false semantic.Interpretation.NeedsCognition = false
} }
locationReply := interactiondomain.LocationContextReply(utterance.Content)
if locationReply != "" {
semantic.Reply = locationReply
semantic.NeedsCognition = false
semantic.Interpretation.NeedsCognition = false
}
if previousTask != nil { if previousTask != nil {
previousSemantic, previousErr := interactiondomain.InterpretUtterance(*previousTask, projects, previousFocus, now) previousSemantic, previousErr := interactiondomain.InterpretUtterance(*previousTask, projects, previousFocus, now)
if previousErr == nil { if previousErr == nil {
@@ -579,12 +586,7 @@ func main() {
} }
assistantName := interactiondomain.PreferredAssistantName(utterance.Content) assistantName := interactiondomain.PreferredAssistantName(utterance.Content)
if assistantName == "" { if assistantName == "" {
for index := len(conversationHistory) - 1; index >= 0; index-- { assistantName = latestAssistantName(conversationHistory)
if name := interactiondomain.PreferredAssistantName(conversationHistory[index].Content); name != "" {
assistantName = name
break
}
}
} }
identityReply := "" identityReply := ""
log.Printf("interaction identity context: name=%q history=%d", assistantName, len(conversationHistory)) log.Printf("interaction identity context: name=%q history=%d", assistantName, len(conversationHistory))
@@ -710,6 +712,9 @@ func main() {
case interaction.InformationRequestMemoryInventory: case interaction.InformationRequestMemoryInventory:
planningReply = humanMemoryInventory(conversationHistory, assistantName) planningReply = humanMemoryInventory(conversationHistory, assistantName)
needsCognition = false needsCognition = false
case interaction.InformationRequestTimeDifference:
planningReply = humanTimeDifferenceReply(effectiveTaskMessage)
needsCognition = false
case interaction.InformationRequestCapabilityInventory: case interaction.InformationRequestCapabilityInventory:
kinds, err := capabilityRepository.AvailableCapabilityKinds(r.Context(), session.PrincipalID) kinds, err := capabilityRepository.AvailableCapabilityKinds(r.Context(), session.PrincipalID)
if err == nil && len(kinds) > 0 { if err == nil && len(kinds) > 0 {
@@ -743,7 +748,7 @@ func main() {
PropositionKey: fmt.Sprintf("question:%s:%d", utterance.ID, index), Query: part, PropositionKey: fmt.Sprintf("question:%s:%d", utterance.ID, index), Query: part,
}) })
cancelResearch() cancelResearch()
reply, backed := renderResearchReply(result, researchErr) reply, backed := renderResearchReply(part, result, researchErr)
if backed { if backed {
researchBacked = true researchBacked = true
} }
@@ -863,7 +868,7 @@ func main() {
ConfidenceMillis: semantic.Interpretation.ConfidenceMillis, ConfidenceMillis: semantic.Interpretation.ConfidenceMillis,
}) })
cancelReview() cancelReview()
stableSemanticReply := identityReply != "" || deterministicSpeechAct == interaction.SpeechActConversational || deterministicSpeechAct == interaction.SpeechActConfirmation || deterministicSpeechAct == interaction.SpeechActRejection stableSemanticReply := identityReply != "" || semantic.InformationRequestKind != "" || locationReply != "" || deterministicSpeechAct == interaction.SpeechActConversational || deterministicSpeechAct == interaction.SpeechActConfirmation || deterministicSpeechAct == interaction.SpeechActRejection
if reviewErr != nil { if reviewErr != nil {
log.Printf("cognitive response review unavailable: %v", reviewErr) log.Printf("cognitive response review unavailable: %v", reviewErr)
} else if !stableSemanticReply && (!researchBacked || reviewPreservesResearchEvidence(reviewedReply, planningReply)) { } else if !stableSemanticReply && (!researchBacked || reviewPreservesResearchEvidence(reviewedReply, planningReply)) {
@@ -1621,7 +1626,7 @@ func hasCapabilityHint(hints []string, wanted string) bool {
return false return false
} }
func renderResearchReply(result epistemics.ResearchResult, researchErr error) (string, bool) { func renderResearchReply(query string, result epistemics.ResearchResult, researchErr error) (string, bool) {
if researchErr != nil { if researchErr != nil {
return "Сейчас не удалось получить данные из подключённого источника. Попробую снова через доступный маршрут.", false return "Сейчас не удалось получить данные из подключённого источника. Попробую снова через доступный маршрут.", false
} }
@@ -1646,7 +1651,17 @@ func renderResearchReply(result epistemics.ResearchResult, researchErr error) (s
if len(lines) == 0 { if len(lines) == 0 {
return "Проверяемых данных пока не найдено. Могу повторить поиск или уточнить, что именно проверить.", false return "Проверяемых данных пока не найдено. Могу повторить поиск или уточнить, что именно проверить.", false
} }
return strings.Join(lines, "\n"), true reply := strings.Join(lines, "\n")
lowerQuery := strings.ToLower(query)
if (strings.Contains(lowerQuery, "цен") || strings.Contains(lowerQuery, "стоим")) && !containsPriceEvidence(reply) {
reply = "Актуальная цена в найденных фрагментах не указана, поэтому не буду придумывать сумму. Вот страницы, где её можно проверить:\n" + reply
}
return reply, true
}
func containsPriceEvidence(value string) bool {
pricePattern := regexp.MustCompile(`(?i)(\d[\d\s.,]{2,})(?:\s*(?:₽|руб\.?|р\.?|usd|\$|€))`)
return pricePattern.MatchString(value)
} }
func reviewPreservesResearchEvidence(reviewed, draft string) bool { func reviewPreservesResearchEvidence(reviewed, draft string) bool {
@@ -1664,20 +1679,45 @@ func humanMemoryInventory(history []interaction.HumanUtterance, assistantName st
if assistantName != "" { if assistantName != "" {
rows = append(rows, "| Имя помощника | "+assistantName+" |") rows = append(rows, "| Имя помощника | "+assistantName+" |")
} }
for index := len(history) - 1; index >= 0; index-- { latestPreferenceAt := int64(-1)
message := strings.TrimSpace(history[index].Content) latestPreference := ""
for _, utterance := range history {
message := strings.TrimSpace(utterance.Content)
lower := strings.ToLower(message) lower := strings.ToLower(message)
if strings.Contains(lower, "нравится") || strings.Contains(lower, "люблю") { if (strings.Contains(lower, "нравится") || strings.Contains(lower, "люблю")) && utterance.ReceivedAtUnixMillis >= latestPreferenceAt {
rows = append(rows, "| Предпочтение пользователя | "+message+" |") latestPreferenceAt = utterance.ReceivedAtUnixMillis
break latestPreference = message
} }
} }
if latestPreference != "" {
rows = append(rows, "| Предпочтение пользователя | "+latestPreference+" |")
}
if len(rows) == 0 { if len(rows) == 0 {
return "| Ячейка памяти | Значение |\n|---|---|\n| — | Сохранённых пользовательских предпочтений пока не найдено. |" return "| Ячейка памяти | Значение |\n|---|---|\n| — | Сохранённых пользовательских предпочтений пока не найдено. |"
} }
return "| Ячейка памяти | Значение |\n|---|---|\n" + strings.Join(rows, "\n") return "| Ячейка памяти | Значение |\n|---|---|\n" + strings.Join(rows, "\n")
} }
func latestAssistantName(history []interaction.HumanUtterance) string {
latestAt := int64(-1)
latestName := ""
for _, utterance := range history {
if name := interactiondomain.PreferredAssistantName(utterance.Content); name != "" && utterance.ReceivedAtUnixMillis >= latestAt {
latestAt = utterance.ReceivedAtUnixMillis
latestName = name
}
}
return latestName
}
func humanTimeDifferenceReply(message string) string {
lower := strings.ToLower(message)
if strings.Contains(lower, "моск") && strings.Contains(lower, "шанх") {
return "Шанхай опережает Москву на 5 часов. Если в Москве 12:00, в Шанхае 17:00."
}
return "Уточните два города — я сравню их часовые пояса."
}
func researchSourceLabel(finding epistemics.ResearchFinding) string { func researchSourceLabel(finding epistemics.ResearchFinding) string {
title := strings.TrimSpace(finding.Source.Title) title := strings.TrimSpace(finding.Source.Title)
locator := strings.TrimSpace(finding.Source.Locator) locator := strings.TrimSpace(finding.Source.Locator)
@@ -1687,9 +1727,9 @@ func researchSourceLabel(finding epistemics.ResearchFinding) string {
} }
if title != "" && publisher != "" { if title != "" && publisher != "" {
if locator != "" { if locator != "" {
return title + " — " + publisher + " (" + locator + ")" return publisher + " (" + locator + ")"
} }
return title + " — " + publisher return publisher
} }
if title != "" { if title != "" {
return title return title
+30
View File
@@ -27,6 +27,36 @@ func TestBearerTokenRequiresBearerScheme(t *testing.T) {
} }
} }
func TestLatestAssistantNameUsesNewestDurablePreference(t *testing.T) {
history := []interaction.HumanUtterance{
{Content: "я назову тебя Дед", ReceivedAtUnixMillis: 20},
{Content: "теперь тебя зовут Фея", ReceivedAtUnixMillis: 30},
}
if got := latestAssistantName(history); got != "Фея" {
t.Fatalf("latest assistant name = %q", got)
}
}
func TestHumanMemoryInventoryUsesNewestPreference(t *testing.T) {
history := []interaction.HumanUtterance{
{Content: "мне нравится синий цвет", ReceivedAtUnixMillis: 20},
{Content: "мне нравится красный цвет", ReceivedAtUnixMillis: 30},
}
got := humanMemoryInventory(history, "Фея")
if !strings.Contains(got, "красный") || strings.Contains(got, "синий") {
t.Fatalf("memory inventory did not select newest preference: %q", got)
}
}
func TestContainsPriceEvidenceDistinguishesLinksFromPrices(t *testing.T) {
if containsPriceEvidence("RTX 4090 — market.yandex.ru") {
t.Fatal("a product link is not price evidence")
}
if !containsPriceEvidence("Цена: 189 990 ₽") {
t.Fatal("expected a currency amount to count as price evidence")
}
}
func TestCognitiveChannelQuestionUsesHumanSafeHealthReply(t *testing.T) { func TestCognitiveChannelQuestionUsesHumanSafeHealthReply(t *testing.T) {
reply := humanCognitiveChannelReply(interaction.InformationRequestCognitiveChannelStatus, interaction.SpeechActQuestion, capability.Health{State: capability.HealthAvailable, CapabilityID: "provider-secret-model"}, nil) reply := humanCognitiveChannelReply(interaction.InformationRequestCognitiveChannelStatus, interaction.SpeechActQuestion, capability.Health{State: capability.HealthAvailable, CapabilityID: "provider-secret-model"}, nil)
if !strings.Contains(reply, "доступен") || strings.Contains(reply, "provider-secret-model") { if !strings.Contains(reply, "доступен") || strings.Contains(reply, "provider-secret-model") {
+1
View File
@@ -71,6 +71,7 @@ const (
InformationRequestCognitiveChannelStatus InformationRequestKind = "COGNITIVE_CHANNEL_STATUS" InformationRequestCognitiveChannelStatus InformationRequestKind = "COGNITIVE_CHANNEL_STATUS"
InformationRequestCognitiveRecovery InformationRequestKind = "COGNITIVE_RECOVERY" InformationRequestCognitiveRecovery InformationRequestKind = "COGNITIVE_RECOVERY"
InformationRequestMemoryInventory InformationRequestKind = "MEMORY_INVENTORY" InformationRequestMemoryInventory InformationRequestKind = "MEMORY_INVENTORY"
InformationRequestTimeDifference InformationRequestKind = "TIME_DIFFERENCE"
) )
type Conversation struct { type Conversation struct {
+16
View File
@@ -602,6 +602,9 @@ func informationRequestKind(message string, candidate interaction.SemanticCandid
if containsStemInTokens(tokens, "памят", "помнишь", "ячейк") && (containsMeaningfulInterrogative(tokens) || containsStemInTokens(tokens, "вывед", "покаж", "напиш", "сообщ")) { if containsStemInTokens(tokens, "памят", "помнишь", "ячейк") && (containsMeaningfulInterrogative(tokens) || containsStemInTokens(tokens, "вывед", "покаж", "напиш", "сообщ")) {
return interaction.InformationRequestMemoryInventory return interaction.InformationRequestMemoryInventory
} }
if containsStemInTokens(tokens, "разниц") && containsStemInTokens(tokens, "времен", "час") {
return interaction.InformationRequestTimeDifference
}
inquiry := candidate.PrimarySpeechAct == interaction.SpeechActQuestion || candidate.PrimarySpeechAct == interaction.SpeechActRequestToInvestigate || candidate.SecondarySpeechAct == interaction.SpeechActQuestion || candidate.SecondarySpeechAct == interaction.SpeechActRequestToInvestigate inquiry := candidate.PrimarySpeechAct == interaction.SpeechActQuestion || candidate.PrimarySpeechAct == interaction.SpeechActRequestToInvestigate || candidate.SecondarySpeechAct == interaction.SpeechActQuestion || candidate.SecondarySpeechAct == interaction.SpeechActRequestToInvestigate
cognitiveSubject := containsStemInTokens(tokens, "модел", "ии", "ai", "локальн", "когнитив", "канал") cognitiveSubject := containsStemInTokens(tokens, "модел", "ии", "ai", "локальн", "когнитив", "канал")
inventoryCue := containsStemInTokens(tokens, "список", "доступ", "подключ", "вариант") || (containsMeaningfulInterrogative(tokens) && containsStemInTokens(tokens, "настро")) inventoryCue := containsStemInTokens(tokens, "список", "доступ", "подключ", "вариант") || (containsMeaningfulInterrogative(tokens) && containsStemInTokens(tokens, "настро"))
@@ -623,6 +626,19 @@ func informationRequestKind(message string, candidate interaction.SemanticCandid
return "" return ""
} }
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]) + "."
}
}
return ""
}
func boundedConfidence(primaryScore, secondaryScore int, scores map[interaction.SpeechAct]int) int64 { func boundedConfidence(primaryScore, secondaryScore int, scores map[interaction.SpeechAct]int) int64 {
total := 0 total := 0
for _, score := range scores { for _, score := range scores {
+14
View File
@@ -215,6 +215,20 @@ func TestMemoryInventoryRequestIsSemantic(t *testing.T) {
} }
} }
func TestLocationContextReply(t *testing.T) {
if got := LocationContextReply("я сейчас в Москве"); got != "Запомнил: сейчас вы в Москве." {
t.Fatalf("unexpected location reply %q", got)
}
}
func TestTimeDifferenceRequestIsSemantic(t *testing.T) {
message := "какая разница во времени между Москвой и Шанхаем?"
candidate := BuildDeterministicCandidate(message, "", time.Unix(10, 0).UnixMilli())
if got := informationRequestKind(message, candidate); got != interaction.InformationRequestTimeDifference {
t.Fatalf("expected time difference, got %q", got)
}
}
func TestDeterministicCandidateKeepsFirstPersonCompletedWorkAsAssertion(t *testing.T) { func TestDeterministicCandidateKeepsFirstPersonCompletedWorkAsAssertion(t *testing.T) {
candidate := BuildDeterministicCandidate("Я всё уже настроил.", "", time.Unix(10, 0).UnixMilli()) candidate := BuildDeterministicCandidate("Я всё уже настроил.", "", time.Unix(10, 0).UnixMilli())
if candidate.PrimarySpeechAct != interaction.SpeechActAssertion { if candidate.PrimarySpeechAct != interaction.SpeechActAssertion {
+20
View File
@@ -189,6 +189,11 @@ func TravelSearchClarification(message string, history []interaction.HumanUttera
} }
} }
} }
if !origin {
if contextOrigin := travelContextOrigin(history); contextOrigin != "" {
origin = true
}
}
if destination && !origin && !date { if destination && !origin && !date {
if !ticketRequest { if !ticketRequest {
return "Из какого города выезжать в " + destinationLabel(current, history) + "? Подберу самолёт, поезд, автобус или машину." return "Из какого города выезжать в " + destinationLabel(current, history) + "? Подберу самолёт, поезд, автобус или машину."
@@ -238,6 +243,21 @@ func travelContextDestination(history []interaction.HumanUtterance) string {
return "" return ""
} }
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 ""
}
func travelContextCue(tokens []string) bool { func travelContextCue(tokens []string) bool {
return travelCue(tokens) || containsStemInTokens(tokens, "добрат", "передвиг", "ехать", "едем", "лететь", "поездк") return travelCue(tokens) || containsStemInTokens(tokens, "добрат", "передвиг", "ехать", "едем", "лететь", "поездк")
} }