DEV-000072 semantic interpretation deferral boundary
CI / test (push) Successful in 18s
CI / test (pull_request) Successful in 17s

This commit is contained in:
m
2026-08-17 23:02:00 +03:00
parent 64870798b9
commit ce666bbc43
22 changed files with 1773 additions and 123 deletions
+98 -32
View File
@@ -11,34 +11,44 @@ import (
)
type SemanticResult struct {
Interpretation interaction.UtteranceInterpretation
Projects []interaction.ProjectReference
Relations []interaction.InteractionRelation
ActiveFocus *situation.ActiveProjectFocus
Reply string
NeedsCognition bool
Interpretation interaction.UtteranceInterpretation
Candidates []interaction.SemanticCandidate
Projects []interaction.ProjectReference
Relations []interaction.InteractionRelation
ActiveFocus *situation.ActiveProjectFocus
Reply string
NeedsCognition bool
CapabilityHints []string
}
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()
if err != nil {
return SemanticResult{}, err
}
millis := now.UnixMilli()
deterministicCandidate := BuildDeterministicCandidate(utterance.Content, utterance.CorrectsUtteranceID, millis)
deterministicCandidate.UtteranceID = utterance.ID
selectedCandidate := deterministicCandidate
result := SemanticResult{
Interpretation: interaction.UtteranceInterpretation{
ID: interaction.InterpretationID(interpretationID),
UtteranceID: utterance.ID,
SpeechAct: act,
ConfidenceMillis: confidenceFor(act),
Source: "deterministic-v1",
SpeechAct: selectedCandidate.PrimarySpeechAct,
SecondarySpeechAct: selectedCandidate.SecondarySpeechAct,
ConfidenceMillis: selectedCandidate.ConfidenceMillis,
Source: string(selectedCandidate.Source),
AssertionVerification: string(epistemics.VerificationUnverified),
RequestedOutcome: requestedOutcome(utterance.Content, act),
Clarification: interaction.ClarificationNotRequired,
RequestedOutcome: selectedCandidate.RequestedOutcome,
Clarification: selectedCandidate.Clarification,
NeedsCognition: selectedCandidate.NeedsCognition,
Applicability: selectedCandidate.Applicability,
SelectionReason: selectedCandidate.SelectionReason,
RecordedAtUnixMillis: millis,
},
NeedsCognition: NeedsCognition(act),
Candidates: []interaction.SemanticCandidate{deterministicCandidate},
NeedsCognition: selectedCandidate.NeedsCognition,
CapabilityHints: append([]string(nil), selectedCandidate.CapabilityHints...),
}
explicitFocus := explicitProjectFocus(utterance.Content, projects)
projectRefs, err := projectReferences(utterance, projects, explicitFocus, previousFocus, millis)
@@ -58,12 +68,15 @@ func InterpretUtterance(utterance interaction.HumanUtterance, projects []situati
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.Applicability = interaction.SemanticCandidateClarify
result.Interpretation.SelectionReason = "consequential ambiguity requires clarification before relying on cheap deterministic interpretation"
result.NeedsCognition = false
result.Reply = "Уточните проект и цель: это потенциально разрушительное изменение, а текущая ссылка недостаточно надёжна."
return result, nil
}
if act == interaction.SpeechActCorrection {
if hasCorrectionMeaning(selectedCandidate, utterance) {
relations, err := correctionRelations(utterance, millis)
if err != nil {
return SemanticResult{}, err
@@ -71,12 +84,56 @@ func InterpretUtterance(utterance interaction.HumanUtterance, projects []situati
result.Relations = append(result.Relations, relations...)
}
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.Interpretation.NeedsCognition = false
}
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 {
lower := strings.ToLower(message)
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
}
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 {
lower := strings.ToLower(message)
if act == interaction.SpeechActUnknown {
@@ -209,10 +252,10 @@ func inheritedFocusAllowed(act interaction.SpeechAct, message string) bool {
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)
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
}
if len(projects) == 0 {
@@ -227,18 +270,34 @@ func semanticReply(message string, result SemanticResult, previousFocus *situati
}
switch result.Interpretation.SpeechAct {
case interaction.SpeechActAssertion:
if result.Interpretation.Applicability == interaction.SemanticNeedsBroaderInterpret || result.Interpretation.Applicability == interaction.SemanticLowConfidence {
return "Смысл сообщения пока понят недостаточно надёжно. Я сохраню его и при доступности более широкого когнитивного разбора не буду притворяться, что это уже проверенный факт."
}
return "Записал как утверждение человека. Это пока не проверенный факт."
case interaction.SpeechActDirective:
if result.Interpretation.SecondarySpeechAct == interaction.SpeechActCorrection {
return "Понял это как исправление предыдущего понимания и одновременно как новую просьбу. Ничего не выполнено без отдельного подтверждённого действия."
}
return "Записал просьбу как намерение пользователя. Ничего не выполнено без отдельного подтверждённого действия."
case interaction.SpeechActDecision:
return "Записал это как явное решение пользователя для дальнейшей обработки."
case interaction.SpeechActCorrection:
if result.Interpretation.SecondarySpeechAct == interaction.SpeechActDirective || result.Interpretation.SecondarySpeechAct == interaction.SpeechActRequestToInvestigate {
return "Исправление записано отдельно, и я вижу здесь ещё новую рабочую просьбу; история сохранена без переписывания."
}
return "Исправление записано новым сообщением; прежняя история сохранена."
case interaction.SpeechActQuestion:
lower := strings.ToLower(message)
if previousFocus != nil && (strings.Contains(lower, "сейчас") || strings.Contains(lower, "что мы") || strings.Contains(lower, "делаем")) {
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)
}
@@ -250,3 +309,10 @@ func isCurrentFocusQuestion(message string, act interaction.SpeechAct) bool {
lower := strings.ToLower(message)
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
}