From f8b334f9f13cedd8e8f2f1b171decb55dcce9a9a Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Sat, 7 Nov 2026 13:48:45 -0500 Subject: [PATCH 1/2] =?UTF-8?q?=E2=9C=A8=20knowledge:=20scope=20block=20on?= =?UTF-8?q?=20entries=20and=20a=20kick-context=20filter=20in=20the=20Prime?= =?UTF-8?q?r?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A knowledge entry can now say where it applies with a frontmatter scope: block (paths, labels, lanes). FileStore parses it into Fact.Scope; Primer.PrimeForKick takes the kick's lane, issue labels and known file paths and keeps a scoped fact only when one dimension matches (OR), both in the ranked set and in graph expansion. Unscoped facts are unchanged. The scheduler passes the base lane name and the primed issues' labels; paths stay empty on the kick path. The count excluded is reported as PrimedKnowledge.ScopedOut and in the "knowledge primed" log line. Proposed by @gregoryhunt at the 2026-11-05 community meeting. Fixes #17045 Part of #17043 Signed-off-by: Andrew Anderson --- changelog.d/added-knowledge-entry-scope.md | 1 + src/docs/knowledge-toc.md | 38 +++ src/pkg/knowledge/filestore.go | 31 +++ src/pkg/knowledge/knowledge_coverage_test.go | 4 +- src/pkg/knowledge/primer.go | 26 ++- src/pkg/knowledge/scope.go | 168 ++++++++++++++ src/pkg/knowledge/scope_test.go | 229 +++++++++++++++++++ src/pkg/knowledge/types.go | 7 + src/pkg/scheduler/kick_priming.go | 24 +- src/pkg/scheduler/kick_priming_scope_test.go | 60 +++++ 10 files changed, 581 insertions(+), 7 deletions(-) create mode 100644 changelog.d/added-knowledge-entry-scope.md create mode 100644 src/pkg/knowledge/scope.go create mode 100644 src/pkg/knowledge/scope_test.go create mode 100644 src/pkg/scheduler/kick_priming_scope_test.go diff --git a/changelog.d/added-knowledge-entry-scope.md b/changelog.d/added-knowledge-entry-scope.md new file mode 100644 index 0000000000..9333086697 --- /dev/null +++ b/changelog.d/added-knowledge-entry-scope.md @@ -0,0 +1 @@ +- Knowledge entries can carry a `scope:` frontmatter block (`paths`, `labels`, `lanes`); the kick primer surfaces a scoped entry only when the kick's lane, issue labels or known file paths match, so repository facts are injected on demand instead of on every kick (#17045). diff --git a/src/docs/knowledge-toc.md b/src/docs/knowledge-toc.md index 7220103b09..a52711a170 100644 --- a/src/docs/knowledge-toc.md +++ b/src/docs/knowledge-toc.md @@ -106,6 +106,44 @@ only unless `include_states` is set), and returns: The dashboard Knowledge section has an **Effective knowledge** panel with an agent picker that renders both lists and each exclusion reason. +### Entry scope (`scope:` frontmatter) + +`knowledge.agent_scopes` says what an *agent* may see. An entry can also say +where *it* applies, with a `scope:` block in its frontmatter +(hivecommons/hive#17045): + +```yaml +--- +title: Editing src/scripts/ requires re-pinning TRUSTED_SCRIPTS_TREE +type: gotcha +layer: project +scope: + paths: [src/scripts/**, .github/scripts/integration-governance.cjs] + labels: [area/ci] + lanes: [] +--- +``` + +- `paths` are repo-relative globs (`**` matches any number of segments), + `labels` are issue labels and `lanes` are base agent names; `labels` and + `lanes` compare case-insensitively. Inline lists only — the frontmatter + parser is line-oriented and block lists (`- item`) inside `scope:` are + skipped. +- An entry **without** `scope:` behaves as before: keyword relevance plus the + agent's `knowledge.agent_scopes`. +- An entry **with** `scope:` is surfaced in a kick only when at least one + declared dimension matches the kick — its lane, a label on one of the primed + issues, or a file path the caller knows. Dimensions are OR-ed; a dimension the + kick cannot evaluate (file paths are not known on the kick path) simply does + not match. Related facts pulled in by graph expansion are gated the same way. +- The primer reports how many relevant entries the kick context excluded in the + `knowledge primed` log line (`scoped_out`) and in `PrimedKnowledge.ScopedOut`. + +The full read (`GET /api/knowledge/entry/{id}`) returns the entry's `scope` +inside `fact`, so an operator can see why an entry does or does not reach a +kick. The agent-level filter (`agent_scopes`) applies first; the entry's own +scope can only narrow further. + ### Prompt-size caps - `limit` defaults to 50 and is clamped to 200. diff --git a/src/pkg/knowledge/filestore.go b/src/pkg/knowledge/filestore.go index d2f7fac6a5..31afcd3a64 100644 --- a/src/pkg/knowledge/filestore.go +++ b/src/pkg/knowledge/filestore.go @@ -57,6 +57,7 @@ type filePage struct { Path string ModTime time.Time Embedding []float64 + Scope *FactScope // Lifecycle frontmatter (#11102); see resolveLifecycleState for defaults. State LifecycleState @@ -209,6 +210,9 @@ func (s *FileStore) reindex() { page.State = parsed.state page.Supersedes = parsed.supersedes page.SupersededBy = parsed.supersededBy + if !parsed.scope.IsZero() { + page.Scope = parsed.scope + } pages[slug] = page return nil @@ -496,6 +500,7 @@ type parsedObsidianFile struct { state LifecycleState supersedes string supersededBy string + scope *FactScope } var wikilinkRe = regexp.MustCompile(`\[\[([^\]|]+)(?:\|[^\]]+)?\]\]`) @@ -526,8 +531,33 @@ func parseObsidianFileDetailed(content string, fallbackTitle string) parsedObsid frontmatter := content[4 : 4+endIdx] parsed.body = strings.TrimSpace(content[4+endIdx+4:]) + // The parser is line-oriented and trims indentation, so a nested + // `scope:` block is recognised by state: once "scope:" is seen, the + // keys paths/labels/lanes belong to it until the next unrelated key. + inScope := false for _, line := range strings.Split(frontmatter, "\n") { line = strings.TrimSpace(line) + if line == "scope:" { + inScope = true + if parsed.scope == nil { + parsed.scope = &FactScope{} + } + continue + } + if inScope { + if consumed := parsed.scope.setFromLine(line); consumed { + continue + } + if strings.HasPrefix(line, "- ") || line == "" { + // Block-list items are not supported inside scope: + // (documented); skip them rather than let them leak + // into tags. + continue + } + if strings.Contains(line, ":") { + inScope = false + } + } if strings.HasPrefix(line, "title:") { parsed.title = strings.TrimSpace(strings.TrimPrefix(line, "title:")) parsed.title = strings.Trim(parsed.title, "\"'") @@ -644,6 +674,7 @@ func (p filePage) effectiveLayer() LayerType { // applyLifecycle copies the page's lifecycle and TOC metadata onto f, defaulting // legacy pages without a recorded state to approved. func (p filePage) applyLifecycle(f *Fact) { + f.Scope = p.Scope f.Supersedes = p.Supersedes f.SupersededBy = p.SupersededBy f.State = resolveLifecycleState(p.State, p.Status, p.SupersededBy) diff --git a/src/pkg/knowledge/knowledge_coverage_test.go b/src/pkg/knowledge/knowledge_coverage_test.go index b3403f1dcb..6c7fa69ba6 100644 --- a/src/pkg/knowledge/knowledge_coverage_test.go +++ b/src/pkg/knowledge/knowledge_coverage_test.go @@ -535,7 +535,7 @@ func TestPrimer_ExpandWithGraph(t *testing.T) { p.SetGraphStore(gs) facts := []Fact{{Slug: "seed", Title: "Seed Fact", Confidence: 0.9, Layer: LayerProject}} - expanded := p.expandWithGraph(facts, nil) + expanded := p.expandWithGraph(facts, nil, KickContext{}) if len(expanded) < 2 { t.Fatalf("expected graph expansion to add related fact, got %d facts", len(expanded)) } @@ -553,7 +553,7 @@ func TestPrimer_ExpandWithGraph(t *testing.T) { func TestPrimer_ExpandWithGraph_NoGraph(t *testing.T) { p := NewPrimer(nil, PrimerConfig{MaxFacts: 25}, covLogger()) facts := []Fact{{Slug: "a"}} - if got := p.expandWithGraph(facts, nil); len(got) != 1 { + if got := p.expandWithGraph(facts, nil, KickContext{}); len(got) != 1 { t.Errorf("expected passthrough without graph, got %d", len(got)) } } diff --git a/src/pkg/knowledge/primer.go b/src/pkg/knowledge/primer.go index ab6f43494f..f75c3eb2be 100644 --- a/src/pkg/knowledge/primer.go +++ b/src/pkg/knowledge/primer.go @@ -97,9 +97,20 @@ func (p *Primer) Prime(ctx context.Context, filePaths []string, keywords []strin // applied on top of the primer's lifecycle filter, so it can only narrow what // the agent is shown, and graph expansion never pulls in an out-of-scope fact. func (p *Primer) PrimeScoped(ctx context.Context, scope *TOCScope, filePaths []string, keywords []string) *PrimedKnowledge { + return p.PrimeForKick(ctx, scope, KickContext{Paths: filePaths}, keywords) +} + +// PrimeForKick is PrimeScoped with the kick's context (#17045): the lane, the +// labels of the issues being primed and, when the caller knows them, the file +// paths being touched. Facts that carry a `scope:` are kept only when the +// context matches one of its dimensions (FactScope.Admits); unscoped facts are +// selected by relevance exactly as before. kc.Paths also feed the search query, +// as filePaths did in PrimeScoped. The count of relevant facts the context +// excluded is reported in PrimedKnowledge.ScopedOut. +func (p *Primer) PrimeForKick(ctx context.Context, scope *TOCScope, kc KickContext, keywords []string) *PrimedKnowledge { start := time.Now() - query := buildQuery(filePaths, keywords) + query := buildQuery(kc.Paths, keywords) if query == "" { return &PrimedKnowledge{} } @@ -145,6 +156,7 @@ func (p *Primer) PrimeScoped(ctx context.Context, scope *TOCScope, filePaths []s if scope != nil { merged = scope.Filter(merged) } + merged, scopedOut := FilterByKickContext(merged, kc) reranked := p.rerankFisherRao(query, merged) prioritized := p.applyPriority(reranked) @@ -152,11 +164,12 @@ func (p *Primer) PrimeScoped(ctx context.Context, scope *TOCScope, filePaths []s prioritized = prioritized[:p.config.MaxFacts] } - prioritized = p.expandWithGraph(prioritized, scope) + prioritized = p.expandWithGraph(prioritized, scope, kc) elapsed := time.Since(start).Milliseconds() p.logger.Info("knowledge primed", "facts", len(prioritized), + "scoped_out", scopedOut, "http_layers", len(p.layers), "file_stores", len(p.fileStores), "graph", p.graphStore != nil, @@ -182,6 +195,7 @@ func (p *Primer) PrimeScoped(ctx context.Context, scope *TOCScope, filePaths []s Hints: hints, QueryTime: elapsed, MaxBytes: p.config.MaxBytes, + ScopedOut: scopedOut, } } @@ -275,8 +289,9 @@ const graphExpansionConfidenceDecay = 0.8 // expandWithGraph performs one-hop traversal from each primed fact's slug, // pulling in related facts that aren't already in the result set. A non-nil -// scope excludes related facts outside it. -func (p *Primer) expandWithGraph(facts []Fact, scope *TOCScope) []Fact { +// scope excludes related facts outside it, and a related fact's own `scope:` +// must admit the kick context. +func (p *Primer) expandWithGraph(facts []Fact, scope *TOCScope, kc KickContext) []Fact { if p.graphStore == nil || len(facts) == 0 { return facts } @@ -308,6 +323,9 @@ func (p *Primer) expandWithGraph(facts []Fact, scope *TOCScope) []Fact { if scope != nil && !scope.InScope(*relFact) { break } + if !relFact.Scope.Admits(kc) { + break + } relFact.Confidence *= graphExpansionConfidenceDecay expanded = append(expanded, *relFact) break diff --git a/src/pkg/knowledge/scope.go b/src/pkg/knowledge/scope.go new file mode 100644 index 0000000000..048e501162 --- /dev/null +++ b/src/pkg/knowledge/scope.go @@ -0,0 +1,168 @@ +package knowledge + +import ( + "path" + "strings" +) + +// FactScope says where a fact applies (hivecommons/hive#17045). It is the +// frontmatter `scope:` block of a knowledge entry: +// +// scope: +// paths: [src/scripts/**, .github/scripts/integration-governance.cjs] +// labels: [area/ci] +// lanes: [developer, reviewer] +// +// Each dimension is a list; an empty list places no constraint on that +// dimension. A fact with no scope at all applies everywhere and is selected by +// relevance alone, exactly as before scopes existed. +type FactScope struct { + // Paths are repo-relative globs; "**" matches any number of segments. + Paths []string `json:"paths,omitempty"` + // Labels are issue labels, compared case-insensitively. + Labels []string `json:"labels,omitempty"` + // Lanes are base agent / lane names, compared case-insensitively. + Lanes []string `json:"lanes,omitempty"` +} + +// IsZero reports whether the scope constrains nothing. +func (s *FactScope) IsZero() bool { + return s == nil || (len(s.Paths) == 0 && len(s.Labels) == 0 && len(s.Lanes) == 0) +} + +// KickContext is what the primer knows about the work a kick is for. The +// scheduler fills Lane and Labels from the lane name and the primed issues; +// Paths is filled only by callers that know which files are being touched. +type KickContext struct { + Lane string + Labels []string + Paths []string +} + +// IsZero reports whether the context carries nothing to match on. +func (kc KickContext) IsZero() bool { + return kc.Lane == "" && len(kc.Labels) == 0 && len(kc.Paths) == 0 +} + +// Admits reports whether a fact carrying scope s may be shown for kc. An +// unscoped fact is always admitted. A scoped fact is admitted when at least one +// declared dimension matches — the dimensions are OR-ed, so an entry scoped to +// both a path glob and a label surfaces for either trigger. A declared +// dimension the context knows nothing about (no paths at kick time, say) simply +// cannot match; it does not admit by default, because the point of a scope is +// that the fact is not paid for on every kick. +func (s *FactScope) Admits(kc KickContext) bool { + if s.IsZero() { + return true + } + if kc.Lane != "" && containsFold(s.Lanes, kc.Lane) { + return true + } + for _, l := range kc.Labels { + if containsFold(s.Labels, l) { + return true + } + } + for _, p := range kc.Paths { + for _, pattern := range s.Paths { + if scopeGlobMatch(pattern, p) { + return true + } + } + } + return false +} + +// FilterByKickContext drops facts whose scope does not admit kc and reports how +// many it dropped. Unscoped facts pass unchanged; a zero context drops every +// scoped fact. +func FilterByKickContext(facts []Fact, kc KickContext) ([]Fact, int) { + kept := facts[:0:0] + dropped := 0 + for _, f := range facts { + if f.Scope.Admits(kc) { + kept = append(kept, f) + continue + } + dropped++ + } + return kept, dropped +} + +// scopeGlobMatch matches a repo-relative path against a glob whose segments +// follow path.Match, with "**" matching zero or more whole segments. Both sides +// are normalised to forward slashes without a leading "./". +func scopeGlobMatch(pattern, p string) bool { + pattern = normaliseScopePath(pattern) + p = normaliseScopePath(p) + if pattern == "" || p == "" { + return false + } + return matchSegments(strings.Split(pattern, "/"), strings.Split(p, "/")) +} + +func normaliseScopePath(s string) string { + s = strings.ReplaceAll(strings.TrimSpace(s), "\\", "/") + s = strings.TrimPrefix(s, "./") + return strings.Trim(s, "/") +} + +func matchSegments(pattern, segs []string) bool { + for len(pattern) > 0 { + if pattern[0] == "**" { + // "**" at the end matches whatever remains, including nothing. + if len(pattern) == 1 { + return true + } + for i := 0; i <= len(segs); i++ { + if matchSegments(pattern[1:], segs[i:]) { + return true + } + } + return false + } + if len(segs) == 0 { + return false + } + if ok, err := path.Match(pattern[0], segs[0]); err != nil || !ok { + return false + } + pattern, segs = pattern[1:], segs[1:] + } + return len(segs) == 0 +} + +// parseScopeList parses the inline-list value of one scope key ("[a, b]" or a +// bare "a, b"); entries are trimmed and unquoted, empties dropped. +func parseScopeList(value string) []string { + value = strings.TrimSpace(value) + value = strings.TrimSuffix(strings.TrimPrefix(value, "["), "]") + var out []string + for _, item := range strings.Split(value, ",") { + item = strings.Trim(strings.TrimSpace(item), "\"'") + if item != "" { + out = append(out, item) + } + } + return out +} + +// setFromLine applies one trimmed frontmatter line inside a `scope:` block and +// reports whether the line was a scope key. +func (s *FactScope) setFromLine(line string) bool { + key, value, ok := strings.Cut(line, ":") + if !ok { + return false + } + switch strings.TrimSpace(key) { + case "paths": + s.Paths = parseScopeList(value) + case "labels": + s.Labels = parseScopeList(value) + case "lanes": + s.Lanes = parseScopeList(value) + default: + return false + } + return true +} diff --git a/src/pkg/knowledge/scope_test.go b/src/pkg/knowledge/scope_test.go new file mode 100644 index 0000000000..87f7d1050c --- /dev/null +++ b/src/pkg/knowledge/scope_test.go @@ -0,0 +1,229 @@ +package knowledge + +import ( + "io" + "log/slog" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestScopeGlobMatch(t *testing.T) { + tests := []struct { + pattern, path string + want bool + }{ + {"src/scripts/**", "src/scripts/check.sh", true}, + {"src/scripts/**", "src/scripts/sub/deep.sh", true}, + {"src/scripts/**", "src/scripts", true}, + {"src/scripts/**", "src/script.go", false}, + {"src/**/*.go", "src/pkg/knowledge/primer.go", true}, + {"src/**/*.go", "src/main.go", true}, + {"src/**/*.go", "src/pkg/knowledge/README.md", false}, + {"**/server.go", "src/pkg/hub/server.go", true}, + {"**/server.go", "server.go", true}, + {".github/scripts/integration-governance.cjs", ".github/scripts/integration-governance.cjs", true}, + {".github/scripts/integration-governance.cjs", ".github/scripts/other.cjs", false}, + {"./src/go.work", "src/go.work", true}, + {"src/go.work", "./src/go.work/", true}, + {"", "src/x", false}, + {"src/**", "", false}, + } + for _, tc := range tests { + if got := scopeGlobMatch(tc.pattern, tc.path); got != tc.want { + t.Errorf("scopeGlobMatch(%q, %q) = %v, want %v", tc.pattern, tc.path, got, tc.want) + } + } +} + +func TestFactScopeAdmits(t *testing.T) { + scoped := &FactScope{ + Paths: []string{"src/scripts/**"}, + Labels: []string{"area/ci"}, + Lanes: []string{"reviewer"}, + } + tests := []struct { + name string + scope *FactScope + kc KickContext + want bool + }{ + {"nil scope admits anything", nil, KickContext{}, true}, + {"empty scope admits anything", &FactScope{}, KickContext{Lane: "x"}, true}, + {"scoped fact, empty context", scoped, KickContext{}, false}, + {"lane match, case-insensitive", scoped, KickContext{Lane: "Reviewer"}, true}, + {"lane mismatch", scoped, KickContext{Lane: "developer"}, false}, + {"label match among others", scoped, KickContext{Labels: []string{"kind/bug", "AREA/CI"}}, true}, + {"label mismatch", scoped, KickContext{Labels: []string{"kind/bug"}}, false}, + {"path match", scoped, KickContext{Paths: []string{"src/scripts/x.sh"}}, true}, + {"path mismatch", scoped, KickContext{Paths: []string{"src/pkg/x.go"}}, false}, + {"dimensions are OR-ed", scoped, KickContext{Lane: "developer", Labels: []string{"area/ci"}}, true}, + {"paths-only scope cannot match a lane", &FactScope{Paths: []string{"src/**"}}, KickContext{Lane: "reviewer"}, false}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := tc.scope.Admits(tc.kc); got != tc.want { + t.Fatalf("Admits = %v, want %v", got, tc.want) + } + }) + } +} + +func TestFilterByKickContext(t *testing.T) { + facts := []Fact{ + {Slug: "open"}, + {Slug: "ci", Scope: &FactScope{Labels: []string{"area/ci"}}}, + {Slug: "scripts", Scope: &FactScope{Paths: []string{"src/scripts/**"}}}, + } + tests := []struct { + name string + kc KickContext + wantSlugs []string + wantDropped int + }{ + {"zero context keeps only unscoped", KickContext{}, []string{"open"}, 2}, + {"label admits the ci fact", KickContext{Labels: []string{"area/ci"}}, []string{"open", "ci"}, 1}, + {"paths admit the scripts fact", KickContext{Paths: []string{"src/scripts/a.sh"}}, []string{"open", "scripts"}, 1}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + kept, dropped := FilterByKickContext(facts, tc.kc) + if dropped != tc.wantDropped { + t.Fatalf("dropped = %d, want %d", dropped, tc.wantDropped) + } + var slugs []string + for _, f := range kept { + slugs = append(slugs, f.Slug) + } + if strings.Join(slugs, ",") != strings.Join(tc.wantSlugs, ",") { + t.Fatalf("kept = %v, want %v", slugs, tc.wantSlugs) + } + }) + } +} + +func TestParseObsidianFile_ScopeBlock(t *testing.T) { + tests := []struct { + name string + content string + wantScope *FactScope + wantTags []string + }{ + { + name: "inline lists, keys after scope still parsed", + content: "---\ntitle: T\nscope:\n paths: [src/scripts/**, .github/x.cjs]\n labels: ['area/ci']\n lanes: [reviewer]\ntags: [repo:org/name, ci]\n---\nbody", + wantScope: &FactScope{ + Paths: []string{"src/scripts/**", ".github/x.cjs"}, + Labels: []string{"area/ci"}, + Lanes: []string{"reviewer"}, + }, + wantTags: []string{"repo:org/name", "ci"}, + }, + { + name: "no scope block", + content: "---\ntitle: T\ntags: [a]\n---\nbody", + wantScope: nil, + wantTags: []string{"a"}, + }, + { + name: "all-empty scope collapses to nil", + content: "---\nscope:\n paths: []\n labels: []\n lanes: []\n---\nbody", + wantScope: nil, + }, + { + name: "block list items inside scope do not leak into tags", + content: "---\ntags: [a]\nscope:\n paths:\n - src/x\n lanes: [dev]\n---\nbody", + wantScope: &FactScope{Lanes: []string{"dev"}}, + wantTags: []string{"a"}, + }, + { + name: "scope keys outside a scope block are ignored", + content: "---\npaths: [src/x]\nlanes: [dev]\n---\nbody", + wantScope: nil, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + parsed := parseObsidianFileDetailed(tc.content, "fallback") + got := parsed.scope + if got.IsZero() { + got = nil + } + if (got == nil) != (tc.wantScope == nil) { + t.Fatalf("scope = %+v, want %+v", got, tc.wantScope) + } + if got != nil { + if strings.Join(got.Paths, "|") != strings.Join(tc.wantScope.Paths, "|") || + strings.Join(got.Labels, "|") != strings.Join(tc.wantScope.Labels, "|") || + strings.Join(got.Lanes, "|") != strings.Join(tc.wantScope.Lanes, "|") { + t.Fatalf("scope = %+v, want %+v", got, tc.wantScope) + } + } + if strings.Join(parsed.tags, "|") != strings.Join(tc.wantTags, "|") { + t.Fatalf("tags = %v, want %v", parsed.tags, tc.wantTags) + } + }) + } +} + +func TestPrimeForKick_ScopedEntries(t *testing.T) { + dir := t.TempDir() + write := func(name, content string) { + t.Helper() + if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + write("repin.md", "---\ntitle: Repin trusted scripts tree\ntype: gotcha\nlayer: project\nscope:\n paths: [src/scripts/**]\n labels: [area/ci]\n---\nEditing src/scripts requires a repin of the trusted scripts tree.") + write("workspace.md", "---\ntitle: Two-module workspace for scripts\ntype: reference\nlayer: project\n---\nsrc is a two-module Go workspace; scripts live beside it.") + + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + store, err := NewFileStore(dir, "repo-knowledge", logger) + if err != nil { + t.Fatal(err) + } + p := NewPrimer(nil, PrimerConfig{}, logger) + p.AddFileStore("repo-knowledge", store, LayerProject) + + keywords := []string{"scripts", "trusted", "repin", "workspace"} + has := func(pk *PrimedKnowledge, slug string) bool { + for _, f := range pk.Facts { + if f.Slug == slug { + return true + } + } + return false + } + + tests := []struct { + name string + kc KickContext + wantRepin bool + wantScopedOut int + }{ + {"kick without matching context hides the scoped entry", KickContext{Lane: "developer"}, false, 1}, + {"label admits it", KickContext{Lane: "developer", Labels: []string{"area/ci"}}, true, 0}, + {"path admits it", KickContext{Paths: []string{"src/scripts/x.sh"}}, true, 0}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + pk := p.PrimeForKick(t.Context(), nil, tc.kc, keywords) + if !has(pk, "workspace") { + t.Fatalf("unscoped entry must always be primed; got %+v", pk.Facts) + } + if has(pk, "repin") != tc.wantRepin { + t.Fatalf("repin primed = %v, want %v", !tc.wantRepin, tc.wantRepin) + } + if pk.ScopedOut != tc.wantScopedOut { + t.Fatalf("ScopedOut = %d, want %d", pk.ScopedOut, tc.wantScopedOut) + } + }) + } + + // PrimeScoped's file paths double as the kick's paths. + pk := p.PrimeScoped(t.Context(), nil, []string{"src/scripts/x.sh"}, keywords) + if !has(pk, "repin") { + t.Fatalf("PrimeScoped with a matching file path should admit the scoped entry; got %+v", pk.Facts) + } +} diff --git a/src/pkg/knowledge/types.go b/src/pkg/knowledge/types.go index d704ccfd9e..a084dc97e6 100644 --- a/src/pkg/knowledge/types.go +++ b/src/pkg/knowledge/types.go @@ -281,6 +281,10 @@ type Fact struct { SupersededBy string `json:"superseded_by,omitempty"` Phase FactPhase `json:"phase,omitempty"` + // Scope says where the fact applies (the entry's `scope:` block, + // #17045). Nil means everywhere; see FactScope.Admits. + Scope *FactScope `json:"scope,omitempty"` + // Updated, BodySize and Origin feed the table of contents (#11103). They // are populated by file-backed stores only and never serialized, so // existing fact payloads are unchanged. @@ -310,6 +314,9 @@ type PrimedKnowledge struct { // rendered is the slugs Render kept, in render order, for the mid-task // advisor's "never repeat what the kick carried" rule (#17052). rendered []string + // ScopedOut counts relevant facts the kick context excluded because their + // scope (paths, labels, lanes) did not match (#17045). + ScopedOut int `json:"-"` } // RenderedSlugs returns the slugs of the facts the last Render kept — the diff --git a/src/pkg/scheduler/kick_priming.go b/src/pkg/scheduler/kick_priming.go index b8f4b90ccf..527d6fec09 100644 --- a/src/pkg/scheduler/kick_priming.go +++ b/src/pkg/scheduler/kick_priming.go @@ -8,6 +8,7 @@ import ( "github.com/hivecommons/hive/crux/agentsmd" "github.com/hivecommons/hive/crux/skillreg" + "github.com/hivecommons/hive/pkg/config" "github.com/hivecommons/hive/pkg/github" "github.com/hivecommons/hive/pkg/knowledge" ) @@ -303,7 +304,7 @@ func (s *Scheduler) primeKnowledgeStats(agentName string, issues []github.Issue) agentScope := knowledge.AgentScope(sc.Layers, sc.Repos, sc.Types, sc.Tags, sc.IncludeStates) scope = &agentScope } - primed := primer.PrimeScoped(context.Background(), scope, nil, keywords) + primed := primer.PrimeForKick(context.Background(), scope, kickContextFor(cfg, agentName, issues[:limit]), keywords) result, omitted := primed.Render() s.primedSlugs.Store(agentName, primed.RenderedSlugs()) inj := knowledgeInjection{ @@ -373,6 +374,27 @@ func (s *Scheduler) KickPrimedSlugs(agentName string) []string { return slugs } +// kickContextFor is the kick context a scoped knowledge entry is matched +// against (#17045): the base lane name (a replica resolves to the agent it +// replicates) and the union of the primed issues' labels. File paths are not +// known on the kick path, so entries scoped by paths alone wait for a caller +// that has them. +func kickContextFor(cfg *config.Config, agentName string, issues []github.Issue) knowledge.KickContext { + kc := knowledge.KickContext{Lane: cfg.BaseAgentName(agentName)} + seen := make(map[string]bool) + for _, issue := range issues { + for _, label := range issue.Labels { + lower := strings.ToLower(strings.TrimSpace(label)) + if lower == "" || seen[lower] { + continue + } + seen[lower] = true + kc.Labels = append(kc.Labels, lower) + } + } + return kc +} + // extractKeywords pulls searchable terms from issue labels and titles. // Title words are included because labels alone are often all noise // (triage/accepted, kind/bug) and produce zero keywords after filtering. diff --git a/src/pkg/scheduler/kick_priming_scope_test.go b/src/pkg/scheduler/kick_priming_scope_test.go new file mode 100644 index 0000000000..2f2f1dc2b4 --- /dev/null +++ b/src/pkg/scheduler/kick_priming_scope_test.go @@ -0,0 +1,60 @@ +package scheduler + +import ( + "strings" + "testing" + + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/github" +) + +func TestKickContextFor(t *testing.T) { + cfg := &config.Config{Agents: map[string]config.AgentConfig{ + "developer": {}, + "developer-2": {ReplicaOf: "developer"}, + }} + tests := []struct { + name string + cfg *config.Config + agent string + issues []github.Issue + wantLane string + wantLabels string + }{ + { + name: "lane and de-duplicated lower-cased labels", + cfg: cfg, + agent: "developer", + issues: []github.Issue{{Labels: []string{"Area/CI", "kind/bug"}}, {Labels: []string{"area/ci", " docs "}}}, + wantLane: "developer", + wantLabels: "area/ci,kind/bug,docs", + }, + { + name: "replica resolves to its base lane", + cfg: cfg, + agent: "developer-2", + issues: nil, + wantLane: "developer", + }, + { + name: "nil config keeps the agent name", + cfg: nil, + agent: "reviewer", + wantLane: "reviewer", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + kc := kickContextFor(tc.cfg, tc.agent, tc.issues) + if kc.Lane != tc.wantLane { + t.Fatalf("Lane = %q, want %q", kc.Lane, tc.wantLane) + } + if got := strings.Join(kc.Labels, ","); got != tc.wantLabels { + t.Fatalf("Labels = %q, want %q", got, tc.wantLabels) + } + if len(kc.Paths) != 0 { + t.Fatalf("Paths must stay empty on the kick path, got %v", kc.Paths) + } + }) + } +} From 18df130e75e0cd8ec6536a2fd1588c969ebed828 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Sat, 7 Nov 2026 13:54:24 -0500 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=8C=B1=20test:=20Agents=20lives=20in?= =?UTF-8?q?=20the=20embedded=20AgentRuntimeConfig?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andrew Anderson --- src/pkg/scheduler/kick_priming_scope_test.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/pkg/scheduler/kick_priming_scope_test.go b/src/pkg/scheduler/kick_priming_scope_test.go index 2f2f1dc2b4..27801be448 100644 --- a/src/pkg/scheduler/kick_priming_scope_test.go +++ b/src/pkg/scheduler/kick_priming_scope_test.go @@ -9,9 +9,11 @@ import ( ) func TestKickContextFor(t *testing.T) { - cfg := &config.Config{Agents: map[string]config.AgentConfig{ - "developer": {}, - "developer-2": {ReplicaOf: "developer"}, + cfg := &config.Config{AgentRuntimeConfig: config.AgentRuntimeConfig{ + Agents: map[string]config.AgentConfig{ + "developer": {}, + "developer-2": {ReplicaOf: "developer"}, + }, }} tests := []struct { name string