Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/added-knowledge-advisor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Mid-task knowledge advisor (opt-in `knowledge.advisor`, default off): when a running agent's work enters a scope that was not on screen at kick time, the matching knowledge entries the kick did not already carry are typed into its session as one `📚 Knowledge:` line each, capped per kick (`knowledge.advisor_max_per_kick`), never during a tool call, with per-agent opt-out (`knowledge.advisor_exclude_agents`) and a `knowledge-advisor` prompt-history trigger for measurement (#17052)
8 changes: 8 additions & 0 deletions src/cmd/hive/agent_runtime_sidecar.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,14 @@ func (h *sidecarHost) SetSandboxMutationBoundary(boundary effects.Boundary) {
// the runtime's own process); trajectory events do not depend on it.
func (h *sidecarHost) SetSpanStarter(crux.SpanStarter) { h.inProcessOnly("SetSpanStarter") }

// SetKnowledgeAdviser is in-process-only in phase 1 of hivecommons/hive#17052:
// the adviser searches the knowledge store that lives in the hive process.
// A sidecar runtime runs without the mid-task advisor until a callback route
// carries the scope → advice exchange.
func (h *sidecarHost) SetKnowledgeAdviser(crux.KnowledgeAdviser) {
h.inProcessOnly("SetKnowledgeAdviser")
}

// SetInferenceRoute and ClearInferenceRoute are cruxhost.InferenceRouter:
// the callback's end of SetInferenceCallbacks. A route that arrives before
// boot has installed the closures is dropped and logged; the runtime's
Expand Down
137 changes: 137 additions & 0 deletions src/cmd/hive/knowledge_adviser.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package main

import (
"context"
"log/slog"
"strings"
"time"

"github.com/hivecommons/hive/crux"
"github.com/hivecommons/hive/pkg/config"
"github.com/hivecommons/hive/pkg/knowledge"
)

// Mid-task knowledge adviser (hivecommons/hive#17052): the hive side of the
// runtime's knowledge advisor. The runtime says which scope an agent just
// entered; this asks the same Primer the kick used, under the same
// knowledge.agent_scopes restriction, and hands back entries the kick did
// not already carry.

const (
// knowledgeAdviseTimeout bounds one adviser query. It runs on the agent's
// poll goroutine, so a slow wiki layer must not stall the poller.
knowledgeAdviseTimeout = 5 * time.Second
// knowledgeAdviseMaxPerScope caps how many entries one scope may queue;
// the runtime's per-kick cap is the real bound, this keeps the queue short.
knowledgeAdviseMaxPerScope = 2
// knowledgeAdviseSummaryRunes caps the body text handed to the runtime.
knowledgeAdviseSummaryRunes = 300
)

type knowledgeAdviser struct {
cfg func() *config.Config
primer func() *knowledge.Primer
primed func(agent string) []string
logger *slog.Logger
}

func newKnowledgeAdviser(b *boot) *knowledgeAdviser {
return &knowledgeAdviser{
cfg: func() *config.Config { return b.cfg },
primer: func() *knowledge.Primer {
if b.sched == nil {
return nil
}
return b.sched.GetPrimer()
},
primed: func(agent string) []string {
if b.sched == nil {
return nil
}
return b.sched.KickPrimedSlugs(agent)
},
logger: b.logger,
}
}

// Policy reads the live config every call so a dashboard change applies to
// the next poll tick without a restart, like the other host resolvers.
func (a *knowledgeAdviser) Policy(agent string) crux.KnowledgeAdvisorPolicy {
cfg := a.cfg()
if cfg == nil || !cfg.KnowledgeAdvisorEnabledFor(agent) {
return crux.KnowledgeAdvisorPolicy{}
}
return crux.KnowledgeAdvisorPolicy{Enabled: true, MaxPerKick: cfg.Knowledge.AdvisorMaxPerKick}
}

// Advise searches the knowledge store for scope. Until #17045 lands the
// Primer has no kick context for paths, so the observed file goes in as the
// primer's file path and the scope's segments as keywords.
func (a *knowledgeAdviser) Advise(agent string, scope crux.KnowledgeScope) []crux.KnowledgeAdvice {
primer := a.primer()
cfg := a.cfg()
if primer == nil || cfg == nil {
return nil
}
var paths []string
if scope.Path != "" {
paths = []string{scope.Path}
}
var agentScope *knowledge.TOCScope
if sc, ok := cfg.KnowledgeAgentScope(agent); ok {
s := knowledge.AgentScope(sc.Layers, sc.Repos, sc.Types, sc.Tags, sc.IncludeStates)
agentScope = &s
}
ctx, cancel := context.WithTimeout(context.Background(), knowledgeAdviseTimeout)
defer cancel()
primed := primer.PrimeScoped(ctx, agentScope, paths, scope.Keywords)
advice := selectKnowledgeAdvice(primed.Facts, a.primed(agent), knowledgeAdviseMaxPerScope)
a.logger.Debug("knowledge advisor: scope entered",
"agent", agent, "scope", scope.Key, "candidates", len(primed.Facts), "advice", len(advice))
return advice
}

// selectKnowledgeAdvice keeps the best-ranked facts not in exclude, up to
// limit, rendered for the runtime's one-line delivery.
func selectKnowledgeAdvice(facts []knowledge.Fact, exclude []string, limit int) []crux.KnowledgeAdvice {
skip := make(map[string]bool, len(exclude))
for _, slug := range exclude {
skip[slug] = true
}
var out []crux.KnowledgeAdvice
for _, f := range facts {
if f.Slug == "" || skip[f.Slug] || strings.TrimSpace(f.Title) == "" {
continue
}
skip[f.Slug] = true
out = append(out, crux.KnowledgeAdvice{
Slug: f.Slug,
Title: f.Title,
Summary: truncateRunes(strings.Join(strings.Fields(f.Body), " "), knowledgeAdviseSummaryRunes),
Ref: knowledgeAdviceRef(f),
})
if len(out) >= limit {
break
}
}
return out
}

// knowledgeAdviceRef is where the agent can read the whole entry: the first
// source document URL, else the knowledge entry id the dashboard serves.
func knowledgeAdviceRef(f knowledge.Fact) string {
for _, s := range f.Sources {
if s.DocURL != "" {
return s.DocURL
}
}
return "knowledge entry " + f.Slug
}

func truncateRunes(s string, n int) string {
r := []rune(s)
if len(r) <= n {
return s
}
return strings.TrimSpace(string(r[:n-1])) + "…"
}
83 changes: 83 additions & 0 deletions src/cmd/hive/knowledge_adviser_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package main

import (
"log/slog"
"reflect"
"strings"
"testing"

"github.com/hivecommons/hive/crux"
"github.com/hivecommons/hive/pkg/config"
"github.com/hivecommons/hive/pkg/knowledge"
)

func TestSelectKnowledgeAdvice(t *testing.T) {
facts := []knowledge.Fact{
{Slug: "primed", Title: "Already in the kick", Body: "x"},
{Slug: "", Title: "No slug", Body: "x"},
{Slug: "untitled", Title: " ", Body: "x"},
{Slug: "tree", Title: "Re-pin the tree", Body: "line one\n\n line two " + strings.Repeat("w", 400),
Sources: []knowledge.Source{{PR: "1"}, {DocURL: "https://wiki/tree"}}},
{Slug: "tree", Title: "Duplicate slug", Body: "x"},
{Slug: "third", Title: "Third", Body: "short"},
{Slug: "fourth", Title: "Fourth", Body: "never reached"},
}
got := selectKnowledgeAdvice(facts, []string{"primed"}, 2)
if len(got) != 2 {
t.Fatalf("got %d advice: %+v", len(got), got)
}
if got[0].Slug != "tree" || got[0].Title != "Re-pin the tree" || got[0].Ref != "https://wiki/tree" {
t.Errorf("first = %+v", got[0])
}
if !strings.HasPrefix(got[0].Summary, "line one line two w") || !strings.HasSuffix(got[0].Summary, "…") {
t.Errorf("summary = %q", got[0].Summary)
}
if n := len([]rune(got[0].Summary)); n > knowledgeAdviseSummaryRunes {
t.Errorf("summary is %d runes, cap %d", n, knowledgeAdviseSummaryRunes)
}
if got[1].Slug != "third" || got[1].Ref != "knowledge entry third" || got[1].Summary != "short" {
t.Errorf("second = %+v", got[1])
}
if selectKnowledgeAdvice(nil, nil, 2) != nil {
t.Error("no facts should yield nil")
}
}

func TestTruncateRunes(t *testing.T) {
if got := truncateRunes("héllo", 5); got != "héllo" {
t.Errorf("under cap = %q", got)
}
if got := truncateRunes("héllo wörld", 6); got != "héllo…" {
t.Errorf("over cap = %q", got)
}
}

func TestKnowledgeAdviserPolicy(t *testing.T) {
cfg := &config.Config{Knowledge: config.KnowledgeConfig{Enabled: true, Advisor: true, AdvisorMaxPerKick: 4}}
a := &knowledgeAdviser{cfg: func() *config.Config { return cfg }, logger: slog.Default()}
want := crux.KnowledgeAdvisorPolicy{Enabled: true, MaxPerKick: 4}
if got := a.Policy("developer"); !reflect.DeepEqual(got, want) {
t.Errorf("policy = %+v, want %+v", got, want)
}
cfg.Knowledge.Advisor = false
if got := a.Policy("developer"); got.Enabled {
t.Errorf("disabled policy = %+v", got)
}
a.cfg = func() *config.Config { return nil }
if got := a.Policy("developer"); got.Enabled {
t.Errorf("nil config policy = %+v", got)
}
}

func TestKnowledgeAdviserAdvise_NoPrimerIsSilent(t *testing.T) {
cfg := &config.Config{Knowledge: config.KnowledgeConfig{Enabled: true, Advisor: true}}
a := &knowledgeAdviser{
cfg: func() *config.Config { return cfg },
primer: func() *knowledge.Primer { return nil },
primed: func(string) []string { return nil },
logger: slog.Default(),
}
if got := a.Advise("developer", crux.KnowledgeScope{Key: "src/a", Path: "src/a/x.go"}); got != nil {
t.Errorf("advice without a primer = %+v", got)
}
}
5 changes: 5 additions & 0 deletions src/cmd/hive/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3919,6 +3919,11 @@ func (b *boot) bootWatchersWith(deps bootWatchersDeps) {
// per-agent "Prompts" tab. Redaction and truncation happen inside the
// store, before anything is written to the PVC.
b.agentMgr.SetRecordPromptCallback(b.dashSrv.RecordPrompt)
// Mid-task knowledge advisor (#17052): the runtime asks this when an
// agent's pane first shows a scope its kick did not cover. Policy is read
// off the live config per call, so knowledge.advisor flips without a
// restart; the adviser itself is a no-op until SetPrimer has run.
b.agentMgr.SetKnowledgeAdviser(newKnowledgeAdviser(b))

// Feed agent lifecycle events (start, stop, launch FAILURE, backend/model
// change) into the durable audit store behind the dashboard's Audit Log.
Expand Down
Loading
Loading