Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db00644cab | ||
|
|
125c99bb46 | ||
|
|
3e537bd582 | ||
|
|
4e6fc7aeee | ||
|
|
9a232ad444 | ||
|
|
3da0eca9b4 |
@@ -32,6 +32,7 @@ import (
|
||||
"github.com/mathiasbq/hyperguild/ingestion/internal/pipeline"
|
||||
"github.com/mathiasbq/hyperguild/ingestion/internal/reranker"
|
||||
"github.com/mathiasbq/hyperguild/ingestion/internal/search"
|
||||
"github.com/mathiasbq/hyperguild/ingestion/internal/startupretry"
|
||||
"github.com/mathiasbq/hyperguild/ingestion/internal/vectorstore"
|
||||
"github.com/mathiasbq/hyperguild/ingestion/internal/watcher"
|
||||
"github.com/mathiasbq/hyperguild/ingestion/internal/webhook"
|
||||
@@ -314,6 +315,36 @@ func main() {
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Built before the watcher, the graph backfill and session ingestion, and
|
||||
// retried rather than fatal (#83). Two separate reasons:
|
||||
//
|
||||
// - On a cold cluster boot this pod can beat dex to serving and gets a
|
||||
// 502 from ingress. Nothing is misconfigured; it simply started first.
|
||||
// Exiting there meant CrashLoopBackOff redoing the backfill on every
|
||||
// attempt, with exponential backoff stretching the brain outage.
|
||||
// - Constructing it first means a genuine config error (wrong issuer,
|
||||
// bad audience) fails in seconds instead of after all that work.
|
||||
//
|
||||
// The budget stays bounded: retrying forever would turn a misconfiguration
|
||||
// into a process that looks alive and never serves.
|
||||
jwtValidator, err := startupretry.Do(ctx,
|
||||
startupretry.Policy{Attempts: 8, Base: time.Second, Max: 30 * time.Second},
|
||||
func(ctx context.Context) (*chassisauth.JWTValidator, error) {
|
||||
v, err := chassisauth.NewJWTValidator(ctx, os.Getenv("DEX_ISSUER_URL"), os.Getenv("MCP_AUDIENCE"))
|
||||
if err != nil {
|
||||
logger.Warn("oidc discovery not ready, retrying", "err", err)
|
||||
}
|
||||
return v, err
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("build jwt validator", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if jwtValidator != nil {
|
||||
logger.Info("jwt auth enabled", "issuer", os.Getenv("DEX_ISSUER_URL"))
|
||||
}
|
||||
|
||||
if watchInterval > 0 {
|
||||
watcher.Start(ctx, watcher.Config{
|
||||
BrainDir: brainDir,
|
||||
@@ -418,15 +449,6 @@ func main() {
|
||||
if webhookHandler != nil {
|
||||
mux.Handle("POST /webhooks/brain-sync", webhookHandler)
|
||||
}
|
||||
jwtValidator, err := chassisauth.NewJWTValidator(ctx, os.Getenv("DEX_ISSUER_URL"), os.Getenv("MCP_AUDIENCE"))
|
||||
if err != nil {
|
||||
logger.Error("build jwt validator", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if jwtValidator != nil {
|
||||
logger.Info("jwt auth enabled", "issuer", os.Getenv("DEX_ISSUER_URL"))
|
||||
}
|
||||
|
||||
// Resource-metadata URL is only emitted on 401 when Dex OAuth is
|
||||
// configured. Static-Bearer-only deployments leave this empty so
|
||||
// clients never see an OAuth challenge.
|
||||
|
||||
@@ -83,7 +83,7 @@ func (s *Service) Capture(ctx context.Context, in CaptureInput) (CaptureReceipt,
|
||||
declared, _ = classification.ParseLevel(in.Context.Classification)
|
||||
}
|
||||
|
||||
effective, securityEvents := s.resolveClassification(declared, in)
|
||||
effective, securityEvents, escalators := s.resolveClassification(declared, in)
|
||||
|
||||
// Server-derived origin governs the I1 gate; a caller-asserted harness
|
||||
// label that names a different zone is descriptive-only and logged as a
|
||||
@@ -107,8 +107,8 @@ func (s *Service) Capture(ctx context.Context, in CaptureInput) (CaptureReceipt,
|
||||
Items: nil, // refused before any write
|
||||
SecurityEvents: append(securityEvents, "I1 refusal: confidential capture via us-nexus origin"),
|
||||
}, AuditCentral)
|
||||
return CaptureReceipt{}, fmt.Errorf("%w: effective classification confidential through %s origin",
|
||||
ErrSovereigntyRefused, in.Context.Origin)
|
||||
return CaptureReceipt{}, fmt.Errorf("%w: effective classification confidential through %s origin (%s)",
|
||||
ErrSovereigntyRefused, in.Context.Origin, escalationReason(escalators))
|
||||
}
|
||||
|
||||
receipt := CaptureReceipt{
|
||||
@@ -221,15 +221,28 @@ func (s *Service) validate(in CaptureInput) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// resolveClassification computes the effective level (stricter of
|
||||
// declared and every target's derived level) and collects a security
|
||||
// event whenever the caller under-declared relative to a target floor.
|
||||
func (s *Service) resolveClassification(declared classification.Level, in CaptureInput) (classification.Level, []string) {
|
||||
// resolveClassification computes the effective level (stricter of declared
|
||||
// and every target's derived level), collects a security event whenever the
|
||||
// caller under-declared relative to a target floor, and names the targets
|
||||
// that carry the strictest level.
|
||||
//
|
||||
// That third return is what makes an I1 refusal actionable. A caller sending
|
||||
// twenty tickets gets one refusal; without the offending target it cannot
|
||||
// tell which repo tripped the gate, and infra#265 shows what happens next —
|
||||
// the caller concluded the tickets ARRAY was broken, built a fallback of
|
||||
// twenty individual calls, and filed a bug against the wrong thing.
|
||||
func (s *Service) resolveClassification(declared classification.Level, in CaptureInput) (classification.Level, []string, []string) {
|
||||
effective := declared
|
||||
var events []string
|
||||
derivedFor := map[string]classification.Level{}
|
||||
var order []string
|
||||
consider := func(kind classification.TargetKind, name string) {
|
||||
derived := s.policy.Derive(classification.Target{Kind: kind, Name: name})
|
||||
effective = classification.Stricter(effective, derived)
|
||||
if _, seen := derivedFor[name]; !seen {
|
||||
derivedFor[name] = derived
|
||||
order = append(order, name)
|
||||
}
|
||||
if declared < derived {
|
||||
events = append(events, fmt.Sprintf("classification under-declared: declared=%s target=%s(%s) derived=%s",
|
||||
declared, name, kindString(kind), derived))
|
||||
@@ -241,7 +254,28 @@ func (s *Service) resolveClassification(declared classification.Level, in Captur
|
||||
for _, tk := range in.Tickets {
|
||||
consider(classification.RepoTarget, tk.Repo)
|
||||
}
|
||||
return effective, events
|
||||
|
||||
// Only targets that actually reach the effective level are named: at
|
||||
// twenty tickets, listing the innocent ones is noise that hides the one
|
||||
// that matters.
|
||||
var escalators []string
|
||||
for _, name := range order {
|
||||
if derivedFor[name] == effective && effective > declared {
|
||||
escalators = append(escalators, name)
|
||||
}
|
||||
}
|
||||
return effective, events, escalators
|
||||
}
|
||||
|
||||
// escalationReason renders why the effective classification landed where it
|
||||
// did, for an operator reading a refusal. Naming the caller's own declaration
|
||||
// matters as much as naming a target: "you asked for this" and "a repo you
|
||||
// touched required it" call for different fixes.
|
||||
func escalationReason(escalators []string) string {
|
||||
if len(escalators) == 0 {
|
||||
return "declared by the caller; no target required it"
|
||||
}
|
||||
return "required by: " + strings.Join(escalators, ", ")
|
||||
}
|
||||
|
||||
func (s *Service) persistInsight(ctx context.Context, ins Insight) (InsightResult, string, error) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package capture
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -59,12 +60,18 @@ type fakeTracker struct {
|
||||
closed []int
|
||||
comments []int
|
||||
err error
|
||||
// failOnTitle makes CreateIssue fail for one specific title, so a
|
||||
// partial-failure receipt can be exercised without failing every item.
|
||||
failOnTitle string
|
||||
}
|
||||
|
||||
func (f *fakeTracker) CreateIssue(_ context.Context, repo, title, _ string) (IssueRef, error) {
|
||||
if f.err != nil {
|
||||
return IssueRef{}, f.err
|
||||
}
|
||||
if f.failOnTitle != "" && title == f.failOnTitle {
|
||||
return IssueRef{}, errors.New("tracker refused this one")
|
||||
}
|
||||
f.created = append(f.created, repo+":"+title)
|
||||
return IssueRef{Repo: repo, Number: 100 + len(f.created), URL: "https://git/" + repo + "/issues/x"}, nil
|
||||
}
|
||||
@@ -87,7 +94,9 @@ func (f *fakeTracker) CommentIssue(_ context.Context, repo string, number int, _
|
||||
|
||||
// fakePolicy derives from an explicit map; default Internal so tests pin
|
||||
// behaviour without depending on the real defaulting.
|
||||
type fakePolicy struct{ tags map[string]classification.Level }
|
||||
type fakePolicy struct {
|
||||
tags map[string]classification.Level
|
||||
}
|
||||
|
||||
func (p fakePolicy) Derive(t classification.Target) classification.Level {
|
||||
if lvl, ok := p.tags[t.Name]; ok {
|
||||
@@ -434,3 +443,98 @@ func TestCaptureDryRunSkipsAuditGate(t *testing.T) {
|
||||
assert.True(t, rec.DryRun)
|
||||
assert.Empty(t, au.entries)
|
||||
}
|
||||
|
||||
// ---- hyperguild#91 part 1 -------------------------------------------------
|
||||
//
|
||||
// The reported symptom was "capture with a tickets array fails" (infra#265:
|
||||
// 20 tickets errored, 5 errored, caller fell back to 20 individual
|
||||
// issue_create calls). The array was never the failing dimension — every
|
||||
// ticket targeted a client repo, and the I1 gate refuses that through a
|
||||
// us-nexus origin at ANY length. The refusal did not say which target
|
||||
// escalated the classification, so it read as a malfunction.
|
||||
|
||||
func TestCapture_TicketsArrayWorksAtLengthOne(t *testing.T) {
|
||||
b, tr, au := &fakeBrain{}, &fakeTracker{}, &fakeAudit{}
|
||||
svc := newSvc(b, tr, fakePolicy{}, au)
|
||||
|
||||
rec, err := svc.Capture(context.Background(), CaptureInput{
|
||||
Context: baseCtx(),
|
||||
Tickets: []Ticket{{Repo: "hyperguild", Action: "create", Title: "one", Body: "b"}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, rec.Tickets, 1)
|
||||
assert.True(t, rec.Tickets[0].OK)
|
||||
assert.Len(t, tr.created, 1)
|
||||
assert.Empty(t, rec.Errors)
|
||||
}
|
||||
|
||||
func TestCapture_TicketsArrayWorksAtLengthMany(t *testing.T) {
|
||||
b, tr, au := &fakeBrain{}, &fakeTracker{}, &fakeAudit{}
|
||||
svc := newSvc(b, tr, fakePolicy{}, au)
|
||||
|
||||
in := CaptureInput{Context: baseCtx()}
|
||||
for i := range 20 {
|
||||
in.Tickets = append(in.Tickets, Ticket{
|
||||
Repo: "hyperguild", Action: "create", Title: fmt.Sprintf("t%02d", i), Body: "b",
|
||||
})
|
||||
}
|
||||
|
||||
rec, err := svc.Capture(context.Background(), in)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, rec.Tickets, 20, "one receipt entry per ticket")
|
||||
for i, r := range rec.Tickets {
|
||||
assert.True(t, r.OK, "ticket %d failed: %+v", i, rec.Errors)
|
||||
}
|
||||
assert.Len(t, tr.created, 20)
|
||||
assert.Empty(t, rec.Errors)
|
||||
}
|
||||
|
||||
func TestCapture_OneFailingTicketDoesNotSinkTheRest(t *testing.T) {
|
||||
// infra#265 asked explicitly: "if ticket 3 of 5 fails, what happened to
|
||||
// 1 and 2?" They land, and the receipt says so per item.
|
||||
b, au := &fakeBrain{}, &fakeAudit{}
|
||||
tr := &fakeTracker{failOnTitle: "boom"}
|
||||
svc := newSvc(b, tr, fakePolicy{}, au)
|
||||
|
||||
rec, err := svc.Capture(context.Background(), CaptureInput{
|
||||
Context: baseCtx(),
|
||||
Tickets: []Ticket{
|
||||
{Repo: "hyperguild", Action: "create", Title: "ok-1", Body: "b"},
|
||||
{Repo: "hyperguild", Action: "create", Title: "boom", Body: "b"},
|
||||
{Repo: "hyperguild", Action: "create", Title: "ok-3", Body: "b"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err, "a per-item failure is a partial receipt, not a call error")
|
||||
require.Len(t, rec.Tickets, 3)
|
||||
assert.True(t, rec.Tickets[0].OK)
|
||||
assert.False(t, rec.Tickets[1].OK)
|
||||
assert.True(t, rec.Tickets[2].OK)
|
||||
require.Len(t, rec.Errors, 1)
|
||||
assert.Contains(t, rec.Errors[0].Item, "ticket[1]")
|
||||
}
|
||||
|
||||
func TestCapture_I1RefusalNamesWhatEscalatedTheClassification(t *testing.T) {
|
||||
// The actual defect behind infra#265. Without the offending target in
|
||||
// the message, a caller with 20 tickets cannot tell which repo tripped
|
||||
// the gate — and reasonably concludes the array itself is broken.
|
||||
b, tr, au := &fakeBrain{}, &fakeTracker{}, &fakeAudit{}
|
||||
pol := fakePolicy{tags: map[string]classification.Level{"trucker-ecommerce": classification.Confidential}}
|
||||
svc := newSvc(b, tr, pol, au)
|
||||
|
||||
ctx := baseCtx()
|
||||
ctx.Origin = ZoneUSNexus
|
||||
_, err := svc.Capture(context.Background(), CaptureInput{
|
||||
Context: ctx,
|
||||
Tickets: []Ticket{
|
||||
{Repo: "hyperguild", Action: "create", Title: "fine", Body: "b"},
|
||||
{Repo: "trucker-ecommerce", Action: "create", Title: "client work", Body: "b"},
|
||||
},
|
||||
})
|
||||
|
||||
require.ErrorIs(t, err, ErrSovereigntyRefused)
|
||||
assert.Contains(t, err.Error(), "trucker-ecommerce",
|
||||
"the refusal must name the target that escalated the classification")
|
||||
assert.NotContains(t, err.Error(), "hyperguild",
|
||||
"only the offending target, or the message is noise at 20 tickets")
|
||||
assert.Empty(t, tr.created, "refused before any write")
|
||||
}
|
||||
|
||||
@@ -101,21 +101,23 @@ func quoteScalars(block []byte) []byte {
|
||||
return []byte(strings.Join(lines, "\n"))
|
||||
}
|
||||
|
||||
// needsQuoting reports whether a scalar value must be quoted to parse as the
|
||||
// string it plainly is. Only the colon case is handled: it is the one this
|
||||
// package exists for, and every other special case risks rewriting a value
|
||||
// that was deliberately structured (a nested mapping, an anchor, a number).
|
||||
// needsQuoting reports whether a scalar value has to be quoted to load as the
|
||||
// string it plainly is.
|
||||
//
|
||||
// The test is YAML's own parser rather than a pattern: ask whether the value
|
||||
// stands alone as the right-hand side of a mapping. Heuristics get this wrong
|
||||
// in both directions — `title: "Foo" — bar` opens with a quote but is not
|
||||
// quoted, and a value may contain a colon inside quotes and be perfectly fine.
|
||||
//
|
||||
// Anything that already parses is left alone, whatever it parses into — a flow
|
||||
// collection, a number, a bool. It is not broken, and quoting would change its
|
||||
// type.
|
||||
func needsQuoting(value string) bool {
|
||||
if strings.HasPrefix(value, "'") || strings.HasPrefix(value, `"`) {
|
||||
return false
|
||||
}
|
||||
if strings.HasPrefix(value, "|") || strings.HasPrefix(value, ">") {
|
||||
return false // block scalar; its content is not parsed as YAML
|
||||
}
|
||||
if strings.HasPrefix(value, "{") || strings.HasPrefix(value, "[") {
|
||||
return false // flow collection; quoting would silently make it a string
|
||||
}
|
||||
return strings.Contains(value, ": ") || strings.HasSuffix(value, ":")
|
||||
var probe map[string]any
|
||||
return yaml.Unmarshal([]byte("v: "+value+"\n"), &probe) != nil
|
||||
}
|
||||
|
||||
// block returns the raw YAML between the opening and closing fences.
|
||||
|
||||
@@ -90,6 +90,17 @@ func TestFix(t *testing.T) {
|
||||
wantKey: "title",
|
||||
wantValue: "Don't do this: it breaks",
|
||||
},
|
||||
{
|
||||
// The value opens with a double quote and then keeps going after
|
||||
// the closing one, so YAML reads it as a quoted scalar followed by
|
||||
// junk. Treating "starts with a quote" as "already quoted" leaves
|
||||
// this broken forever.
|
||||
name: "quotes a value that only looks quoted",
|
||||
doc: "---\ntitle: \"Evaluation Driven Generation\" — a TDD-style scaffold\ntags: [a, b]\n---\n\nbody\n",
|
||||
wantChanged: true,
|
||||
wantKey: "title",
|
||||
wantValue: "\"Evaluation Driven Generation\" — a TDD-style scaffold",
|
||||
},
|
||||
{
|
||||
name: "leaves an already-valid document untouched",
|
||||
doc: "---\ntitle: 'Already quoted: fine'\nwing: homelab\n---\n\nbody\n",
|
||||
@@ -129,6 +140,25 @@ func TestFix(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFix_LeavesStructuredValuesStructured(t *testing.T) {
|
||||
// Only the broken scalar may be touched. A flow sequence on a neighbouring
|
||||
// line still has to load as a sequence afterwards, not as a string.
|
||||
doc := "---\ntitle: Broken: here\ntags: [prompting, llm]\ncount: 3\n---\n\nbody\n"
|
||||
|
||||
got, changed, err := Fix([]byte(doc))
|
||||
require.NoError(t, err)
|
||||
require.True(t, changed)
|
||||
|
||||
b, ok := block(got)
|
||||
require.True(t, ok)
|
||||
var m map[string]any
|
||||
require.NoError(t, yaml.Unmarshal(b, &m))
|
||||
|
||||
assert.Equal(t, "Broken: here", m["title"])
|
||||
assert.Equal(t, []any{"prompting", "llm"}, m["tags"])
|
||||
assert.Equal(t, 3, m["count"])
|
||||
}
|
||||
|
||||
func TestFix_PreservesBodyExactly(t *testing.T) {
|
||||
body := "\nThe body has: colons, 'quotes', and\n---\na horizontal rule.\n"
|
||||
doc := "---\ntitle: Broken: title\n---" + body
|
||||
|
||||
@@ -105,13 +105,6 @@ func (s *Server) tools() []map[string]any {
|
||||
"target": str("path of target note (must be in a different wing)"),
|
||||
}),
|
||||
},
|
||||
{
|
||||
"name": "brain_index",
|
||||
"description": "Regenerate _index.md (Map of Content) for one or all wings under brain/wiki/. Auto-called after brain_write with wing+hall.",
|
||||
"inputSchema": schema([]string{}, map[string]any{
|
||||
"wing": str("optional wing to index; if absent, rebuilds every wing"),
|
||||
}),
|
||||
},
|
||||
{
|
||||
"name": "brain_ingest_raw",
|
||||
"description": "Ingest pre-structured pages into the brain wiki, bypassing the LLM extraction step.",
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/mathiasbq/hyperguild/ingestion/internal/api"
|
||||
)
|
||||
|
||||
// pendingNudgeThreshold is how old a raw/ note has to be before brain_context
|
||||
// mentions the queue. Two weeks: long enough that a note written this sprint
|
||||
// does not nag, short enough that four items cannot sit unnoticed for three
|
||||
// months again (#82).
|
||||
const pendingNudgeThreshold = 14 * 24 * time.Hour
|
||||
|
||||
// PendingNudge is the in-session reminder that the promote/reject queue has
|
||||
// items waiting. It is advisory: a count, an age, and how to look.
|
||||
type PendingNudge struct {
|
||||
Pending int `json:"pending"` // everything in the queue
|
||||
Aging int `json:"aging"` // those past the threshold
|
||||
Oldest string `json:"oldest"` // filename of the oldest pending note
|
||||
OldestDays int `json:"oldest_days"` // its age, in whole days
|
||||
Hint string `json:"hint"`
|
||||
}
|
||||
|
||||
// pendingNudge summarises the raw/ review queue, or returns nil when there is
|
||||
// nothing worth saying.
|
||||
//
|
||||
// The trigger is the missing half of the queue (#82): brain_pending has always
|
||||
// existed, and four real items still sat unreviewed from 2026-04-23 to
|
||||
// 2026-07-15 because nothing ever prompted anyone to call it. The system
|
||||
// should be what remembers the queue exists.
|
||||
//
|
||||
// Threshold-gated on purpose. A notice on every context call is one people
|
||||
// learn to skip, which reproduces the original failure with extra steps.
|
||||
//
|
||||
// It never promotes, rejects, or reorders anything. Age is a reason to ask a
|
||||
// human, not a verdict — an old note may be exactly right to promote once
|
||||
// someone finally looks at it.
|
||||
func pendingNudge(brainDir string, now time.Time, threshold time.Duration) *PendingNudge {
|
||||
pending, err := api.ListPending(brainDir)
|
||||
if err != nil || len(pending) == 0 {
|
||||
// brain_context is a hot path; a broken queue degrades to silence
|
||||
// rather than failing the call that asked for project context.
|
||||
return nil
|
||||
}
|
||||
|
||||
var aging int
|
||||
var oldestName string
|
||||
var oldestAge time.Duration
|
||||
|
||||
for _, p := range pending {
|
||||
created, perr := time.Parse(time.RFC3339, p.CreatedAt)
|
||||
if perr != nil {
|
||||
continue // an unparseable timestamp is not evidence of age
|
||||
}
|
||||
age := now.Sub(created)
|
||||
if age >= threshold {
|
||||
aging++
|
||||
}
|
||||
if age > oldestAge {
|
||||
oldestAge, oldestName = age, p.Filename
|
||||
}
|
||||
}
|
||||
|
||||
if aging == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &PendingNudge{
|
||||
Pending: len(pending),
|
||||
Aging: aging,
|
||||
Oldest: oldestName,
|
||||
OldestDays: int(oldestAge.Hours() / 24),
|
||||
Hint: "call brain_pending to review; nothing is promoted or rejected automatically",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// writePending drops a raw/ note whose created_at is age old.
|
||||
func writePending(t *testing.T, brainDir, name string, age time.Duration, now time.Time) {
|
||||
t.Helper()
|
||||
raw := filepath.Join(brainDir, "raw")
|
||||
require.NoError(t, os.MkdirAll(raw, 0o755))
|
||||
body := "---\ncreated_at: " + now.Add(-age).UTC().Format(time.RFC3339) + "\n---\n\nnote body\n"
|
||||
require.NoError(t, os.WriteFile(filepath.Join(raw, name), []byte(body), 0o644))
|
||||
}
|
||||
|
||||
func TestPendingNudge_SilentWhenNothingIsPending(t *testing.T) {
|
||||
// No queue, no nudge. A notice that fires every session is one people
|
||||
// learn to skip, which is how the queue got ignored for three months in
|
||||
// the first place (#82).
|
||||
got := pendingNudge(t.TempDir(), time.Now(), 14*24*time.Hour)
|
||||
assert.Nil(t, got)
|
||||
}
|
||||
|
||||
func TestPendingNudge_SilentWhileEverythingIsBelowTheThreshold(t *testing.T) {
|
||||
now := time.Now()
|
||||
dir := t.TempDir()
|
||||
writePending(t, dir, "fresh.md", 2*24*time.Hour, now)
|
||||
|
||||
got := pendingNudge(dir, now, 14*24*time.Hour)
|
||||
assert.Nil(t, got, "a two-day-old note is not aging")
|
||||
}
|
||||
|
||||
func TestPendingNudge_ReportsCountAndOldestAgeOnceSomethingAges(t *testing.T) {
|
||||
now := time.Now()
|
||||
dir := t.TempDir()
|
||||
writePending(t, dir, "old.md", 100*24*time.Hour, now)
|
||||
writePending(t, dir, "older.md", 120*24*time.Hour, now)
|
||||
writePending(t, dir, "fresh.md", 1*24*time.Hour, now)
|
||||
|
||||
got := pendingNudge(dir, now, 14*24*time.Hour)
|
||||
require.NotNil(t, got)
|
||||
|
||||
// All three are pending; the threshold decides whether to speak, not
|
||||
// what to count. Someone opening the queue sees the whole queue.
|
||||
assert.Equal(t, 3, got.Pending)
|
||||
assert.Equal(t, 2, got.Aging)
|
||||
assert.Equal(t, 120, got.OldestDays)
|
||||
assert.Equal(t, "older.md", got.Oldest)
|
||||
}
|
||||
|
||||
func TestPendingNudge_NeverDecidesAnything(t *testing.T) {
|
||||
// Aging is a trigger to ask a human, never a verdict. The nudge must
|
||||
// carry no action and must leave the queue exactly as it found it.
|
||||
now := time.Now()
|
||||
dir := t.TempDir()
|
||||
writePending(t, dir, "ancient.md", 365*24*time.Hour, now)
|
||||
|
||||
before, err := os.ReadDir(filepath.Join(dir, "raw"))
|
||||
require.NoError(t, err)
|
||||
|
||||
got := pendingNudge(dir, now, 14*24*time.Hour)
|
||||
require.NotNil(t, got)
|
||||
|
||||
after, err := os.ReadDir(filepath.Join(dir, "raw"))
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, after, len(before), "the nudge must not promote or reject anything")
|
||||
assert.Contains(t, got.Hint, "brain_pending", "the nudge should say how to look, not act")
|
||||
}
|
||||
|
||||
func TestPendingNudge_SurvivesAnUnreadableQueue(t *testing.T) {
|
||||
// brain_context is a hot path; a broken raw/ dir must degrade to silence
|
||||
// rather than failing the whole context call.
|
||||
dir := t.TempDir()
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "raw"), []byte("not a directory"), 0o644))
|
||||
|
||||
assert.NotPanics(t, func() {
|
||||
assert.Nil(t, pendingNudge(dir, time.Now(), 14*24*time.Hour))
|
||||
})
|
||||
}
|
||||
|
||||
func TestBrainContext_CarriesTheNudgeWithoutFailingWhenTheQueueIsEmpty(t *testing.T) {
|
||||
// The wiring, not the summary: a nudge that never reaches a caller is the
|
||||
// same as no nudge, and brain_context must still work with no queue.
|
||||
dir := t.TempDir()
|
||||
srv := NewServer(dir, nil, nil, nil)
|
||||
|
||||
raw, err := srv.brainContext(context.Background(),
|
||||
json.RawMessage(`{"project_root":"/home/mathias/dev/AGENTS/hyperguild"}`))
|
||||
require.NoError(t, err)
|
||||
|
||||
var empty map[string]any
|
||||
require.NoError(t, json.Unmarshal(raw, &empty))
|
||||
assert.NotContains(t, empty, "pending_review", "silence when nothing is aging")
|
||||
|
||||
writePending(t, dir, "ancient.md", 200*24*time.Hour, time.Now())
|
||||
|
||||
raw, err = srv.brainContext(context.Background(),
|
||||
json.RawMessage(`{"project_root":"/home/mathias/dev/AGENTS/hyperguild"}`))
|
||||
require.NoError(t, err)
|
||||
|
||||
var withQueue map[string]any
|
||||
require.NoError(t, json.Unmarshal(raw, &withQueue))
|
||||
nudge, ok := withQueue["pending_review"].(map[string]any)
|
||||
require.True(t, ok, "the nudge must reach the caller: %v", withQueue)
|
||||
assert.Equal(t, float64(1), nudge["aging"])
|
||||
assert.Equal(t, "ancient.md", nudge["oldest"])
|
||||
}
|
||||
@@ -1,9 +1,14 @@
|
||||
// Package mcp implements an MCP HTTP handler for the ingestion service.
|
||||
// Exposed tools: brain_query, brain_write, brain_update, brain_get,
|
||||
// brain_pending, brain_promote, brain_index, brain_tunnel, brain_ingest,
|
||||
// brain_pending, brain_promote, brain_tunnel, brain_ingest,
|
||||
// brain_ingest_raw, brain_answer, brain_classify, brain_graph,
|
||||
// brain_context, session_log, and capture (the #55 relay tool, registered
|
||||
// only when WithCapture is set).
|
||||
//
|
||||
// brain_index dispatches but is deliberately absent from tools/list: it is
|
||||
// auto-called after every write, so surfacing it as a caller verb is
|
||||
// cognitive load with no decision behind it (ADR-0012 rule 4, #78). It stays
|
||||
// callable for maintenance — de-surfacing hides the verb, not the operation.
|
||||
package mcp
|
||||
|
||||
import (
|
||||
|
||||
@@ -59,11 +59,35 @@ func TestServerToolsList(t *testing.T) {
|
||||
assert.ElementsMatch(t, []string{
|
||||
"brain_query", "brain_write", "brain_update", "brain_get",
|
||||
"brain_pending", "brain_promote",
|
||||
"brain_index", "brain_tunnel",
|
||||
"brain_tunnel",
|
||||
"brain_ingest_raw", "brain_ingest",
|
||||
"brain_answer", "brain_classify", "brain_graph", "brain_context",
|
||||
"session_log",
|
||||
}, names)
|
||||
|
||||
// brain_index is auto-called after every brain_write, so surfacing it as
|
||||
// a caller verb is cognitive load with no decision behind it (ADR-0012
|
||||
// rule 4, #78). The capability stays reachable — see the admin test below.
|
||||
assert.NotContains(t, names, "brain_index")
|
||||
}
|
||||
|
||||
func TestBrainIndexStaysCallableForAdminUseAfterDeSurfacing(t *testing.T) {
|
||||
// De-surfacing hides the verb from the model-facing list; it must not
|
||||
// remove the operation. A maintenance caller still needs to rebuild a
|
||||
// Map of Content by hand.
|
||||
srv := mcp.NewServer(t.TempDir(), nil, nil, nil)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/mcp", body(t, map[string]any{
|
||||
"jsonrpc": "2.0", "id": 3, "method": "tools/call",
|
||||
"params": map[string]any{"name": "brain_index", "arguments": map[string]any{}},
|
||||
}))
|
||||
rr := httptest.NewRecorder()
|
||||
srv.ServeHTTP(rr, req)
|
||||
|
||||
require.Equal(t, http.StatusOK, rr.Code)
|
||||
var resp map[string]any
|
||||
require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &resp))
|
||||
assert.NotContains(t, resp, "error", "brain_index must still dispatch: %v", resp["error"])
|
||||
}
|
||||
|
||||
func TestServerNotificationGetsNoBody(t *testing.T) {
|
||||
|
||||
@@ -8,8 +8,10 @@ import (
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mathiasbq/hyperguild/ingestion/internal/search"
|
||||
"github.com/mathiasbq/hyperguild/ingestion/internal/textutil"
|
||||
)
|
||||
|
||||
// brainContextArgs is the input shape of brain_context. project_root is
|
||||
@@ -155,17 +157,21 @@ func (s *Server) brainContext(ctx context.Context, args json.RawMessage) (json.R
|
||||
entries = entries[:limit]
|
||||
}
|
||||
|
||||
return json.Marshal(map[string]any{"entries": entries})
|
||||
out := map[string]any{"entries": entries}
|
||||
// The queue nudge rides along with a call the session already makes, so
|
||||
// noticing an aging note costs nobody a decision to go looking (#82).
|
||||
// Advisory only, and absent entirely when there is nothing to say.
|
||||
if n := pendingNudge(s.brainDir, time.Now(), pendingNudgeThreshold); n != nil {
|
||||
out["pending_review"] = n
|
||||
}
|
||||
return json.Marshal(out)
|
||||
}
|
||||
|
||||
// truncateExcerpt clamps an already-stripped excerpt to maxLen characters
|
||||
// without re-running the frontmatter parser. The ellipsis suffix matches
|
||||
// the convention used in search.excerpt.
|
||||
func truncateExcerpt(s string, maxLen int) string {
|
||||
if len(s) <= maxLen {
|
||||
return s
|
||||
}
|
||||
return s[:maxLen] + "…"
|
||||
return textutil.Truncate(s, maxLen)
|
||||
}
|
||||
|
||||
// readExcerpt loads a doc relative to brainDir, strips its frontmatter,
|
||||
@@ -185,10 +191,7 @@ func readExcerpt(brainDir, relPath string, maxLen int) string {
|
||||
if len(parts) == 3 {
|
||||
body = strings.TrimSpace(parts[2])
|
||||
}
|
||||
if len(body) > maxLen {
|
||||
return body[:maxLen] + "…"
|
||||
}
|
||||
return body
|
||||
return textutil.Truncate(body, maxLen)
|
||||
}
|
||||
|
||||
// max1 returns the maximum of n and 1, used to guard against divide-by-zero
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/mathiasbq/hyperguild/ingestion/internal/brain"
|
||||
"github.com/mathiasbq/hyperguild/ingestion/internal/textutil"
|
||||
"github.com/mathiasbq/hyperguild/ingestion/internal/vectorstore"
|
||||
)
|
||||
|
||||
@@ -427,8 +428,5 @@ func excerpt(content string, maxLen int) string {
|
||||
if len(parts) == 3 {
|
||||
body = strings.TrimSpace(parts[2])
|
||||
}
|
||||
if len(body) > maxLen {
|
||||
return body[:maxLen] + "…"
|
||||
}
|
||||
return body
|
||||
return textutil.Truncate(body, maxLen)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
// Package startupretry retries a startup dependency that may not be serving
|
||||
// yet, instead of exiting on its first failure.
|
||||
//
|
||||
// It exists for the cold-boot ordering race (#83): on a cluster restart the
|
||||
// ingestion pod can reach OIDC discovery before dex is answering, gets a 502
|
||||
// from ingress, and dies — after having already connected postgres, backfilled
|
||||
// the graph and ingested session batches, all of which the restart redoes.
|
||||
// Nothing is misconfigured in that scenario; the pod simply started first.
|
||||
//
|
||||
// The budget is bounded on purpose. Retrying forever would turn a genuine
|
||||
// misconfiguration (wrong issuer URL, bad audience) into a process that looks
|
||||
// healthy and never serves, which is harder to diagnose than a crash loop.
|
||||
package startupretry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Policy bounds the retry: at most Attempts calls, with the delay doubling
|
||||
// from Base and capped at Max.
|
||||
type Policy struct {
|
||||
Attempts int // total calls, including the first; < 1 means 1
|
||||
Base time.Duration // delay before the second attempt
|
||||
Max time.Duration // ceiling for the doubling delay
|
||||
}
|
||||
|
||||
// Do calls fn until it succeeds, the attempt budget is spent, or ctx ends.
|
||||
//
|
||||
// The returned error wraps the last failure, so callers keep the diagnosis
|
||||
// they would have had without the retry.
|
||||
func Do[T any](ctx context.Context, p Policy, fn func(context.Context) (T, error)) (T, error) {
|
||||
var zero T
|
||||
|
||||
attempts := p.Attempts
|
||||
if attempts < 1 {
|
||||
attempts = 1
|
||||
}
|
||||
|
||||
delay := p.Base
|
||||
var lastErr error
|
||||
|
||||
for i := range attempts {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return zero, fmt.Errorf("startupretry: %w", err)
|
||||
}
|
||||
|
||||
v, err := fn(ctx)
|
||||
if err == nil {
|
||||
return v, nil
|
||||
}
|
||||
lastErr = err
|
||||
|
||||
if i == attempts-1 {
|
||||
break
|
||||
}
|
||||
|
||||
if delay <= 0 {
|
||||
delay = time.Second
|
||||
}
|
||||
if p.Max > 0 && delay > p.Max {
|
||||
delay = p.Max
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return zero, fmt.Errorf("startupretry: %w", ctx.Err())
|
||||
case <-time.After(delay):
|
||||
}
|
||||
delay *= 2
|
||||
}
|
||||
|
||||
return zero, fmt.Errorf("startupretry: gave up after %d attempts: %w", attempts, lastErr)
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
// ingestion/internal/startupretry/startupretry_test.go
|
||||
package startupretry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func fastPolicy(attempts int) Policy {
|
||||
return Policy{Attempts: attempts, Base: time.Millisecond, Max: 2 * time.Millisecond}
|
||||
}
|
||||
|
||||
func TestDo_ReturnsImmediatelyOnFirstSuccess(t *testing.T) {
|
||||
calls := 0
|
||||
got, err := Do(context.Background(), fastPolicy(5), func(context.Context) (string, error) {
|
||||
calls++
|
||||
return "ready", nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Do: %v", err)
|
||||
}
|
||||
if got != "ready" {
|
||||
t.Errorf("got %q, want %q", got, "ready")
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Errorf("calls = %d, want 1", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDo_SurvivesTransientFailuresThenSucceeds(t *testing.T) {
|
||||
// The observed cold-boot race: dex is not serving yet, ingress answers
|
||||
// 502 for the first few attempts, then discovery works.
|
||||
calls := 0
|
||||
got, err := Do(context.Background(), fastPolicy(5), func(context.Context) (string, error) {
|
||||
calls++
|
||||
if calls < 4 {
|
||||
return "", errors.New("oidc discovery: status 502")
|
||||
}
|
||||
return "ready", nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Do returned %v — a transient 502 must not be fatal", err)
|
||||
}
|
||||
if got != "ready" {
|
||||
t.Errorf("got %q, want %q", got, "ready")
|
||||
}
|
||||
if calls != 4 {
|
||||
t.Errorf("calls = %d, want 4", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDo_GivesUpAfterTheAttemptBudgetAndReportsTheLastError(t *testing.T) {
|
||||
// A genuinely broken issuer must still fail — retrying forever would turn
|
||||
// a config error into a silent hang, which is worse than crash-looping.
|
||||
last := errors.New("oidc discovery: status 404")
|
||||
calls := 0
|
||||
|
||||
_, err := Do(context.Background(), fastPolicy(3), func(context.Context) (string, error) {
|
||||
calls++
|
||||
return "", last
|
||||
})
|
||||
|
||||
if !errors.Is(err, last) {
|
||||
t.Fatalf("err = %v, want it to wrap the last failure", err)
|
||||
}
|
||||
if calls != 3 {
|
||||
t.Errorf("calls = %d, want 3 (the attempt budget)", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDo_StopsPromptlyWhenTheContextIsCancelled(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
calls := 0
|
||||
|
||||
done := make(chan struct{})
|
||||
var err error
|
||||
go func() {
|
||||
defer close(done)
|
||||
_, err = Do(ctx, Policy{Attempts: 100, Base: 50 * time.Millisecond, Max: time.Second},
|
||||
func(context.Context) (string, error) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
cancel()
|
||||
}
|
||||
return "", errors.New("still down")
|
||||
})
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Do did not return after context cancellation")
|
||||
}
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Errorf("err = %v, want context.Canceled", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDo_BacksOffAndIsCappedByMax(t *testing.T) {
|
||||
var delays []time.Duration
|
||||
p := Policy{Attempts: 5, Base: 10 * time.Millisecond, Max: 25 * time.Millisecond}
|
||||
|
||||
last := time.Now()
|
||||
_, _ = Do(context.Background(), p, func(context.Context) (string, error) {
|
||||
now := time.Now()
|
||||
delays = append(delays, now.Sub(last))
|
||||
last = now
|
||||
return "", errors.New("down")
|
||||
})
|
||||
|
||||
// delays[0] is the first call (no wait); the rest are the sleeps.
|
||||
if len(delays) != 5 {
|
||||
t.Fatalf("attempts = %d, want 5", len(delays))
|
||||
}
|
||||
if delays[1] >= delays[2] {
|
||||
t.Errorf("backoff is not growing: %v then %v", delays[1], delays[2])
|
||||
}
|
||||
for i, d := range delays[1:] {
|
||||
if d > 2*p.Max {
|
||||
t.Errorf("delay %d = %v, exceeds the Max cap %v with slack", i+1, d, p.Max)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPolicy_ZeroValueStillMakesOneAttempt(t *testing.T) {
|
||||
// A caller that forgets to configure the policy must not silently get a
|
||||
// no-op that returns a nil validator and a nil error.
|
||||
calls := 0
|
||||
_, err := Do(context.Background(), Policy{}, func(context.Context) (string, error) {
|
||||
calls++
|
||||
return "", errors.New("down")
|
||||
})
|
||||
|
||||
if calls != 1 {
|
||||
t.Errorf("calls = %d, want 1", calls)
|
||||
}
|
||||
if err == nil {
|
||||
t.Error("err = nil, want the failure surfaced")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Package textutil holds small text helpers shared across the ingestion
|
||||
// service.
|
||||
package textutil
|
||||
|
||||
import "unicode/utf8"
|
||||
|
||||
// Ellipsis marks a value that was cut short.
|
||||
const Ellipsis = "…"
|
||||
|
||||
// Truncate shortens s to at most limit CHARACTERS, appending an ellipsis when
|
||||
// anything was dropped.
|
||||
//
|
||||
// It exists because four call sites did `s[:limit] + "…"` (#93). Both halves
|
||||
// of that are byte operations: len() counts bytes and a slice cuts bytes, so
|
||||
// on Swedish text — where å ä ö are two bytes and an em dash is three — the
|
||||
// cut lands mid-character and leaves an orphaned lead byte. The result is
|
||||
// invalid UTF-8.
|
||||
//
|
||||
// That failed loudly in exactly one place, wiki/index.md, which is written
|
||||
// raw to disk and then rejected by every strict decoder. The other three fed
|
||||
// MCP responses, where encoding/json silently substitutes U+FFFD — so those
|
||||
// had been quietly eating the last character of truncated excerpts with no
|
||||
// error anywhere.
|
||||
//
|
||||
// The marker is appended only when content was actually dropped: an ellipsis
|
||||
// on complete text is a lie about the content.
|
||||
func Truncate(s string, limit int) string {
|
||||
if limit <= 0 {
|
||||
return ""
|
||||
}
|
||||
if utf8.RuneCountInString(s) <= limit {
|
||||
return s
|
||||
}
|
||||
|
||||
// Walk runes rather than converting to []rune: the input can be a whole
|
||||
// note body, and this runs on the read path.
|
||||
count := 0
|
||||
for i := range s {
|
||||
if count == limit {
|
||||
return s[:i] + Ellipsis
|
||||
}
|
||||
count++
|
||||
}
|
||||
return s + Ellipsis
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// ingestion/internal/textutil/truncate_test.go
|
||||
package textutil_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/mathiasbq/hyperguild/ingestion/internal/textutil"
|
||||
)
|
||||
|
||||
func TestTruncate_ShortStringsAreUntouched(t *testing.T) {
|
||||
for _, s := range []string{"", "kort", "räv", "a — b"} {
|
||||
if got := textutil.Truncate(s, 100); got != s {
|
||||
t.Errorf("Truncate(%q, 100) = %q, want it unchanged", s, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncate_NeverCutsInsideACharacter(t *testing.T) {
|
||||
// The property, not an example: whatever the limit, the result must be
|
||||
// valid UTF-8. Byte-slicing Swedish text (å ä ö) or an em dash produces
|
||||
// an orphaned lead byte, which is what corrupted wiki/index.md (#93).
|
||||
s := strings.Repeat("räv — ål — ökäd ", 20)
|
||||
|
||||
for limit := 0; limit <= len(s)+5; limit++ {
|
||||
got := textutil.Truncate(s, limit)
|
||||
if !utf8.ValidString(got) {
|
||||
t.Fatalf("Truncate(s, %d) produced invalid UTF-8: %q", limit, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncate_CountsCharactersNotBytes(t *testing.T) {
|
||||
// "räv" is 4 bytes, 3 runes. A byte-based limit of 3 would cut inside the
|
||||
// "ä"; a rune-based one returns it whole.
|
||||
if got := textutil.Truncate("räv", 3); got != "räv" {
|
||||
t.Errorf("Truncate(\"räv\", 3) = %q, want the whole word", got)
|
||||
}
|
||||
|
||||
got := textutil.Truncate("räven springer", 5)
|
||||
if utf8.RuneCountInString(got) != 6 { // 5 runes + the ellipsis
|
||||
t.Errorf("Truncate(...) = %q, want 5 runes plus the marker", got)
|
||||
}
|
||||
if !strings.HasSuffix(got, "…") {
|
||||
t.Errorf("Truncate(...) = %q, want it marked as truncated", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncate_MarksOnlyWhenSomethingWasDropped(t *testing.T) {
|
||||
// An ellipsis on text that was not cut is a lie about the content.
|
||||
if got := textutil.Truncate("räv", 10); strings.HasSuffix(got, "…") {
|
||||
t.Errorf("Truncate(%q, 10) = %q, want no truncation marker", "räv", got)
|
||||
}
|
||||
if got := textutil.Truncate("räv", 3); strings.HasSuffix(got, "…") {
|
||||
t.Errorf("exact-length input must not be marked: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncate_NonPositiveLimitYieldsNothingRatherThanPanicking(t *testing.T) {
|
||||
for _, limit := range []int{0, -1, -100} {
|
||||
if got := textutil.Truncate("räven", limit); got != "" {
|
||||
t.Errorf("Truncate(_, %d) = %q, want empty", limit, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/mathiasbq/hyperguild/ingestion/internal/textutil"
|
||||
)
|
||||
|
||||
// RebuildIndex writes brain/wiki/index.md from the current wiki contents.
|
||||
@@ -62,10 +64,7 @@ func pageFirstSentence(brainDir string, e Entry) string {
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
if len(line) > 100 {
|
||||
return line[:100] + "…"
|
||||
}
|
||||
return line
|
||||
return textutil.Truncate(line, 100)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user