Files
Cyrene_v2/internal/services/backthink/decide.go
T
Aska 12031bd13c
CI / Backend (build / vet / test / cross-compile) (push) Has been cancelled
CI / Frontend (tsc + vite build) (push) Has been cancelled
fix(backthink): 主动推送降频(15min心跳+60min≤1次+推后30min冷却+刚聊过10min冷避) + 情绪约束(分类限频/活跃感知) + 剥离'我决定:push'内部标记
2026-09-08 13:08:57 +08:00

300 lines
11 KiB
Go

package backthink
import (
"fmt"
"strings"
"time"
)
// Importance is the estimated severity of an event that woke a thinking pass. It
// is the primary positive signal in the interrupt decision: a low-importance
// heartbeat almost never interrupts, while a critical safety event normally does.
type Importance int
const (
// ImportanceLow is a routine trigger (e.g. the periodic heartbeat).
ImportanceLow Importance = iota
// ImportanceNormal is an ordinary event worth reflecting on (device change).
ImportanceNormal
// ImportanceHigh is a notable event (a reminder the user set firing).
ImportanceHigh
// ImportanceCritical is a safety-critical event that may override work/busy.
ImportanceCritical
)
// String returns a stable label for logs and records.
func (i Importance) String() string {
switch i {
case ImportanceLow:
return "low"
case ImportanceNormal:
return "normal"
case ImportanceHigh:
return "high"
case ImportanceCritical:
return "critical"
default:
return fmt.Sprintf("importance(%d)", int(i))
}
}
// highBoredomThreshold is the boredom (0..1) above which a normal daytime event
// is worth interrupting a bored, otherwise idle user. It is a const so no magic
// number appears in the decision path.
const highBoredomThreshold = 0.7
// longIdleThreshold is the gap after the owner's last message beyond which the
// activity gate only lets a genuinely important event through (a long-away owner
// should not be woken for trivia). Compile-time so no magic number appears.
const longIdleThreshold = 2 * time.Hour
// UserState describes the user's current condition as observed from device
// telemetry (heart rate, sleep) and schedule (work, busy). It is the negative
// signal in the interrupt decision: a sleeping, working or busy user is left
// alone. Boredom (0..1) is the soft positive dial that widens interruption.
type UserState struct {
// HeartRateBPM is the current heart rate, 0 when unknown.
HeartRateBPM int
// Sleeping reports whether the user is currently asleep from sleep tracking.
Sleeping bool
// Working reports whether the user is in a work/scheduled block.
Working bool
// Busy reports whether the user is marked busy (calendar / do-not-disturb).
Busy bool
// Boredom ranges 0..1. Higher boredom means the user is idle and more open
// to a gentle interruption.
Boredom float64
}
// String returns a concise human-readable summary for logs/records.
func (s UserState) String() string {
return fmt.Sprintf("bpm=%d sleeping=%v working=%v busy=%v boredom=%.2f",
s.HeartRateBPM, s.Sleeping, s.Working, s.Busy, s.Boredom)
}
// DecisionInput is the set of signals Decide weighs: the event's importance, the
// current wall-clock time, the user's current state and their boredom.
type DecisionInput struct {
// Trigger is a human-readable source label, recorded for traceability.
Trigger string
// Import is the event's estimated importance.
Import Importance
// At is the current wall-clock time, in the local timezone used for the
// do-not-disturb window.
At time.Time
// UserState carries the user's physiological/schedule condition.
UserState UserState
// LastActivity is the wall-clock time of the owner's most recent message.
// HasActivity reports whether a user message was found; when false the
// activity gate falls through without guessing.
LastActivity time.Time
// HasActivity reports whether LastActivity is meaningful.
HasActivity bool
}
// Decision is the outcome of Decide.
type Decision struct {
// ShouldPush reports whether the user should be interrupted.
ShouldPush bool
// Reason is a short human-readable justification, surfaced on the panel.
Reason string
}
// Decide applies the interrupt rule from design/12 §2 (and design/11 §6) with
// "不打扰 (do not interrupt) as the first principle" as its bias, then softens it
// with the activity-aware gate (design/12 §6). It is a pure method on Backthink
// only so it can read the configured quiet-hours window; it does not touch state.
//
// baseDecide's evaluation order is deliberately fail-closed (prefer not
// interrupting):
//
// 1. A sleeping user is never interrupted.
// 2. A working or busy user is interrupted only by a critical event.
// 3. Inside the quiet-hours (deep-night) window only high/critical events
// interrupt; low/normal events are deferred.
// 4. In the daytime, high/critical events always interrupt; a normal event
// interrupts only when the user is quite bored; a low event never does.
//
// A would-push decision is then run through the activity gate, which holds a push
// when the owner just chatted (fresh conversation) or has been away a long while
// and the event is not genuinely important.
func (b *Backthink) Decide(in DecisionInput) Decision {
d := b.baseDecide(in)
if !d.ShouldPush {
return d
}
if !b.activityAllowed(in.Import, in.LastActivity, in.HasActivity, in.At) {
return Decision{ShouldPush: false, Reason: "proactive push held: " + d.Reason}
}
return d
}
// baseDecide is the do-not-interrupt cascade of design/12 §2.
func (b *Backthink) baseDecide(in DecisionInput) Decision {
s := in.UserState
if s.Sleeping {
return Decision{ShouldPush: false, Reason: "user is asleep; not interrupting"}
}
if (s.Working || s.Busy) && in.Import < ImportanceCritical {
return Decision{ShouldPush: false, Reason: "user is working/busy; not interrupting"}
}
if b.inQuietHours(in.At) {
if in.Import >= ImportanceHigh {
return Decision{ShouldPush: true, Reason: "quiet hours but event is important"}
}
return Decision{ShouldPush: false, Reason: "quiet hours; not interrupting"}
}
switch in.Import {
case ImportanceCritical, ImportanceHigh:
return Decision{ShouldPush: true, Reason: "high/critical importance during daytime"}
case ImportanceNormal:
if s.Boredom >= highBoredomThreshold {
return Decision{ShouldPush: true, Reason: "normal importance and user is bored"}
}
return Decision{ShouldPush: false, Reason: "normal importance; not worth interrupting"}
default:
return Decision{ShouldPush: false, Reason: "low importance; not interrupting"}
}
}
// activityAllowed is the activity-aware soft gate (design/12 §6). It widens the
// do-not-interrupt principle to the conversation's own rhythm:
//
// - Within RecentChatCooldown of the owner's last message, the conversation is
// fresh — a non-critical push is held so she is not interrupted mid-chat.
// - After longIdleThreshold without a message, the owner has been away — only a
// genuinely important event is worth waking them for.
// - Anywhere in between, and when activity is unknown, the decision is not
// softened (fall through).
//
// Activity is a soft signal: the hard do-not-disturb gate is separate, and the
// frequency gate (PushGate) applies separately inside the pusher.
func (b *Backthink) activityAllowed(imp Importance, lastActivity time.Time, hasActivity bool, at time.Time) bool {
if !hasActivity {
return true
}
since := at.Sub(lastActivity)
if since <= b.cfg.RecentChatCooldown {
return imp >= ImportanceCritical
}
if since >= longIdleThreshold {
return imp >= ImportanceHigh
}
return true
}
// disturbAllowed is the hard "do not disturb" safety gate for an autonomous push
// (design/12 §2 first principle). Unlike Decide it deliberately ignores trigger
// importance — which design/20 P2 replaces with her own judgment — and only blocks
// when it is genuinely inappropriate to interrupt: the user is asleep, working or
// busy, or it is inside the quiet-hours window. The frequency gate (PushGate)
// applies separately inside the pusher.
func (b *Backthink) disturbAllowed(at time.Time, s UserState) bool {
if s.Sleeping || s.Working || s.Busy {
return false
}
return !b.inQuietHours(at)
}
// interruptReason is the short human-readable note recorded/logged when no push
// goes out (or as the pre-push intent). It keeps the panel self-explanatory:
// either she concluded no push, the do-not-disturb gate refused a push she
// wanted, or the activity gate held it.
func (b *Backthink) interruptReason(push bool, at time.Time, s UserState, imp Importance, lastActivity time.Time, hasActivity bool) string {
switch {
case !push:
return "conclusion requested no push"
case !b.disturbAllowed(at, s):
return "proactive push blocked by do-not-disturb"
case !b.activityAllowed(imp, lastActivity, hasActivity, at):
return "proactive push held by activity gate"
default:
return "proactive push approved"
}
}
// inQuietHours reports whether at falls inside the configured do-not-disturb
// window. The window may wrap midnight (e.g. 23:00-07:00); two equal non-zero
// hours disable it.
func (b *Backthink) inQuietHours(at time.Time) bool {
h := at.Hour()
start, end := b.cfg.QuietStartHour, b.cfg.QuietEndHour
if start <= end {
return h >= start && h < end
}
return h >= start || h < end
}
// PushKind classifies a proactive message into one of a few flavors so the
// frequency gate can limit each flavor within a window, avoiding same-style spam
// (design/12 §6 策略二). It is a soft tag derived from the message body's
// keywords — it affects pacing, never identity or permission.
type PushKind int
const (
// KindGreeting is a warm hello / good-morning / good-night opener.
KindGreeting PushKind = iota
// KindReminder is a nudge about a schedule, task or deadline.
KindReminder
// KindShare is a discovery, observation or interesting find.
KindShare
// KindCare is a warm, caring check-in about the owner's wellbeing.
KindCare
)
// String returns a stable label for logs and records.
func (k PushKind) String() string {
switch k {
case KindGreeting:
return "greeting"
case KindReminder:
return "reminder"
case KindShare:
return "share"
case KindCare:
return "care"
default:
return fmt.Sprintf("pushkind(%d)", int(k))
}
}
// classifyPush assigns a PushKind to a proactive message from its keyword
// content. A message that matches no flavor defaults to KindCare (the warm,
// generic intent of an unsolicited proactive note), which is the least
// spam-prone grouping. Priority is reminder > care > greeting > share so the
// dominant intent wins when several keywords co-occur.
func classifyPush(message string) PushKind {
switch {
case hasAnyKeyword(message, kindReminderKeywords...):
return KindReminder
case hasAnyKeyword(message, kindCareKeywords...):
return KindCare
case hasAnyKeyword(message, kindGreetingKeywords...):
return KindGreeting
case hasAnyKeyword(message, kindShareKeywords...):
return KindShare
default:
return KindCare
}
}
// keyword sets for classifyPush. They are package vars (not consts) so the
// classification stays flexible and testable, but they are immutable by
// convention and never mutated at run time.
var (
kindReminderKeywords = []string{"提醒", "记得", "别忘了", "该去", "日程", "会议", "体检", "吃药", "喝药", "到点", "几点", "还有", "迟到", "明天", "马上", "最后", "截止"}
kindCareKeywords = []string{"关心", "最近", "辛苦", "注意身体", "照顾好", "好好休息", "心情", "还好", "想你了", "想我", "担心", "保重", "你还好", "陪你", "累"}
kindGreetingKeywords = []string{"早安", "晚安", "早上好", "中午好", "晚上好", "午安", "回来", "吃饭", "睡了"}
kindShareKeywords = []string{"发现", "分享", "看到", "听说", "注意到", "告诉你", "有个", "想到", "有意思", "有趣", "你知道吗"}
)
// hasAnyKeyword reports whether s contains any of the given substrings.
func hasAnyKeyword(s string, subs ...string) bool {
for _, sub := range subs {
if strings.Contains(s, sub) {
return true
}
}
return false
}