build: 内置 norma 模块,构建不再依赖上游仓库
把 github.com/Autumn-27/norma v0.4.3(commit 320ae32)的源码复制到 third_party/norma,并用 go.mod 的 replace 指向本地副本。上游删除仓库或 改写 tag 都不再影响本仓库构建。 - 已验证 GOPROXY=off 下可完整编译并打出发行包 - go.sum 中该模块的两条校验记录随之删除(本地 replace 不需要哈希) - 升级方法与授权注意事项见 third_party/README.md
This commit is contained in:
1 parent
a819fa3230
commit
f782b612ec
213 files changed
+37401
-2
No files matched your search
+272
@@ -0,0 +1,272 @@
|
||||
package compaction
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
|
||||
// recSummarizer records calls and the messages it was handed.
|
||||
type recSummarizer struct {
|
||||
calls int
|
||||
last []llm.Message
|
||||
reply string
|
||||
err error
|
||||
}
|
||||
|
||||
func (r *recSummarizer) fn(_ context.Context, msgs []llm.Message) (string, error) {
|
||||
r.calls++
|
||||
r.last = msgs
|
||||
if r.err != nil {
|
||||
return "", r.err
|
||||
}
|
||||
if r.reply == "" {
|
||||
return "DIGEST", nil
|
||||
}
|
||||
return r.reply, nil
|
||||
}
|
||||
|
||||
func boundaryCount(msgs []llm.Message) int {
|
||||
n := 0
|
||||
for _, m := range msgs {
|
||||
if llm.IsBoundaryMarker(m) {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// --- autoCompact gating ---
|
||||
|
||||
func TestAutoCompactNilSummarizer(t *testing.T) {
|
||||
c := New(smallWindow(), nil)
|
||||
msgs := []llm.Message{bigMsg(llm.RoleUser, 4000), bigMsg(llm.RoleUser, 4000), bigMsg(llm.RoleUser, 4000)}
|
||||
if _, ok := c.autoCompact(context.Background(), msgs, 100, "auto"); ok {
|
||||
t.Fatal("nil summarizer → autoCompact must not run")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoCompactTrippedBreaker(t *testing.T) {
|
||||
rs := &recSummarizer{}
|
||||
c := New(smallWindow(), rs.fn)
|
||||
c.tripped = true
|
||||
msgs := []llm.Message{bigMsg(llm.RoleUser, 4000), bigMsg(llm.RoleUser, 4000), bigMsg(llm.RoleUser, 4000)}
|
||||
if _, ok := c.autoCompact(context.Background(), msgs, 100, "auto"); ok {
|
||||
t.Fatal("tripped breaker → autoCompact must not run")
|
||||
}
|
||||
if rs.calls != 0 {
|
||||
t.Fatalf("summarizer should not be called when tripped, calls=%d", rs.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoCompactTooFewMessages(t *testing.T) {
|
||||
rs := &recSummarizer{}
|
||||
c := New(smallWindow(), rs.fn) // KeepRecent=2
|
||||
msgs := []llm.Message{bigMsg(llm.RoleUser, 4000), bigMsg(llm.RoleUser, 4000)}
|
||||
if _, ok := c.autoCompact(context.Background(), msgs, 100, "auto"); ok {
|
||||
t.Fatal("workingBounds empty (tailStart<=start) → must not run")
|
||||
}
|
||||
if rs.calls != 0 {
|
||||
t.Fatalf("summarizer should not be called, calls=%d", rs.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoCompactFailureThenSuccessResets(t *testing.T) {
|
||||
rs := &recSummarizer{err: errors.New("boom")}
|
||||
c := New(smallWindow(), rs.fn)
|
||||
mk := func() []llm.Message {
|
||||
var m []llm.Message
|
||||
for range 6 {
|
||||
m = append(m, bigMsg(llm.RoleUser, 4000))
|
||||
}
|
||||
return m
|
||||
}
|
||||
c.autoCompact(context.Background(), mk(), 100, "auto") // fail 1
|
||||
c.autoCompact(context.Background(), mk(), 100, "auto") // fail 2
|
||||
if c.failures != 2 || c.tripped {
|
||||
t.Fatalf("after 2 failures: failures=%d tripped=%v", c.failures, c.tripped)
|
||||
}
|
||||
rs.err = nil // now succeeds
|
||||
if _, ok := c.autoCompact(context.Background(), mk(), 100, "auto"); !ok {
|
||||
t.Fatal("expected success")
|
||||
}
|
||||
if c.failures != 0 {
|
||||
t.Fatalf("success must reset failures, got %d", c.failures)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoCompactBoundaryMeta(t *testing.T) {
|
||||
rs := &recSummarizer{}
|
||||
c := New(Config{ContextWindow: 200000, MaxOutputTokens: 8000, KeepRecent: 2}, rs.fn)
|
||||
var msgs []llm.Message
|
||||
for range 6 {
|
||||
msgs = append(msgs, bigMsg(llm.RoleUser, 4000))
|
||||
}
|
||||
out, ok := c.autoCompact(context.Background(), msgs, 4242, "reactive")
|
||||
if !ok {
|
||||
t.Fatal("expected run")
|
||||
}
|
||||
i := llm.LastBoundaryIndex(out)
|
||||
meta, _ := llm.ParseBoundaryMeta(out[i])
|
||||
if meta.Trigger != "reactive" || meta.PreTokens != 4242 {
|
||||
t.Fatalf("meta=%+v", meta)
|
||||
}
|
||||
// messagesSummarized == len of the summarized head (msgs[start:tailStart]).
|
||||
if meta.MessagesSummarized != len(msgs)-2 { // KeepRecent=2 preserved
|
||||
t.Fatalf("messagesSummarized=%d, want %d", meta.MessagesSummarized, len(msgs)-2)
|
||||
}
|
||||
if rs.calls != 1 || len(rs.last) != len(msgs)-2 {
|
||||
t.Fatalf("summarizer got %d messages, want %d", len(rs.last), len(msgs)-2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoCompactMultipleBoundaries(t *testing.T) {
|
||||
rs := &recSummarizer{}
|
||||
c := New(Config{ContextWindow: 200000, MaxOutputTokens: 8000, KeepRecent: 2}, rs.fn)
|
||||
msgs := []llm.Message{llm.UserText("FIRST_UNIQUE")}
|
||||
for range 6 {
|
||||
msgs = append(msgs, bigMsg(llm.RoleUser, 4000))
|
||||
}
|
||||
out1, ok := c.autoCompact(context.Background(), msgs, 100, "auto")
|
||||
if !ok {
|
||||
t.Fatal("first compaction failed")
|
||||
}
|
||||
// Add more turns after the first boundary, then compact again.
|
||||
out1 = append(out1, bigMsg(llm.RoleUser, 4000), bigMsg(llm.RoleUser, 4000), bigMsg(llm.RoleUser, 4000))
|
||||
out2, ok := c.autoCompact(context.Background(), out1, 200, "auto")
|
||||
if !ok {
|
||||
t.Fatal("second compaction failed")
|
||||
}
|
||||
if boundaryCount(out2) != 2 {
|
||||
t.Fatalf("want 2 boundaries, got %d", boundaryCount(out2))
|
||||
}
|
||||
if rs.calls != 2 {
|
||||
t.Fatalf("want 2 summarizer calls, got %d", rs.calls)
|
||||
}
|
||||
// The second summary must only cover post-first-boundary messages.
|
||||
for _, m := range rs.last {
|
||||
if strings.Contains(m.Text(), "FIRST_UNIQUE") {
|
||||
t.Fatal("second compaction re-summarized pre-boundary history")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Pre orchestration matrix ---
|
||||
|
||||
func TestPreDisabledWindow(t *testing.T) {
|
||||
rs := &recSummarizer{}
|
||||
c := New(Config{ContextWindow: -1}, rs.fn)
|
||||
msgs := []llm.Message{bigMsg(llm.RoleUser, 4000)}
|
||||
out := c.Pre(context.Background(), msgs, 999999)
|
||||
if len(out) != len(msgs) || rs.calls != 0 {
|
||||
t.Fatal("ContextWindow<=0 disables compaction")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreBelowMicroThresholdNoOp(t *testing.T) {
|
||||
rs := &recSummarizer{}
|
||||
c := New(Config{ContextWindow: 200000, MaxOutputTokens: 8000}, rs.fn)
|
||||
msgs := manyReadPairs(microKeepRecent + 5) // has clearable results...
|
||||
out := c.Pre(context.Background(), msgs, 1) // ...but the gate says we're tiny
|
||||
if boundaryCount(out) != 0 || countCleared(out) != 0 || rs.calls != 0 {
|
||||
t.Fatal("below microThreshold → no micro, no auto")
|
||||
}
|
||||
}
|
||||
|
||||
// AutoCompact reached purely via the last-response gate on a micro no-op turn
|
||||
// (no compactable results), proving the accurate last-response size is used for
|
||||
// the auto decision, not a re-estimate.
|
||||
func TestPreAutoViaLastInputTokensNoMicro(t *testing.T) {
|
||||
rs := &recSummarizer{}
|
||||
c := New(Config{ContextWindow: 200000, MaxOutputTokens: 8000, KeepRecent: 2}, rs.fn)
|
||||
var msgs []llm.Message
|
||||
for range 10 {
|
||||
msgs = append(msgs, llm.UserText("small")) // no compactable tools
|
||||
}
|
||||
out := c.Pre(context.Background(), msgs, 200000) // above autoThreshold (179000)
|
||||
if boundaryCount(out) != 1 {
|
||||
t.Fatalf("auto should fire from the last-response gate, boundaries=%d", boundaryCount(out))
|
||||
}
|
||||
if rs.calls != 1 {
|
||||
t.Fatalf("summarizer calls=%d, want 1", rs.calls)
|
||||
}
|
||||
}
|
||||
|
||||
// MicroCompact-only band: above micro, below auto, not predictive → clears results
|
||||
// but inserts no boundary.
|
||||
func TestPreMicroOnlyBand(t *testing.T) {
|
||||
rs := &recSummarizer{}
|
||||
// eff=96000, micro=57600, auto=83000, growth=19000 → predictive at tok>77000.
|
||||
c := New(Config{ContextWindow: 100000, MaxOutputTokens: 4000, KeepRecent: 2}, rs.fn)
|
||||
msgs := manyReadPairs(microKeepRecent + 1) // small real size, one clearable
|
||||
out := c.Pre(context.Background(), msgs, 60000)
|
||||
if rs.calls != 0 || boundaryCount(out) != 0 {
|
||||
t.Fatalf("micro-only band should not autoCompact (calls=%d boundaries=%d)", rs.calls, boundaryCount(out))
|
||||
}
|
||||
if countCleared(out) != 1 {
|
||||
t.Fatalf("micro should clear the oldest result, cleared=%d", countCleared(out))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreAutoNilSummarizerNoBoundary(t *testing.T) {
|
||||
c := New(Config{ContextWindow: 200000, MaxOutputTokens: 8000, KeepRecent: 2}, nil)
|
||||
var msgs []llm.Message
|
||||
for range 10 {
|
||||
msgs = append(msgs, llm.UserText("m"+strconv.Itoa(len(msgs))))
|
||||
}
|
||||
out := c.Pre(context.Background(), msgs, 200000)
|
||||
if boundaryCount(out) != 0 {
|
||||
t.Fatal("nil summarizer → no boundary even above autoThreshold")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreNonDestructive(t *testing.T) {
|
||||
rs := &recSummarizer{}
|
||||
c := New(Config{ContextWindow: 200000, MaxOutputTokens: 8000, KeepRecent: 2}, rs.fn)
|
||||
var msgs []llm.Message
|
||||
for range 10 {
|
||||
msgs = append(msgs, llm.UserText("keep"))
|
||||
}
|
||||
out := c.Pre(context.Background(), msgs, 200000)
|
||||
// Full history retained + boundary + summary.
|
||||
if len(out) != len(msgs)+2 {
|
||||
t.Fatalf("len(out)=%d, want %d", len(out), len(msgs)+2)
|
||||
}
|
||||
if EstimateTokens(out) <= EstimateTokens(llm.MessagesForAPI(out)) {
|
||||
t.Fatal("retained history should exceed the API view")
|
||||
}
|
||||
}
|
||||
|
||||
// --- Reactive edges ---
|
||||
|
||||
func TestReactiveTripped(t *testing.T) {
|
||||
rs := &recSummarizer{}
|
||||
c := New(smallWindow(), rs.fn)
|
||||
c.tripped = true
|
||||
msgs := []llm.Message{bigMsg(llm.RoleUser, 4000), bigMsg(llm.RoleUser, 4000), bigMsg(llm.RoleUser, 4000)}
|
||||
if _, ok := c.Reactive(context.Background(), msgs); ok {
|
||||
t.Fatal("tripped → reactive cannot compact")
|
||||
}
|
||||
}
|
||||
|
||||
// If the summary is larger than the original working set, Reactive reports it did
|
||||
// not shrink (ok=false) even though a boundary was inserted.
|
||||
func TestReactiveNoShrinkWhenSummaryHuge(t *testing.T) {
|
||||
rs := &recSummarizer{reply: strings.Repeat("z", 200000)}
|
||||
c := New(Config{ContextWindow: 200000, MaxOutputTokens: 8000, KeepRecent: 2}, rs.fn)
|
||||
var msgs []llm.Message
|
||||
for range 6 {
|
||||
msgs = append(msgs, bigMsg(llm.RoleUser, 400))
|
||||
}
|
||||
out, ok := c.Reactive(context.Background(), msgs)
|
||||
if ok {
|
||||
t.Fatal("a huge summary means the API view did not shrink → ok=false")
|
||||
}
|
||||
if boundaryCount(out) != 1 {
|
||||
t.Fatalf("autoCompact still inserts a boundary, got %d", boundaryCount(out))
|
||||
}
|
||||
}
|
||||
+431
@@ -0,0 +1,431 @@
|
||||
// Package compaction keeps a conversation within a model's context window using
|
||||
// three mechanisms aligned 1:1 with claude-code (see docs/COMPACTION-SPEC-3.md):
|
||||
//
|
||||
// - MicroCompact — clear stale COMPACTABLE tool-result bodies (non-destructive:
|
||||
// the result can be re-read). Keeps the most recent N compactable results and
|
||||
// clears the rest.
|
||||
// - AutoCompact — summarize the working head behind a compact boundary at the
|
||||
// token threshold (or predictively). Non-destructive: the full history is
|
||||
// retained in the message array; only messages after the last boundary are
|
||||
// sent to the model (llm.MessagesForAPI).
|
||||
// - Reactive — on a prompt-too-long (413) error, force one AutoCompact and
|
||||
// retry. It reuses AutoCompact; it is not a separate algorithm.
|
||||
//
|
||||
// Snip and Context-Collapse are intentionally absent: snip's removal decision can
|
||||
// only come from a model tool / user command (no automatic trigger), and
|
||||
// context-collapse is disabled by default in claude-code. Thresholds are derived
|
||||
// from the model's context window (minus a summary reservation and a buffer),
|
||||
// with a predictive pre-request check. Token counts prefer the previous model
|
||||
// response's input_tokens and otherwise fall back to a 4/3-scaled per-block
|
||||
// length estimate.
|
||||
package compaction
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
|
||||
// Summarizer condenses messages into a digest. Injected so the host controls
|
||||
// which model summarizes (and so tests can mock).
|
||||
type Summarizer func(ctx context.Context, msgs []llm.Message) (string, error)
|
||||
|
||||
// Config tunes the compactor.
|
||||
type Config struct {
|
||||
// ContextWindow is the model's total context window in tokens (default 200000).
|
||||
ContextWindow int
|
||||
// MaxOutputTokens is the model's max output capability; the summary reservation
|
||||
// is min(MaxOutputTokens, 20000) (default 8000).
|
||||
MaxOutputTokens int
|
||||
// KeepRecent is the number of recent messages AutoCompact always preserves as
|
||||
// the un-summarized tail (default 8). MicroCompact uses its own microKeepRecent.
|
||||
KeepRecent int
|
||||
}
|
||||
|
||||
func (c *Config) defaults() {
|
||||
if c.ContextWindow == 0 {
|
||||
c.ContextWindow = 200000
|
||||
}
|
||||
if c.MaxOutputTokens == 0 {
|
||||
c.MaxOutputTokens = 8000
|
||||
}
|
||||
if c.KeepRecent == 0 {
|
||||
c.KeepRecent = 8
|
||||
}
|
||||
}
|
||||
|
||||
// compactableTools — tools whose results MicroCompact may clear. Mirrors
|
||||
// claude-code COMPACTABLE_TOOLS (file read, shell, grep/glob, web, edit/write);
|
||||
// deliberately excludes LS/MultiEdit/NotebookEdit.
|
||||
var compactableTools = map[string]bool{
|
||||
"Read": true, "Bash": true, "Grep": true, "Glob": true,
|
||||
"WebFetch": true, "WebSearch": true, "Edit": true, "Write": true,
|
||||
}
|
||||
|
||||
const (
|
||||
microClearedMessage = "[Old tool result content cleared]" // == claude-code TIME_BASED_MC_CLEARED_MESSAGE
|
||||
microKeepRecent = 5 // == claude-code KEEP_RECENT (compactable results kept)
|
||||
toolResultGrowthGuess = 15000 // == claude-code TOOL_RESULT_GROWTH_ESTIMATE
|
||||
maxAutoCompactFails = 3 // == claude-code MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES
|
||||
)
|
||||
|
||||
// Compactor applies the strategy. Construct with New.
|
||||
type Compactor struct {
|
||||
cfg Config
|
||||
summarize Summarizer
|
||||
failures int
|
||||
tripped bool
|
||||
}
|
||||
|
||||
// New builds a Compactor. summarize may be nil to disable AutoCompact.
|
||||
func New(cfg Config, summarize Summarizer) *Compactor {
|
||||
cfg.defaults()
|
||||
return &Compactor{cfg: cfg, summarize: summarize}
|
||||
}
|
||||
|
||||
// --- threshold math ---
|
||||
|
||||
// reservedForSummary is min(model max output, 20000). MaxOutputTokens stands in
|
||||
// for the model's output capability; 0 (unset) reserves the full 20000.
|
||||
func (c *Compactor) reservedForSummary() int {
|
||||
r := c.cfg.MaxOutputTokens
|
||||
if r > 20000 || r == 0 {
|
||||
r = 20000
|
||||
}
|
||||
return r
|
||||
}
|
||||
func (c *Compactor) effectiveWindow() int { return c.cfg.ContextWindow - c.reservedForSummary() }
|
||||
|
||||
// buffer tiers off the EFFECTIVE window (== claude-code getAutocompactBufferTokens).
|
||||
func (c *Compactor) buffer() int {
|
||||
switch ew := c.effectiveWindow(); {
|
||||
case ew >= 800000:
|
||||
return 50000
|
||||
case ew >= 400000:
|
||||
return 30000
|
||||
default:
|
||||
return 13000
|
||||
}
|
||||
}
|
||||
func (c *Compactor) autoThreshold() int { return c.effectiveWindow() - c.buffer() }
|
||||
func (c *Compactor) microThreshold() int { return c.effectiveWindow() * 6 / 10 }
|
||||
|
||||
// maxTurnGrowth == claude-code estimateMaxTurnGrowth: min(maxOutput,20000)+15000.
|
||||
func (c *Compactor) maxTurnGrowth() int { return c.reservedForSummary() + toolResultGrowthGuess }
|
||||
func (c *Compactor) predictiveOver(tok int) bool {
|
||||
return tok+c.maxTurnGrowth() > c.effectiveWindow()
|
||||
}
|
||||
|
||||
// count returns the token count of the API view (post-boundary). When
|
||||
// lastInputTokens > 0 (the total token size the previous model response
|
||||
// reported), it is preferred over local estimation — mirroring claude-code's
|
||||
// tokenCountWithEstimation. After a working-set mutation, callers pass 0 to force
|
||||
// a fresh per-block estimate.
|
||||
func (c *Compactor) count(msgs []llm.Message, lastInputTokens int) int {
|
||||
if lastInputTokens > 0 {
|
||||
return lastInputTokens
|
||||
}
|
||||
return EstimateTokens(llm.MessagesForAPI(msgs)) * 4 / 3
|
||||
}
|
||||
|
||||
// EstimateTokens approximates the token footprint of messages (~4 chars/token),
|
||||
// counting each block by type (text, thinking text, tool_use name+input, and
|
||||
// nested tool_result content). Mirrors claude-code roughTokenCountEstimation
|
||||
// (without the 4/3 scale, which count applies).
|
||||
func EstimateTokens(msgs []llm.Message) int {
|
||||
chars := 0
|
||||
for _, m := range msgs {
|
||||
for _, b := range m.Content {
|
||||
chars += blockChars(b)
|
||||
}
|
||||
}
|
||||
return chars / 4
|
||||
}
|
||||
|
||||
// blockChars is the per-block character footprint. A Norma ContentBlock has no
|
||||
// image/document type; if one is added, its fixed 2000-token cost (claude-code
|
||||
// IMAGE_MAX_TOKEN_SIZE) would be added here.
|
||||
func blockChars(b llm.ContentBlock) int {
|
||||
switch b.Type {
|
||||
case llm.BlockText:
|
||||
return len(b.Text)
|
||||
case llm.BlockThinking:
|
||||
return len(b.Thinking)
|
||||
case llm.BlockToolUse:
|
||||
return len(b.Name) + len(b.Input)
|
||||
case llm.BlockToolResult:
|
||||
n := 0
|
||||
for _, cb := range b.Content {
|
||||
n += blockChars(cb)
|
||||
}
|
||||
return n
|
||||
default:
|
||||
return len(b.Text)
|
||||
}
|
||||
}
|
||||
|
||||
// Pre conditions the history before a model request: MicroCompact to clear stale
|
||||
// tool results, then AutoCompact at the threshold (or predictively). Both are
|
||||
// non-destructive. lastInputTokens is the previous response's total token size
|
||||
// (0 if none yet), used as the initial gate count.
|
||||
func (c *Compactor) Pre(ctx context.Context, msgs []llm.Message, lastInputTokens int) []llm.Message {
|
||||
if c.cfg.ContextWindow <= 0 {
|
||||
return msgs
|
||||
}
|
||||
tok := c.count(msgs, lastInputTokens)
|
||||
if tok <= c.microThreshold() {
|
||||
return msgs
|
||||
}
|
||||
// MicroCompact: clear old COMPACTABLE tool results (non-destructive). Only
|
||||
// re-estimate when it actually changed the array; otherwise the gate count
|
||||
// (which prefers the accurate last-response size) still holds.
|
||||
if out, changed := c.microCompact(msgs); changed {
|
||||
msgs = out
|
||||
tok = c.count(msgs, 0)
|
||||
}
|
||||
// AutoCompact: at the threshold, or predictively if the next turn would overflow.
|
||||
if tok >= c.autoThreshold() || c.predictiveOver(tok) {
|
||||
if out, ok := c.autoCompact(ctx, msgs, tok, "auto"); ok {
|
||||
msgs = out
|
||||
}
|
||||
}
|
||||
return msgs
|
||||
}
|
||||
|
||||
// Reactive force-compacts after a prompt-too-long error by running one
|
||||
// AutoCompact (mirrors claude-code tryReactiveCompact, which only summarizes —
|
||||
// no micro/collapse/snip cascade). Returns whether the API view shrank.
|
||||
func (c *Compactor) Reactive(ctx context.Context, msgs []llm.Message) ([]llm.Message, bool) {
|
||||
before := c.count(msgs, 0)
|
||||
if out, ok := c.autoCompact(ctx, msgs, before, "reactive"); ok {
|
||||
return out, c.count(out, 0) < before
|
||||
}
|
||||
return msgs, false
|
||||
}
|
||||
|
||||
// IsOverflow is the method form (satisfies the harness Compactor interface).
|
||||
func (c *Compactor) IsOverflow(err error) bool { return IsOverflow(err) }
|
||||
|
||||
// IsOverflow reports whether err is a context-length / prompt-too-long failure.
|
||||
func IsOverflow(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
s := strings.ToLower(err.Error())
|
||||
return strings.Contains(s, "too long") || strings.Contains(s, "context length") ||
|
||||
strings.Contains(s, "context_length") || strings.Contains(s, "maximum context") ||
|
||||
strings.Contains(s, "status 413")
|
||||
}
|
||||
|
||||
// --- working-set geometry ---
|
||||
|
||||
// workingBounds returns [start, tailStart): start is just after the last
|
||||
// boundary marker (0 if none); tailStart is where the preserved recent tail
|
||||
// begins. Messages in [start, tailStart) are eligible for summary.
|
||||
func (c *Compactor) workingBounds(msgs []llm.Message) (start, tailStart int) {
|
||||
start = llm.LastBoundaryIndex(msgs) + 1
|
||||
tailStart = max(lastNNonMarkerStart(msgs, c.cfg.KeepRecent), start)
|
||||
return
|
||||
}
|
||||
|
||||
func lastNNonMarkerStart(msgs []llm.Message, keep int) int {
|
||||
count, i := 0, len(msgs)
|
||||
for i > 0 && count < keep {
|
||||
i--
|
||||
if !llm.IsBoundaryMarker(msgs[i]) {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return i
|
||||
}
|
||||
|
||||
// --- MicroCompact: keep the most recent N compactable results, clear the rest ---
|
||||
|
||||
// microCompact clears the bodies of all COMPACTABLE tool results except the most
|
||||
// recent microKeepRecent, returning the (possibly new) message slice and whether
|
||||
// anything changed. It is non-destructive: a cleared result can be re-read.
|
||||
func (c *Compactor) microCompact(msgs []llm.Message) ([]llm.Message, bool) {
|
||||
// Collect compactable tool_use ids in encounter order.
|
||||
var ids []string
|
||||
for _, m := range msgs {
|
||||
for _, b := range m.Content {
|
||||
if b.Type == llm.BlockToolUse && compactableTools[b.Name] {
|
||||
ids = append(ids, b.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(ids) <= microKeepRecent {
|
||||
return msgs, false // nothing old enough to clear
|
||||
}
|
||||
clearSet := make(map[string]bool, len(ids)-microKeepRecent)
|
||||
for _, id := range ids[:len(ids)-microKeepRecent] {
|
||||
clearSet[id] = true
|
||||
}
|
||||
changed := false
|
||||
out := append([]llm.Message(nil), msgs...)
|
||||
for i := range out {
|
||||
var nc []llm.ContentBlock
|
||||
for j, b := range out[i].Content {
|
||||
if b.Type == llm.BlockToolResult && clearSet[b.ToolUseID] && !isCleared(b.Content) {
|
||||
if nc == nil {
|
||||
nc = append([]llm.ContentBlock(nil), out[i].Content...)
|
||||
}
|
||||
nc[j].Content = []llm.ContentBlock{llm.TextBlock(microClearedMessage)}
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if nc != nil {
|
||||
out[i].Content = nc
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return msgs, false
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
func isCleared(blocks []llm.ContentBlock) bool {
|
||||
return len(blocks) == 1 && blocks[0].Type == llm.BlockText && blocks[0].Text == microClearedMessage
|
||||
}
|
||||
|
||||
// --- AutoCompact: non-destructive boundary + summary ---
|
||||
|
||||
func (c *Compactor) autoCompact(ctx context.Context, msgs []llm.Message, preTok int, trigger string) ([]llm.Message, bool) {
|
||||
if c.summarize == nil || c.tripped {
|
||||
return msgs, false
|
||||
}
|
||||
start, tailStart := c.workingBounds(msgs)
|
||||
if tailStart <= start {
|
||||
return msgs, false
|
||||
}
|
||||
toSummarize := contentOnly(msgs[start:tailStart])
|
||||
if len(toSummarize) == 0 {
|
||||
return msgs, false
|
||||
}
|
||||
summary, err := c.summarize(ctx, toSummarize)
|
||||
if err != nil {
|
||||
c.failures++
|
||||
if c.failures >= maxAutoCompactFails {
|
||||
c.tripped = true
|
||||
}
|
||||
return msgs, false
|
||||
}
|
||||
c.failures = 0
|
||||
|
||||
// Skill instructions in the summarized head are lossy in the prose summary, so
|
||||
// re-inject the latest invocation of each skill verbatim just after the summary
|
||||
// (post-boundary → sent to the model). Retained history keeps the originals; we
|
||||
// only re-surface skills that fell behind the new boundary.
|
||||
reinjected := reinjectSkills(msgs, tailStart)
|
||||
boundary := llm.BoundaryMessage(llm.BoundaryMeta{
|
||||
Trigger: trigger,
|
||||
PreTokens: preTok,
|
||||
MessagesSummarized: len(toSummarize),
|
||||
ActiveSkills: skillNames(reinjected),
|
||||
})
|
||||
summaryMsg := llm.Message{Role: llm.RoleUser, Content: []llm.ContentBlock{
|
||||
llm.TextBlock(compactContinuationPreamble + summary),
|
||||
}}
|
||||
// Retain everything before tailStart (non-destructive); insert the new
|
||||
// boundary + summary (+ re-injected skills) just before the preserved recent tail.
|
||||
out := make([]llm.Message, 0, len(msgs)+2+len(reinjected))
|
||||
out = append(out, msgs[:tailStart]...)
|
||||
out = append(out, boundary, summaryMsg)
|
||||
out = append(out, reinjected...)
|
||||
out = append(out, msgs[tailStart:]...)
|
||||
return out, true
|
||||
}
|
||||
|
||||
// compactContinuationPreamble prefixes the inserted summary message, mirroring
|
||||
// claude-code getCompactUserSummaryMessage. formatCompactSummary already prefixes
|
||||
// the digest with "Summary:\n".
|
||||
const compactContinuationPreamble = "This session is being continued from a previous conversation that ran out of context. The conversation is summarized below:\n\n"
|
||||
|
||||
// Skill re-injection budget: per-skill and total token caps for verbatim skill
|
||||
// instructions re-surfaced after a compaction boundary (mirrors claude-code's
|
||||
// 5K/25K policy). Most-recently-invoked skills win when the total is exceeded.
|
||||
const (
|
||||
maxSkillReinjectTokens = 5000
|
||||
maxSkillReinjectTotalTokens = 25000
|
||||
)
|
||||
|
||||
// skillNames returns the invoked-skill names of the given re-injected messages.
|
||||
func skillNames(msgs []llm.Message) []string {
|
||||
var out []string
|
||||
for _, m := range msgs {
|
||||
if name, ok := llm.SkillInvocationName(m); ok {
|
||||
out = append(out, name)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// reinjectSkills finds the latest invocation of each skill in the history behind
|
||||
// the new boundary (msgs[:tailStart]) and returns copies to place after the
|
||||
// summary, newest-first under budget, restored to chronological order. A skill
|
||||
// whose latest invocation is already in the preserved tail (index >= tailStart)
|
||||
// is skipped — it is still in the model's view.
|
||||
func reinjectSkills(msgs []llm.Message, tailStart int) []llm.Message {
|
||||
type entry struct {
|
||||
msg llm.Message
|
||||
idx int
|
||||
}
|
||||
latest := map[string]*entry{}
|
||||
var order []string
|
||||
for i, m := range msgs {
|
||||
name, ok := llm.SkillInvocationName(m)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if e, seen := latest[name]; seen {
|
||||
e.msg, e.idx = m, i
|
||||
} else {
|
||||
latest[name] = &entry{msg: m, idx: i}
|
||||
order = append(order, name)
|
||||
}
|
||||
}
|
||||
if len(latest) == 0 {
|
||||
return nil
|
||||
}
|
||||
// Candidates whose latest invocation fell behind the boundary, newest-first.
|
||||
var cands []*entry
|
||||
for _, name := range order {
|
||||
if e := latest[name]; e.idx < tailStart {
|
||||
cands = append(cands, e)
|
||||
}
|
||||
}
|
||||
sort.Slice(cands, func(a, b int) bool { return cands[a].idx > cands[b].idx })
|
||||
|
||||
kept := make([]*entry, 0, len(cands))
|
||||
total := 0
|
||||
for _, e := range cands {
|
||||
m := llm.TruncateSkillMessage(e.msg, maxSkillReinjectTokens*4)
|
||||
t := EstimateTokens([]llm.Message{m})
|
||||
if total+t > maxSkillReinjectTotalTokens {
|
||||
continue // drop this one; a smaller, older skill may still fit
|
||||
}
|
||||
total += t
|
||||
kept = append(kept, &entry{msg: m, idx: e.idx})
|
||||
}
|
||||
if len(kept) == 0 {
|
||||
return nil
|
||||
}
|
||||
sort.Slice(kept, func(a, b int) bool { return kept[a].idx < kept[b].idx })
|
||||
out := make([]llm.Message, 0, len(kept))
|
||||
for _, e := range kept {
|
||||
out = append(out, e.msg)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func contentOnly(msgs []llm.Message) []llm.Message {
|
||||
out := make([]llm.Message, 0, len(msgs))
|
||||
for _, m := range msgs {
|
||||
if !llm.IsBoundaryMarker(m) {
|
||||
out = append(out, m)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
+230
@@ -0,0 +1,230 @@
|
||||
package compaction
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
|
||||
func bigMsg(role llm.Role, n int) llm.Message {
|
||||
return llm.Message{Role: role, Content: []llm.ContentBlock{llm.TextBlock(strings.Repeat("x", n))}}
|
||||
}
|
||||
|
||||
// smallWindow makes thresholds tiny so a few messages exceed them.
|
||||
func smallWindow() Config {
|
||||
return Config{ContextWindow: 16000, MaxOutputTokens: 1000, KeepRecent: 2}
|
||||
}
|
||||
|
||||
func TestAutoCompactIsNonDestructive(t *testing.T) {
|
||||
c := New(smallWindow(), func(_ context.Context, msgs []llm.Message) (string, error) {
|
||||
return "DIGEST", nil
|
||||
})
|
||||
var msgs []llm.Message
|
||||
for i := 0; i < 8; i++ {
|
||||
msgs = append(msgs, bigMsg(llm.RoleUser, 4000))
|
||||
}
|
||||
out, ok := c.autoCompact(context.Background(), msgs, 1234, "auto")
|
||||
if !ok {
|
||||
t.Fatal("autoCompact did not run")
|
||||
}
|
||||
// Non-destructive: full original history retained + boundary + summary.
|
||||
if len(out) != len(msgs)+2 {
|
||||
t.Fatalf("len(out)=%d, want %d (history + boundary + summary)", len(out), len(msgs)+2)
|
||||
}
|
||||
if llm.LastBoundaryIndex(out) < 0 {
|
||||
t.Fatal("no boundary marker inserted")
|
||||
}
|
||||
// API view = summary + recent tail (boundary stripped).
|
||||
api := llm.MessagesForAPI(out)
|
||||
if !strings.Contains(api[0].Text(), "DIGEST") {
|
||||
t.Fatalf("API view should start with the summary, got %q", api[0].Text())
|
||||
}
|
||||
if len(api) != 1+smallWindow().KeepRecent {
|
||||
t.Fatalf("API view = summary + %d recent, got %d", smallWindow().KeepRecent, len(api))
|
||||
}
|
||||
// Retained history (full array) far exceeds what is actually sent.
|
||||
if EstimateTokens(out) <= EstimateTokens(api) {
|
||||
t.Fatal("retained history should exceed the API view")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoCompactReinjectsInvokedSkills(t *testing.T) {
|
||||
c := New(smallWindow(), func(_ context.Context, msgs []llm.Message) (string, error) {
|
||||
return "DIGEST", nil
|
||||
})
|
||||
// An old skill invocation, then enough bulk to push it behind the boundary.
|
||||
skillMsg := llm.SkillInvocationMessage("deploy", "/skills/deploy", "1. build\n2. ship")
|
||||
msgs := []llm.Message{skillMsg}
|
||||
for i := 0; i < 8; i++ {
|
||||
msgs = append(msgs, bigMsg(llm.RoleUser, 4000))
|
||||
}
|
||||
out, ok := c.autoCompact(context.Background(), msgs, 1234, "auto")
|
||||
if !ok {
|
||||
t.Fatal("autoCompact did not run")
|
||||
}
|
||||
// The skill instructions must appear in the API view (post-boundary), verbatim,
|
||||
// even though the transcript copy was summarized to "DIGEST".
|
||||
api := llm.MessagesForAPI(out)
|
||||
var found bool
|
||||
for _, m := range api {
|
||||
if name, ok := llm.SkillInvocationName(m); ok && name == "deploy" && strings.Contains(m.Text(), "1. build") {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("invoked skill 'deploy' was not re-injected into the post-boundary API view")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReinjectSkillsDedupesAndSkipsTail(t *testing.T) {
|
||||
// Two invocations of the same skill behind the boundary → keep only the latest.
|
||||
old := llm.SkillInvocationMessage("x", "", "OLD BODY")
|
||||
newer := llm.SkillInvocationMessage("x", "", "NEW BODY")
|
||||
// A different skill whose only invocation is in the preserved tail → not re-injected.
|
||||
tail := llm.SkillInvocationMessage("y", "", "TAIL BODY")
|
||||
msgs := []llm.Message{old, newer, bigMsg(llm.RoleUser, 10), tail}
|
||||
tailStart := 3 // msgs[3:] is the preserved tail
|
||||
|
||||
got := reinjectSkills(msgs, tailStart)
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("want 1 re-injected skill (latest x, y skipped), got %d", len(got))
|
||||
}
|
||||
if name, _ := llm.SkillInvocationName(got[0]); name != "x" {
|
||||
t.Fatalf("want skill x, got %q", name)
|
||||
}
|
||||
if !strings.Contains(got[0].Text(), "NEW BODY") || strings.Contains(got[0].Text(), "OLD BODY") {
|
||||
t.Fatalf("should keep the latest invocation body, got %q", got[0].Text())
|
||||
}
|
||||
}
|
||||
|
||||
func TestReinjectSkillsTruncatesToBudget(t *testing.T) {
|
||||
huge := strings.Repeat("z", maxSkillReinjectTokens*4*3) // ~3x the per-skill char cap
|
||||
msgs := []llm.Message{
|
||||
llm.SkillInvocationMessage("big", "", huge),
|
||||
bigMsg(llm.RoleUser, 10),
|
||||
}
|
||||
got := reinjectSkills(msgs, 1)
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("want 1 re-injected skill, got %d", len(got))
|
||||
}
|
||||
if EstimateTokens(got) > maxSkillReinjectTokens+50 {
|
||||
t.Fatalf("re-injected skill not truncated to per-skill budget: %d tokens", EstimateTokens(got))
|
||||
}
|
||||
if !strings.Contains(got[0].Text(), "truncated") {
|
||||
t.Fatal("truncated skill should carry a truncation note")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCircuitBreakerTrips(t *testing.T) {
|
||||
c := New(smallWindow(), func(context.Context, []llm.Message) (string, error) {
|
||||
return "", errors.New("boom")
|
||||
})
|
||||
mk := func() []llm.Message {
|
||||
var m []llm.Message
|
||||
for i := 0; i < 6; i++ {
|
||||
m = append(m, bigMsg(llm.RoleUser, 4000))
|
||||
}
|
||||
return m
|
||||
}
|
||||
for i := 0; i < 4; i++ {
|
||||
c.autoCompact(context.Background(), mk(), 1000, "auto")
|
||||
}
|
||||
if !c.tripped {
|
||||
t.Fatal("breaker should trip after 3 failures")
|
||||
}
|
||||
}
|
||||
|
||||
// resultText returns the concatenated text of a tool_result block's content.
|
||||
func resultText(b llm.ContentBlock) string {
|
||||
var s strings.Builder
|
||||
for _, cb := range b.Content {
|
||||
s.WriteString(cb.Text)
|
||||
}
|
||||
return s.String()
|
||||
}
|
||||
|
||||
// readPair builds an assistant Read tool_use + its user tool_result.
|
||||
func toolPair(name, id, body string) []llm.Message {
|
||||
return []llm.Message{
|
||||
{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{Type: llm.BlockToolUse, ID: id, Name: name, Input: []byte(`{}`)}}},
|
||||
{Role: llm.RoleUser, Content: []llm.ContentBlock{llm.ToolResultText(id, body, false)}},
|
||||
}
|
||||
}
|
||||
|
||||
// TestMicroCompactKeepsRecentClearsOld verifies the keep-last-N semantics: with
|
||||
// microKeepRecent (5) recent compactable results and older ones beyond that, only
|
||||
// the older results are cleared.
|
||||
func TestMicroCompactKeepsRecentClearsOld(t *testing.T) {
|
||||
c := New(Config{ContextWindow: 16000, MaxOutputTokens: 1000}, nil)
|
||||
var msgs []llm.Message
|
||||
total := microKeepRecent + 2 // 2 older than the kept window
|
||||
for i := 0; i < total; i++ {
|
||||
msgs = append(msgs, toolPair("Read", "r"+strconv.Itoa(i), strings.Repeat("y", 500))...)
|
||||
}
|
||||
out, changed := c.microCompact(msgs)
|
||||
if !changed {
|
||||
t.Fatal("microCompact should report a change")
|
||||
}
|
||||
// The first two Read results (oldest) must be cleared; the last five kept.
|
||||
cleared := 0
|
||||
for i, m := range out {
|
||||
if len(m.Content) == 1 && m.Content[0].Type == llm.BlockToolResult {
|
||||
if strings.Contains(resultText(m.Content[0]), "cleared") {
|
||||
cleared++
|
||||
} else if i < 2*2 { // one of the two oldest result messages
|
||||
t.Fatalf("oldest result at %d should be cleared", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
if cleared != 2 {
|
||||
t.Fatalf("want 2 old results cleared, got %d", cleared)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMicroCompactSkipsNonCompactableTools verifies non-compactable tool results
|
||||
// are never cleared, even when older than the kept window.
|
||||
func TestMicroCompactSkipsNonCompactableTools(t *testing.T) {
|
||||
c := New(Config{ContextWindow: 16000, MaxOutputTokens: 1000}, nil)
|
||||
var msgs []llm.Message
|
||||
msgs = append(msgs, toolPair("Agent", "a0", strings.Repeat("y", 5000))...) // oldest, non-compactable
|
||||
for i := 0; i < microKeepRecent+1; i++ {
|
||||
msgs = append(msgs, toolPair("Read", "r"+strconv.Itoa(i), strings.Repeat("y", 500))...)
|
||||
}
|
||||
out, _ := c.microCompact(msgs)
|
||||
if strings.Contains(resultText(out[1].Content[0]), "cleared") {
|
||||
t.Fatal("Agent (non-compactable) result should NOT be cleared")
|
||||
}
|
||||
}
|
||||
|
||||
func TestThresholdMath(t *testing.T) {
|
||||
// reserved = min(maxOutputTokens, 20000) = 8000.
|
||||
c := New(Config{ContextWindow: 200000, MaxOutputTokens: 8000}, nil)
|
||||
if c.effectiveWindow() != 200000-8000 {
|
||||
t.Fatalf("effectiveWindow=%d, want 192000", c.effectiveWindow())
|
||||
}
|
||||
if c.buffer() != 13000 {
|
||||
t.Fatalf("buffer=%d", c.buffer())
|
||||
}
|
||||
if c.autoThreshold() != 192000-13000 {
|
||||
t.Fatalf("autoThreshold=%d, want 179000", c.autoThreshold())
|
||||
}
|
||||
// Large window → larger buffer.
|
||||
big := New(Config{ContextWindow: 1000000, MaxOutputTokens: 32000}, nil)
|
||||
if big.buffer() != 50000 || big.reservedForSummary() != 20000 {
|
||||
t.Fatalf("big: buffer=%d reserved=%d", big.buffer(), big.reservedForSummary())
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsOverflow(t *testing.T) {
|
||||
if !IsOverflow(errors.New("anthropic: status 400: prompt is too long")) {
|
||||
t.Fatal("should detect prompt too long")
|
||||
}
|
||||
if IsOverflow(errors.New("network timeout")) {
|
||||
t.Fatal("false positive")
|
||||
}
|
||||
}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
package compaction
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
|
||||
func manyReadPairs(n int) []llm.Message {
|
||||
var msgs []llm.Message
|
||||
for i := range n {
|
||||
msgs = append(msgs, toolPair("Read", "r"+strconv.Itoa(i), strings.Repeat("y", 200))...)
|
||||
}
|
||||
return msgs
|
||||
}
|
||||
|
||||
func countCleared(msgs []llm.Message) int {
|
||||
n := 0
|
||||
for _, m := range msgs {
|
||||
for _, b := range m.Content {
|
||||
if b.Type == llm.BlockToolResult && strings.Contains(resultText(b), "cleared") {
|
||||
n++
|
||||
}
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func TestMicroExactlyKeepRecentNoChange(t *testing.T) {
|
||||
c := New(Config{ContextWindow: 200000}, nil)
|
||||
msgs := manyReadPairs(microKeepRecent) // exactly the kept window
|
||||
out, changed := c.microCompact(msgs)
|
||||
if changed || countCleared(out) != 0 {
|
||||
t.Fatalf("with exactly %d results nothing should clear (changed=%v cleared=%d)", microKeepRecent, changed, countCleared(out))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMicroClearsOldestBeyondWindow(t *testing.T) {
|
||||
c := New(Config{ContextWindow: 200000}, nil)
|
||||
for _, extra := range []int{1, 3, 7} {
|
||||
msgs := manyReadPairs(microKeepRecent + extra)
|
||||
out, changed := c.microCompact(msgs)
|
||||
if !changed {
|
||||
t.Fatalf("extra=%d: expected a change", extra)
|
||||
}
|
||||
if got := countCleared(out); got != extra {
|
||||
t.Fatalf("extra=%d: cleared=%d, want %d (all but the last %d)", extra, got, extra, microKeepRecent)
|
||||
}
|
||||
// The most recent microKeepRecent results must be intact.
|
||||
if strings.Contains(resultText(out[len(out)-1].Content[0]), "cleared") {
|
||||
t.Fatalf("extra=%d: most-recent result was wrongly cleared", extra)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMicroNoCompactableNoChange(t *testing.T) {
|
||||
c := New(Config{ContextWindow: 200000}, nil)
|
||||
var msgs []llm.Message
|
||||
for i := range 10 {
|
||||
msgs = append(msgs, toolPair("Agent", "a"+strconv.Itoa(i), strings.Repeat("y", 500))...)
|
||||
}
|
||||
if _, changed := c.microCompact(msgs); changed {
|
||||
t.Fatal("no compactable tools → no change")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMicroIdempotent(t *testing.T) {
|
||||
c := New(Config{ContextWindow: 200000}, nil)
|
||||
msgs := manyReadPairs(microKeepRecent + 3)
|
||||
out1, changed1 := c.microCompact(msgs)
|
||||
if !changed1 {
|
||||
t.Fatal("first pass should change")
|
||||
}
|
||||
out2, changed2 := c.microCompact(out1)
|
||||
if changed2 {
|
||||
t.Fatal("second pass should be a no-op (already cleared)")
|
||||
}
|
||||
if countCleared(out1) != countCleared(out2) {
|
||||
t.Fatal("idempotence violated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMicroPreservesSiblingBlocks(t *testing.T) {
|
||||
c := New(Config{ContextWindow: 200000}, nil)
|
||||
// Target result (oldest) lives in a message alongside a text block.
|
||||
msgs := []llm.Message{
|
||||
{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{Type: llm.BlockToolUse, ID: "t0", Name: "Read"}}},
|
||||
{Role: llm.RoleUser, Content: []llm.ContentBlock{
|
||||
llm.TextBlock("KEEP ME"),
|
||||
llm.ToolResultText("t0", strings.Repeat("z", 500), false),
|
||||
}},
|
||||
}
|
||||
msgs = append(msgs, manyReadPairs(microKeepRecent)...) // push t0 out of the keep window
|
||||
out, changed := c.microCompact(msgs)
|
||||
if !changed {
|
||||
t.Fatal("expected a change")
|
||||
}
|
||||
sib := out[1].Content
|
||||
if len(sib) != 2 || sib[0].Text != "KEEP ME" {
|
||||
t.Fatalf("sibling text block not preserved: %+v", sib)
|
||||
}
|
||||
if !strings.Contains(resultText(sib[1]), "cleared") {
|
||||
t.Fatal("target result should be cleared")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMicroKeepsRecentToolResult(t *testing.T) {
|
||||
c := New(Config{ContextWindow: 200000}, nil)
|
||||
msgs := manyReadPairs(microKeepRecent + 1)
|
||||
out, _ := c.microCompact(msgs)
|
||||
// Only the oldest (r0) result is cleared; r1..r5 stay.
|
||||
if !strings.Contains(resultText(out[1].Content[0]), "cleared") {
|
||||
t.Fatal("oldest (r0) should be cleared")
|
||||
}
|
||||
for i := 1; i <= microKeepRecent; i++ {
|
||||
resultMsg := out[2*i+1] // each pair is [tool_use, tool_result]
|
||||
if strings.Contains(resultText(resultMsg.Content[0]), "cleared") {
|
||||
t.Fatalf("recent result r%d should be intact", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMicroMultipleResultsInOneMessage(t *testing.T) {
|
||||
c := New(Config{ContextWindow: 200000}, nil)
|
||||
// Parallel tool_use then one user message carrying both results.
|
||||
msgs := []llm.Message{
|
||||
{Role: llm.RoleAssistant, Content: []llm.ContentBlock{
|
||||
{Type: llm.BlockToolUse, ID: "a", Name: "Read"},
|
||||
{Type: llm.BlockToolUse, ID: "b", Name: "Grep"},
|
||||
}},
|
||||
{Role: llm.RoleUser, Content: []llm.ContentBlock{
|
||||
llm.ToolResultText("a", strings.Repeat("y", 300), false),
|
||||
llm.ToolResultText("b", strings.Repeat("y", 300), false),
|
||||
}},
|
||||
}
|
||||
msgs = append(msgs, manyReadPairs(microKeepRecent)...) // push a,b out of the window
|
||||
out, changed := c.microCompact(msgs)
|
||||
if !changed {
|
||||
t.Fatal("expected a change")
|
||||
}
|
||||
both := out[1].Content
|
||||
if !strings.Contains(resultText(both[0]), "cleared") || !strings.Contains(resultText(both[1]), "cleared") {
|
||||
t.Fatalf("both old results in the shared message should be cleared: %+v", both)
|
||||
}
|
||||
}
|
||||
|
||||
// A compactable tool_use whose result is still within the recent window must not
|
||||
// be cleared even if OTHER (older) compactable results exist.
|
||||
func TestMicroRecentWindowProtectsByToolNotMessage(t *testing.T) {
|
||||
c := New(Config{ContextWindow: 200000}, nil)
|
||||
msgs := manyReadPairs(microKeepRecent + 2)
|
||||
out, _ := c.microCompact(msgs)
|
||||
if got := countCleared(out); got != 2 {
|
||||
t.Fatalf("cleared=%d, want 2 (only the two oldest)", got)
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package compaction
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
|
||||
func TestIsOverflowStrings(t *testing.T) {
|
||||
cases := []struct {
|
||||
msg string
|
||||
want bool
|
||||
}{
|
||||
{"", false}, // nil handled separately below
|
||||
{"anthropic: status 400: prompt is too long", true},
|
||||
{"context length exceeded", true},
|
||||
{"maximum context window reached", true},
|
||||
{"error: context_length_exceeded", true},
|
||||
{"anthropic: status 413", true},
|
||||
{"network timeout", false},
|
||||
{"rate limited", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := IsOverflow(errors.New(tc.msg)); got != tc.want {
|
||||
t.Errorf("IsOverflow(%q)=%v, want %v", tc.msg, got, tc.want)
|
||||
}
|
||||
}
|
||||
if IsOverflow(nil) {
|
||||
t.Fatal("IsOverflow(nil) must be false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsOverflowMethodForm(t *testing.T) {
|
||||
c := New(Config{ContextWindow: 200000}, nil)
|
||||
if !c.IsOverflow(errors.New("prompt is too long")) {
|
||||
t.Fatal("method form should detect overflow")
|
||||
}
|
||||
if c.IsOverflow(errors.New("boom")) {
|
||||
t.Fatal("method form false positive")
|
||||
}
|
||||
}
|
||||
|
||||
// New applies all defaults for a zero Config: 200000 window, 8000 output,
|
||||
// 8 recent messages — verified through the derived thresholds and geometry.
|
||||
func TestDefaultsApplied(t *testing.T) {
|
||||
c := New(Config{}, func(context.Context, []llm.Message) (string, error) { return "D", nil })
|
||||
if c.effectiveWindow() != 192000 { // 200000 - 8000
|
||||
t.Fatalf("effectiveWindow=%d, want 192000 (defaulted window/output)", c.effectiveWindow())
|
||||
}
|
||||
if c.autoThreshold() != 179000 {
|
||||
t.Fatalf("autoThreshold=%d, want 179000", c.autoThreshold())
|
||||
}
|
||||
// KeepRecent defaulted to 8: summarizing 10 messages preserves the last 8.
|
||||
var msgs []llm.Message
|
||||
for range 10 {
|
||||
msgs = append(msgs, bigMsg(llm.RoleUser, 10))
|
||||
}
|
||||
out, ok := c.autoCompact(context.Background(), msgs, 100, "auto")
|
||||
if !ok {
|
||||
t.Fatal("autoCompact should run")
|
||||
}
|
||||
meta, _ := llm.ParseBoundaryMeta(out[llm.LastBoundaryIndex(out)])
|
||||
if meta.MessagesSummarized != 2 { // 10 - 8 kept
|
||||
t.Fatalf("messagesSummarized=%d, want 2 (KeepRecent defaulted to 8)", meta.MessagesSummarized)
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package compaction
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
|
||||
// Simulates a long-running conversation that repeatedly grows past the auto
|
||||
// threshold: each cycle appends several turns, then Pre is called with the model
|
||||
// reporting an over-threshold context. Every cycle must insert a NEW boundary,
|
||||
// the API view (what is actually sent) must stay bounded, and the retained
|
||||
// history must keep growing (non-destructive).
|
||||
func TestPreRepeatedCompactionOverGrowingConversation(t *testing.T) {
|
||||
rs := &recSummarizer{reply: "SUMMARY"}
|
||||
c := New(Config{ContextWindow: 200000, MaxOutputTokens: 8000, KeepRecent: 2}, rs.fn)
|
||||
|
||||
var msgs []llm.Message
|
||||
const cycles = 6
|
||||
for iter := range cycles {
|
||||
for j := range 5 { // conversation grows by 5 turns
|
||||
msgs = append(msgs, llm.UserText(fmt.Sprintf("turn-%d-%d", iter, j)))
|
||||
}
|
||||
// The model reports we are above the auto threshold (179000).
|
||||
msgs = c.Pre(context.Background(), msgs, 200000)
|
||||
|
||||
if got := boundaryCount(msgs); got != iter+1 {
|
||||
t.Fatalf("cycle %d: want %d boundaries, got %d", iter, iter+1, got)
|
||||
}
|
||||
if api := llm.MessagesForAPI(msgs); len(api) > 8 {
|
||||
t.Fatalf("cycle %d: API view unbounded (%d messages)", iter, len(api))
|
||||
}
|
||||
}
|
||||
|
||||
if rs.calls != cycles {
|
||||
t.Fatalf("want %d summarizer calls (one per cycle), got %d", cycles, rs.calls)
|
||||
}
|
||||
// Full history retained on disk-array; only a small slice reaches the model.
|
||||
if len(msgs) <= len(llm.MessagesForAPI(msgs)) {
|
||||
t.Fatal("retained history should far exceed the API view")
|
||||
}
|
||||
// The most recent boundary's summary is what leads the API view.
|
||||
if api := llm.MessagesForAPI(msgs); !strings.Contains(api[0].Text(), "SUMMARY") {
|
||||
t.Fatalf("API view should start with the latest summary, got %q", api[0].Text())
|
||||
}
|
||||
}
|
||||
|
||||
// Same repeated-compaction property, but driven purely by ESTIMATION (no
|
||||
// last-response hint): genuinely large messages push the estimated size past the
|
||||
// threshold each cycle, so compaction must keep firing on its own.
|
||||
func TestPreRepeatedCompactionViaEstimation(t *testing.T) {
|
||||
rs := &recSummarizer{reply: "S"}
|
||||
c := New(Config{ContextWindow: 200000, MaxOutputTokens: 8000, KeepRecent: 2}, rs.fn)
|
||||
|
||||
// autoThreshold = 179000 → count = chars/3 must exceed it (chars > ~537000).
|
||||
// Append 4 big turns per cycle (200000 chars each) so the post-boundary window
|
||||
// re-crosses the threshold AND exceeds KeepRecent (2) so a head remains.
|
||||
big := func(tag string) llm.Message { return llm.UserText(tag + strings.Repeat("x", 200000)) }
|
||||
|
||||
var msgs []llm.Message
|
||||
prev := 0
|
||||
for iter := range 4 {
|
||||
for j := range 4 {
|
||||
msgs = append(msgs, big(fmt.Sprintf("c%d-%d", iter, j)))
|
||||
}
|
||||
msgs = c.Pre(context.Background(), msgs, 0) // no last-response hint → estimation
|
||||
|
||||
got := boundaryCount(msgs)
|
||||
if got <= prev {
|
||||
t.Fatalf("cycle %d: estimation-driven compaction did not fire (boundaries stayed %d)", iter, got)
|
||||
}
|
||||
prev = got
|
||||
// The API view must stay under the threshold after each compaction.
|
||||
if tok := c.count(msgs, 0); tok >= c.autoThreshold() {
|
||||
t.Fatalf("cycle %d: API view still above autoThreshold after compaction: %d", iter, tok)
|
||||
}
|
||||
}
|
||||
if prev == 0 {
|
||||
t.Fatal("expected estimation-driven compaction to fire at least once")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package compaction
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
|
||||
// With many skills behind the boundary whose combined size exceeds the total
|
||||
// re-injection budget (25000 tokens), the newest fit and the oldest are dropped —
|
||||
// exercising the candidate/kept sort paths and the over-budget branch.
|
||||
func TestReinjectSkillsBudgetDropsOldest(t *testing.T) {
|
||||
const n = 8
|
||||
var msgs []llm.Message
|
||||
for i := range n {
|
||||
// Each body is large enough that truncation caps it near the per-skill cap,
|
||||
// so several skills together blow the total budget.
|
||||
body := strings.Repeat("x", 24000)
|
||||
msgs = append(msgs, llm.SkillInvocationMessage("skill"+string(rune('A'+i)), "", body))
|
||||
}
|
||||
msgs = append(msgs, llm.UserText("tail")) // preserved tail
|
||||
tailStart := n // all skills are behind the boundary
|
||||
|
||||
got := reinjectSkills(msgs, tailStart)
|
||||
if len(got) < 2 {
|
||||
t.Fatalf("expected multiple skills re-injected, got %d", len(got))
|
||||
}
|
||||
if len(got) >= n {
|
||||
t.Fatalf("total budget should drop at least one skill, kept %d of %d", len(got), n)
|
||||
}
|
||||
// Kept skills stay in chronological (idx-ascending) order.
|
||||
for i := 1; i < len(got); i++ {
|
||||
if pos(got[i]) < pos(got[i-1]) {
|
||||
t.Fatal("re-injected skills must be in chronological order")
|
||||
}
|
||||
}
|
||||
// The oldest skill (skillA) is the one dropped when over budget.
|
||||
for _, m := range got {
|
||||
if name, _ := llm.SkillInvocationName(m); name == "skillA" {
|
||||
t.Fatal("oldest skill should be dropped first when over budget")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// pos returns a stable ordering key from a skill message's body letter (the tests
|
||||
// build bodies that keep their name letter), used only to check ordering.
|
||||
func pos(m llm.Message) int {
|
||||
name, _ := llm.SkillInvocationName(m)
|
||||
if name == "" {
|
||||
return 0
|
||||
}
|
||||
return int(name[len(name)-1])
|
||||
}
|
||||
|
||||
// A single skill under budget is re-injected as-is (baseline for the budget path).
|
||||
func TestReinjectSkillsSingleFits(t *testing.T) {
|
||||
msgs := []llm.Message{
|
||||
llm.SkillInvocationMessage("solo", "/s", "1. do a thing"),
|
||||
llm.UserText("tail"),
|
||||
}
|
||||
got := reinjectSkills(msgs, 1)
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("want 1 re-injected skill, got %d", len(got))
|
||||
}
|
||||
if name, _ := llm.SkillInvocationName(got[0]); name != "solo" {
|
||||
t.Fatalf("want solo, got %q", name)
|
||||
}
|
||||
}
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
package compaction
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"iter"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
|
||||
// captureProvider records each request and yields a scripted reply, optionally
|
||||
// failing the first failN Stream calls with failErr (default: an overflow error).
|
||||
type captureProvider struct {
|
||||
reqs []llm.CompletionRequest
|
||||
reply string
|
||||
failN int
|
||||
failErr error
|
||||
calls int
|
||||
}
|
||||
|
||||
func (p *captureProvider) Stream(_ context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
|
||||
p.calls++
|
||||
p.reqs = append(p.reqs, req)
|
||||
call := p.calls
|
||||
return func(yield func(llm.StreamEvent, error) bool) {
|
||||
if call <= p.failN {
|
||||
e := p.failErr
|
||||
if e == nil {
|
||||
e = errors.New("prompt is too long")
|
||||
}
|
||||
yield(llm.StreamEvent{}, e)
|
||||
return
|
||||
}
|
||||
if !yield(llm.StreamEvent{Type: llm.SETextDelta, Text: p.reply}, nil) {
|
||||
return
|
||||
}
|
||||
yield(llm.StreamEvent{Type: llm.SEMessageStop}, nil)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *captureProvider) Complete(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
|
||||
acc := llm.NewAccumulator()
|
||||
for ev, err := range p.Stream(ctx, req) {
|
||||
if err != nil {
|
||||
return llm.Message{}, "", llm.Usage{}, err
|
||||
}
|
||||
acc.Add(ev)
|
||||
}
|
||||
return acc.Message(), acc.StopReason, acc.Usage, nil
|
||||
}
|
||||
|
||||
func asstText(s string) llm.Message {
|
||||
return llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{llm.TextBlock(s)}}
|
||||
}
|
||||
|
||||
// --- MicroCompact / AutoCompact are covered in compaction_test.go; these cover
|
||||
// the three-mechanism spec surface (COMPACTION-SPEC-3.md). ---
|
||||
|
||||
func TestReactiveRunsAutoCompactOnly(t *testing.T) {
|
||||
c := New(smallWindow(), func(context.Context, []llm.Message) (string, error) { return "DIGEST", nil })
|
||||
var msgs []llm.Message
|
||||
for range 8 {
|
||||
msgs = append(msgs, bigMsg(llm.RoleUser, 4000))
|
||||
}
|
||||
out, ok := c.Reactive(context.Background(), msgs)
|
||||
if !ok {
|
||||
t.Fatal("reactive should shrink the API view")
|
||||
}
|
||||
if llm.LastBoundaryIndex(out) < 0 {
|
||||
t.Fatal("reactive must insert a boundary (it runs AutoCompact)")
|
||||
}
|
||||
// Non-destructive: full history retained + boundary + summary, no snip removal.
|
||||
if len(out) != len(msgs)+2 {
|
||||
t.Fatalf("len(out)=%d, want %d (history + boundary + summary)", len(out), len(msgs)+2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReactiveNoSummarizerReturnsFalse(t *testing.T) {
|
||||
c := New(smallWindow(), nil) // summarize == nil → AutoCompact cannot run
|
||||
msgs := []llm.Message{bigMsg(llm.RoleUser, 4000), bigMsg(llm.RoleUser, 4000)}
|
||||
if _, ok := c.Reactive(context.Background(), msgs); ok {
|
||||
t.Fatal("with no summarizer, reactive cannot shrink (no snip fallback)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCountPrefersLastInputTokens(t *testing.T) {
|
||||
c := New(Config{ContextWindow: 200000}, nil)
|
||||
msgs := []llm.Message{bigMsg(llm.RoleUser, 4000)}
|
||||
if got := c.count(msgs, 12345); got != 12345 {
|
||||
t.Fatalf("count should prefer lastInputTokens=12345, got %d", got)
|
||||
}
|
||||
if est := c.count(msgs, 0); est <= 0 {
|
||||
t.Fatal("estimation fallback should be > 0")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBufferKeyedOnEffectiveWindow(t *testing.T) {
|
||||
// Raw window 410k is above the 400k tier, but effectiveWindow 390k is below it.
|
||||
c := New(Config{ContextWindow: 410000, MaxOutputTokens: 20000}, nil)
|
||||
if c.buffer() != 13000 {
|
||||
t.Fatalf("buffer=%d, want 13000 (keyed on effectiveWindow=390000)", c.buffer())
|
||||
}
|
||||
c2 := New(Config{ContextWindow: 420000, MaxOutputTokens: 20000}, nil) // eff=400000
|
||||
if c2.buffer() != 30000 {
|
||||
t.Fatalf("buffer=%d, want 30000", c2.buffer())
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaxTurnGrowthMinCap(t *testing.T) {
|
||||
c := New(Config{ContextWindow: 200000, MaxOutputTokens: 64000}, nil)
|
||||
// reserved = min(64000, 20000) = 20000 → growth = 20000 + 15000.
|
||||
if c.maxTurnGrowth() != 35000 {
|
||||
t.Fatalf("maxTurnGrowth=%d, want 35000", c.maxTurnGrowth())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSummaryUsesContinuationPreamble(t *testing.T) {
|
||||
c := New(smallWindow(), func(context.Context, []llm.Message) (string, error) { return "DIGEST", nil })
|
||||
var msgs []llm.Message
|
||||
for range 8 {
|
||||
msgs = append(msgs, bigMsg(llm.RoleUser, 4000))
|
||||
}
|
||||
out, ok := c.autoCompact(context.Background(), msgs, 100, "auto")
|
||||
if !ok {
|
||||
t.Fatal("autoCompact did not run")
|
||||
}
|
||||
if api := llm.MessagesForAPI(out); !strings.HasPrefix(api[0].Text(), "This session is being continued") {
|
||||
t.Fatalf("summary should carry the continuation preamble, got %q", api[0].Text())
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatCompactSummary(t *testing.T) {
|
||||
raw := "<analysis>\nscratch thoughts\n</analysis>\n\n<summary>\nThe outcome.\n</summary>"
|
||||
got := formatCompactSummary(raw)
|
||||
if strings.Contains(got, "analysis") || strings.Contains(got, "scratch") {
|
||||
t.Fatalf("<analysis> not stripped: %q", got)
|
||||
}
|
||||
if got != "Summary:\nThe outcome." {
|
||||
t.Fatalf("got %q, want %q", got, "Summary:\nThe outcome.")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupByAPIRoundAndTruncate(t *testing.T) {
|
||||
msgs := []llm.Message{llm.UserText("u0"), asstText("a1"), llm.UserText("u1"), asstText("a2")}
|
||||
if g := groupByAPIRound(msgs); len(g) != 3 {
|
||||
t.Fatalf("groups=%d, want 3 ([u0][a1 u1][a2])", len(g))
|
||||
}
|
||||
out, ok := truncateHeadForPTLRetry(msgs)
|
||||
if !ok {
|
||||
t.Fatal("should truncate (≥2 groups)")
|
||||
}
|
||||
if out[0].Text() != ptlRetryMarker {
|
||||
t.Fatalf("result starting with an assistant must be marker-prefixed, got %q", out[0].Text())
|
||||
}
|
||||
if _, ok := truncateHeadForPTLRetry([]llm.Message{llm.UserText("only")}); ok {
|
||||
t.Fatal("a single group cannot be truncated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPairForReplayDropsDangling(t *testing.T) {
|
||||
msgs := []llm.Message{
|
||||
{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{Type: llm.BlockToolUse, ID: "x", Name: "Read"}}}, // no result
|
||||
llm.UserText("keep me"),
|
||||
{Role: llm.RoleUser, Content: []llm.ContentBlock{llm.ToolResultText("y", "orphan", false)}}, // no use
|
||||
}
|
||||
out := pairForReplay(msgs)
|
||||
if len(out) != 1 || out[0].Text() != "keep me" {
|
||||
t.Fatalf("dangling tool blocks should be dropped, got %+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderSummarizerReplaysRealMessages(t *testing.T) {
|
||||
p := &captureProvider{reply: "<summary>DONE</summary>"}
|
||||
s := ProviderSummarizer(p, 8000, false)
|
||||
head := []llm.Message{llm.UserText("hello"), asstText("hi")}
|
||||
got, err := s(context.Background(), head)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != "Summary:\nDONE" {
|
||||
t.Fatalf("summary format: %q", got)
|
||||
}
|
||||
if len(p.reqs) != 1 {
|
||||
t.Fatalf("calls=%d, want 1", len(p.reqs))
|
||||
}
|
||||
req := p.reqs[0]
|
||||
if req.Thinking != "disabled" {
|
||||
t.Fatalf("thinking=%q, want disabled", req.Thinking)
|
||||
}
|
||||
if req.MaxTokens != 8000 { // min(20000, 8000)
|
||||
t.Fatalf("maxTokens=%d, want 8000", req.MaxTokens)
|
||||
}
|
||||
if len(req.System) != 1 || req.System[0] != summarySystemPrompt {
|
||||
t.Fatalf("system prompt not set: %v", req.System)
|
||||
}
|
||||
if len(req.Messages) != 3 || req.Messages[0].Text() != "hello" {
|
||||
t.Fatalf("real messages not replayed: %+v", req.Messages)
|
||||
}
|
||||
if !strings.Contains(req.Messages[2].Text(), "CRITICAL: Respond with TEXT ONLY") {
|
||||
t.Fatal("summary-request prompt must be the last message")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderSummarizerCapsAt20k(t *testing.T) {
|
||||
p := &captureProvider{reply: "<summary>X</summary>"}
|
||||
_, _ = ProviderSummarizer(p, 0, false)(context.Background(), []llm.Message{llm.UserText("hi")})
|
||||
if p.reqs[0].MaxTokens != compactMaxOutputTokens {
|
||||
t.Fatalf("maxTokens=%d, want %d", p.reqs[0].MaxTokens, compactMaxOutputTokens)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderSummarizerPTLRetry(t *testing.T) {
|
||||
p := &captureProvider{reply: "<summary>OK</summary>", failN: 1} // first call overflows
|
||||
s := ProviderSummarizer(p, 0, false)
|
||||
head := []llm.Message{llm.UserText("u0"), asstText("a1"), llm.UserText("u1"), asstText("a2")}
|
||||
got, err := s(context.Background(), head)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != "Summary:\nOK" {
|
||||
t.Fatalf("got %q", got)
|
||||
}
|
||||
if len(p.reqs) != 2 {
|
||||
t.Fatalf("want 2 calls (overflow + truncated retry), got %d", len(p.reqs))
|
||||
}
|
||||
// The retry dropped the oldest API-round group (u0) and prepended the marker.
|
||||
retry := p.reqs[1].Messages
|
||||
if retry[0].Text() != ptlRetryMarker {
|
||||
t.Fatalf("retry should start with the PTL marker, got %q", retry[0].Text())
|
||||
}
|
||||
for _, m := range retry {
|
||||
if m.Text() == "u0" {
|
||||
t.Fatal("retry should have dropped the oldest group (u0)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderSummarizerStreamingRetry(t *testing.T) {
|
||||
p := &captureProvider{reply: "<summary>R</summary>", failN: 1, failErr: errors.New("network blip")}
|
||||
s := ProviderSummarizer(p, 0, false)
|
||||
got, err := s(context.Background(), []llm.Message{llm.UserText("hi")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != "Summary:\nR" {
|
||||
t.Fatalf("got %q", got)
|
||||
}
|
||||
if len(p.reqs) != 2 { // transient failure retried once within streamSummary
|
||||
t.Fatalf("want 2 stream attempts, got %d", len(p.reqs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderSummarizerNonOverflowErrorSurfaces(t *testing.T) {
|
||||
// A persistent non-overflow error exhausts streaming retries and surfaces.
|
||||
p := &captureProvider{reply: "x", failN: 99, failErr: errors.New("boom")}
|
||||
if _, err := ProviderSummarizer(p, 0, false)(context.Background(), []llm.Message{llm.UserText("hi")}); err == nil {
|
||||
t.Fatal("expected error to surface")
|
||||
}
|
||||
if len(p.reqs) != maxStreamingRetries {
|
||||
t.Fatalf("want %d stream attempts, got %d", maxStreamingRetries, len(p.reqs))
|
||||
}
|
||||
}
|
||||
+335
@@ -0,0 +1,335 @@
|
||||
package compaction
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
|
||||
// Summary generation constants (== claude-code).
|
||||
const (
|
||||
compactMaxOutputTokens = 20000 // COMPACT_MAX_OUTPUT_TOKENS
|
||||
maxPTLRetries = 3 // MAX_PTL_RETRIES
|
||||
maxStreamingRetries = 2 // MAX_COMPACT_STREAMING_RETRIES
|
||||
ptlRetryMarker = "[earlier conversation truncated for compaction retry]" // PTL_RETRY_MARKER
|
||||
)
|
||||
|
||||
// summarySystemPrompt is the summarizer's system prompt (== claude-code
|
||||
// streamCompactSummary fallback path). Thinking is disabled and no tools are
|
||||
// offered; the no-tools guardrails live in the user prompt (§7).
|
||||
const summarySystemPrompt = "You are a helpful AI assistant tasked with summarizing conversations."
|
||||
|
||||
// ProviderSummarizer builds a Summarizer backed by an llm.Provider. It replays
|
||||
// the real conversation messages (not a rendered text transcript) followed by the
|
||||
// summary-request user message, with thinking disabled and output capped at
|
||||
// min(20000, maxOutputTokens). It retries transient stream failures
|
||||
// (MAX_COMPACT_STREAMING_RETRIES) and, if the summary request itself overflows,
|
||||
// drops the oldest API-round groups and retries (MAX_PTL_RETRIES).
|
||||
func ProviderSummarizer(p llm.Provider, maxOutputTokens int, nonStreaming bool) Summarizer {
|
||||
maxOut := compactMaxOutputTokens
|
||||
if maxOutputTokens > 0 && maxOutputTokens < maxOut {
|
||||
maxOut = maxOutputTokens
|
||||
}
|
||||
return func(ctx context.Context, msgs []llm.Message) (string, error) {
|
||||
work := pairForReplay(msgs)
|
||||
var lastErr error
|
||||
for attempt := 0; attempt <= maxPTLRetries; attempt++ {
|
||||
raw, err := streamSummary(ctx, p, maxOut, work, nonStreaming)
|
||||
if err == nil {
|
||||
return formatCompactSummary(raw), nil
|
||||
}
|
||||
if !IsOverflow(err) {
|
||||
return "", err
|
||||
}
|
||||
lastErr = err
|
||||
truncated, ok := truncateHeadForPTLRetry(work)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
work = truncated
|
||||
}
|
||||
return "", lastErr
|
||||
}
|
||||
}
|
||||
|
||||
// streamSummary issues one summary request (head + summary-request message),
|
||||
// retrying transient (non-overflow) stream failures. Overflow is returned
|
||||
// immediately so the caller can truncate and retry at a coarser granularity.
|
||||
func streamSummary(ctx context.Context, p llm.Provider, maxOut int, head []llm.Message, nonStreaming bool) (string, error) {
|
||||
reqMsgs := make([]llm.Message, 0, len(head)+1)
|
||||
reqMsgs = append(reqMsgs, head...)
|
||||
reqMsgs = append(reqMsgs, llm.UserText(compactPrompt))
|
||||
req := llm.CompletionRequest{
|
||||
System: []string{summarySystemPrompt},
|
||||
Messages: reqMsgs,
|
||||
MaxTokens: maxOut,
|
||||
Thinking: "disabled",
|
||||
}
|
||||
var lastErr error
|
||||
for range maxStreamingRetries {
|
||||
if ctx.Err() != nil {
|
||||
return "", ctx.Err()
|
||||
}
|
||||
var text string
|
||||
var callErr error
|
||||
if nonStreaming {
|
||||
msg, _, _, err := p.Complete(ctx, req)
|
||||
text, callErr = msg.Text(), err
|
||||
} else {
|
||||
acc := llm.NewAccumulator()
|
||||
for ev, err := range p.Stream(ctx, req) {
|
||||
if err != nil {
|
||||
callErr = err
|
||||
break
|
||||
}
|
||||
acc.Add(ev)
|
||||
}
|
||||
if callErr == nil {
|
||||
text = acc.Message().Text()
|
||||
}
|
||||
}
|
||||
if callErr == nil {
|
||||
return text, nil
|
||||
}
|
||||
if IsOverflow(callErr) {
|
||||
return "", callErr // PTL — let the caller truncate, don't burn streaming retries
|
||||
}
|
||||
lastErr = callErr // transient — retry
|
||||
}
|
||||
return "", lastErr
|
||||
}
|
||||
|
||||
// pairForReplay drops dangling tool_use / tool_result blocks so the replayed head
|
||||
// is a valid request (the working-set boundary may split a tool_use from its
|
||||
// result). Mirrors claude-code's ensureToolResultPairing intent (drop, not
|
||||
// synthesize — summarization only needs the surrounding text). Messages left
|
||||
// empty are removed.
|
||||
func pairForReplay(msgs []llm.Message) []llm.Message {
|
||||
useIDs := map[string]bool{}
|
||||
resIDs := map[string]bool{}
|
||||
for _, m := range msgs {
|
||||
for _, b := range m.Content {
|
||||
switch b.Type {
|
||||
case llm.BlockToolUse:
|
||||
useIDs[b.ID] = true
|
||||
case llm.BlockToolResult:
|
||||
resIDs[b.ToolUseID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
out := make([]llm.Message, 0, len(msgs))
|
||||
for _, m := range msgs {
|
||||
nc := make([]llm.ContentBlock, 0, len(m.Content))
|
||||
for _, b := range m.Content {
|
||||
switch b.Type {
|
||||
case llm.BlockToolUse:
|
||||
if !resIDs[b.ID] {
|
||||
continue
|
||||
}
|
||||
case llm.BlockToolResult:
|
||||
if !useIDs[b.ToolUseID] {
|
||||
continue
|
||||
}
|
||||
}
|
||||
nc = append(nc, b)
|
||||
}
|
||||
if len(nc) > 0 {
|
||||
out = append(out, llm.Message{Role: m.Role, Content: nc})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// truncateHeadForPTLRetry drops the oldest API-round groups when the summary
|
||||
// request itself overflows (== claude-code truncateHeadForPTLRetry, 20% fallback
|
||||
// branch — Norma cannot read a precise token gap from the provider error). It
|
||||
// strips a leading retry marker, groups by API round, drops floor(20%) of the
|
||||
// oldest groups (≥1, keeping ≥1), and re-prepends the marker if the result would
|
||||
// start with an assistant message (the API requires a user-first message).
|
||||
func truncateHeadForPTLRetry(msgs []llm.Message) ([]llm.Message, bool) {
|
||||
input := msgs
|
||||
if len(input) > 0 && isPTLMarker(input[0]) {
|
||||
input = input[1:]
|
||||
}
|
||||
groups := groupByAPIRound(input)
|
||||
if len(groups) < 2 {
|
||||
return nil, false
|
||||
}
|
||||
dropCount := len(groups) / 5 // floor(len * 0.2)
|
||||
dropCount = max(dropCount, 1)
|
||||
dropCount = min(dropCount, len(groups)-1)
|
||||
var sliced []llm.Message
|
||||
for _, g := range groups[dropCount:] {
|
||||
sliced = append(sliced, g...)
|
||||
}
|
||||
if len(sliced) == 0 {
|
||||
return nil, false
|
||||
}
|
||||
if sliced[0].Role == llm.RoleAssistant {
|
||||
sliced = append([]llm.Message{llm.UserText(ptlRetryMarker)}, sliced...)
|
||||
}
|
||||
return sliced, true
|
||||
}
|
||||
|
||||
func isPTLMarker(m llm.Message) bool {
|
||||
return m.Role == llm.RoleUser && len(m.Content) == 1 &&
|
||||
m.Content[0].Type == llm.BlockText && m.Content[0].Text == ptlRetryMarker
|
||||
}
|
||||
|
||||
// groupByAPIRound partitions messages into one group per API round-trip: a new
|
||||
// group begins at each assistant message. Mirrors claude-code
|
||||
// groupMessagesByApiRound (Norma has one assistant message per round, so role
|
||||
// boundaries == message-id boundaries). Group 0 holds any leading preamble.
|
||||
func groupByAPIRound(msgs []llm.Message) [][]llm.Message {
|
||||
var groups [][]llm.Message
|
||||
var cur []llm.Message
|
||||
for _, m := range msgs {
|
||||
if m.Role == llm.RoleAssistant && len(cur) > 0 {
|
||||
groups = append(groups, cur)
|
||||
cur = nil
|
||||
}
|
||||
cur = append(cur, m)
|
||||
}
|
||||
if len(cur) > 0 {
|
||||
groups = append(groups, cur)
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
var (
|
||||
analysisRe = regexp.MustCompile(`(?s)<analysis>.*?</analysis>`)
|
||||
summaryRe = regexp.MustCompile(`(?s)<summary>(.*?)</summary>`)
|
||||
blankRe = regexp.MustCompile(`\n{2,}`)
|
||||
)
|
||||
|
||||
// formatCompactSummary post-processes the model's raw output (== claude-code
|
||||
// formatCompactSummary): strip the <analysis> scratchpad, unwrap <summary> into a
|
||||
// "Summary:" header, and collapse blank-line runs.
|
||||
func formatCompactSummary(raw string) string {
|
||||
s := analysisRe.ReplaceAllString(raw, "")
|
||||
if m := summaryRe.FindStringSubmatch(s); m != nil {
|
||||
s = "Summary:\n" + strings.TrimSpace(m[1])
|
||||
}
|
||||
s = blankRe.ReplaceAllString(s, "\n\n")
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
// compactPrompt is the full summary-request user message:
|
||||
// NO_TOOLS_PREAMBLE + BASE_COMPACT_PROMPT + NO_TOOLS_TRAILER (§7).
|
||||
var compactPrompt = noToolsPreamble + baseCompactPrompt + noToolsTrailer
|
||||
|
||||
// noToolsPreamble == claude-code NO_TOOLS_PREAMBLE (prompt.ts:19-26).
|
||||
const noToolsPreamble = `CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.
|
||||
|
||||
- Do NOT use Read, Bash, Grep, Glob, Edit, Write, or ANY other tool.
|
||||
- You already have all the context you need in the conversation above.
|
||||
- Tool calls will be REJECTED and will waste your only turn — you will fail the task.
|
||||
- Your entire response must be plain text: an <analysis> block followed by a <summary> block.
|
||||
|
||||
`
|
||||
|
||||
// noToolsTrailer == claude-code NO_TOOLS_TRAILER (prompt.ts:269-272).
|
||||
const noToolsTrailer = `
|
||||
|
||||
REMINDER: Do NOT call any tools. Respond with plain text only — an <analysis> block followed by a <summary> block. Tool calls will be rejected and you will fail the task.`
|
||||
|
||||
// baseCompactPrompt == claude-code BASE_COMPACT_PROMPT (prompt.ts:61-143), verbatim
|
||||
// (including the DETAILED_ANALYSIS_INSTRUCTION_BASE it interpolates and the source
|
||||
// trailing spaces on the "All user messages:" and "...in your response. " lines).
|
||||
const baseCompactPrompt = `Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
|
||||
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
|
||||
|
||||
Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
|
||||
|
||||
1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
|
||||
- The user's explicit requests and intents
|
||||
- Your approach to addressing the user's requests
|
||||
- Key decisions, technical concepts and code patterns
|
||||
- Specific details like:
|
||||
- file names
|
||||
- full code snippets
|
||||
- function signatures
|
||||
- file edits
|
||||
- Errors that you ran into and how you fixed them
|
||||
- Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
||||
2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
|
||||
|
||||
Your summary should include the following sections:
|
||||
|
||||
1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
|
||||
2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
|
||||
3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
|
||||
4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
||||
5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
|
||||
6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
|
||||
7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
|
||||
8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
|
||||
9. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.
|
||||
If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.
|
||||
|
||||
Here's an example of how your output should be structured:
|
||||
|
||||
<example>
|
||||
<analysis>
|
||||
[Your thought process, ensuring all points are covered thoroughly and accurately]
|
||||
</analysis>
|
||||
|
||||
<summary>
|
||||
1. Primary Request and Intent:
|
||||
[Detailed description]
|
||||
|
||||
2. Key Technical Concepts:
|
||||
- [Concept 1]
|
||||
- [Concept 2]
|
||||
- [...]
|
||||
|
||||
3. Files and Code Sections:
|
||||
- [File Name 1]
|
||||
- [Summary of why this file is important]
|
||||
- [Summary of the changes made to this file, if any]
|
||||
- [Important Code Snippet]
|
||||
- [File Name 2]
|
||||
- [Important Code Snippet]
|
||||
- [...]
|
||||
|
||||
4. Errors and fixes:
|
||||
- [Detailed description of error 1]:
|
||||
- [How you fixed the error]
|
||||
- [User feedback on the error if any]
|
||||
- [...]
|
||||
|
||||
5. Problem Solving:
|
||||
[Description of solved problems and ongoing troubleshooting]
|
||||
|
||||
6. All user messages:
|
||||
- [Detailed non tool use user message]
|
||||
- [...]
|
||||
|
||||
7. Pending Tasks:
|
||||
- [Task 1]
|
||||
- [Task 2]
|
||||
- [...]
|
||||
|
||||
8. Current Work:
|
||||
[Precise description of current work]
|
||||
|
||||
9. Optional Next Step:
|
||||
[Optional Next step to take]
|
||||
|
||||
</summary>
|
||||
</example>
|
||||
|
||||
Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.
|
||||
|
||||
There may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:
|
||||
<example>
|
||||
## Compact Instructions
|
||||
When summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.
|
||||
</example>
|
||||
|
||||
<example>
|
||||
# Summary instructions
|
||||
When you are using compact - please focus on test output and code changes. Include file reads verbatim.
|
||||
</example>`
|
||||
@@ -0,0 +1,194 @@
|
||||
package compaction
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
|
||||
func toolUse(id, name string) llm.Message {
|
||||
return llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{Type: llm.BlockToolUse, ID: id, Name: name}}}
|
||||
}
|
||||
func toolResult(id string) llm.Message {
|
||||
return llm.Message{Role: llm.RoleUser, Content: []llm.ContentBlock{llm.ToolResultText(id, "body", false)}}
|
||||
}
|
||||
|
||||
// --- pairForReplay ---
|
||||
|
||||
func TestPairForReplayKeepsPaired(t *testing.T) {
|
||||
msgs := []llm.Message{llm.UserText("q"), toolUse("a", "Read"), toolResult("a"), asstText("done")}
|
||||
out := pairForReplay(msgs)
|
||||
if len(out) != 4 {
|
||||
t.Fatalf("paired blocks must be kept, got %d: %+v", len(out), out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPairForReplayDropsDanglingUse(t *testing.T) {
|
||||
msgs := []llm.Message{asstText("hi"), toolUse("a", "Read")} // result missing
|
||||
out := pairForReplay(msgs)
|
||||
if len(out) != 1 || out[0].Text() != "hi" {
|
||||
t.Fatalf("dangling tool_use should be dropped: %+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPairForReplayDropsDanglingResult(t *testing.T) {
|
||||
msgs := []llm.Message{llm.UserText("q"), toolResult("z")} // use missing
|
||||
out := pairForReplay(msgs)
|
||||
if len(out) != 1 || out[0].Text() != "q" {
|
||||
t.Fatalf("dangling tool_result should be dropped: %+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPairForReplayKeepsSiblingTextOfDroppedResult(t *testing.T) {
|
||||
msgs := []llm.Message{{Role: llm.RoleUser, Content: []llm.ContentBlock{
|
||||
llm.TextBlock("keep"),
|
||||
llm.ToolResultText("gone", "x", false), // dangling
|
||||
}}}
|
||||
out := pairForReplay(msgs)
|
||||
if len(out) != 1 || len(out[0].Content) != 1 || out[0].Content[0].Text != "keep" {
|
||||
t.Fatalf("sibling text should survive: %+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
// --- groupByAPIRound ---
|
||||
|
||||
func TestGroupByAPIRoundShapes(t *testing.T) {
|
||||
u := llm.UserText("u")
|
||||
a := asstText("a")
|
||||
cases := []struct {
|
||||
name string
|
||||
in []llm.Message
|
||||
want int
|
||||
}{
|
||||
{"empty", nil, 0},
|
||||
{"one user", []llm.Message{u}, 1},
|
||||
{"two user", []llm.Message{u, u}, 1},
|
||||
{"one assistant", []llm.Message{a}, 1},
|
||||
{"assistant then user", []llm.Message{a, u}, 1},
|
||||
{"user then assistant", []llm.Message{u, a}, 2},
|
||||
{"alternating", []llm.Message{u, a, u, a}, 3},
|
||||
{"consecutive assistants", []llm.Message{a, a}, 2},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := len(groupByAPIRound(tc.in)); got != tc.want {
|
||||
t.Errorf("%s: groups=%d, want %d", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- truncateHeadForPTLRetry ---
|
||||
|
||||
func TestTruncateSingleGroupFails(t *testing.T) {
|
||||
if _, ok := truncateHeadForPTLRetry([]llm.Message{llm.UserText("solo")}); ok {
|
||||
t.Fatal("a single group cannot be truncated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncateDropsTwentyPercent(t *testing.T) {
|
||||
// 10 groups: [U] then 9 lone assistants.
|
||||
msgs := []llm.Message{llm.UserText("u0")}
|
||||
for range 9 {
|
||||
msgs = append(msgs, asstText("a"))
|
||||
}
|
||||
if len(groupByAPIRound(msgs)) != 10 {
|
||||
t.Fatalf("precondition: want 10 groups, got %d", len(groupByAPIRound(msgs)))
|
||||
}
|
||||
out, ok := truncateHeadForPTLRetry(msgs)
|
||||
if !ok {
|
||||
t.Fatal("should truncate")
|
||||
}
|
||||
// drop floor(10*0.2)=2 groups → 8 assistants remain, marker prepended.
|
||||
if out[0].Text() != ptlRetryMarker || len(out) != 1+8 {
|
||||
t.Fatalf("want marker + 8 messages, got len=%d first=%q", len(out), out[0].Text())
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncateKeepsAtLeastOneGroup(t *testing.T) {
|
||||
out, ok := truncateHeadForPTLRetry([]llm.Message{llm.UserText("u"), asstText("a")}) // 2 groups
|
||||
if !ok {
|
||||
t.Fatal("should truncate 2 groups")
|
||||
}
|
||||
// drop 1 → [A] remains, marker prepended (result would start with assistant).
|
||||
if out[0].Text() != ptlRetryMarker || len(out) != 2 {
|
||||
t.Fatalf("want [marker, A], got %+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncateDoesNotDoubleMarker(t *testing.T) {
|
||||
msgs := []llm.Message{llm.UserText(ptlRetryMarker), llm.UserText("u"), asstText("a"), llm.UserText("u2"), asstText("a2")}
|
||||
out, ok := truncateHeadForPTLRetry(msgs)
|
||||
if !ok {
|
||||
t.Fatal("should truncate")
|
||||
}
|
||||
if out[0].Text() != ptlRetryMarker {
|
||||
t.Fatalf("first should be the (single) marker, got %q", out[0].Text())
|
||||
}
|
||||
if out[1].Text() == ptlRetryMarker {
|
||||
t.Fatal("marker must not be doubled")
|
||||
}
|
||||
}
|
||||
|
||||
// --- formatCompactSummary ---
|
||||
|
||||
func TestFormatCompactSummaryCases(t *testing.T) {
|
||||
cases := []struct{ name, in, want string }{
|
||||
{"plain passthrough", "just text", "just text"},
|
||||
{"analysis stripped, no summary tags", "<analysis>secret</analysis>\nHello", "Hello"},
|
||||
{"summary extracted ignoring surroundings", "before <summary>THE BODY</summary> after", "Summary:\nTHE BODY"},
|
||||
{"multiline analysis then summary", "<analysis>l1\nl2</analysis>\n<summary>ok</summary>", "Summary:\nok"},
|
||||
{"blank lines collapsed", "<summary>a\n\n\n\nb</summary>", "Summary:\na\n\nb"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := formatCompactSummary(tc.in); got != tc.want {
|
||||
t.Errorf("%s: got %q, want %q", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- ProviderSummarizer maxOut cap ---
|
||||
|
||||
func TestProviderSummarizerMaxOutCap(t *testing.T) {
|
||||
cases := []struct{ mo, want int }{
|
||||
{0, 20000}, // unset → cap
|
||||
{8000, 8000}, // below cap → passthrough
|
||||
{20000, 20000}, // at cap
|
||||
{25000, 20000}, // above cap → clamped
|
||||
{19999, 19999}, // just below cap
|
||||
}
|
||||
for _, tc := range cases {
|
||||
p := &captureProvider{reply: "<summary>x</summary>"}
|
||||
_, _ = ProviderSummarizer(p, tc.mo, false)(context.Background(), []llm.Message{llm.UserText("hi")})
|
||||
if p.reqs[0].MaxTokens != tc.want {
|
||||
t.Errorf("mo=%d: MaxTokens=%d, want %d", tc.mo, p.reqs[0].MaxTokens, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- retry / cancellation edges ---
|
||||
|
||||
func TestSummarizerContextCancelled(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
p := &captureProvider{reply: "x"}
|
||||
_, err := ProviderSummarizer(p, 0, false)(ctx, []llm.Message{llm.UserText("hi")})
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("want context.Canceled, got %v", err)
|
||||
}
|
||||
if p.calls != 0 {
|
||||
t.Fatalf("no stream should be issued on a cancelled ctx, calls=%d", p.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSummarizerPTLExhausts(t *testing.T) {
|
||||
p := &captureProvider{failN: 999} // every attempt overflows
|
||||
head := []llm.Message{llm.UserText("u0"), asstText("a1"), llm.UserText("u1"), asstText("a2")}
|
||||
_, err := ProviderSummarizer(p, 0, false)(context.Background(), head)
|
||||
if err == nil || !IsOverflow(err) {
|
||||
t.Fatalf("persistent overflow should surface an overflow error, got %v", err)
|
||||
}
|
||||
if p.calls < 2 {
|
||||
t.Fatalf("should have retried after truncation, calls=%d", p.calls)
|
||||
}
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
package compaction
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
|
||||
// raw builds a Compactor with the given cfg WITHOUT New's defaulting, so tests
|
||||
// can exercise the exact threshold math (incl. the reserved==0 guard).
|
||||
func raw(cw, mo int) *Compactor {
|
||||
return &Compactor{cfg: Config{ContextWindow: cw, MaxOutputTokens: mo}}
|
||||
}
|
||||
|
||||
func TestReservedForSummaryTable(t *testing.T) {
|
||||
cases := []struct {
|
||||
mo int
|
||||
want int
|
||||
}{
|
||||
{0, 20000}, // unset → full reservation
|
||||
{1, 1}, // below cap → passthrough
|
||||
{8000, 8000}, // typical
|
||||
{19999, 19999}, // just below cap
|
||||
{20000, 20000}, // at cap
|
||||
{20001, 20000}, // above cap → clamped
|
||||
{64000, 20000}, // well above cap → clamped
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := raw(200000, tc.mo).reservedForSummary(); got != tc.want {
|
||||
t.Errorf("reservedForSummary(mo=%d)=%d, want %d", tc.mo, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEffectiveWindowTable(t *testing.T) {
|
||||
cases := []struct{ cw, mo, want int }{
|
||||
{200000, 8000, 192000},
|
||||
{200000, 32000, 180000}, // reserved clamped to 20000
|
||||
{200000, 0, 180000}, // reserved==0 guard → 20000
|
||||
{16000, 1000, 15000},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := raw(tc.cw, tc.mo).effectiveWindow(); got != tc.want {
|
||||
t.Errorf("effectiveWindow(cw=%d,mo=%d)=%d, want %d", tc.cw, tc.mo, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// buffer tiers off the EFFECTIVE window, not the raw context window. These cases
|
||||
// straddle the 400k and 800k boundaries by exactly ±1 token of effective window
|
||||
// (reserved fixed at 20000).
|
||||
func TestBufferTierBoundaries(t *testing.T) {
|
||||
cases := []struct {
|
||||
cw, want int
|
||||
eff int
|
||||
}{
|
||||
{419999, 13000, 399999}, // just below 400k tier
|
||||
{420000, 30000, 400000}, // exactly 400k
|
||||
{819999, 30000, 799999}, // just below 800k tier
|
||||
{820000, 50000, 800000}, // exactly 800k
|
||||
}
|
||||
for _, tc := range cases {
|
||||
c := raw(tc.cw, 20000)
|
||||
if c.effectiveWindow() != tc.eff {
|
||||
t.Fatalf("precondition: effectiveWindow=%d, want %d", c.effectiveWindow(), tc.eff)
|
||||
}
|
||||
if got := c.buffer(); got != tc.want {
|
||||
t.Errorf("buffer(eff=%d)=%d, want %d", tc.eff, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoAndMicroThresholds(t *testing.T) {
|
||||
c := raw(200000, 8000) // eff=192000, buffer=13000
|
||||
if got, want := c.autoThreshold(), 179000; got != want {
|
||||
t.Errorf("autoThreshold=%d, want %d", got, want)
|
||||
}
|
||||
if got, want := c.microThreshold(), 115200; got != want { // 192000*6/10
|
||||
t.Errorf("microThreshold=%d, want %d", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaxTurnGrowthTable(t *testing.T) {
|
||||
cases := []struct{ mo, want int }{
|
||||
{8000, 23000}, // 8000 + 15000
|
||||
{20000, 35000}, // 20000 + 15000
|
||||
{64000, 35000}, // clamped reserved 20000 + 15000
|
||||
{0, 35000}, // reserved==0 guard → 20000 + 15000
|
||||
{19999, 34999}, // 19999 + 15000
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := raw(200000, tc.mo).maxTurnGrowth(); got != tc.want {
|
||||
t.Errorf("maxTurnGrowth(mo=%d)=%d, want %d", tc.mo, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// predictiveOver(tok) == tok + maxTurnGrowth > effectiveWindow. With eff=192000
|
||||
// and growth=23000, the tipping point is tok > 169000.
|
||||
func TestPredictiveOverBoundary(t *testing.T) {
|
||||
c := raw(200000, 8000)
|
||||
cases := []struct {
|
||||
tok int
|
||||
want bool
|
||||
}{
|
||||
{168999, false},
|
||||
{169000, false}, // 169000+23000 == 192000, not strictly greater
|
||||
{169001, true},
|
||||
{500000, true},
|
||||
{0, false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := c.predictiveOver(tc.tok); got != tc.want {
|
||||
t.Errorf("predictiveOver(%d)=%v, want %v", tc.tok, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCountPrefersLastInputTokensBranches(t *testing.T) {
|
||||
c := New(Config{ContextWindow: 200000}, nil)
|
||||
msgs := []llm.Message{llm.UserText(strings.Repeat("x", 40))} // est = 40/4=10 → count = 13
|
||||
if got := c.count(msgs, 999); got != 999 {
|
||||
t.Errorf("positive lastInputTokens should win: got %d", got)
|
||||
}
|
||||
est := c.count(msgs, 0)
|
||||
if est != 10*4/3 {
|
||||
t.Errorf("estimation path: got %d, want %d", est, 10*4/3)
|
||||
}
|
||||
if neg := c.count(msgs, -5); neg != est {
|
||||
t.Errorf("non-positive lastInputTokens should fall back to estimation: got %d, want %d", neg, est)
|
||||
}
|
||||
}
|
||||
|
||||
// EstimateTokens counts each block by type: text length, thinking length,
|
||||
// tool_use name+input, and nested tool_result content; total chars / 4.
|
||||
func TestEstimateTokensPerBlock(t *testing.T) {
|
||||
msgs := []llm.Message{
|
||||
llm.UserText("aaaa"), // 4
|
||||
{Role: llm.RoleAssistant, Content: []llm.ContentBlock{
|
||||
{Type: llm.BlockThinking, Thinking: "bbbbbbbb"}, // 8
|
||||
{Type: llm.BlockToolUse, Name: "Read", Input: []byte(`{"k":123}`)}, // 4 + 9 = 13
|
||||
}},
|
||||
{Role: llm.RoleUser, Content: []llm.ContentBlock{
|
||||
{Type: llm.BlockToolResult, ToolUseID: "x", Content: []llm.ContentBlock{llm.TextBlock("cccc")}}, // 4
|
||||
}},
|
||||
}
|
||||
// total chars = 4 + 8 + 13 + 4 = 29 → 29/4 = 7
|
||||
if got := EstimateTokens(msgs); got != 7 {
|
||||
t.Fatalf("EstimateTokens=%d, want 7", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEstimateTokensEmpty(t *testing.T) {
|
||||
if got := EstimateTokens(nil); got != 0 {
|
||||
t.Fatalf("EstimateTokens(nil)=%d, want 0", got)
|
||||
}
|
||||
if got := EstimateTokens([]llm.Message{{Role: llm.RoleUser}}); got != 0 {
|
||||
t.Fatalf("EstimateTokens(empty content)=%d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// count operates on the API view: only messages after the last boundary, with
|
||||
// the boundary marker itself excluded.
|
||||
func TestCountUsesMessagesForAPI(t *testing.T) {
|
||||
c := New(Config{ContextWindow: 200000}, nil)
|
||||
msgs := []llm.Message{
|
||||
llm.UserText(strings.Repeat("a", 4000)), // pre-boundary, must NOT be counted
|
||||
llm.BoundaryMessage(llm.BoundaryMeta{}),
|
||||
llm.UserText("bbbb"), // 4 chars → est 1 → count 1
|
||||
}
|
||||
if got := c.count(msgs, 0); got != 1 {
|
||||
t.Fatalf("count should ignore pre-boundary history: got %d, want 1", got)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user