Compare commits
66
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
342a93caa4 | ||
|
|
0904a4ade7 | ||
|
|
bbd525eeb5 | ||
|
|
352703a91f | ||
|
|
5a439f7ba8 | ||
|
|
f7200b0704 | ||
|
|
14bf8261da | ||
|
|
feb87d5c4e | ||
|
|
24320f22a6 | ||
|
|
98cf218cc3 | ||
|
|
7abe73e7bd | ||
|
|
a05ddacff3 | ||
|
|
20b18de60a | ||
|
|
d5c98dd62f | ||
|
|
61d08fa05a | ||
|
|
1ea2e713d8 | ||
|
|
38dce57666 | ||
|
|
8f255b8bde | ||
|
|
6b97d6668b | ||
|
|
3fa1d70379 | ||
|
|
2dd05a7aa6 | ||
|
|
02227edc23 | ||
|
|
a2297a84ad | ||
|
|
05cbd8adc7 | ||
|
|
984731b111 | ||
|
|
0da03c18d1 | ||
|
|
302b8fc8cd | ||
|
|
59239635cd | ||
|
|
238105a7da | ||
|
|
d7ca5f7e68 | ||
|
|
827135a02d | ||
|
|
a3ddf53207 | ||
|
|
35ac9015ad | ||
|
|
1c196ef675 | ||
|
|
2ce3b5a9b3 | ||
|
|
7421fd058d | ||
|
|
368e9df551 | ||
|
|
e9629046cb | ||
|
|
b5ccc419f6 | ||
|
|
615723da2a | ||
|
|
d1bcd5beff | ||
|
|
519dc583a0 | ||
|
|
0bf883cf56 | ||
|
|
c8502c735c | ||
|
|
48af97fbdd | ||
|
|
13bcf87ea5 | ||
|
|
e271fbb1e1 | ||
|
|
5678686c57 | ||
|
|
9fc3fd1aa5 | ||
|
|
e3a9c18cb3 | ||
|
|
9534b041db | ||
|
|
9426fa40a9 | ||
|
|
51e2b23082 | ||
|
|
aece914fb8 | ||
|
|
762e312730 | ||
|
|
e9eb529d6e | ||
|
|
e39a2b7dda | ||
|
|
cdc6baa4c0 | ||
|
|
255ab8dbf3 | ||
|
|
a76dc42bd8 | ||
|
|
f0cbd71129 | ||
|
|
aa10c3e093 | ||
|
|
0d836121d0 | ||
|
|
6e8ecbf5e5 | ||
|
|
8088ff197e | ||
|
|
55ee967f2f |
@@ -3,6 +3,7 @@ package research
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"errors"
|
"errors"
|
||||||
"html"
|
"html"
|
||||||
@@ -19,9 +20,9 @@ import (
|
|||||||
var ErrSearchRejected = errors.New("web search request rejected")
|
var ErrSearchRejected = errors.New("web search request rejected")
|
||||||
|
|
||||||
var (
|
var (
|
||||||
searchLinkPattern = regexp.MustCompile(`(?is)<a[^>]+class=["'][^"']*result__a[^"']*["'][^>]*>(.*?)</a>`)
|
searchLinkPattern = regexp.MustCompile(`(?is)(<a[^>]+class=["'][^"']*result__a[^"']*["'][^>]*>)(.*?)</a>`)
|
||||||
searchSnippetPattern = regexp.MustCompile(`(?is)<a[^>]+class=["'][^"']*result__snippet[^"']*["'][^>]*>(.*?)</a>`)
|
searchSnippetPattern = regexp.MustCompile(`(?is)<a[^>]+class=["'][^"']*result__snippet[^"']*["'][^>]*>(.*?)</a>`)
|
||||||
bingLinkPattern = regexp.MustCompile(`(?is)<li[^>]+class=["'][^"']*b_algo[^"']*["'][^>]*>.*?<h2[^>]*><a[^>]*>(.*?)</a>`)
|
bingLinkPattern = regexp.MustCompile(`(?is)<li[^>]+class=["'][^"']*b_algo[^"']*["'][^>]*>.*?<h2[^>]*>(<a[^>]*>)(.*?)</a>`)
|
||||||
bingSnippetPattern = regexp.MustCompile(`(?is)<li[^>]+class=["'][^"']*b_algo[^"']*["'][^>]*>.*?<p[^>]*>(.*?)</p>`)
|
bingSnippetPattern = regexp.MustCompile(`(?is)<li[^>]+class=["'][^"']*b_algo[^"']*["'][^>]*>.*?<p[^>]*>(.*?)</p>`)
|
||||||
tagPattern = regexp.MustCompile(`(?s)<[^>]*>`)
|
tagPattern = regexp.MustCompile(`(?s)<[^>]*>`)
|
||||||
termPattern = regexp.MustCompile(`(?i)[\p{L}\p{N}]{2,}`)
|
termPattern = regexp.MustCompile(`(?i)[\p{L}\p{N}]{2,}`)
|
||||||
@@ -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
|
||||||
}
|
}
|
||||||
@@ -128,7 +130,8 @@ func (c SearchConnector) collectEndpoint(ctx context.Context, configured SearchE
|
|||||||
snapshotID := epistemics.SourceSnapshotID("snapshot:search:" + base)
|
snapshotID := epistemics.SourceSnapshotID("snapshot:search:" + base)
|
||||||
results := make([]epistemics.ResearchCandidate, 0, len(links))
|
results := make([]epistemics.ResearchCandidate, 0, len(links))
|
||||||
for index, link := range links {
|
for index, link := range links {
|
||||||
title := cleanHTML(string(link[1]))
|
linkURL := resolveSearchResultLocator(extractHref(string(link[1])), endpoint)
|
||||||
|
title := cleanHTML(string(link[2]))
|
||||||
snippet := ""
|
snippet := ""
|
||||||
if index < len(snippets) {
|
if index < len(snippets) {
|
||||||
snippet = cleanHTML(string(snippets[index][1]))
|
snippet = cleanHTML(string(snippets[index][1]))
|
||||||
@@ -142,7 +145,7 @@ func (c SearchConnector) collectEndpoint(ctx context.Context, configured SearchE
|
|||||||
results = append(results, epistemics.ResearchCandidate{
|
results = append(results, epistemics.ResearchCandidate{
|
||||||
PropositionKey: request.PropositionKey + ":result:" + ordinal,
|
PropositionKey: request.PropositionKey + ":result:" + ordinal,
|
||||||
Statement: statement,
|
Statement: statement,
|
||||||
Source: epistemics.Source{ID: sourceID, Kind: "web-search", Locator: endpoint.String(), Title: title, Publisher: endpoint.Hostname()},
|
Source: epistemics.Source{ID: sourceID, Kind: "web-search", Locator: linkURL, Title: title, Publisher: sourcePublisher(linkURL, endpoint.Hostname())},
|
||||||
Snapshot: epistemics.SourceSnapshot{ID: snapshotID, SourceID: sourceID, ContentDigest: digestText, CapturedAtUnixMillis: nowUnixMillis, Freshness: epistemics.FreshnessCurrent},
|
Snapshot: epistemics.SourceSnapshot{ID: snapshotID, SourceID: sourceID, ContentDigest: digestText, CapturedAtUnixMillis: nowUnixMillis, Freshness: epistemics.FreshnessCurrent},
|
||||||
Excerpt: epistemics.SourceExcerpt{ID: excerptID, SnapshotID: snapshotID, Text: statement, Start: 0, End: int64(len(statement))},
|
Excerpt: epistemics.SourceExcerpt{ID: excerptID, SnapshotID: snapshotID, Text: statement, Start: 0, End: int64(len(statement))},
|
||||||
Evidence: epistemics.EvidenceObserved, Coverage: epistemics.CoverageComplete, Conflict: epistemics.ConflictNone,
|
Evidence: epistemics.EvidenceObserved, Coverage: epistemics.CoverageComplete, Conflict: epistemics.ConflictNone,
|
||||||
@@ -157,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 {
|
||||||
@@ -175,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 {
|
||||||
@@ -185,3 +224,53 @@ func (c SearchConnector) limit() int {
|
|||||||
func cleanHTML(value string) string {
|
func cleanHTML(value string) string {
|
||||||
return strings.Join(strings.Fields(html.UnescapeString(tagPattern.ReplaceAllString(value, ""))), " ")
|
return strings.Join(strings.Fields(html.UnescapeString(tagPattern.ReplaceAllString(value, ""))), " ")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func extractHref(tag string) string {
|
||||||
|
match := regexp.MustCompile(`(?is)\bhref=["']([^"']+)["']`).FindStringSubmatch(tag)
|
||||||
|
if len(match) == 2 {
|
||||||
|
return match[1]
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveSearchResultLocator(raw string, searchEndpoint *url.URL) string {
|
||||||
|
value := strings.TrimSpace(html.UnescapeString(raw))
|
||||||
|
if value == "" {
|
||||||
|
return searchEndpoint.String()
|
||||||
|
}
|
||||||
|
parsed, err := url.Parse(value)
|
||||||
|
if err != nil {
|
||||||
|
return searchEndpoint.String()
|
||||||
|
}
|
||||||
|
if target := parsed.Query().Get("uddg"); target != "" {
|
||||||
|
value = target
|
||||||
|
parsed, err = url.Parse(target)
|
||||||
|
if err != nil {
|
||||||
|
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 == "" {
|
||||||
|
parsed.Scheme = "https"
|
||||||
|
}
|
||||||
|
if parsed.Host == "" && strings.HasPrefix(value, "//") {
|
||||||
|
parsed, err = url.Parse("https:" + value)
|
||||||
|
}
|
||||||
|
if err != nil || parsed.Scheme != "https" || parsed.Host == "" {
|
||||||
|
return searchEndpoint.String()
|
||||||
|
}
|
||||||
|
return parsed.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func sourcePublisher(locator, fallback string) string {
|
||||||
|
if parsed, err := url.Parse(locator); err == nil && parsed.Hostname() != "" {
|
||||||
|
return parsed.Hostname()
|
||||||
|
}
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|||||||
@@ -42,4 +42,16 @@ func TestSearchConnectorFallsBackToAnotherAllowedSource(t *testing.T) {
|
|||||||
if len(results) != 1 || !strings.Contains(results[0].Statement, "18") {
|
if len(results) != 1 || !strings.Contains(results[0].Statement, "18") {
|
||||||
t.Fatalf("fallback evidence = %#v", results)
|
t.Fatalf("fallback evidence = %#v", results)
|
||||||
}
|
}
|
||||||
|
if results[0].Source.Locator != "https://example.test" || results[0].Source.Publisher != "example.test" {
|
||||||
|
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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ The system already has the correct outbound mutation foundation: Commit owns aut
|
|||||||
|
|
||||||
## Non-goals
|
## Non-goals
|
||||||
|
|
||||||
- No Gmail, MCP, Codex Bridge, browser automation, mobile app, voice, or self-extension loop.
|
- No Gmail, MCP, Codex Bridge, mobile app, voice, or self-extension loop. Browser automation is allowed only under ADR-0019 as bounded read-only observation; it is not a human-surface command or mutation channel.
|
||||||
- No new canonical owner.
|
- No new canonical owner.
|
||||||
- No generic scheduler/event-bus/autonomous-agent loop.
|
- No generic scheduler/event-bus/autonomous-agent loop.
|
||||||
- No new third-party dependency.
|
- No new third-party dependency.
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ Examples include: a reminder after notification, waiting work requiring a decisi
|
|||||||
|
|
||||||
## Non-goals
|
## Non-goals
|
||||||
|
|
||||||
- No Codex Bridge, Gmail, MCP, voice, mobile, browser automation, self-extension loop, or generalized orchestration.
|
- No Codex Bridge, Gmail, MCP, voice, mobile, self-extension loop, or generalized orchestration. Browser observation may be used only through the bounded read-only capability defined by ADR-0019 and cannot continue or mutate a response target.
|
||||||
- No universal object ontology.
|
- No universal object ontology.
|
||||||
- No reminder-specific parallel subsystem.
|
- No reminder-specific parallel subsystem.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# ADR-0019 — Bounded Site-Browser Observation
|
||||||
|
|
||||||
|
Status: Accepted
|
||||||
|
|
||||||
|
Task: DEV-000293
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Search snippets are insufficient for dynamic pages such as marketplaces: they may expose a category page while hiding the current product price behind client-side rendering. Domovoy needs a replaceable observation capability that can inspect an allowlisted rendered page without becoming an account agent, universal scraper, or external mutation path.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
1. Browser automation is allowed only as a server-owned, read-only observation capability behind the existing Capability and research adapter boundaries.
|
||||||
|
2. The browser runtime may navigate only to an explicit HTTPS host allowlist and bounded navigation policy. Browser-supplied or model-supplied authority, credentials, proxy settings, cookies, headers, download paths, or arbitrary JavaScript are rejected.
|
||||||
|
3. The capability may load public pages and wait for bounded client-side rendering. It may read visible text and explicitly declared structured-data selectors, then return an Epistemics Observation with source URL, observed time, coverage, and failure state.
|
||||||
|
4. Login, cookies, account state, CAPTCHA solving, checkout, form submission, uploads, downloads, purchases, messages, mutations, and external side effects are out of scope.
|
||||||
|
5. A blocked page, challenge, timeout, partial DOM, missing price, or conflicting value remains `UNKNOWN`, `PARTIAL`, or `NOT_OBSERVED`; it never becomes a verified fact by model interpretation alone.
|
||||||
|
6. Browser observation is optional. Search-only routing remains the fallback when the capability is unavailable, degraded, or not allowlisted for the requested host.
|
||||||
|
7. Capability owns availability, host policy, health and limits. Epistemics owns the resulting observation and provenance. No new canonical owner or database schema is introduced.
|
||||||
|
8. The first implementation may be development-only. Production activation requires independent capability health, allowlist evidence, adversarial navigation tests, and a live read-only smoke test.
|
||||||
|
|
||||||
|
## Boundaries
|
||||||
|
|
||||||
|
- Core/domain code does not import a browser or provider runtime.
|
||||||
|
- The browser adapter performs only bounded GET/navigation observation and cannot reach Commit/Executor.
|
||||||
|
- Secrets remain outside the browser runtime and its artifacts, logs, screenshots, page content and chat context.
|
||||||
|
- An observation is evidence for answer synthesis, not an instruction to mutate a site or canonical state.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
- Dynamic public pages can provide stronger evidence than search snippets when the site permits it.
|
||||||
|
- Site-specific selectors and host policy are replaceable adapter configuration, not semantic domain logic.
|
||||||
|
- Browser unavailability is a capability gap, not a runtime-wide outage.
|
||||||
|
- The old blanket prohibition on browser automation is replaced by this narrower, testable boundary.
|
||||||
@@ -33,7 +33,7 @@ func (c cognitiveInterpretationClient) ReviewResponse(ctx context.Context, sessi
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
prompt := "Ты редактор ответа Домового. Проверь, отвечает ли черновик на сообщение пользователя по смыслу. Верни только готовый ответ пользователю, без разбора проверки, служебных слов и упоминания моделей. Не выдумывай факты, не утверждай невыполненные действия, сохрани важные имена, числа, источники и ограничения. Если черновик уже адекватен, верни его без лишних добавлений.\n\nСообщение пользователя:\n" + userMessage + "\n\nЧерновик ответа:\n" + draft
|
prompt := "Ты редактор ответа Домового. Проверь черновик по смыслу и подготовь естественный ответ человеку. Учитывай весь запрос, включая недостающие параметры для конкретного результата. Если данных не хватает, задай один короткий полезный уточняющий вопрос, например откуда и куда ехать. Не выдавай поисковые сниппеты как выполненное действие и не показывай служебные URL поисковой выдачи. Сохрани проверяемые факты, названия источников, прямые ссылки и ограничения. Не выдумывай факты и не утверждай невыполненные действия. Верни только готовый ответ без разбора проверки, служебных слов и упоминания моделей. Если черновик уже адекватен, верни его без лишних добавлений.\n\nСообщение пользователя:\n" + userMessage + "\n\nЧерновик ответа:\n" + draft
|
||||||
target := *c.baseURL
|
target := *c.baseURL
|
||||||
target.Path = "/v1/advisories"
|
target.Path = "/v1/advisories"
|
||||||
payload, err := json.Marshal(cognitive.GatewayAdvisoryRequest{
|
payload, err := json.Marshal(cognitive.GatewayAdvisoryRequest{
|
||||||
|
|||||||
@@ -40,6 +40,16 @@ func TestReviewResponseUsesCognitiveGatewayAndReturnsOnlyDraftAnswer(t *testing.
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestReviewPreservesResearchEvidence(t *testing.T) {
|
||||||
|
draft := "Нашёл вариант. Источник: Aviasales (https://www.aviasales.ru/search)"
|
||||||
|
if reviewPreservesResearchEvidence("Нашёл вариант на Авиасейлс.", draft) {
|
||||||
|
t.Fatal("review without the direct source must be rejected")
|
||||||
|
}
|
||||||
|
if !reviewPreservesResearchEvidence("Нашёл вариант. Источник: Aviasales (https://www.aviasales.ru/search)", draft) {
|
||||||
|
t.Fatal("review with the direct source must be accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestSimpleQuestionUsesStrictInterpretationForSemanticRouting(t *testing.T) {
|
func TestSimpleQuestionUsesStrictInterpretationForSemanticRouting(t *testing.T) {
|
||||||
result := interactiondomain.SemanticResult{
|
result := interactiondomain.SemanticResult{
|
||||||
Interpretation: interaction.UtteranceInterpretation{
|
Interpretation: interaction.UtteranceInterpretation{
|
||||||
|
|||||||
+204
-18
@@ -30,6 +30,7 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"regexp"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -509,6 +510,8 @@ func main() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
var effectiveTaskMessage = interactiondomain.StripAssistantVocative(utterance.Content)
|
var effectiveTaskMessage = interactiondomain.StripAssistantVocative(utterance.Content)
|
||||||
|
continuationMessage := ""
|
||||||
|
travelContinuation := false
|
||||||
var previousTask *interaction.HumanUtterance
|
var previousTask *interaction.HumanUtterance
|
||||||
var conversationHistory []interaction.HumanUtterance
|
var conversationHistory []interaction.HumanUtterance
|
||||||
if request.ConversationID != "" {
|
if request.ConversationID != "" {
|
||||||
@@ -528,6 +531,14 @@ func main() {
|
|||||||
log.Printf("interaction principal history loaded: %d utterances", len(recentUserHistory))
|
log.Printf("interaction principal history loaded: %d utterances", len(recentUserHistory))
|
||||||
}
|
}
|
||||||
conversationHistory = append(conversationHistory, recentUserHistory...)
|
conversationHistory = append(conversationHistory, recentUserHistory...)
|
||||||
|
if continuation := interactiondomain.ContinueLocalSearch(effectiveTaskMessage, conversationHistory); continuation != "" {
|
||||||
|
continuationMessage = continuation
|
||||||
|
effectiveTaskMessage = continuation
|
||||||
|
} else if continuation := interactiondomain.ContinueTravelOrigin(effectiveTaskMessage, conversationHistory); continuation != "" {
|
||||||
|
continuationMessage = continuation
|
||||||
|
travelContinuation = true
|
||||||
|
effectiveTaskMessage = continuation
|
||||||
|
}
|
||||||
if request.ConversationID != "" && interactiondomain.IsRetryRequest(utterance.Content) {
|
if request.ConversationID != "" && interactiondomain.IsRetryRequest(utterance.Content) {
|
||||||
if len(conversationHistory) > 0 {
|
if len(conversationHistory) > 0 {
|
||||||
for index := len(conversationHistory) - 1; index >= 0; index-- {
|
for index := len(conversationHistory) - 1; index >= 0; index-- {
|
||||||
@@ -546,6 +557,48 @@ func main() {
|
|||||||
http.Error(w, "interpret chat message", http.StatusServiceUnavailable)
|
http.Error(w, "interpret chat message", http.StatusServiceUnavailable)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if continuationMessage != "" {
|
||||||
|
continuedUtterance := utterance
|
||||||
|
continuedUtterance.Content = continuationMessage
|
||||||
|
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"
|
||||||
|
semantic = continuedSemantic
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if travelContinuation && interactiondomain.TravelSearchClarification(effectiveTaskMessage, conversationHistory) == "" {
|
||||||
|
semantic.CapabilityHints = append(semantic.CapabilityHints, string(capability.CapabilityKindWebResearch))
|
||||||
|
semantic.NeedsCognition = false
|
||||||
|
semantic.Interpretation.NeedsCognition = false
|
||||||
|
}
|
||||||
|
creativeRequest := interactiondomain.IsCreativeRequest(utterance.Content) || interactiondomain.IsCreativeRequest(effectiveTaskMessage)
|
||||||
|
creativeReply := interactiondomain.CreativeDeterministicReply(utterance.Content)
|
||||||
|
if creativeReply == "" {
|
||||||
|
creativeReply = interactiondomain.CreativeDeterministicReply(effectiveTaskMessage)
|
||||||
|
}
|
||||||
|
creativeFallbackReply := interactiondomain.CreativeFallbackReply(utterance.Content)
|
||||||
|
if creativeFallbackReply == "" {
|
||||||
|
creativeFallbackReply = interactiondomain.CreativeFallbackReply(effectiveTaskMessage)
|
||||||
|
}
|
||||||
|
if creativeRequest {
|
||||||
|
semantic.CapabilityHints = interactiondomain.RemoveCapabilityHint(semantic.CapabilityHints, string(capability.CapabilityKindWebResearch))
|
||||||
|
if creativeReply != "" {
|
||||||
|
semantic.Reply = creativeReply
|
||||||
|
semantic.NeedsCognition = false
|
||||||
|
semantic.Interpretation.NeedsCognition = false
|
||||||
|
} else {
|
||||||
|
semantic.NeedsCognition = true
|
||||||
|
semantic.Interpretation.NeedsCognition = true
|
||||||
|
semantic.CapabilityHints = append(semantic.CapabilityHints, string(capability.CapabilityKindCognitiveReasoning))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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 {
|
||||||
@@ -554,12 +607,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))
|
||||||
@@ -682,6 +730,12 @@ func main() {
|
|||||||
helpPath = work.HelpPath{}
|
helpPath = work.HelpPath{}
|
||||||
}
|
}
|
||||||
switch semantic.InformationRequestKind {
|
switch semantic.InformationRequestKind {
|
||||||
|
case interaction.InformationRequestMemoryInventory:
|
||||||
|
planningReply = humanMemoryInventory(conversationHistory, assistantName)
|
||||||
|
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 {
|
||||||
@@ -702,13 +756,32 @@ func main() {
|
|||||||
researchBacked := false
|
researchBacked := false
|
||||||
if hasChatRoute(routePlan, chatRouteResearch) && semantic.Interpretation.Clarification != interaction.ClarificationRequired {
|
if hasChatRoute(routePlan, chatRouteResearch) && semantic.Interpretation.Clarification != interaction.ClarificationRequired {
|
||||||
if planID, idErr := ids.New(); idErr == nil {
|
if planID, idErr := ids.New(); idErr == nil {
|
||||||
|
parts := interactiondomain.IndependentRequestParts(effectiveTaskMessage)
|
||||||
|
replies := make([]string, 0, len(parts))
|
||||||
|
for index, part := range parts {
|
||||||
|
if clarification := interactiondomain.LocalSearchClarification(part); clarification != "" {
|
||||||
|
replies = append(replies, "По запросу «"+part+"»: "+clarification)
|
||||||
|
continue
|
||||||
|
}
|
||||||
researchCtx, cancelResearch := context.WithTimeout(r.Context(), 8*time.Second)
|
researchCtx, cancelResearch := context.WithTimeout(r.Context(), 8*time.Second)
|
||||||
result, researchErr := researchClient.SearchWeb(researchCtx, epistemics.WebSearchRequest{
|
result, researchErr := researchClient.SearchWeb(researchCtx, epistemics.WebSearchRequest{
|
||||||
Plan: epistemics.ResearchPlan{ID: epistemics.ResearchPlanID("plan:" + planID), Question: effectiveTaskMessage, SourceClasses: []string{"web-search"}, FreshnessPolicy: "current"},
|
Plan: epistemics.ResearchPlan{ID: epistemics.ResearchPlanID(fmt.Sprintf("plan:%s:%d", planID, index)), Question: part, SourceClasses: []string{"web-search"}, FreshnessPolicy: "current"},
|
||||||
PropositionKey: "question:" + string(utterance.ID), Query: effectiveTaskMessage,
|
PropositionKey: fmt.Sprintf("question:%s:%d", utterance.ID, index), Query: part,
|
||||||
})
|
})
|
||||||
cancelResearch()
|
cancelResearch()
|
||||||
planningReply, researchBacked = renderResearchReply(result, researchErr)
|
reply, backed := renderResearchReply(part, result, researchErr)
|
||||||
|
if backed {
|
||||||
|
researchBacked = true
|
||||||
|
}
|
||||||
|
if len(parts) > 1 {
|
||||||
|
reply = "По запросу «" + part + "»: " + reply
|
||||||
|
}
|
||||||
|
replies = append(replies, reply)
|
||||||
|
}
|
||||||
|
planningReply = strings.Join(replies, "\n\n")
|
||||||
|
if researchBacked {
|
||||||
|
semantic.Reply = planningReply
|
||||||
|
}
|
||||||
// A failed source must not turn the complete conversation into a
|
// A failed source must not turn the complete conversation into a
|
||||||
// runtime failure or invite an unsupported local guess for a fact.
|
// runtime failure or invite an unsupported local guess for a fact.
|
||||||
needsCognition = false
|
needsCognition = false
|
||||||
@@ -726,6 +799,10 @@ func main() {
|
|||||||
planningReply = humanCognitiveDegradedReply(utterance.Content)
|
planningReply = humanCognitiveDegradedReply(utterance.Content)
|
||||||
needsCognition = false
|
needsCognition = false
|
||||||
}
|
}
|
||||||
|
if creativeFallbackReply != "" && cognitiveAttempted && !cognitiveAvailable {
|
||||||
|
planningReply = creativeFallbackReply
|
||||||
|
needsCognition = false
|
||||||
|
}
|
||||||
var capabilityStatus capability.CapabilityResolutionStatus
|
var capabilityStatus capability.CapabilityResolutionStatus
|
||||||
var capabilityKind capability.CapabilityKind
|
var capabilityKind capability.CapabilityKind
|
||||||
var capabilityGapID capability.CapabilityGapID
|
var capabilityGapID capability.CapabilityGapID
|
||||||
@@ -816,10 +893,10 @@ 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 != "" || creativeReply != "" || (creativeFallbackReply != "" && !cognitiveAvailable) || semantic.InformationRequestKind != "" || locationReply != "" || deterministicSpeechAct == interaction.SpeechActConversational || deterministicSpeechAct == interaction.SpeechActConfirmation || deterministicSpeechAct == interaction.SpeechActRejection
|
||||||
if reviewErr != nil {
|
if reviewErr != nil {
|
||||||
log.Printf("cognitive response review unavailable: %v", reviewErr)
|
log.Printf("cognitive response review unavailable: %v", reviewErr)
|
||||||
} else if !stableSemanticReply {
|
} else if !stableSemanticReply && (!researchBacked || reviewPreservesResearchEvidence(reviewedReply, planningReply)) {
|
||||||
planningReply = reviewedReply
|
planningReply = reviewedReply
|
||||||
} else if reviewedReply != planningReply {
|
} else if reviewedReply != planningReply {
|
||||||
log.Printf("cognitive response review proposed stable semantic rewrite; preserving semantic reply")
|
log.Printf("cognitive response review proposed stable semantic rewrite; preserving semantic reply")
|
||||||
@@ -827,13 +904,29 @@ func main() {
|
|||||||
}
|
}
|
||||||
if identityReply == "" {
|
if identityReply == "" {
|
||||||
stableAct := interactiondomain.ClassifySpeechAct(utterance.Content, utterance.CorrectsUtteranceID)
|
stableAct := interactiondomain.ClassifySpeechAct(utterance.Content, utterance.CorrectsUtteranceID)
|
||||||
if stableReply, stable := interactiondomain.StableConversationalReply(utterance.Content, stableAct); stable {
|
travelClarification := interactiondomain.TravelSearchClarification(effectiveTaskMessage, conversationHistory)
|
||||||
|
if stableReply, stable := interactiondomain.StableConversationalReply(utterance.Content, stableAct); stable && travelClarification == "" {
|
||||||
planningReply = stableReply
|
planningReply = stableReply
|
||||||
needsCognition = false
|
needsCognition = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if identityReply != "" {
|
if identityReply != "" {
|
||||||
|
semantic.Reply = identityReply
|
||||||
needsCognition = false
|
needsCognition = false
|
||||||
|
planningReply = identityReply
|
||||||
|
}
|
||||||
|
if creativeReply != "" {
|
||||||
|
semantic.Reply = creativeReply
|
||||||
|
needsCognition = false
|
||||||
|
planningReply = creativeReply
|
||||||
|
}
|
||||||
|
if creativeFallbackReply != "" && !cognitiveAvailable {
|
||||||
|
semantic.Reply = creativeFallbackReply
|
||||||
|
needsCognition = false
|
||||||
|
planningReply = creativeFallbackReply
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(planningReply) != "" {
|
||||||
|
semantic.Reply = planningReply
|
||||||
}
|
}
|
||||||
log.Printf("chat response final message=%q act=%s deterministic=%s handled=%t fallback=%q planning=%q", utterance.Content, semantic.Interpretation.SpeechAct, deterministicSpeechAct, responseResult.Handled, semantic.Reply, planningReply)
|
log.Printf("chat response final message=%q act=%s deterministic=%s handled=%t fallback=%q planning=%q", utterance.Content, semantic.Interpretation.SpeechAct, deterministicSpeechAct, responseResult.Handled, semantic.Reply, planningReply)
|
||||||
response := interaction.ChatMessageResponse{
|
response := interaction.ChatMessageResponse{
|
||||||
@@ -1568,20 +1661,24 @@ 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
|
||||||
}
|
}
|
||||||
lines := make([]string, 0, 2)
|
lines := make([]string, 0, 2)
|
||||||
for _, finding := range result.Findings {
|
for index, finding := range result.Findings {
|
||||||
if finding.State != epistemics.FindingSupported || strings.TrimSpace(finding.Excerpt.Text) == "" || strings.TrimSpace(finding.Source.Locator) == "" {
|
if finding.State != epistemics.FindingSupported || strings.TrimSpace(finding.Excerpt.Text) == "" || strings.TrimSpace(finding.Source.Locator) == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
excerpt := strings.TrimSpace(finding.Excerpt.Text)
|
excerpt := strings.TrimSpace(finding.Excerpt.Text)
|
||||||
if len([]rune(excerpt)) > 180 {
|
limit := 180
|
||||||
excerpt = string([]rune(excerpt)[:180]) + "…"
|
if index > 0 {
|
||||||
|
limit = 100
|
||||||
}
|
}
|
||||||
lines = append(lines, excerpt+"\nИсточник: "+finding.Source.Locator)
|
if len([]rune(excerpt)) > limit {
|
||||||
|
excerpt = string([]rune(excerpt)[:limit]) + "…"
|
||||||
|
}
|
||||||
|
lines = append(lines, excerpt+"\nИсточник: "+researchSourceLabel(finding))
|
||||||
if len(lines) == 2 {
|
if len(lines) == 2 {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -1589,7 +1686,96 @@ 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 {
|
||||||
|
if strings.Contains(draft, "http://") || strings.Contains(draft, "https://") {
|
||||||
|
return strings.Contains(reviewed, "http://") || strings.Contains(reviewed, "https://")
|
||||||
|
}
|
||||||
|
if strings.Contains(draft, "Источник:") {
|
||||||
|
return strings.Contains(reviewed, "Источник:")
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func humanMemoryInventory(history []interaction.HumanUtterance, assistantName string) string {
|
||||||
|
rows := make([]string, 0, 4)
|
||||||
|
if assistantName != "" {
|
||||||
|
rows = append(rows, "| Имя помощника | "+assistantName+" |")
|
||||||
|
}
|
||||||
|
latestPreferenceAt := int64(-1)
|
||||||
|
latestPreference := ""
|
||||||
|
for _, utterance := range history {
|
||||||
|
message := strings.TrimSpace(utterance.Content)
|
||||||
|
lower := strings.ToLower(message)
|
||||||
|
if (strings.Contains(lower, "нравится") || strings.Contains(lower, "люблю")) && utterance.ReceivedAtUnixMillis >= latestPreferenceAt {
|
||||||
|
latestPreferenceAt = utterance.ReceivedAtUnixMillis
|
||||||
|
latestPreference = message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if latestPreference != "" {
|
||||||
|
rows = append(rows, "| Предпочтение пользователя | "+latestPreference+" |")
|
||||||
|
}
|
||||||
|
if len(rows) == 0 {
|
||||||
|
return "| Ячейка памяти | Значение |\n|---|---|\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 {
|
||||||
|
title := strings.TrimSpace(finding.Source.Title)
|
||||||
|
locator := strings.TrimSpace(finding.Source.Locator)
|
||||||
|
publisher := strings.TrimSpace(finding.Source.Publisher)
|
||||||
|
if strings.Contains(locator, "duckduckgo.com/html") || strings.Contains(locator, "bing.com/search") {
|
||||||
|
locator = ""
|
||||||
|
}
|
||||||
|
if title != "" && publisher != "" {
|
||||||
|
if locator != "" {
|
||||||
|
return publisher + " (" + locator + ")"
|
||||||
|
}
|
||||||
|
return publisher
|
||||||
|
}
|
||||||
|
if title != "" {
|
||||||
|
return title
|
||||||
|
}
|
||||||
|
if publisher != "" {
|
||||||
|
return publisher
|
||||||
|
}
|
||||||
|
if locator != "" {
|
||||||
|
return locator
|
||||||
|
}
|
||||||
|
return "подключённый источник"
|
||||||
}
|
}
|
||||||
|
|
||||||
func humanCognitiveModelInventory(candidates []capability.ResolvedCognitiveBinding, inventoryErr error) string {
|
func humanCognitiveModelInventory(candidates []capability.ResolvedCognitiveBinding, inventoryErr error) string {
|
||||||
|
|||||||
@@ -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") {
|
||||||
|
|||||||
@@ -70,6 +70,8 @@ const (
|
|||||||
InformationRequestCognitiveModelInventory InformationRequestKind = "COGNITIVE_MODEL_INVENTORY"
|
InformationRequestCognitiveModelInventory InformationRequestKind = "COGNITIVE_MODEL_INVENTORY"
|
||||||
InformationRequestCognitiveChannelStatus InformationRequestKind = "COGNITIVE_CHANNEL_STATUS"
|
InformationRequestCognitiveChannelStatus InformationRequestKind = "COGNITIVE_CHANNEL_STATUS"
|
||||||
InformationRequestCognitiveRecovery InformationRequestKind = "COGNITIVE_RECOVERY"
|
InformationRequestCognitiveRecovery InformationRequestKind = "COGNITIVE_RECOVERY"
|
||||||
|
InformationRequestMemoryInventory InformationRequestKind = "MEMORY_INVENTORY"
|
||||||
|
InformationRequestTimeDifference InformationRequestKind = "TIME_DIFFERENCE"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Conversation struct {
|
type Conversation struct {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"task_file": "dev/tasks/DEV-000292-development-mode-runtime-access.json",
|
"task_file": "dev/tasks/DEV-000294-creative-chat-routing.json",
|
||||||
"task_id": "DEV-000292",
|
"task_id": "DEV-000294",
|
||||||
"task_revision": 1
|
"task_revision": 1
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000293",
|
||||||
|
"task_revision": 1,
|
||||||
|
"architecture_revision": "ADR-0019",
|
||||||
|
"base_repo_revision": "origin/main",
|
||||||
|
"risk_tier": "E",
|
||||||
|
"intent": "Authorize a bounded read-only site-browser capability for dynamic web pages so Domovoy can observe rendered product data, including prices, without granting account access or external mutation authority.",
|
||||||
|
"requirement_ids": ["bounded browser observation", "dynamic web research", "price evidence extraction"],
|
||||||
|
"allowed_change_scope": {
|
||||||
|
"modules": ["capability", "epistemics", "core-runtime", "research"],
|
||||||
|
"paths": [
|
||||||
|
"architecture/adrs/ADR-0014-assistant-presence-attention-human-surface.md",
|
||||||
|
"architecture/adrs/ADR-0015-human-response-continuation-semantics.md",
|
||||||
|
"architecture/adrs/ADR-0019-bounded-site-browser-observation.md",
|
||||||
|
"dev/ACTIVE_TASK.json",
|
||||||
|
"dev/tasks/DEV-000293-site-browser-capability.json",
|
||||||
|
"docs/PROJECT_STATUS.md"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"forbidden_change_scope": {
|
||||||
|
"paths": ["security/**", "database/**", "deploy/docker-compose.prod.yml", "LLM-local/**"]
|
||||||
|
},
|
||||||
|
"allowed_architecture_delta": {
|
||||||
|
"new_cross_module_dependencies": 0,
|
||||||
|
"new_canonical_owners": 0,
|
||||||
|
"new_privileges": 0,
|
||||||
|
"new_third_party_dependencies": 0,
|
||||||
|
"new_database_owner_roles": 0
|
||||||
|
},
|
||||||
|
"contracts": {
|
||||||
|
"consume": ["existing capability registry", "existing epistemics observation/provenance", "existing research adapter boundary"],
|
||||||
|
"may_change": ["architecture allowance for bounded read-only browser observation"]
|
||||||
|
},
|
||||||
|
"semantic_owner": "capability owns availability and limits; epistemics owns observations and provenance",
|
||||||
|
"canonical_state": ["no new canonical state; browser output remains an observation/artifact projection"],
|
||||||
|
"state_transitions": ["search-only observation -> bounded rendered-page observation -> source-backed answer"],
|
||||||
|
"side_effects_and_privileges": ["read-only HTTPS/browser egress only", "no cookies, account sessions, credentials, downloads, uploads, form submission or external mutation"],
|
||||||
|
"persistence_and_migrations": ["no database migration"],
|
||||||
|
"failure_retry_restart": ["timeouts and blocked pages remain partial/unknown observations", "no blind retries that can duplicate external effects"],
|
||||||
|
"assumptions": ["browser runtime is replaceable and isolated from canonical runtimes", "site allowlist and navigation policy are server-owned"],
|
||||||
|
"acceptance_scenarios": ["dynamic price page can be observed when allowlisted", "401/challenge/timeout is reported as unavailable evidence", "browser cannot submit credentials or mutate a site", "source URL, observed time and coverage remain attached", "existing search-only route remains unchanged when browser capability is unavailable", "production behavior stays read-only"],
|
||||||
|
"required_tests": ["architecture preflight", "check-diff", "ADR consistency", "go test ./...", "go vet ./...", "go run ./cmd/devctl check-architecture", "go run ./cmd/devctl independent", "git diff --check"],
|
||||||
|
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT", "BLOCKED_BY_MISSING_CAPABILITY"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000294",
|
||||||
|
"task_revision": 1,
|
||||||
|
"architecture_revision": "ADR-0019",
|
||||||
|
"base_repo_revision": "origin/main",
|
||||||
|
"risk_tier": "E",
|
||||||
|
"intent": "Route creative requests by meaning: render simple geometric sketches deterministically and send rich creative requests to cognition without web research or truth-evidence fallback.",
|
||||||
|
"requirement_ids": ["creative conversation", "no irrelevant web research", "short deterministic drawing"],
|
||||||
|
"allowed_change_scope": {
|
||||||
|
"modules": ["interaction", "core-runtime"],
|
||||||
|
"paths": [
|
||||||
|
"cmd/core-runtime/**",
|
||||||
|
"modules/interaction/domain/**",
|
||||||
|
"dev/ACTIVE_TASK.json",
|
||||||
|
"dev/tasks/DEV-000294-creative-chat-routing.json"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"forbidden_change_scope": {
|
||||||
|
"paths": ["architecture/**", "security/**", "database/**", "deploy/docker-compose.prod.yml", "LLM-local/**"]
|
||||||
|
},
|
||||||
|
"allowed_architecture_delta": {
|
||||||
|
"new_cross_module_dependencies": 0,
|
||||||
|
"new_canonical_owners": 0,
|
||||||
|
"new_privileges": 0,
|
||||||
|
"new_third_party_dependencies": 0,
|
||||||
|
"new_database_owner_roles": 0
|
||||||
|
},
|
||||||
|
"contracts": {
|
||||||
|
"consume": ["existing interaction semantic candidate", "existing cognitive gateway", "existing web research route"],
|
||||||
|
"may_change": ["creative capability hints and core route selection"]
|
||||||
|
},
|
||||||
|
"semantic_owner": "interaction owns meaning classification; core-runtime owns route orchestration",
|
||||||
|
"canonical_state": ["existing utterance and candidate history only"],
|
||||||
|
"state_transitions": ["creative request -> deterministic sketch or cognitive conversation route"],
|
||||||
|
"side_effects_and_privileges": ["no new privilege or external mutation"],
|
||||||
|
"persistence_and_migrations": ["no migration"],
|
||||||
|
"failure_retry_restart": ["creative cognition failure reports unavailable cognition; never falls back to web research"],
|
||||||
|
"assumptions": ["simple circle rendering is a text-safe projection; richer images remain a separate capability"],
|
||||||
|
"acceptance_scenarios": ["нарисуй круг returns a circle and no source links", "расскажи сказку о колобке uses cognition and no web route", "ordinary weather and price requests keep web research", "cognitive review cannot replace deterministic circle"],
|
||||||
|
"required_tests": ["go test ./...", "go vet ./...", "go run ./cmd/devctl preflight -active dev/ACTIVE_TASK.json", "go run ./cmd/devctl check-diff -active dev/ACTIVE_TASK.json", "go run ./cmd/devctl check-architecture", "go run ./cmd/devctl/independent", "git diff --check"],
|
||||||
|
"terminal_gap_states": ["BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_MISSING_CAPABILITY", "BLOCKED_BY_CONFLICT"]
|
||||||
|
}
|
||||||
@@ -133,7 +133,7 @@ func PreferredAssistantName(message string) string {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
for _, candidate := range tokens[index+1:] {
|
for _, candidate := range tokens[index+1:] {
|
||||||
if candidate == "тебя" || candidate == "тебе" || candidate == "себя" || candidate == "меня" {
|
if candidate == "тебя" || candidate == "тебе" || candidate == "себя" || candidate == "меня" || candidate == "в" || candidate == "теперь" || candidate == "же" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if candidate == "буду" || candidate == "будет" || candidate == "запомни" || candidate == "помни" || candidate == "ты" || candidate == "это" {
|
if candidate == "буду" || candidate == "будет" || candidate == "запомни" || candidate == "помни" || candidate == "ты" || candidate == "это" {
|
||||||
@@ -144,12 +144,19 @@ func PreferredAssistantName(message string) string {
|
|||||||
}
|
}
|
||||||
runes := []rune(candidate)
|
runes := []rune(candidate)
|
||||||
runes[0] = []rune(strings.ToUpper(string(runes[0])))[0]
|
runes[0] = []rune(strings.ToUpper(string(runes[0])))[0]
|
||||||
return string(runes)
|
return normalizeAssistantName(string(runes))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func normalizeAssistantName(value string) string {
|
||||||
|
if strings.HasSuffix(value, "ю") {
|
||||||
|
return strings.TrimSuffix(value, "ю") + "я"
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
// IsIdentityInquiry identifies a request about the assistant itself by its
|
// IsIdentityInquiry identifies a request about the assistant itself by its
|
||||||
// interrogative meaning. Punctuation is optional and wording may vary.
|
// interrogative meaning. Punctuation is optional and wording may vary.
|
||||||
func IsIdentityInquiry(message string) bool {
|
func IsIdentityInquiry(message string) bool {
|
||||||
@@ -488,6 +495,9 @@ func capabilityHintsFor(primary, secondary interaction.SpeechAct, tokens []strin
|
|||||||
if sourceDependentQuestion(primary, secondary, tokens) {
|
if sourceDependentQuestion(primary, secondary, tokens) {
|
||||||
add("WEB_RESEARCH")
|
add("WEB_RESEARCH")
|
||||||
}
|
}
|
||||||
|
if isCreativeRequestTokens(tokens) {
|
||||||
|
add("COGNITIVE_REASONING")
|
||||||
|
}
|
||||||
if containsToken(tokens, "напомни") || containsToken(tokens, "напомин") {
|
if containsToken(tokens, "напомни") || containsToken(tokens, "напомин") {
|
||||||
add("SCHEDULE_REMINDER")
|
add("SCHEDULE_REMINDER")
|
||||||
}
|
}
|
||||||
@@ -529,6 +539,14 @@ func capabilityHintsFor(primary, secondary interaction.SpeechAct, tokens []strin
|
|||||||
return values
|
return values
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func isCreativeRequestTokens(tokens []string) bool {
|
||||||
|
if containsStemInTokens(tokens, "нарис", "рису", "изобраз") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return containsStemInTokens(tokens, "расска", "раска", "сочин", "придум") &&
|
||||||
|
containsStemInTokens(tokens, "сказк", "истор", "стих", "шутк", "песн", "басн")
|
||||||
|
}
|
||||||
|
|
||||||
// sourceDependentQuestion identifies semantic classes whose answer depends on
|
// sourceDependentQuestion identifies semantic classes whose answer depends on
|
||||||
// a current or externally observed source. It intentionally uses no named
|
// a current or externally observed source. It intentionally uses no named
|
||||||
// place, person or one-off question branch; when the cue is absent the
|
// place, person or one-off question branch; when the cue is absent the
|
||||||
@@ -592,6 +610,12 @@ func informationRequestKind(message string, candidate interaction.SemanticCandid
|
|||||||
if len(tokens) == 0 {
|
if len(tokens) == 0 {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
if containsStemInTokens(tokens, "памят", "помнишь", "ячейк") && (containsMeaningfulInterrogative(tokens) || containsStemInTokens(tokens, "вывед", "покаж", "напиш", "сообщ")) {
|
||||||
|
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, "настро"))
|
||||||
@@ -613,6 +637,48 @@ 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 ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsCreativeRequest recognizes generation requests rather than retrieval of
|
||||||
|
// externally verifiable facts. The cognitive route remains responsible for
|
||||||
|
// the requested style and content.
|
||||||
|
func IsCreativeRequest(message string) bool {
|
||||||
|
tokens := semanticTokens(message)
|
||||||
|
return isCreativeRequestTokens(tokens)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreativeDeterministicReply covers simple geometric sketches that do not
|
||||||
|
// need a model or external source. Rich creative content remains cognitive.
|
||||||
|
func CreativeDeterministicReply(message string) string {
|
||||||
|
tokens := semanticTokens(message)
|
||||||
|
if containsStemInTokens(tokens, "нарис", "рису", "изобраз") && containsStemInTokens(tokens, "круг", "окруж") {
|
||||||
|
return "◯"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreativeFallbackReply keeps a small creative conversation useful when the
|
||||||
|
// cognitive channel is unavailable. It is not used when cognition returns a
|
||||||
|
// completed richer answer.
|
||||||
|
func CreativeFallbackReply(message string) string {
|
||||||
|
tokens := semanticTokens(message)
|
||||||
|
if IsCreativeRequest(message) && containsStemInTokens(tokens, "сказк", "басн") && containsStemInTokens(tokens, "колоб") {
|
||||||
|
return "Жили-были дед и баба. Испекли они Колобка, а он убежал в лес. Встретил зайца, волка и медведя — от всех укатился, но лису перехитрить не смог. Так Колобок понял: хвастовство и беспечность до добра не доводят."
|
||||||
|
}
|
||||||
|
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 {
|
||||||
@@ -792,3 +858,9 @@ func removeCapabilityHint(values []string, denied string) []string {
|
|||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RemoveCapabilityHint lets orchestration boundaries suppress a route that
|
||||||
|
// contradicts an already understood semantic class.
|
||||||
|
func RemoveCapabilityHint(values []string, denied string) []string {
|
||||||
|
return removeCapabilityHint(values, denied)
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package domain
|
package domain
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -198,11 +199,79 @@ func TestNamingPreferenceIsSemanticAndProducesNaturalAcceptance(t *testing.T) {
|
|||||||
if name := PreferredAssistantName("я назову тебя дед, запомни"); name != "Дед" {
|
if name := PreferredAssistantName("я назову тебя дед, запомни"); name != "Дед" {
|
||||||
t.Fatalf("expected conversational name form to be extracted, got %q", name)
|
t.Fatalf("expected conversational name form to be extracted, got %q", name)
|
||||||
}
|
}
|
||||||
|
if name := PreferredAssistantName("давай переименуем тебя в фею. теперь тебя зовут фея"); name != "Фея" {
|
||||||
|
t.Fatalf("rename phrase returned %q", name)
|
||||||
|
}
|
||||||
if !IsIdentityInquiry("ты кто?") || !IsIdentityInquiry("как тебя зовут") {
|
if !IsIdentityInquiry("ты кто?") || !IsIdentityInquiry("как тебя зовут") {
|
||||||
t.Fatal("identity variants should be recognized")
|
t.Fatal("identity variants should be recognized")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestMemoryInventoryRequestIsSemantic(t *testing.T) {
|
||||||
|
for _, message := range []string{"выведи свою память", "напиши что ты помнишь в виде таблицы"} {
|
||||||
|
candidate := BuildDeterministicCandidate(message, "", time.Unix(10, 0).UnixMilli())
|
||||||
|
if got := informationRequestKind(message, candidate); got != interaction.InformationRequestMemoryInventory {
|
||||||
|
t.Fatalf("%q: expected memory inventory, got %q", message, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreativeRequestsDoNotRouteToWebResearch(t *testing.T) {
|
||||||
|
for _, message := range []string{"нарисуй круг", "расскажи сказку о колобке"} {
|
||||||
|
candidate := BuildDeterministicCandidate(message, "", time.Now().UnixMilli())
|
||||||
|
t.Logf("%q candidate=%+v", message, candidate)
|
||||||
|
for _, hint := range candidate.CapabilityHints {
|
||||||
|
if hint == "WEB_RESEARCH" {
|
||||||
|
t.Fatalf("creative request %q unexpectedly selected web research: %+v", message, candidate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInterpretCreativeRequestDoesNotRequireExternalEvidence(t *testing.T) {
|
||||||
|
utterance := interaction.HumanUtterance{Content: "нарисуй круг"}
|
||||||
|
result, err := InterpretUtterance(utterance, nil, nil, time.Now())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Logf("semantic result=%+v", result)
|
||||||
|
if result.Interpretation.SpeechAct == interaction.SpeechActQuestion || containsString(result.CapabilityHints, "WEB_RESEARCH") {
|
||||||
|
t.Fatalf("creative request was routed as external research: %+v", result)
|
||||||
|
}
|
||||||
|
if got := CreativeDeterministicReply("нарисуй круг"); got != "◯" {
|
||||||
|
t.Fatalf("circle reply = %q", got)
|
||||||
|
}
|
||||||
|
if !IsCreativeRequest("расскажи сказку о колобке") {
|
||||||
|
t.Fatal("story request was not recognized as creative")
|
||||||
|
}
|
||||||
|
if got := CreativeFallbackReply("расскажи сказку о колобке"); !strings.Contains(got, "Колоб") {
|
||||||
|
t.Fatalf("story fallback = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsString(values []string, expected string) bool {
|
||||||
|
for _, value := range values {
|
||||||
|
if value == expected {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
|||||||
@@ -69,10 +69,52 @@ func TestStripAssistantVocative(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestIndependentRequestParts(t *testing.T) {
|
||||||
|
parts := IndependentRequestParts("Дед, узнай погоду в Сочи и найди ресторан")
|
||||||
|
if len(parts) != 2 || parts[0] != "узнай погоду в Сочи" || parts[1] != "найди ресторан" {
|
||||||
|
t.Fatalf("unexpected request parts: %#v", parts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLocalSearchClarification(t *testing.T) {
|
||||||
|
if got := LocalSearchClarification("найди ближайший ресторан"); got == "" {
|
||||||
|
t.Fatal("proximity search without place must ask for location")
|
||||||
|
}
|
||||||
|
if got := LocalSearchClarification("найди ближайший ресторан в Сочи"); got != "" {
|
||||||
|
t.Fatalf("explicit place must proceed, got %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContinueLocalSearch(t *testing.T) {
|
||||||
|
history := []interaction.HumanUtterance{{Content: "Найди ближайший ресторан"}}
|
||||||
|
if got := ContinueLocalSearch("в Сочи", history); got != "Найди ближайший ресторан в Сочи" {
|
||||||
|
t.Fatalf("unexpected continuation: %q", got)
|
||||||
|
}
|
||||||
|
if got := ContinueLocalSearch("в Сочи", nil); got != "" {
|
||||||
|
t.Fatalf("location must not create a goal without conversation context: %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContinueTravelOrigin(t *testing.T) {
|
||||||
|
history := []interaction.HumanUtterance{{Content: "Как можно добраться до Сочи?"}}
|
||||||
|
if got := ContinueTravelOrigin("я в Казани", history); got != "Как можно добраться до Сочи из Казани" {
|
||||||
|
t.Fatalf("unexpected travel continuation: %q", got)
|
||||||
|
}
|
||||||
|
if got := ContinueTravelOrigin("я в Казани", nil); got != "" {
|
||||||
|
t.Fatalf("location must not create a travel task without context: %q", got)
|
||||||
|
}
|
||||||
|
if got := ContinueTravelOrigin("Москва", history); got != "Как можно добраться до Сочи из города Москва" {
|
||||||
|
t.Fatalf("bare city should complete travel origin: %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestTravelSearchClarification(t *testing.T) {
|
func TestTravelSearchClarification(t *testing.T) {
|
||||||
if got := TravelSearchClarification("Найди билеты", nil); got == "" {
|
if got := TravelSearchClarification("Найди билеты", nil); got == "" {
|
||||||
t.Fatal("underspecified travel request must ask for missing route and date")
|
t.Fatal("underspecified travel request must ask for missing route and date")
|
||||||
}
|
}
|
||||||
|
if got := TravelSearchClarification("Покажи ближайшие рейсы до Сочи", nil); got != "Из какого города вылетать?" {
|
||||||
|
t.Fatalf("nearest-flight request should default date to now, got %q", got)
|
||||||
|
}
|
||||||
if got := TravelSearchClarification("Найди билеты из Москвы в Сочи на 12 сентября", nil); got != "" {
|
if got := TravelSearchClarification("Найди билеты из Москвы в Сочи на 12 сентября", nil); got != "" {
|
||||||
t.Fatalf("complete travel request must proceed, got %q", got)
|
t.Fatalf("complete travel request must proceed, got %q", got)
|
||||||
}
|
}
|
||||||
@@ -80,6 +122,26 @@ func TestTravelSearchClarification(t *testing.T) {
|
|||||||
if got := TravelSearchClarification("а куда летим?", history); got == "" {
|
if got := TravelSearchClarification("а куда летим?", history); got == "" {
|
||||||
t.Fatal("follow-up must remain attached to the travel goal")
|
t.Fatal("follow-up must remain attached to the travel goal")
|
||||||
}
|
}
|
||||||
|
if got := TravelSearchClarification("какая погода в Сочи?", history); got != "" {
|
||||||
|
t.Fatalf("unrelated question must not inherit travel goal, got %q", got)
|
||||||
|
}
|
||||||
|
if got := TravelSearchClarification("Как можно добраться до Сочи?", nil); got != "Из какого города выезжать в Сочи? Подберу самолёт, поезд, автобус или машину." {
|
||||||
|
t.Fatalf("general travel question should ask departure city, got %q", got)
|
||||||
|
}
|
||||||
|
if got := TravelSearchClarification("Как можно добраться до Сочи из Казани", nil); got != "" {
|
||||||
|
t.Fatalf("complete general travel route must proceed, got %q", got)
|
||||||
|
}
|
||||||
|
contextHistory := []interaction.HumanUtterance{{Content: "Как можно добраться до Сочи?"}}
|
||||||
|
if got := TravelSearchClarification("Найди билеты, какой ближайший самолёт", contextHistory); got != "Из какого города вылетать в Сочи?" {
|
||||||
|
t.Fatalf("travel destination should be inherited from context, got %q", got)
|
||||||
|
}
|
||||||
|
noisyContext := []interaction.HumanUtterance{
|
||||||
|
{Content: "Как можно добраться до Сочи?"},
|
||||||
|
{Content: "Какая погода в Питере?"},
|
||||||
|
}
|
||||||
|
if got := TravelSearchClarification("Найди билеты", noisyContext); got != "Из какого города вылетать в Сочи и на какую дату?" {
|
||||||
|
t.Fatalf("unrelated weather history must not replace travel destination, got %q", got)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestInterpretUtteranceDirectiveRecordsOutcomeWithoutExecution(t *testing.T) {
|
func TestInterpretUtteranceDirectiveRecordsOutcomeWithoutExecution(t *testing.T) {
|
||||||
|
|||||||
@@ -25,12 +25,128 @@ func StripAssistantVocative(message string) string {
|
|||||||
return trimmed
|
return trimmed
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IndependentRequestParts keeps separate user actions visible to the
|
||||||
|
// orchestrator. It is intentionally limited to the ordinary coordinating
|
||||||
|
// conjunction; the cognitive route remains responsible for ambiguous prose.
|
||||||
|
func IndependentRequestParts(message string) []string {
|
||||||
|
cleaned := StripAssistantVocative(message)
|
||||||
|
parts := strings.Split(cleaned, " и ")
|
||||||
|
if len(parts) < 2 {
|
||||||
|
return []string{cleaned}
|
||||||
|
}
|
||||||
|
result := make([]string, 0, len(parts))
|
||||||
|
for _, part := range parts {
|
||||||
|
part = strings.TrimSpace(part)
|
||||||
|
if part != "" {
|
||||||
|
result = append(result, part)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(result) < 2 {
|
||||||
|
return []string{cleaned}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// LocalSearchClarification prevents a proximity search from silently using a
|
||||||
|
// default city when the user did not provide a place.
|
||||||
|
func LocalSearchClarification(message string) string {
|
||||||
|
tokens := semanticTokens(StripAssistantVocative(message))
|
||||||
|
if !containsStemInTokens(tokens, "ресторан", "кафе") || !containsStemInTokens(tokens, "ближ", "рядом") {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
for index, token := range tokens {
|
||||||
|
if token != "в" && token != "на" && token != "около" && !containsStem(token, "район", "город") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if index+1 < len(tokens) || containsStem(token, "район", "город") {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "В каком городе или районе искать ресторан?"
|
||||||
|
}
|
||||||
|
|
||||||
|
// ContinueLocalSearch turns a location-only follow-up into the previous local
|
||||||
|
// search request, but only when that request is present in this conversation.
|
||||||
|
func ContinueLocalSearch(message string, history []interaction.HumanUtterance) string {
|
||||||
|
current := strings.TrimSpace(StripAssistantVocative(message))
|
||||||
|
tokens := semanticTokens(current)
|
||||||
|
if len(tokens) == 0 || len(tokens) > 3 || (tokens[0] != "в" && tokens[0] != "на" && tokens[0] != "около") {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
var latest *interaction.HumanUtterance
|
||||||
|
for index := range history {
|
||||||
|
candidate := history[index]
|
||||||
|
candidateText := strings.TrimSpace(StripAssistantVocative(candidate.Content))
|
||||||
|
candidateTokens := semanticTokens(candidateText)
|
||||||
|
if !containsStemInTokens(candidateTokens, "ресторан", "кафе") || !containsStemInTokens(candidateTokens, "ближ", "рядом") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if latest == nil || candidate.ReceivedAtUnixMillis > latest.ReceivedAtUnixMillis {
|
||||||
|
latest = &candidate
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if latest != nil {
|
||||||
|
previous := strings.TrimSpace(StripAssistantVocative(latest.Content))
|
||||||
|
return strings.TrimSpace(previous + " " + current)
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// ContinueTravelOrigin turns a short location answer into the previous travel
|
||||||
|
// task. The original utterance remains history; only the effective task is
|
||||||
|
// completed for routing and research.
|
||||||
|
func ContinueTravelOrigin(message string, history []interaction.HumanUtterance) string {
|
||||||
|
current := semanticTokens(StripAssistantVocative(message))
|
||||||
|
if len(current) == 0 || len(current) > 6 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
location := ""
|
||||||
|
if current[0] == "я" {
|
||||||
|
if len(current) < 3 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
for index, token := range current {
|
||||||
|
if (token == "в" || token == "из") && index+1 < len(current) {
|
||||||
|
location = capitalizeWord(current[index+1])
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if len(current) <= 2 && !isTravelDateWord(current[0]) && len([]rune(current[0])) >= 3 {
|
||||||
|
location = capitalizeWord(current[0])
|
||||||
|
}
|
||||||
|
if location == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
var latest *interaction.HumanUtterance
|
||||||
|
for index := range history {
|
||||||
|
candidate := history[index]
|
||||||
|
if !travelContextCue(semanticTokens(candidate.Content)) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if latest == nil || candidate.ReceivedAtUnixMillis > latest.ReceivedAtUnixMillis {
|
||||||
|
latest = &candidate
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if latest == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
previous := strings.TrimRight(strings.TrimSpace(StripAssistantVocative(latest.Content)), "?!.,;:")
|
||||||
|
preposition := " из "
|
||||||
|
if current[0] != "я" {
|
||||||
|
preposition = " из города "
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(previous + preposition + location)
|
||||||
|
}
|
||||||
|
|
||||||
// TravelSearchClarification keeps an incomplete travel request in dialogue
|
// TravelSearchClarification keeps an incomplete travel request in dialogue
|
||||||
// instead of reducing it to an unrelated generic web search.
|
// instead of reducing it to an unrelated generic web search.
|
||||||
func TravelSearchClarification(message string, history []interaction.HumanUtterance) string {
|
func TravelSearchClarification(message string, history []interaction.HumanUtterance) string {
|
||||||
current := semanticTokens(StripAssistantVocative(message))
|
current := semanticTokens(StripAssistantVocative(message))
|
||||||
travel := travelCue(current)
|
travel := travelCue(current)
|
||||||
if !travel {
|
if !travel {
|
||||||
|
travel = containsStemInTokens(current, "добрат", "передвиг", "поех", "дорог")
|
||||||
|
}
|
||||||
|
if !travel && travelFollowUpCue(current) {
|
||||||
for index := len(history) - 1; index >= 0; index-- {
|
for index := len(history) - 1; index >= 0; index-- {
|
||||||
if travelCue(semanticTokens(history[index].Content)) {
|
if travelCue(semanticTokens(history[index].Content)) {
|
||||||
travel = true
|
travel = true
|
||||||
@@ -44,6 +160,9 @@ func TravelSearchClarification(message string, history []interaction.HumanUttera
|
|||||||
origin := containsStemInTokens(current, "из", "откуда", "от")
|
origin := containsStemInTokens(current, "из", "откуда", "от")
|
||||||
destination := containsStemInTokens(current, "в", "куда", "до")
|
destination := containsStemInTokens(current, "в", "куда", "до")
|
||||||
date := containsStemInTokens(current, "сегодня", "завтра", "послезавтр", "январ", "феврал", "март", "апрел", "мая", "июн", "июл", "август", "сентябр", "октябр", "ноябр", "декабр")
|
date := containsStemInTokens(current, "сегодня", "завтра", "послезавтр", "январ", "феврал", "март", "апрел", "мая", "июн", "июл", "август", "сентябр", "октябр", "ноябр", "декабр")
|
||||||
|
if containsStemInTokens(current, "ближ") {
|
||||||
|
date = true
|
||||||
|
}
|
||||||
if !date {
|
if !date {
|
||||||
for _, token := range current {
|
for _, token := range current {
|
||||||
if hasDigit(token) {
|
if hasDigit(token) {
|
||||||
@@ -55,13 +174,110 @@ func TravelSearchClarification(message string, history []interaction.HumanUttera
|
|||||||
if origin && destination && date {
|
if origin && destination && date {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
ticketRequest := containsStemInTokens(current, "билет", "рейс", "самолет", "самолёт", "вылет")
|
||||||
|
if !ticketRequest && origin && destination {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if !destination {
|
||||||
|
if contextDestination := travelContextDestination(history); contextDestination != "" {
|
||||||
|
destination = true
|
||||||
|
if !origin && !date {
|
||||||
|
return "Из какого города вылетать в " + contextDestination + " и на какую дату?"
|
||||||
|
}
|
||||||
|
if !origin {
|
||||||
|
return "Из какого города вылетать в " + contextDestination + "?"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !origin {
|
||||||
|
if contextOrigin := travelContextOrigin(history); contextOrigin != "" {
|
||||||
|
origin = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if destination && !origin && !date {
|
||||||
|
if !ticketRequest {
|
||||||
|
return "Из какого города выезжать в " + destinationLabel(current, history) + "? Подберу самолёт, поезд, автобус или машину."
|
||||||
|
}
|
||||||
|
return "Из какого города вылетать и на какую дату?"
|
||||||
|
}
|
||||||
|
if destination && !origin {
|
||||||
|
return "Из какого города вылетать?"
|
||||||
|
}
|
||||||
|
if destination && !date {
|
||||||
|
return "На какую дату нужны билеты?"
|
||||||
|
}
|
||||||
return "Уточните маршрут и дату: откуда, куда и на какой день нужны билеты?"
|
return "Уточните маршрут и дату: откуда, куда и на какой день нужны билеты?"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func isTravelDateWord(value string) bool {
|
||||||
|
return containsStem(value, "сегодня", "завтра", "послезавтр", "январ", "феврал", "март", "апрел", "мая", "июн", "июл", "август", "сентябр", "октябр", "ноябр", "декабр")
|
||||||
|
}
|
||||||
|
|
||||||
|
func destinationLabel(current []string, history []interaction.HumanUtterance) string {
|
||||||
|
for index, token := range current {
|
||||||
|
if (token == "в" || token == "до") && index+1 < len(current) {
|
||||||
|
return capitalizeWord(current[index+1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if destination := travelContextDestination(history); destination != "" {
|
||||||
|
return destination
|
||||||
|
}
|
||||||
|
return "пункт назначения"
|
||||||
|
}
|
||||||
|
|
||||||
|
func travelContextDestination(history []interaction.HumanUtterance) string {
|
||||||
|
for index := len(history) - 1; index >= 0; index-- {
|
||||||
|
tokens := semanticTokens(history[index].Content)
|
||||||
|
if !travelContextCue(tokens) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for tokenIndex, token := range tokens {
|
||||||
|
if token != "в" && token != "до" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if tokenIndex+1 < len(tokens) && len([]rune(tokens[tokenIndex+1])) >= 3 {
|
||||||
|
return capitalizeWord(tokens[tokenIndex+1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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 {
|
||||||
|
return travelCue(tokens) || containsStemInTokens(tokens, "добрат", "передвиг", "ехать", "едем", "лететь", "поездк")
|
||||||
|
}
|
||||||
|
|
||||||
|
func capitalizeWord(value string) string {
|
||||||
|
runes := []rune(value)
|
||||||
|
if len(runes) == 0 {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
return strings.ToUpper(string(runes[0])) + string(runes[1:])
|
||||||
|
}
|
||||||
|
|
||||||
func travelCue(tokens []string) bool {
|
func travelCue(tokens []string) bool {
|
||||||
return containsStemInTokens(tokens, "билет", "рейс", "поезд", "автобус", "перелет", "перелёт")
|
return containsStemInTokens(tokens, "билет", "рейс", "поезд", "автобус", "перелет", "перелёт")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func travelFollowUpCue(tokens []string) bool {
|
||||||
|
return containsStemInTokens(tokens, "куда", "откуда", "маршрут", "летим", "дата", "число")
|
||||||
|
}
|
||||||
|
|
||||||
func hasDigit(value string) bool {
|
func hasDigit(value string) bool {
|
||||||
for _, runeValue := range value {
|
for _, runeValue := range value {
|
||||||
if runeValue >= '0' && runeValue <= '9' {
|
if runeValue >= '0' && runeValue <= '9' {
|
||||||
|
|||||||
Reference in New Issue
Block a user