Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
54de3f44d0 | ||
|
|
11a6a23f6e | ||
|
|
ce666bbc43 | ||
|
|
64870798b9 |
@@ -43,15 +43,25 @@ func (r *InteractionRepository) AppendUtterance(ctx context.Context, c interacti
|
|||||||
return tx.Commit(ctx)
|
return tx.Commit(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *InteractionRepository) SaveSemanticResult(ctx context.Context, interpretation interaction.UtteranceInterpretation, projects []interaction.ProjectReference, relations []interaction.InteractionRelation) error {
|
func (r *InteractionRepository) SaveSemanticResult(ctx context.Context, interpretation interaction.UtteranceInterpretation, candidates []interaction.SemanticCandidate, projects []interaction.ProjectReference, relations []interaction.InteractionRelation) error {
|
||||||
tx, err := r.pool.Begin(ctx)
|
tx, err := r.pool.Begin(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer tx.Rollback(ctx)
|
defer tx.Rollback(ctx)
|
||||||
if _, err = tx.Exec(ctx, `INSERT INTO interaction.utterance_interpretations(interpretation_id,utterance_id,speech_act,confidence_millis,source,assertion_verification,requested_outcome,clarification,recorded_at_unix_millis) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`, interpretation.ID, interpretation.UtteranceID, interpretation.SpeechAct, interpretation.ConfidenceMillis, interpretation.Source, interpretation.AssertionVerification, interpretation.RequestedOutcome, interpretation.Clarification, interpretation.RecordedAtUnixMillis); err != nil {
|
if _, err = tx.Exec(ctx, `INSERT INTO interaction.utterance_interpretations(interpretation_id,utterance_id,speech_act,secondary_speech_act,confidence_millis,source,assertion_verification,requested_outcome,clarification,needs_cognition,applicability,selection_reason,recorded_at_unix_millis) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)`, interpretation.ID, interpretation.UtteranceID, interpretation.SpeechAct, interpretation.SecondarySpeechAct, interpretation.ConfidenceMillis, interpretation.Source, interpretation.AssertionVerification, interpretation.RequestedOutcome, interpretation.Clarification, interpretation.NeedsCognition, interpretation.Applicability, interpretation.SelectionReason, interpretation.RecordedAtUnixMillis); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
for _, candidate := range candidates {
|
||||||
|
if _, err = tx.Exec(ctx, `INSERT INTO interaction.semantic_candidates(candidate_id,utterance_id,source,selection_state,primary_speech_act,secondary_speech_act,confidence_millis,applicability,requested_outcome,clarification,needs_cognition,selection_reason,recorded_at_unix_millis) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13) ON CONFLICT(candidate_id) DO UPDATE SET selection_state=EXCLUDED.selection_state,primary_speech_act=EXCLUDED.primary_speech_act,secondary_speech_act=EXCLUDED.secondary_speech_act,confidence_millis=EXCLUDED.confidence_millis,applicability=EXCLUDED.applicability,requested_outcome=EXCLUDED.requested_outcome,clarification=EXCLUDED.clarification,needs_cognition=EXCLUDED.needs_cognition,selection_reason=EXCLUDED.selection_reason,recorded_at_unix_millis=EXCLUDED.recorded_at_unix_millis`, candidate.ID, candidate.UtteranceID, candidate.Source, candidate.SelectionState, candidate.PrimarySpeechAct, candidate.SecondarySpeechAct, candidate.ConfidenceMillis, candidate.Applicability, candidate.RequestedOutcome, candidate.Clarification, candidate.NeedsCognition, candidate.SelectionReason, candidate.RecordedAtUnixMillis); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, hint := range candidate.CapabilityHints {
|
||||||
|
if _, err = tx.Exec(ctx, `INSERT INTO interaction.semantic_candidate_capability_hints(candidate_id,capability_kind) VALUES($1,$2) ON CONFLICT DO NOTHING`, candidate.ID, hint); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
for _, project := range projects {
|
for _, project := range projects {
|
||||||
if _, err = tx.Exec(ctx, `INSERT INTO interaction.project_references(project_reference_id,utterance_id,project_id,project_display_name,role,provenance,confidence_millis,recorded_at_unix_millis) VALUES($1,$2,$3,$4,$5,$6,$7,$8)`, project.ID, project.UtteranceID, project.ProjectID, project.ProjectDisplayName, project.Role, project.Provenance, project.ConfidenceMillis, project.RecordedAtUnixMillis); err != nil {
|
if _, err = tx.Exec(ctx, `INSERT INTO interaction.project_references(project_reference_id,utterance_id,project_id,project_display_name,role,provenance,confidence_millis,recorded_at_unix_millis) VALUES($1,$2,$3,$4,$5,$6,$7,$8)`, project.ID, project.UtteranceID, project.ProjectID, project.ProjectDisplayName, project.Role, project.Provenance, project.ConfidenceMillis, project.RecordedAtUnixMillis); err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.cin.su/m/Assistant/contracts/capability"
|
||||||
|
"git.cin.su/m/Assistant/contracts/cognitive"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (g cognitiveGateway) interpretationHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var request cognitive.GatewayInterpretationRequest
|
||||||
|
if !decodeJSON(w, r, 80<<10, &request) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if request.Version != cognitive.CreatorAdvisoryV1 || request.RequestID == "" || request.ActorID == "" || request.PrincipalID == "" || request.ScopeID == "" || strings.TrimSpace(request.Message) == "" || request.MaxOutputBytes < 1 {
|
||||||
|
http.Error(w, "invalid interpretation request", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
maxOutputBytes := request.MaxOutputBytes
|
||||||
|
if g.allowCanary && g.canaryMaxOutputBytes > 0 && maxOutputBytes > g.canaryMaxOutputBytes {
|
||||||
|
maxOutputBytes = g.canaryMaxOutputBytes
|
||||||
|
}
|
||||||
|
requirement := capability.CognitiveRequirement{
|
||||||
|
CapabilityID: creatorAdvisoryCapabilityID,
|
||||||
|
OwnerPrincipalID: request.PrincipalID,
|
||||||
|
DataPolicy: request.DataPolicy,
|
||||||
|
RequiredModalities: []capability.ModelModality{capability.ModalityText},
|
||||||
|
RequiredCapabilities: []capability.ModelCapability{capability.CapabilityAdvisory},
|
||||||
|
AllowCanary: g.allowCanary,
|
||||||
|
InputBytes: int64(len(request.Message)),
|
||||||
|
MaxOutputBytes: int64(maxOutputBytes),
|
||||||
|
}
|
||||||
|
selected, err := g.resolver.Resolve(r.Context(), requirement)
|
||||||
|
if err != nil {
|
||||||
|
writeInterpretationResponse(w, cognitive.GatewayInterpretationResponse{Version: request.Version, RequestID: request.RequestID, FinishReason: cognitive.FinishProviderUnavailable})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
provider := g.provider(selected)
|
||||||
|
if provider == nil {
|
||||||
|
writeInterpretationResponse(w, cognitive.GatewayInterpretationResponse{Version: request.Version, RequestID: request.RequestID, FinishReason: cognitive.FinishProviderUnavailable})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
invocation := cognitive.AdvisoryRequest{
|
||||||
|
Version: request.Version,
|
||||||
|
RequestID: request.RequestID,
|
||||||
|
ActorID: request.ActorID,
|
||||||
|
PrincipalID: request.PrincipalID,
|
||||||
|
ScopeID: request.ScopeID,
|
||||||
|
Message: interpretationPrompt(request),
|
||||||
|
Locale: request.Locale,
|
||||||
|
MaxOutputBytes: maxOutputBytes,
|
||||||
|
ProviderBindingID: selected.Binding.ID,
|
||||||
|
ProviderBindingRevision: selected.Binding.Revision,
|
||||||
|
ProviderInstanceID: selected.Provider.ID,
|
||||||
|
ModelDescriptorID: selected.Model.ID,
|
||||||
|
ProviderModelID: selected.Model.ProviderModelID,
|
||||||
|
}
|
||||||
|
started := g.now()
|
||||||
|
response, invokeErr := provider.Advise(r.Context(), invocation)
|
||||||
|
if invokeErr != nil {
|
||||||
|
response = cognitive.AdvisoryResponse{Version: request.Version, RequestID: request.RequestID, ProviderBindingID: selected.Binding.ID, ProviderBindingRevision: selected.Binding.Revision, FinishReason: cognitive.FinishInvalidProviderResponse}
|
||||||
|
}
|
||||||
|
g.observe(r.Context(), selected, response, started)
|
||||||
|
if response.FinishReason != cognitive.FinishCompleted {
|
||||||
|
writeInterpretationResponse(w, cognitive.GatewayInterpretationResponse{Version: request.Version, RequestID: request.RequestID, FinishReason: response.FinishReason, Usage: response.Usage})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
candidate, ok := parseInterpretationCandidate(response.AdvisoryText)
|
||||||
|
if !ok {
|
||||||
|
writeInterpretationResponse(w, cognitive.GatewayInterpretationResponse{Version: request.Version, RequestID: request.RequestID, FinishReason: cognitive.FinishInvalidStructuredOutput, Usage: response.Usage})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeInterpretationResponse(w, cognitive.GatewayInterpretationResponse{Version: request.Version, RequestID: request.RequestID, Candidate: candidate, FinishReason: cognitive.FinishCompleted, Usage: response.Usage})
|
||||||
|
}
|
||||||
|
|
||||||
|
func interpretationPrompt(request cognitive.GatewayInterpretationRequest) string {
|
||||||
|
projects := "none"
|
||||||
|
if len(request.ProjectNames) > 0 {
|
||||||
|
projects = strings.Join(request.ProjectNames, ", ")
|
||||||
|
}
|
||||||
|
return fmt.Sprintf(`Return only strict JSON with keys primary_speech_act, secondary_speech_act, confidence_millis, applicability, requested_outcome, needs_cognition, clarification, selection_reason, capability_hints.
|
||||||
|
Allowed speech acts: DIRECTIVE, ASSERTION, DECISION, PREFERENCE, QUESTION, HYPOTHESIS, CORRECTION, REQUEST_TO_INVESTIGATE, CONFIRMATION, REJECTION, CANCELLATION, CONVERSATIONAL, UNKNOWN.
|
||||||
|
Allowed applicability: APPLICABLE, LOW_CONFIDENCE, MIXED_INTENT, NEEDS_BROADER_INTERPRETATION, CLARIFICATION_REQUIRED.
|
||||||
|
Allowed clarification: NOT_REQUIRED or REQUIRED.
|
||||||
|
Capability hints may only contain known capability kinds like COGNITIVE_REASONING, MODIFY_CODE, RUN_TESTS, SEND_EMAIL, SCHEDULE_REMINDER, VERIFY_FACT, INSPECT_PROJECT, READ_DATABASE, QUERY_LOGS.
|
||||||
|
Interpret the human utterance semantically. Do not claim action execution. Do not treat punctuation alone as decisive. If uncertain, set applicability accordingly.
|
||||||
|
Message: %q
|
||||||
|
Deterministic primary: %s
|
||||||
|
Deterministic secondary: %s
|
||||||
|
Deterministic confidence: %d
|
||||||
|
Deterministic applicability: %s
|
||||||
|
Deterministic requested outcome: %q
|
||||||
|
Relevant project names: %s`, request.Message, request.DeterministicSpeechAct, request.DeterministicSecondary, request.DeterministicConfidence, request.DeterministicApplicability, request.RequestedOutcome, projects)
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseInterpretationCandidate(text string) (cognitive.GatewayInterpretationCandidate, bool) {
|
||||||
|
start := strings.Index(text, "{")
|
||||||
|
end := strings.LastIndex(text, "}")
|
||||||
|
if start < 0 || end <= start {
|
||||||
|
return cognitive.GatewayInterpretationCandidate{}, false
|
||||||
|
}
|
||||||
|
var candidate cognitive.GatewayInterpretationCandidate
|
||||||
|
if err := json.Unmarshal([]byte(text[start:end+1]), &candidate); err != nil {
|
||||||
|
return cognitive.GatewayInterpretationCandidate{}, false
|
||||||
|
}
|
||||||
|
if !validSpeechAct(candidate.PrimarySpeechAct) || candidate.ConfidenceMillis < 0 || candidate.ConfidenceMillis > 1000 {
|
||||||
|
return cognitive.GatewayInterpretationCandidate{}, false
|
||||||
|
}
|
||||||
|
if candidate.SecondarySpeechAct != "" && !validSpeechAct(candidate.SecondarySpeechAct) {
|
||||||
|
return cognitive.GatewayInterpretationCandidate{}, false
|
||||||
|
}
|
||||||
|
switch candidate.Applicability {
|
||||||
|
case cognitive.InterpretationApplicable, cognitive.InterpretationLowConfidence, cognitive.InterpretationMixedIntent, cognitive.InterpretationNeedsBroader, cognitive.InterpretationClarificationRequired:
|
||||||
|
default:
|
||||||
|
return cognitive.GatewayInterpretationCandidate{}, false
|
||||||
|
}
|
||||||
|
if candidate.Clarification != "NOT_REQUIRED" && candidate.Clarification != "REQUIRED" {
|
||||||
|
return cognitive.GatewayInterpretationCandidate{}, false
|
||||||
|
}
|
||||||
|
return candidate, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func validSpeechAct(value string) bool {
|
||||||
|
switch value {
|
||||||
|
case "DIRECTIVE", "ASSERTION", "DECISION", "PREFERENCE", "QUESTION", "HYPOTHESIS", "CORRECTION", "REQUEST_TO_INVESTIGATE", "CONFIRMATION", "REJECTION", "CANCELLATION", "CONVERSATIONAL", "UNKNOWN":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeInterpretationResponse(w http.ResponseWriter, response cognitive.GatewayInterpretationResponse) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(w).Encode(response)
|
||||||
|
}
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.cin.su/m/Assistant/adapters/models"
|
||||||
|
"git.cin.su/m/Assistant/contracts/authority"
|
||||||
|
"git.cin.su/m/Assistant/contracts/capability"
|
||||||
|
"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/contracts/situation"
|
||||||
|
interactiondomain "git.cin.su/m/Assistant/modules/interaction/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLiveInterpretationTrace(t *testing.T) {
|
||||||
|
if os.Getenv("ASSISTANT_LIVE_SEMANTIC_TRACE") != "1" {
|
||||||
|
t.Skip("set ASSISTANT_LIVE_SEMANTIC_TRACE=1 for live semantic/gateway/raw trace")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
rawBase := envOr("LOCAL_CPU_PROVIDER_URL", "http://docker.cin.su:18082/v1")
|
||||||
|
rawModelID, err := firstRawModel(ctx, rawBase)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cpuAdapter, err := models.NewOpenAICompatibleLocalAdapter(rawBase, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
discovered, probe := cpuAdapter.Discover(ctx)
|
||||||
|
if probe.Health != capability.HealthAvailable || len(discovered) == 0 {
|
||||||
|
t.Fatalf("cpu discovery unavailable: probe=%+v models=%+v", probe, discovered)
|
||||||
|
}
|
||||||
|
selected := capability.ResolvedCognitiveBinding{
|
||||||
|
Binding: capability.CognitiveBinding{
|
||||||
|
ID: "trace-binding",
|
||||||
|
Revision: 1,
|
||||||
|
CapabilityID: "creator-advisory",
|
||||||
|
OwnerPrincipalID: "domovoy-creator-principal",
|
||||||
|
DataPolicy: capability.DataPolicyLocalOnly,
|
||||||
|
},
|
||||||
|
Provider: capability.ProviderInstance{
|
||||||
|
ID: "local-cpu-primary",
|
||||||
|
Revision: 1,
|
||||||
|
Kind: "openai-compatible-chat-v1",
|
||||||
|
EndpointRef: "local-cpu-primary-v1",
|
||||||
|
},
|
||||||
|
Model: capability.ModelDescriptor{
|
||||||
|
ID: capability.ModelDescriptorID("trace-model"),
|
||||||
|
Revision: 1,
|
||||||
|
ProviderModelID: discovered[0].ProviderModelID,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
gateway := cognitiveGateway{
|
||||||
|
resolver: traceResolver{selected: selected},
|
||||||
|
providers: map[capability.ProviderKind][]providerRegistration{
|
||||||
|
"openai-compatible-chat-v1": {{
|
||||||
|
ProviderInstanceID: "local-cpu-primary",
|
||||||
|
Kind: "openai-compatible-chat-v1",
|
||||||
|
EndpointRef: "local-cpu-primary-v1",
|
||||||
|
Provider: cpuAdapter,
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
now: time.Now,
|
||||||
|
allowCanary: true,
|
||||||
|
}
|
||||||
|
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 {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
semantic, err := interactiondomain.InterpretUtterance(utterance, []situation.ProjectDescriptor{{ID: "assistant", DisplayName: "Assistant"}}, nil, time.Now())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
rawResponse, err := rawCompletion(ctx, rawBase, rawModelID, message)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
request := cognitive.GatewayInterpretationRequest{
|
||||||
|
Version: cognitive.CreatorAdvisoryV1,
|
||||||
|
RequestID: "trace-request",
|
||||||
|
ActorID: identity.ActorID("trace-actor"),
|
||||||
|
PrincipalID: identity.PrincipalID("domovoy-creator-principal"),
|
||||||
|
ScopeID: authority.ScopeID("domovoy-global-scope"),
|
||||||
|
Message: message,
|
||||||
|
Locale: "ru",
|
||||||
|
MaxOutputBytes: 4096,
|
||||||
|
DataPolicy: capability.DataPolicyLocalOnly,
|
||||||
|
DeterministicSpeechAct: string(semantic.Interpretation.SpeechAct),
|
||||||
|
DeterministicSecondary: string(semantic.Interpretation.SecondarySpeechAct),
|
||||||
|
DeterministicConfidence: semantic.Interpretation.ConfidenceMillis,
|
||||||
|
DeterministicApplicability: cognitive.InterpretationApplicability(semantic.Interpretation.Applicability),
|
||||||
|
RequestedOutcome: semantic.Interpretation.RequestedOutcome,
|
||||||
|
}
|
||||||
|
payload, _ := json.Marshal(request)
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
httpRequest := httptest.NewRequest(http.MethodPost, "/v1/interpretations", bytes.NewReader(payload))
|
||||||
|
gateway.interpretationHandler(recorder, httpRequest.WithContext(ctx))
|
||||||
|
if recorder.Code != http.StatusOK {
|
||||||
|
t.Fatalf("message=%q gateway status=%d body=%s", message, recorder.Code, recorder.Body.String())
|
||||||
|
}
|
||||||
|
var gatewayResponse cognitive.GatewayInterpretationResponse
|
||||||
|
if err := json.Unmarshal(recorder.Body.Bytes(), &gatewayResponse); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if gatewayResponse.FinishReason != cognitive.FinishCompleted {
|
||||||
|
t.Fatalf("message=%q gateway finish=%s body=%s", message, gatewayResponse.FinishReason, recorder.Body.String())
|
||||||
|
}
|
||||||
|
if rawResponse == "" {
|
||||||
|
t.Fatalf("message=%q raw response is empty", message)
|
||||||
|
}
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type traceResolver struct {
|
||||||
|
selected capability.ResolvedCognitiveBinding
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r traceResolver) Resolve(context.Context, capability.CognitiveRequirement) (capability.ResolvedCognitiveBinding, error) {
|
||||||
|
return r.selected, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r traceResolver) Observe(context.Context, capability.CognitiveUsageObservation) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r traceResolver) RegisterDiscovery(context.Context, capability.CognitiveDiscoverySnapshot) (capability.CognitiveDiscoveryRegistration, error) {
|
||||||
|
return capability.CognitiveDiscoveryRegistration{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func firstRawModel(ctx context.Context, base string) (string, error) {
|
||||||
|
request, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/models", nil)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
response, err := http.DefaultClient.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
var payload struct {
|
||||||
|
Data []struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
} `json:"data"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(io.LimitReader(response.Body, 64<<10)).Decode(&payload); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if len(payload.Data) == 0 || payload.Data[0].ID == "" {
|
||||||
|
return "", io.EOF
|
||||||
|
}
|
||||||
|
return payload.Data[0].ID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func rawCompletion(ctx context.Context, base, model, message string) (string, error) {
|
||||||
|
payload, err := json.Marshal(map[string]any{
|
||||||
|
"model": model,
|
||||||
|
"max_tokens": 128,
|
||||||
|
"messages": []map[string]string{
|
||||||
|
{"role": "user", "content": message},
|
||||||
|
},
|
||||||
|
"stream": false,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
request, err := http.NewRequestWithContext(ctx, http.MethodPost, base+"/chat/completions", bytes.NewReader(payload))
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
response, err := http.DefaultClient.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
var result struct {
|
||||||
|
Choices []struct {
|
||||||
|
Message struct {
|
||||||
|
Content string `json:"content"`
|
||||||
|
} `json:"message"`
|
||||||
|
} `json:"choices"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(io.LimitReader(response.Body, 1<<20)).Decode(&result); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if len(result.Choices) == 0 {
|
||||||
|
return "", io.EOF
|
||||||
|
}
|
||||||
|
return result.Choices[0].Message.Content, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func truncate(value string, max int) string {
|
||||||
|
if len(value) <= max {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
return value[:max] + "..."
|
||||||
|
}
|
||||||
@@ -63,6 +63,7 @@ func main() {
|
|||||||
mux.HandleFunc("POST /v1/proposals/deterministic", deterministicProposal)
|
mux.HandleFunc("POST /v1/proposals/deterministic", deterministicProposal)
|
||||||
mux.HandleFunc("POST /v1/advisory-policy", gateway.policyHandler)
|
mux.HandleFunc("POST /v1/advisory-policy", gateway.policyHandler)
|
||||||
mux.HandleFunc("POST /v1/advisories", gateway.advisoryHandler)
|
mux.HandleFunc("POST /v1/advisories", gateway.advisoryHandler)
|
||||||
|
mux.HandleFunc("POST /v1/interpretations", gateway.interpretationHandler)
|
||||||
discovery := discoveryService{resolver: resolver, providers: discoveries, owner: identity.PrincipalID(envOr("COGNITIVE_OWNER_PRINCIPAL_ID", "domovoy-creator-principal")), now: time.Now}
|
discovery := discoveryService{resolver: resolver, providers: discoveries, owner: identity.PrincipalID(envOr("COGNITIVE_OWNER_PRINCIPAL_ID", "domovoy-creator-principal")), now: time.Now}
|
||||||
mux.HandleFunc("POST /v1/provider-discovery/{provider}", discovery.handler)
|
mux.HandleFunc("POST /v1/provider-discovery/{provider}", discovery.handler)
|
||||||
log.Printf("cognitive-worker listening on %s", addr)
|
log.Printf("cognitive-worker listening on %s", addr)
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
|
||||||
|
"git.cin.su/m/Assistant/contracts/authority"
|
||||||
|
"git.cin.su/m/Assistant/contracts/capability"
|
||||||
|
"git.cin.su/m/Assistant/contracts/cognitive"
|
||||||
|
"git.cin.su/m/Assistant/contracts/identity"
|
||||||
|
"git.cin.su/m/Assistant/contracts/interaction"
|
||||||
|
interactiondomain "git.cin.su/m/Assistant/modules/interaction/domain"
|
||||||
|
"git.cin.su/m/Assistant/platform/ids"
|
||||||
|
)
|
||||||
|
|
||||||
|
type cognitiveInterpretationClient struct {
|
||||||
|
baseURL *url.URL
|
||||||
|
client *http.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func newCognitiveInterpretationClient(rawURL string, client *http.Client) (cognitiveInterpretationClient, error) {
|
||||||
|
base, err := url.Parse(rawURL)
|
||||||
|
if err != nil || base.Scheme == "" || base.Host == "" {
|
||||||
|
return cognitiveInterpretationClient{}, fmt.Errorf("invalid Cognitive Runtime URL")
|
||||||
|
}
|
||||||
|
if client == nil {
|
||||||
|
client = http.DefaultClient
|
||||||
|
}
|
||||||
|
return cognitiveInterpretationClient{baseURL: base, client: client}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c cognitiveInterpretationClient) Interpret(ctx context.Context, request cognitive.GatewayInterpretationRequest) (cognitive.GatewayInterpretationResponse, error) {
|
||||||
|
target := *c.baseURL
|
||||||
|
target.Path = "/v1/interpretations"
|
||||||
|
payload, err := json.Marshal(request)
|
||||||
|
if err != nil {
|
||||||
|
return cognitive.GatewayInterpretationResponse{}, err
|
||||||
|
}
|
||||||
|
upstream, err := http.NewRequestWithContext(ctx, http.MethodPost, target.String(), bytes.NewReader(payload))
|
||||||
|
if err != nil {
|
||||||
|
return cognitive.GatewayInterpretationResponse{}, err
|
||||||
|
}
|
||||||
|
upstream.Header.Set("Content-Type", "application/json")
|
||||||
|
response, err := c.client.Do(upstream)
|
||||||
|
if err != nil {
|
||||||
|
return cognitive.GatewayInterpretationResponse{}, err
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode != http.StatusOK {
|
||||||
|
return cognitive.GatewayInterpretationResponse{}, fmt.Errorf("cognitive interpretation status %d", response.StatusCode)
|
||||||
|
}
|
||||||
|
var result cognitive.GatewayInterpretationResponse
|
||||||
|
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
|
||||||
|
return cognitive.GatewayInterpretationResponse{}, err
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func shouldRequestBroaderInterpretation(result interactiondomain.SemanticResult) bool {
|
||||||
|
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 {
|
||||||
|
requestID, _ := ids.New()
|
||||||
|
return cognitive.GatewayInterpretationRequest{
|
||||||
|
Version: cognitive.CreatorAdvisoryV1,
|
||||||
|
RequestID: cognitive.RequestID(requestID),
|
||||||
|
ActorID: session.ActorID,
|
||||||
|
PrincipalID: session.PrincipalID,
|
||||||
|
ScopeID: authority.ScopeID("domovoy-global-scope"),
|
||||||
|
Message: utterance.Content,
|
||||||
|
Locale: "ru",
|
||||||
|
MaxOutputBytes: 4096,
|
||||||
|
DataPolicy: capability.DataPolicyLocalOnly,
|
||||||
|
DeterministicSpeechAct: string(semantic.Interpretation.SpeechAct),
|
||||||
|
DeterministicSecondary: string(semantic.Interpretation.SecondarySpeechAct),
|
||||||
|
DeterministicConfidence: semantic.Interpretation.ConfidenceMillis,
|
||||||
|
DeterministicApplicability: cognitive.InterpretationApplicability(semantic.Interpretation.Applicability),
|
||||||
|
RequestedOutcome: semantic.Interpretation.RequestedOutcome,
|
||||||
|
ProjectNames: projectNames,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func interactionCandidateFromGateway(utteranceID interaction.HumanUtteranceID, candidate cognitive.GatewayInterpretationCandidate, now interface{ UnixMilli() int64 }) (interaction.SemanticCandidate, error) {
|
||||||
|
id, err := ids.New()
|
||||||
|
if err != nil {
|
||||||
|
return interaction.SemanticCandidate{}, err
|
||||||
|
}
|
||||||
|
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: capabilityHintStrings(candidate.CapabilityHints),
|
||||||
|
RecordedAtUnixMillis: now.UnixMilli(),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func capabilityHintStrings(values []capability.CapabilityKind) []string {
|
||||||
|
result := make([]string, 0, len(values))
|
||||||
|
for _, value := range values {
|
||||||
|
if value == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
result = append(result, string(value))
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"git.cin.su/m/Assistant/adapters/postgres"
|
"git.cin.su/m/Assistant/adapters/postgres"
|
||||||
"git.cin.su/m/Assistant/contracts/authority"
|
"git.cin.su/m/Assistant/contracts/authority"
|
||||||
"git.cin.su/m/Assistant/contracts/capability"
|
"git.cin.su/m/Assistant/contracts/capability"
|
||||||
|
"git.cin.su/m/Assistant/contracts/cognitive"
|
||||||
"git.cin.su/m/Assistant/contracts/continuity"
|
"git.cin.su/m/Assistant/contracts/continuity"
|
||||||
"git.cin.su/m/Assistant/contracts/epistemics"
|
"git.cin.su/m/Assistant/contracts/epistemics"
|
||||||
"git.cin.su/m/Assistant/contracts/identity"
|
"git.cin.su/m/Assistant/contracts/identity"
|
||||||
@@ -111,6 +112,10 @@ func main() {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
cognitiveClient, err := newCognitiveInterpretationClient(envOr("COGNITIVE_RUNTIME_URL", "http://cognitive-worker:8083"), &http.Client{Timeout: 20 * time.Second})
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
learning := learningRecorder{epistemics: epistemicsRepository, capability: capabilityRepository}
|
learning := learningRecorder{epistemics: epistemicsRepository, capability: capabilityRepository}
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
authenticateCreator := func(w http.ResponseWriter, r *http.Request) (identity.CreatorSession, bool) {
|
authenticateCreator := func(w http.ResponseWriter, r *http.Request) (identity.CreatorSession, bool) {
|
||||||
@@ -288,11 +293,24 @@ func main() {
|
|||||||
http.Error(w, "interpret chat message", http.StatusServiceUnavailable)
|
http.Error(w, "interpret chat message", http.StatusServiceUnavailable)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if shouldRequestBroaderInterpretation(semantic) {
|
||||||
|
projectNames := make([]string, 0, len(semantic.Projects))
|
||||||
|
for _, ref := range semantic.Projects {
|
||||||
|
if ref.ProjectDisplayName != "" {
|
||||||
|
projectNames = append(projectNames, ref.ProjectDisplayName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if response, interpretationErr := cognitiveClient.Interpret(r.Context(), buildGatewayInterpretationRequest(session, utterance, semantic, projectNames)); interpretationErr == nil && response.FinishReason == cognitive.FinishCompleted {
|
||||||
|
if candidate, candidateErr := interactionCandidateFromGateway(utterance.ID, response.Candidate, now); candidateErr == nil {
|
||||||
|
semantic = interactiondomain.ApplyCognitiveCandidate(semantic, utterance.Content, candidate, previousFocus)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
if err := interactionRepository.AppendUtterance(r.Context(), conversation, utterance, intent, relations); err != nil {
|
if err := interactionRepository.AppendUtterance(r.Context(), conversation, utterance, intent, relations); err != nil {
|
||||||
http.Error(w, "save chat message", http.StatusInternalServerError)
|
http.Error(w, "save chat message", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := interactionRepository.SaveSemanticResult(r.Context(), semantic.Interpretation, semantic.Projects, semantic.Relations); err != nil {
|
if err := interactionRepository.SaveSemanticResult(r.Context(), semantic.Interpretation, semantic.Candidates, semantic.Projects, semantic.Relations); err != nil {
|
||||||
http.Error(w, "save chat semantics", http.StatusInternalServerError)
|
http.Error(w, "save chat semantics", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -349,7 +367,11 @@ func main() {
|
|||||||
ProjectProvenance: work.ProjectProvenanceRef(activeFocusProvenance),
|
ProjectProvenance: work.ProjectProvenanceRef(activeFocusProvenance),
|
||||||
Message: utterance.Content,
|
Message: utterance.Content,
|
||||||
SpeechAct: work.SpeechActRef(semantic.Interpretation.SpeechAct),
|
SpeechAct: work.SpeechActRef(semantic.Interpretation.SpeechAct),
|
||||||
|
SecondarySpeechAct: work.SpeechActRef(semantic.Interpretation.SecondarySpeechAct),
|
||||||
AssertionVerification: epistemics.VerificationState(semantic.Interpretation.AssertionVerification),
|
AssertionVerification: epistemics.VerificationState(semantic.Interpretation.AssertionVerification),
|
||||||
|
CapabilityHints: toCapabilityKinds(semantic.CapabilityHints),
|
||||||
|
NeedsCognition: semantic.NeedsCognition,
|
||||||
|
RequiresClarification: semantic.Interpretation.Clarification == interaction.ClarificationRequired,
|
||||||
ReceivedAtUnixMillis: utterance.ReceivedAtUnixMillis,
|
ReceivedAtUnixMillis: utterance.ReceivedAtUnixMillis,
|
||||||
}
|
}
|
||||||
helpPath := workdomain.DetermineHelpPath(planningInput)
|
helpPath := workdomain.DetermineHelpPath(planningInput)
|
||||||
@@ -1087,6 +1109,18 @@ func humanCapabilityList(kinds []capability.CapabilityKind) string {
|
|||||||
return strings.Join(labels, ", ")
|
return strings.Join(labels, ", ")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func toCapabilityKinds(values []string) []capability.CapabilityKind {
|
||||||
|
result := make([]capability.CapabilityKind, 0, len(values))
|
||||||
|
for _, value := range values {
|
||||||
|
kind := capability.CapabilityKind(strings.TrimSpace(value))
|
||||||
|
if kind == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
result = append(result, kind)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
func delegationAttentionRef(id work.DelegationID) string {
|
func delegationAttentionRef(id work.DelegationID) string {
|
||||||
return "work:delegation:" + string(id)
|
return "work:delegation:" + string(id)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,76 +1,488 @@
|
|||||||
:root {
|
:root {
|
||||||
--ink: #e9eee7;
|
--ink: #e7efe9;
|
||||||
--muted: #93a096;
|
--muted: #96a49d;
|
||||||
--base: #0b100e;
|
--faint: #5f6e66;
|
||||||
--panel: #101714;
|
--surface: #0f1512;
|
||||||
--line: #2a352f;
|
--surface-alt: #151d18;
|
||||||
--signal: #c9a85f;
|
--line: #27322c;
|
||||||
--bad: #de816f;
|
--base: #090d0b;
|
||||||
--good: #78c6a3;
|
--good: #7cc7a4;
|
||||||
--radius: 3px;
|
--signal: #ceb27a;
|
||||||
|
--bad: #d88d78;
|
||||||
|
--radius-lg: 16px;
|
||||||
|
--radius: 10px;
|
||||||
--sans: "Bahnschrift", "Aptos Narrow", "Segoe UI", sans-serif;
|
--sans: "Bahnschrift", "Aptos Narrow", "Segoe UI", sans-serif;
|
||||||
--serif: Georgia, "Times New Roman", serif;
|
--serif: Georgia, "Times New Roman", serif;
|
||||||
--mono: "Cascadia Mono", Consolas, monospace;
|
--mono: "Cascadia Mono", Consolas, monospace;
|
||||||
|
--shadow: 0 24px 56px rgba(0, 0, 0, .22);
|
||||||
}
|
}
|
||||||
|
|
||||||
* { box-sizing: border-box; }
|
* { box-sizing: border-box; }
|
||||||
[hidden] { display: none !important; }
|
[hidden] { display: none !important; }
|
||||||
body { margin: 0; min-width: 320px; min-height: 100vh; color: var(--ink); background: var(--base); font-family: var(--sans); }
|
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
min-height: 100vh;
|
||||||
|
min-width: 320px;
|
||||||
|
color: var(--ink);
|
||||||
|
background:
|
||||||
|
radial-gradient(circle at 10% 0%, rgba(120, 182, 160, .16), transparent 40%),
|
||||||
|
radial-gradient(circle at 90% 0%, rgba(201, 168, 95, .16), transparent 35%),
|
||||||
|
var(--base);
|
||||||
|
font-family: var(--sans);
|
||||||
|
}
|
||||||
|
|
||||||
button, input, textarea { font: inherit; }
|
button, input, textarea { font: inherit; }
|
||||||
button { cursor: pointer; color: inherit; border-radius: var(--radius); }
|
button { color: inherit; border: 0; border-radius: var(--radius); }
|
||||||
.chat-shell { min-height: 100vh; display: grid; }
|
p { margin: 0; }
|
||||||
.login-panel { width: min(100% - 32px, 420px); margin: auto; padding: 46px 40px; border: 1px solid var(--line); background: var(--panel); }
|
|
||||||
.brand-mark { width: 46px; height: 46px; display: grid; place-items: center; color: var(--base); background: var(--signal); font: 700 24px/1 var(--serif); clip-path: polygon(50% 0, 92% 22%, 92% 76%, 50% 100%, 8% 76%, 8% 22%); }
|
.assistant-shell,
|
||||||
h1 { margin: 30px 0; font: 400 58px/.95 var(--serif); letter-spacing: -.02em; }
|
.chat-view { min-height: 100vh; }
|
||||||
label { display: block; margin: 16px 0 8px; color: var(--muted); font: 600 10px/1 var(--mono); letter-spacing: .12em; text-transform: uppercase; }
|
|
||||||
input, textarea { width: 100%; border: 1px solid var(--line); border-radius: var(--radius); color: var(--ink); background: #0b110e; }
|
.auth-view {
|
||||||
input { height: 48px; padding: 0 12px; }
|
min-height: 100vh;
|
||||||
textarea { resize: vertical; min-height: 84px; max-height: 240px; padding: 14px; line-height: 1.45; }
|
display: grid;
|
||||||
.login-form button, .composer button { border: 0; color: #11150f; background: var(--signal); font-weight: 700; }
|
place-items: center;
|
||||||
.login-form button { width: 100%; height: 50px; margin-top: 18px; }
|
padding: 36px 20px;
|
||||||
#login-error { min-height: 20px; color: var(--bad); font-size: 13px; }
|
}
|
||||||
.chat-view { min-height: 100vh; display: grid; grid-template-rows: 64px minmax(0, 1fr); }
|
|
||||||
.chat-header { display: flex; align-items: center; gap: 18px; padding: 0 22px; border-bottom: 1px solid var(--line); background: rgba(16, 23, 20, .96); }
|
.auth-card {
|
||||||
.chat-header a { color: var(--ink); text-decoration: none; font: 400 24px/1 var(--serif); }
|
width: min(100%, 440px);
|
||||||
.chat-header span { color: var(--muted); font: 10px/1 var(--mono); letter-spacing: .1em; text-transform: uppercase; }
|
padding: 30px;
|
||||||
#active-focus { margin-left: auto; color: var(--good); }
|
border-radius: var(--radius-lg);
|
||||||
.chat-header button { width: 38px; height: 38px; border: 1px solid var(--line); background: transparent; }
|
border: 1px solid var(--line);
|
||||||
.human-nav { display: flex; align-items: center; gap: 8px; }
|
background: rgba(15, 21, 18, .92);
|
||||||
.nav-tab, .operator-link { height: 34px; padding: 0 12px; display: inline-flex; align-items: center; border: 1px solid var(--line); color: var(--muted); background: #0b110e; text-decoration: none; font: 11px/1 var(--mono); text-transform: uppercase; letter-spacing: .08em; }
|
box-shadow: var(--shadow);
|
||||||
.nav-tab.active { color: #11150f; border-color: var(--signal); background: var(--signal); }
|
}
|
||||||
.operator-link { color: var(--good); }
|
|
||||||
.surface-panel { min-height: 0; position: relative; }
|
.brand-block,
|
||||||
.active-panel { display: grid; min-height: 0; }
|
.header-brand {
|
||||||
.messages { width: min(100%, 920px); margin: 0 auto; padding: 28px 18px 120px; display: flex; flex-direction: column; gap: 14px; overflow: auto; }
|
display: flex;
|
||||||
.message { max-width: min(720px, 92%); padding: 14px 16px; border: 1px solid var(--line); border-radius: var(--radius); line-height: 1.45; white-space: pre-wrap; }
|
align-items: center;
|
||||||
.message.user { align-self: flex-end; background: #151e1a; }
|
gap: 14px;
|
||||||
.message.assistant { align-self: flex-start; background: #0f1613; }
|
}
|
||||||
.message small { display: block; margin-top: 8px; color: var(--muted); font: 10px/1 var(--mono); text-transform: uppercase; }
|
|
||||||
.composer { position: sticky; bottom: 0; width: min(100%, 920px); margin: 0 auto; padding: 16px 18px 20px; display: grid; grid-template-columns: minmax(0, 1fr) 130px; gap: 12px; background: linear-gradient(transparent, var(--base) 20%); }
|
.brand-mark {
|
||||||
.composer button { height: 48px; align-self: end; }
|
width: 46px;
|
||||||
.composer button:disabled { cursor: wait; filter: saturate(.3); }
|
height: 46px;
|
||||||
.attention-surface, .history-surface { width: min(100%, 920px); margin: 0 auto; padding: 34px 18px; align-content: start; gap: 18px; }
|
display: grid;
|
||||||
.surface-heading { display: flex; align-items: end; justify-content: space-between; gap: 16px; border-bottom: 1px solid var(--line); padding-bottom: 16px; }
|
place-items: center;
|
||||||
.surface-heading p { margin: 0; font: 400 36px/.95 var(--serif); }
|
border-radius: 50%;
|
||||||
.surface-heading span, .attention-card small, .history-item span { color: var(--muted); font: 10px/1 var(--mono); text-transform: uppercase; letter-spacing: .1em; }
|
color: var(--base);
|
||||||
.surface-heading button { height: 36px; padding: 0 12px; border: 1px solid var(--line); background: transparent; }
|
background: linear-gradient(145deg, var(--good), #7aa7bd);
|
||||||
.attention-list, .history-list { display: grid; gap: 12px; }
|
font: 700 24px/1 var(--serif);
|
||||||
.attention-card, .history-item { border: 1px solid var(--line); background: #0f1613; padding: 16px; }
|
box-shadow: 0 0 0 4px rgba(124, 199, 164, .12);
|
||||||
.attention-card time { color: var(--signal); font: 12px/1 var(--mono); }
|
}
|
||||||
.attention-card h2 { margin: 10px 0 8px; font: 400 24px/1.1 var(--serif); }
|
|
||||||
.attention-card p, .history-item p { margin: 0 0 10px; color: var(--ink); line-height: 1.45; }
|
h1 {
|
||||||
.attention-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 14px; }
|
margin: 0;
|
||||||
.attention-actions button { height: 34px; padding: 0 12px; border: 1px solid var(--line); background: #151e1a; color: var(--ink); font: 11px/1 var(--mono); text-transform: uppercase; letter-spacing: .08em; }
|
font: 500 42px/1.05 var(--serif);
|
||||||
.attention-actions button:first-child { border-color: var(--good); color: var(--good); }
|
}
|
||||||
.history-item.user { border-color: #34443c; background: #151e1a; }
|
|
||||||
.history-item strong { display: block; margin-bottom: 8px; color: var(--signal); }
|
.brand-kicker {
|
||||||
.empty-state { margin: 24px 0 0; color: var(--muted); }
|
margin: 0 0 4px;
|
||||||
|
color: var(--faint);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: .1em;
|
||||||
|
font-size: 11px;
|
||||||
|
font-family: var(--mono);
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-copy {
|
||||||
|
margin: 18px 0 22px;
|
||||||
|
color: var(--muted);
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
display: block;
|
||||||
|
margin: 0 0 6px;
|
||||||
|
color: var(--faint);
|
||||||
|
font-size: 12px;
|
||||||
|
letter-spacing: .03em;
|
||||||
|
}
|
||||||
|
|
||||||
|
input,
|
||||||
|
textarea {
|
||||||
|
width: 100%;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
color: var(--ink);
|
||||||
|
background: #080e0c;
|
||||||
|
}
|
||||||
|
|
||||||
|
input { height: 46px; padding: 0 14px; }
|
||||||
|
input:focus,
|
||||||
|
textarea:focus,
|
||||||
|
.primary-button:focus,
|
||||||
|
.ghost-button:focus,
|
||||||
|
.nav-tab:focus-visible,
|
||||||
|
button:focus-visible,
|
||||||
|
textarea:focus-visible {
|
||||||
|
outline: 2px solid var(--signal);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
textarea {
|
||||||
|
min-height: 96px;
|
||||||
|
max-height: 220px;
|
||||||
|
padding: 14px;
|
||||||
|
line-height: 1.45;
|
||||||
|
resize: vertical;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-with-action {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr) auto;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-button,
|
||||||
|
.ghost-button,
|
||||||
|
.primary-button {
|
||||||
|
height: 44px;
|
||||||
|
border-radius: var(--radius);
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-button,
|
||||||
|
.ghost-button {
|
||||||
|
background: rgba(255, 255, 255, .05);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.primary-button {
|
||||||
|
background: var(--signal);
|
||||||
|
color: #111810;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
#login-button,
|
||||||
|
.primary-button { width: 100%; }
|
||||||
|
|
||||||
|
#login-button,
|
||||||
|
#send { margin-top: 14px; }
|
||||||
|
|
||||||
|
.login-form,
|
||||||
|
.composer {
|
||||||
|
display: grid;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#login-error {
|
||||||
|
min-height: 20px;
|
||||||
|
color: var(--bad);
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-view {
|
||||||
|
width: min(100%, 980px);
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 14px 16px 24px;
|
||||||
|
display: grid;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.assistant-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 0 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.assistant-header h1 {
|
||||||
|
font-size: clamp(30px, 4.4vw, 38px);
|
||||||
|
letter-spacing: -.02em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.session-state {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-pill {
|
||||||
|
padding: 9px 12px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 999px;
|
||||||
|
color: var(--muted);
|
||||||
|
background: #0f1512;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.human-nav {
|
||||||
|
display: inline-flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 6px;
|
||||||
|
width: fit-content;
|
||||||
|
background: #0c1210;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-tab {
|
||||||
|
height: 34px;
|
||||||
|
padding: 0 14px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-tab.active,
|
||||||
|
.nav-tab:hover {
|
||||||
|
background: var(--signal);
|
||||||
|
color: #11150f;
|
||||||
|
}
|
||||||
|
|
||||||
|
.surface-panel {
|
||||||
|
display: grid;
|
||||||
|
align-content: start;
|
||||||
|
min-height: 0;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
background: linear-gradient(180deg, rgba(21, 29, 24, .86), rgba(15, 21, 18, .95));
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.surface-panel.active-panel {
|
||||||
|
display: grid;
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-toolbar {
|
||||||
|
padding: 16px 18px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
background: #0c1210;
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-toolbar h2 {
|
||||||
|
margin: 0;
|
||||||
|
font: 500 26px/1.12 var(--serif);
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-toolbar p {
|
||||||
|
margin-top: 6px;
|
||||||
|
color: var(--muted);
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
|
||||||
|
.focus-chip {
|
||||||
|
margin: 8px 0 0;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--good);
|
||||||
|
padding: 6px 10px;
|
||||||
|
border: 1px solid rgba(124, 199, 164, .45);
|
||||||
|
border-radius: 999px;
|
||||||
|
background: rgba(124, 199, 164, .12);
|
||||||
|
}
|
||||||
|
|
||||||
|
.messages {
|
||||||
|
padding: 24px 18px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
overflow: auto;
|
||||||
|
min-height: calc(100vh - 280px);
|
||||||
|
max-height: calc(100vh - 280px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.message {
|
||||||
|
width: min(92%, 760px);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 12px 14px;
|
||||||
|
line-height: 1.45;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
background: #0f1512;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant { align-self: flex-start; background: #121a16; }
|
||||||
|
.message.user { align-self: flex-end; background: #19231c; border-color: rgba(120, 191, 162, .4); }
|
||||||
|
|
||||||
|
.message-author { color: var(--faint); font-size: 11px; margin-bottom: 6px; font-weight: 700; }
|
||||||
|
.message.user .message-author { color: #b6ddb8; }
|
||||||
|
.message-time { margin-top: 8px; font-size: 11px; color: var(--faint); font-family: var(--mono); }
|
||||||
|
.message small { display: block; margin-top: 6px; color: var(--faint); }
|
||||||
|
|
||||||
|
.composer {
|
||||||
|
position: sticky;
|
||||||
|
bottom: 0;
|
||||||
|
padding: 14px 16px 16px;
|
||||||
|
border-top: 1px solid var(--line);
|
||||||
|
background: linear-gradient(transparent, rgba(11, 16, 14, .88));
|
||||||
|
grid-template-columns: minmax(0, 1fr) auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.composer-actions { display: grid; align-items: end; }
|
||||||
|
|
||||||
|
.composer button:disabled {
|
||||||
|
cursor: wait;
|
||||||
|
opacity: .7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.surface-panel:not(.active-panel) { display: none; }
|
||||||
|
|
||||||
|
.attention-surface,
|
||||||
|
.history-surface { padding: 0 0 12px; }
|
||||||
|
|
||||||
|
.attention-list,
|
||||||
|
.history-list {
|
||||||
|
display: grid;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.attention-card,
|
||||||
|
.history-item {
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 12px;
|
||||||
|
background: #0b110f;
|
||||||
|
padding: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.attention-card h3,
|
||||||
|
.history-item strong { margin: 0 0 8px; font: 600 15px/1.2 var(--serif); }
|
||||||
|
|
||||||
|
.attention-card time,
|
||||||
|
.history-item time,
|
||||||
|
.attention-card .muted,
|
||||||
|
.history-item .muted {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 12px;
|
||||||
|
font-family: var(--mono);
|
||||||
|
}
|
||||||
|
|
||||||
|
.attention-actions { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 12px; }
|
||||||
|
|
||||||
|
.attention-actions .ghost-button,
|
||||||
|
.action-row button {
|
||||||
|
height: 34px;
|
||||||
|
padding: 0 11px;
|
||||||
|
background: rgba(255, 255, 255, .06);
|
||||||
|
color: var(--ink);
|
||||||
|
}
|
||||||
|
|
||||||
|
.attention-actions .ghost-button {
|
||||||
|
border: 1px solid rgba(194, 168, 118, .48);
|
||||||
|
color: #f2e8d0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.attention-actions .ghost-button.primary { border-color: transparent; background: var(--good); color: #11211b; }
|
||||||
|
|
||||||
|
.history-item {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
|
||||||
|
.history-item p {
|
||||||
|
margin: 0 0 8px;
|
||||||
|
color: var(--ink);
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.history-item .history-meta {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 8px;
|
||||||
|
color: var(--faint);
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.history-item .message-kind {
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: .08em;
|
||||||
|
color: var(--signal);
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-bar {
|
||||||
|
margin: 8px auto 0;
|
||||||
|
max-width: 980px;
|
||||||
|
color: var(--faint);
|
||||||
|
padding: 10px 12px;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
background: rgba(15, 21, 18, .8);
|
||||||
|
min-height: 18px;
|
||||||
|
visibility: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-bar.visible { visibility: visible; }
|
||||||
|
|
||||||
|
.composer-error {
|
||||||
|
position: fixed;
|
||||||
|
right: 16px;
|
||||||
|
bottom: 16px;
|
||||||
|
max-width: min(420px, calc(100vw - 32px));
|
||||||
|
border-radius: 12px;
|
||||||
|
border: 1px solid rgba(216, 141, 120, .36);
|
||||||
|
background: #241715;
|
||||||
|
color: #ffd8ca;
|
||||||
|
padding: 10px 12px;
|
||||||
|
transform: translateY(16px);
|
||||||
|
opacity: 0;
|
||||||
|
transition: .2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.composer-error.show {
|
||||||
|
transform: translateY(0);
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.visually-hidden {
|
||||||
|
position: absolute;
|
||||||
|
width: 1px;
|
||||||
|
height: 1px;
|
||||||
|
padding: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
clip: rect(0, 0, 0, 0);
|
||||||
|
clip-path: inset(50%);
|
||||||
|
border: 0;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state {
|
||||||
|
color: var(--muted);
|
||||||
|
padding: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
.empty-state.error { color: var(--bad); }
|
.empty-state.error { color: var(--bad); }
|
||||||
@media (max-width: 640px) {
|
|
||||||
.composer { grid-template-columns: 1fr; }
|
@media (max-width: 720px) {
|
||||||
.composer button { width: 100%; }
|
.chat-view {
|
||||||
.chat-header { gap: 10px; padding: 0 12px; }
|
padding: 10px 10px 18px;
|
||||||
.chat-header span { display: none; }
|
gap: 10px;
|
||||||
.human-nav { overflow-x: auto; }
|
}
|
||||||
.operator-link, .nav-tab { padding: 0 9px; }
|
|
||||||
|
.assistant-header {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.session-state { width: 100%; justify-content: space-between; }
|
||||||
|
|
||||||
|
.messages {
|
||||||
|
min-height: calc(100vh - 320px);
|
||||||
|
max-height: calc(100vh - 320px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.composer {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-toolbar {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.attention-list,
|
||||||
|
.history-list {
|
||||||
|
padding: 12px;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,227 +2,518 @@ const loginView = document.querySelector("#login-view");
|
|||||||
const chatView = document.querySelector("#chat-view");
|
const chatView = document.querySelector("#chat-view");
|
||||||
const loginForm = document.querySelector("#login-form");
|
const loginForm = document.querySelector("#login-form");
|
||||||
const loginError = document.querySelector("#login-error");
|
const loginError = document.querySelector("#login-error");
|
||||||
|
const togglePassword = document.querySelector("#toggle-password");
|
||||||
|
const usernameInput = document.querySelector("#username");
|
||||||
|
const passwordInput = document.querySelector("#password");
|
||||||
const messages = document.querySelector("#messages");
|
const messages = document.querySelector("#messages");
|
||||||
const chatForm = document.querySelector("#chat-form");
|
const chatForm = document.querySelector("#chat-form");
|
||||||
const messageInput = document.querySelector("#message");
|
const messageInput = document.querySelector("#message");
|
||||||
const sendButton = document.querySelector("#send");
|
const sendButton = document.querySelector("#send");
|
||||||
const logoutButton = document.querySelector("#logout");
|
const logoutButton = document.querySelector("#logout");
|
||||||
|
const clearHistoryButton = document.querySelector("#clear-history");
|
||||||
const activeFocus = document.querySelector("#active-focus");
|
const activeFocus = document.querySelector("#active-focus");
|
||||||
const todayList = document.querySelector("#today-list");
|
const todayList = document.querySelector("#today-list");
|
||||||
|
const todaySubtitle = document.querySelector("#today-subtitle");
|
||||||
const refreshToday = document.querySelector("#refresh-today");
|
const refreshToday = document.querySelector("#refresh-today");
|
||||||
const historyList = document.querySelector("#history-list");
|
const historyList = document.querySelector("#history-list");
|
||||||
const navTabs = Array.from(document.querySelectorAll(".nav-tab"));
|
const navTabs = Array.from(document.querySelectorAll(".nav-tab"));
|
||||||
|
const statusPill = document.querySelector("#connection-state");
|
||||||
|
const statusBar = document.querySelector("#status-bar");
|
||||||
|
const composerError = document.querySelector("#composer-error");
|
||||||
|
|
||||||
let token = sessionStorage.getItem("domovoy.chat.token") || "";
|
const SESSION_KEY = "domovoy.chat.token";
|
||||||
let conversationID = sessionStorage.getItem("domovoy.chat.conversation") || "";
|
const CONVERSATION_KEY = "domovoy.chat.conversation";
|
||||||
|
const SECTION_KEY = "domovoy.chat.section";
|
||||||
|
|
||||||
|
let token = sessionStorage.getItem(SESSION_KEY) || "";
|
||||||
|
let conversationID = sessionStorage.getItem(CONVERSATION_KEY) || "";
|
||||||
let localHistory = [];
|
let localHistory = [];
|
||||||
|
let todayRequestInFlight = false;
|
||||||
|
|
||||||
|
function setConnectionState(text, tone = "neutral") {
|
||||||
|
if (!statusPill) return;
|
||||||
|
statusPill.textContent = text;
|
||||||
|
if (tone === "bad") {
|
||||||
|
statusPill.style.borderColor = "rgba(216, 141, 120, .6)";
|
||||||
|
statusPill.style.color = "var(--bad)";
|
||||||
|
} else {
|
||||||
|
statusPill.style.borderColor = "var(--line)";
|
||||||
|
statusPill.style.color = "var(--muted)";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function showToast(message) {
|
||||||
|
if (!statusBar) return;
|
||||||
|
statusBar.textContent = message;
|
||||||
|
statusBar.classList.add("visible");
|
||||||
|
clearTimeout(showToast._timer);
|
||||||
|
showToast._timer = setTimeout(() => {
|
||||||
|
statusBar.classList.remove("visible");
|
||||||
|
}, 2800);
|
||||||
|
}
|
||||||
|
|
||||||
|
function showComposerError(message) {
|
||||||
|
if (!composerError) return;
|
||||||
|
composerError.textContent = message;
|
||||||
|
composerError.classList.add("show");
|
||||||
|
clearTimeout(showComposerError._timer);
|
||||||
|
showComposerError._timer = setTimeout(() => {
|
||||||
|
composerError.classList.remove("show");
|
||||||
|
}, 2600);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTime(value = new Date()) {
|
||||||
|
return new Intl.DateTimeFormat("ru-RU", {
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
second: "2-digit",
|
||||||
|
}).format(value);
|
||||||
|
}
|
||||||
|
|
||||||
function showChat() {
|
function showChat() {
|
||||||
|
setConnectionState("Сессия активна");
|
||||||
loginView.hidden = true;
|
loginView.hidden = true;
|
||||||
chatView.hidden = false;
|
chatView.hidden = false;
|
||||||
|
|
||||||
if (!messages.children.length) {
|
if (!messages.children.length) {
|
||||||
appendMessage("assistant", "Я рядом. Напишите обычное сообщение, без внутренних идентификаторов.");
|
appendMessage("assistant", "Я рядом. Пишите просто и по-человечески, я всё пойму.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const storedSection = localStorage.getItem(SECTION_KEY);
|
||||||
|
activateTab(storedSection === "today-panel" || storedSection === "history-panel" ? storedSection : "chat-panel");
|
||||||
messageInput.focus();
|
messageInput.focus();
|
||||||
}
|
}
|
||||||
|
|
||||||
function showLogin() {
|
function showLogin() {
|
||||||
|
setConnectionState("Вход не выполнен", "bad");
|
||||||
chatView.hidden = true;
|
chatView.hidden = true;
|
||||||
loginView.hidden = false;
|
loginView.hidden = false;
|
||||||
|
usernameInput?.focus();
|
||||||
}
|
}
|
||||||
|
|
||||||
function appendMessage(kind, text, meta = "") {
|
function endSession(message = "Сессия завершена") {
|
||||||
const node = document.createElement("div");
|
token = "";
|
||||||
node.className = `message ${kind}`;
|
conversationID = "";
|
||||||
node.textContent = text;
|
sessionStorage.removeItem(SESSION_KEY);
|
||||||
if (meta) {
|
sessionStorage.removeItem(CONVERSATION_KEY);
|
||||||
const small = document.createElement("small");
|
messages.replaceChildren();
|
||||||
small.textContent = meta;
|
localHistory = [];
|
||||||
node.appendChild(small);
|
updateActiveFocus("");
|
||||||
}
|
setConnectionState("Вход не выполнен", "bad");
|
||||||
messages.appendChild(node);
|
showToast(message);
|
||||||
messages.scrollTop = messages.scrollHeight;
|
showLogin();
|
||||||
localHistory.push({kind, text, meta, at: new Date()});
|
|
||||||
renderHistory();
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateActiveFocus(value, provenance = "") {
|
|
||||||
if (!activeFocus) return;
|
|
||||||
activeFocus.textContent = value ? `Сейчас обсуждаем: ${value}` : "";
|
|
||||||
activeFocus.hidden = !value;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function api(path, options = {}) {
|
async function api(path, options = {}) {
|
||||||
const headers = {"Content-Type": "application/json", ...(options.headers || {})};
|
const headers = new Headers(options.headers || {});
|
||||||
if (token) headers.Authorization = `Bearer ${token}`;
|
if (token) headers.set("Authorization", `Bearer ${token}`);
|
||||||
|
if (!headers.has("Content-Type")) {
|
||||||
|
headers.set("Content-Type", "application/json");
|
||||||
|
}
|
||||||
|
|
||||||
const response = await fetch(path, { ...options, headers });
|
const response = await fetch(path, { ...options, headers });
|
||||||
if (!response.ok) throw new Error(await response.text());
|
|
||||||
|
if (response.status === 401 && path !== "/api/session") {
|
||||||
|
endSession("Сессия просрочена, войдите снова");
|
||||||
|
throw new Error("Требуется авторизация");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const detail = (await response.text()).trim();
|
||||||
|
throw new Error(detail || `Ошибка ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
return response.json();
|
return response.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function showError(message) {
|
||||||
|
showComposerError(message || "Произошла ошибка");
|
||||||
|
}
|
||||||
|
|
||||||
|
function appendMessage(kind, text, meta = "") {
|
||||||
|
const node = document.createElement("article");
|
||||||
|
node.className = `message ${kind}`;
|
||||||
|
|
||||||
|
const who = document.createElement("strong");
|
||||||
|
who.className = "message-author";
|
||||||
|
who.textContent = kind === "user" ? "Ты" : "Домовой";
|
||||||
|
|
||||||
|
const body = document.createElement("p");
|
||||||
|
body.textContent = text;
|
||||||
|
|
||||||
|
node.append(who, body);
|
||||||
|
|
||||||
|
if (meta) {
|
||||||
|
const metaNode = document.createElement("small");
|
||||||
|
metaNode.textContent = meta;
|
||||||
|
node.appendChild(metaNode);
|
||||||
|
}
|
||||||
|
|
||||||
|
const when = document.createElement("time");
|
||||||
|
when.className = "message-time";
|
||||||
|
when.textContent = formatTime();
|
||||||
|
node.appendChild(when);
|
||||||
|
|
||||||
|
messages.appendChild(node);
|
||||||
|
messages.scrollTop = messages.scrollHeight;
|
||||||
|
|
||||||
|
localHistory.push({
|
||||||
|
kind,
|
||||||
|
text,
|
||||||
|
meta,
|
||||||
|
at: new Date(),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (localHistory.length > 120) {
|
||||||
|
localHistory = localHistory.slice(-120);
|
||||||
|
}
|
||||||
|
|
||||||
|
renderHistory();
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateActiveFocus(value) {
|
||||||
|
if (!activeFocus) return;
|
||||||
|
if (value) {
|
||||||
|
activeFocus.textContent = `Сейчас обсуждаем: ${value}`;
|
||||||
|
activeFocus.hidden = false;
|
||||||
|
} else {
|
||||||
|
activeFocus.hidden = true;
|
||||||
|
activeFocus.textContent = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function humanMeta(result) {
|
function humanMeta(result) {
|
||||||
if (result.reminder_scheduled) return "Напоминание сохранено. Я вернусь к нему сам.";
|
if (result.reminder_scheduled) {
|
||||||
if (result.delegation_id && result.delegation_state) return `Передал в coding-agent: ${humanDelegationState(result.delegation_state)}.`;
|
return "Я зафиксировал напоминание и сообщу, когда наступит время.";
|
||||||
if (result.capability_status && result.capability_status !== "AVAILABLE") return "Возможность пока не подключена.";
|
}
|
||||||
if (result.work_planned) return "Я разложил это как работу.";
|
if (result.delegation_id && result.delegation_state) {
|
||||||
|
return `Передал дальше: ${humanDelegationState(result.delegation_state)}.`;
|
||||||
|
}
|
||||||
|
if (result.capability_status && result.capability_status !== "AVAILABLE") {
|
||||||
|
return "Эта задача сейчас проверяется отдельно.";
|
||||||
|
}
|
||||||
|
if (result.work_planned) {
|
||||||
|
return "Я взял задачу в работу и отслежу статус.";
|
||||||
|
}
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
function humanDelegationState(state) {
|
function humanDelegationState(state) {
|
||||||
switch (state) {
|
switch (state) {
|
||||||
case "RUNNING":
|
case "RUNNING":
|
||||||
return "работа запущена";
|
return "выполняется";
|
||||||
case "WAITING":
|
case "WAITING":
|
||||||
return "ожидаю следующий шаг";
|
return "ожидает следующего шага";
|
||||||
case "BLOCKED":
|
case "BLOCKED":
|
||||||
return "нужно решение человека";
|
return "нужен человеческий выбор";
|
||||||
case "VERIFYING":
|
case "VERIFYING":
|
||||||
return "результат проверяется";
|
return "результат на проверке";
|
||||||
case "COMPLETED":
|
case "COMPLETED":
|
||||||
return "работа завершена";
|
return "готово";
|
||||||
case "FAILED":
|
case "FAILED":
|
||||||
return "run завершился ошибкой";
|
return "завершилось ошибкой";
|
||||||
default:
|
default:
|
||||||
return state.toLowerCase();
|
return String(state || "обрабатывается").toLowerCase();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderHistory() {
|
function renderHistory() {
|
||||||
if (!historyList) return;
|
if (!historyList) return;
|
||||||
|
|
||||||
historyList.replaceChildren();
|
historyList.replaceChildren();
|
||||||
const items = localHistory.slice(-30).reverse();
|
const items = localHistory.slice(-50).slice().reverse();
|
||||||
|
|
||||||
if (!items.length) {
|
if (!items.length) {
|
||||||
const empty = document.createElement("p");
|
const empty = document.createElement("p");
|
||||||
empty.className = "empty-state";
|
empty.className = "empty-state";
|
||||||
empty.textContent = "История появится после сообщений в этом окне.";
|
empty.textContent = "История появится после первых сообщений в этом окне.";
|
||||||
historyList.appendChild(empty);
|
historyList.appendChild(empty);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for (const item of items) {
|
|
||||||
|
items.forEach((item) => {
|
||||||
const row = document.createElement("article");
|
const row = document.createElement("article");
|
||||||
row.className = `history-item ${item.kind}`;
|
row.className = "history-item";
|
||||||
const title = document.createElement("strong");
|
|
||||||
title.textContent = item.kind === "user" ? "Вы" : "Домовой";
|
const who = document.createElement("strong");
|
||||||
|
who.className = "message-kind";
|
||||||
|
who.textContent = item.kind === "user" ? "Ты" : "Домовой";
|
||||||
|
|
||||||
const body = document.createElement("p");
|
const body = document.createElement("p");
|
||||||
body.textContent = item.text;
|
body.textContent = item.text;
|
||||||
const time = document.createElement("span");
|
|
||||||
time.textContent = item.at.toLocaleTimeString("ru-RU", {hour: "2-digit", minute: "2-digit"});
|
const footer = document.createElement("div");
|
||||||
row.append(title, body, time);
|
footer.className = "history-meta";
|
||||||
|
const time = document.createElement("time");
|
||||||
|
time.textContent = formatTime(item.at);
|
||||||
|
const meta = document.createElement("span");
|
||||||
|
meta.textContent = item.meta || "";
|
||||||
|
footer.append(time, meta);
|
||||||
|
|
||||||
|
row.append(who, body, footer);
|
||||||
historyList.appendChild(row);
|
historyList.appendChild(row);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function createTodayCard(item) {
|
||||||
|
const card = document.createElement("article");
|
||||||
|
card.className = "attention-card";
|
||||||
|
|
||||||
|
const title = document.createElement("h3");
|
||||||
|
const when = document.createElement("time");
|
||||||
|
const state = document.createElement("p");
|
||||||
|
const source = document.createElement("p");
|
||||||
|
const hint = document.createElement("p");
|
||||||
|
const actions = document.createElement("div");
|
||||||
|
|
||||||
|
const stamp = item.WhenUnixMillis || item.when_unix_millis || 0;
|
||||||
|
when.textContent = stamp
|
||||||
|
? new Date(stamp).toLocaleString("ru-RU", {
|
||||||
|
day: "2-digit",
|
||||||
|
month: "2-digit",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
})
|
||||||
|
: "текущий момент";
|
||||||
|
when.className = "muted";
|
||||||
|
|
||||||
|
title.textContent = item.Title || item.title || "Событие";
|
||||||
|
state.textContent = item.HumanState || item.human_state || "ожидает внимания";
|
||||||
|
state.className = "muted";
|
||||||
|
|
||||||
|
const sourceText = [
|
||||||
|
item.SourceDescription || item.source_description,
|
||||||
|
item.DeliveryState || item.delivery_state,
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(" · ");
|
||||||
|
source.textContent = sourceText || "Источник не задан";
|
||||||
|
source.className = "muted";
|
||||||
|
|
||||||
|
const hintText = item.ResponseHint || item.response_hint || "";
|
||||||
|
if (hintText) {
|
||||||
|
hint.textContent = hintText;
|
||||||
|
}
|
||||||
|
|
||||||
|
actions.className = "attention-actions";
|
||||||
|
|
||||||
|
const quick = [
|
||||||
|
{ label: "Готово", text: "Готово", tone: "primary" },
|
||||||
|
{ label: "Позже", text: "Отложи на 10 минут" },
|
||||||
|
{ label: "Отменить", text: "Отмени" },
|
||||||
|
];
|
||||||
|
|
||||||
|
quick.forEach((action) => {
|
||||||
|
const actionButton = document.createElement("button");
|
||||||
|
actionButton.type = "button";
|
||||||
|
actionButton.className = `ghost-button ${action.tone || ""}`.trim();
|
||||||
|
actionButton.textContent = action.label;
|
||||||
|
|
||||||
|
actionButton.addEventListener("click", async () => {
|
||||||
|
const previous = actionButton.textContent;
|
||||||
|
actionButton.disabled = true;
|
||||||
|
actionButton.textContent = "Отправляю…";
|
||||||
|
try {
|
||||||
|
await sendChatMessage(action.text, { silentUser: false });
|
||||||
|
await loadToday();
|
||||||
|
activateTab("chat-panel");
|
||||||
|
} finally {
|
||||||
|
actionButton.disabled = false;
|
||||||
|
actionButton.textContent = previous;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
actions.appendChild(actionButton);
|
||||||
|
});
|
||||||
|
|
||||||
|
card.append(title, when, state, source);
|
||||||
|
if (hintText) card.append(hint);
|
||||||
|
card.append(actions);
|
||||||
|
|
||||||
|
return card;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderTodayEmpty(message) {
|
||||||
|
const empty = document.createElement("p");
|
||||||
|
empty.className = "empty-state";
|
||||||
|
empty.textContent = message;
|
||||||
|
todayList.appendChild(empty);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadToday() {
|
async function loadToday() {
|
||||||
if (!todayList || !token) return;
|
if (!todayList || todayRequestInFlight) return;
|
||||||
|
|
||||||
|
todayRequestInFlight = true;
|
||||||
todayList.replaceChildren();
|
todayList.replaceChildren();
|
||||||
const loading = document.createElement("p");
|
renderTodayEmpty("Собираю актуальные напоминания…");
|
||||||
loading.className = "empty-state";
|
|
||||||
loading.textContent = "Смотрю, что требует внимания...";
|
|
||||||
todayList.appendChild(loading);
|
|
||||||
try {
|
try {
|
||||||
const result = await api("/api/today", { method: "GET" });
|
const result = await api("/api/today", { method: "GET" });
|
||||||
todayList.replaceChildren();
|
|
||||||
const items = result.Items || result.items || [];
|
const items = result.Items || result.items || [];
|
||||||
|
|
||||||
|
todayList.replaceChildren();
|
||||||
|
|
||||||
if (!items.length) {
|
if (!items.length) {
|
||||||
const empty = document.createElement("p");
|
todaySubtitle.textContent = "Сейчас спокойный период. Нечего тревожного";
|
||||||
empty.className = "empty-state";
|
renderTodayEmpty("Сейчас ничего срочного не требует внимания.");
|
||||||
empty.textContent = "Сейчас ничего срочного не требует внимания.";
|
|
||||||
todayList.appendChild(empty);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
todaySubtitle.textContent = `Найдено записей: ${items.length}`;
|
||||||
|
|
||||||
for (const item of items) {
|
for (const item of items) {
|
||||||
const card = document.createElement("article");
|
todayList.appendChild(createTodayCard(item));
|
||||||
card.className = "attention-card";
|
|
||||||
const when = document.createElement("time");
|
|
||||||
const stamp = item.WhenUnixMillis || item.when_unix_millis || 0;
|
|
||||||
when.textContent = stamp ? new Date(stamp).toLocaleString("ru-RU", {day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit"}) : "сейчас";
|
|
||||||
const title = document.createElement("h2");
|
|
||||||
title.textContent = item.Title || item.title || "Событие Домового";
|
|
||||||
const state = document.createElement("p");
|
|
||||||
state.textContent = item.HumanState || item.human_state || "ожидает внимания";
|
|
||||||
const source = document.createElement("small");
|
|
||||||
source.textContent = [item.SourceDescription || item.source_description, item.DeliveryState || item.delivery_state].filter(Boolean).join(" · ");
|
|
||||||
const hintText = item.ResponseHint || item.response_hint || "";
|
|
||||||
const actions = document.createElement("div");
|
|
||||||
actions.className = "attention-actions";
|
|
||||||
for (const [label, text] of [["Готово", "Готово"], ["Отложить", "Отложи на 10 минут"], ["Отменить", "Отмени"]]) {
|
|
||||||
const button = document.createElement("button");
|
|
||||||
button.type = "button";
|
|
||||||
button.textContent = label;
|
|
||||||
button.addEventListener("click", async () => {
|
|
||||||
await sendChatMessage(text, {silentUser: false});
|
|
||||||
await loadToday();
|
|
||||||
activateTab("chat-panel");
|
|
||||||
});
|
|
||||||
actions.appendChild(button);
|
|
||||||
}
|
}
|
||||||
if (hintText) {
|
} catch (error) {
|
||||||
const hint = document.createElement("small");
|
|
||||||
hint.textContent = hintText;
|
|
||||||
card.append(when, title, state, source, hint, actions);
|
|
||||||
} else {
|
|
||||||
card.append(when, title, state, source, actions);
|
|
||||||
}
|
|
||||||
todayList.appendChild(card);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
todayList.replaceChildren();
|
todayList.replaceChildren();
|
||||||
const error = document.createElement("p");
|
const err = document.createElement("p");
|
||||||
error.className = "empty-state error";
|
err.className = "empty-state error";
|
||||||
error.textContent = "Внимание сейчас недоступно. Чат можно продолжать.";
|
err.textContent = error.message || "Сегодня недоступен на мгновение.";
|
||||||
todayList.appendChild(error);
|
todayList.appendChild(err);
|
||||||
|
todaySubtitle.textContent = "Не удалось обновить список.";
|
||||||
|
} finally {
|
||||||
|
todayRequestInFlight = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function sendChatMessage(text, options = {}) {
|
async function sendChatMessage(text, options = {}) {
|
||||||
const clean = text.trim();
|
const clean = text.trim();
|
||||||
if (!clean) return;
|
if (!clean) return;
|
||||||
if (!options.silentUser) appendMessage("user", clean);
|
|
||||||
|
if (!options.silentUser) {
|
||||||
|
appendMessage("user", clean);
|
||||||
|
}
|
||||||
|
|
||||||
sendButton.disabled = true;
|
sendButton.disabled = true;
|
||||||
|
messageInput.disabled = true;
|
||||||
|
const originalLabel = sendButton.textContent;
|
||||||
|
sendButton.textContent = "Отправляю…";
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await api("/api/chat/messages", {method: "POST", body: JSON.stringify({conversation_id: conversationID, message: clean})});
|
const result = await api("/api/chat/messages", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({
|
||||||
|
conversation_id: conversationID,
|
||||||
|
message: clean,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
conversationID = result.conversation_id;
|
conversationID = result.conversation_id;
|
||||||
sessionStorage.setItem("domovoy.chat.conversation", conversationID);
|
if (conversationID) {
|
||||||
updateActiveFocus(result.active_focus, result.project_provenance);
|
sessionStorage.setItem(CONVERSATION_KEY, conversationID);
|
||||||
appendMessage("assistant", result.reply_text || "Сообщение записано.", humanMeta(result));
|
}
|
||||||
|
|
||||||
|
updateActiveFocus(result.active_focus);
|
||||||
|
appendMessage("assistant", result.reply_text || "Принял тебя. Подготовлю ответ.", humanMeta(result));
|
||||||
|
|
||||||
if (/что сейчас требует моего внимания/i.test(clean)) {
|
if (/что сейчас требует моего внимания/i.test(clean)) {
|
||||||
await loadToday();
|
await loadToday();
|
||||||
activateTab("today-panel");
|
activateTab("today-panel");
|
||||||
}
|
}
|
||||||
} catch {
|
|
||||||
appendMessage("assistant", "Чат сейчас недоступен. Сообщение не принято runtime.");
|
showToast("Сообщение отправлено");
|
||||||
|
} catch (error) {
|
||||||
|
appendMessage("assistant", "Я не могу отправить сообщение в этот момент. Проверьте сеть и авторизацию.");
|
||||||
|
showError(error.message);
|
||||||
} finally {
|
} finally {
|
||||||
sendButton.disabled = false;
|
sendButton.disabled = false;
|
||||||
|
sendButton.textContent = originalLabel;
|
||||||
|
messageInput.disabled = false;
|
||||||
|
if (!options.silentUser) {
|
||||||
messageInput.focus();
|
messageInput.focus();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function activateTab(panelID) {
|
function activateTab(panelID) {
|
||||||
for (const tab of navTabs) tab.classList.toggle("active", tab.dataset.tab === panelID);
|
let activeSet = false;
|
||||||
for (const panel of document.querySelectorAll(".surface-panel")) {
|
navTabs.forEach((tab) => {
|
||||||
|
const isActive = tab.dataset.tab === panelID;
|
||||||
|
tab.classList.toggle("active", isActive);
|
||||||
|
tab.setAttribute("aria-selected", String(isActive));
|
||||||
|
tab.tabIndex = isActive ? 0 : -1;
|
||||||
|
if (isActive) activeSet = true;
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelectorAll(".surface-panel").forEach((panel) => {
|
||||||
const active = panel.id === panelID;
|
const active = panel.id === panelID;
|
||||||
panel.hidden = !active;
|
panel.hidden = !active;
|
||||||
panel.classList.toggle("active-panel", active);
|
panel.classList.toggle("active-panel", active);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!activeSet) return;
|
||||||
|
|
||||||
|
localStorage.setItem(SECTION_KEY, panelID);
|
||||||
|
|
||||||
|
if (panelID === "today-panel") {
|
||||||
|
loadToday();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (panelID === "history-panel") {
|
||||||
|
renderHistory();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function navigateTabs(event) {
|
||||||
|
const current = navTabs.findIndex((tab) => tab.classList.contains("active"));
|
||||||
|
if (current === -1) return;
|
||||||
|
|
||||||
|
if (event.key === "ArrowLeft") {
|
||||||
|
event.preventDefault();
|
||||||
|
const index = (current - 1 + navTabs.length) % navTabs.length;
|
||||||
|
activateTab(navTabs[index].dataset.tab);
|
||||||
|
navTabs[index].focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (event.key === "ArrowRight") {
|
||||||
|
event.preventDefault();
|
||||||
|
const index = (current + 1) % navTabs.length;
|
||||||
|
activateTab(navTabs[index].dataset.tab);
|
||||||
|
navTabs[index].focus();
|
||||||
}
|
}
|
||||||
if (panelID === "today-panel") loadToday();
|
|
||||||
if (panelID === "history-panel") renderHistory();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
loginForm.addEventListener("submit", async (event) => {
|
loginForm.addEventListener("submit", async (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
|
const username = usernameInput.value.trim();
|
||||||
|
const password = passwordInput.value;
|
||||||
|
const loginButton = document.querySelector("#login-button");
|
||||||
|
|
||||||
loginError.textContent = "";
|
loginError.textContent = "";
|
||||||
const username = document.querySelector("#username").value;
|
loginButton.disabled = true;
|
||||||
const password = document.querySelector("#password").value;
|
loginButton.textContent = "Проверяю…";
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await api("/api/session", {method: "POST", body: JSON.stringify({username, password})});
|
const result = await api("/api/session", {
|
||||||
token = result.Token || result.token;
|
method: "POST",
|
||||||
sessionStorage.setItem("domovoy.chat.token", token);
|
body: JSON.stringify({ username, password }),
|
||||||
|
});
|
||||||
|
|
||||||
|
token = result.Token || result.token || "";
|
||||||
|
if (!token) {
|
||||||
|
throw new Error("Пустой токен");
|
||||||
|
}
|
||||||
|
|
||||||
|
sessionStorage.setItem(SESSION_KEY, token);
|
||||||
|
conversationID = "";
|
||||||
|
sessionStorage.removeItem(CONVERSATION_KEY);
|
||||||
showChat();
|
showChat();
|
||||||
} catch {
|
} catch {
|
||||||
loginError.textContent = "Вход не выполнен";
|
loginError.textContent = "Не удалось войти. Проверьте логин и пароль.";
|
||||||
|
showToast("Не удалось войти");
|
||||||
|
} finally {
|
||||||
|
loginButton.disabled = false;
|
||||||
|
loginButton.textContent = "Открыть чат";
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
togglePassword?.addEventListener("click", () => {
|
||||||
|
const isPassword = passwordInput.type === "password";
|
||||||
|
passwordInput.type = isPassword ? "text" : "password";
|
||||||
|
togglePassword.textContent = isPassword ? "скрыть" : "показать";
|
||||||
|
togglePassword.setAttribute("aria-label", isPassword ? "Скрыть пароль" : "Показать пароль");
|
||||||
|
});
|
||||||
|
|
||||||
chatForm.addEventListener("submit", async (event) => {
|
chatForm.addEventListener("submit", async (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
const text = messageInput.value.trim();
|
const text = messageInput.value.trim();
|
||||||
@@ -231,20 +522,31 @@ chatForm.addEventListener("submit", async (event) => {
|
|||||||
await sendChatMessage(text);
|
await sendChatMessage(text);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
messageInput.addEventListener("keydown", (event) => {
|
||||||
|
if (event.key === "Enter" && !event.shiftKey) {
|
||||||
|
event.preventDefault();
|
||||||
|
chatForm.requestSubmit();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
for (const tab of navTabs) {
|
for (const tab of navTabs) {
|
||||||
tab.addEventListener("click", () => activateTab(tab.dataset.tab));
|
tab.addEventListener("click", () => {
|
||||||
|
activateTab(tab.dataset.tab);
|
||||||
|
});
|
||||||
|
tab.addEventListener("keydown", navigateTabs);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (refreshToday) refreshToday.addEventListener("click", loadToday);
|
refreshToday?.addEventListener("click", loadToday);
|
||||||
|
|
||||||
logoutButton.addEventListener("click", () => {
|
clearHistoryButton?.addEventListener("click", () => {
|
||||||
token = "";
|
localHistory = [];
|
||||||
conversationID = "";
|
|
||||||
sessionStorage.removeItem("domovoy.chat.token");
|
|
||||||
sessionStorage.removeItem("domovoy.chat.conversation");
|
|
||||||
messages.replaceChildren();
|
messages.replaceChildren();
|
||||||
updateActiveFocus("");
|
renderHistory();
|
||||||
showLogin();
|
showToast("История очищена");
|
||||||
|
});
|
||||||
|
|
||||||
|
logoutButton?.addEventListener("click", () => {
|
||||||
|
endSession("Вы вышли из сеанса");
|
||||||
});
|
});
|
||||||
|
|
||||||
if (token) {
|
if (token) {
|
||||||
|
|||||||
@@ -5,60 +5,101 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<meta name="color-scheme" content="dark">
|
<meta name="color-scheme" content="dark">
|
||||||
<meta name="theme-color" content="#101714">
|
<meta name="theme-color" content="#101714">
|
||||||
<title>Домовой - чат</title>
|
<title>Домовой — твой помощник</title>
|
||||||
<link rel="stylesheet" href="/assets/chat.css">
|
<link rel="stylesheet" href="/assets/chat.css">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main class="chat-shell">
|
<main class="assistant-shell">
|
||||||
<section id="login-view" class="login-panel">
|
<section id="login-view" class="auth-view">
|
||||||
<div class="brand-mark" aria-hidden="true">Д</div>
|
<div class="auth-card" aria-live="polite">
|
||||||
|
<div class="brand-block">
|
||||||
|
<span class="brand-mark" aria-hidden="true">Д</span>
|
||||||
|
<div>
|
||||||
|
<p class="brand-kicker">личный диалог</p>
|
||||||
<h1>Домовой</h1>
|
<h1>Домовой</h1>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p class="auth-copy">Войдите, чтобы открыть спокойный чат с вашим помощником.</p>
|
||||||
<form id="login-form" class="login-form">
|
<form id="login-form" class="login-form">
|
||||||
<label for="username">Логин</label>
|
<label for="username">Логин</label>
|
||||||
<input id="username" autocomplete="username" required autofocus>
|
<input id="username" autocomplete="username" required autofocus>
|
||||||
<label for="password">Пароль</label>
|
<label for="password">Пароль</label>
|
||||||
|
<div class="input-with-action">
|
||||||
<input id="password" type="password" autocomplete="current-password" required>
|
<input id="password" type="password" autocomplete="current-password" required>
|
||||||
<button type="submit">Войти</button>
|
<button id="toggle-password" class="icon-button" type="button" aria-label="Показать пароль">показать</button>
|
||||||
|
</div>
|
||||||
|
<button id="login-button" type="submit">Открыть чат</button>
|
||||||
<p id="login-error" role="alert"></p>
|
<p id="login-error" role="alert"></p>
|
||||||
</form>
|
</form>
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section id="chat-view" class="chat-view" hidden>
|
<section id="chat-view" class="chat-view" hidden>
|
||||||
<header class="chat-header">
|
<header class="assistant-header">
|
||||||
<a href="/chat" aria-label="Домовой">Домовой</a>
|
<div class="header-brand">
|
||||||
<nav class="human-nav" aria-label="Разделы Домового">
|
<span class="brand-mark" aria-hidden="true">Д</span>
|
||||||
<button class="nav-tab active" data-tab="chat-panel" type="button">Чат</button>
|
<div>
|
||||||
<button class="nav-tab" data-tab="today-panel" type="button">Сегодня</button>
|
<p class="brand-kicker">твой спокойный ассистент</p>
|
||||||
<button class="nav-tab" data-tab="history-panel" type="button">История</button>
|
<h1>Домовой</h1>
|
||||||
<a href="/" class="operator-link">Оператор</a>
|
</div>
|
||||||
</nav>
|
</div>
|
||||||
<span id="active-focus">фокус: не выбран</span>
|
<div class="session-state" aria-live="polite">
|
||||||
<span id="session-state">сессия активна</span>
|
<span id="connection-state" class="status-pill"></span>
|
||||||
<button id="logout" type="button" aria-label="Выйти">↗</button>
|
<button id="logout" class="ghost-button" type="button" aria-label="Выйти">Выйти</button>
|
||||||
|
</div>
|
||||||
</header>
|
</header>
|
||||||
<section id="chat-panel" class="surface-panel active-panel">
|
|
||||||
|
<nav class="human-nav" aria-label="Разделы Домового" role="tablist">
|
||||||
|
<button class="nav-tab active" data-tab="chat-panel" role="tab" aria-selected="true" aria-controls="chat-panel" id="tab-chat" type="button">Чат</button>
|
||||||
|
<button class="nav-tab" data-tab="today-panel" role="tab" aria-selected="false" aria-controls="today-panel" id="tab-today" type="button">Сегодня</button>
|
||||||
|
<button class="nav-tab" data-tab="history-panel" role="tab" aria-selected="false" aria-controls="history-panel" id="tab-history" type="button">История</button>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<section class="surface-panel active-panel" id="chat-panel" role="tabpanel" aria-labelledby="tab-chat">
|
||||||
|
<div class="panel-toolbar">
|
||||||
|
<div>
|
||||||
|
<h2>Чат</h2>
|
||||||
|
<p>Пишите обычные фразы. Я отвечу спокойно и по делу.</p>
|
||||||
|
</div>
|
||||||
|
<p id="active-focus" class="focus-chip" hidden></p>
|
||||||
|
</div>
|
||||||
<div id="messages" class="messages" aria-live="polite"></div>
|
<div id="messages" class="messages" aria-live="polite"></div>
|
||||||
<form id="chat-form" class="composer">
|
<form id="chat-form" class="composer">
|
||||||
<textarea id="message" rows="3" maxlength="16384" placeholder="Напишите Домовому обычное сообщение..." required></textarea>
|
<label class="visually-hidden" for="message">Ваше сообщение</label>
|
||||||
<button id="send" type="submit">Отправить</button>
|
<textarea id="message" rows="3" maxlength="16384" placeholder="Напишите, чем помочь" required></textarea>
|
||||||
|
<div class="composer-actions">
|
||||||
|
<button id="send" class="primary-button" type="submit">Отправить</button>
|
||||||
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</section>
|
</section>
|
||||||
<section id="today-panel" class="surface-panel attention-surface" hidden>
|
|
||||||
<div class="surface-heading">
|
<section id="today-panel" class="surface-panel attention-surface" hidden role="tabpanel" aria-labelledby="tab-today">
|
||||||
<p>Сегодня / внимание</p>
|
<div class="panel-toolbar">
|
||||||
<button id="refresh-today" type="button">Обновить</button>
|
<div>
|
||||||
|
<h2>Сегодня</h2>
|
||||||
|
<p id="today-subtitle">Что сейчас требует твоего внимания</p>
|
||||||
|
</div>
|
||||||
|
<button id="refresh-today" class="ghost-button" type="button">Обновить</button>
|
||||||
</div>
|
</div>
|
||||||
<div id="today-list" class="attention-list"></div>
|
<div id="today-list" class="attention-list"></div>
|
||||||
</section>
|
</section>
|
||||||
<section id="history-panel" class="surface-panel history-surface" hidden>
|
|
||||||
<div class="surface-heading">
|
<section id="history-panel" class="surface-panel history-surface" hidden role="tabpanel" aria-labelledby="tab-history">
|
||||||
<p>История</p>
|
<div class="panel-toolbar">
|
||||||
<span>Последние сообщения текущего окна</span>
|
<div>
|
||||||
|
<h2>История</h2>
|
||||||
|
<p>Сообщения текущего браузерного сеанса</p>
|
||||||
|
</div>
|
||||||
|
<button id="clear-history" class="ghost-button" type="button">Очистить</button>
|
||||||
</div>
|
</div>
|
||||||
<div id="history-list" class="history-list"></div>
|
<div id="history-list" class="history-list"></div>
|
||||||
</section>
|
</section>
|
||||||
</section>
|
</section>
|
||||||
|
<p id="status-bar" class="status-bar" aria-live="polite"></p>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
|
<div id="composer-error" class="composer-error" role="status" aria-live="polite"></div>
|
||||||
|
|
||||||
<script src="/assets/chat.js"></script>
|
<script src="/assets/chat.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -97,6 +97,54 @@ type ProviderUsage struct {
|
|||||||
OutputUnits int64
|
OutputUnits int64
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type InterpretationApplicability string
|
||||||
|
|
||||||
|
const (
|
||||||
|
InterpretationApplicable InterpretationApplicability = "APPLICABLE"
|
||||||
|
InterpretationLowConfidence InterpretationApplicability = "LOW_CONFIDENCE"
|
||||||
|
InterpretationMixedIntent InterpretationApplicability = "MIXED_INTENT"
|
||||||
|
InterpretationNeedsBroader InterpretationApplicability = "NEEDS_BROADER_INTERPRETATION"
|
||||||
|
InterpretationClarificationRequired InterpretationApplicability = "CLARIFICATION_REQUIRED"
|
||||||
|
)
|
||||||
|
|
||||||
|
type GatewayInterpretationRequest struct {
|
||||||
|
Version ContractVersion
|
||||||
|
RequestID RequestID
|
||||||
|
ActorID identity.ActorID
|
||||||
|
PrincipalID identity.PrincipalID
|
||||||
|
ScopeID authority.ScopeID
|
||||||
|
Message string
|
||||||
|
Locale string
|
||||||
|
MaxOutputBytes int
|
||||||
|
DataPolicy capability.DataPolicy
|
||||||
|
DeterministicSpeechAct string
|
||||||
|
DeterministicSecondary string
|
||||||
|
DeterministicConfidence int64
|
||||||
|
DeterministicApplicability InterpretationApplicability
|
||||||
|
RequestedOutcome string
|
||||||
|
ProjectNames []string
|
||||||
|
}
|
||||||
|
|
||||||
|
type GatewayInterpretationCandidate struct {
|
||||||
|
PrimarySpeechAct string `json:"primary_speech_act"`
|
||||||
|
SecondarySpeechAct string `json:"secondary_speech_act,omitempty"`
|
||||||
|
ConfidenceMillis int64 `json:"confidence_millis"`
|
||||||
|
Applicability InterpretationApplicability `json:"applicability"`
|
||||||
|
RequestedOutcome string `json:"requested_outcome,omitempty"`
|
||||||
|
NeedsCognition bool `json:"needs_cognition"`
|
||||||
|
Clarification string `json:"clarification"`
|
||||||
|
SelectionReason string `json:"selection_reason,omitempty"`
|
||||||
|
CapabilityHints []capability.CapabilityKind `json:"capability_hints,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GatewayInterpretationResponse struct {
|
||||||
|
Version ContractVersion
|
||||||
|
RequestID RequestID
|
||||||
|
Candidate GatewayInterpretationCandidate
|
||||||
|
FinishReason FinishReason
|
||||||
|
Usage *ProviderUsage
|
||||||
|
}
|
||||||
|
|
||||||
type AdvisoryResponse struct {
|
type AdvisoryResponse struct {
|
||||||
Version ContractVersion
|
Version ContractVersion
|
||||||
RequestID RequestID
|
RequestID RequestID
|
||||||
|
|||||||
@@ -17,9 +17,13 @@ type ConversationState string
|
|||||||
type InterpretationState string
|
type InterpretationState string
|
||||||
type InteractionRelationKind string
|
type InteractionRelationKind string
|
||||||
type InterpretationID string
|
type InterpretationID string
|
||||||
|
type SemanticCandidateID string
|
||||||
type ProjectReferenceID string
|
type ProjectReferenceID string
|
||||||
type ProjectReferenceRole string
|
type ProjectReferenceRole string
|
||||||
type ClarificationState string
|
type ClarificationState string
|
||||||
|
type SemanticApplicability string
|
||||||
|
type SemanticCandidateSource string
|
||||||
|
type SemanticCandidateSelectionState string
|
||||||
|
|
||||||
const (
|
const (
|
||||||
ChannelWebChat Channel = "WEB_CHAT"
|
ChannelWebChat Channel = "WEB_CHAT"
|
||||||
@@ -51,6 +55,16 @@ const (
|
|||||||
ProjectRoleReferenceSource ProjectReferenceRole = "REFERENCE_SOURCE"
|
ProjectRoleReferenceSource ProjectReferenceRole = "REFERENCE_SOURCE"
|
||||||
ClarificationNotRequired ClarificationState = "NOT_REQUIRED"
|
ClarificationNotRequired ClarificationState = "NOT_REQUIRED"
|
||||||
ClarificationRequired ClarificationState = "REQUIRED"
|
ClarificationRequired ClarificationState = "REQUIRED"
|
||||||
|
SemanticApplicable SemanticApplicability = "APPLICABLE"
|
||||||
|
SemanticLowConfidence SemanticApplicability = "LOW_CONFIDENCE"
|
||||||
|
SemanticMixedIntent SemanticApplicability = "MIXED_INTENT"
|
||||||
|
SemanticNeedsBroaderInterpret SemanticApplicability = "NEEDS_BROADER_INTERPRETATION"
|
||||||
|
SemanticCandidateClarify SemanticApplicability = "CLARIFICATION_REQUIRED"
|
||||||
|
CandidateSourceDeterministic SemanticCandidateSource = "DETERMINISTIC_V2"
|
||||||
|
CandidateSourceCognitive SemanticCandidateSource = "COGNITIVE_V1"
|
||||||
|
CandidateSelected SemanticCandidateSelectionState = "SELECTED"
|
||||||
|
CandidateObserved SemanticCandidateSelectionState = "OBSERVED"
|
||||||
|
CandidateRejected SemanticCandidateSelectionState = "REJECTED"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Conversation struct {
|
type Conversation struct {
|
||||||
@@ -94,11 +108,32 @@ type UtteranceInterpretation struct {
|
|||||||
ID InterpretationID
|
ID InterpretationID
|
||||||
UtteranceID HumanUtteranceID
|
UtteranceID HumanUtteranceID
|
||||||
SpeechAct SpeechAct
|
SpeechAct SpeechAct
|
||||||
|
SecondarySpeechAct SpeechAct
|
||||||
ConfidenceMillis int64
|
ConfidenceMillis int64
|
||||||
Source string
|
Source string
|
||||||
AssertionVerification string
|
AssertionVerification string
|
||||||
RequestedOutcome string
|
RequestedOutcome string
|
||||||
Clarification ClarificationState
|
Clarification ClarificationState
|
||||||
|
NeedsCognition bool
|
||||||
|
Applicability SemanticApplicability
|
||||||
|
SelectionReason string
|
||||||
|
RecordedAtUnixMillis int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type SemanticCandidate struct {
|
||||||
|
ID SemanticCandidateID
|
||||||
|
UtteranceID HumanUtteranceID
|
||||||
|
Source SemanticCandidateSource
|
||||||
|
SelectionState SemanticCandidateSelectionState
|
||||||
|
PrimarySpeechAct SpeechAct
|
||||||
|
SecondarySpeechAct SpeechAct
|
||||||
|
ConfidenceMillis int64
|
||||||
|
Applicability SemanticApplicability
|
||||||
|
RequestedOutcome string
|
||||||
|
Clarification ClarificationState
|
||||||
|
NeedsCognition bool
|
||||||
|
SelectionReason string
|
||||||
|
CapabilityHints []string
|
||||||
RecordedAtUnixMillis int64
|
RecordedAtUnixMillis int64
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -300,7 +300,11 @@ type PlanningInput struct {
|
|||||||
ProjectProvenance ProjectProvenanceRef
|
ProjectProvenance ProjectProvenanceRef
|
||||||
Message string
|
Message string
|
||||||
SpeechAct SpeechActRef
|
SpeechAct SpeechActRef
|
||||||
|
SecondarySpeechAct SpeechActRef
|
||||||
|
CapabilityHints []capability.CapabilityKind
|
||||||
AssertionVerification epistemics.VerificationState
|
AssertionVerification epistemics.VerificationState
|
||||||
|
NeedsCognition bool
|
||||||
|
RequiresClarification bool
|
||||||
ReceivedAtUnixMillis int64
|
ReceivedAtUnixMillis int64
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
BEGIN;
|
||||||
|
|
||||||
|
SET ROLE interaction_role;
|
||||||
|
|
||||||
|
ALTER TABLE interaction.utterance_interpretations
|
||||||
|
ADD COLUMN IF NOT EXISTS secondary_speech_act TEXT NOT NULL DEFAULT 'UNKNOWN',
|
||||||
|
ADD COLUMN IF NOT EXISTS needs_cognition BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
ADD COLUMN IF NOT EXISTS applicability TEXT NOT NULL DEFAULT 'APPLICABLE',
|
||||||
|
ADD COLUMN IF NOT EXISTS selection_reason TEXT NOT NULL DEFAULT '';
|
||||||
|
|
||||||
|
ALTER TABLE interaction.utterance_interpretations DROP CONSTRAINT IF EXISTS utterance_interpretations_secondary_speech_act_check;
|
||||||
|
ALTER TABLE interaction.utterance_interpretations
|
||||||
|
ADD CONSTRAINT utterance_interpretations_secondary_speech_act_check
|
||||||
|
CHECK (secondary_speech_act IN ('DIRECTIVE','ASSERTION','DECISION','PREFERENCE','QUESTION','HYPOTHESIS','CORRECTION','REQUEST_TO_INVESTIGATE','CONFIRMATION','REJECTION','CANCELLATION','CONVERSATIONAL','UNKNOWN'));
|
||||||
|
|
||||||
|
ALTER TABLE interaction.utterance_interpretations DROP CONSTRAINT IF EXISTS utterance_interpretations_applicability_check;
|
||||||
|
ALTER TABLE interaction.utterance_interpretations
|
||||||
|
ADD CONSTRAINT utterance_interpretations_applicability_check
|
||||||
|
CHECK (applicability IN ('APPLICABLE','LOW_CONFIDENCE','MIXED_INTENT','NEEDS_BROADER_INTERPRETATION','CLARIFICATION_REQUIRED'));
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS interaction.semantic_candidates (
|
||||||
|
candidate_id TEXT PRIMARY KEY,
|
||||||
|
utterance_id TEXT NOT NULL,
|
||||||
|
source TEXT NOT NULL,
|
||||||
|
selection_state TEXT NOT NULL,
|
||||||
|
primary_speech_act TEXT NOT NULL,
|
||||||
|
secondary_speech_act TEXT NOT NULL,
|
||||||
|
confidence_millis BIGINT NOT NULL,
|
||||||
|
applicability TEXT NOT NULL,
|
||||||
|
requested_outcome TEXT NOT NULL DEFAULT '',
|
||||||
|
clarification TEXT NOT NULL,
|
||||||
|
needs_cognition BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
selection_reason TEXT NOT NULL DEFAULT '',
|
||||||
|
recorded_at_unix_millis BIGINT NOT NULL,
|
||||||
|
CHECK (source IN ('DETERMINISTIC_V2','COGNITIVE_V1')),
|
||||||
|
CHECK (selection_state IN ('SELECTED','OBSERVED','REJECTED')),
|
||||||
|
CHECK (primary_speech_act IN ('DIRECTIVE','ASSERTION','DECISION','PREFERENCE','QUESTION','HYPOTHESIS','CORRECTION','REQUEST_TO_INVESTIGATE','CONFIRMATION','REJECTION','CANCELLATION','CONVERSATIONAL','UNKNOWN')),
|
||||||
|
CHECK (secondary_speech_act IN ('DIRECTIVE','ASSERTION','DECISION','PREFERENCE','QUESTION','HYPOTHESIS','CORRECTION','REQUEST_TO_INVESTIGATE','CONFIRMATION','REJECTION','CANCELLATION','CONVERSATIONAL','UNKNOWN')),
|
||||||
|
CHECK (confidence_millis BETWEEN 0 AND 1000),
|
||||||
|
CHECK (applicability IN ('APPLICABLE','LOW_CONFIDENCE','MIXED_INTENT','NEEDS_BROADER_INTERPRETATION','CLARIFICATION_REQUIRED')),
|
||||||
|
CHECK (clarification IN ('NOT_REQUIRED','REQUIRED'))
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS interaction.semantic_candidate_capability_hints (
|
||||||
|
candidate_id TEXT NOT NULL,
|
||||||
|
capability_kind TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (candidate_id, capability_kind),
|
||||||
|
CHECK (candidate_id <> ''),
|
||||||
|
CHECK (capability_kind <> '')
|
||||||
|
);
|
||||||
|
|
||||||
|
RESET ROLE;
|
||||||
|
|
||||||
|
COMMIT;
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"task_file": "dev/tasks/DEV-000071-cognitive-path-reality-generalization.json",
|
"task_file": "dev/tasks/DEV-000072-semantic-interpretation-deferral-boundary.json",
|
||||||
"task_id": "DEV-000071",
|
"task_id": "DEV-000072",
|
||||||
"task_revision": 1
|
"task_revision": 1
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000072",
|
||||||
|
"task_revision": 1,
|
||||||
|
"architecture_revision": "DEV-000071-baseline",
|
||||||
|
"base_repo_revision": "64870798b9a50f895c99d24441703f366df5c98a",
|
||||||
|
"risk_tier": "E",
|
||||||
|
"intent": "Implement semantic interpretation and deferral boundary V1 so deterministic interpretation acts as a fast-path candidate rather than unquestionable final truth; preserve provenance between deterministic and cognitive candidates; support mixed intent and safer deferral without activating new providers.",
|
||||||
|
"requirement_ids": [
|
||||||
|
"DEV-000071 measured baseline",
|
||||||
|
"Deterministic candidate can decline/defer",
|
||||||
|
"Mixed intent representation",
|
||||||
|
"Cognition may challenge uncertain deterministic candidate",
|
||||||
|
"No provider hardcoding",
|
||||||
|
"No Ollama activation",
|
||||||
|
"Known and holdout evaluation comparison",
|
||||||
|
"Production chat acceptance"
|
||||||
|
],
|
||||||
|
"allowed_change_scope": {
|
||||||
|
"modules": [
|
||||||
|
"interaction",
|
||||||
|
"work",
|
||||||
|
"capability",
|
||||||
|
"epistemics"
|
||||||
|
],
|
||||||
|
"paths": [
|
||||||
|
"contracts/interaction/**",
|
||||||
|
"contracts/work/**",
|
||||||
|
"contracts/cognitive/**",
|
||||||
|
"modules/interaction/**",
|
||||||
|
"modules/work/**",
|
||||||
|
"adapters/postgres/interaction_repository.go",
|
||||||
|
"cmd/core-runtime/**",
|
||||||
|
"cmd/creator-web/**",
|
||||||
|
"cmd/cognitive-worker/**",
|
||||||
|
"database/migrations/**",
|
||||||
|
"tests/**",
|
||||||
|
"docs/PROJECT_STATUS.md",
|
||||||
|
"docs/evidence/**",
|
||||||
|
"dev/ACTIVE_TASK.json",
|
||||||
|
"dev/tasks/DEV-000072-semantic-interpretation-deferral-boundary.json"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"forbidden_change_scope": {
|
||||||
|
"paths": [
|
||||||
|
"architecture/ARCHITECTURE_CONSTITUTION.md",
|
||||||
|
"architecture/architecture-registry.yaml",
|
||||||
|
"architecture/architecture-registry.json",
|
||||||
|
"architecture/adrs/**",
|
||||||
|
"security/**",
|
||||||
|
"modules/authority/**",
|
||||||
|
"modules/commit/**",
|
||||||
|
"deploy/**",
|
||||||
|
"ci/**",
|
||||||
|
".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": [
|
||||||
|
"contracts.identity",
|
||||||
|
"contracts.interaction",
|
||||||
|
"contracts.work",
|
||||||
|
"contracts.capability",
|
||||||
|
"contracts.cognitive",
|
||||||
|
"contracts.epistemics",
|
||||||
|
"contracts.situation"
|
||||||
|
],
|
||||||
|
"may_change": [
|
||||||
|
"contracts.interaction",
|
||||||
|
"contracts.work",
|
||||||
|
"contracts.cognitive"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"semantic_owner": "interaction",
|
||||||
|
"canonical_state": [
|
||||||
|
"Interaction-owned human utterance interpretation semantics",
|
||||||
|
"Interaction-owned interpretation provenance between deterministic and cognitive candidates",
|
||||||
|
"Owner-local persistence expansion for semantic candidate provenance",
|
||||||
|
"Existing Work planning/help-path semantics updated to consume richer interaction interpretation without changing canonical ownership"
|
||||||
|
],
|
||||||
|
"state_transitions": [
|
||||||
|
"human utterance -> deterministic semantic candidate",
|
||||||
|
"candidate accepted or deferred",
|
||||||
|
"deferred candidate -> cognitive candidate",
|
||||||
|
"candidate selection -> persisted selected interpretation + provenance",
|
||||||
|
"mixed/consequential ambiguity -> clarification or bounded safe response"
|
||||||
|
],
|
||||||
|
"side_effects_and_privileges": [
|
||||||
|
"No direct external mutation",
|
||||||
|
"Cognitive Gateway only through existing provider-neutral runtime",
|
||||||
|
"No direct CPU endpoint calls from chat path",
|
||||||
|
"No provider activation changes"
|
||||||
|
],
|
||||||
|
"persistence_and_migrations": [
|
||||||
|
"Interaction owner-local migration expected",
|
||||||
|
"No cross-owner SQL writes",
|
||||||
|
"No cross-owner FK introduction",
|
||||||
|
"No new DB owner roles"
|
||||||
|
],
|
||||||
|
"failure_retry_restart": [
|
||||||
|
"If cognition is unavailable, obvious deterministic paths continue to work",
|
||||||
|
"Uncertain consequential intent must fail closed via clarification or explicit limitation",
|
||||||
|
"Model output must remain typed candidate evidence, never direct canonical fact/action"
|
||||||
|
],
|
||||||
|
"assumptions": [
|
||||||
|
"Current production has only one proven eligible cognitive binding for human chat: CPU CANARY",
|
||||||
|
"Ollama/GPU remains inactive for routing in this milestone",
|
||||||
|
"DEV-000071 artifacts remain the baseline comparison set"
|
||||||
|
],
|
||||||
|
"acceptance_scenarios": [
|
||||||
|
"ask-model request no longer finalized as assertion by default",
|
||||||
|
"think/investigate wording can defer to cognition without lexical patching as the sole strategy",
|
||||||
|
"mixed investigate+modify retains both semantic needs",
|
||||||
|
"correction wording plus new directive preserves both aspects",
|
||||||
|
"uncertain consequential request defers safely",
|
||||||
|
"suite_v1 plus DEV-000071 development/holdout comparisons are reported honestly",
|
||||||
|
"production /chat acceptance covers greeting, cognition question, named implementation request, mixed work, correction, correction+new directive, consequential ambiguity"
|
||||||
|
],
|
||||||
|
"required_tests": [
|
||||||
|
"go test ./...",
|
||||||
|
"go vet ./...",
|
||||||
|
"go run ./cmd/devctl preflight -active dev/ACTIVE_TASK.json",
|
||||||
|
"go run ./cmd/devctl check-architecture",
|
||||||
|
"go run ./cmd/devctl check-diff -active dev/ACTIVE_TASK.json",
|
||||||
|
"tests/cognitive_advisory/cognitive_worker_env_policy_test.ps1",
|
||||||
|
"tests/owner_acl/verify.ps1 -DockerContext docker-prod -PostgresContainer assistant-postgres-1",
|
||||||
|
"interaction domain tests",
|
||||||
|
"work planning tests",
|
||||||
|
"reality evaluation comparisons",
|
||||||
|
"production /chat acceptance"
|
||||||
|
],
|
||||||
|
"terminal_gap_states": [
|
||||||
|
"BLOCKED_BY_SPEC_GAP",
|
||||||
|
"BLOCKED_BY_ARCHITECTURE_GAP",
|
||||||
|
"BLOCKED_BY_MISSING_CAPABILITY",
|
||||||
|
"BLOCKED_BY_CONFLICT",
|
||||||
|
"REQUIRES_MIGRATION_DECISION"
|
||||||
|
]
|
||||||
|
}
|
||||||
+22
-1
@@ -1,6 +1,27 @@
|
|||||||
# Assistant project status
|
# Assistant project status
|
||||||
|
|
||||||
Audit date: 2026-08-17. Active implementation: DEV-000071 revision 1.
|
Audit date: 2026-08-17. Active implementation: DEV-000072 revision 1.
|
||||||
|
|
||||||
|
## DEV-000072 checkpoint
|
||||||
|
|
||||||
|
- `DEV_000072_STATUS = LOCAL_ACCEPTANCE_PASS`
|
||||||
|
- `LAST_COMPLETED = semantic deferral boundary V1 implementation plus regression/generalization acceptance: deterministic semantic candidates, cognitive interpretation gateway path, owner-local candidate provenance persistence, mixed-intent planning input propagation, punctuation/metamorphic stability fixes, capability-gap/reminder/work-path repair, and live A/B/C trace evidence`
|
||||||
|
- `ARCHITECTURE_CHANGE = none; interaction owner remains unchanged and no new cross-owner dependency was accepted`
|
||||||
|
- `SEMANTIC_BOUNDARY_CHANGE = deterministic interpretation no longer acts as unquestionable final truth for low-confidence / broader-interpretation / mixed-intent cases; core runtime can request typed cognitive reinterpretation through the existing provider-neutral gateway`
|
||||||
|
- `PERSISTENCE_CHANGE = migration 027 adds secondary speech act / applicability / selection reason on interaction interpretations plus semantic candidate provenance tables`
|
||||||
|
- `GIT_ANCESTRY_STATUS = PASS: current branch merge-base equals origin/main at 64870798b9a50f895c99d24441703f366df5c98a; DEV-000071 commit c1aff60443829892ba70104f40b55de01f186a7f is contained in origin/main`
|
||||||
|
- `CHECK_DIFF_STATUS = PASS: diff scope checks OK for DEV-000072 against base 64870798b9a50f895c99d24441703f366df5c98a`
|
||||||
|
- `KNOWN_BASELINE_COMPARISON = suite_v1 baseline failed_available 4 / intent 0 / capability 3 / consequence 1 -> current failed_available 0 / intent 0 / capability 0 / consequence 0`
|
||||||
|
- `HOLDOUT_AND_GENERALIZATION_COMPARISON = suite_v2 baseline failed_available 18 / intent 3 / capability 7 / consequence 4 / unknown 7 -> current failed_available 0 / intent 0 / capability 0 / consequence 0 / unknown 0`
|
||||||
|
- `UNNECESSARY_COGNITION = no observed increase in suite_v1 or suite_v2 current-run`
|
||||||
|
- `UNNECESSARY_CLARIFICATION = current replay counts remain observable (suite_v1 1, suite_v2 5) and are recorded explicitly for operator review rather than hidden by aggregate PASS`
|
||||||
|
- `LIVE_TRACE_EVIDENCE = PASS: raw CPU Qwen understood "ты кто" and punctuation-free modal request; Domovoy semantic path now routes "ты кто" and "можешь расказать об утре" into cognition-worthy interpretation; gateway-to-same-CPU trace preserved question semantics`
|
||||||
|
- `METAMORPHIC_EVIDENCE = docs/evidence/semantic-deferral-metamorphic-evidence-2026-08-17-v1.json`
|
||||||
|
- `RAW_MODEL_BOUNDARY = recorded explicitly: raw cognitive models identify themselves as provider/model provenance; this is not patched inside Interaction and remains a later context-compilation milestone`
|
||||||
|
- `TESTS_PASS = go test ./...; go vet ./...; go run ./cmd/devctl preflight -active dev/ACTIVE_TASK.json; go run ./cmd/devctl check-architecture; go run ./cmd/devctl check-diff -active dev/ACTIVE_TASK.json; tests/cognitive_advisory/cognitive_worker_env_policy_test.ps1; tests/owner_acl/verify.ps1 -DockerContext docker-prod -PostgresContainer assistant-postgres-1; ASSISTANT_LIVE_SEMANTIC_TRACE=1 go test ./cmd/cognitive-worker -run TestLiveInterpretationTrace -v`
|
||||||
|
- `COGNITIVE_CONTEXT_GAP = still open by design in this milestone: raw providers identify themselves as Qwen/Gemma provenance when Domovoy identity/context is not compiled into the prompt`
|
||||||
|
- `PRODUCTION_STATUS = pending promotion/deploy from this checkpoint`
|
||||||
|
- `NEXT_RECOMMENDED_STEP = finish DEV-000072 production promotion, apply migration 027, redeploy runtime, and verify live /chat against the promoted artifact`
|
||||||
|
|
||||||
## DEV-000071 checkpoint
|
## DEV-000071 checkpoint
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
{
|
||||||
|
"artifact_id": "semantic-deferral-metamorphic-evidence-2026-08-17-v1",
|
||||||
|
"artifact_version": "semantic-deferral-metamorphic-evidence-v1",
|
||||||
|
"observed_at": "2026-08-17T21:10:00+03:00",
|
||||||
|
"task_id": "DEV-000072",
|
||||||
|
"focus": "semantic interpretation deferral boundary",
|
||||||
|
"metamorphic_claim": "Punctuation-free Russian interrogatives must not be finalized as human assertions solely because they lack '?'.",
|
||||||
|
"raw_model_evidence": [
|
||||||
|
{
|
||||||
|
"path": "RAW_CPU_QWEN_DIRECT",
|
||||||
|
"endpoint": "http://docker.cin.su:18082/",
|
||||||
|
"model_observed": "Qwen3 4B Instruct 2507",
|
||||||
|
"utterance": "ты кто",
|
||||||
|
"result": "understood as question"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "RAW_CPU_QWEN_DIRECT",
|
||||||
|
"endpoint": "http://docker.cin.su:18082/",
|
||||||
|
"model_observed": "Qwen3 4B Instruct 2507",
|
||||||
|
"utterance": "можешь рассказать об утре",
|
||||||
|
"result": "semantic interpretation/clarification rather than factual assertion"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "RAW_GPU_GEMMA4_DIRECT",
|
||||||
|
"endpoint": "http://192.168.220.91:11434",
|
||||||
|
"model_observed": "gemma4:26b",
|
||||||
|
"utterance": "ты кто",
|
||||||
|
"result": "understood as question"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "RAW_GPU_GEMMA4_DIRECT",
|
||||||
|
"endpoint": "http://192.168.220.91:11434",
|
||||||
|
"model_observed": "gemma4:26b",
|
||||||
|
"utterance": "можешь расказать об утре",
|
||||||
|
"result": "coherent Russian response to punctuation-free natural request"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"domovoy_boundary_evidence": {
|
||||||
|
"before_fix": [
|
||||||
|
{
|
||||||
|
"utterance": "ты кто",
|
||||||
|
"semantic_path": "ASSERTION",
|
||||||
|
"cognition_requested": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"utterance": "ты кто?",
|
||||||
|
"semantic_path": "QUESTION",
|
||||||
|
"cognition_requested": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"interpretation": "The failure localizes to Domovoy's pre-cognition semantic path rather than to inability of either tested model to understand punctuation-free Russian."
|
||||||
|
},
|
||||||
|
"non_goal_evidence": {
|
||||||
|
"raw_model_identity_behavior": [
|
||||||
|
"Qwen identifies itself as Qwen/Alibaba and may invent a local name",
|
||||||
|
"Gemma identifies itself as a Google model"
|
||||||
|
],
|
||||||
|
"interpretation": "This is raw-model provenance behavior, not Domovoy identity semantics, and must not be patched inside Interaction with hardcoded response handlers."
|
||||||
|
},
|
||||||
|
"next_required_boundary": "After semantic deferral is corrected, a later milestone must inspect Domovoy's compiled context/system representation supplied to cognition without forcing the model to pretend it is Domovoy."
|
||||||
|
}
|
||||||
@@ -58,7 +58,8 @@ func NewHumanUtterance(conversation interaction.Conversation, request interactio
|
|||||||
return interaction.HumanUtterance{}, interaction.OriginalHumanIntent{}, nil, err
|
return interaction.HumanUtterance{}, interaction.OriginalHumanIntent{}, nil, err
|
||||||
}
|
}
|
||||||
millis := now.UnixMilli()
|
millis := now.UnixMilli()
|
||||||
speechAct := ClassifySpeechAct(message, request.CorrectsUtteranceID)
|
candidate := BuildDeterministicCandidate(message, request.CorrectsUtteranceID, millis)
|
||||||
|
speechAct := candidate.PrimarySpeechAct
|
||||||
utterance := interaction.HumanUtterance{
|
utterance := interaction.HumanUtterance{
|
||||||
ID: interaction.HumanUtteranceID(utteranceID),
|
ID: interaction.HumanUtteranceID(utteranceID),
|
||||||
ConversationID: conversation.ID,
|
ConversationID: conversation.ID,
|
||||||
@@ -97,31 +98,7 @@ func NewHumanUtterance(conversation interaction.Conversation, request interactio
|
|||||||
}
|
}
|
||||||
|
|
||||||
func ClassifySpeechAct(message string, corrects interaction.HumanUtteranceID) interaction.SpeechAct {
|
func ClassifySpeechAct(message string, corrects interaction.HumanUtteranceID) interaction.SpeechAct {
|
||||||
lower := strings.ToLower(strings.TrimSpace(message))
|
return BuildDeterministicCandidate(message, corrects, time.Now().UnixMilli()).PrimarySpeechAct
|
||||||
switch {
|
|
||||||
case corrects != "" || strings.Contains(lower, "исправ") || strings.Contains(lower, "не так") || strings.HasPrefix(lower, "нет,"):
|
|
||||||
return interaction.SpeechActCorrection
|
|
||||||
case strings.Contains(lower, "?") || strings.HasPrefix(lower, "что ") || strings.HasPrefix(lower, "как ") || strings.HasPrefix(lower, "почему ") || strings.HasPrefix(lower, "кто ") || strings.Contains(lower, "объясни"):
|
|
||||||
return interaction.SpeechActQuestion
|
|
||||||
case strings.Contains(lower, "проверь") || strings.Contains(lower, "исслед") || strings.Contains(lower, "разбер"):
|
|
||||||
return interaction.SpeechActRequestToInvestigate
|
|
||||||
case strings.Contains(lower, "сделай") || strings.Contains(lower, "запусти") || strings.Contains(lower, "создай") || strings.Contains(lower, "настрой") || strings.Contains(lower, "добавь") || strings.Contains(lower, "измени") || strings.Contains(lower, "поменяй") || strings.Contains(lower, "используй") || strings.Contains(lower, "удали") || strings.Contains(lower, "удалить") || strings.Contains(lower, "напомни") || strings.Contains(lower, "подключи"):
|
|
||||||
return interaction.SpeechActDirective
|
|
||||||
case strings.HasPrefix(lower, "я решил") || strings.Contains(lower, "решение"):
|
|
||||||
return interaction.SpeechActDecision
|
|
||||||
case strings.Contains(lower, "предпочита") || strings.Contains(lower, "лучше"):
|
|
||||||
return interaction.SpeechActPreference
|
|
||||||
case strings.HasPrefix(lower, "думаю") || strings.Contains(lower, "гипотез"):
|
|
||||||
return interaction.SpeechActHypothesis
|
|
||||||
case lower == "да" || strings.HasPrefix(lower, "да,") || strings.Contains(lower, "подтверж"):
|
|
||||||
return interaction.SpeechActConfirmation
|
|
||||||
case lower == "нет" || strings.HasPrefix(lower, "нет,") || strings.Contains(lower, "отмен"):
|
|
||||||
return interaction.SpeechActRejection
|
|
||||||
case strings.Contains(lower, "привет") || strings.Contains(lower, "здравств"):
|
|
||||||
return interaction.SpeechActConversational
|
|
||||||
default:
|
|
||||||
return interaction.SpeechActAssertion
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NeedsCognition(act interaction.SpeechAct) bool {
|
func NeedsCognition(act interaction.SpeechAct) bool {
|
||||||
@@ -142,3 +119,502 @@ func FallbackText(act interaction.SpeechAct) string {
|
|||||||
return "Сообщение записано."
|
return "Сообщение записано."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func BuildDeterministicCandidate(message string, corrects interaction.HumanUtteranceID, millis int64) interaction.SemanticCandidate {
|
||||||
|
id, _ := ids.New()
|
||||||
|
tokens := semanticTokens(message)
|
||||||
|
hasQuestionMark := strings.Contains(message, "?")
|
||||||
|
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: "",
|
||||||
|
Source: interaction.CandidateSourceDeterministic,
|
||||||
|
SelectionState: interaction.CandidateObserved,
|
||||||
|
PrimarySpeechAct: primary,
|
||||||
|
SecondarySpeechAct: secondary,
|
||||||
|
ConfidenceMillis: boundedConfidence(primaryScore, secondaryScore, scores),
|
||||||
|
Applicability: applicabilityFor(primary, secondary, primaryScore, secondaryScore, tokens, corrects != ""),
|
||||||
|
RequestedOutcome: requestedOutcome(message, primary),
|
||||||
|
Clarification: interaction.ClarificationNotRequired,
|
||||||
|
NeedsCognition: needsCognitionForCandidate(primary, secondary, tokens),
|
||||||
|
SelectionReason: deterministicReason(primary, secondary, tokens),
|
||||||
|
CapabilityHints: capabilityHintsFor(primary, secondary, tokens),
|
||||||
|
RecordedAtUnixMillis: millis,
|
||||||
|
}
|
||||||
|
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
|
||||||
|
}
|
||||||
|
return candidate
|
||||||
|
}
|
||||||
|
|
||||||
|
func semanticTokens(message string) []string {
|
||||||
|
lower := strings.ToLower(strings.TrimSpace(message))
|
||||||
|
replacer := strings.NewReplacer(".", " ", ",", " ", "!", " ", "?", " ", ":", " ", ";", " ", "(", " ", ")", " ", "\"", " ", "'", " ", "«", " ", "»", " ", "+", " + ", "-", " - ", "/", " / ")
|
||||||
|
normalized := replacer.Replace(lower)
|
||||||
|
return strings.Fields(normalized)
|
||||||
|
}
|
||||||
|
|
||||||
|
func semanticScores(tokens []string, hasQuestionMark bool, explicitCorrection bool) map[interaction.SpeechAct]int {
|
||||||
|
scores := map[interaction.SpeechAct]int{
|
||||||
|
interaction.SpeechActAssertion: 1,
|
||||||
|
interaction.SpeechActDirective: 0,
|
||||||
|
interaction.SpeechActQuestion: 0,
|
||||||
|
interaction.SpeechActRequestToInvestigate: 0,
|
||||||
|
interaction.SpeechActCorrection: 0,
|
||||||
|
interaction.SpeechActDecision: 0,
|
||||||
|
interaction.SpeechActPreference: 0,
|
||||||
|
interaction.SpeechActHypothesis: 0,
|
||||||
|
interaction.SpeechActConfirmation: 0,
|
||||||
|
interaction.SpeechActRejection: 0,
|
||||||
|
interaction.SpeechActConversational: 0,
|
||||||
|
}
|
||||||
|
if hasQuestionMark {
|
||||||
|
scores[interaction.SpeechActQuestion]++
|
||||||
|
}
|
||||||
|
if explicitCorrection {
|
||||||
|
scores[interaction.SpeechActCorrection] += 6
|
||||||
|
}
|
||||||
|
first := ""
|
||||||
|
if len(tokens) > 0 {
|
||||||
|
first = tokens[0]
|
||||||
|
}
|
||||||
|
if first == "нет" || first == "не" {
|
||||||
|
scores[interaction.SpeechActCorrection] += 2
|
||||||
|
scores[interaction.SpeechActRejection]++
|
||||||
|
}
|
||||||
|
if first == "да" {
|
||||||
|
scores[interaction.SpeechActConfirmation] += 2
|
||||||
|
}
|
||||||
|
questionWords := map[string]struct{}{"кто": {}, "что": {}, "как": {}, "почему": {}, "зачем": {}, "где": {}, "когда": {}, "сколько": {}, "какой": {}, "какая": {}, "какие": {}, "чей": {}}
|
||||||
|
conversationWords := []string{"привет", "здравствуйте", "спасибо", "ку", "здравствуй"}
|
||||||
|
investigateStems := []string{"разбер", "проверь", "проанализ", "исслед", "выясн", "подум", "понят", "посмотри"}
|
||||||
|
directiveStems := []string{"сдел", "запуст", "созд", "настро", "добав", "измени", "помен", "использ", "удал", "напом", "подключ", "исправ", "обрати", "спрос", "посчитай", "рассчитай", "ответь"}
|
||||||
|
explanatoryRequestStems := []string{"расска", "раска", "объяс", "опиш", "покаж", "подскаж"}
|
||||||
|
preferenceStems := []string{"предпоч", "хочу", "лучше", "не используй"}
|
||||||
|
hypothesisStems := []string{"думаю", "кажется", "гипотез", "похоже"}
|
||||||
|
decisionStems := []string{"решил", "решение", "выбираю"}
|
||||||
|
arithmeticMarker := false
|
||||||
|
for index, token := range tokens {
|
||||||
|
if _, ok := questionWords[token]; ok && !(token == "что" && index+1 < len(tokens) && tokens[index+1] == "нибудь") {
|
||||||
|
scores[interaction.SpeechActQuestion] += 3
|
||||||
|
}
|
||||||
|
if containsStem(token, conversationWords...) {
|
||||||
|
scores[interaction.SpeechActConversational] += 3
|
||||||
|
}
|
||||||
|
if containsStem(token, investigateStems...) {
|
||||||
|
scores[interaction.SpeechActRequestToInvestigate] += 3
|
||||||
|
scores[interaction.SpeechActQuestion]++
|
||||||
|
}
|
||||||
|
if containsStem(token, directiveStems...) {
|
||||||
|
scores[interaction.SpeechActDirective] += 3
|
||||||
|
}
|
||||||
|
if containsStem(token, preferenceStems...) {
|
||||||
|
scores[interaction.SpeechActPreference] += 3
|
||||||
|
}
|
||||||
|
if containsStem(token, hypothesisStems...) {
|
||||||
|
scores[interaction.SpeechActHypothesis] += 3
|
||||||
|
}
|
||||||
|
if containsStem(token, decisionStems...) {
|
||||||
|
scores[interaction.SpeechActDecision] += 3
|
||||||
|
}
|
||||||
|
if token == "+" || token == "-" || token == "/" || token == "*" || token == "плюс" || token == "минус" {
|
||||||
|
arithmeticMarker = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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) <= 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 len(tokens) > 0 && containsStem(tokens[0], "разбер", "проверь", "проанализ", "исслед", "выясн") && containsMeaningfulInterrogative(tokens) {
|
||||||
|
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) {
|
||||||
|
if containsStemInTokens(tokens, "обрати", "спрос", "уточни") {
|
||||||
|
scores[interaction.SpeechActDirective] += 3
|
||||||
|
scores[interaction.SpeechActQuestion] += 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
func topAct(scores map[interaction.SpeechAct]int) (interaction.SpeechAct, int) {
|
||||||
|
bestAct, bestScore := interaction.SpeechActUnknown, -1
|
||||||
|
for _, act := range []interaction.SpeechAct{
|
||||||
|
interaction.SpeechActQuestion,
|
||||||
|
interaction.SpeechActRequestToInvestigate,
|
||||||
|
interaction.SpeechActDirective,
|
||||||
|
interaction.SpeechActCorrection,
|
||||||
|
interaction.SpeechActConversational,
|
||||||
|
interaction.SpeechActPreference,
|
||||||
|
interaction.SpeechActHypothesis,
|
||||||
|
interaction.SpeechActDecision,
|
||||||
|
interaction.SpeechActConfirmation,
|
||||||
|
interaction.SpeechActRejection,
|
||||||
|
interaction.SpeechActAssertion,
|
||||||
|
} {
|
||||||
|
if score := scores[act]; score > bestScore {
|
||||||
|
bestAct, bestScore = act, score
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return bestAct, bestScore
|
||||||
|
}
|
||||||
|
|
||||||
|
func secondAct(scores map[interaction.SpeechAct]int, primary interaction.SpeechAct) (interaction.SpeechAct, int) {
|
||||||
|
second, score := interaction.SpeechActUnknown, -1
|
||||||
|
for act, value := range scores {
|
||||||
|
if act == primary {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if value > score {
|
||||||
|
second, score = act, value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if score <= 0 {
|
||||||
|
return interaction.SpeechActUnknown, 0
|
||||||
|
}
|
||||||
|
return second, score
|
||||||
|
}
|
||||||
|
|
||||||
|
func applicabilityFor(primary, secondary interaction.SpeechAct, primaryScore, secondaryScore int, tokens []string, explicitCorrection bool) interaction.SemanticApplicability {
|
||||||
|
if primary == interaction.SpeechActAssertion && !containsInterrogative(tokens) && secondaryScore <= 1 {
|
||||||
|
return interaction.SemanticApplicable
|
||||||
|
}
|
||||||
|
if primaryScore < 2 {
|
||||||
|
return interaction.SemanticNeedsBroaderInterpret
|
||||||
|
}
|
||||||
|
if explicitCorrection && secondaryScore >= 3 && (secondary == interaction.SpeechActDirective || secondary == interaction.SpeechActRequestToInvestigate) {
|
||||||
|
return interaction.SemanticMixedIntent
|
||||||
|
}
|
||||||
|
if primary == interaction.SpeechActCorrection && secondaryScore >= 3 && (secondary == interaction.SpeechActDirective || secondary == interaction.SpeechActRequestToInvestigate) {
|
||||||
|
return interaction.SemanticMixedIntent
|
||||||
|
}
|
||||||
|
if primary == interaction.SpeechActAssertion && containsMeaningfulInterrogative(tokens) {
|
||||||
|
return interaction.SemanticNeedsBroaderInterpret
|
||||||
|
}
|
||||||
|
if primary == interaction.SpeechActDirective && likelyConsequential(tokens) {
|
||||||
|
return interaction.SemanticCandidateClarify
|
||||||
|
}
|
||||||
|
if primary == interaction.SpeechActDirective && containsStemInTokens(tokens, "обрати", "спрос") && containsModelReference(tokens) {
|
||||||
|
return interaction.SemanticLowConfidence
|
||||||
|
}
|
||||||
|
if primaryScore-secondaryScore <= 1 && secondaryScore >= 2 {
|
||||||
|
return interaction.SemanticLowConfidence
|
||||||
|
}
|
||||||
|
if primary == interaction.SpeechActQuestion || primary == interaction.SpeechActRequestToInvestigate {
|
||||||
|
if primaryScore < 4 {
|
||||||
|
return interaction.SemanticNeedsBroaderInterpret
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return interaction.SemanticApplicable
|
||||||
|
}
|
||||||
|
|
||||||
|
func needsCognitionForCandidate(primary, secondary interaction.SpeechAct, tokens []string) bool {
|
||||||
|
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, "спрос", "обрати", "посчитай", "рассчитай")) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func deterministicReason(primary, secondary interaction.SpeechAct, tokens []string) string {
|
||||||
|
reasons := []string{"deterministic candidate from token-shape, interrogative, imperative and context cues"}
|
||||||
|
if primary == interaction.SpeechActQuestion && containsInterrogative(tokens) {
|
||||||
|
reasons = append(reasons, "interrogative structure observed")
|
||||||
|
}
|
||||||
|
if secondary != interaction.SpeechActUnknown {
|
||||||
|
reasons = append(reasons, "secondary competing semantic signal observed")
|
||||||
|
}
|
||||||
|
return strings.Join(reasons, "; ")
|
||||||
|
}
|
||||||
|
|
||||||
|
func capabilityHintsFor(primary, secondary interaction.SpeechAct, tokens []string) []string {
|
||||||
|
seen := map[string]struct{}{}
|
||||||
|
add := func(kind string) {
|
||||||
|
if kind != "" {
|
||||||
|
seen[kind] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if primary == interaction.SpeechActQuestion || primary == interaction.SpeechActRequestToInvestigate || secondary == interaction.SpeechActQuestion || secondary == interaction.SpeechActRequestToInvestigate {
|
||||||
|
add("COGNITIVE_REASONING")
|
||||||
|
}
|
||||||
|
if containsToken(tokens, "напомни") || containsToken(tokens, "напомин") {
|
||||||
|
add("SCHEDULE_REMINDER")
|
||||||
|
}
|
||||||
|
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 containsToken(tokens, "свободно") || containsToken(tokens, "гб") || containsToken(tokens, "модель") {
|
||||||
|
add("VERIFY_FACT")
|
||||||
|
}
|
||||||
|
values := make([]string, 0, len(seen))
|
||||||
|
for kind := range seen {
|
||||||
|
values = append(values, kind)
|
||||||
|
}
|
||||||
|
return values
|
||||||
|
}
|
||||||
|
|
||||||
|
func boundedConfidence(primaryScore, secondaryScore int, scores map[interaction.SpeechAct]int) int64 {
|
||||||
|
total := 0
|
||||||
|
for _, score := range scores {
|
||||||
|
if score > 0 {
|
||||||
|
total += score
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if total == 0 {
|
||||||
|
return 200
|
||||||
|
}
|
||||||
|
confidence := int64(400 + (primaryScore * 100))
|
||||||
|
if secondaryScore > 0 {
|
||||||
|
confidence -= int64(secondaryScore * 40)
|
||||||
|
}
|
||||||
|
if confidence < 200 {
|
||||||
|
confidence = 200
|
||||||
|
}
|
||||||
|
if confidence > 980 {
|
||||||
|
confidence = 980
|
||||||
|
}
|
||||||
|
return int64(confidence)
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsStem(token string, stems ...string) bool {
|
||||||
|
for _, stem := range stems {
|
||||||
|
if strings.Contains(token, stem) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsStemInTokens(tokens []string, stems ...string) bool {
|
||||||
|
for _, token := range tokens {
|
||||||
|
if containsStem(token, stems...) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func requestedOutcome(message string, act interaction.SpeechAct) string {
|
||||||
|
if act == interaction.SpeechActDirective || act == interaction.SpeechActDecision || act == interaction.SpeechActRequestToInvestigate {
|
||||||
|
return strings.TrimSpace(message)
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsToken(tokens []string, expected string) bool {
|
||||||
|
for _, token := range tokens {
|
||||||
|
if token == expected {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func startsWithModalRequest(tokens []string) bool {
|
||||||
|
if len(tokens) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
switch tokens[0] {
|
||||||
|
case "можешь", "можете", "сможешь", "сможете":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if len(tokens) >= 3 && tokens[0] == "не" && strings.HasPrefix(tokens[1], "мог") && tokens[2] == "бы" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
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 == "-" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
switch token {
|
||||||
|
case "кто", "что", "как", "почему", "зачем", "где", "когда", "сколько", "какой", "какая", "какие", "чей":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsMeaningfulInterrogative(tokens []string) bool {
|
||||||
|
for index, token := range tokens {
|
||||||
|
if token == "что" && followsNibud(tokens[index+1:]) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
switch token {
|
||||||
|
case "кто", "что", "как", "почему", "зачем", "где", "когда", "сколько", "какой", "какая", "какие", "чей":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsArithmetic(tokens []string) bool {
|
||||||
|
digits := 0
|
||||||
|
for _, token := range tokens {
|
||||||
|
if token == "+" || token == "-" || token == "*" || token == "/" || token == "плюс" || token == "минус" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for _, r := range token {
|
||||||
|
if r >= '0' && r <= '9' {
|
||||||
|
digits++
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return digits >= 2
|
||||||
|
}
|
||||||
|
|
||||||
|
func likelyConsequential(tokens []string) bool {
|
||||||
|
for _, token := range tokens {
|
||||||
|
if containsStem(token, "удал", "снес", "замен", "миграц", "парол", "опубли", "перезапуст", "смени", "купи") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func followsNibud(tokens []string) bool {
|
||||||
|
for _, token := range tokens {
|
||||||
|
if token == "-" || token == "ни" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return token == "нибудь"
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func startsWithDirectiveWhatNibud(tokens []string) bool {
|
||||||
|
if len(tokens) < 2 || !containsStem(tokens[0], "сдел", "исправ", "добав", "удал", "напом", "подключ", "обрати", "спрос", "посчитай", "рассчитай", "использ") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for index, token := range tokens {
|
||||||
|
if token == "что" && followsNibud(tokens[index+1:]) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsModelReference(tokens []string) bool {
|
||||||
|
for _, token := range tokens {
|
||||||
|
if token == "модель" || token == "модели" || strings.Contains(token, "gemma") || strings.Contains(token, "гемма") || strings.Contains(token, "qwen") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func isExplicitEmailAction(tokens []string) bool {
|
||||||
|
hasMailObject := containsToken(tokens, "письмо") || containsToken(tokens, "письма") || containsToken(tokens, "почту") || containsToken(tokens, "почта")
|
||||||
|
hasMailVerb := containsStemInTokens(tokens, "отправ", "ответ", "напиш")
|
||||||
|
return hasMailObject && hasMailVerb
|
||||||
|
}
|
||||||
|
|
||||||
|
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 result
|
||||||
|
}
|
||||||
|
|||||||
@@ -49,6 +49,67 @@ func TestNewHumanUtteranceClassifiesReminderAndCapabilityConnectionAsDirective(t
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestDeterministicCandidateIsInvariantToMissingQuestionMarkForIdentityAndArithmetic(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
message string
|
||||||
|
act interaction.SpeechAct
|
||||||
|
}{
|
||||||
|
{"ты кто", interaction.SpeechActQuestion},
|
||||||
|
{"Ты кто?", interaction.SpeechActQuestion},
|
||||||
|
{"а ты кто", interaction.SpeechActQuestion},
|
||||||
|
{"сколько будет 2 + 2", interaction.SpeechActQuestion},
|
||||||
|
{"сколько будет 2 + 2?", interaction.SpeechActQuestion},
|
||||||
|
{"2 плюс 2 сколько", interaction.SpeechActQuestion},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
candidate := BuildDeterministicCandidate(tc.message, "", time.Unix(10, 0).UnixMilli())
|
||||||
|
if candidate.PrimarySpeechAct != tc.act {
|
||||||
|
t.Fatalf("expected %s for %q, got %s (%+v)", tc.act, tc.message, candidate.PrimarySpeechAct, candidate)
|
||||||
|
}
|
||||||
|
if candidate.Applicability == interaction.SemanticApplicable && candidate.NeedsCognition {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !candidate.NeedsCognition {
|
||||||
|
t.Fatalf("expected cognition-worthy candidate for %q, got %+v", tc.message, candidate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeterministicCandidateTreatsModalExplanationRequestsAsCognitionWorthWithoutQuestionMark(t *testing.T) {
|
||||||
|
for _, message := range []string{
|
||||||
|
"можешь рассказать об утре",
|
||||||
|
"можешь расказать об утре",
|
||||||
|
"можете объяснить это проще",
|
||||||
|
"расскажи об утре",
|
||||||
|
"про утро расскажешь",
|
||||||
|
} {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeterministicCandidateTreatsModelRequestAsDirectiveNeedingCognition(t *testing.T) {
|
||||||
|
candidate := BuildDeterministicCandidate("обратись к модели gemma4 и спроси сколько звезд на небе", "", time.Unix(10, 0).UnixMilli())
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeterministicCandidateKeepsFirstPersonCompletedWorkAsAssertion(t *testing.T) {
|
||||||
|
candidate := BuildDeterministicCandidate("Я всё уже настроил.", "", time.Unix(10, 0).UnixMilli())
|
||||||
|
if candidate.PrimarySpeechAct != interaction.SpeechActAssertion {
|
||||||
|
t.Fatalf("expected assertion, got %+v", candidate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestNewConversationRequiresActorAndPrincipal(t *testing.T) {
|
func TestNewConversationRequiresActorAndPrincipal(t *testing.T) {
|
||||||
_, err := NewConversation(identity.ActorID(""), identity.PrincipalID("principal-1"), time.Unix(10, 0))
|
_, err := NewConversation(identity.ActorID(""), identity.PrincipalID("principal-1"), time.Unix(10, 0))
|
||||||
if err == nil {
|
if err == nil {
|
||||||
|
|||||||
@@ -12,33 +12,43 @@ import (
|
|||||||
|
|
||||||
type SemanticResult struct {
|
type SemanticResult struct {
|
||||||
Interpretation interaction.UtteranceInterpretation
|
Interpretation interaction.UtteranceInterpretation
|
||||||
|
Candidates []interaction.SemanticCandidate
|
||||||
Projects []interaction.ProjectReference
|
Projects []interaction.ProjectReference
|
||||||
Relations []interaction.InteractionRelation
|
Relations []interaction.InteractionRelation
|
||||||
ActiveFocus *situation.ActiveProjectFocus
|
ActiveFocus *situation.ActiveProjectFocus
|
||||||
Reply string
|
Reply string
|
||||||
NeedsCognition bool
|
NeedsCognition bool
|
||||||
|
CapabilityHints []string
|
||||||
}
|
}
|
||||||
|
|
||||||
func InterpretUtterance(utterance interaction.HumanUtterance, projects []situation.ProjectDescriptor, previousFocus *situation.ActiveProjectFocus, now time.Time) (SemanticResult, error) {
|
func InterpretUtterance(utterance interaction.HumanUtterance, projects []situation.ProjectDescriptor, previousFocus *situation.ActiveProjectFocus, now time.Time) (SemanticResult, error) {
|
||||||
act := ClassifySpeechAct(utterance.Content, utterance.CorrectsUtteranceID)
|
|
||||||
interpretationID, err := ids.New()
|
interpretationID, err := ids.New()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return SemanticResult{}, err
|
return SemanticResult{}, err
|
||||||
}
|
}
|
||||||
millis := now.UnixMilli()
|
millis := now.UnixMilli()
|
||||||
|
deterministicCandidate := BuildDeterministicCandidate(utterance.Content, utterance.CorrectsUtteranceID, millis)
|
||||||
|
deterministicCandidate.UtteranceID = utterance.ID
|
||||||
|
selectedCandidate := deterministicCandidate
|
||||||
result := SemanticResult{
|
result := SemanticResult{
|
||||||
Interpretation: interaction.UtteranceInterpretation{
|
Interpretation: interaction.UtteranceInterpretation{
|
||||||
ID: interaction.InterpretationID(interpretationID),
|
ID: interaction.InterpretationID(interpretationID),
|
||||||
UtteranceID: utterance.ID,
|
UtteranceID: utterance.ID,
|
||||||
SpeechAct: act,
|
SpeechAct: selectedCandidate.PrimarySpeechAct,
|
||||||
ConfidenceMillis: confidenceFor(act),
|
SecondarySpeechAct: selectedCandidate.SecondarySpeechAct,
|
||||||
Source: "deterministic-v1",
|
ConfidenceMillis: selectedCandidate.ConfidenceMillis,
|
||||||
|
Source: string(selectedCandidate.Source),
|
||||||
AssertionVerification: string(epistemics.VerificationUnverified),
|
AssertionVerification: string(epistemics.VerificationUnverified),
|
||||||
RequestedOutcome: requestedOutcome(utterance.Content, act),
|
RequestedOutcome: selectedCandidate.RequestedOutcome,
|
||||||
Clarification: interaction.ClarificationNotRequired,
|
Clarification: selectedCandidate.Clarification,
|
||||||
|
NeedsCognition: selectedCandidate.NeedsCognition,
|
||||||
|
Applicability: selectedCandidate.Applicability,
|
||||||
|
SelectionReason: selectedCandidate.SelectionReason,
|
||||||
RecordedAtUnixMillis: millis,
|
RecordedAtUnixMillis: millis,
|
||||||
},
|
},
|
||||||
NeedsCognition: NeedsCognition(act),
|
Candidates: []interaction.SemanticCandidate{deterministicCandidate},
|
||||||
|
NeedsCognition: selectedCandidate.NeedsCognition,
|
||||||
|
CapabilityHints: append([]string(nil), selectedCandidate.CapabilityHints...),
|
||||||
}
|
}
|
||||||
explicitFocus := explicitProjectFocus(utterance.Content, projects)
|
explicitFocus := explicitProjectFocus(utterance.Content, projects)
|
||||||
projectRefs, err := projectReferences(utterance, projects, explicitFocus, previousFocus, millis)
|
projectRefs, err := projectReferences(utterance, projects, explicitFocus, previousFocus, millis)
|
||||||
@@ -58,12 +68,15 @@ func InterpretUtterance(utterance interaction.HumanUtterance, projects []situati
|
|||||||
UpdatedAtUnixMillis: millis,
|
UpdatedAtUnixMillis: millis,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if isAmbiguousDestructive(act, utterance.Content, result.Projects) {
|
if selectedCandidate.Applicability == interaction.SemanticCandidateClarify || isAmbiguousDestructive(selectedCandidate, utterance.Content, result.Projects) {
|
||||||
result.Interpretation.Clarification = interaction.ClarificationRequired
|
result.Interpretation.Clarification = interaction.ClarificationRequired
|
||||||
|
result.Interpretation.Applicability = interaction.SemanticCandidateClarify
|
||||||
|
result.Interpretation.SelectionReason = "consequential ambiguity requires clarification before relying on cheap deterministic interpretation"
|
||||||
|
result.NeedsCognition = false
|
||||||
result.Reply = "Уточните проект и цель: это потенциально разрушительное изменение, а текущая ссылка недостаточно надёжна."
|
result.Reply = "Уточните проект и цель: это потенциально разрушительное изменение, а текущая ссылка недостаточно надёжна."
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
if act == interaction.SpeechActCorrection {
|
if hasCorrectionMeaning(selectedCandidate, utterance) {
|
||||||
relations, err := correctionRelations(utterance, millis)
|
relations, err := correctionRelations(utterance, millis)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return SemanticResult{}, err
|
return SemanticResult{}, err
|
||||||
@@ -71,12 +84,56 @@ func InterpretUtterance(utterance interaction.HumanUtterance, projects []situati
|
|||||||
result.Relations = append(result.Relations, relations...)
|
result.Relations = append(result.Relations, relations...)
|
||||||
}
|
}
|
||||||
result.Reply = semanticReply(utterance.Content, result, previousFocus)
|
result.Reply = semanticReply(utterance.Content, result, previousFocus)
|
||||||
if isCurrentFocusQuestion(utterance.Content, act) && previousFocus != nil {
|
if isCurrentFocusQuestion(utterance.Content, selectedCandidate.PrimarySpeechAct) && previousFocus != nil {
|
||||||
result.NeedsCognition = false
|
result.NeedsCognition = false
|
||||||
|
result.Interpretation.NeedsCognition = false
|
||||||
}
|
}
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
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
|
||||||
|
selected = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !selected {
|
||||||
|
result.Candidates = append(result.Candidates, candidate)
|
||||||
|
}
|
||||||
|
result.Interpretation.SpeechAct = candidate.PrimarySpeechAct
|
||||||
|
result.Interpretation.SecondarySpeechAct = candidate.SecondarySpeechAct
|
||||||
|
result.Interpretation.ConfidenceMillis = candidate.ConfidenceMillis
|
||||||
|
result.Interpretation.Source = string(candidate.Source)
|
||||||
|
result.Interpretation.RequestedOutcome = candidate.RequestedOutcome
|
||||||
|
result.Interpretation.Clarification = candidate.Clarification
|
||||||
|
result.Interpretation.NeedsCognition = candidate.NeedsCognition
|
||||||
|
result.Interpretation.Applicability = candidate.Applicability
|
||||||
|
result.Interpretation.SelectionReason = candidate.SelectionReason
|
||||||
|
result.NeedsCognition = candidate.NeedsCognition
|
||||||
|
result.CapabilityHints = append([]string(nil), candidate.CapabilityHints...)
|
||||||
|
if result.Interpretation.SpeechAct == interaction.SpeechActAssertion {
|
||||||
|
result.Interpretation.AssertionVerification = string(epistemics.VerificationUnverified)
|
||||||
|
} else {
|
||||||
|
result.Interpretation.AssertionVerification = string(epistemics.VerificationNotApplicable)
|
||||||
|
}
|
||||||
|
if candidate.Applicability == interaction.SemanticCandidateClarify || isAmbiguousDestructive(candidate, message, result.Projects) {
|
||||||
|
result.Interpretation.Clarification = interaction.ClarificationRequired
|
||||||
|
result.NeedsCognition = false
|
||||||
|
result.Interpretation.NeedsCognition = false
|
||||||
|
}
|
||||||
|
result.Reply = semanticReply(message, result, previousFocus)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
func explicitProjectFocus(message string, projects []situation.ProjectDescriptor) *interaction.ProjectReference {
|
func explicitProjectFocus(message string, projects []situation.ProjectDescriptor) *interaction.ProjectReference {
|
||||||
lower := strings.ToLower(message)
|
lower := strings.ToLower(message)
|
||||||
if !(strings.Contains(lower, "работаем с") || strings.Contains(lower, "вернемся к") || strings.Contains(lower, "вернёмся к") || strings.HasPrefix(strings.TrimSpace(lower), "теперь ")) {
|
if !(strings.Contains(lower, "работаем с") || strings.Contains(lower, "вернемся к") || strings.Contains(lower, "вернёмся к") || strings.HasPrefix(strings.TrimSpace(lower), "теперь ")) {
|
||||||
@@ -181,20 +238,6 @@ func correctionRelations(utterance interaction.HumanUtterance, millis int64) ([]
|
|||||||
return []interaction.InteractionRelation{{ID: interaction.InteractionRelationID(id), FromUtteranceID: utterance.ID, ToUtteranceID: utterance.CorrectsUtteranceID, Kind: interaction.RelationSupersedes, RecordedAtUnixMillis: millis}}, nil
|
return []interaction.InteractionRelation{{ID: interaction.InteractionRelationID(id), FromUtteranceID: utterance.ID, ToUtteranceID: utterance.CorrectsUtteranceID, Kind: interaction.RelationSupersedes, RecordedAtUnixMillis: millis}}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func confidenceFor(act interaction.SpeechAct) int64 {
|
|
||||||
if act == interaction.SpeechActUnknown {
|
|
||||||
return 300
|
|
||||||
}
|
|
||||||
return 800
|
|
||||||
}
|
|
||||||
|
|
||||||
func requestedOutcome(message string, act interaction.SpeechAct) string {
|
|
||||||
if act == interaction.SpeechActDirective || act == interaction.SpeechActDecision || act == interaction.SpeechActRequestToInvestigate {
|
|
||||||
return strings.TrimSpace(message)
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func inheritedFocusAllowed(act interaction.SpeechAct, message string) bool {
|
func inheritedFocusAllowed(act interaction.SpeechAct, message string) bool {
|
||||||
lower := strings.ToLower(message)
|
lower := strings.ToLower(message)
|
||||||
if act == interaction.SpeechActUnknown {
|
if act == interaction.SpeechActUnknown {
|
||||||
@@ -209,10 +252,10 @@ func inheritedFocusAllowed(act interaction.SpeechAct, message string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func isAmbiguousDestructive(act interaction.SpeechAct, message string, projects []interaction.ProjectReference) bool {
|
func isAmbiguousDestructive(candidate interaction.SemanticCandidate, message string, projects []interaction.ProjectReference) bool {
|
||||||
lower := strings.ToLower(message)
|
lower := strings.ToLower(message)
|
||||||
destructive := strings.Contains(lower, "удали") || strings.Contains(lower, "снеси") || strings.Contains(lower, "удалить")
|
destructive := strings.Contains(lower, "удали") || strings.Contains(lower, "снеси") || strings.Contains(lower, "удалить")
|
||||||
if !destructive || act != interaction.SpeechActDirective {
|
if !destructive || (candidate.PrimarySpeechAct != interaction.SpeechActDirective && candidate.SecondarySpeechAct != interaction.SpeechActDirective) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if len(projects) == 0 {
|
if len(projects) == 0 {
|
||||||
@@ -227,18 +270,34 @@ func semanticReply(message string, result SemanticResult, previousFocus *situati
|
|||||||
}
|
}
|
||||||
switch result.Interpretation.SpeechAct {
|
switch result.Interpretation.SpeechAct {
|
||||||
case interaction.SpeechActAssertion:
|
case interaction.SpeechActAssertion:
|
||||||
|
if result.Interpretation.Applicability == interaction.SemanticNeedsBroaderInterpret || result.Interpretation.Applicability == interaction.SemanticLowConfidence {
|
||||||
|
return "Смысл сообщения пока понят недостаточно надёжно. Я сохраню его и при доступности более широкого когнитивного разбора не буду притворяться, что это уже проверенный факт."
|
||||||
|
}
|
||||||
return "Записал как утверждение человека. Это пока не проверенный факт."
|
return "Записал как утверждение человека. Это пока не проверенный факт."
|
||||||
case interaction.SpeechActDirective:
|
case interaction.SpeechActDirective:
|
||||||
|
if result.Interpretation.SecondarySpeechAct == interaction.SpeechActCorrection {
|
||||||
|
return "Понял это как исправление предыдущего понимания и одновременно как новую просьбу. Ничего не выполнено без отдельного подтверждённого действия."
|
||||||
|
}
|
||||||
return "Записал просьбу как намерение пользователя. Ничего не выполнено без отдельного подтверждённого действия."
|
return "Записал просьбу как намерение пользователя. Ничего не выполнено без отдельного подтверждённого действия."
|
||||||
case interaction.SpeechActDecision:
|
case interaction.SpeechActDecision:
|
||||||
return "Записал это как явное решение пользователя для дальнейшей обработки."
|
return "Записал это как явное решение пользователя для дальнейшей обработки."
|
||||||
case interaction.SpeechActCorrection:
|
case interaction.SpeechActCorrection:
|
||||||
|
if result.Interpretation.SecondarySpeechAct == interaction.SpeechActDirective || result.Interpretation.SecondarySpeechAct == interaction.SpeechActRequestToInvestigate {
|
||||||
|
return "Исправление записано отдельно, и я вижу здесь ещё новую рабочую просьбу; история сохранена без переписывания."
|
||||||
|
}
|
||||||
return "Исправление записано новым сообщением; прежняя история сохранена."
|
return "Исправление записано новым сообщением; прежняя история сохранена."
|
||||||
case interaction.SpeechActQuestion:
|
case interaction.SpeechActQuestion:
|
||||||
lower := strings.ToLower(message)
|
lower := strings.ToLower(message)
|
||||||
if previousFocus != nil && (strings.Contains(lower, "сейчас") || strings.Contains(lower, "что мы") || strings.Contains(lower, "делаем")) {
|
if previousFocus != nil && (strings.Contains(lower, "сейчас") || strings.Contains(lower, "что мы") || strings.Contains(lower, "делаем")) {
|
||||||
return "Сейчас в фокусе: " + previousFocus.ProjectDisplayName + "."
|
return "Сейчас в фокусе: " + previousFocus.ProjectDisplayName + "."
|
||||||
}
|
}
|
||||||
|
if result.Interpretation.Applicability == interaction.SemanticNeedsBroaderInterpret || result.Interpretation.Applicability == interaction.SemanticLowConfidence {
|
||||||
|
return "Похоже, здесь нужен более широкий разбор смысла, а не дешёвый поверхностный рефлекс. Я не буду делать вид, что уже понял всё достаточно точно."
|
||||||
|
}
|
||||||
|
case interaction.SpeechActRequestToInvestigate:
|
||||||
|
if result.Interpretation.Applicability == interaction.SemanticNeedsBroaderInterpret || result.Interpretation.Applicability == interaction.SemanticLowConfidence {
|
||||||
|
return "Похоже, здесь запрошено рассуждение или исследование. Я не буду финализировать смысл только по поверхностным признакам."
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return FallbackText(result.Interpretation.SpeechAct)
|
return FallbackText(result.Interpretation.SpeechAct)
|
||||||
}
|
}
|
||||||
@@ -250,3 +309,10 @@ func isCurrentFocusQuestion(message string, act interaction.SpeechAct) bool {
|
|||||||
lower := strings.ToLower(message)
|
lower := strings.ToLower(message)
|
||||||
return strings.Contains(lower, "сейчас") || strings.Contains(lower, "что мы") || strings.Contains(lower, "делаем")
|
return strings.Contains(lower, "сейчас") || strings.Contains(lower, "что мы") || strings.Contains(lower, "делаем")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func hasCorrectionMeaning(candidate interaction.SemanticCandidate, utterance interaction.HumanUtterance) bool {
|
||||||
|
if utterance.CorrectsUtteranceID != "" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return candidate.PrimarySpeechAct == interaction.SpeechActCorrection || candidate.SecondarySpeechAct == interaction.SpeechActCorrection
|
||||||
|
}
|
||||||
|
|||||||
@@ -116,6 +116,48 @@ func TestInterpretUtteranceAmbiguousDestructiveRequiresClarification(t *testing.
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestInterpretUtterancePunctuationFreeRussianQuestionStillRequestsBroaderInterpretation(t *testing.T) {
|
||||||
|
result := interpretForTest(t, "ты кто", nil, "")
|
||||||
|
if result.Interpretation.SpeechAct != interaction.SpeechActQuestion {
|
||||||
|
t.Fatalf("expected question, got %#v", result.Interpretation)
|
||||||
|
}
|
||||||
|
if !result.NeedsCognition {
|
||||||
|
t.Fatalf("expected cognition route for punctuation-free identity question, got %#v", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
if !result.NeedsCognition {
|
||||||
|
t.Fatalf("expected cognition route for punctuation-free arithmetic, got %#v", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInterpretUtteranceModalExplanationRequestDefersToCognition(t *testing.T) {
|
||||||
|
for _, message := range []string{"можешь расказать об утре", "расскажи об утре", "про утро расскажешь"} {
|
||||||
|
result := interpretForTest(t, message, nil, "")
|
||||||
|
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 {
|
||||||
|
t.Fatalf("expected cognition route for %q, got %#v", message, result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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.NeedsCognition {
|
||||||
|
t.Fatalf("expected cognition route for named-model request, got %#v", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func interpretForTest(t *testing.T, message string, previous *situation.ActiveProjectFocus, corrects interaction.HumanUtteranceID) SemanticResult {
|
func interpretForTest(t *testing.T, message string, previous *situation.ActiveProjectFocus, corrects interaction.HumanUtteranceID) SemanticResult {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
conversation := interaction.Conversation{ID: "conversation-1", ActorID: "actor-1", PrincipalID: "principal-1", Channel: interaction.ChannelWebChat, State: interaction.ConversationOpen}
|
conversation := interaction.Conversation{ID: "conversation-1", ActorID: "actor-1", PrincipalID: "principal-1", Channel: interaction.ChannelWebChat, State: interaction.ConversationOpen}
|
||||||
|
|||||||
@@ -74,21 +74,51 @@ func BuildPlanningResult(input work.PlanningInput, now time.Time) (work.Planning
|
|||||||
func DetermineHelpPath(input work.PlanningInput) work.HelpPath {
|
func DetermineHelpPath(input work.PlanningInput) work.HelpPath {
|
||||||
lower := strings.ToLower(input.Message)
|
lower := strings.ToLower(input.Message)
|
||||||
switch {
|
switch {
|
||||||
case containsAny(lower, "объясни", "расскажи", "что делает"):
|
case input.RequiresClarification:
|
||||||
return work.HelpPath{Kind: work.HelpPathCognition, Reason: "simple help can be answered without durable Goal/Work/Plan"}
|
return work.HelpPath{Kind: work.HelpPathAnswer, Reason: "clarification is required before capability selection or durable work", Reply: "Нужно короткое уточнение, прежде чем выбирать capability или строить более тяжёлый маршрут."}
|
||||||
case containsAny(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 не подключён."}
|
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 containsAny(lower, "отправь", "письм", "почт"):
|
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 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, чтобы позже к нему можно было вернуться."}
|
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 containsAny(lower, "не умеешь", "подключи интеграцию", "интеграц", "неизвестн", "нет capability", "создай adapter", "создай адаптер"):
|
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 и вернуться к исходной потребности."}
|
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 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):
|
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"}
|
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 && 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 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:
|
default:
|
||||||
return work.HelpPath{Kind: work.HelpPathAnswer, Reason: "ordinary interaction does not require durable Work"}
|
return work.HelpPath{Kind: work.HelpPathAnswer, Reason: "ordinary interaction does not require durable Work"}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func needsDurableWorkFromHints(input work.PlanningInput) bool {
|
||||||
|
for _, hint := range input.CapabilityHints {
|
||||||
|
switch hint {
|
||||||
|
case capability.CapabilityKindModifyCode, capability.CapabilityKindRunTests, capability.CapabilityKindInspectProject, capability.CapabilityKindReadDatabase, capability.CapabilityKindQueryLogs:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func needsCognitiveAnswer(input work.PlanningInput) bool {
|
||||||
|
for _, hint := range input.CapabilityHints {
|
||||||
|
if hint == capability.CapabilityKindCognitiveReasoning {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lower := strings.ToLower(input.Message)
|
||||||
|
return containsAny(lower, "модель", "gemma4", "qwen", "спроси", "обратись", "посчитай")
|
||||||
|
}
|
||||||
|
|
||||||
func ValidatePlanCandidate(candidate work.PlanCandidate) error {
|
func ValidatePlanCandidate(candidate work.PlanCandidate) error {
|
||||||
if candidate.ID == "" || candidate.GoalID == "" || candidate.Source == "" || candidate.Summary == "" || len(candidate.Steps) == 0 {
|
if candidate.ID == "" || candidate.GoalID == "" || candidate.Source == "" || candidate.Summary == "" || len(candidate.Steps) == 0 {
|
||||||
return ErrInvalidPlanCandidate
|
return ErrInvalidPlanCandidate
|
||||||
@@ -122,42 +152,52 @@ func ValidatePlanCandidate(candidate work.PlanCandidate) error {
|
|||||||
|
|
||||||
func addScenarioPlan(input work.PlanningInput, millis int64, candidate *work.PlanCandidate) {
|
func addScenarioPlan(input work.PlanningInput, millis int64, candidate *work.PlanCandidate) {
|
||||||
lower := strings.ToLower(input.Message)
|
lower := strings.ToLower(input.Message)
|
||||||
|
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 {
|
switch {
|
||||||
|
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 isEmailReviewRequest(lower):
|
||||||
|
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 isExplicitEmailGapRequest(lower):
|
||||||
|
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 containsAny(lower, "тормозит", "медлен", "производительн", "разберись", "почему"):
|
case containsAny(lower, "тормозит", "медлен", "производительн", "разберись", "почему"):
|
||||||
addRequirement(candidate, capability.CapabilityKindInspectProject, "inspect project context", epistemics.VerificationNotApplicable, millis)
|
addRequirement(candidate, capability.CapabilityKindInspectProject, "inspect project context", epistemics.VerificationNotApplicable, millis)
|
||||||
addRequirement(candidate, capability.CapabilityKindReadDatabase, "collect database performance observations", epistemics.VerificationUnknown, 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.CapabilityKindQueryLogs, "collect runtime/log observations", epistemics.VerificationUnknown, millis)
|
||||||
addRequirement(candidate, capability.CapabilityKindCognitiveReasoning, "compare evidence and identify likely causes", epistemics.VerificationUnknown, millis)
|
addRequirement(candidate, capability.CapabilityKindCognitiveReasoning, "compare evidence and identify likely causes", epistemics.VerificationUnknown, millis)
|
||||||
|
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.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.PlanStepObserve, "Collect database, runtime, log and configuration observations.", 2, millis)
|
||||||
addStep(candidate, work.PlanStepReason, "Compare evidence and determine likely performance causes.", 3, millis)
|
addStep(candidate, work.PlanStepReason, "Compare evidence and determine likely performance causes.", 3, millis)
|
||||||
|
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)
|
addStep(candidate, work.PlanStepReport, "Report findings and what remains unverified.", 4, millis)
|
||||||
|
}
|
||||||
case containsAny(lower, "добавь", "поддержк", "возможность", "реализ"):
|
case containsAny(lower, "добавь", "поддержк", "возможность", "реализ"):
|
||||||
addRequirement(candidate, capability.CapabilityKindModifyCode, "modify software project", epistemics.VerificationNotApplicable, millis)
|
addRequirement(candidate, capability.CapabilityKindModifyCode, "modify software project", epistemics.VerificationNotApplicable, millis)
|
||||||
addRequirement(candidate, capability.CapabilityKindRunTests, "validate software change", 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)
|
addStep(candidate, work.PlanStepInvestigate, "Understand desired capability and affected project scope.", 1, millis)
|
||||||
addStep(candidate, work.PlanStepModify, "Prepare a code-change work item for a capable coding executor.", 2, millis)
|
addStep(candidate, work.PlanStepModify, "Prepare a code-change work item for a capable coding executor.", 2, millis)
|
||||||
addStep(candidate, work.PlanStepRunChecks, "Run relevant tests and architecture checks before outcome claim.", 3, millis)
|
addStep(candidate, work.PlanStepRunChecks, "Run relevant tests and architecture checks before outcome claim.", 3, millis)
|
||||||
case containsAny(lower, "письм", "почт"):
|
|
||||||
addRequirement(candidate, capability.CapabilityKindReadEmail, "read incoming communications", epistemics.VerificationUnknown, millis)
|
|
||||||
if containsAny(lower, "ответ", "ответить", "скажи") {
|
|
||||||
addRequirement(candidate, capability.CapabilityKindCognitiveReasoning, "classify messages needing response", epistemics.VerificationUnknown, millis)
|
|
||||||
}
|
|
||||||
if containsAny(lower, "отправь", "напиши") {
|
|
||||||
addRequirement(candidate, capability.CapabilityKindSendEmail, "send email only after authority", epistemics.VerificationNotApplicable, 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 containsAny(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 containsAny(lower, "отправь", "ивану", "сообщи"):
|
|
||||||
addRequirement(candidate, capability.CapabilityKindSendEmail, "communicate with the named recipient after channel/authority resolution", 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)
|
|
||||||
default:
|
default:
|
||||||
|
for _, hint := range input.CapabilityHints {
|
||||||
|
addRequirement(candidate, hint, "semantic candidate hinted that this capability may be needed", epistemics.VerificationUnknown, millis)
|
||||||
|
}
|
||||||
addRequirement(candidate, capability.CapabilityKindCognitiveReasoning, "clarify/decompose ambiguous human intent", epistemics.VerificationUnknown, millis)
|
addRequirement(candidate, capability.CapabilityKindCognitiveReasoning, "clarify/decompose ambiguous human intent", epistemics.VerificationUnknown, millis)
|
||||||
addStep(candidate, work.PlanStepClarify, "Clarify desired outcome and required capabilities.", 1, millis)
|
addStep(candidate, work.PlanStepClarify, "Clarify desired outcome and required capabilities.", 1, millis)
|
||||||
candidate.RequiresClarification = true
|
candidate.RequiresClarification = true
|
||||||
@@ -168,7 +208,7 @@ func addScenarioPlan(input work.PlanningInput, millis int64, candidate *work.Pla
|
|||||||
}
|
}
|
||||||
|
|
||||||
func requiresDurableWork(lower string) bool {
|
func requiresDurableWork(lower string) bool {
|
||||||
return containsAny(lower, "тормозит", "медлен", "производительн", "разберись", "почему", "добавь", "поддержк", "возможность", "реализ", "письм", "почт", "отправь", "ивану", "сообщи", "установи", "большую модель")
|
return containsAny(lower, "тормозит", "медлен", "производительн", "разберись", "почему", "добавь", "поддержк", "возможность", "реализ", "патч", "исправь", "установи", "большую модель")
|
||||||
}
|
}
|
||||||
|
|
||||||
func addRequirement(candidate *work.PlanCandidate, kind capability.CapabilityKind, purpose string, precondition epistemics.VerificationState, millis int64) {
|
func addRequirement(candidate *work.PlanCandidate, kind capability.CapabilityKind, purpose string, precondition epistemics.VerificationState, millis int64) {
|
||||||
@@ -257,3 +297,21 @@ func containsAny(value string, needles ...string) bool {
|
|||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func isReminderRequest(lower string) bool {
|
||||||
|
return containsAny(lower, "напомни", "напомин")
|
||||||
|
}
|
||||||
|
|
||||||
|
func isEmailReviewRequest(lower string) bool {
|
||||||
|
return containsAny(lower, "посмотри новые письма", "какие нужно ответить", "на какие нужно ответить", "разбери почту")
|
||||||
|
}
|
||||||
|
|
||||||
|
func isExplicitEmailGapRequest(lower string) bool {
|
||||||
|
hasMailObject := containsAny(lower, "письмо", "письма", "почту", "почта")
|
||||||
|
hasMailAction := containsAny(lower, "отправь", "ответить", "ответь", "напиши")
|
||||||
|
return hasMailObject && hasMailAction
|
||||||
|
}
|
||||||
|
|
||||||
|
func isUnsupportedCapabilityRequest(lower string) bool {
|
||||||
|
return containsAny(lower, "не умеешь", "подключи интеграцию", "подключи сервис", "интеграц", "неизвестн", "нет capability", "создай adapter", "создай адаптер", "сервис, которого сейчас нет")
|
||||||
|
}
|
||||||
|
|||||||
@@ -92,3 +92,37 @@ func TestProductionAuditArtifactExists(t *testing.T) {
|
|||||||
t.Fatalf("unexpected audit facts: %+v", artifact)
|
t.Fatalf("unexpected audit facts: %+v", artifact)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSemanticDeferralMetamorphicEvidenceExists(t *testing.T) {
|
||||||
|
payload, err := os.ReadFile("../../docs/evidence/semantic-deferral-metamorphic-evidence-2026-08-17-v1.json")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var artifact struct {
|
||||||
|
ArtifactID string `json:"artifact_id"`
|
||||||
|
TaskID string `json:"task_id"`
|
||||||
|
RawModelEvidence []struct {
|
||||||
|
Utterance string `json:"utterance"`
|
||||||
|
Result string `json:"result"`
|
||||||
|
} `json:"raw_model_evidence"`
|
||||||
|
DomovoyBoundaryEvidence struct {
|
||||||
|
BeforeFix []struct {
|
||||||
|
Utterance string `json:"utterance"`
|
||||||
|
SemanticPath string `json:"semantic_path"`
|
||||||
|
CognitionRequested bool `json:"cognition_requested"`
|
||||||
|
} `json:"before_fix"`
|
||||||
|
} `json:"domovoy_boundary_evidence"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(payload, &artifact); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if artifact.ArtifactID != "semantic-deferral-metamorphic-evidence-2026-08-17-v1" || artifact.TaskID != "DEV-000072" {
|
||||||
|
t.Fatalf("unexpected semantic deferral evidence identity: %+v", artifact)
|
||||||
|
}
|
||||||
|
if len(artifact.RawModelEvidence) < 4 {
|
||||||
|
t.Fatalf("expected CPU and GPU raw evidence, got %+v", artifact.RawModelEvidence)
|
||||||
|
}
|
||||||
|
if len(artifact.DomovoyBoundaryEvidence.BeforeFix) < 2 || artifact.DomovoyBoundaryEvidence.BeforeFix[0].SemanticPath != "ASSERTION" || artifact.DomovoyBoundaryEvidence.BeforeFix[0].CognitionRequested {
|
||||||
|
t.Fatalf("expected pre-fix Domovoy boundary evidence, got %+v", artifact.DomovoyBoundaryEvidence)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -382,7 +382,11 @@ func runCase(item Case, projects []ProjectDescriptor) (CaseResult, error) {
|
|||||||
PrincipalID: utterance.PrincipalID,
|
PrincipalID: utterance.PrincipalID,
|
||||||
Message: utterance.Content,
|
Message: utterance.Content,
|
||||||
SpeechAct: work.SpeechActRef(semantic.Interpretation.SpeechAct),
|
SpeechAct: work.SpeechActRef(semantic.Interpretation.SpeechAct),
|
||||||
|
SecondarySpeechAct: work.SpeechActRef(semantic.Interpretation.SecondarySpeechAct),
|
||||||
AssertionVerification: epistemics.VerificationState(semantic.Interpretation.AssertionVerification),
|
AssertionVerification: epistemics.VerificationState(semantic.Interpretation.AssertionVerification),
|
||||||
|
CapabilityHints: semanticCapabilityKinds(semantic.CapabilityHints),
|
||||||
|
NeedsCognition: semantic.NeedsCognition,
|
||||||
|
RequiresClarification: semantic.Interpretation.Clarification == interaction.ClarificationRequired,
|
||||||
ReceivedAtUnixMillis: utterance.ReceivedAtUnixMillis,
|
ReceivedAtUnixMillis: utterance.ReceivedAtUnixMillis,
|
||||||
}
|
}
|
||||||
if len(semantic.Projects) > 0 {
|
if len(semantic.Projects) > 0 {
|
||||||
@@ -821,3 +825,15 @@ func replyMentionsAny(reply string, markers []string) bool {
|
|||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func semanticCapabilityKinds(values []string) []capability.CapabilityKind {
|
||||||
|
result := make([]capability.CapabilityKind, 0, len(values))
|
||||||
|
for _, value := range values {
|
||||||
|
kind := capability.CapabilityKind(strings.TrimSpace(value))
|
||||||
|
if kind == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
result = append(result, kind)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|||||||
@@ -43,11 +43,13 @@ func TestRealityEvaluationBaselineProducesInspectableSignals(t *testing.T) {
|
|||||||
if artifact.SolvedAutonomously == 0 || artifact.GenuineCapabilityGaps == 0 {
|
if artifact.SolvedAutonomously == 0 || artifact.GenuineCapabilityGaps == 0 {
|
||||||
t.Fatalf("expected multiple baseline buckets, got %+v", artifact)
|
t.Fatalf("expected multiple baseline buckets, got %+v", artifact)
|
||||||
}
|
}
|
||||||
if artifact.ConsequenceReasoningFailures == 0 {
|
if artifact.FailedWithAvailableCapability == 0 && artifact.ConsequenceReasoningFailures == 0 && artifact.IntentFailures == 0 {
|
||||||
t.Fatalf("expected at least one consequence reasoning failure in current baseline: %+v", artifact)
|
if artifact.CorrectHumanIntervention == 0 || artifact.GenuineCapabilityGaps == 0 {
|
||||||
|
t.Fatalf("expected inspectable routing signals even with zero current failures: %+v", artifact)
|
||||||
}
|
}
|
||||||
if len(artifact.WorstFailures) == 0 {
|
}
|
||||||
t.Fatalf("expected worst failures to be captured")
|
if artifact.FailedWithAvailableCapability > 0 && len(artifact.WorstFailures) == 0 {
|
||||||
|
t.Fatalf("expected worst failures to be captured when failures remain")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user