313 lines
11 KiB
Go
313 lines
11 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"strings"
|
|
|
|
hexisclient "github.com/kami/hexis/pkg/client"
|
|
"github.com/kami/maven/internal/ipc"
|
|
"github.com/kami/maven/internal/router"
|
|
)
|
|
|
|
// praxisCapability is one arm of the Praxis act dispatch. This is an interface
|
|
// rather than a map[string]func because each arm carries its own state: the
|
|
// verb aliases it answers to, the trace name it records, and its own reply
|
|
// formatting. The dispatch grows an arm per Praxis capability, so a new one is
|
|
// added to praxisCapabilities below and nothing else changes.
|
|
type praxisCapability interface {
|
|
// aliases are the verbs (router fn slots, EN and RU) this capability answers to.
|
|
aliases() []string
|
|
// handle runs the capability and returns the user-facing reply.
|
|
handle(ctx context.Context, h *reactiveHandler, px *praxisClient, dec router.Decision) string
|
|
}
|
|
|
|
// praxisCapabilities is the registry handlePraxisAct consults, in order.
|
|
var praxisCapabilities = []praxisCapability{
|
|
listAttentionCapability{},
|
|
praxisItemAction{
|
|
verbs: []string{"acknowledge_item", "принято", "понял", "поняла"},
|
|
ask: "какой пункт отметить принятым?",
|
|
op: "acknowledge",
|
|
failure: "не получилось отметить принятым.",
|
|
success: "принято.",
|
|
call: func(ctx context.Context, px *praxisClient, id string) error {
|
|
_, err := px.Acknowledge(ctx, id)
|
|
return err
|
|
},
|
|
},
|
|
praxisItemAction{
|
|
verbs: []string{"resolve_item", "сделано", "готово", "решено"},
|
|
ask: "какой пункт отметить сделанным?",
|
|
op: "resolve",
|
|
failure: "не получилось отметить сделанным.",
|
|
success: "отмечено как сделано.",
|
|
call: func(ctx context.Context, px *praxisClient, id string) error {
|
|
_, err := px.Resolve(ctx, id)
|
|
return err
|
|
},
|
|
},
|
|
praxisItemAction{
|
|
verbs: []string{"ignore_item", "игнорировать", "неважно"},
|
|
ask: "какой пункт игнорировать?",
|
|
op: "ignore",
|
|
failure: "не получилось проигнорировать.",
|
|
success: "проигнорировано.",
|
|
call: func(ctx context.Context, px *praxisClient, id string) error {
|
|
_, err := px.Ignore(ctx, id)
|
|
return err
|
|
},
|
|
},
|
|
praxisItemAction{
|
|
verbs: []string{"pin_item", "закрепить"},
|
|
ask: "какой пункт закрепить?",
|
|
op: "pin",
|
|
failure: "не получилось закрепить.",
|
|
success: "закреплено.",
|
|
call: func(ctx context.Context, px *praxisClient, id string) error {
|
|
_, err := px.Pin(ctx, id, true)
|
|
return err
|
|
},
|
|
},
|
|
listChangesCapability{},
|
|
}
|
|
|
|
// handlePraxisAct — dispatches ecosystem tool acts through the Praxis tools API.
|
|
// Returns "" when the act is not a Praxis verb (the caller falls through to the
|
|
// system command executor). Returns a reply string otherwise.
|
|
func (h *reactiveHandler) handlePraxisAct(ctx context.Context, dec router.Decision) string {
|
|
if h.ecosystem == nil || h.ecosystem.praxis == nil {
|
|
return ""
|
|
}
|
|
px := h.ecosystem.praxis
|
|
for _, capability := range praxisCapabilities {
|
|
for _, alias := range capability.aliases() {
|
|
if alias == dec.Slots.Fn {
|
|
return capability.handle(ctx, h, px, dec)
|
|
}
|
|
}
|
|
}
|
|
// Not a Praxis verb — let the caller fall through.
|
|
return ""
|
|
}
|
|
|
|
// praxisItemAction is the shared shape of the item-lifecycle capabilities: take
|
|
// an item id from the value slot, call one Praxis endpoint, trace the result.
|
|
type praxisItemAction struct {
|
|
verbs []string
|
|
ask string // reply when no item id was given
|
|
op string // trace + log name of the operation
|
|
failure string // reply when the Praxis call errors
|
|
success string
|
|
call func(ctx context.Context, px *praxisClient, id string) error
|
|
}
|
|
|
|
func (a praxisItemAction) aliases() []string { return a.verbs }
|
|
|
|
func (a praxisItemAction) handle(ctx context.Context, h *reactiveHandler, px *praxisClient, dec router.Decision) string {
|
|
id := dec.Slots.Value
|
|
if id == "" {
|
|
return a.ask
|
|
}
|
|
if err := a.call(ctx, px, id); err != nil {
|
|
log.Printf("ecosystem: praxis %s %s: %v", a.op, id, err)
|
|
return a.failure
|
|
}
|
|
h.recordPraxisTrace(ctx, a.op, map[string]any{"item_id": id})
|
|
return a.success
|
|
}
|
|
|
|
// listAttentionCapability reads the attention digest and surfaces every item it speaks.
|
|
type listAttentionCapability struct{}
|
|
|
|
func (listAttentionCapability) aliases() []string {
|
|
return []string{"list_attention", "attention", "внимание", "что требует внимания", "что нового"}
|
|
}
|
|
|
|
func (listAttentionCapability) handle(ctx context.Context, h *reactiveHandler, px *praxisClient, _ router.Decision) string {
|
|
items, err := px.ListAttention(ctx, 20)
|
|
if err != nil {
|
|
log.Printf("ecosystem: praxis attention: %v", err)
|
|
return "не могу сейчас узнать, что требует внимания."
|
|
}
|
|
if len(items) == 0 {
|
|
return "ничего не требует внимания."
|
|
}
|
|
h.recordPraxisTrace(ctx, "list_attention", map[string]any{"count": len(items)})
|
|
var parts []string
|
|
for _, item := range items {
|
|
title, _ := item["title"].(string)
|
|
// importance arrives as JSON number ⇒ float64 over the HTTP contract.
|
|
importance, _ := item["importance"].(float64)
|
|
rule, _ := item["rule"].(string)
|
|
s := title
|
|
if importance > 0 {
|
|
s += fmt.Sprintf(" (важность %d", int(importance))
|
|
if rule != "" {
|
|
s += ": " + rule
|
|
}
|
|
s += ")"
|
|
}
|
|
parts = append(parts, s)
|
|
|
|
// Speaking an item surfaces it, it does not acknowledge it
|
|
// (ECOSYSTEM-SPEC.md §2.3: surfaced != acknowledged). Best-effort:
|
|
// a failed surface call must not block delivering the digest.
|
|
if id, ok := item["id"].(string); ok && id != "" {
|
|
if _, err := px.Surface(ctx, id); err != nil {
|
|
log.Printf("ecosystem: praxis surface %s: %v", id, err)
|
|
}
|
|
}
|
|
}
|
|
return "требует внимания: " + strings.Join(parts, "; ")
|
|
}
|
|
|
|
// listChangesCapability reads the recent-changes feed.
|
|
type listChangesCapability struct{}
|
|
|
|
func (listChangesCapability) aliases() []string {
|
|
return []string{"list_changes", "changes", "изменения", "что изменилось"}
|
|
}
|
|
|
|
func (listChangesCapability) handle(ctx context.Context, h *reactiveHandler, px *praxisClient, _ router.Decision) string {
|
|
changes, err := px.ListChanges(ctx, 20)
|
|
if err != nil {
|
|
log.Printf("ecosystem: praxis changes: %v", err)
|
|
return "не могу сейчас узнать об изменениях."
|
|
}
|
|
if len(changes) == 0 {
|
|
return "нет изменений."
|
|
}
|
|
h.recordPraxisTrace(ctx, "list_changes", map[string]any{"count": len(changes)})
|
|
var parts []string
|
|
for _, c := range changes {
|
|
title, _ := c["title"].(string)
|
|
typ, _ := c["change_type"].(string)
|
|
parts = append(parts, fmt.Sprintf("%s (%s)", title, typ))
|
|
}
|
|
return "изменения: " + strings.Join(parts, "; ")
|
|
}
|
|
|
|
// recordPraxisTrace — writes a fact recording a cross-service ecosystem call.
|
|
// The fact is stored with source "praxis:trace" so the proactive loop can
|
|
// reference it and the dashboard can display recent ecosystem activity.
|
|
func (h *reactiveHandler) recordPraxisTrace(ctx context.Context, operation string, details map[string]any) {
|
|
now := h.now()
|
|
value := operation
|
|
if len(details) > 0 {
|
|
if b, err := json.Marshal(details); err == nil {
|
|
value = operation + " " + string(b)
|
|
}
|
|
}
|
|
_, _ = h.api.WriteFact(ctx, ipc.WriteFactReq{
|
|
Ts: now,
|
|
Kind: "system",
|
|
Key: "praxis:" + operation,
|
|
Value: value,
|
|
Source: "praxis:trace",
|
|
Confidence: 1.0,
|
|
})
|
|
}
|
|
|
|
// handleHexisAct — resolves entity references through Nexus and executes
|
|
// matching capabilities through Hexis. Returns a reply string when handled,
|
|
// or "" to fall through to the system command executor.
|
|
func (h *reactiveHandler) handleHexisAct(ctx context.Context, dec router.Decision) string {
|
|
if h.ecosystem == nil {
|
|
return ""
|
|
}
|
|
|
|
// Resolve the utterance text as an entity reference through Nexus. An
|
|
// ambiguous match must stop and clarify — never guess a mutation target.
|
|
entityID, displayName, ambiguous, err := h.ecosystem.resolveEntityReference(ctx, dec.Slots.Text, nil)
|
|
if err != nil {
|
|
// A genuine Nexus dependency failure, not "no such entity" — stop here
|
|
// and report degradation rather than silently falling through to the
|
|
// local command executor (ECOSYSTEM-SPEC.md: services degrade
|
|
// independently, never a silent all-clear).
|
|
return "экосистема недоступна, попробуй ещё раз."
|
|
}
|
|
if len(ambiguous) > 0 {
|
|
return "уточни, что именно: " + strings.Join(ambiguous, ", ") + "?"
|
|
}
|
|
if entityID == "" {
|
|
return ""
|
|
}
|
|
|
|
// Discover Hexis capabilities for this entity. A resolved entity with a
|
|
// genuine Hexis failure must not be treated as "no capabilities" and
|
|
// fall through to unrelated local execution.
|
|
caps, err := h.ecosystem.discoverCapabilities(ctx, entityID)
|
|
if err != nil {
|
|
return "экосистема недоступна, попробуй ещё раз."
|
|
}
|
|
if len(caps) == 0 {
|
|
return ""
|
|
}
|
|
|
|
// Match the user's verb to a capability by name/description. Collect all
|
|
// matches: more than one is itself ambiguous, so we ask rather than pick
|
|
// the first (ecosystem invariant: no arbitrary target for mutation).
|
|
verb := dec.Slots.Fn
|
|
if verb == "" {
|
|
verb = dec.Slots.Text
|
|
}
|
|
verbLower := strings.ToLower(verb)
|
|
|
|
var matches []*hexisclient.Capability
|
|
for i, c := range caps {
|
|
if strings.Contains(strings.ToLower(c.Name), verbLower) ||
|
|
(c.Description != "" && strings.Contains(strings.ToLower(c.Description), verbLower)) {
|
|
matches = append(matches, &caps[i])
|
|
}
|
|
}
|
|
if len(matches) == 0 {
|
|
return ""
|
|
}
|
|
if len(matches) > 1 {
|
|
var names []string
|
|
for _, m := range matches {
|
|
names = append(names, m.Name)
|
|
}
|
|
return "какую команду для " + displayName + ": " + strings.Join(names, ", ") + "?"
|
|
}
|
|
matched := matches[0]
|
|
|
|
// Read-only capabilities run immediately; mutating ones are parked for an
|
|
// explicit spoken confirm bound to this capability + target.
|
|
if !matched.ReadOnly {
|
|
h.mu.Lock()
|
|
h.pendingHexis = &pendingHexisExec{
|
|
capabilityID: matched.ID,
|
|
capName: matched.Name,
|
|
entityID: entityID,
|
|
displayName: displayName,
|
|
expiry: h.now().Add(confirmTTL),
|
|
}
|
|
h.mu.Unlock()
|
|
return "выполнить «" + matched.Name + "» для " + displayName + "? скажи «да» или «нет»."
|
|
}
|
|
|
|
return h.execHexis(ctx, matched.ID, matched.Name, entityID, displayName)
|
|
}
|
|
|
|
// execHexis runs a resolved capability and records a cross-service trace with
|
|
// the correlation ID. It reports command success, never operational recovery
|
|
// (Praxis observes recovery independently).
|
|
func (h *reactiveHandler) execHexis(ctx context.Context, capID, capName, entityID, displayName string) string {
|
|
correlationID, err := h.ecosystem.executeCapability(ctx, capID, entityID, nil)
|
|
if err != nil {
|
|
log.Printf("ecosystem: hexis execute error (cor=%s): %v", correlationID, err)
|
|
return "не получилось выполнить команду для " + displayName + "."
|
|
}
|
|
h.recordPraxisTrace(ctx, "hexis:"+capName, map[string]any{
|
|
"entity_id": entityID,
|
|
"entity_name": displayName,
|
|
"capability": capName,
|
|
"correlation_id": correlationID,
|
|
})
|
|
return "команда выполнена для " + displayName + "."
|
|
}
|