Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7eb2f5f313 | ||
|
|
39a27102c9 | ||
|
|
7ac9a2697c | ||
|
|
f2e8ec08c5 | ||
|
|
1cfbb4ae66 | ||
|
|
7618a0bcbe | ||
|
|
dcdc9a2e64 | ||
|
|
5783faf9dc | ||
|
|
9a968fe2f6 | ||
|
|
41d4d7202f | ||
|
|
ed3932c57a | ||
|
|
3367361483 | ||
|
|
51638d6e8c | ||
|
|
0a1ad9f7d5 | ||
|
|
4d51e65226 |
@@ -112,9 +112,6 @@ func parseInterpretationCandidate(text string) (cognitive.GatewayInterpretationC
|
||||
if candidate.SecondarySpeechAct != "" && !validSpeechAct(candidate.SecondarySpeechAct) {
|
||||
return cognitive.GatewayInterpretationCandidate{}, false
|
||||
}
|
||||
if candidate.SecondarySpeechAct == "" {
|
||||
candidate.SecondarySpeechAct = "UNKNOWN"
|
||||
}
|
||||
switch candidate.Applicability {
|
||||
case cognitive.InterpretationApplicable, cognitive.InterpretationLowConfidence, cognitive.InterpretationMixedIntent, cognitive.InterpretationNeedsBroader, cognitive.InterpretationClarificationRequired:
|
||||
default:
|
||||
@@ -123,11 +120,6 @@ func parseInterpretationCandidate(text string) (cognitive.GatewayInterpretationC
|
||||
if candidate.Clarification != "NOT_REQUIRED" && candidate.Clarification != "REQUIRED" {
|
||||
return cognitive.GatewayInterpretationCandidate{}, false
|
||||
}
|
||||
for _, hint := range candidate.CapabilityHints {
|
||||
if !validCapabilityKind(hint) {
|
||||
return cognitive.GatewayInterpretationCandidate{}, false
|
||||
}
|
||||
}
|
||||
return candidate, true
|
||||
}
|
||||
|
||||
@@ -139,25 +131,6 @@ func validSpeechAct(value string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func validCapabilityKind(value capability.CapabilityKind) bool {
|
||||
switch value {
|
||||
case capability.CapabilityKindReadEmail,
|
||||
capability.CapabilityKindSendEmail,
|
||||
capability.CapabilityKindReadDatabase,
|
||||
capability.CapabilityKindQueryLogs,
|
||||
capability.CapabilityKindInspectProject,
|
||||
capability.CapabilityKindModifyCode,
|
||||
capability.CapabilityKindRunTests,
|
||||
capability.CapabilityKindWebResearch,
|
||||
capability.CapabilityKindCognitiveReasoning,
|
||||
capability.CapabilityKindScheduleReminder,
|
||||
capability.CapabilityKindVerifyFact:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func writeInterpretationResponse(w http.ResponseWriter, response cognitive.GatewayInterpretationResponse) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(response)
|
||||
|
||||
@@ -17,7 +17,6 @@ import (
|
||||
"git.cin.su/m/Assistant/contracts/cognitive"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
"git.cin.su/m/Assistant/contracts/interaction"
|
||||
"git.cin.su/m/Assistant/platform/ids"
|
||||
"git.cin.su/m/Assistant/contracts/situation"
|
||||
interactiondomain "git.cin.su/m/Assistant/modules/interaction/domain"
|
||||
)
|
||||
@@ -75,32 +74,7 @@ func TestLiveInterpretationTrace(t *testing.T) {
|
||||
now: time.Now,
|
||||
allowCanary: true,
|
||||
}
|
||||
for _, message := range []string{
|
||||
"расскажи как это работает",
|
||||
"Расскажи, как это работает?",
|
||||
"Расскажи как это работает",
|
||||
"можешь объяснить почему база растёт",
|
||||
"почему postgres использует столько памяти",
|
||||
"ПОЧЕМУ postgres использует так много памяти",
|
||||
"домовой не видит ии",
|
||||
"домовой не вижит ии",
|
||||
"разберись почему сервис упал",
|
||||
"посмотри что произошло",
|
||||
"исправь ошибку если найдёшь",
|
||||
"разберись почему падает и исправь если причина очевидна",
|
||||
"нет не UPO а UPO2",
|
||||
"нет не UPO а UPO2 и обнови конфиг",
|
||||
"postgres сейчас работает",
|
||||
"основная база называется UPO",
|
||||
"привет",
|
||||
"спасибо",
|
||||
"ты кто",
|
||||
"ты кто?",
|
||||
"как тебя зовут",
|
||||
"кто ты вообще",
|
||||
"что ты думаешь",
|
||||
"расскажи подробнее",
|
||||
} {
|
||||
for _, message := range []string{"ты кто", "можешь расказать об утре"} {
|
||||
conversation := interaction.Conversation{ID: "trace-conversation", ActorID: "trace-actor", PrincipalID: "domovoy-creator-principal", Channel: interaction.ChannelWebChat, State: interaction.ConversationOpen}
|
||||
utterance, _, _, err := interactiondomain.NewHumanUtterance(conversation, interaction.ChatMessageRequest{Message: message}, time.Now())
|
||||
if err != nil {
|
||||
@@ -147,27 +121,15 @@ func TestLiveInterpretationTrace(t *testing.T) {
|
||||
if rawResponse == "" {
|
||||
t.Fatalf("message=%q raw response is empty", message)
|
||||
}
|
||||
cognitiveCandidate, err := cognitiveCandidateFromGateway(utterance.ID, gatewayResponse.Candidate, time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
if message == "ты кто" {
|
||||
if semantic.Interpretation.SpeechAct != interaction.SpeechActQuestion || !semantic.NeedsCognition {
|
||||
t.Fatalf("semantic path still fails punctuation-free identity question: %+v", semantic.Interpretation)
|
||||
}
|
||||
if gatewayResponse.Candidate.PrimarySpeechAct != "QUESTION" {
|
||||
t.Fatalf("gateway did not preserve question semantics: %+v", gatewayResponse.Candidate)
|
||||
}
|
||||
}
|
||||
selected := interactiondomain.ApplyCognitiveCandidate(semantic, utterance.Content, cognitiveCandidate, nil)
|
||||
cognitionUsed := selected.Interpretation.Source == string(interaction.CandidateSourceCognitive)
|
||||
clarificationReason := string(selected.Interpretation.Clarification)
|
||||
t.Logf("TRACE message=%q", message)
|
||||
deterministic := semantic.Candidates[0]
|
||||
t.Logf(" deterministic candidate: %+v", deterministic)
|
||||
t.Logf(" raw response=%q", truncate(rawResponse, 180))
|
||||
t.Logf(" cognitive candidate: %+v", cognitiveCandidate)
|
||||
t.Logf(" selected interpretation: act=%s secondary=%s selection_source=%s needs_cognition=%t",
|
||||
selected.Interpretation.SpeechAct,
|
||||
selected.Interpretation.SecondarySpeechAct,
|
||||
selected.Interpretation.Source,
|
||||
selected.Interpretation.NeedsCognition,
|
||||
)
|
||||
t.Logf(" cognition used: %t", cognitionUsed)
|
||||
t.Logf(" clarification reason: %s", clarificationReason)
|
||||
t.Logf(" reply=%q", selected.Reply)
|
||||
t.Logf("TRACE message=%q deterministic=%s/%s needs_cognition=%t raw=%q gateway_candidate=%+v", message, semantic.Interpretation.SpeechAct, semantic.Interpretation.Applicability, semantic.NeedsCognition, truncate(rawResponse, 180), gatewayResponse.Candidate)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,30 +217,3 @@ func truncate(value string, max int) string {
|
||||
}
|
||||
return value[:max] + "..."
|
||||
}
|
||||
|
||||
func cognitiveCandidateFromGateway(utteranceID interaction.HumanUtteranceID, candidate cognitive.GatewayInterpretationCandidate, now interface{ UnixMilli() int64 }) (interaction.SemanticCandidate, error) {
|
||||
id, err := ids.New()
|
||||
if err != nil {
|
||||
return interaction.SemanticCandidate{}, err
|
||||
}
|
||||
capabilityHints := make([]string, 0, len(candidate.CapabilityHints))
|
||||
for _, hint := range candidate.CapabilityHints {
|
||||
capabilityHints = append(capabilityHints, string(hint))
|
||||
}
|
||||
return interaction.SemanticCandidate{
|
||||
ID: interaction.SemanticCandidateID(id),
|
||||
UtteranceID: utteranceID,
|
||||
Source: interaction.CandidateSourceCognitive,
|
||||
SelectionState: interaction.CandidateSelected,
|
||||
PrimarySpeechAct: interaction.SpeechAct(candidate.PrimarySpeechAct),
|
||||
SecondarySpeechAct: interaction.SpeechAct(candidate.SecondarySpeechAct),
|
||||
ConfidenceMillis: candidate.ConfidenceMillis,
|
||||
Applicability: interaction.SemanticApplicability(candidate.Applicability),
|
||||
RequestedOutcome: candidate.RequestedOutcome,
|
||||
Clarification: interaction.ClarificationState(candidate.Clarification),
|
||||
NeedsCognition: candidate.NeedsCognition,
|
||||
SelectionReason: candidate.SelectionReason,
|
||||
CapabilityHints: capabilityHints,
|
||||
RecordedAtUnixMillis: now.UnixMilli(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/capability"
|
||||
)
|
||||
|
||||
func TestParseInterpretationCandidateNormalizesOmittedSecondarySpeechAct(t *testing.T) {
|
||||
candidate, ok := parseInterpretationCandidate(`{"primary_speech_act":"QUESTION","confidence_millis":800,"applicability":"APPLICABLE","clarification":"NOT_REQUIRED"}`)
|
||||
if !ok {
|
||||
t.Fatal("expected valid candidate")
|
||||
}
|
||||
if candidate.SecondarySpeechAct != "UNKNOWN" {
|
||||
t.Fatalf("expected omitted secondary speech act to normalize to UNKNOWN, got %q", candidate.SecondarySpeechAct)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseInterpretationCandidateRejectsUnknownCapabilityHint(t *testing.T) {
|
||||
_, ok := parseInterpretationCandidate(`{"primary_speech_act":"QUESTION","confidence_millis":800,"applicability":"APPLICABLE","clarification":"NOT_REQUIRED","capability_hints":["INVENTED_CAPABILITY"]}`)
|
||||
if ok {
|
||||
t.Fatal("expected unknown capability hint to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidCapabilityKindMatchesContractEnum(t *testing.T) {
|
||||
if !validCapabilityKind(capability.CapabilityKindCognitiveReasoning) {
|
||||
t.Fatal("expected cognitive reasoning capability to be valid")
|
||||
}
|
||||
if validCapabilityKind(capability.CapabilityKind("INVENTED_CAPABILITY")) {
|
||||
t.Fatal("invented capability must be invalid")
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,12 @@ func (c cognitiveInterpretationClient) Interpret(ctx context.Context, request co
|
||||
}
|
||||
|
||||
func shouldRequestBroaderInterpretation(result interactiondomain.SemanticResult) bool {
|
||||
return interactiondomain.ShouldAttemptCognitive(result)
|
||||
switch result.Interpretation.Applicability {
|
||||
case interaction.SemanticNeedsBroaderInterpret, interaction.SemanticLowConfidence, interaction.SemanticMixedIntent:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func buildGatewayInterpretationRequest(session identity.CreatorSession, utterance interaction.HumanUtterance, semantic interactiondomain.SemanticResult, projectNames []string) cognitive.GatewayInterpretationRequest {
|
||||
@@ -117,4 +122,4 @@ func capabilityHintStrings(values []capability.CapabilityKind) []string {
|
||||
result = append(result, string(value))
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -293,7 +293,7 @@ func main() {
|
||||
http.Error(w, "interpret chat message", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if interactiondomain.ShouldAttemptCognitive(semantic) {
|
||||
if shouldRequestBroaderInterpretation(semantic) {
|
||||
projectNames := make([]string, 0, len(semantic.Projects))
|
||||
for _, ref := range semantic.Projects {
|
||||
if ref.ProjectDisplayName != "" {
|
||||
@@ -1170,4 +1170,4 @@ func evidenceRefsToEpistemics(values []work.EvidenceRef) []epistemics.EvidenceRe
|
||||
result = append(result, epistemics.EvidenceRef(value))
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,29 @@ func TestChatPageServedWithoutInternalIDs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicSurfacesSeparateChatAndConsole(t *testing.T) {
|
||||
handler, err := newHandler("http://core", "http://continuity", "http://commit", http.DefaultClient, "http://cognitive")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, test := range []struct {
|
||||
path string
|
||||
must string
|
||||
mustNot string
|
||||
}{
|
||||
{path: "/", must: "Напишите Домовому обычное сообщение", mustNot: "context-preset"},
|
||||
{path: "/admin", must: "context-preset", mustNot: "Напишите Домовому обычное сообщение"},
|
||||
{path: "/chat", must: "Напишите Домовому обычное сообщение", mustNot: "context-preset"},
|
||||
} {
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, test.path, nil))
|
||||
body := recorder.Body.String()
|
||||
if recorder.Code != http.StatusOK || !strings.Contains(body, test.must) || strings.Contains(body, test.mustNot) {
|
||||
t.Fatalf("%s response=%d contains expected=%t forbidden=%t", test.path, recorder.Code, strings.Contains(body, test.must), strings.Contains(body, test.mustNot))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatMessageUsesCoreAndLocalOnlyCognitiveGateway(t *testing.T) {
|
||||
var cognitiveRequest cognitive.GatewayAdvisoryRequest
|
||||
core := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -112,7 +112,12 @@ func (g *gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/" {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
serveEmbeddedHTML(w, "chat.html")
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/admin" {
|
||||
serveEmbeddedHTML(w, "index.html")
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/chat" {
|
||||
r = r.Clone(r.Context())
|
||||
@@ -122,6 +127,17 @@ func (g *gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
g.static.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
func serveEmbeddedHTML(w http.ResponseWriter, name string) {
|
||||
body, err := staticFiles.ReadFile("static/" + name)
|
||||
if err != nil {
|
||||
http.Error(w, "page unavailable", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = w.Write(body)
|
||||
}
|
||||
|
||||
type browserAdvisoryRequest struct {
|
||||
Message string `json:"message"`
|
||||
SessionID string `json:"session_id"`
|
||||
|
||||
@@ -229,7 +229,7 @@ func TestConsoleAndSecurityHeaders(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
request := httptest.NewRequest(http.MethodGet, "/admin", nil)
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), "Домовой") ||
|
||||
@@ -237,8 +237,13 @@ func TestConsoleAndSecurityHeaders(t *testing.T) {
|
||||
!strings.Contains(response.Body.String(), "context-state") ||
|
||||
!strings.Contains(response.Body.String(), "copy-context") ||
|
||||
!strings.Contains(response.Body.String(), "К содержимому") ||
|
||||
!strings.Contains(response.Body.String(), "aria-current=\"page\"") ||
|
||||
!strings.Contains(response.Body.String(), "aria-current=\"location\"") ||
|
||||
!strings.Contains(response.Body.String(), "section-nav-link") ||
|
||||
!strings.Contains(response.Body.String(), "data-page=\"overview\"") ||
|
||||
!strings.Contains(response.Body.String(), "data-page=\"diagnostics\"") ||
|
||||
!strings.Contains(response.Body.String(), "data-page=\"operations\"") ||
|
||||
!strings.Contains(response.Body.String(), "data-page=\"learning\"") ||
|
||||
!strings.Contains(response.Body.String(), "data-page=\"settings\"") ||
|
||||
!strings.Contains(response.Body.String(), "satisfaction-dialog") || !strings.Contains(response.Body.String(), "Подтверждаю переход") ||
|
||||
!strings.Contains(response.Body.String(), "action-history") || !strings.Contains(response.Body.String(), "Журнал действий") ||
|
||||
!strings.Contains(response.Body.String(), "advisory-form") || !strings.Contains(response.Body.String(), "Спросить Домового") ||
|
||||
|
||||
@@ -190,7 +190,7 @@ async function sendChatMessage(text, options = {}) {
|
||||
activateTab("today-panel");
|
||||
}
|
||||
} catch {
|
||||
appendMessage("assistant", "Не могу отправить сообщение. Попробуйте ещё раз.");
|
||||
appendMessage("assistant", "Чат сейчас недоступен. Сообщение не принято runtime.");
|
||||
} finally {
|
||||
sendButton.disabled = false;
|
||||
messageInput.focus();
|
||||
|
||||
@@ -114,7 +114,7 @@ button:focus-visible, input:focus-visible, textarea:focus-visible, select:focus-
|
||||
.secondary-button { height: 42px; margin-top: 20px; color: #11150f; background: var(--signal); font-size: 12px; }
|
||||
.section-nav { display: grid; gap: 3px; margin-top: 4px; }
|
||||
.section-nav-link { display: grid; grid-template-columns: 28px 1fr; gap: 2px 10px; padding: 11px 10px; border-left: 2px solid transparent; color: var(--muted); text-decoration: none; transition: background .18s, border-color .18s, color .18s; }
|
||||
.section-nav-link:hover, .section-nav-link:focus-visible, .section-nav-link.active, .section-nav-link[aria-current="page"] { border-left-color: var(--signal); color: var(--ink); background: rgba(201,168,95,.07); outline: 0; }
|
||||
.section-nav-link:hover, .section-nav-link:focus-visible, .section-nav-link.active, .section-nav-link[aria-current="location"] { border-left-color: var(--signal); color: var(--ink); background: rgba(201,168,95,.07); outline: 0; }
|
||||
.section-nav-link span { grid-row: 1 / span 2; color: var(--signal); font: 9px/1.4 var(--mono); }
|
||||
.section-nav-link b { font: 600 11px/1.2 var(--sans); }
|
||||
.section-nav-link small { color: var(--faint); font: 9px/1.2 var(--mono); }
|
||||
@@ -123,6 +123,7 @@ button:focus-visible, input:focus-visible, textarea:focus-visible, select:focus-
|
||||
.session-stamp strong { overflow: hidden; color: var(--muted); font: 10px/1.4 var(--mono); text-overflow: ellipsis; }
|
||||
|
||||
.workspace { grid-column: 2; grid-row: 2; width: min(100%, 1740px); justify-self: start; padding: 42px clamp(24px, 3vw, 48px) 64px; min-width: 0; }
|
||||
.workspace > [data-page][hidden] { display: none !important; }
|
||||
.workspace > section { scroll-margin-top: 94px; }
|
||||
.workspace-head { display: flex; align-items: end; justify-content: space-between; gap: 24px; margin-bottom: 34px; }
|
||||
.workspace-head h1 { margin: 0; font: 400 clamp(34px, 4vw, 50px)/1 var(--serif); letter-spacing: -.035em; }
|
||||
@@ -378,7 +379,7 @@ html[data-reduced-motion="true"] *, html[data-reduced-motion="true"] *::before,
|
||||
.workspace { padding: 30px 16px 50px; }
|
||||
.section-nav { display: flex; gap: 6px; margin: 10px -18px -24px; padding: 10px 18px; overflow-x: auto; border-top: 1px solid var(--line-soft); background: #0e1512; scrollbar-width: thin; }
|
||||
.section-nav-link { min-width: 142px; padding: 10px; border-left: 0; border-bottom: 2px solid transparent; }
|
||||
.section-nav-link:hover, .section-nav-link:focus-visible, .section-nav-link.active, .section-nav-link[aria-current="page"] { border-left-color: transparent; border-bottom-color: var(--signal); }
|
||||
.section-nav-link:hover, .section-nav-link:focus-visible, .section-nav-link.active, .section-nav-link[aria-current="location"] { border-left-color: transparent; border-bottom-color: var(--signal); }
|
||||
.workspace-head { align-items: start; flex-direction: column; }
|
||||
.last-update { text-align: left; }
|
||||
.signal-strip { grid-template-columns: 1fr; }
|
||||
|
||||
@@ -20,37 +20,29 @@ let lastAuthorizedActionID = "";
|
||||
let advisoryPolicy = {Mode: "deterministic", ExternalEgress: false, AcknowledgementRequired: false};
|
||||
let uiSettings = {density: "comfortable", refresh: "off", motion: false};
|
||||
|
||||
const sectionNavLinks = Array.from(document.querySelectorAll(".section-nav-link"));
|
||||
const cabinetSections = ["overview", "diagnostics", "operations", "settings"]
|
||||
.map((id) => byId(id))
|
||||
.filter(Boolean);
|
||||
const pageNavLinks = Array.from(document.querySelectorAll(".section-nav-link, .topbar-nav a"));
|
||||
const pageViews = Array.from(document.querySelectorAll("[data-page]"));
|
||||
const cabinetPages = ["overview", "diagnostics", "operations", "learning", "settings"];
|
||||
|
||||
function setActiveSection(id) {
|
||||
sectionNavLinks.forEach((link) => {
|
||||
const active = link.getAttribute("href") === `#${id}`;
|
||||
function setActivePage(id, updateHistory = false) {
|
||||
const page = cabinetPages.includes(id) ? id : "overview";
|
||||
pageViews.forEach((view) => { view.hidden = view.dataset.page !== page; });
|
||||
document.body.dataset.page = page;
|
||||
pageNavLinks.forEach((link) => {
|
||||
const active = link.getAttribute("href") === `#${page}`;
|
||||
link.classList.toggle("active", active);
|
||||
if (active) link.setAttribute("aria-current", "page");
|
||||
if (active) link.setAttribute("aria-current", "location");
|
||||
else link.removeAttribute("aria-current");
|
||||
});
|
||||
if (updateHistory && window.location.hash !== `#${page}`) window.history.pushState({}, "", `#${page}`);
|
||||
}
|
||||
|
||||
if ("IntersectionObserver" in window) {
|
||||
const sectionObserver = new IntersectionObserver((entries) => {
|
||||
const visible = entries.filter((entry) => entry.isIntersecting)
|
||||
.sort((a, b) => b.intersectionRatio - a.intersectionRatio)[0];
|
||||
if (visible) setActiveSection(visible.target.id);
|
||||
}, {rootMargin: "-18% 0px -64% 0px", threshold: [0, .25, .6, 1]});
|
||||
cabinetSections.forEach((section) => sectionObserver.observe(section));
|
||||
}
|
||||
|
||||
sectionNavLinks.forEach((link) => link.addEventListener("click", () => {
|
||||
const id = link.getAttribute("href").slice(1);
|
||||
setActiveSection(id);
|
||||
pageNavLinks.forEach((link) => link.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
setActivePage(link.getAttribute("href").slice(1), true);
|
||||
}));
|
||||
window.addEventListener("hashchange", () => {
|
||||
const id = window.location.hash.slice(1);
|
||||
if (cabinetSections.some((section) => section.id === id)) setActiveSection(id);
|
||||
});
|
||||
window.addEventListener("popstate", () => setActivePage(window.location.hash.slice(1)));
|
||||
setActivePage(window.location.hash.slice(1));
|
||||
|
||||
function setText(id, value, fallback = "—") {
|
||||
byId(id).textContent = value === undefined || value === null || value === "" ? fallback : String(value);
|
||||
|
||||
@@ -25,12 +25,12 @@
|
||||
|
||||
<section id="chat-view" class="chat-view" hidden>
|
||||
<header class="chat-header">
|
||||
<a href="/chat" aria-label="Домовой">Домовой</a>
|
||||
<a href="/" aria-label="Домовой">Домовой</a>
|
||||
<nav class="human-nav" aria-label="Разделы Домового">
|
||||
<button class="nav-tab active" data-tab="chat-panel" type="button">Чат</button>
|
||||
<button class="nav-tab" data-tab="today-panel" type="button">Сегодня</button>
|
||||
<button class="nav-tab" data-tab="history-panel" type="button">История</button>
|
||||
<a href="/" class="operator-link">Оператор</a>
|
||||
<a href="/admin" class="operator-link">Консоль</a>
|
||||
</nav>
|
||||
<span id="active-focus">фокус: не выбран</span>
|
||||
<span id="session-state">сессия активна</span>
|
||||
|
||||
@@ -49,6 +49,7 @@
|
||||
<a href="#overview">Обзор</a>
|
||||
<a href="#diagnostics">Проверки</a>
|
||||
<a href="#operations">Операции</a>
|
||||
<a href="#learning">Опыт</a>
|
||||
<a href="#settings">Настройки</a>
|
||||
</nav>
|
||||
<button id="refresh-all" class="text-button" type="button">Обновить</button>
|
||||
@@ -97,10 +98,11 @@
|
||||
<div class="context-actions"><button class="secondary-button" type="submit">Загрузить контекст</button><button id="reset-context" class="text-button" type="button">Сбросить</button></div>
|
||||
</form>
|
||||
<nav class="section-nav" aria-label="Навигация по кабинету">
|
||||
<a class="section-nav-link active" aria-current="page" href="#overview"><span>01</span><b>Состояние</b><small>фокус и сигналы</small></a>
|
||||
<a class="section-nav-link active" aria-current="location" href="#overview"><span>01</span><b>Состояние</b><small>фокус и сигналы</small></a>
|
||||
<a class="section-nav-link" href="#diagnostics"><span>02</span><b>Проверки</b><small>доступность и границы</small></a>
|
||||
<a class="section-nav-link" href="#operations"><span>03</span><b>Операции</b><small>ожидания и действия</small></a>
|
||||
<a class="section-nav-link" href="#settings"><span>04</span><b>Настройки</b><small>интерфейс и обновление</small></a>
|
||||
<a class="section-nav-link" href="#learning"><span>04</span><b>Опыт</b><small>reflection и навыки</small></a>
|
||||
<a class="section-nav-link" href="#settings"><span>05</span><b>Настройки</b><small>интерфейс и обновление</small></a>
|
||||
</nav>
|
||||
<div class="session-stamp">
|
||||
<span>ACTOR</span>
|
||||
@@ -111,7 +113,7 @@
|
||||
</aside>
|
||||
|
||||
<main class="workspace">
|
||||
<section id="overview" class="workspace-head">
|
||||
<section id="overview" class="workspace-head" data-page="overview">
|
||||
<div>
|
||||
<p class="eyebrow">операционная картина</p>
|
||||
<h1>Состояние сейчас</h1>
|
||||
@@ -119,14 +121,14 @@
|
||||
<p id="last-update" class="last-update">Данные ещё не запрошены</p>
|
||||
</section>
|
||||
|
||||
<section class="signal-strip" aria-label="Сводка состояния">
|
||||
<section class="signal-strip" aria-label="Сводка состояния" data-page="overview">
|
||||
<div><span>ФОКУС</span><strong id="focus-signal" data-state="idle">ожидает</strong></div>
|
||||
<div><span>ЗАДАЧА</span><strong id="task-signal" data-state="idle">ожидает</strong></div>
|
||||
<div><span>CONTINUITY</span><strong id="prospective-signal" data-state="idle">ожидает</strong></div>
|
||||
<div><span>ВОЗМОЖНОСТЬ</span><strong id="capability-signal" data-state="idle">ожидает</strong></div>
|
||||
</section>
|
||||
|
||||
<section id="diagnostics" class="diagnostics-panel" aria-labelledby="diagnostics-title">
|
||||
<section id="diagnostics" class="diagnostics-panel" aria-labelledby="diagnostics-title" data-page="diagnostics">
|
||||
<header class="panel-heading">
|
||||
<div><p>Проверяемая система</p><h2 id="diagnostics-title">Диагностика кабинета</h2></div>
|
||||
<div class="panel-heading-tools"><span id="diagnostic-summary">Проверка ещё не запускалась</span><button id="run-diagnostics" class="secondary-button compact-button" type="button">Проверить всё</button></div>
|
||||
@@ -140,7 +142,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="advisor-panel" aria-labelledby="advisor-title">
|
||||
<section class="advisor-panel" aria-labelledby="advisor-title" data-page="diagnostics">
|
||||
<div class="advisor-intro">
|
||||
<p>COGNITIVE / ADVISORY V1</p>
|
||||
<h2 id="advisor-title">Спросить Домового</h2>
|
||||
@@ -168,7 +170,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="operations" class="register-panel" aria-labelledby="register-title">
|
||||
<section id="operations" class="register-panel" aria-labelledby="register-title" data-page="operations">
|
||||
<header>
|
||||
<div><p>Continuity / ближайшие</p><h2 id="register-title">Реестр ожиданий</h2></div>
|
||||
<span id="prospective-count">0 ЗАПИСЕЙ</span>
|
||||
@@ -178,7 +180,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="activity-panel" aria-labelledby="activity-title">
|
||||
<section class="activity-panel" aria-labelledby="activity-title" data-page="operations">
|
||||
<header>
|
||||
<div><p>Commit / владелец</p><h2 id="activity-title">Журнал действий</h2></div>
|
||||
<div class="activity-tools">
|
||||
@@ -191,7 +193,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="learning-panel" aria-labelledby="learning-title">
|
||||
<section id="learning" class="learning-panel" aria-labelledby="learning-title" data-page="learning">
|
||||
<header>
|
||||
<div><p>Learning / evidence</p><h2 id="learning-title">Опыт и reflection</h2></div>
|
||||
<div class="activity-tools">
|
||||
@@ -215,7 +217,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="settings" class="settings-panel" aria-labelledby="settings-title">
|
||||
<section id="settings" class="settings-panel" aria-labelledby="settings-title" data-page="settings">
|
||||
<header class="panel-heading">
|
||||
<div><p>Локальные предпочтения</p><h2 id="settings-title">Настройки рабочего кабинета</h2></div>
|
||||
<span id="settings-saved" class="settings-saved">Сохраняются в этом браузере</span>
|
||||
@@ -228,7 +230,7 @@
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="data-grid">
|
||||
<section class="data-grid" data-page="overview">
|
||||
<article class="data-card focus-card">
|
||||
<header><span class="card-number">01</span><div><p>Situation</p><h2>Активный фокус</h2></div><span id="focus-badge" class="status-badge neutral">НЕ ЗАГРУЖЕН</span></header>
|
||||
<dl>
|
||||
|
||||
@@ -8,8 +8,8 @@ services:
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:-assistant}
|
||||
POSTGRES_USER: ${POSTGRES_SUPERUSER:?POSTGRES_SUPERUSER is required}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_SUPERUSER_PASSWORD:?POSTGRES_SUPERUSER_PASSWORD is required}
|
||||
POSTGRES_USER: ${POSTGRES_SUPERUSER}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_SUPERUSER_PASSWORD}
|
||||
CONTINUITY_DB_PASSWORD: ${CONTINUITY_DB_PASSWORD}
|
||||
IDENTITY_DB_PASSWORD: ${IDENTITY_DB_PASSWORD}
|
||||
AUTHORITY_DB_PASSWORD: ${AUTHORITY_DB_PASSWORD}
|
||||
@@ -23,7 +23,7 @@ services:
|
||||
- assistant_pg:/var/lib/postgresql
|
||||
- assistant_core_secrets:/run/secrets:ro
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_SUPERUSER:?POSTGRES_SUPERUSER is required} -d ${POSTGRES_DB:-assistant}"]
|
||||
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_SUPERUSER} -d ${POSTGRES_DB:-assistant}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
@@ -95,7 +95,7 @@ services:
|
||||
POSTGRES_USER: continuity_role
|
||||
POSTGRES_PASSWORD: ${CONTINUITY_DB_PASSWORD}
|
||||
CORE_RUNTIME_URL: http://core-runtime:8080
|
||||
COMMIT_EXECUTOR_TOKEN: ${COMMIT_EXECUTOR_TOKEN:?COMMIT_EXECUTOR_TOKEN is required}
|
||||
COMMIT_EXECUTOR_TOKEN: ${COMMIT_EXECUTOR_TOKEN}
|
||||
|
||||
commit-runtime:
|
||||
build: { context: .., dockerfile: deploy/images/runtime.Dockerfile, args: { TARGET: commit-runtime, SOURCE_REVISION: "${ASSISTANT_SOURCE_REVISION:-unknown}" } }
|
||||
@@ -111,7 +111,7 @@ services:
|
||||
AUTHORITY_POSTGRES_PASSWORD: ${AUTHORITY_DB_PASSWORD}
|
||||
CORE_RUNTIME_URL: http://core-runtime:8080
|
||||
CONTINUITY_RUNTIME_URL: http://continuity-runtime:8081
|
||||
COMMIT_EXECUTOR_TOKEN: ${COMMIT_EXECUTOR_TOKEN:?COMMIT_EXECUTOR_TOKEN is required}
|
||||
COMMIT_EXECUTOR_TOKEN: ${COMMIT_EXECUTOR_TOKEN}
|
||||
NOTIFICATION_WRITE_TOKEN_FILE: /run/notification-writer/token
|
||||
NOTIFICATION_WRITE_SECRET_REF: domovoy-notification-write-v1
|
||||
# External mutation credentials belong here only via Portainer/Docker secrets/env injection.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"task_file": "dev/tasks/DEV-000074-creator-cabinet-operations.json",
|
||||
"task_id": "DEV-000074",
|
||||
"task_file": "dev/tasks/DEV-000075-creator-chat-primary-surface.json",
|
||||
"task_id": "DEV-000075",
|
||||
"task_revision": 1
|
||||
}
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
{
|
||||
"task_id": "DEV-000073",
|
||||
"task_revision": 1,
|
||||
"architecture_revision": "DEV-000072-baseline",
|
||||
"base_repo_revision": "da94ed1",
|
||||
"risk_tier": "E",
|
||||
"intent": "Make Assistant production Compose fail closed when required PostgreSQL and executor inputs are absent, without mutating neighboring projects or storing secrets in the repository.",
|
||||
"requirement_ids": [
|
||||
"Production missing inputs must fail before container startup",
|
||||
"Assistant-only deployment scope",
|
||||
"No secret values in Git",
|
||||
"No neighboring project mutation"
|
||||
],
|
||||
"allowed_change_scope": {
|
||||
"modules": [],
|
||||
"paths": [
|
||||
"deploy/docker-compose.prod.yml",
|
||||
"docs/PROJECT_STATUS.md",
|
||||
"dev/ACTIVE_TASK.json",
|
||||
"dev/tasks/DEV-000073-production-compose-fail-closed.json"
|
||||
]
|
||||
},
|
||||
"forbidden_change_scope": {
|
||||
"paths": [
|
||||
"architecture/**",
|
||||
"security/**",
|
||||
"modules/**",
|
||||
"contracts/**",
|
||||
"database/migrations/**",
|
||||
"deploy/docker-compose.dev.yml",
|
||||
".gitea/**"
|
||||
]
|
||||
},
|
||||
"allowed_architecture_delta": {
|
||||
"new_cross_module_dependencies": 0,
|
||||
"new_canonical_owners": 0,
|
||||
"new_privileges": 0,
|
||||
"new_third_party_dependencies": 0,
|
||||
"new_provider_adapters": 0,
|
||||
"new_database_owner_roles": 0
|
||||
},
|
||||
"contracts": {
|
||||
"consume": [
|
||||
"existing production Compose topology",
|
||||
"existing external secret injection"
|
||||
],
|
||||
"may_change": []
|
||||
},
|
||||
"semantic_owner": "none-production-configuration",
|
||||
"canonical_state": [],
|
||||
"state_transitions": [
|
||||
"missing required production input -> Compose validation failure",
|
||||
"all required inputs present -> existing Assistant stack topology remains unchanged"
|
||||
],
|
||||
"side_effects_and_privileges": [
|
||||
"No secret creation or storage in Git",
|
||||
"No deployment of neighboring projects",
|
||||
"Promotion only after exact artifact and health checks"
|
||||
],
|
||||
"persistence_and_migrations": [
|
||||
"No database migration",
|
||||
"No canonical state change"
|
||||
],
|
||||
"failure_retry_restart": [
|
||||
"Missing required input fails before Compose startup",
|
||||
"Existing Assistant containers remain untouched until explicit promotion"
|
||||
],
|
||||
"assumptions": [
|
||||
"Production control plane is docker-prod / docker.cin.su",
|
||||
"Required secret values remain external to the repository",
|
||||
"Neighboring Docker projects must not be included in any Compose operation"
|
||||
],
|
||||
"acceptance_scenarios": [
|
||||
"Compose rejects missing POSTGRES_SUPERUSER",
|
||||
"Compose rejects missing POSTGRES_SUPERUSER_PASSWORD",
|
||||
"Compose rejects missing COMMIT_EXECUTOR_TOKEN",
|
||||
"Compose renders with synthetic non-secret values",
|
||||
"scope check passes",
|
||||
"Assistant-only production inspection identifies exact artifact and health state"
|
||||
],
|
||||
"required_tests": [
|
||||
"docker compose config -q with missing inputs",
|
||||
"docker compose config -q with synthetic inputs",
|
||||
"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",
|
||||
"production Assistant-only health and artifact inspection"
|
||||
],
|
||||
"terminal_gap_states": [
|
||||
"BLOCKED_BY_MISSING_CAPABILITY",
|
||||
"BLOCKED_BY_CONFLICT",
|
||||
"REQUIRES_MIGRATION_DECISION"
|
||||
]
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"task_id": "DEV-000074",
|
||||
"task_revision": 1,
|
||||
"task_revision": 6,
|
||||
"architecture_revision": "DEV-000073-baseline",
|
||||
"base_repo_revision": "407275c",
|
||||
"base_repo_revision": "1cfbb4ae66e24d514e59dabafb936c35546bd418",
|
||||
"risk_tier": "E",
|
||||
"intent": "Make the authenticated Creator Web cabinet understandable and operable for a human by adding section navigation, read-only diagnostics, and browser-local interface preferences without changing domain state or authority boundaries.",
|
||||
"requirement_ids": [
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"task_id": "DEV-000075",
|
||||
"task_revision": 1,
|
||||
"architecture_revision": "DEV-000073-baseline",
|
||||
"base_repo_revision": "39a27102c9665e41f29e85bc8f82a316bbbe3962",
|
||||
"risk_tier": "E",
|
||||
"intent": "Make live conversation with Domovoy the public starting surface and keep the Creator operator console on a separate admin route.",
|
||||
"requirement_ids": [
|
||||
"Public root opens the human chat",
|
||||
"Operator console remains available at a separate admin route",
|
||||
"Existing /chat route remains compatible",
|
||||
"Chat does not expose provider, model, binding, session or workspace internals"
|
||||
],
|
||||
"allowed_change_scope": {
|
||||
"modules": ["cmd/creator-web"],
|
||||
"paths": [
|
||||
"cmd/creator-web/server.go",
|
||||
"cmd/creator-web/server_test.go",
|
||||
"cmd/creator-web/chat_test.go",
|
||||
"cmd/creator-web/static/chat.html",
|
||||
"dev/ACTIVE_TASK.json",
|
||||
"dev/tasks/DEV-000075-creator-chat-primary-surface.json"
|
||||
]
|
||||
},
|
||||
"forbidden_change_scope": {
|
||||
"paths": ["architecture/**", "security/**", "database/**", "modules/**", "contracts/**", "adapters/**", "deploy/**"]
|
||||
},
|
||||
"allowed_architecture_delta": {
|
||||
"new_cross_module_dependencies": 0,
|
||||
"new_canonical_owners": 0,
|
||||
"new_privileges": 0,
|
||||
"new_third_party_dependencies": 0,
|
||||
"new_provider_adapters": 0,
|
||||
"new_database_owner_roles": 0
|
||||
},
|
||||
"contracts": {"consume": ["existing /chat and authenticated Creator endpoints"], "may_change": []},
|
||||
"semantic_owner": "none-interface-adapter",
|
||||
"canonical_state": [],
|
||||
"state_transitions": ["GET / -> chat surface", "GET /admin -> operator console surface"],
|
||||
"side_effects_and_privileges": ["No new privilege", "No canonical mutation", "No model/provider routing change"],
|
||||
"persistence_and_migrations": ["No persistence or migration"],
|
||||
"failure_retry_restart": ["Existing chat failure behavior remains unchanged"],
|
||||
"assumptions": ["/chat is the existing human chat surface", "The operator console may be reached at /admin"],
|
||||
"acceptance_scenarios": ["Root serves chat", "Admin serves console", "Chat compatibility remains", "Internal IDs remain absent from chat HTML"],
|
||||
"required_tests": ["go test ./cmd/creator-web", "go test ./...", "go vet ./...", "devctl preflight", "devctl check-diff", "devctl check-architecture", "git diff --check"],
|
||||
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT"]
|
||||
}
|
||||
@@ -2,42 +2,6 @@
|
||||
|
||||
Audit date: 2026-08-17. Active implementation: DEV-000072 revision 1.
|
||||
|
||||
## Production recovery checkpoint — 2026-08-21
|
||||
|
||||
- `RECOVERY_ACTION = assistant-only docker compose up -d --no-build using ignored local secrets/docker-prod-bootstrap.env; no build, prune, volume deletion or neighbor-stack command`
|
||||
- `RECOVERY_RESULT = PASS: assistant-creator-web healthy on host port 18080; assistant-postgres healthy; core-runtime, continuity-runtime, commit-runtime and cognitive-worker running; https://assistant.cin.su/healthz returned HTTP 200`
|
||||
- `ROUTING_FINDING = Caddy already routes assistant.cin.su to host.docker.internal:18080; the 502 was caused by creator-web being Created with no listener, not by a bad Caddy port`
|
||||
- `PRODUCTION_ARTIFACT_AFTER_RECOVERY = revision 2e0c0236aa29d493d1ee9579354c244029cea09a on inspected Assistant containers; CURRENT_HEAD remains local and is not promoted`
|
||||
- `NEIGHBOR_SCOPE = read-only before/after snapshots showed atlas, llm-local, adapter-1c, gitea, portainer and Caddy still running; no neighbor container was targeted`
|
||||
|
||||
## Creator cabinet operations checkpoint — 2026-08-21
|
||||
|
||||
- `TASK = DEV-000074 Creator cabinet operations`
|
||||
- `UI_CHANGE = human-facing navigation for overview, diagnostics, operations and settings; read-only gateway diagnostics; browser-local density, auto-refresh and reduced-motion preferences`
|
||||
- `UI_VALIDATION = PASS: node --check console.js; go test ./cmd/creator-web; go test ./...; go vet ./...; devctl preflight; check-diff; check-architecture; git diff --check; browser console had no errors on static smoke`
|
||||
- `PRODUCTION_PROMOTION = Assistant-only creator-web image built from revision 3ed64631f6a0defbf90c7981179f99d26de34ca9 and started with no dependency recreation`
|
||||
- `PRODUCTION_UI_EVIDENCE = https://assistant.cin.su/ HTTP 200 and deployed HTML contains diagnostics/settings markers; creator-web healthy on 18080; healthz HTTP 200`
|
||||
- `NEIGHBOR_SCOPE = atlas, llm-local, adapter-1c, gitea, portainer and Caddy remained running; no neighbor image or container was targeted`
|
||||
- `VISUAL_HOTFIX = 2026-08-21: constrained workspace to 1740px on wide screens, raised contrast and reduced grain, made diagnostics explain HTTP failure classes; creator-web revision 4226c986d70af017ecfbb8755e0d7a44bc189fa is healthy`
|
||||
- `DIAGNOSTIC_RECOVERY = 2026-08-21: synchronized eight Assistant PostgreSQL role passwords from the ignored production bootstrap secret without changing data; authenticated session, advisory policy, capability health, today, attention, actions and learning endpoints all returned HTTP 200`
|
||||
- `CONTEXT_UX = 2026-08-21: primary session/workspace inputs remain visible; task, prospective item and capability IDs moved into an expandable advanced section; browser-local context reset added; cache-busted assets served by creator-web revision 93b0965485e8ba9ca85613a71d137f3f35203376`
|
||||
|
||||
## Post-audit local repair checkpoint — 2026-08-21
|
||||
|
||||
- `CURRENT_BRANCH = codex/domovoy-understanding-repair-v1`
|
||||
- `CURRENT_HEAD = 3aa0a1d` (10 local repair/config commits ahead of `origin/codex/domovoy-understanding-repair-v1`)
|
||||
- `ACTIVE_TASK = DEV-000073 production Compose fail-closed configuration`
|
||||
- `LOCAL_VALIDATION = PASS: go test ./...; go vet ./...; devctl preflight; check-diff; check-architecture; git diff --check; node --check for creator-web chat.js and console.js; docker compose config with missing-input rejection and synthetic-input render`
|
||||
- `REPAIRS = selected semantic candidate preservation; cognitive gateway candidate validation; cognitive deferral planning precedence; safe creator-web and creator-console error rendering; fail-closed production Compose inputs`
|
||||
- `PRODUCTION_STATUS = recovered for existing production artifact; not verified for CURRENT_HEAD; no current-branch promotion, migration application or live /chat acceptance is claimed here`
|
||||
- `NEXT_REQUIRED_EVIDENCE = promote the exact evaluated artifact, apply migration 027 if absent, then verify production health and authenticated /chat acceptance`
|
||||
- `PROMOTION_ACCESS = Portainer API key remains unavailable; recovery used the authorized Docker production context and ignored local secret file without printing or copying its values`
|
||||
- `CURRENT_PRODUCTION_READONLY_AUDIT = 2026-08-21 after recovery: https://assistant.cin.su/healthz returned HTTP 200; assistant-postgres-1 and assistant-creator-web-1 healthy; all Assistant runtime containers running`
|
||||
- `CURRENT_PRODUCTION_BLOCKERS = current branch 3aa0a1d is not the deployed artifact; authenticated /chat acceptance remains pending`
|
||||
- `PRODUCTION_BLOCKER_SCOPE = exact current-branch promotion and live acceptance remain outstanding; no neighbor stack was mutated`
|
||||
- `CURRENT_PRODUCTION_ARTIFACT = revision 2e0c0236aa29d493d1ee9579354c244029cea09a on all inspected project-built containers; CURRENT_HEAD is not promoted`
|
||||
- `CURRENT_PRODUCTION_SCHEMA = migration 027 is present: interaction.semantic_candidates, interaction.semantic_candidate_capability_hints, and interpretation columns secondary_speech_act/applicability/selection_reason were confirmed read-only`
|
||||
|
||||
## DEV-000072 checkpoint
|
||||
|
||||
- `DEV_000072_STATUS = LOCAL_ACCEPTANCE_PASS`
|
||||
|
||||
+111
-169
@@ -127,6 +127,19 @@ func BuildDeterministicCandidate(message string, corrects interaction.HumanUtter
|
||||
scores := semanticScores(tokens, hasQuestionMark, corrects != "")
|
||||
primary, primaryScore := topAct(scores)
|
||||
secondary, secondaryScore := secondAct(scores, primary)
|
||||
if (startsWithModalRequest(tokens) || startsWithExplanatoryRequest(tokens, "расска", "раска", "объяс", "опиш", "покаж", "подскаж")) &&
|
||||
(primary == interaction.SpeechActAssertion || primary == interaction.SpeechActDirective) &&
|
||||
(secondary == interaction.SpeechActQuestion || secondary == interaction.SpeechActRequestToInvestigate) {
|
||||
primary, secondary = secondary, primary
|
||||
}
|
||||
if primary == interaction.SpeechActQuestion && !hasQuestionMark && !containsMeaningfulInterrogative(tokens) &&
|
||||
!startsWithModalRequest(tokens) && !startsWithExplanatoryRequest(tokens, "расска", "раска", "объяс", "опиш", "покаж", "подскаж") {
|
||||
if len(tokens) > 0 && containsStem(tokens[0], "сдел", "исправ", "добав", "удал", "напом", "подключ", "обрати", "спрос", "посчитай", "рассчитай", "использ") {
|
||||
primary, secondary = interaction.SpeechActDirective, interaction.SpeechActUnknown
|
||||
} else {
|
||||
primary, secondary = interaction.SpeechActAssertion, interaction.SpeechActUnknown
|
||||
}
|
||||
}
|
||||
candidate := interaction.SemanticCandidate{
|
||||
ID: interaction.SemanticCandidateID(id),
|
||||
UtteranceID: "",
|
||||
@@ -146,6 +159,10 @@ func BuildDeterministicCandidate(message string, corrects interaction.HumanUtter
|
||||
if candidate.PrimarySpeechAct == interaction.SpeechActUnknown {
|
||||
candidate.PrimarySpeechAct = interaction.SpeechActAssertion
|
||||
}
|
||||
if startsWithDirectiveWhatNibud(tokens) {
|
||||
candidate.NeedsCognition = false
|
||||
candidate.CapabilityHints = removeCapabilityHint(candidate.CapabilityHints, "COGNITIVE_REASONING")
|
||||
}
|
||||
if candidate.Applicability == interaction.SemanticCandidateClarify {
|
||||
candidate.Clarification = interaction.ClarificationRequired
|
||||
candidate.NeedsCognition = false
|
||||
@@ -175,8 +192,7 @@ func semanticScores(tokens []string, hasQuestionMark bool, explicitCorrection bo
|
||||
interaction.SpeechActConversational: 0,
|
||||
}
|
||||
if hasQuestionMark {
|
||||
scores[interaction.SpeechActQuestion] += 4
|
||||
scores[interaction.SpeechActRequestToInvestigate]++
|
||||
scores[interaction.SpeechActQuestion]++
|
||||
}
|
||||
if explicitCorrection {
|
||||
scores[interaction.SpeechActCorrection] += 6
|
||||
@@ -193,26 +209,24 @@ func semanticScores(tokens []string, hasQuestionMark bool, explicitCorrection bo
|
||||
scores[interaction.SpeechActConfirmation] += 2
|
||||
}
|
||||
questionWords := map[string]struct{}{"кто": {}, "что": {}, "как": {}, "почему": {}, "зачем": {}, "где": {}, "когда": {}, "сколько": {}, "какой": {}, "какая": {}, "какие": {}, "чей": {}}
|
||||
conversationWords := []string{"привет", "здравствуйте", "спасибо", "ку", "здравствуй", "добрый"}
|
||||
investigateStems := []string{"разбер", "проверь", "провери", "проанализ", "исслед", "выясн", "узнай"}
|
||||
directiveStems := []string{"сдел", "запуст", "созд", "настро", "добав", "измени", "помен", "поменя", "измен", "использ", "удал", "напом", "подключ", "исправ", "обрати", "поправ", "обнов", "ответь", "посмотри", "проверь"}
|
||||
conversationWords := []string{"привет", "здравствуйте", "спасибо", "ку", "здравствуй"}
|
||||
investigateStems := []string{"разбер", "проверь", "проанализ", "исслед", "выясн", "подум", "понят", "посмотри"}
|
||||
directiveStems := []string{"сдел", "запуст", "созд", "настро", "добав", "измени", "помен", "использ", "удал", "напом", "подключ", "исправ", "обрати", "спрос", "посчитай", "рассчитай", "ответь"}
|
||||
explanatoryRequestStems := []string{"расска", "раска", "объяс", "опиш", "покаж", "подскаж"}
|
||||
preferenceStems := []string{"предпоч", "хочу", "лучше", "не используй"}
|
||||
hypothesisStems := []string{"думаю", "кажется", "гипотез", "похоже"}
|
||||
decisionStems := []string{"решил", "решение", "выбираю"}
|
||||
arithmeticMarker := false
|
||||
for index, token := range tokens {
|
||||
if firstPersonPastReport(tokens, index) && containsStem(token, directiveStems...) {
|
||||
continue
|
||||
}
|
||||
if _, ok := questionWords[token]; ok && !(token == "что" && index+1 < len(tokens) && tokens[index+1] == "нибудь") {
|
||||
scores[interaction.SpeechActQuestion] += 4
|
||||
scores[interaction.SpeechActQuestion] += 3
|
||||
}
|
||||
if containsStem(token, conversationWords...) {
|
||||
scores[interaction.SpeechActConversational] += 4
|
||||
scores[interaction.SpeechActConversational] += 3
|
||||
}
|
||||
if containsStem(token, investigateStems...) {
|
||||
scores[interaction.SpeechActRequestToInvestigate] += 3
|
||||
scores[interaction.SpeechActQuestion] += 1
|
||||
scores[interaction.SpeechActQuestion]++
|
||||
}
|
||||
if containsStem(token, directiveStems...) {
|
||||
scores[interaction.SpeechActDirective] += 3
|
||||
@@ -230,31 +244,54 @@ func semanticScores(tokens []string, hasQuestionMark bool, explicitCorrection bo
|
||||
arithmeticMarker = true
|
||||
}
|
||||
}
|
||||
if looksLikeInstructionWithoutPunctuationAfterLead(tokens) {
|
||||
scores[interaction.SpeechActQuestion] += 4
|
||||
scores[interaction.SpeechActRequestToInvestigate] += 2
|
||||
if len(tokens) >= 2 && tokens[0] == "я" && containsStemInTokens(tokens[1:], "настро", "сдела", "исправ", "удал", "созда", "перезапуст", "поменя", "добави") {
|
||||
scores[interaction.SpeechActAssertion] += 5
|
||||
}
|
||||
if arithmeticMarker {
|
||||
scores[interaction.SpeechActQuestion] += 2
|
||||
scores[interaction.SpeechActDirective]++
|
||||
}
|
||||
if len(tokens) > 0 && startsWithModalRequest(tokens) {
|
||||
if len(tokens) <= 4 {
|
||||
for index, token := range tokens {
|
||||
if _, ok := questionWords[token]; ok && !(token == "что" && index+1 < len(tokens) && tokens[index+1] == "нибудь") {
|
||||
scores[interaction.SpeechActQuestion]++
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(tokens) == 2 && tokens[0] == "ты" {
|
||||
scores[interaction.SpeechActQuestion] += 2
|
||||
}
|
||||
if len(tokens) >= 2 && tokens[0] == "как" && containsToken(tokens, "зовут") {
|
||||
scores[interaction.SpeechActQuestion] += 2
|
||||
}
|
||||
if startsWithDirectiveWhatNibud(tokens) {
|
||||
scores[interaction.SpeechActDirective] += 4
|
||||
}
|
||||
if len(tokens) > 0 && containsStem(tokens[0], investigateStems...) {
|
||||
scores[interaction.SpeechActRequestToInvestigate] += 2
|
||||
}
|
||||
if looksLikeInformationRequest(tokens) {
|
||||
scores[interaction.SpeechActQuestion] += 4
|
||||
if len(tokens) > 0 && containsStem(tokens[0], "разбер", "проверь", "проанализ", "исслед", "выясн") && containsMeaningfulInterrogative(tokens) {
|
||||
scores[interaction.SpeechActRequestToInvestigate] += 2
|
||||
}
|
||||
if !hasQuestionMark && containsInterrogative(tokens) {
|
||||
scores[interaction.SpeechActQuestion] += 4
|
||||
scores[interaction.SpeechActRequestToInvestigate] += 2
|
||||
if startsWithExplanatoryRequest(tokens, explanatoryRequestStems...) {
|
||||
scores[interaction.SpeechActQuestion] += 2
|
||||
scores[interaction.SpeechActRequestToInvestigate] += 3
|
||||
}
|
||||
if startsWithModalRequest(tokens) && containsStemInTokens(tokens, explanatoryRequestStems...) {
|
||||
scores[interaction.SpeechActQuestion] += 3
|
||||
scores[interaction.SpeechActRequestToInvestigate] += 3
|
||||
}
|
||||
if containsModelReference(tokens) {
|
||||
scores[interaction.SpeechActQuestion] += 2
|
||||
scores[interaction.SpeechActDirective] += 1
|
||||
if containsStemInTokens(tokens, "обрати", "спрос", "уточни") {
|
||||
scores[interaction.SpeechActDirective] += 3
|
||||
scores[interaction.SpeechActQuestion] += 2
|
||||
}
|
||||
}
|
||||
if !hasQuestionMark && scores[interaction.SpeechActQuestion] == 0 && scores[interaction.SpeechActRequestToInvestigate] == 0 &&
|
||||
scores[interaction.SpeechActDirective] <= 1 && scores[interaction.SpeechActCorrection] == 0 {
|
||||
if containsStemInTokens(tokens, "замени", "смени") {
|
||||
scores[interaction.SpeechActDirective] += 3
|
||||
}
|
||||
if !hasQuestionMark && !containsInterrogative(tokens) && !startsWithModalRequest(tokens) && !startsWithExplanatoryRequest(tokens, explanatoryRequestStems...) &&
|
||||
scores[interaction.SpeechActDirective] == 0 && scores[interaction.SpeechActRequestToInvestigate] == 0 && scores[interaction.SpeechActCorrection] == 0 {
|
||||
scores[interaction.SpeechActAssertion] += 2
|
||||
}
|
||||
return scores
|
||||
@@ -311,7 +348,7 @@ func applicabilityFor(primary, secondary interaction.SpeechAct, primaryScore, se
|
||||
if primary == interaction.SpeechActCorrection && secondaryScore >= 3 && (secondary == interaction.SpeechActDirective || secondary == interaction.SpeechActRequestToInvestigate) {
|
||||
return interaction.SemanticMixedIntent
|
||||
}
|
||||
if primary == interaction.SpeechActQuestion && containsMeaningfulInterrogative(tokens) {
|
||||
if primary == interaction.SpeechActAssertion && containsMeaningfulInterrogative(tokens) {
|
||||
return interaction.SemanticNeedsBroaderInterpret
|
||||
}
|
||||
if primary == interaction.SpeechActDirective && likelyConsequential(tokens) {
|
||||
@@ -320,9 +357,6 @@ func applicabilityFor(primary, secondary interaction.SpeechAct, primaryScore, se
|
||||
if primary == interaction.SpeechActDirective && containsStemInTokens(tokens, "обрати", "спрос") && containsModelReference(tokens) {
|
||||
return interaction.SemanticLowConfidence
|
||||
}
|
||||
if primary == interaction.SpeechActDirective && containsStemInTokens(tokens, "убери", "снеси", "удали", "удал", "стер") && len(tokens) > 1 {
|
||||
return interaction.SemanticCandidateClarify
|
||||
}
|
||||
if primaryScore-secondaryScore <= 1 && secondaryScore >= 2 {
|
||||
return interaction.SemanticLowConfidence
|
||||
}
|
||||
@@ -331,35 +365,17 @@ func applicabilityFor(primary, secondary interaction.SpeechAct, primaryScore, se
|
||||
return interaction.SemanticNeedsBroaderInterpret
|
||||
}
|
||||
}
|
||||
if primary == interaction.SpeechActConversational {
|
||||
return interaction.SemanticApplicable
|
||||
}
|
||||
if primary == interaction.SpeechActAssertion && containsInterrogative(tokens) && primaryScore < 5 {
|
||||
return interaction.SemanticNeedsBroaderInterpret
|
||||
}
|
||||
return interaction.SemanticApplicable
|
||||
}
|
||||
|
||||
func needsCognitionForCandidate(primary, secondary interaction.SpeechAct, tokens []string) bool {
|
||||
if primary == interaction.SpeechActConversational && secondary == interaction.SpeechActDirective {
|
||||
return true
|
||||
}
|
||||
if primary == interaction.SpeechActQuestion && containsMeaningfulInterrogative(tokens) {
|
||||
return true
|
||||
}
|
||||
if isAssistantStatusProbe(primary, secondary, tokens) {
|
||||
return true
|
||||
}
|
||||
if primary == interaction.SpeechActAssertion && containsModelReference(tokens) && containsStemInTokens(tokens, "работает", "падает", "растет", "растёет", "свободно", "виснет") {
|
||||
return true
|
||||
}
|
||||
if primary == interaction.SpeechActQuestion || primary == interaction.SpeechActRequestToInvestigate {
|
||||
return true
|
||||
}
|
||||
if secondary == interaction.SpeechActQuestion || secondary == interaction.SpeechActRequestToInvestigate {
|
||||
return true
|
||||
}
|
||||
if primary == interaction.SpeechActDirective && (containsInterrogative(tokens) || containsModelReference(tokens) || containsStemInTokens(tokens, "обрати", "посмотри", "разбер", "исправ", "обнов", "добав")) {
|
||||
if primary == interaction.SpeechActDirective && (containsInterrogative(tokens) || containsModelReference(tokens) || containsStemInTokens(tokens, "спрос", "обрати", "посчитай", "рассчитай")) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
@@ -370,9 +386,6 @@ func deterministicReason(primary, secondary interaction.SpeechAct, tokens []stri
|
||||
if primary == interaction.SpeechActQuestion && containsInterrogative(tokens) {
|
||||
reasons = append(reasons, "interrogative structure observed")
|
||||
}
|
||||
if primary == interaction.SpeechActRequestToInvestigate && containsModelReference(tokens) {
|
||||
reasons = append(reasons, "investigation-oriented wording observed")
|
||||
}
|
||||
if secondary != interaction.SpeechActUnknown {
|
||||
reasons = append(reasons, "secondary competing semantic signal observed")
|
||||
}
|
||||
@@ -389,34 +402,34 @@ func capabilityHintsFor(primary, secondary interaction.SpeechAct, tokens []strin
|
||||
if primary == interaction.SpeechActQuestion || primary == interaction.SpeechActRequestToInvestigate || secondary == interaction.SpeechActQuestion || secondary == interaction.SpeechActRequestToInvestigate {
|
||||
add("COGNITIVE_REASONING")
|
||||
}
|
||||
if isAssistantStatusProbe(primary, secondary, tokens) {
|
||||
add("COGNITIVE_REASONING")
|
||||
}
|
||||
if isExplicitReminder(tokens) {
|
||||
add("SCHEDULE_REMINDER")
|
||||
}
|
||||
if isExplicitEmailAction(tokens) || containsToken(tokens, "письма") || containsToken(tokens, "почту") || containsToken(tokens, "почта") {
|
||||
add("SEND_EMAIL")
|
||||
add("READ_EMAIL")
|
||||
}
|
||||
if primary == interaction.SpeechActDirective && containsStemInTokens(tokens, "добав", "реализ", "поддержк") {
|
||||
add("MODIFY_CODE")
|
||||
}
|
||||
if containsToken(tokens, "напомни") || containsToken(tokens, "напомин") {
|
||||
add("SCHEDULE_REMINDER")
|
||||
}
|
||||
if primary == interaction.SpeechActRequestToInvestigate || (primary == interaction.SpeechActQuestion && containsInterrogative(tokens) && containsStemInTokens(tokens, "почему", "как", "что")) {
|
||||
add("COGNITIVE_REASONING")
|
||||
if isExplicitEmailAction(tokens) {
|
||||
add("SEND_EMAIL")
|
||||
}
|
||||
if containsToken(tokens, "код") || containsToken(tokens, "патч") || containsToken(tokens, "текст") || containsToken(tokens, "главной") || containsToken(tokens, "чате") {
|
||||
if primary == interaction.SpeechActDirective || primary == interaction.SpeechActRequestToInvestigate || secondary == interaction.SpeechActDirective {
|
||||
add("MODIFY_CODE")
|
||||
add("RUN_TESTS")
|
||||
}
|
||||
}
|
||||
if containsToken(tokens, "assistant") && containsStemInTokens(tokens, "исправ", "добав", "измени", "помен", "патч") {
|
||||
add("MODIFY_CODE")
|
||||
add("RUN_TESTS")
|
||||
}
|
||||
if containsStemInTokens(tokens, "исправ", "поправ") && (containsToken(tokens, "чате") || containsToken(tokens, "текст") || containsToken(tokens, "assistant")) {
|
||||
add("MODIFY_CODE")
|
||||
add("RUN_TESTS")
|
||||
}
|
||||
if containsStemInTokens(tokens, "патч", "исправ", "поправ") && containsStemInTokens(tokens, "разбер", "проверь", "почему", "тормозит", "подум") {
|
||||
add("MODIFY_CODE")
|
||||
add("RUN_TESTS")
|
||||
}
|
||||
if containsInterrogative(tokens) && containsArithmetic(tokens) {
|
||||
add("COGNITIVE_REASONING")
|
||||
}
|
||||
if containsStemInTokens(tokens, "тормоз", "медлен", "почему", "что", "сервис", "база", "падает") {
|
||||
add("INSPECT_PROJECT")
|
||||
add("READ_DATABASE")
|
||||
add("QUERY_LOGS")
|
||||
}
|
||||
if containsToken(tokens, "свободно") || containsToken(tokens, "гб") || containsToken(tokens, "модель") || containsToken(tokens, "postgres") || containsToken(tokens, "база") {
|
||||
if containsToken(tokens, "свободно") || containsToken(tokens, "гб") || containsToken(tokens, "модель") {
|
||||
add("VERIFY_FACT")
|
||||
}
|
||||
values := make([]string, 0, len(seen))
|
||||
@@ -446,7 +459,7 @@ func boundedConfidence(primaryScore, secondaryScore int, scores map[interaction.
|
||||
if confidence > 980 {
|
||||
confidence = 980
|
||||
}
|
||||
return confidence
|
||||
return int64(confidence)
|
||||
}
|
||||
|
||||
func containsStem(token string, stems ...string) bool {
|
||||
@@ -488,7 +501,7 @@ func startsWithModalRequest(tokens []string) bool {
|
||||
return false
|
||||
}
|
||||
switch tokens[0] {
|
||||
case "можешь", "можете", "сможешь", "сможете", "давай", "допусти":
|
||||
case "можешь", "можете", "сможешь", "сможете":
|
||||
return true
|
||||
}
|
||||
if len(tokens) >= 3 && tokens[0] == "не" && strings.HasPrefix(tokens[1], "мог") && tokens[2] == "бы" {
|
||||
@@ -497,6 +510,16 @@ func startsWithModalRequest(tokens []string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func startsWithExplanatoryRequest(tokens []string, stems ...string) bool {
|
||||
if len(tokens) == 0 {
|
||||
return false
|
||||
}
|
||||
if containsStem(tokens[0], stems...) {
|
||||
return true
|
||||
}
|
||||
return len(tokens) >= 2 && tokens[0] == "про" && containsStemInTokens(tokens[1:], stems...)
|
||||
}
|
||||
|
||||
func containsInterrogative(tokens []string) bool {
|
||||
for _, token := range tokens {
|
||||
if token == "-" {
|
||||
@@ -539,69 +562,9 @@ func containsArithmetic(tokens []string) bool {
|
||||
return digits >= 2
|
||||
}
|
||||
|
||||
func looksLikeInstructionWithoutPunctuation(first string) bool {
|
||||
if first == "" {
|
||||
return false
|
||||
}
|
||||
switch {
|
||||
case strings.HasSuffix(first, "й"), strings.HasSuffix(first, "и"), strings.HasSuffix(first, "ите"):
|
||||
return utf8.RuneCountInString(first) > 3
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func looksLikeInstructionWithoutPunctuationAfterLead(tokens []string) bool {
|
||||
if len(tokens) < 2 {
|
||||
return false
|
||||
}
|
||||
if utf8.RuneCountInString(tokens[0]) > 3 {
|
||||
return false
|
||||
}
|
||||
switch tokens[0] {
|
||||
case "про", "по", "на", "в", "за":
|
||||
default:
|
||||
return false
|
||||
}
|
||||
for _, token := range tokens[1:] {
|
||||
if utf8.RuneCountInString(token) <= 3 {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case strings.HasSuffix(token, "ешь"), strings.HasSuffix(token, "и"), strings.HasSuffix(token, "й"), strings.HasSuffix(token, "те"), strings.HasSuffix(token, "йте"):
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func looksLikeInformationRequest(tokens []string) bool {
|
||||
if len(tokens) < 2 {
|
||||
return false
|
||||
}
|
||||
if !containsSuffix(tokens[0], "й", "и", "те", "йте") {
|
||||
return false
|
||||
}
|
||||
for _, token := range tokens[1:] {
|
||||
if containsStem(token, "что", "как", "почему", "зачем", "когда", "кто", "какой", "какая", "какие", "об", "про", "подроб") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func containsSuffix(value string, suffixes ...string) bool {
|
||||
for _, suffix := range suffixes {
|
||||
if strings.HasSuffix(value, suffix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func likelyConsequential(tokens []string) bool {
|
||||
for _, token := range tokens {
|
||||
if containsStem(token, "удал", "снес", "замен", "миграц", "парол", "опубли", "перезапуст", "смени", "купи", "установ", "внедр") {
|
||||
if containsStem(token, "удал", "снес", "замен", "миграц", "парол", "опубли", "перезапуст", "смени", "купи") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -618,18 +581,12 @@ func followsNibud(tokens []string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func firstPersonPastReport(tokens []string, index int) bool {
|
||||
if len(tokens) == 0 || index == 0 {
|
||||
func startsWithDirectiveWhatNibud(tokens []string) bool {
|
||||
if len(tokens) < 2 || !containsStem(tokens[0], "сдел", "исправ", "добав", "удал", "напом", "подключ", "обрати", "спрос", "посчитай", "рассчитай", "использ") {
|
||||
return false
|
||||
}
|
||||
if tokens[0] != "я" && tokens[0] != "мы" {
|
||||
return false
|
||||
}
|
||||
if index < 2 {
|
||||
return false
|
||||
}
|
||||
for _, token := range tokens[:index] {
|
||||
if token == "всё" || token == "все" || token == "сейчас" || token == "уже" {
|
||||
for index, token := range tokens {
|
||||
if token == "что" && followsNibud(tokens[index+1:]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -638,25 +595,7 @@ func firstPersonPastReport(tokens []string, index int) bool {
|
||||
|
||||
func containsModelReference(tokens []string) bool {
|
||||
for _, token := range tokens {
|
||||
if token == "модель" || token == "модели" || token == "postgres" || token == "postgresql" || strings.Contains(token, "gemma") || strings.Contains(token, "гемма") || strings.Contains(token, "qwen") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isAssistantStatusProbe(primary, secondary interaction.SpeechAct, tokens []string) bool {
|
||||
if primary != interaction.SpeechActAssertion && primary != interaction.SpeechActCorrection && primary != interaction.SpeechActQuestion && primary != interaction.SpeechActRequestToInvestigate && primary != interaction.SpeechActUnknown {
|
||||
return false
|
||||
}
|
||||
if !(containsToken(tokens, "домовой") || containsToken(tokens, "ассистент") || containsToken(tokens, "бот") || containsToken(tokens, "ты") || containsToken(tokens, "ии") || containsToken(tokens, "ai") || containsToken(tokens, "gpt")) {
|
||||
return false
|
||||
}
|
||||
if containsToken(tokens, "не") && containsStemInTokens(tokens, "вид", "виж", "понима", "ответ", "отвеч", "работа", "реагир", "слыш", "слуш", "ищ", "уведом", "чувств") {
|
||||
return true
|
||||
}
|
||||
for index := 0; index < len(tokens)-1; index++ {
|
||||
if tokens[index] == "не" && (containsStem(tokens[index+1], "вид", "виж", "понима", "ответ", "отвеч", "работа", "реагир", "слыш", "слуш", "ищ", "уведом", "чувств")) {
|
||||
if token == "модель" || token == "модели" || strings.Contains(token, "gemma") || strings.Contains(token, "гемма") || strings.Contains(token, "qwen") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -665,14 +604,17 @@ func isAssistantStatusProbe(primary, secondary interaction.SpeechAct, tokens []s
|
||||
|
||||
func isExplicitEmailAction(tokens []string) bool {
|
||||
hasMailObject := containsToken(tokens, "письмо") || containsToken(tokens, "письма") || containsToken(tokens, "почту") || containsToken(tokens, "почта")
|
||||
hasMailVerb := containsStemInTokens(tokens, "отправ", "ответ", "напиш", "пиши", "напишите")
|
||||
hasMailVerb := containsStemInTokens(tokens, "отправ", "ответ", "напиш")
|
||||
return hasMailObject && hasMailVerb
|
||||
}
|
||||
|
||||
func isExplicitReminder(tokens []string) bool {
|
||||
hasReminder := containsToken(tokens, "напомни") || containsToken(tokens, "напомин")
|
||||
if hasReminder {
|
||||
return true
|
||||
func removeCapabilityHint(values []string, denied string) []string {
|
||||
result := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
if value == denied {
|
||||
continue
|
||||
}
|
||||
result = append(result, value)
|
||||
}
|
||||
return containsStemInTokens(tokens, "напомин", "напомни")
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -56,12 +56,10 @@ func TestDeterministicCandidateIsInvariantToMissingQuestionMarkForIdentityAndAri
|
||||
}{
|
||||
{"ты кто", interaction.SpeechActQuestion},
|
||||
{"Ты кто?", interaction.SpeechActQuestion},
|
||||
{"ТЫ КТО", interaction.SpeechActQuestion},
|
||||
{"а ты кто", interaction.SpeechActQuestion},
|
||||
{"сколько будет 2 + 2", interaction.SpeechActQuestion},
|
||||
{"сколько будет 2 + 2?", interaction.SpeechActQuestion},
|
||||
{"2 плюс 2 сколько", interaction.SpeechActQuestion},
|
||||
{"как тебя зовут", interaction.SpeechActQuestion},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
candidate := BuildDeterministicCandidate(tc.message, "", time.Unix(10, 0).UnixMilli())
|
||||
@@ -84,14 +82,11 @@ func TestDeterministicCandidateTreatsModalExplanationRequestsAsCognitionWorthWit
|
||||
"можете объяснить это проще",
|
||||
"расскажи об утре",
|
||||
"про утро расскажешь",
|
||||
"РАССКАЖИ ПОХОЖЕ ЧТО ПРОИСХОДИТ",
|
||||
"можете обяснить почему база растет",
|
||||
"ты не видишь ии",
|
||||
"домовой не отвечает",
|
||||
"домовой не работает",
|
||||
"домовой не реагирует",
|
||||
} {
|
||||
candidate := BuildDeterministicCandidate(message, "", time.Unix(10, 0).UnixMilli())
|
||||
if candidate.PrimarySpeechAct != interaction.SpeechActQuestion && candidate.PrimarySpeechAct != interaction.SpeechActRequestToInvestigate {
|
||||
t.Fatalf("expected broader cognitive speech act for %q, got %+v", message, candidate)
|
||||
}
|
||||
if !candidate.NeedsCognition {
|
||||
t.Fatalf("expected cognition for %q, got %+v", message, candidate)
|
||||
}
|
||||
@@ -100,8 +95,8 @@ func TestDeterministicCandidateTreatsModalExplanationRequestsAsCognitionWorthWit
|
||||
|
||||
func TestDeterministicCandidateTreatsModelRequestAsDirectiveNeedingCognition(t *testing.T) {
|
||||
candidate := BuildDeterministicCandidate("обратись к модели gemma4 и спроси сколько звезд на небе", "", time.Unix(10, 0).UnixMilli())
|
||||
if candidate.PrimarySpeechAct != interaction.SpeechActDirective && candidate.PrimarySpeechAct != interaction.SpeechActRequestToInvestigate && candidate.PrimarySpeechAct != interaction.SpeechActQuestion {
|
||||
t.Fatalf("expected action-like or inquiry intent, got %+v", candidate)
|
||||
if candidate.PrimarySpeechAct != interaction.SpeechActDirective {
|
||||
t.Fatalf("expected directive, got %+v", candidate)
|
||||
}
|
||||
if !candidate.NeedsCognition {
|
||||
t.Fatalf("expected cognition-worthy model request, got %+v", candidate)
|
||||
|
||||
@@ -29,7 +29,6 @@ func InterpretUtterance(utterance interaction.HumanUtterance, projects []situati
|
||||
millis := now.UnixMilli()
|
||||
deterministicCandidate := BuildDeterministicCandidate(utterance.Content, utterance.CorrectsUtteranceID, millis)
|
||||
deterministicCandidate.UtteranceID = utterance.ID
|
||||
deterministicCandidate.SelectionState = interaction.CandidateSelected
|
||||
selectedCandidate := deterministicCandidate
|
||||
result := SemanticResult{
|
||||
Interpretation: interaction.UtteranceInterpretation{
|
||||
@@ -93,37 +92,23 @@ func InterpretUtterance(utterance interaction.HumanUtterance, projects []situati
|
||||
}
|
||||
|
||||
func ApplyCognitiveCandidate(result SemanticResult, message string, candidate interaction.SemanticCandidate, previousFocus *situation.ActiveProjectFocus) SemanticResult {
|
||||
candidate.SelectionState = interaction.CandidateSelected
|
||||
if candidate.UtteranceID == "" {
|
||||
candidate.UtteranceID = result.Interpretation.UtteranceID
|
||||
}
|
||||
candidate.SelectionState = interaction.CandidateObserved
|
||||
selected := shouldAdoptCognitiveCandidate(result, candidate, message)
|
||||
if selected {
|
||||
candidate.SelectionState = interaction.CandidateSelected
|
||||
}
|
||||
|
||||
matched := false
|
||||
selected := false
|
||||
for index := range result.Candidates {
|
||||
if result.Candidates[index].SelectionState == interaction.CandidateSelected {
|
||||
result.Candidates[index].SelectionState = interaction.CandidateObserved
|
||||
}
|
||||
if result.Candidates[index].ID == candidate.ID {
|
||||
result.Candidates[index] = candidate
|
||||
matched = true
|
||||
selected = true
|
||||
}
|
||||
}
|
||||
if selected {
|
||||
for index := range result.Candidates {
|
||||
if result.Candidates[index].ID != candidate.ID && result.Candidates[index].SelectionState == interaction.CandidateSelected {
|
||||
result.Candidates[index].SelectionState = interaction.CandidateObserved
|
||||
}
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
result.Candidates = append(result.Candidates, candidate)
|
||||
}
|
||||
if !selected {
|
||||
result.Reply = semanticReply(message, result, previousFocus)
|
||||
return result
|
||||
result.Candidates = append(result.Candidates, candidate)
|
||||
}
|
||||
|
||||
result.Interpretation.SpeechAct = candidate.PrimarySpeechAct
|
||||
result.Interpretation.SecondarySpeechAct = candidate.SecondarySpeechAct
|
||||
result.Interpretation.ConfidenceMillis = candidate.ConfidenceMillis
|
||||
@@ -140,7 +125,7 @@ func ApplyCognitiveCandidate(result SemanticResult, message string, candidate in
|
||||
} else {
|
||||
result.Interpretation.AssertionVerification = string(epistemics.VerificationNotApplicable)
|
||||
}
|
||||
if result.Interpretation.Applicability == interaction.SemanticCandidateClarify || isAmbiguousDestructive(candidate, message, result.Projects) {
|
||||
if candidate.Applicability == interaction.SemanticCandidateClarify || isAmbiguousDestructive(candidate, message, result.Projects) {
|
||||
result.Interpretation.Clarification = interaction.ClarificationRequired
|
||||
result.NeedsCognition = false
|
||||
result.Interpretation.NeedsCognition = false
|
||||
@@ -149,74 +134,6 @@ func ApplyCognitiveCandidate(result SemanticResult, message string, candidate in
|
||||
return result
|
||||
}
|
||||
|
||||
func shouldAdoptCognitiveCandidate(result SemanticResult, candidate interaction.SemanticCandidate, message string) bool {
|
||||
if result.Interpretation.Clarification == interaction.ClarificationRequired {
|
||||
return false
|
||||
}
|
||||
if candidate.Source != interaction.CandidateSourceCognitive {
|
||||
return false
|
||||
}
|
||||
if candidate.Applicability == interaction.SemanticCandidateClarify {
|
||||
return false
|
||||
}
|
||||
if candidate.PrimarySpeechAct == interaction.SpeechActUnknown {
|
||||
return false
|
||||
}
|
||||
if isConsequenceRisk(message) && result.Interpretation.SpeechAct == interaction.SpeechActDirective {
|
||||
if candidate.PrimarySpeechAct != interaction.SpeechActDirective {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if candidate.PrimarySpeechAct != result.Interpretation.SpeechAct {
|
||||
if result.Interpretation.SpeechAct == interaction.SpeechActQuestion || result.Interpretation.SpeechAct == interaction.SpeechActRequestToInvestigate || result.Interpretation.SpeechAct == interaction.SpeechActConversational {
|
||||
return true
|
||||
}
|
||||
if result.Interpretation.Applicability == interaction.SemanticNeedsBroaderInterpret || result.Interpretation.Applicability == interaction.SemanticLowConfidence || result.Interpretation.Applicability == interaction.SemanticMixedIntent {
|
||||
return true
|
||||
}
|
||||
return candidate.NeedsCognition
|
||||
}
|
||||
if candidate.NeedsCognition {
|
||||
return true
|
||||
}
|
||||
if result.Interpretation.SpeechAct == interaction.SpeechActQuestion || result.Interpretation.SpeechAct == interaction.SpeechActRequestToInvestigate || result.Interpretation.SpeechAct == interaction.SpeechActConversational {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isConsequenceRisk(message string) bool {
|
||||
lower := strings.ToLower(strings.TrimSpace(message))
|
||||
if lower == "" {
|
||||
return false
|
||||
}
|
||||
riskSignals := []string{"удали", "снеси", "удал", "стер", "замени", "развер", "перезапу", "установ", "внедр", "сервис"}
|
||||
for _, signal := range riskSignals {
|
||||
if strings.Contains(lower, signal) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func ShouldAttemptCognitive(result SemanticResult) bool {
|
||||
if result.Interpretation.Clarification == interaction.ClarificationRequired {
|
||||
return false
|
||||
}
|
||||
if result.NeedsCognition {
|
||||
return true
|
||||
}
|
||||
if result.Interpretation.SpeechAct == interaction.SpeechActQuestion || result.Interpretation.SpeechAct == interaction.SpeechActRequestToInvestigate || result.Interpretation.SpeechAct == interaction.SpeechActConversational {
|
||||
return true
|
||||
}
|
||||
if result.Interpretation.Applicability == interaction.SemanticNeedsBroaderInterpret || result.Interpretation.Applicability == interaction.SemanticLowConfidence || result.Interpretation.Applicability == interaction.SemanticMixedIntent {
|
||||
return true
|
||||
}
|
||||
if result.Interpretation.SpeechAct == interaction.SpeechActDirective {
|
||||
return !isConsequenceRisk(result.Interpretation.RequestedOutcome)
|
||||
}
|
||||
return false
|
||||
}
|
||||
func explicitProjectFocus(message string, projects []situation.ProjectDescriptor) *interaction.ProjectReference {
|
||||
lower := strings.ToLower(message)
|
||||
if !(strings.Contains(lower, "работаем с") || strings.Contains(lower, "вернемся к") || strings.Contains(lower, "вернёмся к") || strings.HasPrefix(strings.TrimSpace(lower), "теперь ")) {
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
"git.cin.su/m/Assistant/contracts/interaction"
|
||||
"git.cin.su/m/Assistant/contracts/situation"
|
||||
"git.cin.su/m/Assistant/platform/ids"
|
||||
)
|
||||
|
||||
func TestInterpretUtteranceRecordsExplicitProjectFocus(t *testing.T) {
|
||||
@@ -36,8 +35,8 @@ func TestInterpretUtteranceAssertionIsNotVerifiedFact(t *testing.T) {
|
||||
|
||||
func TestInterpretUtteranceDirectiveRecordsOutcomeWithoutExecution(t *testing.T) {
|
||||
result := interpretForTest(t, "Поменяй базу на УПО1.", activeFocus("upo", "УПО"), "")
|
||||
if result.Interpretation.SpeechAct != interaction.SpeechActDirective && result.Interpretation.SpeechAct != interaction.SpeechActRequestToInvestigate {
|
||||
t.Fatalf("expected directive-style intent, got %s", result.Interpretation.SpeechAct)
|
||||
if result.Interpretation.SpeechAct != interaction.SpeechActDirective {
|
||||
t.Fatalf("expected directive, got %s", result.Interpretation.SpeechAct)
|
||||
}
|
||||
if result.Interpretation.RequestedOutcome == "" || !strings.Contains(result.Reply, "Ничего не выполнено") {
|
||||
t.Fatalf("expected non-executed requested outcome, got %#v reply=%q", result.Interpretation, result.Reply)
|
||||
@@ -117,206 +116,30 @@ func TestInterpretUtteranceAmbiguousDestructiveRequiresClarification(t *testing.
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterpretUtteranceNaturalRussianHelpflowUsesContextAwareCognitionInput(t *testing.T) {
|
||||
cases := []struct {
|
||||
message string
|
||||
wantSpeech interaction.SpeechAct
|
||||
wantCognition bool
|
||||
allowNoMatch bool
|
||||
}{
|
||||
{message: "расскажи как это работает", wantSpeech: interaction.SpeechActQuestion, wantCognition: true},
|
||||
{message: "Расскажи, как это работает?", wantSpeech: interaction.SpeechActQuestion, wantCognition: true},
|
||||
{message: "Расскажи как это работает", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "можешь объяснить почему база растёт", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "ПОЧЕМУ postgres использует так много памяти", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "ПОЧЕМУ postgres использует столько памяти", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "разберись почему сервис упал", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "разберись почему сервис упал", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "посмотри что произошло", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "исправь ошибку если найдёшь", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "разберись почему падает и исправь если причина очевидна", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "нет не UPO а UPO2", wantSpeech: interaction.SpeechActCorrection, wantCognition: false},
|
||||
{message: "нет не UPO а UPO2 и обнови конфиг", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "postgres сейчас работает", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "сейчас домовой не видит ии", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "домовой не видит ии", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "основная база называется UPO", wantSpeech: interaction.SpeechActAssertion, wantCognition: false},
|
||||
{message: "привет", wantSpeech: interaction.SpeechActConversational, wantCognition: false},
|
||||
{message: "спасибо", wantSpeech: interaction.SpeechActConversational, wantCognition: false},
|
||||
{message: "ты кто", wantSpeech: interaction.SpeechActQuestion, wantCognition: true},
|
||||
{message: "Ты кто?", wantSpeech: interaction.SpeechActQuestion, wantCognition: true},
|
||||
{message: "как тебя зовут", wantSpeech: interaction.SpeechActQuestion, wantCognition: true},
|
||||
{message: "кто ты вообще", wantSpeech: interaction.SpeechActQuestion, wantCognition: true},
|
||||
{message: "что ты думаешь", wantSpeech: interaction.SpeechActQuestion, wantCognition: true},
|
||||
{message: "расскажи подробнее", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "СЕЙЧАС ДОМОВОЙ НЕ ВИДИТ ИИ", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "не понимаю меня не понимает ии", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "домовой не вижит ии", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "домовой не отвечает мне", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "домовой не слушает меня", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "домовой не отвечает на команды", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
{message: "ПОЧЕМУ postgres использует так много памяти", wantSpeech: "", wantCognition: true, allowNoMatch: true},
|
||||
func TestInterpretUtterancePunctuationFreeRussianQuestionStillRequestsBroaderInterpretation(t *testing.T) {
|
||||
result := interpretForTest(t, "ты кто", nil, "")
|
||||
if result.Interpretation.SpeechAct != interaction.SpeechActQuestion {
|
||||
t.Fatalf("expected question, got %#v", result.Interpretation)
|
||||
}
|
||||
for _, tc := range cases {
|
||||
result := interpretForTest(t, tc.message, nil, "")
|
||||
if tc.wantSpeech != "" && result.Interpretation.SpeechAct != tc.wantSpeech {
|
||||
t.Fatalf("message %q expected speech=%s got %s", tc.message, tc.wantSpeech, result.Interpretation.SpeechAct)
|
||||
}
|
||||
if tc.wantSpeech == "" && !tc.allowNoMatch && result.Interpretation.SpeechAct == "" {
|
||||
t.Fatalf("message %q got empty speech interpretation", tc.message)
|
||||
}
|
||||
if result.NeedsCognition != tc.wantCognition {
|
||||
t.Fatalf("message %q expected needs_cognition=%t got %t, applicability=%s interpretation=%#v", tc.message, tc.wantCognition, result.NeedsCognition, result.Interpretation.Applicability, result.Interpretation)
|
||||
}
|
||||
if tc.message != "" && result.Interpretation.Clarification == interaction.ClarificationRequired && tc.wantCognition {
|
||||
t.Fatalf("message %q unexpectedly required clarification while asking for safe conversational understanding", tc.message)
|
||||
}
|
||||
if !result.NeedsCognition {
|
||||
t.Fatalf("expected cognition route for punctuation-free identity question, got %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterpretUtteranceDiagnosticTraceLineage(t *testing.T) {
|
||||
message := "ты кто"
|
||||
conversation := interaction.Conversation{ID: "conversation-1", ActorID: "actor-1", PrincipalID: "principal-1", Channel: interaction.ChannelWebChat, State: interaction.ConversationOpen}
|
||||
utterance, _, _, err := NewHumanUtterance(conversation, interaction.ChatMessageRequest{Message: message}, time.Unix(100, 0))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
func TestInterpretUtterancePunctuationFreeArithmeticStillRequestsCognition(t *testing.T) {
|
||||
result := interpretForTest(t, "сколько будет 2 + 2", nil, "")
|
||||
if result.Interpretation.SpeechAct != interaction.SpeechActQuestion {
|
||||
t.Fatalf("expected question, got %#v", result.Interpretation)
|
||||
}
|
||||
result, err := InterpretUtterance(utterance, projectRegistryForTest(), nil, time.Unix(100, 0))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
candidateID, err := ids.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cognitiveCandidate := interaction.SemanticCandidate{
|
||||
ID: interaction.SemanticCandidateID(candidateID),
|
||||
UtteranceID: utterance.ID,
|
||||
Source: interaction.CandidateSourceCognitive,
|
||||
SelectionState: interaction.CandidateObserved,
|
||||
PrimarySpeechAct: interaction.SpeechActQuestion,
|
||||
SecondarySpeechAct: interaction.SpeechActUnknown,
|
||||
ConfidenceMillis: 780,
|
||||
Applicability: interaction.SemanticNeedsBroaderInterpret,
|
||||
RequestedOutcome: "",
|
||||
Clarification: interaction.ClarificationNotRequired,
|
||||
NeedsCognition: true,
|
||||
SelectionReason: "trace-oriented cognitive clarification of identity-style intent",
|
||||
CapabilityHints: []string{"COGNITIVE_REASONING"},
|
||||
RecordedAtUnixMillis: time.Unix(100, 0).UnixMilli(),
|
||||
}
|
||||
selected := ApplyCognitiveCandidate(result, message, cognitiveCandidate, nil)
|
||||
var deterministic, selectedCandidate *interaction.SemanticCandidate
|
||||
for index := range selected.Candidates {
|
||||
c := &selected.Candidates[index]
|
||||
if c.Source == interaction.CandidateSourceDeterministic {
|
||||
deterministic = c
|
||||
}
|
||||
if c.SelectionState == interaction.CandidateSelected {
|
||||
selectedCandidate = c
|
||||
}
|
||||
}
|
||||
if deterministic == nil {
|
||||
t.Fatal("expected deterministic candidate in trace")
|
||||
}
|
||||
if selectedCandidate == nil {
|
||||
t.Fatal("expected selected candidate in trace")
|
||||
}
|
||||
if selected.Interpretation.Source != string(interaction.CandidateSourceCognitive) {
|
||||
t.Fatalf("selection source should switch to cognitive, got %s", selected.Interpretation.Source)
|
||||
}
|
||||
if selected.Interpretation.NeedsCognition != selectedCandidate.NeedsCognition {
|
||||
t.Fatalf("expected selected interpretation cognition=%t got %t", selectedCandidate.NeedsCognition, selected.Interpretation.NeedsCognition)
|
||||
}
|
||||
if selected.Interpretation.Clarification != selectedCandidate.Clarification {
|
||||
t.Fatalf("expected selected candidate clarification to match interpretation clarification")
|
||||
}
|
||||
if selectedCandidate.SelectionReason == "" {
|
||||
t.Fatal("expected clarification/selection reason in selected trace")
|
||||
}
|
||||
t.Logf("TRACE deterministic_source=%s cognitive_source=%s selected_source=%s needs_cognition=%t clarification_reason=%s",
|
||||
deterministic.Source, selectedCandidate.Source, selected.Interpretation.Source, selected.Interpretation.NeedsCognition, selected.Interpretation.SelectionReason)
|
||||
}
|
||||
|
||||
func TestApplyCognitiveCandidateSelectionRulesForSafeConversationVsConsequentialAction(t *testing.T) {
|
||||
conversation := interaction.Conversation{ID: "conversation-1", ActorID: "actor-1", PrincipalID: "principal-1", Channel: interaction.ChannelWebChat, State: interaction.ConversationOpen}
|
||||
safeUtterance, _, _, err := NewHumanUtterance(conversation, interaction.ChatMessageRequest{Message: "ты кто"}, time.Unix(100, 0))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
safeSemantic, err := InterpretUtterance(safeUtterance, projectRegistryForTest(), nil, time.Unix(100, 0))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
safeCandidateID, err := ids.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
safeCognitive := interaction.SemanticCandidate{
|
||||
ID: interaction.SemanticCandidateID(safeCandidateID),
|
||||
UtteranceID: safeUtterance.ID,
|
||||
Source: interaction.CandidateSourceCognitive,
|
||||
SelectionState: interaction.CandidateObserved,
|
||||
PrimarySpeechAct: interaction.SpeechActAssertion,
|
||||
SecondarySpeechAct: interaction.SpeechActUnknown,
|
||||
ConfidenceMillis: 770,
|
||||
Applicability: interaction.SemanticNeedsBroaderInterpret,
|
||||
RequestedOutcome: "",
|
||||
Clarification: interaction.ClarificationNotRequired,
|
||||
NeedsCognition: true,
|
||||
SelectionReason: "identity-style trace test",
|
||||
CapabilityHints: []string{"COGNITIVE_REASONING"},
|
||||
RecordedAtUnixMillis: time.Unix(100, 0).UnixMilli(),
|
||||
}
|
||||
safeSelected := ApplyCognitiveCandidate(safeSemantic, safeUtterance.Content, safeCognitive, nil)
|
||||
if safeSelected.Interpretation.Source != string(interaction.CandidateSourceCognitive) {
|
||||
t.Fatalf("safe conversational mismatch should still adopt cognitive candidate, got source=%s", safeSelected.Interpretation.Source)
|
||||
}
|
||||
if safeSelected.Interpretation.SpeechAct != interaction.SpeechActAssertion {
|
||||
t.Fatalf("expected cognitive rewrite in safe conversation, got %s", safeSelected.Interpretation.SpeechAct)
|
||||
}
|
||||
|
||||
riskyUtterance, _, _, err := NewHumanUtterance(conversation, interaction.ChatMessageRequest{Message: "удали УПО"}, time.Unix(100, 0))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
riskySemantic, err := InterpretUtterance(riskyUtterance, projectRegistryForTest(), nil, time.Unix(100, 0))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if riskySemantic.Interpretation.SpeechAct != interaction.SpeechActDirective {
|
||||
t.Fatalf("expected directive baseline, got %s", riskySemantic.Interpretation.SpeechAct)
|
||||
}
|
||||
riskyCandidateID, err := ids.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
riskyCognitive := interaction.SemanticCandidate{
|
||||
ID: interaction.SemanticCandidateID(riskyCandidateID),
|
||||
UtteranceID: riskyUtterance.ID,
|
||||
Source: interaction.CandidateSourceCognitive,
|
||||
SelectionState: interaction.CandidateObserved,
|
||||
PrimarySpeechAct: interaction.SpeechActQuestion,
|
||||
SecondarySpeechAct: interaction.SpeechActUnknown,
|
||||
ConfidenceMillis: 780,
|
||||
Applicability: interaction.SemanticNeedsBroaderInterpret,
|
||||
RequestedOutcome: "",
|
||||
Clarification: interaction.ClarificationNotRequired,
|
||||
NeedsCognition: true,
|
||||
SelectionReason: "destructive path mismatch guard",
|
||||
CapabilityHints: []string{"COGNITIVE_REASONING"},
|
||||
RecordedAtUnixMillis: time.Unix(100, 0).UnixMilli(),
|
||||
}
|
||||
riskySelected := ApplyCognitiveCandidate(riskySemantic, riskyUtterance.Content, riskyCognitive, nil)
|
||||
if riskySelected.Interpretation.Source != string(interaction.CandidateSourceDeterministic) {
|
||||
t.Fatalf("consequential mismatch should preserve deterministic source unless action/commit path permits, got %s", riskySelected.Interpretation.Source)
|
||||
if !result.NeedsCognition {
|
||||
t.Fatalf("expected cognition route for punctuation-free arithmetic, got %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterpretUtteranceModalExplanationRequestStillRequestsCognition(t *testing.T) {
|
||||
func TestInterpretUtteranceModalExplanationRequestDefersToCognition(t *testing.T) {
|
||||
for _, message := range []string{"можешь расказать об утре", "расскажи об утре", "про утро расскажешь"} {
|
||||
result := interpretForTest(t, message, nil, "")
|
||||
if result.Interpretation.SpeechAct == interaction.SpeechActAssertion && result.Interpretation.Applicability == interaction.SemanticApplicable {
|
||||
if result.Interpretation.SpeechAct != interaction.SpeechActQuestion && result.Interpretation.SpeechAct != interaction.SpeechActRequestToInvestigate {
|
||||
t.Fatalf("expected cognition-worthy interpretation for %q, got %#v", message, result.Interpretation)
|
||||
}
|
||||
if !result.NeedsCognition {
|
||||
@@ -325,46 +148,13 @@ func TestInterpretUtteranceModalExplanationRequestStillRequestsCognition(t *test
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterpretUtteranceSelectsDeterministicCandidateByDefault(t *testing.T) {
|
||||
result := interpretForTest(t, "основная база называется UPO", nil, "")
|
||||
if len(result.Candidates) != 1 {
|
||||
t.Fatalf("expected one deterministic candidate, got %d", len(result.Candidates))
|
||||
func TestInterpretUtteranceNamedModelRequestIsDirectiveNeedingCognition(t *testing.T) {
|
||||
result := interpretForTest(t, "обратись к модели gemma4 и спроси сколько звезд на небе", nil, "")
|
||||
if result.Interpretation.SpeechAct != interaction.SpeechActDirective {
|
||||
t.Fatalf("expected directive, got %#v", result.Interpretation)
|
||||
}
|
||||
if result.Candidates[0].SelectionState != interaction.CandidateSelected {
|
||||
t.Fatalf("deterministic candidate must be selected by default, got %s", result.Candidates[0].SelectionState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRejectedCognitiveCandidatePreservesSelectedDeterministicCandidate(t *testing.T) {
|
||||
result := interpretForTest(t, "основная база называется UPO", nil, "")
|
||||
candidateID, err := ids.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rejected := interaction.SemanticCandidate{
|
||||
ID: interaction.SemanticCandidateID(candidateID),
|
||||
UtteranceID: result.Interpretation.UtteranceID,
|
||||
Source: interaction.CandidateSourceCognitive,
|
||||
PrimarySpeechAct: interaction.SpeechActQuestion,
|
||||
SecondarySpeechAct: interaction.SpeechActUnknown,
|
||||
ConfidenceMillis: 700,
|
||||
Applicability: interaction.SemanticApplicable,
|
||||
Clarification: interaction.ClarificationNotRequired,
|
||||
NeedsCognition: false,
|
||||
SelectionReason: "must not replace a safe assertion with an unrelated candidate",
|
||||
}
|
||||
result = ApplyCognitiveCandidate(result, "основная база называется UPO", rejected, nil)
|
||||
selected := 0
|
||||
for _, candidate := range result.Candidates {
|
||||
if candidate.SelectionState == interaction.CandidateSelected {
|
||||
selected++
|
||||
if candidate.Source != interaction.CandidateSourceDeterministic {
|
||||
t.Fatalf("rejected cognitive candidate replaced deterministic selection: %#v", candidate)
|
||||
}
|
||||
}
|
||||
}
|
||||
if selected != 1 {
|
||||
t.Fatalf("expected exactly one selected candidate after rejection, got %d", selected)
|
||||
if !result.NeedsCognition {
|
||||
t.Fatalf("expected cognition route for named-model request, got %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -73,44 +73,27 @@ func BuildPlanningResult(input work.PlanningInput, now time.Time) (work.Planning
|
||||
|
||||
func DetermineHelpPath(input work.PlanningInput) work.HelpPath {
|
||||
lower := strings.ToLower(input.Message)
|
||||
hasRecallHint := hasPlanningHint(input, capability.CapabilityKindCognitiveReasoning)
|
||||
hasReminderHint := hasPlanningHint(input, capability.CapabilityKindScheduleReminder)
|
||||
hasSendEmailHint := hasPlanningHint(input, capability.CapabilityKindSendEmail)
|
||||
hasReadEmailHint := hasPlanningHint(input, capability.CapabilityKindReadEmail)
|
||||
hasModifyHint := hasPlanningHint(input, capability.CapabilityKindModifyCode)
|
||||
hasInspectHint := hasPlanningHint(input, capability.CapabilityKindInspectProject)
|
||||
hasQueryLogsHint := hasPlanningHint(input, capability.CapabilityKindQueryLogs)
|
||||
hasVerifyHint := hasPlanningHint(input, capability.CapabilityKindVerifyFact)
|
||||
rawTextFallbackAllowed := len(input.CapabilityHints) == 0 && !input.RequiresClarification && !input.NeedsCognition
|
||||
unsupportedCapabilityFallbackAllowed := len(input.CapabilityHints) == 0 && !input.RequiresClarification && !input.NeedsCognition
|
||||
if input.SpeechAct != work.SpeechActRef("") && input.SpeechAct != work.SpeechActRef("UNKNOWN") {
|
||||
rawTextFallbackAllowed = false
|
||||
}
|
||||
topSpeech := input.SpeechAct
|
||||
|
||||
switch {
|
||||
case input.RequiresClarification:
|
||||
return work.HelpPath{Kind: work.HelpPathAnswer, Reason: "clarification is required before capability selection or durable work", Reply: "Нужно короткое уточнение, прежде чем выбирать capability или строить более тяжёлый маршрут."}
|
||||
case topSpeech == work.SpeechActRef("REQUEST_TO_INVESTIGATE"):
|
||||
return work.HelpPath{Kind: work.HelpPathDurableWork, NeedsDurableGoal: true, NeedsDurableWork: true, NeedsDurablePlan: true, Reason: "explicit request-to-investigate should materialize durable work"}
|
||||
case hasReminderHint || (rawTextFallbackAllowed && isReminderRequest(lower)):
|
||||
case isReminderRequest(lower):
|
||||
return work.HelpPath{Kind: work.HelpPathDirectCapability, SuggestedCapabilityKinds: []capability.CapabilityKind{capability.CapabilityKindScheduleReminder}, Reason: "reminder is a direct scheduling-capability path, not a coding/project workflow", Reply: "Понял: нужен reminder/scheduler capability. В DEV-000063 я фиксирую это как безопасный путь помощи; само напоминание ещё не зарегистрировано, потому что scheduling adapter не подключён."}
|
||||
case isEmailReviewRequest(lower) && hasReadEmailHint:
|
||||
case isEmailReviewRequest(lower):
|
||||
return work.HelpPath{Kind: work.HelpPathDurableWork, NeedsDurableGoal: true, NeedsDurableWork: true, NeedsDurablePlan: true, Reason: "mail triage/review needs structured reading and reasoning without claiming outbound send"}
|
||||
case hasSendEmailHint || (rawTextFallbackAllowed && isExplicitEmailGapRequest(lower)):
|
||||
case isExplicitEmailGapRequest(lower):
|
||||
return work.HelpPath{Kind: work.HelpPathCapabilityGap, SuggestedCapabilityKinds: []capability.CapabilityKind{capability.CapabilityKindSendEmail}, CapabilityGap: true, Reason: "email sending needs a communication capability implementation and explicit authority", Reply: "Сейчас у меня ещё не подключена возможность отправлять почту. Я зафиксирую этот capability gap, чтобы позже к нему можно было вернуться."}
|
||||
case hasModifyHint || hasInspectHint || hasQueryLogsHint || hasReadEmailHint || hasRecallHint || hasVerifyHint || needsDurableWorkFromHints(input):
|
||||
return work.HelpPath{Kind: work.HelpPathDurableWork, NeedsDurableGoal: true, NeedsDurableWork: true, NeedsDurablePlan: true, Reason: "semantic hints indicate project/code work even if cognition may still be useful upstream"}
|
||||
case unsupportedCapabilityFallbackAllowed && isUnsupportedCapabilityRequest(lower):
|
||||
case isUnsupportedCapabilityRequest(lower):
|
||||
return work.HelpPath{Kind: work.HelpPathCapabilityGap, SuggestedCapabilityKinds: []capability.CapabilityKind{}, CapabilityGap: true, Reason: "requested help needs a currently missing capability and may later trigger acquisition/self-extension", Reply: "Похоже, для этой просьбы нужна capability, которой сейчас нет. Это не задача конкретного executor автоматически: в будущем Домовой сможет найти, подключить или создать подходящую capability и вернуться к исходной потребности."}
|
||||
case rawTextFallbackAllowed && requiresDurableWork(lower):
|
||||
return work.HelpPath{Kind: work.HelpPathDurableWork, NeedsDurableGoal: true, NeedsDurableWork: true, NeedsDurablePlan: true, Reason: "request needs durable coordination, planning, investigation, or outcome tracking"}
|
||||
case rawTextFallbackAllowed && containsAny(lower, "объясни", "расскажи", "что делает"):
|
||||
case needsDurableWorkFromHints(input):
|
||||
return work.HelpPath{Kind: work.HelpPathDurableWork, NeedsDurableGoal: true, NeedsDurableWork: true, NeedsDurablePlan: true, Reason: "semantic hints indicate project/code work even if cognition may still be useful upstream"}
|
||||
case requiresDurableWork(lower):
|
||||
return work.HelpPath{Kind: work.HelpPathDurableWork, NeedsDurableGoal: true, NeedsDurableWork: true, NeedsDurablePlan: true, Reason: "request needs durable coordination, planning, investigation, delegation, or outcome tracking"}
|
||||
case containsAny(lower, "объясни", "расскажи", "что делает"):
|
||||
return work.HelpPath{Kind: work.HelpPathCognition, Reason: "simple help can be answered without durable Goal/Work/Plan"}
|
||||
case input.NeedsCognition && (topSpeech == work.SpeechActRef("QUESTION") || topSpeech == work.SpeechActRef("REQUEST_TO_INVESTIGATE") || hasRecallHint):
|
||||
case input.NeedsCognition && needsCognitiveAnswer(input):
|
||||
return work.HelpPath{Kind: work.HelpPathCognition, Reason: "semantic layer marked this utterance as cognition-relevant and no durable work path outranks it"}
|
||||
case topSpeech == work.SpeechActRef("QUESTION") || topSpeech == work.SpeechActRef("REQUEST_TO_INVESTIGATE"):
|
||||
return work.HelpPath{Kind: work.HelpPathAnswer, Reason: "question-like request has no structured durable-work intent"}
|
||||
case input.NeedsCognition && (input.SpeechAct == work.SpeechActRef("QUESTION") || input.SpeechAct == work.SpeechActRef("REQUEST_TO_INVESTIGATE")):
|
||||
return work.HelpPath{Kind: work.HelpPathCognition, Reason: "semantic layer marked this utterance as cognition-relevant"}
|
||||
default:
|
||||
return work.HelpPath{Kind: work.HelpPathAnswer, Reason: "ordinary interaction does not require durable Work"}
|
||||
}
|
||||
@@ -126,15 +109,6 @@ func needsDurableWorkFromHints(input work.PlanningInput) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func hasPlanningHint(input work.PlanningInput, expected capability.CapabilityKind) bool {
|
||||
for _, hint := range input.CapabilityHints {
|
||||
if hint == expected {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func needsCognitiveAnswer(input work.PlanningInput) bool {
|
||||
for _, hint := range input.CapabilityHints {
|
||||
if hint == capability.CapabilityKindCognitiveReasoning {
|
||||
@@ -178,32 +152,14 @@ func ValidatePlanCandidate(candidate work.PlanCandidate) error {
|
||||
|
||||
func addScenarioPlan(input work.PlanningInput, millis int64, candidate *work.PlanCandidate) {
|
||||
lower := strings.ToLower(input.Message)
|
||||
hasReminderHint := hasPlanningHint(input, capability.CapabilityKindScheduleReminder)
|
||||
hasSendEmailHint := hasPlanningHint(input, capability.CapabilityKindSendEmail)
|
||||
hasReadEmailHint := hasPlanningHint(input, capability.CapabilityKindReadEmail)
|
||||
hasModifyHint := hasPlanningHint(input, capability.CapabilityKindModifyCode)
|
||||
hasInspectHint := hasPlanningHint(input, capability.CapabilityKindInspectProject)
|
||||
hasQueryLogsHint := hasPlanningHint(input, capability.CapabilityKindQueryLogs)
|
||||
hasVerifyHint := hasPlanningHint(input, capability.CapabilityKindVerifyFact)
|
||||
requiresInvestigation := input.SpeechAct == work.SpeechActRef("REQUEST_TO_INVESTIGATE")
|
||||
if input.SecondarySpeechAct == work.SpeechActRef("CORRECTION") {
|
||||
addStep(candidate, work.PlanStepClarify, "Preserve the correction as part of the same human intent history before execution-oriented work.", len(candidate.Steps)+1, millis)
|
||||
}
|
||||
switch {
|
||||
case hasReminderHint:
|
||||
addRequirement(candidate, capability.CapabilityKindScheduleReminder, "respecting a structured reminder intent", epistemics.VerificationNotApplicable, millis)
|
||||
addStep(candidate, work.PlanStepSchedule, "Interpret requested reminder horizon and context.", 1, millis)
|
||||
case isReminderRequest(lower):
|
||||
addRequirement(candidate, capability.CapabilityKindScheduleReminder, "schedule a future reminder after temporal interpretation", epistemics.VerificationNotApplicable, millis)
|
||||
addStep(candidate, work.PlanStepSchedule, "Interpret the requested reminder time and reminder subject.", 1, millis)
|
||||
addStep(candidate, work.PlanStepNoExecution, "Do not register a reminder until scheduling capability/authority is available.", 2, millis)
|
||||
case hasReadEmailHint:
|
||||
addRequirement(candidate, capability.CapabilityKindReadEmail, "read incoming communications", epistemics.VerificationUnknown, millis)
|
||||
addRequirement(candidate, capability.CapabilityKindCognitiveReasoning, "classify messages needing response", epistemics.VerificationUnknown, millis)
|
||||
addStep(candidate, work.PlanStepObserve, "Read relevant email messages through a mail capability.", 1, millis)
|
||||
addStep(candidate, work.PlanStepReason, "Classify which messages need a response and why.", 2, millis)
|
||||
addStep(candidate, work.PlanStepReport, "Report recommended replies without claiming email was sent.", 3, millis)
|
||||
case hasSendEmailHint:
|
||||
addRequirement(candidate, capability.CapabilityKindSendEmail, "send email only after authority", epistemics.VerificationNotApplicable, millis)
|
||||
addStep(candidate, work.PlanStepPrepare, "Resolve recipient and appropriate communication channel.", 1, millis)
|
||||
addStep(candidate, work.PlanStepCommunicate, "Prepare the message for a communication adapter; do not send without authority.", 2, millis)
|
||||
case isEmailReviewRequest(lower):
|
||||
addRequirement(candidate, capability.CapabilityKindReadEmail, "read incoming communications", epistemics.VerificationUnknown, millis)
|
||||
addRequirement(candidate, capability.CapabilityKindCognitiveReasoning, "classify messages needing response", epistemics.VerificationUnknown, millis)
|
||||
@@ -214,29 +170,25 @@ func addScenarioPlan(input work.PlanningInput, millis int64, candidate *work.Pla
|
||||
addRequirement(candidate, capability.CapabilityKindSendEmail, "send email only after authority", epistemics.VerificationNotApplicable, millis)
|
||||
addStep(candidate, work.PlanStepPrepare, "Resolve recipient and appropriate communication channel.", 1, millis)
|
||||
addStep(candidate, work.PlanStepCommunicate, "Prepare the message for a communication adapter; do not send without authority.", 2, millis)
|
||||
case isReminderRequest(lower):
|
||||
addRequirement(candidate, capability.CapabilityKindScheduleReminder, "schedule a future reminder after temporal interpretation", epistemics.VerificationNotApplicable, millis)
|
||||
addStep(candidate, work.PlanStepSchedule, "Interpret the requested reminder time and reminder subject.", 1, millis)
|
||||
addStep(candidate, work.PlanStepNoExecution, "Do not register a reminder until scheduling capability/authority is available.", 2, millis)
|
||||
case requiresInvestigation || hasInspectHint || hasQueryLogsHint || hasVerifyHint:
|
||||
case containsAny(lower, "тормозит", "медлен", "производительн", "разберись", "почему"):
|
||||
addRequirement(candidate, capability.CapabilityKindInspectProject, "inspect project context", epistemics.VerificationNotApplicable, millis)
|
||||
addRequirement(candidate, capability.CapabilityKindReadDatabase, "collect database performance observations", epistemics.VerificationUnknown, millis)
|
||||
addRequirement(candidate, capability.CapabilityKindQueryLogs, "collect runtime/log observations", epistemics.VerificationUnknown, millis)
|
||||
addRequirement(candidate, capability.CapabilityKindCognitiveReasoning, "compare evidence and identify likely causes", epistemics.VerificationUnknown, millis)
|
||||
if containsAny(lower, "патч", "исправ") || containsAny(lower, "обнов", "конфиг") {
|
||||
if containsAny(lower, "патч", "исправ") {
|
||||
addRequirement(candidate, capability.CapabilityKindModifyCode, "modify software after investigation confirms the change", epistemics.VerificationUnknown, millis)
|
||||
addRequirement(candidate, capability.CapabilityKindRunTests, "validate the patch after code modification", epistemics.VerificationNotApplicable, millis)
|
||||
}
|
||||
addStep(candidate, work.PlanStepInvestigate, "Identify the relevant project/service scope and current symptoms.", 1, millis)
|
||||
addStep(candidate, work.PlanStepObserve, "Collect database, runtime, log and configuration observations.", 2, millis)
|
||||
addStep(candidate, work.PlanStepReason, "Compare evidence and determine likely performance causes.", 3, millis)
|
||||
if containsAny(lower, "патч", "исправ") || containsAny(lower, "обнов", "конфиг") {
|
||||
if containsAny(lower, "патч", "исправ") {
|
||||
addStep(candidate, work.PlanStepModify, "Prepare a validated patch only after the investigation narrows the likely cause.", 4, millis)
|
||||
addStep(candidate, work.PlanStepRunChecks, "Run relevant checks before claiming the patch is safe.", 5, millis)
|
||||
} else {
|
||||
addStep(candidate, work.PlanStepReport, "Report findings and what remains unverified.", 4, millis)
|
||||
}
|
||||
case hasModifyHint:
|
||||
case containsAny(lower, "добавь", "поддержк", "возможность", "реализ"):
|
||||
addRequirement(candidate, capability.CapabilityKindModifyCode, "modify software project", epistemics.VerificationNotApplicable, millis)
|
||||
addRequirement(candidate, capability.CapabilityKindRunTests, "validate software change", epistemics.VerificationNotApplicable, millis)
|
||||
addStep(candidate, work.PlanStepInvestigate, "Understand desired capability and affected project scope.", 1, millis)
|
||||
@@ -254,6 +206,7 @@ func addScenarioPlan(input work.PlanningInput, millis int64, candidate *work.Pla
|
||||
addDelegation(candidate, requirement, millis)
|
||||
}
|
||||
}
|
||||
|
||||
func requiresDurableWork(lower string) bool {
|
||||
return containsAny(lower, "тормозит", "медлен", "производительн", "разберись", "почему", "добавь", "поддержк", "возможность", "реализ", "патч", "исправь", "установи", "большую модель")
|
||||
}
|
||||
|
||||
@@ -25,9 +25,7 @@ func TestPlanningInvestigationIsNotCodexPrompt(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestPlanningCodeChangeRequiresModifyCodeWithoutExecutor(t *testing.T) {
|
||||
input := planningInputForTest("В Assistant добавь поддержку X.", "DIRECTIVE", epistemics.VerificationNotApplicable)
|
||||
input.CapabilityHints = []capability.CapabilityKind{capability.CapabilityKindModifyCode}
|
||||
result := planForTestWithInput(t, input)
|
||||
result := planForTest(t, "В Assistant добавь поддержку X.", "DIRECTIVE", epistemics.VerificationNotApplicable)
|
||||
requireKinds(t, result, capability.CapabilityKindModifyCode, capability.CapabilityKindRunTests)
|
||||
for _, delegation := range result.Candidate.Delegations {
|
||||
if delegation.ExecutorHint != "" {
|
||||
@@ -43,9 +41,7 @@ func TestPlanningEmailReviewIsNotCodexSpecific(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestPlanningReminderUsesSchedulingRequirement(t *testing.T) {
|
||||
input := planningInputForTest("Напомни завтра позвонить врачу.", "DIRECTIVE", epistemics.VerificationNotApplicable)
|
||||
input.CapabilityHints = []capability.CapabilityKind{capability.CapabilityKindScheduleReminder}
|
||||
result := planForTestWithInput(t, input)
|
||||
result := planForTest(t, "Напомни завтра позвонить врачу.", "DIRECTIVE", epistemics.VerificationNotApplicable)
|
||||
requireKinds(t, result, capability.CapabilityKindScheduleReminder)
|
||||
requireNoKind(t, result, capability.CapabilityKindModifyCode)
|
||||
}
|
||||
@@ -83,18 +79,14 @@ func TestPlanningFallbackPersistsWithoutCognition(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestHelpPathSimpleAnswerDoesNotRequireDurableGoalWorkPlan(t *testing.T) {
|
||||
input := planningInputForTest("Объясни, что делает этот код.", "QUESTION", epistemics.VerificationNotApplicable)
|
||||
input.NeedsCognition = true
|
||||
path := DetermineHelpPath(input)
|
||||
path := DetermineHelpPath(planningInputForTest("Объясни, что делает этот код.", "QUESTION", epistemics.VerificationNotApplicable))
|
||||
if path.Kind != work.HelpPathCognition || path.NeedsDurableGoal || path.NeedsDurableWork || path.NeedsDurablePlan {
|
||||
t.Fatalf("simple help must not require durable planning: %#v", path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHelpPathReminderCanUseDirectCapabilityWithoutWorkflow(t *testing.T) {
|
||||
input := planningInputForTest("Напомни завтра позвонить.", "DIRECTIVE", epistemics.VerificationNotApplicable)
|
||||
input.CapabilityHints = []capability.CapabilityKind{capability.CapabilityKindScheduleReminder}
|
||||
path := DetermineHelpPath(input)
|
||||
path := DetermineHelpPath(planningInputForTest("Напомни завтра позвонить.", "DIRECTIVE", epistemics.VerificationNotApplicable))
|
||||
if path.Kind != work.HelpPathDirectCapability || path.NeedsDurableWork || len(path.SuggestedCapabilityKinds) != 1 || path.SuggestedCapabilityKinds[0] != capability.CapabilityKindScheduleReminder {
|
||||
t.Fatalf("reminder should be direct scheduling capability path: %#v", path)
|
||||
}
|
||||
@@ -107,31 +99,6 @@ func TestHelpPathComplexWorkMaterializesDurablePlanning(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHelpPathStructuredIntentNotOverriddenByRawRussianText(t *testing.T) {
|
||||
path := DetermineHelpPath(work.PlanningInput{
|
||||
ConversationID: "conversation-1",
|
||||
UtteranceID: "utterance-1",
|
||||
IntentID: "intent-1",
|
||||
ActorID: identity.ActorID("actor-1"),
|
||||
PrincipalID: identity.PrincipalID("principal-1"),
|
||||
ProjectID: work.ProjectRef("upo"),
|
||||
ProjectDisplayName: "УПО",
|
||||
ProjectProvenance: work.ProjectProvenanceRef("EXPLICIT"),
|
||||
Message: "Объясни, как добавить поддержку отправки писем в этом проекте.",
|
||||
SpeechAct: work.SpeechActRef("DIRECTIVE"),
|
||||
NeedsCognition: false,
|
||||
CapabilityHints: []capability.CapabilityKind{capability.CapabilityKindModifyCode},
|
||||
AssertionVerification: epistemics.VerificationNotApplicable,
|
||||
ReceivedAtUnixMillis: time.Unix(100, 0).UnixMilli(),
|
||||
})
|
||||
if path.Kind != work.HelpPathDurableWork || !path.NeedsDurableWork || !path.NeedsDurablePlan {
|
||||
t.Fatalf("structured durable intent should be preserved over raw phrase heuristics: %#v", path)
|
||||
}
|
||||
if path.Kind == work.HelpPathCognition {
|
||||
t.Fatalf("raw Russian phrase should not force cognition when selected interpretation is already directive: %#v", path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHelpPathCapabilityGapDoesNotBecomeCodexTask(t *testing.T) {
|
||||
path := DetermineHelpPath(planningInputForTest("Подключи интеграцию с неизвестным сервисом, которого сейчас нет.", "DIRECTIVE", epistemics.VerificationNotApplicable))
|
||||
if path.Kind != work.HelpPathCapabilityGap || !path.CapabilityGap {
|
||||
@@ -142,33 +109,9 @@ func TestHelpPathCapabilityGapDoesNotBecomeCodexTask(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHelpPathStructuredHintsOverrideRawCognitionPhrase(t *testing.T) {
|
||||
input := planningInputForTest("Объясни, что делает этот код.", "QUESTION", epistemics.VerificationNotApplicable)
|
||||
input.NeedsCognition = false
|
||||
input.CapabilityHints = []capability.CapabilityKind{capability.CapabilityKindSendEmail}
|
||||
path := DetermineHelpPath(input)
|
||||
if path.Kind != work.HelpPathCapabilityGap || !path.CapabilityGap {
|
||||
t.Fatalf("structured send-email hint should force capability gap path: %#v", path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHelpPathDoesNotUseUnsupportedCapabilityHeuristicAfterCognitiveDeferral(t *testing.T) {
|
||||
input := planningInputForTest("Подключи интеграцию с неизвестным сервисом, которого сейчас нет.", "DIRECTIVE", epistemics.VerificationNotApplicable)
|
||||
input.NeedsCognition = true
|
||||
path := DetermineHelpPath(input)
|
||||
if path.Kind == work.HelpPathCapabilityGap {
|
||||
t.Fatalf("raw unsupported-capability phrase must not override deferred cognitive interpretation: %#v", path)
|
||||
}
|
||||
}
|
||||
|
||||
func planForTest(t *testing.T, message string, act string, verification epistemics.VerificationState) work.PlanningResult {
|
||||
t.Helper()
|
||||
return planForTestWithInput(t, planningInputForTest(message, act, verification))
|
||||
}
|
||||
|
||||
func planForTestWithInput(t *testing.T, input work.PlanningInput) work.PlanningResult {
|
||||
t.Helper()
|
||||
result, err := BuildPlanningResult(input, time.Unix(100, 0))
|
||||
result, err := BuildPlanningResult(planningInputForTest(message, act, verification), time.Unix(100, 0))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user