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:
wangdefa committed 2026-10-20 21:10:41 -07:00
1 parent a819fa3230
commit f782b612ec
213 files changed
+37401 -2

No files matched your search

+99
View File
@@ -0,0 +1,99 @@
package noaadapter
import (
"fmt"
"os"
"path/filepath"
"sync"
"github.com/Autumn-27/norma/noa"
)
// fileArchiver writes archives under <root>/tier<N>/.
type fileArchiver struct {
mu sync.Mutex
root string
}
// NewFileArchiver returns an Archiver rooted at dir.
func NewFileArchiver(root string) noa.Archiver { return &fileArchiver{root: root} }
// Write persists one archive atomically.
//
// Atomicity matters more here than almost anywhere else in the system: a block
// exists only if its archive does, and a half-written archive would be a block
// promising originals it cannot produce. Writing to a temp file and renaming
// means a reader sees either the whole file or none of it.
func (a *fileArchiver) Write(tier noa.Tier, blockID, startRef, endRef string, content []byte) (string, string, error) {
a.mu.Lock()
defer a.mu.Unlock()
rel := filepath.Join(noa.ArchiveTierDir(tier), noa.ArchiveFileName(blockID, startRef, endRef))
abs := filepath.Join(a.root, rel)
if err := os.MkdirAll(filepath.Dir(abs), 0o755); err != nil {
return "", "", fmt.Errorf("create archive dir: %w", err)
}
tmp, err := os.CreateTemp(filepath.Dir(abs), ".noa-*.tmp")
if err != nil {
return "", "", fmt.Errorf("create temp archive: %w", err)
}
tmpName := tmp.Name()
if _, err := tmp.Write(content); err != nil {
tmp.Close()
os.Remove(tmpName)
return "", "", fmt.Errorf("write archive: %w", err)
}
if err := tmp.Close(); err != nil {
os.Remove(tmpName)
return "", "", fmt.Errorf("close archive: %w", err)
}
if err := os.Chmod(tmpName, 0o644); err != nil {
os.Remove(tmpName)
return "", "", fmt.Errorf("chmod archive: %w", err)
}
if err := os.Rename(tmpName, abs); err != nil {
os.Remove(tmpName)
return "", "", fmt.Errorf("install archive: %w", err)
}
return abs, filepath.ToSlash(rel), nil
}
// Remove deletes an archive, used to roll back a failed batch. A missing file
// is not an error: rollback may run over archives that never landed.
func (a *fileArchiver) Remove(abs string) error {
a.mu.Lock()
defer a.mu.Unlock()
if err := os.Remove(abs); err != nil && !os.IsNotExist(err) {
return err
}
return nil
}
// reuseArchiver wraps an Archiver so an existing file is adopted rather than
// rewritten.
//
// State rebuilt from the transcript replays past compressions; their archives
// are historical fact and must not be overwritten by a re-render. Only a
// genuinely missing archive is regenerated.
type reuseArchiver struct {
inner noa.Archiver
root string
}
// NewReuseArchiver returns an Archiver that adopts archives already on disk.
func NewReuseArchiver(root string) noa.Archiver {
return &reuseArchiver{inner: NewFileArchiver(root), root: root}
}
func (a *reuseArchiver) Write(tier noa.Tier, blockID, startRef, endRef string, content []byte) (string, string, error) {
rel := filepath.Join(noa.ArchiveTierDir(tier), noa.ArchiveFileName(blockID, startRef, endRef))
abs := filepath.Join(a.root, rel)
if _, err := os.Stat(abs); err == nil {
return abs, filepath.ToSlash(rel), nil
}
return a.inner.Write(tier, blockID, startRef, endRef, content)
}
// Remove is a no-op: a replay must not delete archives it did not create.
func (a *reuseArchiver) Remove(string) error { return nil }
+428
View File
@@ -0,0 +1,428 @@
package noaadapter
import (
"encoding/json"
"fmt"
"math/rand/v2"
"os"
"strings"
"testing"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/noa"
"github.com/Autumn-27/norma/tool"
)
// The scripted simAgent models a model that either cooperates perfectly or does
// nothing at all. Real models do neither: they hallucinate refs, invert ranges,
// reach into the protected tail, re-compress what they already compressed, and
// occasionally emit something that is not a range at all.
//
// chaosAgent is that model. It is seeded, so a failure reproduces exactly.
//
// The point is not that any single call succeeds — most are meant to be
// rejected. The point is that after any sequence of them the GLOBAL invariants
// still hold, because those are what the rest of the system depends on.
type chaosAgent struct {
*simAgent
rng *rand.Rand
// competence is how many of the twelve behaviour slots are the cooperative
// one. 4 is a model that is wrong most of the time; 9 is a good model having
// an ordinary bad day.
competence int
accepted int
rejected int
kinds map[string]int
}
func newChaosAgent(t *testing.T, sess *Session, seed uint64) *chaosAgent {
return &chaosAgent{
simAgent: newSimAgent(t, sess, 1),
rng: rand.New(rand.NewPCG(seed, seed^0x9e3779b9)),
competence: 4,
kinds: map[string]int{},
}
}
// step runs one turn: work, look at the view, then do something — usually
// something wrong.
func (c *chaosAgent) step() []llm.Message {
c.t.Helper()
c.work(1000 + c.rng.IntN(6000))
view := c.sess.View(c.history)
c.viewTokens = append(c.viewTokens, estimateMessages(view))
nudge := findNudge(view)
if nudge != "" {
c.nudgesSeen++
}
kind, entries := c.invent(nudge)
c.kinds[kind]++
if entries == nil {
return view
}
c.callSeq++
callID := fmt.Sprintf("compress_%d", c.callSeq)
args, _ := json.Marshal(map[string]any{"content": entries})
res, err := runCompress(c.sess, args, &tool.ToolContext{ToolUseID: callID})
if err != nil {
c.t.Fatalf("turn %d (%s): Compress returned a Go error, which the harness cannot turn "+
"into a tool result: %v", c.turn, kind, err)
}
if len(res.Content) == 0 || res.Content[0].Text == "" {
c.t.Fatalf("turn %d (%s): Compress produced an empty result; the provider rejects those", c.turn, kind)
}
panel := res.Content[0].Text
if n := noa.PanelBlockCount(panel); n > 0 {
c.accepted += n
} else {
c.rejected++
}
c.history = append(c.history,
llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{
Type: llm.BlockToolUse, ID: callID, Name: noa.CompressToolName, Input: args,
}}},
llm.Message{Role: llm.RoleUser, Content: []llm.ContentBlock{{
Type: llm.BlockToolResult, ToolUseID: callID,
Content: []llm.ContentBlock{llm.TextBlock(panel)},
}}},
)
return view
}
// invent picks a way to behave. Roughly a third of calls are legitimate, so the
// session makes real progress and the invariants are checked against a state
// that actually has blocks in it.
func (c *chaosAgent) invent(nudge string) (string, []map[string]any) {
// rangeLineRE is anchored at the start of a line, so it has to be applied per
// line — the same way simAgent.act reads the table.
var rows [][]string
for _, line := range strings.Split(nudge, "\n") {
if m := rangeLineRE.FindStringSubmatch(line); m != nil {
rows = append(rows, m)
}
}
blocks := blockLineRE.FindAllStringSubmatch(nudge, -1)
targets := tierTargets(nudge)
roll := c.rng.IntN(12)
if roll < c.competence {
// Cooperate, when there is something to cooperate with.
if len(rows) == 0 {
return "nothing offered", nil
}
var out []map[string]any
for _, m := range rows {
out = append(out, map[string]any{
"startId": m[1], "endId": m[2], "summary": c.summary(m[1] + "–" + m[2]),
})
}
return "cooperative", out
}
switch roll {
case 4:
// Consolidate blocks, whether or not asked to. A tier nudge names its
// targets explicitly; otherwise fall back to the block map.
if len(targets) >= 2 {
return "consolidate", []map[string]any{{
"startId": targets[0], "endId": targets[len(targets)-1],
"summary": c.summary("consolidation"),
}}
}
if len(blocks) < 2 {
return "no blocks to consolidate", nil
}
return "consolidate", []map[string]any{{
"startId": blocks[0][1], "endId": blocks[len(blocks)-1][1],
"summary": c.summary("consolidation"),
}}
case 5:
// Refs that were never handed out.
return "hallucinated refs", []map[string]any{{
"startId": noa.IndexToRef(90000 + c.rng.IntN(9000)),
"endId": noa.IndexToRef(99000 + c.rng.IntN(900)),
"summary": c.summary("invented"),
}}
case 6:
// End before start.
if len(rows) == 0 {
return "nothing to invert", nil
}
m := rows[c.rng.IntN(len(rows))]
return "inverted range", []map[string]any{{
"startId": m[2], "endId": m[1], "summary": c.summary("backwards"),
}}
case 7:
// Reach into the protected tail — the most recent messages.
last := len(c.sess.State().MessageRefs.ByRef)
if last < 4 {
return "history too short", nil
}
return "into the protected tail", []map[string]any{{
"startId": noa.IndexToRef(last - 2), "endId": noa.IndexToRef(last),
"summary": c.summary("recent"),
}}
case 8:
// Two overlapping ranges in one call.
if len(rows) == 0 {
return "nothing to overlap", nil
}
m := rows[0]
return "overlapping ranges", []map[string]any{
{"startId": m[1], "endId": m[2], "summary": c.summary("first")},
{"startId": m[1], "endId": m[2], "summary": c.summary("second")},
}
case 9:
// Re-compress something already consumed.
if len(blocks) == 0 {
return "nothing consumed yet", nil
}
b := blocks[c.rng.IntN(len(blocks))]
return "re-compress consumed", []map[string]any{{
"startId": b[3], "endId": b[4], "summary": c.summary("again"),
}}
case 10:
// A summary that says nothing, and one that says far too much.
if len(rows) == 0 {
return "nothing to summarise", nil
}
m := rows[0]
if c.rng.IntN(2) == 0 {
return "empty summary", []map[string]any{{"startId": m[1], "endId": m[2], "summary": ""}}
}
return "enormous summary", []map[string]any{{
"startId": m[1], "endId": m[2], "summary": strings.Repeat("verbose. ", 6000),
}}
default:
return "ignored the nudge", nil
}
}
// checkInvariants is the whole point of the chaos run. Every one of these is
// something another part of the system assumes without checking.
func checkInvariants(t *testing.T, sess *Session, history []llm.Message, when string) {
t.Helper()
st := sess.State()
// 1. Block ids are never reused, and never exceed the allocator.
seenBlock := map[string]bool{}
for _, b := range st.Blocks {
if seenBlock[b.BlockID] {
t.Fatalf("%s: block id %s was issued twice", when, b.BlockID)
}
seenBlock[b.BlockID] = true
}
// 2. Active blocks partition what they cover: no message may be claimed by
// two live summaries, or the model would see it described twice and the
// token accounting would double-count.
owner := map[string]string{}
for _, b := range noa.ActiveBlocks(st) {
for _, id := range b.EffectiveMessageIDs {
if prev, dup := owner[id]; dup {
t.Fatalf("%s: message %s is covered by both %s and %s", when, id, prev, b.BlockID)
}
owner[id] = b.BlockID
}
}
// 3. Nothing is lost. Every original message must still be accounted for in
// one of the ways the design allows. Anything else has fallen out of the
// conversation entirely, which no amount of archiving can undo.
//
// Identity is a content hash, so a message the valve truncated no longer
// hashes to its original id. It is still present, and its tool_use id is
// what survives the rewrite — so that is what it is matched on.
cores, _ := Project(history)
viewed, _ := Project(sess.View(history))
inView := map[string]bool{}
viewCallIDs := map[string]bool{}
for _, c := range viewed {
inView[c.ID] = true
if c.ToolCallID != "" {
viewCallIDs[c.ToolCallID] = true
}
}
for _, c := range cores {
switch {
case inView[c.ID]:
case owner[c.ID] != "":
case c.ToolCallID != "" && viewCallIDs[c.ToolCallID]:
// Present, but rewritten by emergency-truncate.
case c.ToolName == noa.CompressToolName:
// Compress bookkeeping. Calls whose block is live are stubbed, the last
// KeepLastOrphaned failures are kept so the model can see its mistake,
// and older failures are dropped as noise. All three are by design.
default:
t.Fatalf("%s: message %s (%s, tool %q) is neither in the view nor covered by "+
"any block — it is simply gone", when, c.ID, c.ContentType, c.ToolName)
}
}
// 4. Every active block's archive is on disk and names the block.
for _, b := range noa.ActiveBlocks(st) {
raw, err := os.ReadFile(b.ArchivePath)
if err != nil {
t.Fatalf("%s: block %s archive unreadable: %v", when, b.BlockID, err)
}
if !strings.Contains(string(raw), b.BlockID) {
t.Fatalf("%s: block %s archive does not name the block", when, b.BlockID)
}
}
// 5. The request the provider would receive is well-formed.
assertValidRequest(t, sess.View(history), 0)
}
// The headline chaos test: a model behaving badly in every way the design
// anticipates, over a long session, must leave the invariants intact.
func TestChaosAgentPreservesInvariants(t *testing.T) {
for _, seed := range []uint64{1, 7, 42, 1337, 90210} {
t.Run(fmt.Sprintf("seed%d", seed), func(t *testing.T) {
sess := simSession(t, 40000)
c := newChaosAgent(t, sess, seed)
for i := range 70 {
c.step()
if i%7 == 0 {
checkInvariants(t, sess, c.history, fmt.Sprintf("turn %d", c.turn))
}
}
checkInvariants(t, sess, c.history, "end")
if c.accepted == 0 {
t.Fatalf("70 chaotic turns produced no accepted compression at all; "+
"the agent is not exercising the success path (kinds: %v)", c.kinds)
}
if c.rejected == 0 {
t.Fatalf("no call was rejected; the agent is not exercising the failure path (kinds: %v)", c.kinds)
}
t.Logf("accepted=%d rejected=%d nudges=%d kinds=%v", c.accepted, c.rejected, c.nudgesSeen, c.kinds)
})
}
}
// A malformed call must never take the session down with it. Whatever the model
// sends, the tool answers with a tool result — never a Go error, which the
// harness would surface as a failed turn rather than something the model can
// correct.
func TestChaosAgentNeverProducesAGoError(t *testing.T) {
sess := simSession(t, 40000)
c := newChaosAgent(t, sess, 99)
for range 40 {
c.step() // step() fails the test if runCompress ever returns an error
}
if c.accepted+c.rejected == 0 {
t.Fatalf("40 turns produced no Compress call at all; the fixture is degenerate (kinds: %v)", c.kinds)
}
}
// A good model having an ordinary bad day — mostly right, occasionally wrong —
// is the realistic case, and it must still be held inside the window.
func TestMostlyCompetentModelStaysBounded(t *testing.T) {
window := 40000
for _, seed := range []uint64{3, 11, 2024} {
t.Run(fmt.Sprintf("seed%d", seed), func(t *testing.T) {
sess := simSession(t, window)
c := newChaosAgent(t, sess, seed)
c.competence = 9
for range 90 {
c.step()
}
tail := c.viewTokens[len(c.viewTokens)-15:]
peak := 0
for _, n := range tail {
peak = max(peak, n)
}
if peak > window {
t.Fatalf("the last fifteen turns peaked at %d over a %d window "+
"(accepted=%d rejected=%d nudges=%d); occasional mistakes must not break "+
"compression.\nThe mechanism: a couple of ignored or failed nudges trip the "+
"attempt ladder, and suppression then lifts only after NudgeGrowthFloor "+
"(%d tokens) of further growth — more than half this window. Nudging goes "+
"quiet at ~90%% usage and does not resume before overflow. See "+
"noa.TestSuppressionReleaseFitsInsideTheWindow.",
peak, window, c.accepted, c.rejected, c.nudgesSeen,
noa.NudgeGrowthFloor(sess.Config()))
}
t.Logf("tail peak %d of %d (accepted=%d rejected=%d nudges=%d)",
peak, window, c.accepted, c.rejected, c.nudgesSeen)
})
}
}
// A model that tries on every nudge and gets it wrong every time is silenced as
// fast as one that never tries at all — the ladder counts a failed attempt and
// an ignored nudge the same way.
//
// That is deliberate (both reclaim nothing, and both loop just as expensively),
// but the consequence is worth pinning: an EAGER model gets no more chances than
// a silent one, so a model whose only problem is picking bad refs never gets the
// repeated guidance that would let it correct course, and the context runs past
// the window exactly as if it had never tried.
//
// If this test starts failing because the eager model gets materially more
// nudges, the ladder's policy has changed and the reasoning above needs revising
// rather than the numbers.
func TestFailedAttemptsAreSilencedLikeIgnoredOnes(t *testing.T) {
window := 40000
run := func(eager bool) (nudges, final int) {
sess := simSession(t, window)
a := newSimAgent(t, sess, 1000000)
for i := range 60 {
a.work(4000)
view := sess.View(a.history)
a.viewTokens = append(a.viewTokens, estimateMessages(view))
if findNudge(view) == "" {
continue
}
nudges++
if !eager {
continue
}
// Always willing, always wrong: refs that were never handed out.
id := fmt.Sprintf("c_%d", i)
args, _ := json.Marshal(map[string]any{"content": []map[string]any{{
"startId": noa.IndexToRef(90001), "endId": noa.IndexToRef(90009),
"summary": a.summary("unresolvable"),
}}})
res, err := runCompress(sess, args, &tool.ToolContext{ToolUseID: id})
if err != nil {
t.Fatalf("runCompress: %v", err)
}
a.history = append(a.history,
llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{
Type: llm.BlockToolUse, ID: id, Name: noa.CompressToolName, Input: args}}},
llm.Message{Role: llm.RoleUser, Content: []llm.ContentBlock{{
Type: llm.BlockToolResult, ToolUseID: id,
Content: []llm.ContentBlock{llm.TextBlock(res.Content[0].Text)}}}})
}
return nudges, a.viewTokens[len(a.viewTokens)-1]
}
eagerNudges, eagerFinal := run(true)
silentNudges, silentFinal := run(false)
if eagerNudges > silentNudges*2 {
t.Fatalf("the eager model got %d nudges against the silent model's %d; the ladder "+
"now distinguishes them and this test's premise is stale", eagerNudges, silentNudges)
}
if eagerFinal <= window {
t.Fatalf("the eager-but-wrong model ended at %d, inside the %d window; "+
"something now rescues it and the documented limitation no longer holds",
eagerFinal, window)
}
t.Logf("eager-but-wrong: %d nudges, ended at %d tokens; never tried: %d nudges, ended at %d "+
"(window %d) — trying and failing buys nothing over staying silent",
eagerNudges, eagerFinal, silentNudges, silentFinal, window)
}
+91
View File
@@ -0,0 +1,91 @@
package noaadapter
import (
"context"
"github.com/Autumn-27/norma/compaction"
"github.com/Autumn-27/norma/llm"
)
// Compactor adapts a Session to the harness's context-manager interfaces.
//
// It satisfies harness.Compactor and harness.ContextView. Implementing the
// latter is what takes over request construction from llm.MessagesForAPI.
type Compactor struct {
sess *Session
// overflow tracks what a prompt-too-long error taught us.
overflow overflowState
}
// Pre is a no-op on the history.
//
// The built-in compaction rewrites messages here; noa must not. Message
// identity is a content hash over the stored text, and a rewrite would change
// every id derived from it, invalidating every ref the model holds.
func (c *Compactor) Pre(_ context.Context, msgs []llm.Message, lastInputTokens int) []llm.Message {
if lastInputTokens > 0 {
c.sess.noteProviderTokens(lastInputTokens)
}
return msgs
}
// View builds the request's message array.
func (c *Compactor) View(_ context.Context, msgs []llm.Message) []llm.Message {
return c.sess.View(msgs)
}
// IsOverflow reports whether err is a context-overflow rejection. The built-in
// compaction already recognises every provider's phrasing, so the detection is
// borrowed rather than duplicated.
func (c *Compactor) IsOverflow(err error) bool {
return compaction.New(compaction.Config{}, nil).IsOverflow(err)
}
// Reactive recovers from a prompt-too-long error.
//
// noa cannot ask the model to compress here — the model is not in the loop at
// this point. What it can do is arm the mechanical valve and VERIFY the result:
// returning true without actually shrinking the view would produce a
// 413 → retry → 413 loop, which is worse than a clean failure. So the view is
// rebuilt and measured, and false is returned if it did not shrink.
func (c *Compactor) Reactive(ctx context.Context, msgs []llm.Message) ([]llm.Message, bool) {
// Compare against the array the provider actually rejected, not the raw
// projection. The projection is always larger than the sent view, so
// measuring against it would show progress on every attempt and never admit
// that arming changed nothing.
before := c.sess.sentTokens()
c.overflow.arm(c.sess.Config().ModelContextLimit)
floor := c.overflow.armedFloor()
c.sess.setEmergencyFloor(floor)
after := estimateMessages(c.View(ctx, msgs))
shrank := before == 0 || after < before
fits := floor == 0 || after <= floor
if !shrank || !fits {
// Nothing more to give. Returning true here would promise a smaller
// request that is not smaller, and the loop would retry into the same
// rejection indefinitely; a clean prompt-too-long is the better outcome.
c.sess.setEmergencyFloor(0)
c.overflow.disarm()
return msgs, false
}
return msgs, true
}
// estimateMessages sizes a rebuilt request.
func estimateMessages(msgs []llm.Message) int {
total := 0
for _, m := range msgs {
for _, b := range m.Content {
total += len(b.Text) / 4
total += len(b.Thinking) / 4
total += len(b.Input) / 4
for _, inner := range b.Content {
total += len(inner.Text) / 4
}
}
}
return total
}
+81
View File
@@ -0,0 +1,81 @@
package noaadapter
import (
"fmt"
"sort"
"strings"
"github.com/Autumn-27/norma/noa"
)
// DeadRangeTracker breaks the loop where a model keeps asking to compress refs
// that cannot resolve.
//
// A small model handed a stale ref will often resubmit the identical batch: the
// rejection tells it the range is dead, but not that repeating it is futile.
// Each retry costs a full turn, and the failure ladder alone is slow to bite
// because a parse-clean call that reclaims nothing still looks like progress.
//
// So the second sighting of the same range set is refused outright, with the
// live ranges named — a rejection the model can act on instead of repeat.
type DeadRangeTracker struct {
// seen counts how many times each range-set signature has failed.
seen map[string]int
}
// NewDeadRangeTracker returns an empty tracker.
func NewDeadRangeTracker() *DeadRangeTracker {
return &DeadRangeTracker{seen: map[string]int{}}
}
// signature identifies a batch by its ranges, order-independent: the model may
// reshuffle a retry without changing what it is asking for.
func signature(ranges []noa.CompressRange) string {
parts := make([]string, 0, len(ranges))
for _, r := range ranges {
parts = append(parts, strings.ToLower(strings.TrimSpace(r.StartRef))+".."+
strings.ToLower(strings.TrimSpace(r.EndRef)))
}
sort.Strings(parts)
return strings.Join(parts, ",")
}
// Check reports whether this batch has already failed often enough to refuse.
// The returned string is the refusal to show the model; "" means proceed.
func (d *DeadRangeTracker) Check(ranges []noa.CompressRange, state noa.CompressionState) string {
if len(ranges) == 0 {
return ""
}
if d.seen[signature(ranges)] < noa.DeadRepeatReject {
return ""
}
var b strings.Builder
fmt.Fprintf(&b, "This exact range set has already failed %d times and will fail again — "+
"the refs do not resolve against the current context. Do not resubmit it.",
noa.DeadRepeatReject)
// Naming what IS live turns a dead end into a next step.
if spans := noa.ActiveBlockSpans(state); len(spans) > 0 {
var live []string
for _, s := range spans {
live = append(live, fmt.Sprintf("%s(T%d)=%s–%s", s.BlockID, s.Tier, s.StartRef, s.EndRef))
}
fmt.Fprintf(&b, "\nLive blocks you can target instead: %s.", strings.Join(live, ", "))
}
b.WriteString("\nOtherwise use the refs shown in the <noa-ref> tags of the current context.")
return b.String()
}
// Record notes that a batch failed.
func (d *DeadRangeTracker) Record(ranges []noa.CompressRange) {
if len(ranges) == 0 {
return
}
d.seen[signature(ranges)]++
}
// Reset clears the tracker after a successful compression: the view changed, so
// what was dead before may not be now.
func (d *DeadRangeTracker) Reset() {
d.seen = map[string]int{}
}
+342
View File
@@ -0,0 +1,342 @@
package noaadapter
import (
"encoding/json"
"path/filepath"
"strings"
"testing"
"github.com/Autumn-27/norma/noa"
"github.com/Autumn-27/norma/tool"
)
func deadRanges(refs ...[2]string) []noa.CompressRange {
out := make([]noa.CompressRange, 0, len(refs))
for _, r := range refs {
out = append(out, noa.CompressRange{StartRef: r[0], EndRef: r[1], Summary: longSummary})
}
return out
}
// The refusal only fires on the SECOND sighting: the first failure carries a
// corrective message the model deserves a chance to act on.
func TestDeadRangeRefusesOnRepeat(t *testing.T) {
d := NewDeadRangeTracker()
st := noa.CreateInitialState("s", "/a")
rs := deadRanges([2]string{"m09000", "m09001"})
if msg := d.Check(rs, st); msg != "" {
t.Fatalf("refused on first sight: %q", msg)
}
d.Record(rs)
if msg := d.Check(rs, st); msg != "" {
t.Fatalf("refused after one failure: %q", msg)
}
d.Record(rs)
msg := d.Check(rs, st)
if msg == "" {
t.Fatalf("not refused after %d failures", noa.DeadRepeatReject)
}
if !strings.Contains(msg, "Do not resubmit") {
t.Fatalf("refusal = %q, want an explicit instruction to stop", msg)
}
}
// A dead end the model cannot act on is just another wasted turn; naming the
// live blocks turns it into a next step.
func TestDeadRangeNamesLiveBlocks(t *testing.T) {
d := NewDeadRangeTracker()
st := noa.CreateInitialState("s", "/a")
st.Blocks = []noa.CompressionBlock{
{BlockID: "b3", Tier: 2, StartRef: "m00012", EndRef: "m00160", Active: true},
}
rs := deadRanges([2]string{"m09000", "m09001"})
d.Record(rs)
d.Record(rs)
msg := d.Check(rs, st)
if !strings.Contains(msg, "b3(T2)=m00012–m00160") {
t.Fatalf("refusal = %q, want it to name the live block", msg)
}
}
// A retry that reshuffles the ranges is still the same request.
func TestDeadRangeSignatureIsOrderIndependent(t *testing.T) {
d := NewDeadRangeTracker()
st := noa.CreateInitialState("s", "/a")
a := deadRanges([2]string{"m1", "m2"}, [2]string{"m3", "m4"})
b := deadRanges([2]string{"m3", "m4"}, [2]string{"m1", "m2"})
d.Record(a)
d.Record(b)
if d.Check(a, st) == "" {
t.Fatal("a reordered resubmission was treated as a different request")
}
}
// A successful compression changes the view, so what was dead may not be.
func TestDeadRangeResetAfterSuccess(t *testing.T) {
d := NewDeadRangeTracker()
st := noa.CreateInitialState("s", "/a")
rs := deadRanges([2]string{"m1", "m2"})
d.Record(rs)
d.Record(rs)
if d.Check(rs, st) == "" {
t.Fatal("expected a refusal before the reset")
}
d.Reset()
if msg := d.Check(rs, st); msg != "" {
t.Fatalf("still refusing after a successful compression: %q", msg)
}
}
// End to end: the third identical call is refused without reaching the engine.
func TestDeadRangeBreaksLoopEndToEnd(t *testing.T) {
sess, msgs := pressureSession(t)
sess.View(msgs)
args, _ := json.Marshal(map[string]any{
"content": []map[string]any{{"startId": "m09000", "endId": "m09001", "summary": longSummary}},
})
var last string
for range 3 {
res, _ := runCompress(sess, args, &tool.ToolContext{ToolUseID: "x"})
last = res.Content[0].Text
}
if !strings.Contains(last, "Do not resubmit") {
t.Fatalf("the third identical call was not refused:\n%s", last)
}
}
// The provider's figure was measured before the compression, so it describes a
// context that no longer exists. Trusting it would pin the pressure ladder at
// the pre-compression size and re-raise an emergency the model just resolved.
func TestFloorStaleIgnoresPreCompressionAnchor(t *testing.T) {
sess, msgs := pressureSession(t)
sess.View(msgs)
sess.mu.Lock()
sess.providerTokens = 999999
sess.providerTokensAt = 0
sess.lastCompressAt = 1 // a compression happened after that figure was taken
cores, _ := Project(msgs)
got := sess.resolveTokenCount(cores)
est := estimateCoreTokens(cores)
sess.mu.Unlock()
if got != est {
t.Fatalf("token count = %d, want the local estimate %d — the provider anchor predates the compression", got, est)
}
}
func TestProviderTokensUsedWhenCurrent(t *testing.T) {
sess, msgs := pressureSession(t)
sess.View(msgs)
sess.mu.Lock()
cores, _ := Project(msgs)
est := estimateCoreTokens(cores)
sess.providerTokens = est + 100 // authoritative and current, so it is adopted
sess.providerTokensAt = 0
sess.lastCompressAt = 0
got := sess.resolveTokenCount(cores)
sess.mu.Unlock()
if got != est+100 {
t.Fatalf("token count = %d, want the provider figure %d", got, est+100)
}
}
// A provider figure well above the estimate is NOT discarded as drift: it is
// authoritative (it describes the array the provider actually received) and it
// carries overhead the projection omits — the system prompt and tool
// definitions. So it is applied as a raise-only floor. Discarding it was the
// accomplice to the raw-history mis-count: once the estimate itself read high
// the honest provider number was rejected as "drift" on every turn, and nothing
// could pull the ladder back down (session-847926).
//
// The one exception, that a provider figure predating a compression is ignored,
// is the floor-stale guard, pinned separately by
// TestProviderAnchorPredatingCompression.
func TestProviderTokensRaiseTheFloor(t *testing.T) {
sess, msgs := pressureSession(t)
sess.View(msgs)
sess.mu.Lock()
cores, _ := Project(msgs)
base := estimateProjectedTokens(cores, sess.state, sess.cfg)
sess.providerTokens = base * 10
sess.providerTokensAt = 0
sess.lastCompressAt = 0
got := sess.resolveTokenCount(cores)
sess.mu.Unlock()
if got != base*10 {
t.Fatalf("token count = %d, want the provider figure %d — it is authoritative and "+
"must raise the count, not be thrown away as drift", got, base*10)
}
}
func TestDeriveChildStateKeepsLedgerResetsPacing(t *testing.T) {
parent := sampleState()
child := DeriveChildState(parent, "child", "/archive/child")
if len(child.Blocks) != len(parent.Blocks) {
t.Fatalf("child has %d blocks, want the parent's %d", len(child.Blocks), len(parent.Blocks))
}
if child.NextBlockID != parent.NextBlockID {
t.Fatalf("NextBlockID = %d, want it inherited — otherwise the child allocates ids that collide",
child.NextBlockID)
}
if len(child.MessageRefs.ByRaw) != len(parent.MessageRefs.ByRaw) {
t.Fatal("the ref map was not inherited; the child could not address inherited context")
}
if child.Nudge.LastNudgeShownTokens != 0 || len(child.Nudge.LastShownByTier) != 0 {
t.Fatalf("nudge pacing = %+v, want it reset for the child's own conversation", child.Nudge)
}
if child.Stats != (noa.Stats{}) {
t.Fatalf("stats = %+v, want them reset so the child reports its own work", child.Stats)
}
// The inherited archive must stay findable from the child.
if child.Blocks[0].ArchivePath != parent.Blocks[0].ArchivePath {
t.Fatalf("archive path = %q, want the parent's absolute path kept", child.Blocks[0].ArchivePath)
}
if child.ArchiveRoot != "/archive/child" {
t.Fatalf("ArchiveRoot = %q, want the child's own directory for NEW archives", child.ArchiveRoot)
}
}
// Deep-copied, so a child mutating its ledger cannot corrupt the parent's.
func TestDeriveChildStateIsDeepCopy(t *testing.T) {
parent := sampleState()
child := DeriveChildState(parent, "child", "/archive/child")
child.Blocks[0].Active = false
child.Blocks[0].EffectiveMessageIDs[0] = "mutated"
child.MessageRefs.ByRaw["h_abc"] = "m99999"
if !parent.Blocks[0].Active {
t.Error("the parent's block was deactivated by the child")
}
if parent.Blocks[0].EffectiveMessageIDs[0] == "mutated" {
t.Error("the coverage slice is shared with the child")
}
if parent.MessageRefs.ByRaw["h_abc"] != "m00001" {
t.Error("the ref map is shared with the child")
}
}
func TestInheritStateWalksParentChain(t *testing.T) {
base := t.TempDir()
// The grandparent has the ledger; the parent is empty.
gpRoot := filepath.Join(base, "grandparent")
if err := NewStateStore(gpRoot).Save(sampleState()); err != nil {
t.Fatalf("seed grandparent: %v", err)
}
pRoot := filepath.Join(base, "parent")
if err := NewStateStore(pRoot).Save(noa.CreateInitialState("parent", pRoot)); err != nil {
t.Fatalf("seed parent: %v", err)
}
got, from, ok := InheritState(InheritOptions{
ArchiveBaseDir: base, SessionID: "child",
ParentIDs: []string{"parent", "grandparent"},
})
if !ok {
t.Fatal("nothing inherited despite a grandparent with blocks")
}
if from != "grandparent" {
t.Fatalf("inherited from %q, want the nearest ancestor that has blocks", from)
}
if len(got.Blocks) != 1 {
t.Fatalf("inherited %d blocks, want 1", len(got.Blocks))
}
if got.SessionID != "child" {
t.Fatalf("SessionID = %q, want the child's own", got.SessionID)
}
}
func TestInheritStateStopsAtDepthLimit(t *testing.T) {
base := t.TempDir()
// Only the tenth ancestor has anything, past the walk limit.
deep := filepath.Join(base, "a9")
if err := NewStateStore(deep).Save(sampleState()); err != nil {
t.Fatalf("seed: %v", err)
}
var parents []string
for i := range 9 {
parents = append(parents, "a"+string(rune('0'+i)))
}
parents = append(parents, "a9")
_, _, ok := InheritState(InheritOptions{
ArchiveBaseDir: base, SessionID: "child", ParentIDs: parents,
})
if ok {
t.Fatalf("the walk exceeded the %d-ancestor limit", maxInheritDepth)
}
}
func TestInheritStateNoParents(t *testing.T) {
got, from, ok := InheritState(InheritOptions{ArchiveBaseDir: t.TempDir(), SessionID: "solo"})
if ok || from != "" {
t.Fatalf("inherited %q from nowhere", from)
}
if len(got.Blocks) != 0 || got.SessionID != "solo" {
t.Fatalf("fresh state = %+v", got)
}
}
// A session that would otherwise start from zero picks up the ancestor's ledger
// rather than re-compressing everything it already did.
func TestSessionInheritsFromParent(t *testing.T) {
base := t.TempDir()
parentRoot := filepath.Join(base, "parent")
if err := NewStateStore(parentRoot).Save(sampleState()); err != nil {
t.Fatalf("seed parent: %v", err)
}
var warns []string
sess, err := newSession(Options{
ArchiveBaseDir: base, SessionID: "child", ParentSessionIDs: []string{"parent"},
OnWarn: func(m string) { warns = append(warns, m) },
})
if err != nil {
t.Fatalf("newSession: %v", err)
}
if len(sess.State().Blocks) != 1 {
t.Fatalf("child has %d blocks, want the parent's 1", len(sess.State().Blocks))
}
if !strings.Contains(strings.Join(warns, "\n"), "inherited") {
t.Fatalf("the host was not told about the inheritance: %v", warns)
}
}
// A session with its own ledger must not have it replaced.
func TestSessionDoesNotInheritOverOwnState(t *testing.T) {
base := t.TempDir()
if err := NewStateStore(filepath.Join(base, "parent")).Save(sampleState()); err != nil {
t.Fatalf("seed parent: %v", err)
}
own := sampleState()
own.SessionID = "child"
own.Blocks = append(own.Blocks, noa.CompressionBlock{BlockID: "b9", Tier: 1, Active: true})
if err := NewStateStore(filepath.Join(base, "child")).Save(own); err != nil {
t.Fatalf("seed child: %v", err)
}
sess, err := newSession(Options{
ArchiveBaseDir: base, SessionID: "child", ParentSessionIDs: []string{"parent"},
})
if err != nil {
t.Fatalf("newSession: %v", err)
}
if len(sess.State().Blocks) != 2 {
t.Fatalf("child has %d blocks, want its own 2 kept", len(sess.State().Blocks))
}
}
func TestSubagentArchiveRoot(t *testing.T) {
got := SubagentArchiveRoot("/base", "sess", "agent7")
want := filepath.Join("/base", "sess", "subagents", "agent7")
if got != want {
t.Fatalf("SubagentArchiveRoot = %q, want %q", got, want)
}
}
+376
View File
@@ -0,0 +1,376 @@
package noaadapter
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/noa"
"github.com/Autumn-27/norma/tool"
)
func edgeSession(t *testing.T) *Session {
t.Helper()
opts := baseOptions()
sess, err := EnableWithSession(&opts, Options{ArchiveBaseDir: t.TempDir(), SessionID: "edge"})
if err != nil {
t.Fatalf("EnableWithSession: %v", err)
}
return sess
}
// --- Degenerate histories ------------------------------------------------
func TestViewOfEmptyHistory(t *testing.T) {
sess := edgeSession(t)
if got := sess.View(nil); len(got) != 0 {
t.Fatalf("view of an empty history = %v", got)
}
}
func TestViewOfSingleMessage(t *testing.T) {
sess := edgeSession(t)
got := sess.View([]llm.Message{userText("hello")})
if len(got) != 1 {
t.Fatalf("got %d messages, want 1", len(got))
}
if !strings.HasPrefix(got[0].Text(), "hello") {
t.Fatalf("text = %q", got[0].Text())
}
}
// A history that is only tool traffic (no user text at all) must still project.
func TestViewOfToolOnlyHistory(t *testing.T) {
sess := edgeSession(t)
msgs := []llm.Message{
assistantWith(toolUse("t1", "Read", `{}`)),
toolResult("t1", "output"),
}
got := sess.View(msgs)
if len(got) != 2 {
t.Fatalf("got %d messages, want the exchange preserved", len(got))
}
}
// An assistant message carrying only thinking must survive: dropping it would
// orphan the tool call that follows.
func TestViewKeepsThinkingOnlyMessage(t *testing.T) {
sess := edgeSession(t)
msgs := []llm.Message{
userText("q"),
assistantWith(llm.ContentBlock{Type: llm.BlockThinking, Thinking: "pondering", Signature: "sig"}),
assistantWith(toolUse("t1", "Read", `{}`)),
toolResult("t1", "out"),
}
got := sess.View(msgs)
found := false
for _, m := range got {
for _, b := range m.Content {
if b.Type == llm.BlockThinking {
found = true
if b.Signature != "sig" {
t.Fatalf("signature = %q, want it preserved", b.Signature)
}
}
}
}
if !found {
t.Fatal("the thinking-only message was dropped")
}
}
// --- Compress against odd views ------------------------------------------
func TestCompressBeforeAnyView(t *testing.T) {
sess := edgeSession(t)
args, _ := json.Marshal(map[string]any{
"content": []map[string]any{{"startId": "m00001", "endId": "m00002", "summary": longSummary}},
})
res, err := runCompress(sess, args, &tool.ToolContext{ToolUseID: "x"})
if err != nil {
t.Fatalf("runCompress before any View: %v", err)
}
// No view means no refs; it must report that rather than crash.
if noa.PanelBlockCount(res.Content[0].Text) != 0 {
t.Fatalf("a block was created with no view:\n%s", res.Content[0].Text)
}
}
func TestCompressWithNilToolContext(t *testing.T) {
sess, msgs := pressureSession(t)
sess.View(msgs)
args, _ := json.Marshal(map[string]any{
"content": []map[string]any{{"startId": "m00001", "endId": "m00008", "summary": longSummary}},
})
if _, err := runCompress(sess, args, nil); err != nil {
t.Fatalf("a nil ToolContext must not break the call: %v", err)
}
}
// --- Concurrency ---------------------------------------------------------
// View and Compress share one Session. Background tasks and subagents can reach
// it at the same time, so the shared state must be safe under -race.
func TestSessionConcurrentViewAndCompress(t *testing.T) {
sess, msgs := pressureSession(t)
sess.View(msgs)
args, _ := json.Marshal(map[string]any{
"content": []map[string]any{{"startId": "m00001", "endId": "m00008", "summary": longSummary}},
})
var wg sync.WaitGroup
for i := range 8 {
wg.Add(1)
go func(n int) {
defer wg.Done()
if n%2 == 0 {
sess.View(msgs)
} else {
_, _ = runCompress(sess, args, &tool.ToolContext{ToolUseID: "c"})
}
}(i)
}
wg.Wait()
// Whatever interleaving happened, the ledger must be coherent.
st := sess.State()
seen := map[string]bool{}
for _, b := range st.Blocks {
if seen[b.BlockID] {
t.Fatalf("block id %s was allocated twice", b.BlockID)
}
seen[b.BlockID] = true
}
for raw, ref := range st.MessageRefs.ByRaw {
if ref == noa.BlockedRef {
continue
}
if st.MessageRefs.ByRef[ref] != raw {
t.Fatalf("ref map is inconsistent: ByRaw[%q]=%q but ByRef[%q]=%q",
raw, ref, ref, st.MessageRefs.ByRef[ref])
}
}
}
func TestStateStoreConcurrentSaves(t *testing.T) {
s := NewStateStore(t.TempDir())
var wg sync.WaitGroup
for i := range 16 {
wg.Add(1)
go func(n int) {
defer wg.Done()
st := sampleState()
st.NextBlockID = n + 1
_ = s.Save(st)
}(i)
}
wg.Wait()
if _, err := s.Load("sess", "/a"); err != nil {
t.Fatalf("state is unreadable after concurrent saves: %v", err)
}
}
func TestArchiverConcurrentWrites(t *testing.T) {
a := NewFileArchiver(t.TempDir())
var wg sync.WaitGroup
errs := make([]error, 16)
for i := range 16 {
wg.Add(1)
go func(n int) {
defer wg.Done()
id := "b" + string(rune('a'+n))
_, _, errs[n] = a.Write(1, id, "m00001", "m00009", []byte("body "+id))
}(i)
}
wg.Wait()
for i, err := range errs {
if err != nil {
t.Fatalf("concurrent write %d failed: %v", i, err)
}
}
}
// --- Filesystem failures -------------------------------------------------
// A compression whose archive cannot be written must not create a block: the
// block would claim originals that are not there.
func TestCompressFailsWhenArchiveDirIsUnwritable(t *testing.T) {
base := t.TempDir()
opts := baseOptions()
sess, err := EnableWithSession(&opts, Options{ArchiveBaseDir: base, SessionID: "ro"})
if err != nil {
t.Fatalf("EnableWithSession: %v", err)
}
body := strings.Repeat("compressible content. ", 300)
tail := strings.Repeat("recent tail content. ", 250)
msgs := []llm.Message{userText("the task")}
for range 4 {
msgs = append(msgs, llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{llm.TextBlock(body)}})
}
for range 6 {
msgs = append(msgs, userText(tail))
}
sess.View(msgs)
// Make the session directory read-only so the archive write fails.
dir := filepath.Join(base, "ro")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.Chmod(dir, 0o500); err != nil {
t.Skipf("cannot make the directory read-only here: %v", err)
}
t.Cleanup(func() { _ = os.Chmod(dir, 0o755) })
if os.Geteuid() == 0 {
t.Skip("running as root; a read-only directory is not enforced")
}
args, _ := json.Marshal(map[string]any{
"content": []map[string]any{{"startId": "m00002", "endId": "m00005", "summary": longSummary}},
})
res, _ := runCompress(sess, args, &tool.ToolContext{ToolUseID: "x"})
panel := res.Content[0].Text
if noa.PanelBlockCount(panel) != 0 {
t.Fatalf("a block was created despite an unwritable archive:\n%s", panel)
}
if len(sess.State().Blocks) != 0 {
t.Fatal("state gained a block whose archive could not be written")
}
if !strings.Contains(panel, "archive") {
t.Fatalf("the panel does not explain the archive failure:\n%s", panel)
}
}
// --- Identity edge cases -------------------------------------------------
// Two messages that differ only by role must not collide: the role is part of
// what a message IS.
func TestIdentityDistinguishesRole(t *testing.T) {
a := DeriveMessageID(noa.RoleUser, noa.CTText, "same text", "", "")
b := DeriveMessageID(noa.RoleAssistant, noa.CTText, "same text", "", "")
if a == b {
t.Fatal("a user and an assistant message with identical text share an id")
}
}
func TestIdentityDistinguishesToolCallID(t *testing.T) {
a := DeriveMessageID(noa.RoleTool, noa.CTToolResult, "out", "call_1", "Read")
b := DeriveMessageID(noa.RoleTool, noa.CTToolResult, "out", "call_2", "Read")
if a == b {
t.Fatal("two results of different calls share an id")
}
}
// Many repetitions of the same content must each keep a distinct identity.
func TestClusterCounterHandlesManyDuplicates(t *testing.T) {
cc := NewClusterCounter()
seen := map[string]bool{}
for range 1000 {
id := cc.Next("base")
if seen[id] {
t.Fatalf("duplicate id %q", id)
}
seen[id] = true
}
}
// A history of identical messages is the worst case for content hashing.
func TestViewWithManyIdenticalMessages(t *testing.T) {
sess := edgeSession(t)
var msgs []llm.Message
for range 50 {
msgs = append(msgs, userText("git status"))
}
sess.View(msgs)
st := sess.State()
if len(st.MessageRefs.ByRaw) != 50 {
t.Fatalf("assigned %d refs for 50 identical messages, want 50 distinct identities",
len(st.MessageRefs.ByRaw))
}
// And the assignment must be stable across turns.
before := make(map[string]string, len(st.MessageRefs.ByRaw))
for k, v := range st.MessageRefs.ByRaw {
before[k] = v
}
sess.View(msgs)
for k, v := range sess.State().MessageRefs.ByRaw {
if before[k] != "" && before[k] != v {
t.Fatalf("message %q changed ref from %q to %q", k, before[k], v)
}
}
}
// --- Tag edge cases ------------------------------------------------------
// A message whose own text happens to look like a tag must not be corrupted.
func TestTagStrippingIgnoresTagLikeContent(t *testing.T) {
cases := []string{
`the config says <noa-ref id="user-service"/> which is unrelated`,
"<noa-archive block=\"b1\" tier=\"1\" range=\"m1-m2\" path=\"/p.md\"/>",
"prose about <noa-ref> tags in general",
`<noa-ref id="m00001"/> in the MIDDLE of a sentence`,
}
for _, in := range cases {
if got := StripRefTag(in); got != in {
t.Errorf("StripRefTag altered content it should not touch:\n in: %q\n out: %q", in, got)
}
}
}
// Re-tagging an already-tagged body must not stack tags.
func TestTagInjectionIsIdempotentAcrossTurns(t *testing.T) {
sess := edgeSession(t)
msgs := []llm.Message{userText("hello")}
for range 5 {
view := sess.View(msgs)
if n := strings.Count(view[0].Text(), "<noa-ref"); n != 1 {
t.Fatalf("message carries %d tags, want exactly 1: %q", n, view[0].Text())
}
}
}
// --- State file compatibility -------------------------------------------
// A state file from a newer version must be refused rather than half-read.
func TestStateStoreForwardIncompatibility(t *testing.T) {
root := t.TempDir()
if err := os.WriteFile(filepath.Join(root, "state.json"),
[]byte(`{"version":2,"blocks":[{"blockId":"b1","tier":1,"active":true}]}`), 0o644); err != nil {
t.Fatal(err)
}
got, err := NewStateStore(root).Load("s", "/a")
if err == nil {
t.Fatal("a newer state file was accepted; fields it does not know about would be silently dropped")
}
if len(got.Blocks) != 0 {
t.Fatal("blocks were read out of an incompatible file")
}
}
// A block whose archive was deleted still renders; the model gets a path that
// does not resolve, which is better than losing the summary too.
func TestMissingArchiveDoesNotBreakTheView(t *testing.T) {
o, msgs, sess := compressedSession(t)
blocks := sess.State().Blocks
if err := os.Remove(blocks[0].ArchivePath); err != nil {
t.Fatalf("remove archive: %v", err)
}
view := sess.View(msgs)
found := false
for _, m := range view {
if strings.HasPrefix(m.Text(), noa.SummaryHeader) {
found = true
}
}
if !found {
t.Fatal("the summary vanished when its archive did; the compression would be lost twice over")
}
// And a rebuild can regenerate the archive from the transcript.
_ = o
}
+247
View File
@@ -0,0 +1,247 @@
package noaadapter
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Autumn-27/norma/agentcore"
"github.com/Autumn-27/norma/compaction"
"github.com/Autumn-27/norma/harness"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/noa"
"github.com/Autumn-27/norma/tool"
)
func baseOptions() agentcore.Options {
return agentcore.Options{
SystemPrompt: []string{"you are an assistant"},
Tools: []tool.CoreTool{},
Compaction: &compaction.Config{ContextWindow: 200000},
}
}
// Enable attaches all three pieces at once. Wiring them separately would make
// three ways to get it half-right, each of which fails quietly.
func TestEnableAttachesAllThreePieces(t *testing.T) {
opts := baseOptions()
if err := Enable(&opts, Options{ArchiveBaseDir: t.TempDir(), SessionID: "s1"}); err != nil {
t.Fatalf("Enable: %v", err)
}
if opts.Compactor == nil {
t.Fatal("Compactor not attached")
}
if _, ok := opts.Compactor.(harness.ContextView); !ok {
t.Fatal("the compactor must implement harness.ContextView, or it never takes over the projection")
}
found := false
for _, tl := range opts.Tools {
if tl.Name() == noa.CompressToolName {
found = true
}
}
if !found {
t.Fatalf("the Compress tool was not registered; tools = %v", toolNames(opts.Tools))
}
joined := strings.Join(opts.AppendSystemPrompt, "\n")
if !strings.Contains(joined, noa.SystemPromptHeader) {
t.Fatal("the resident prompt was not appended")
}
if opts.DynamicBoundary < len(opts.SystemPrompt)+1 {
t.Fatalf("DynamicBoundary = %d, want it to cover the noa section — otherwise the prompt is re-billed every request",
opts.DynamicBoundary)
}
}
// Not calling Enable is the off switch: Options must be untouched.
func TestNotEnablingLeavesOptionsUntouched(t *testing.T) {
opts := baseOptions()
before := opts
if opts.Compactor != nil {
t.Fatal("Compactor set without Enable")
}
if len(opts.Tools) != len(before.Tools) {
t.Fatal("tools changed without Enable")
}
if len(opts.AppendSystemPrompt) != 0 {
t.Fatal("system prompt changed without Enable")
}
if opts.Compaction == nil {
t.Fatal("the built-in compaction must remain configured when noa is off")
}
}
// The archive is the only route back to compressed originals, so its location
// must be the host's explicit decision — never a silent fallback.
func TestEnableRequiresArchiveDir(t *testing.T) {
opts := baseOptions()
err := Enable(&opts, Options{SessionID: "s1"})
if err == nil {
t.Fatal("Enable accepted an empty ArchiveBaseDir")
}
if opts.Compactor != nil || len(opts.Tools) != 0 || len(opts.AppendSystemPrompt) != 0 {
t.Fatalf("a failed Enable must leave Options untouched: %+v", opts)
}
}
// The session enabled by Enable is the same one the tool holds — otherwise the
// tool would compress into a state the view never reads.
func TestEnableSharesOneSession(t *testing.T) {
opts := baseOptions()
sess, err := EnableWithSession(&opts, Options{ArchiveBaseDir: t.TempDir(), SessionID: "s1"})
if err != nil {
t.Fatalf("EnableWithSession: %v", err)
}
c := opts.Compactor.(*Compactor)
if c.sess != sess {
t.Fatal("the compactor and the returned session differ")
}
}
func toolNames(ts []tool.CoreTool) []string {
out := make([]string, len(ts))
for i, t := range ts {
out[i] = t.Name()
}
return out
}
// End to end: a model-driven compression must shrink the view, write an
// archive holding the originals, and survive a restart.
func TestCompressEndToEnd(t *testing.T) {
dir := t.TempDir()
opts := baseOptions()
sess, err := EnableWithSession(&opts, Options{ArchiveBaseDir: dir, SessionID: "sess1"})
if err != nil {
t.Fatalf("EnableWithSession: %v", err)
}
body := strings.Repeat("compressible content. ", 300)
tail := strings.Repeat("recent tail content. ", 250)
msgs := []llm.Message{userText("the task")}
for range 4 {
msgs = append(msgs, llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{llm.TextBlock(body)}})
}
for range 6 {
msgs = append(msgs, userText(tail))
}
view := sess.View(msgs)
if len(view) != len(msgs) {
t.Fatalf("initial view has %d messages, want %d unchanged", len(view), len(msgs))
}
// The model compresses the filler.
args, _ := json.Marshal(map[string]any{
"topic": "filler",
"content": []map[string]any{{
"startId": "m00002", "endId": "m00005", "summary": longSummary,
}},
})
res, err := runCompress(sess, args, &tool.ToolContext{ToolUseID: "toolu_1"})
if err != nil {
t.Fatalf("runCompress: %v", err)
}
panel := res.Content[0].Text
if res.IsError {
t.Fatalf("compression reported an error: %s", panel)
}
if noa.PanelBlockCount(panel) != 1 {
t.Fatalf("panel reports %d blocks, want 1:\n%s", noa.PanelBlockCount(panel), panel)
}
// The next view must be smaller and carry the summary.
after := sess.View(msgs)
if len(after) >= len(view) {
t.Fatalf("view has %d messages after compression, want fewer than %d", len(after), len(view))
}
foundSummary := false
for _, m := range after {
if strings.HasPrefix(m.Text(), noa.SummaryHeader) {
foundSummary = true
if !strings.Contains(m.Text(), "<noa-archive") {
t.Fatalf("the summary carries no archive pointer: %q", m.Text())
}
}
}
if !foundSummary {
t.Fatal("no summary message in the compressed view")
}
// The archive must hold the originals.
blocks := sess.State().Blocks
if len(blocks) != 1 {
t.Fatalf("state has %d blocks, want 1", len(blocks))
}
archive, err := os.ReadFile(blocks[0].ArchivePath)
if err != nil {
t.Fatalf("read archive: %v", err)
}
if !strings.Contains(string(archive), "compressible content.") {
t.Fatal("the archive does not contain the original text")
}
if !strings.Contains(string(archive), "block: "+blocks[0].BlockID) {
t.Fatal("the archive is missing its front matter")
}
// State must survive a restart.
if _, err := os.Stat(filepath.Join(dir, "sess1", "state.json")); err != nil {
t.Fatalf("state file not written: %v", err)
}
opts2 := baseOptions()
sess2, err := EnableWithSession(&opts2, Options{ArchiveBaseDir: dir, SessionID: "sess1"})
if err != nil {
t.Fatalf("reopen: %v", err)
}
if len(sess2.State().Blocks) != 1 {
t.Fatalf("reopened session has %d blocks, want 1", len(sess2.State().Blocks))
}
}
// Two consecutive views of an unchanged history must be byte-identical, or the
// prefix cache is invalidated every turn.
func TestViewIsStableAcrossTurns(t *testing.T) {
opts := baseOptions()
sess, err := EnableWithSession(&opts, Options{ArchiveBaseDir: t.TempDir(), SessionID: "s"})
if err != nil {
t.Fatalf("EnableWithSession: %v", err)
}
msgs := []llm.Message{
userText("the task"),
{Role: llm.RoleAssistant, Content: []llm.ContentBlock{llm.TextBlock("a reply")}},
userText("follow up"),
}
first := sess.View(msgs)
second := sess.View(msgs)
if len(first) != len(second) {
t.Fatalf("view length changed: %d -> %d", len(first), len(second))
}
for i := range first {
if first[i].Text() != second[i].Text() {
t.Fatalf("message %d changed between identical turns:\n%q\n%q", i, first[i].Text(), second[i].Text())
}
}
}
// View must never write back: message identity is a content hash over the
// stored text, so a rewrite would invalidate every ref the model holds.
func TestViewDoesNotMutateHistory(t *testing.T) {
opts := baseOptions()
sess, _ := EnableWithSession(&opts, Options{ArchiveBaseDir: t.TempDir(), SessionID: "s"})
msgs := []llm.Message{userText("original text")}
_ = sess.View(msgs)
if msgs[0].Text() != "original text" {
t.Fatalf("history was mutated: %q", msgs[0].Text())
}
}
const longSummary = "Explored the authentication design and settled on JWT with refresh tokens. " +
"Key files: auth/jwt.go (issue/verify), auth/middleware.go (context injection). " +
"Refresh tokens live in Redis with a 7-day TTL; access tokens are 15 minutes."
+56
View File
@@ -0,0 +1,56 @@
// Package noaadapter wires the pure noa engine into Norma: it projects
// llm.Message into noa's flat representation and back, persists state and
// archives, and exposes the Compress tool.
//
// See docs/noa-实施方案.md for the specification.
package noaadapter
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/Autumn-27/norma/noa"
)
// DeriveMessageID computes a message's stable identity.
//
// llm.Message has no id field, so noa derives one from the content. A content
// hash rather than an array index is not a stylistic choice: indices shift
// whenever a message is pruned, a nudge is injected, or a session resumes, and
// every ref in the map would break at once. A hash stays put.
//
// text must already have any ref tag stripped. A tag inside the hash would make
// the id change every time the tag is re-rendered, which is every turn.
func DeriveMessageID(role noa.Role, ct noa.ContentType, text, toolCallID, toolName string) string {
seed := string(role) + "|" + string(ct) + "|" + toolCallID + "|" + toolName + "|" + text
sum := sha256.Sum256([]byte(seed))
return "h_" + hex.EncodeToString(sum[:])[:16]
}
// ClusterCounter disambiguates messages that hash identically.
//
// Repeating a command produces byte-identical output, and two messages sharing
// an id would collapse into one in the ref map. The counter appends an
// occurrence suffix so each keeps its own identity, while the first occurrence
// keeps the bare hash — so an unchanged history projects to unchanged ids.
type ClusterCounter struct {
counts map[string]int
}
// NewClusterCounter returns a counter for one projection pass. It must be fresh
// per pass: reusing one across passes would give the same message a different
// suffix each time.
func NewClusterCounter() *ClusterCounter {
return &ClusterCounter{counts: map[string]int{}}
}
// Next returns the id to use for the next occurrence of base.
func (c *ClusterCounter) Next(base string) string {
n := c.counts[base]
c.counts[base] = n + 1
if n == 0 {
return base
}
return fmt.Sprintf("%s_%d", base, n)
}
+84
View File
@@ -0,0 +1,84 @@
package noaadapter
import (
"path/filepath"
"github.com/Autumn-27/norma/noa"
)
// maxInheritDepth bounds the walk up the parent chain. Deep enough for any real
// nesting, shallow enough that a cycle or a mis-linked session cannot spin.
const maxInheritDepth = 8
// DeriveChildState hands a subagent the parent's compression ledger.
//
// What carries over and what does not follows from what each field means:
//
// - Blocks, MessageRefs, TokenSnapshot, NextBlockID are the ledger. Without
// them a child that sees inherited context could not address it, and would
// allocate block ids that collide with the parent's.
// - Nudge is reset. Pacing describes one conversation's pressure history; the
// child starts its own, and inheriting a mid-session cadence would either
// silence it or make it nag immediately.
// - Stats is reset so the child reports its own work.
//
// Inherited blocks keep their original ArchivePath. It is absolute and the file
// is still there, so the child can follow a compression back to its originals
// exactly as the parent could — while its own new archives land in its own
// directory.
func DeriveChildState(parent noa.CompressionState, childSessionID, childArchiveRoot string) noa.CompressionState {
child := noa.CloneState(parent)
child.SessionID = childSessionID
child.ArchiveRoot = childArchiveRoot
child.Nudge = noa.NudgeState{LastShownByTier: map[noa.Tier]int{}}
child.Stats = noa.Stats{}
return child
}
// SubagentArchiveRoot is where a subagent's own archives live.
func SubagentArchiveRoot(base, sessionID, agentID string) string {
return filepath.Join(base, sessionID, "subagents", agentID)
}
// InheritOptions describes one link in a parent chain.
type InheritOptions struct {
// ArchiveBaseDir is shared by every session in the chain.
ArchiveBaseDir string
// SessionID is the session being opened.
SessionID string
// ParentIDs are candidate ancestors, nearest first. The walk stops at the
// first one with blocks.
ParentIDs []string
}
// InheritState finds a usable ledger for a session that has none of its own.
//
// A session can arrive empty for ordinary reasons — a fork, a subagent, a
// transcript copied without its sidecar — and starting from zero would make the
// model re-compress everything the ancestor already compressed. So the chain is
// walked until a state with blocks turns up.
//
// Returns ok=false when nothing was found, which is the normal case for a
// genuinely new session.
func InheritState(o InheritOptions) (noa.CompressionState, string, bool) {
root := filepath.Join(o.ArchiveBaseDir, o.SessionID)
for i, parentID := range o.ParentIDs {
if i >= maxInheritDepth {
break
}
if parentID == "" || parentID == o.SessionID {
continue
}
parentRoot := filepath.Join(o.ArchiveBaseDir, parentID)
store := NewStateStore(parentRoot)
if !store.Exists() {
continue
}
st, err := store.Load(parentID, parentRoot)
if err != nil || len(st.Blocks) == 0 {
continue
}
return DeriveChildState(st, o.SessionID, root), parentID, true
}
return noa.CreateInitialState(o.SessionID, root), "", false
}
+587
View File
@@ -0,0 +1,587 @@
package noaadapter
import (
"encoding/json"
"fmt"
"os"
"regexp"
"strings"
"testing"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/noa"
"github.com/Autumn-27/norma/tool"
)
// simAgent drives a scripted conversation through noa the way a real agent
// would: it works, it watches the view, and when the context manager asks it to
// compress it reads the range table and acts on it.
//
// Nothing here reaches inside noa. The simulation goes through View, reads the
// rendered nudge as text, and calls the Compress tool with ordinary JSON — so a
// failure means the system genuinely does not work end to end, not that a test
// helper drifted from the implementation.
type simAgent struct {
t *testing.T
sess *Session
history []llm.Message
turn int
callSeq int
obeyRate int // compress on 1 of every N nudges; 1 = always
// Telemetry.
viewTokens []int
nudgesSeen int
compressions int
failures int
}
func newSimAgent(t *testing.T, sess *Session, obeyRate int) *simAgent {
t.Helper()
return &simAgent{t: t, sess: sess, obeyRate: max(obeyRate, 1),
history: []llm.Message{userText("Refactor the authentication subsystem and keep it tested.")}}
}
// work appends one turn of plausible agent activity: a thought, a tool call,
// and its output.
func (a *simAgent) work(outputChars int) {
a.turn++
callID := fmt.Sprintf("call_%d", a.turn)
a.history = append(a.history,
llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{
{Type: llm.BlockThinking, Thinking: fmt.Sprintf("Turn %d: checking the next file.", a.turn),
Signature: fmt.Sprintf("sig-%d", a.turn)},
llm.TextBlock(fmt.Sprintf("Reading file %d.", a.turn)),
{Type: llm.BlockToolUse, ID: callID, Name: "Read",
Input: json.RawMessage(fmt.Sprintf(`{"file_path":"/src/mod%d.go"}`, a.turn))},
}},
llm.Message{Role: llm.RoleUser, Content: []llm.ContentBlock{{
Type: llm.BlockToolResult, ToolUseID: callID,
Content: []llm.ContentBlock{llm.TextBlock(
fmt.Sprintf("// mod%d.go\n", a.turn) + strings.Repeat("source line of code. ", outputChars/21))},
}}},
)
}
// rangeLineRE matches the compressible rows of a rendered nudge.
var rangeLineRE = regexp.MustCompile(`^\s{2}(m\d{5})–(m\d{5})\s+\d+ msgs\s+\S+ \[tool`)
// blockLineRE matches the block map entries of a rendered nudge, which read
// `b3(T2)=m00044–m00097`.
var blockLineRE = regexp.MustCompile(`(b\d+)\(T(\d+)\)=(m\d{5})–(m\d{5})`)
// tierTargetLineRE matches the target list a tier-2/3 nudge carries, which is a
// DIFFERENT shape from the block map: ` b7 4 msgs 2.0K→79 "work batch"`
// (FormatTierTargetBlocks). Reading a tier nudge with the block-map pattern
// silently finds nothing and the agent does nothing — which is exactly the way
// a real model would fail if the two formats were as easy to confuse.
var tierTargetLineRE = regexp.MustCompile(`^\s{2}(b\d+)\s+\d+ msgs\s`)
// tierTargets pulls the block ids a tier nudge is asking to consolidate.
func tierTargets(nudge string) []string {
var out []string
for _, line := range strings.Split(nudge, "\n") {
if m := tierTargetLineRE.FindStringSubmatch(line); m != nil {
out = append(out, m[1])
}
}
return out
}
// observe renders the view and reacts to whatever the context manager says.
func (a *simAgent) observe() []llm.Message {
a.t.Helper()
view := a.sess.View(a.history)
a.viewTokens = append(a.viewTokens, estimateMessages(view))
nudge := findNudge(view)
if nudge == "" {
return view
}
a.nudgesSeen++
if a.nudgesSeen%a.obeyRate != 0 {
// Ignoring a nudge is a normal outcome and must not wedge the system.
return view
}
a.act(nudge)
return view
}
// act picks a target the way a cooperative model would: tier consolidation when
// asked for it, otherwise the ranges the table offered.
func (a *simAgent) act(nudge string) {
a.t.Helper()
var entries []map[string]any
if strings.Contains(nudge, "DISTILLATION TRIGGER") || strings.Contains(nudge, "CONDENSATION TRIGGER") {
if targets := tierTargets(nudge); len(targets) >= 2 {
entries = append(entries, map[string]any{
"startId": targets[0], "endId": targets[len(targets)-1],
"summary": a.summary("consolidated blocks"), "topic": "consolidation",
})
}
}
if len(entries) == 0 {
for _, line := range strings.Split(nudge, "\n") {
if m := rangeLineRE.FindStringSubmatch(line); m != nil {
entries = append(entries, map[string]any{
"startId": m[1], "endId": m[2],
"summary": a.summary(m[1] + "–" + m[2]), "topic": "work batch",
})
}
}
}
if len(entries) == 0 {
return
}
a.callSeq++
callID := fmt.Sprintf("compress_%d", a.callSeq)
args, _ := json.Marshal(map[string]any{"content": entries})
res, err := runCompress(a.sess, args, &tool.ToolContext{ToolUseID: callID})
if err != nil {
a.t.Fatalf("turn %d: Compress errored: %v", a.turn, err)
}
panel := res.Content[0].Text
if n := noa.PanelBlockCount(panel); n > 0 {
a.compressions += n
} else {
a.failures++
}
// A real agent's call and its result become part of the history.
a.history = append(a.history,
llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{
Type: llm.BlockToolUse, ID: callID, Name: noa.CompressToolName, Input: args,
}}},
llm.Message{Role: llm.RoleUser, Content: []llm.ContentBlock{{
Type: llm.BlockToolResult, ToolUseID: callID,
Content: []llm.ContentBlock{llm.TextBlock(panel)},
}}},
)
}
// summary produces something that satisfies the length rules and reads like
// what the guidance asks for.
func (a *simAgent) summary(label string) string {
return fmt.Sprintf("Summary of %s: read and reviewed several modules under /src. "+
"Key files: auth/jwt.go:42 (token issue/verify), auth/middleware.go:18 (context injection). "+
"Decision: keep JWT with refresh tokens because session cookies cannot cross the mobile client. "+
"Open: the clock-skew leeway is still hard-coded at 60s.", label)
}
func findNudge(view []llm.Message) string {
for _, m := range view {
if strings.Contains(m.Text(), "HOW TO COMPRESS") {
return m.Text()
}
}
return ""
}
func simSession(t *testing.T, window int) *Session {
t.Helper()
opts := baseOptions()
cfg := noa.DefaultConfig(window)
sess, err := EnableWithSession(&opts, Options{
ArchiveBaseDir: t.TempDir(), SessionID: "sim", Config: &cfg,
})
if err != nil {
t.Fatalf("EnableWithSession: %v", err)
}
return sess
}
// The point of the whole system: a conversation far longer than the window runs
// to completion without the context growing without bound.
func TestLongSessionStaysBounded(t *testing.T) {
window := 40000
sess := simSession(t, window)
a := newSimAgent(t, sess, 1)
for range 60 {
a.work(4000)
a.observe()
}
if a.compressions == 0 {
t.Fatal("60 turns of growth produced no compression at all")
}
peak := 0
for _, n := range a.viewTokens {
peak = max(peak, n)
}
if peak > window {
t.Fatalf("view peaked at %d tokens, past the %d window", peak, window)
}
// The tail is what matters: early turns are allowed to grow freely.
tail := a.viewTokens[len(a.viewTokens)-10:]
tailPeak := 0
for _, n := range tail {
tailPeak = max(tailPeak, n)
}
if tailPeak > window*3/4 {
t.Fatalf("the last ten turns peaked at %d tokens (>75%% of the %d window); "+
"compression is not keeping up", tailPeak, window)
}
t.Logf("turns=%d nudges=%d compressions=%d failures=%d peak=%d tailPeak=%d blocks=%d",
a.turn, a.nudgesSeen, a.compressions, a.failures, peak, tailPeak, len(sess.State().Blocks))
}
// Blocks accumulating is only a problem if their summaries start to dominate
// the context — that is the invariant worth holding, not a block count.
//
// Under pressure the tier with the most to reclaim wins, and while raw content
// keeps piling up that is tier 1. So a busy session legitimately carries many
// tier-1 blocks; what must not happen is the summaries themselves becoming the
// thing filling the window.
func TestLongSessionSummariesDoNotDominate(t *testing.T) {
window := 40000
sess := simSession(t, window)
a := newSimAgent(t, sess, 1)
for range 80 {
a.work(4000)
a.observe()
}
active := noa.ActiveBlocks(sess.State())
if len(active) == 0 {
t.Fatal("no active blocks after 80 turns")
}
summaryTokens := 0
tiers := map[noa.Tier]int{}
for _, b := range active {
summaryTokens += noa.DefaultCountTokens(b.Summary)
tiers[b.Tier]++
}
if summaryTokens > window/4 {
t.Fatalf("summaries occupy %d of the %d window (>25%%) across %d blocks — "+
"consolidation is not keeping up", summaryTokens, window, len(active))
}
t.Logf("active blocks by tier: %v (total %d, %d summary tokens = %.1f%% of window)",
tiers, len(active), summaryTokens, float64(summaryTokens)*100/float64(window))
}
// Compression has to actually reclaim space, not merely rearrange it.
func TestCompressionReclaimsTokens(t *testing.T) {
sess := simSession(t, 40000)
a := newSimAgent(t, sess, 1)
for range 40 {
a.work(4000)
a.observe()
}
st := sess.State()
var compressed, summaryCost int
for _, b := range st.Blocks {
compressed += b.CompressedTokens
summaryCost += noa.DefaultCountTokens(b.Summary)
}
if compressed == 0 {
t.Fatal("nothing was compressed")
}
if summaryCost >= compressed {
t.Fatalf("summaries cost %d tokens to replace %d — compression reclaimed nothing", summaryCost, compressed)
}
ratio := float64(compressed) / float64(max(summaryCost, 1))
if ratio < 2 {
t.Fatalf("compression ratio %.1fx is too low to be worth a turn", ratio)
}
t.Logf("reclaimed %d tokens into %d (%.1fx) across %d blocks", compressed, summaryCost, ratio, len(st.Blocks))
}
// Every compressed range must be recoverable from disk, however deep the tier
// chain goes.
func TestLongSessionArchivesRemainComplete(t *testing.T) {
sess := simSession(t, 40000)
a := newSimAgent(t, sess, 1)
for range 50 {
a.work(4000)
a.observe()
}
st := sess.State()
if len(st.Blocks) == 0 {
t.Fatal("no blocks to check")
}
for _, b := range st.Blocks {
raw, err := os.ReadFile(b.ArchivePath)
if err != nil {
t.Fatalf("block %s (tier %d): archive unreadable: %v", b.BlockID, b.Tier, err)
}
body := string(raw)
if !strings.Contains(body, "block: "+b.BlockID) {
t.Fatalf("block %s: archive front matter does not identify it", b.BlockID)
}
if b.Tier == 1 {
// A tier-1 archive holds raw messages.
if !strings.Contains(body, "· tool_result ·") && !strings.Contains(body, "· assistant") {
t.Fatalf("block %s: tier-1 archive holds no original messages:\n%s", b.BlockID, head(body, 400))
}
} else {
// A higher tier holds the summaries it absorbed, each pointing on.
if !strings.Contains(body, "绝对路径") {
t.Fatalf("block %s: tier-%d archive names no child archive:\n%s", b.BlockID, b.Tier, head(body, 400))
}
}
}
}
// A model that only sometimes complies must not wedge the system, and the
// failure ladder must not silence nudging for good.
func TestLongSessionWithPartiallyCompliantModel(t *testing.T) {
sess := simSession(t, 40000)
a := newSimAgent(t, sess, 3) // acts on one nudge in three
for range 80 {
a.work(4000)
a.observe()
}
if a.compressions == 0 {
t.Fatal("a partially compliant model produced no compression at all")
}
// The mechanical valve must have held the line where the model did not.
peak := 0
for _, n := range a.viewTokens {
peak = max(peak, n)
}
if peak > 40000 {
t.Fatalf("view peaked at %d, past the window — the mechanical valve did not hold", peak)
}
t.Logf("partial compliance: nudges=%d compressions=%d peak=%d", a.nudgesSeen, a.compressions, peak)
}
// A model that never compresses is the worst case the design has to survive.
func TestLongSessionWithUncooperativeModel(t *testing.T) {
window := 40000
sess := simSession(t, window)
a := newSimAgent(t, sess, 1000000) // never acts
for range 60 {
a.work(4000)
a.observe()
}
if a.compressions != 0 {
t.Fatal("the uncooperative model compressed something; the fixture is wrong")
}
peak := 0
for _, n := range a.viewTokens {
peak = max(peak, n)
}
// What IS guaranteed: nudging stops rather than replaying a multi-thousand
// token prompt into a context that is already too big.
if a.nudgesSeen > 25 {
t.Fatalf("%d nudges were sent to a model that never acted; suppression is not working", a.nudgesSeen)
}
// What is NOT guaranteed is that the context stays under the window — see
// TestTruncateCannotHelpWithManyMediumMessages. The designed outcome there
// is a clean ReasonPromptTooLong via Reactive, not a silent overflow.
t.Logf("uncooperative: nudges=%d peak=%d window=%d (overflow is expected here; "+
"the valve only bites on individually large messages)", a.nudgesSeen, peak, window)
}
// What the mechanical valve actually guarantees: when tool results are large
// enough to cut, it removes most of their weight from every request.
//
// It is a stopgap, not a substitute for compression. Truncation leaves a floor
// of roughly one thousand tokens per message (the head and tail it keeps), so
// enough messages will still exceed any window — see
// TestTruncateFloorAccumulatesWithoutCompression. What it buys is time, and a
// request that stays valid while the model has the chance to act.
func TestTruncateRemovesMostOfLargeOutputs(t *testing.T) {
window := 40000
sess := simSession(t, window)
a := newSimAgent(t, sess, 1000000) // never compresses
for range 8 {
a.work(40000) // each tool result is far above the truncation floor
a.observe()
}
cores, _ := Project(a.history)
raw := estimateCoreTokens(cores)
sent := a.viewTokens[len(a.viewTokens)-1]
if sent >= raw/2 {
t.Fatalf("the request carries %d of %d raw tokens; truncation removed almost nothing", sent, raw)
}
if sess.lastTruncatedCount == 0 {
t.Fatal("no tool result was truncated despite every one being far above the floor")
}
t.Logf("raw=%d sent=%d (%.0f%% removed) across %d truncations",
raw, sent, (1-float64(sent)/float64(raw))*100, sess.lastTruncatedCount)
}
// A second documented limitation, pinned so it is known rather than discovered.
//
// Truncation keeps a head and a tail of each message, which floors it at roughly
// a thousand tokens. N truncated messages therefore cannot go below about N
// thousand tokens, and a long enough uncooperative session exceeds any window no
// matter how aggressively the valve fires.
//
// This is why the valve is explicitly a last resort rather than a strategy: only
// compression removes messages from the request entirely.
func TestTruncateFloorAccumulatesWithoutCompression(t *testing.T) {
window := 40000
sess := simSession(t, window)
a := newSimAgent(t, sess, 1000000)
for range 60 {
a.work(40000)
a.observe()
}
last := a.viewTokens[len(a.viewTokens)-1]
if last <= window {
t.Skip("the fixture stayed under the window; the floor was not reached")
}
// Even overflowing, truncation must still have done its work — the failure
// mode is an accumulated floor, not an inactive valve.
if sess.lastTruncatedCount == 0 {
t.Fatal("the valve stopped firing entirely; that is a different bug")
}
c := &Compactor{sess: sess}
if _, ok := c.Reactive(t.Context(), a.history); ok {
t.Fatal("Reactive claimed it shrank a view it cannot shrink; that produces a 413 retry loop")
}
t.Logf("accumulated floor: %d tokens over a %d window after 60 uncompressed turns "+
"(%d truncations); Reactive correctly refused", last, window, sess.lastTruncatedCount)
}
// A documented limitation, pinned so it is a known property rather than a
// surprise.
//
// emergency-truncate cuts individual tool results. It cannot help when the
// context is made of many MEDIUM messages: each is below the minimum worth
// cutting, and cutting one to head+tail would make it longer than it started.
// The constants (1000-token floor, 2000+2000 kept) are sized for a large window,
// where anything worth truncating is much bigger than this.
//
// The designed outcome in that case is not silent overflow: Reactive rebuilds
// the view, sees it did not shrink, and returns false so the run ends with a
// clean ReasonPromptTooLong instead of a 413 retry loop.
func TestTruncateCannotHelpWithManyMediumMessages(t *testing.T) {
window := 40000
sess := simSession(t, window)
a := newSimAgent(t, sess, 1000000)
for range 40 {
a.work(4000) // just under both truncation criteria
a.observe()
}
peak := 0
for _, n := range a.viewTokens {
peak = max(peak, n)
}
if peak <= window {
t.Skip("the fixture did not reach the window; the limitation is not exercised")
}
// Reactive is what turns this into a clean failure rather than a retry loop.
c := &Compactor{sess: sess}
if _, ok := c.Reactive(t.Context(), a.history); ok {
t.Fatal("Reactive claimed it shrank a view it cannot shrink; that produces a 413 retry loop")
}
t.Logf("documented limitation: peak=%d window=%d, Reactive correctly refused", peak, window)
}
// Whatever happens, the request must stay well-formed.
func TestLongSessionViewStaysValid(t *testing.T) {
sess := simSession(t, 40000)
a := newSimAgent(t, sess, 2)
for range 50 {
a.work(4000)
view := a.observe()
assertValidRequest(t, view, a.turn)
}
}
// assertValidRequest checks the invariants a provider would reject.
func assertValidRequest(t *testing.T, view []llm.Message, turn int) {
t.Helper()
useIDs := map[string]bool{}
resIDs := map[string]bool{}
for _, m := range view {
if len(m.Content) == 0 {
t.Fatalf("turn %d: an empty message reached the request", turn)
}
for _, b := range m.Content {
switch b.Type {
case llm.BlockToolUse:
useIDs[b.ID] = true
case llm.BlockToolResult:
resIDs[b.ToolUseID] = true
case llm.BlockThinking:
if b.Signature == "" {
t.Fatalf("turn %d: a thinking block lost its signature; Anthropic rejects that on replay", turn)
}
}
}
if m.Role == llm.RoleAssistant && m.Text() == "" && len(m.ToolUses()) == 0 {
hasThinking := false
for _, b := range m.Content {
if b.Type == llm.BlockThinking {
hasThinking = true
}
}
if !hasThinking {
t.Fatalf("turn %d: an empty assistant message reached the request", turn)
}
}
}
for id := range resIDs {
if !useIDs[id] {
t.Fatalf("turn %d: tool_result %s has no matching tool_use", turn, id)
}
}
for id := range useIDs {
if !resIDs[id] {
t.Fatalf("turn %d: tool_use %s has no matching tool_result", turn, id)
}
}
}
// The task definition must survive any amount of compression.
func TestLongSessionPreservesFirstUserMessage(t *testing.T) {
sess := simSession(t, 40000)
a := newSimAgent(t, sess, 1)
for range 60 {
a.work(4000)
a.observe()
}
view := sess.View(a.history)
found := false
for _, m := range view {
if strings.Contains(m.Text(), "Refactor the authentication subsystem") {
found = true
}
}
if !found {
t.Fatal("the first user message was compressed away; the model no longer knows what it is doing")
}
}
// Refs are handed out once. Nothing in a long session may renumber them.
func TestLongSessionRefsNeverChange(t *testing.T) {
sess := simSession(t, 40000)
a := newSimAgent(t, sess, 1)
seen := map[string]string{}
for range 50 {
a.work(4000)
a.observe()
for raw, ref := range sess.State().MessageRefs.ByRaw {
if prev, ok := seen[raw]; ok && prev != ref {
t.Fatalf("message %s changed ref from %s to %s at turn %d", raw, prev, ref, a.turn)
}
seen[raw] = ref
}
}
if len(seen) < 20 {
t.Fatalf("only %d refs were assigned across 50 turns; the fixture is not exercising much", len(seen))
}
}
func head(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] + "…"
}
+93
View File
@@ -0,0 +1,93 @@
package noaadapter
import (
"time"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/noa"
)
// Materialize applies a session's compression state to a message array so the
// session can continue with noa switched off.
//
// Why this is needed: l.messages is an in-memory working copy rebuilt from the
// transcript on every resume, and the transcript holds the FULL history. With
// noa off, View no longer runs, so llm.MessagesForAPI would send all of it and
// overflow immediately.
//
// It is a pure function — no transcript write, no state mutation, no trace —
// which buys three properties:
//
// - Idempotent: same transcript + same state, same output, every resume.
// - Reversible: turning noa back on costs nothing, because the block ledger
// was never touched.
// - The transcript stays exactly what it is: a record of what happened, with
// no derived content mixed in for later readers to have to distinguish.
//
// The archive pointers inside the summaries keep working: they are plain paths
// to files that are still on disk, readable with the ordinary Read tool. Being
// able to follow a compression back to its originals does not depend on any
// noa code still running.
//
// No state and no active blocks means nothing to do, so calling this
// unconditionally is safe.
func Materialize(msgs []llm.Message, o Options) ([]llm.Message, error) {
if o.ArchiveBaseDir == "" {
return msgs, ErrNoArchiveDir
}
sess, err := newSession(o)
if err != nil {
return msgs, err
}
state := sess.State()
if len(noa.ActiveBlocks(state)) == 0 {
return msgs, nil
}
cores, sc := Project(msgs)
pruned, _ := noa.RunPruneOnly(cores, state, sess.Config())
// No ref tags: they address a scheme that is no longer running, and would
// only invite the model to use ids nothing will resolve.
return Reassemble(pruned, msgs, sc, ReassembleOptions{Tag: false}), nil
}
// RebuildFromHistory reconstructs compression state by replaying the Compress
// calls recorded in a conversation.
//
// It is the fallback when state.json is missing — imported, corrupted, or never
// written. No model is involved: the summaries live in the recorded call
// arguments, so replaying returns the byte-identical text rather than a fresh
// approximation of it.
//
// Existing archives are adopted rather than rewritten. They are historical fact;
// a re-render would be a different file describing the same moment.
func RebuildFromHistory(msgs []llm.Message, o Options) (*Session, error) {
sess, err := newSession(o)
if err != nil {
return nil, err
}
cores, _ := Project(msgs)
now := sess.now()
res := noa.RebuildStateFromLog(noa.RebuildInput{
Messages: cores,
Config: sess.Config(),
Archiver: NewReuseArchiver(sess.ArchiveRoot()),
SessionID: o.SessionID,
ArchiveRoot: sess.ArchiveRoot(),
CreatedAt: now.Format(time.RFC3339),
Now: now.Unix(),
})
for _, w := range res.Warnings {
sess.warn("rebuild: " + w)
}
sess.mu.Lock()
sess.state = res.State
sess.mu.Unlock()
if err := sess.store.Save(res.State); err != nil {
sess.warn("rebuild: state save failed: " + err.Error())
}
return sess, nil
}
+298
View File
@@ -0,0 +1,298 @@
package noaadapter
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/noa"
"github.com/Autumn-27/norma/tool"
)
// compressedSession returns a session with one real block, plus the history it
// was built from and the options needed to reopen it.
func compressedSession(t *testing.T) (Options, []llm.Message, *Session) {
t.Helper()
dir := t.TempDir()
o := Options{ArchiveBaseDir: dir, SessionID: "sess"}
opts := baseOptions()
sess, err := EnableWithSession(&opts, o)
if err != nil {
t.Fatalf("EnableWithSession: %v", err)
}
body := strings.Repeat("compressible content. ", 300)
tail := strings.Repeat("recent tail content. ", 250)
msgs := []llm.Message{userText("the task")}
for range 4 {
msgs = append(msgs, llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{llm.TextBlock(body)}})
}
for range 6 {
msgs = append(msgs, userText(tail))
}
sess.View(msgs)
args, _ := json.Marshal(map[string]any{
"content": []map[string]any{{"startId": "m00002", "endId": "m00005", "summary": longSummary}},
})
res, err := runCompress(sess, args, &tool.ToolContext{ToolUseID: "toolu_1"})
if err != nil || noa.PanelBlockCount(res.Content[0].Text) != 1 {
t.Fatalf("setup compression failed: %v / %s", err, res.Content[0].Text)
}
return o, msgs, sess
}
// With noa off, the full history would be sent and overflow at once; applying
// the state keeps it the size it was compressed to.
func TestMaterializeAppliesCompression(t *testing.T) {
o, msgs, _ := compressedSession(t)
out, err := Materialize(msgs, o)
if err != nil {
t.Fatalf("Materialize: %v", err)
}
if len(out) >= len(msgs) {
t.Fatalf("materialized to %d messages, want fewer than the %d original", len(out), len(msgs))
}
found := false
for _, m := range out {
if strings.HasPrefix(m.Text(), noa.SummaryHeader) {
found = true
// The archive pointer must survive: following a compression back to
// its originals is a plain file read and does not need noa running.
if !strings.Contains(m.Text(), "<noa-archive") {
t.Fatalf("the summary lost its archive pointer: %q", m.Text())
}
}
}
if !found {
t.Fatal("no summary in the materialized output")
}
}
// Ref tags address a scheme that is no longer running; leaving them would
// invite the model to use ids nothing will resolve.
func TestMaterializeEmitsNoRefTags(t *testing.T) {
o, msgs, _ := compressedSession(t)
out, err := Materialize(msgs, o)
if err != nil {
t.Fatalf("Materialize: %v", err)
}
for _, m := range out {
if strings.Contains(m.Text(), "<noa-ref") {
t.Fatalf("a ref tag survived materialization: %q", m.Text())
}
}
}
func TestMaterializeIsIdempotent(t *testing.T) {
o, msgs, _ := compressedSession(t)
first, err := Materialize(msgs, o)
if err != nil {
t.Fatalf("Materialize: %v", err)
}
second, err := Materialize(msgs, o)
if err != nil {
t.Fatalf("Materialize (second): %v", err)
}
if len(first) != len(second) {
t.Fatalf("lengths differ between runs: %d vs %d", len(first), len(second))
}
for i := range first {
if first[i].Text() != second[i].Text() {
t.Fatalf("message %d differs between runs:\n%q\n%q", i, first[i].Text(), second[i].Text())
}
}
}
// Safe to call unconditionally: with nothing compressed there is nothing to do.
func TestMaterializeWithoutBlocksIsPassthrough(t *testing.T) {
o := Options{ArchiveBaseDir: t.TempDir(), SessionID: "fresh"}
msgs := []llm.Message{userText("hello"), userText("world")}
out, err := Materialize(msgs, o)
if err != nil {
t.Fatalf("Materialize: %v", err)
}
if len(out) != len(msgs) {
t.Fatalf("got %d messages, want the input returned unchanged", len(out))
}
}
// The transcript and the block ledger must be untouched, so switching noa back
// on costs nothing.
func TestMaterializeLeavesStateAndHistoryAlone(t *testing.T) {
o, msgs, sess := compressedSession(t)
before := sess.State()
stateFile := filepath.Join(o.ArchiveBaseDir, o.SessionID, "state.json")
raw1, err := os.ReadFile(stateFile)
if err != nil {
t.Fatalf("read state: %v", err)
}
originalFirst := msgs[0].Text()
if _, err := Materialize(msgs, o); err != nil {
t.Fatalf("Materialize: %v", err)
}
raw2, _ := os.ReadFile(stateFile)
if string(raw1) != string(raw2) {
t.Fatal("Materialize rewrote state.json; it must be a pure function")
}
if msgs[0].Text() != originalFirst {
t.Fatal("Materialize mutated the input history")
}
// Re-enabling must find the ledger intact.
opts := baseOptions()
again, err := EnableWithSession(&opts, o)
if err != nil {
t.Fatalf("re-enable: %v", err)
}
if len(again.State().Blocks) != len(before.Blocks) {
t.Fatalf("blocks after re-enable = %d, want %d", len(again.State().Blocks), len(before.Blocks))
}
}
func TestMaterializeRequiresArchiveDir(t *testing.T) {
if _, err := Materialize(nil, Options{SessionID: "s"}); err == nil {
t.Fatal("Materialize accepted an empty ArchiveBaseDir")
}
}
// Losing state.json costs a replay, not the data: the summaries live in the
// recorded call arguments and come back byte-identical.
func TestRebuildFromHistoryRecoversBlocks(t *testing.T) {
o, msgs, sess := compressedSession(t)
original := sess.State()
// Simulate the conversation as the transcript holds it: the compression
// call and its result are real messages.
args, _ := json.Marshal(map[string]any{
"content": []map[string]any{{"startId": "m00002", "endId": "m00005", "summary": longSummary}},
})
history := append([]llm.Message(nil), msgs...)
history = append(history,
llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{
Type: llm.BlockToolUse, ID: "toolu_1", Name: noa.CompressToolName, Input: args,
}}},
llm.Message{Role: llm.RoleUser, Content: []llm.ContentBlock{{
Type: llm.BlockToolResult, ToolUseID: "toolu_1",
Content: []llm.ContentBlock{llm.TextBlock("▣ noa | 12K → 3K tokens (~9K reclaimed)\n b1(T1)=m00002–m00005 → /a/b1.md")},
}}},
)
// Wipe the state file and rebuild.
if err := os.Remove(filepath.Join(o.ArchiveBaseDir, o.SessionID, "state.json")); err != nil {
t.Fatalf("remove state: %v", err)
}
fresh := Options{ArchiveBaseDir: o.ArchiveBaseDir, SessionID: o.SessionID}
rebuilt, err := RebuildFromHistory(history, fresh)
if err != nil {
t.Fatalf("RebuildFromHistory: %v", err)
}
blocks := rebuilt.State().Blocks
if len(blocks) != 1 {
t.Fatalf("rebuilt %d blocks, want 1", len(blocks))
}
if blocks[0].Summary != original.Blocks[0].Summary {
t.Fatal("the rebuilt summary differs — replay must return the byte-identical text, not a regeneration")
}
if !rebuilt.store.Exists() {
t.Fatal("the rebuilt state was not persisted")
}
}
// A call that failed then would fail identically now; replaying it is pointless.
func TestRebuildSkipsFailedCalls(t *testing.T) {
dir := t.TempDir()
o := Options{ArchiveBaseDir: dir, SessionID: "s"}
args, _ := json.Marshal(map[string]any{
"content": []map[string]any{{"startId": "m00001", "endId": "m00002", "summary": longSummary}},
})
history := []llm.Message{
userText("the task"),
{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{
Type: llm.BlockToolUse, ID: "failed", Name: noa.CompressToolName, Input: args,
}}},
{Role: llm.RoleUser, Content: []llm.ContentBlock{{
Type: llm.BlockToolResult, ToolUseID: "failed",
Content: []llm.ContentBlock{llm.TextBlock("▣ noa | 0 blocks created\n error: Summary too short")},
}}},
}
sess, err := RebuildFromHistory(history, o)
if err != nil {
t.Fatalf("RebuildFromHistory: %v", err)
}
if len(sess.State().Blocks) != 0 {
t.Fatalf("rebuilt %d blocks from a failed call, want 0", len(sess.State().Blocks))
}
}
// Existing archives are historical fact; a re-render would be a different file
// describing the same moment.
func TestReuseArchiverAdoptsExistingFiles(t *testing.T) {
root := t.TempDir()
a := NewReuseArchiver(root)
abs, rel, err := a.Write(1, "b1", "m00001", "m00009", []byte("original content"))
if err != nil {
t.Fatalf("first write: %v", err)
}
abs2, rel2, err := a.Write(1, "b1", "m00001", "m00009", []byte("DIFFERENT content"))
if err != nil {
t.Fatalf("second write: %v", err)
}
if abs != abs2 || rel != rel2 {
t.Fatalf("paths differ: %s/%s vs %s/%s", abs, rel, abs2, rel2)
}
raw, _ := os.ReadFile(abs)
if string(raw) != "original content" {
t.Fatalf("the existing archive was overwritten: %q", raw)
}
// Remove is a no-op: a replay must not delete archives it did not create.
if err := a.Remove(abs); err != nil {
t.Fatalf("Remove: %v", err)
}
if _, err := os.Stat(abs); err != nil {
t.Fatal("a replay deleted a pre-existing archive")
}
}
func TestFileArchiverWritesAtomically(t *testing.T) {
root := t.TempDir()
a := NewFileArchiver(root)
abs, rel, err := a.Write(2, "b5", "m00012", "m00160", []byte("archive body"))
if err != nil {
t.Fatalf("Write: %v", err)
}
if !strings.HasSuffix(rel, ".md") || !strings.HasPrefix(rel, "tier2/") {
t.Fatalf("rel = %q, want tier2/<name>.md", rel)
}
raw, err := os.ReadFile(abs)
if err != nil {
t.Fatalf("read back: %v", err)
}
if string(raw) != "archive body" {
t.Fatalf("content = %q", raw)
}
// No temp files may be left behind.
entries, _ := os.ReadDir(filepath.Join(root, "tier2"))
for _, e := range entries {
if strings.HasPrefix(e.Name(), ".noa-") {
t.Fatalf("a temp file survived: %s", e.Name())
}
}
if err := a.Remove(abs); err != nil {
t.Fatalf("Remove: %v", err)
}
if _, err := os.Stat(abs); !os.IsNotExist(err) {
t.Fatal("Remove did not delete the archive")
}
// Removing a missing archive is fine: rollback runs over files that may
// never have landed.
if err := a.Remove(abs); err != nil {
t.Fatalf("Remove of a missing file = %v, want nil", err)
}
}
+71
View File
@@ -0,0 +1,71 @@
package noaadapter
import (
"github.com/Autumn-27/norma/agentcore"
"github.com/Autumn-27/norma/noa"
"github.com/Autumn-27/norma/tool"
)
// Enable wires noa into a set of agentcore Options.
//
// This is the ONLY entry point, and it is all-or-nothing by design. It attaches
// three things at once:
//
// 1. opts.Compactor — takes over the view (and disables the built-in
// Compaction, which a session cannot run alongside it)
// 2. opts.Tools += Compress — the compression tool
// 3. opts.AppendSystemPrompt — the three resident prompt sections
//
// They must live or die together. Wiring them separately makes three ways to
// get it half-right, and each failure is quiet:
//
// - no Compactor: the model compresses, the panel says it worked, and the
// view never changes — the compression went nowhere.
// - no tool: the prompt teaches a tool that does not exist.
// - no prompt: the model has the tool but not the rules, and writes summaries
// that drop paths, decisions and error strings. Nothing reports an error;
// it surfaces hours later as a model that has forgotten what it did.
//
// Not calling Enable is the off switch: nothing is attached, and the built-in
// compaction keeps working exactly as before.
func Enable(opts *agentcore.Options, o Options) error {
if o.ModelContextLimit == 0 && o.Config == nil {
o.ModelContextLimit = defaultContextLimit
}
if o.OnWarn == nil {
o.OnWarn = opts.OnWarn
}
sess, err := newSession(o)
if err != nil {
return err
}
opts.Compactor = &Compactor{sess: sess}
opts.Tools = append(opts.Tools, newCompressTool(sess))
opts.AppendSystemPrompt = append(opts.AppendSystemPrompt, noa.BuildSystemPrompt(noa.Sections{}))
// The prompt section is fully static, so it belongs in the cacheable prefix.
// Left past the boundary it would be re-billed every single request.
opts.DynamicBoundary = len(opts.SystemPrompt) + len(opts.AppendSystemPrompt)
return nil
}
// defaultContextLimit is used when the host names no window. It is deliberately
// conservative: guessing high would delay every pressure threshold past the
// point where they could still help.
const defaultContextLimit = 200000
// EnableWithSession is Enable, also returning the session so a host can inspect
// state or archives. The session is owned by the returned wiring; callers must
// not construct a second one over the same directory.
func EnableWithSession(opts *agentcore.Options, o Options) (*Session, error) {
if err := Enable(opts, o); err != nil {
return nil, err
}
c, ok := opts.Compactor.(*Compactor)
if !ok {
return nil, ErrNoArchiveDir
}
return c.sess, nil
}
var _ tool.CoreTool = newCompressTool(&Session{cfg: noa.DefaultConfig(1)})
+262
View File
@@ -0,0 +1,262 @@
package noaadapter
import (
"encoding/json"
"strings"
"testing"
"github.com/Autumn-27/norma/agentcore"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/noa"
"github.com/Autumn-27/norma/tool"
)
// pressureSession builds a session whose view is large enough to sit in the
// pressure band with a real backlog.
func pressureSession(t *testing.T) (*Session, []llm.Message) {
t.Helper()
opts := baseOptions()
cfg := noa.DefaultConfig(20000) // a small window makes the fixture manageable
sess, err := EnableWithSession(&opts, Options{
ArchiveBaseDir: t.TempDir(), SessionID: "s", Config: &cfg,
})
if err != nil {
t.Fatalf("EnableWithSession: %v", err)
}
body := strings.Repeat("compressible tool output. ", 400)
msgs := []llm.Message{userText("the task")}
for i := range 6 {
msgs = append(msgs, llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{
{Type: llm.BlockToolUse, ID: "t" + string(rune('a'+i)), Name: "Bash", Input: json.RawMessage(`{}`)},
}})
msgs = append(msgs, llm.Message{Role: llm.RoleUser, Content: []llm.ContentBlock{{
Type: llm.BlockToolResult, ToolUseID: "t" + string(rune('a'+i)),
Content: []llm.ContentBlock{llm.TextBlock(body)},
}}})
}
tail := strings.Repeat("recent. ", 300)
for range 6 {
msgs = append(msgs, userText(tail))
}
return sess, msgs
}
func viewHasNudge(view []llm.Message) bool {
for _, m := range view {
if strings.Contains(m.Text(), "HOW TO COMPRESS") {
return true
}
}
return false
}
func TestNudgeIsInjectedUnderPressure(t *testing.T) {
sess, msgs := pressureSession(t)
view := sess.View(msgs)
if !viewHasNudge(view) {
t.Fatal("no nudge injected despite pressure and a large backlog")
}
last := view[len(view)-1]
if last.Role != llm.RoleUser {
t.Fatalf("the nudge landed as %s, want a user message", last.Role)
}
}
// The nudge exists only in the request. It is never written back, so the host's
// history stays exactly as it was.
func TestNudgeNeverEntersHistory(t *testing.T) {
sess, msgs := pressureSession(t)
before := len(msgs)
view := sess.View(msgs)
if !viewHasNudge(view) {
t.Skip("no nudge this turn; the injection path is covered elsewhere")
}
if len(msgs) != before {
t.Fatalf("history grew from %d to %d — the nudge must not be written back", before, len(msgs))
}
for _, m := range msgs {
if strings.Contains(m.Text(), "HOW TO COMPRESS") {
t.Fatal("a nudge reached the stored history")
}
}
}
// Three consecutive ignored nudges must silence nudging: replaying a
// multi-thousand-token nudge into an overflowing context makes the problem it
// describes worse.
func TestNudgeSuppressedAfterRepeatedIgnores(t *testing.T) {
sess, msgs := pressureSession(t)
nudged := 0
for range sess.Config().MaxCompressAttempts {
if viewHasNudge(sess.View(msgs)) {
nudged++
}
// The model answers with plain text — no Compress call at all.
msgs = append(msgs, llm.Message{Role: llm.RoleAssistant,
Content: []llm.ContentBlock{llm.TextBlock("working on it")}})
}
if nudged == 0 {
t.Fatal("no nudge fired at all; the fixture is not under pressure")
}
if viewHasNudge(sess.View(msgs)) {
t.Fatalf("still nudging after %d ignored prompts", nudged)
}
}
// Suppression must not be permanent: once the context has grown by a cadence
// step the situation genuinely differs from the one the model declined.
func TestNudgeSuppressionLiftsAfterGrowth(t *testing.T) {
sess, msgs := pressureSession(t)
for range sess.Config().MaxCompressAttempts + 1 {
sess.View(msgs)
msgs = append(msgs, llm.Message{Role: llm.RoleAssistant,
Content: []llm.ContentBlock{llm.TextBlock("working on it")}})
}
if viewHasNudge(sess.View(msgs)) {
t.Fatal("expected suppression before testing its release")
}
// The context grows by well over a cadence step.
grow := strings.Repeat("more content. ", 4000)
for range 3 {
msgs = append(msgs, llm.Message{Role: llm.RoleAssistant,
Content: []llm.ContentBlock{llm.TextBlock(grow)}})
}
if !viewHasNudge(sess.View(msgs)) {
t.Fatal("suppression did not lift after the context grew a full cadence step")
}
}
// A new user message is a new situation; the ladder resets.
func TestNudgeSuppressionResetsOnUserTurn(t *testing.T) {
sess, msgs := pressureSession(t)
for range sess.Config().MaxCompressAttempts + 1 {
sess.View(msgs)
msgs = append(msgs, llm.Message{Role: llm.RoleAssistant,
Content: []llm.ContentBlock{llm.TextBlock("working on it")}})
}
if viewHasNudge(sess.View(msgs)) {
t.Fatal("expected suppression before testing the reset")
}
msgs = append(msgs, userText("actually, do this instead"))
if !viewHasNudge(sess.View(msgs)) {
t.Fatal("a new user turn must reset the failure ladder")
}
}
// Norma packs tool results into user-role messages, so the role alone cannot
// distinguish a person speaking from a tool answering.
func TestIsRealUserTurn(t *testing.T) {
if !isRealUserTurn(userText("hello")) {
t.Error("a plain user message must read as a real turn")
}
if isRealUserTurn(toolResult("t1", "output")) {
t.Error("a packaged tool result must NOT read as a real user turn")
}
if isRealUserTurn(llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{llm.TextBlock("x")}}) {
t.Error("an assistant message is not a user turn")
}
if isRealUserTurn(llm.Message{Role: llm.RoleUser}) {
t.Error("an empty message is not a turn")
}
}
func TestLastAssistantCalledCompress(t *testing.T) {
compressCall := llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{
{Type: llm.BlockToolUse, ID: "t1", Name: noa.CompressToolName, Input: json.RawMessage(`{}`)},
}}
other := llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{
{Type: llm.BlockToolUse, ID: "t1", Name: "Read", Input: json.RawMessage(`{}`)},
}}
if !lastAssistantCalledCompress([]llm.Message{userText("q"), compressCall}) {
t.Error("a Compress call was not detected")
}
if lastAssistantCalledCompress([]llm.Message{userText("q"), other}) {
t.Error("a Read call was mistaken for a Compress call")
}
// Only the MOST RECENT assistant message counts: an older compression says
// nothing about whether this nudge was acted on.
if lastAssistantCalledCompress([]llm.Message{compressCall, other}) {
t.Error("an older Compress call must not mask the latest response")
}
}
// A successful compression clears the ladder outright.
func TestSuccessfulCompressionResetsAttempts(t *testing.T) {
sess, msgs := pressureSession(t)
sess.View(msgs)
// Two failures.
for range 2 {
_, _ = runCompress(sess, json.RawMessage(`{"content":[{"startId":"m09999","endId":"m09998","summary":"`+
strings.Repeat("s", 100)+`"}]}`), &tool.ToolContext{ToolUseID: "x"})
}
if sess.attempts != 2 {
t.Fatalf("attempts = %d, want 2", sess.attempts)
}
args, _ := json.Marshal(map[string]any{
"content": []map[string]any{{"startId": "m00001", "endId": "m00008", "summary": longSummary}},
})
res, _ := runCompress(sess, args, &tool.ToolContext{ToolUseID: "ok"})
if noa.PanelBlockCount(res.Content[0].Text) == 0 {
t.Skipf("the fixture produced no compressible block: %s", res.Content[0].Text)
}
if sess.attempts != 0 {
t.Fatalf("attempts = %d after a successful compression, want 0", sess.attempts)
}
}
// Malformed arguments count against the same ladder: from the context's point
// of view nothing was reclaimed either way.
func TestParseFailureCountsAsAttempt(t *testing.T) {
sess, msgs := pressureSession(t)
sess.View(msgs)
before := sess.attempts
res, _ := runCompress(sess, json.RawMessage(`not json`), &tool.ToolContext{ToolUseID: "x"})
if !res.IsError {
t.Fatal("malformed arguments must be reported as an error")
}
if sess.attempts != before+1 {
t.Fatalf("attempts = %d, want %d", sess.attempts, before+1)
}
}
// "No ranges provided" is neither success nor failure — a valid question with a
// valid answer must not distort the ladder.
func TestNoRangesIsNeutral(t *testing.T) {
sess, msgs := pressureSession(t)
sess.View(msgs)
before := sess.attempts
res, _ := runCompress(sess, json.RawMessage(`{"content":[]}`), &tool.ToolContext{ToolUseID: "x"})
if res.IsError {
t.Fatalf("an empty range list must not be an error: %s", res.Content[0].Text)
}
if res.Content[0].Text != noa.NoRangesMessage {
t.Fatalf("result = %q, want %q", res.Content[0].Text, noa.NoRangesMessage)
}
if sess.attempts != before {
t.Fatalf("attempts = %d, want it unchanged at %d", sess.attempts, before)
}
}
func TestEnableAppendsResidentPromptOnly(t *testing.T) {
opts := agentcore.Options{SystemPrompt: []string{"host"}}
if err := Enable(&opts, Options{ArchiveBaseDir: t.TempDir(), SessionID: "s"}); err != nil {
t.Fatalf("Enable: %v", err)
}
prompt := strings.Join(opts.AppendSystemPrompt, "\n")
for _, want := range []string{"NOA TAGS", "COMPRESSION SUMMARIES IN CONTEXT", "THE ARCHIVE"} {
if !strings.Contains(prompt, want) {
t.Errorf("resident prompt is missing %q", want)
}
}
// Everything that teaches a one-off action travels with the nudge instead;
// duplicating it here would double the cost for no benefit.
for _, unwanted := range []string{"HOW TO COMPRESS", "WHEN TO COMPRESS", "TIER 2 COMPRESSION"} {
if strings.Contains(prompt, unwanted) {
t.Errorf("resident prompt carries %q, which belongs in the nudge", unwanted)
}
}
}
+78
View File
@@ -0,0 +1,78 @@
package noaadapter
import (
"regexp"
"strconv"
"sync"
)
// overflowState remembers what a context-overflow error taught us.
//
// The provider's real window is often smaller than the configured one (a proxy
// trims it, a deployment differs from the published spec). Rather than guessing
// again next turn, the error is mined for the actual number and the mechanical
// valve is armed so the next view is built to fit.
type overflowState struct {
mu sync.Mutex
// learnedWindow is the window size parsed out of an error, 0 if unknown.
learnedWindow int
// armed makes the next view build to the emergency floor.
armed bool
}
func (o *overflowState) arm(configured int) {
o.mu.Lock()
defer o.mu.Unlock()
o.armed = true
if o.learnedWindow == 0 {
o.learnedWindow = configured
}
}
func (o *overflowState) disarm() {
o.mu.Lock()
defer o.mu.Unlock()
o.armed = false
}
// armedFloor is the token ceiling the next view must fit under, or 0 when not
// armed.
func (o *overflowState) armedFloor() int {
o.mu.Lock()
defer o.mu.Unlock()
if !o.armed || o.learnedWindow <= 0 {
return 0
}
return int(float64(o.learnedWindow) * 0.95)
}
// learn records a window size parsed from an error message.
func (o *overflowState) learn(window int) {
if window <= 0 {
return
}
o.mu.Lock()
defer o.mu.Unlock()
o.learnedWindow = window
}
// windowPatterns extract the real context window from an overflow error.
// Providers phrase this several ways; each pattern captures the limit.
var windowPatterns = []*regexp.Regexp{
regexp.MustCompile(`(?i)maximum context length is (\d+)`),
regexp.MustCompile(`(?i)context (?:window|length) (?:of|is) (\d+)`),
regexp.MustCompile(`(?i)max(?:imum)?[ _-]?tokens?[^0-9]{0,20}(\d{4,})`),
regexp.MustCompile(`(?i)limit(?:ed)? to (\d{4,}) tokens`),
}
// ParseOverflowWindow extracts a context window size from an error message.
func ParseOverflowWindow(msg string) int {
for _, re := range windowPatterns {
if m := re.FindStringSubmatch(msg); m != nil {
if n, err := strconv.Atoi(m[1]); err == nil && n > 0 {
return n
}
}
}
return 0
}
+162
View File
@@ -0,0 +1,162 @@
package noaadapter
import (
"context"
"errors"
"testing"
"github.com/Autumn-27/norma/llm"
)
// The three harness-facing methods are the whole public surface between noa and
// the agent loop, and until now only View was exercised.
// Pre must not touch the history. The built-in compaction rewrites messages
// here; noa's message identity is a content hash, so a rewrite would change
// every id and invalidate every ref the model is holding.
func TestPreLeavesTheHistoryUntouched(t *testing.T) {
sess := simSession(t, 40000)
c := &Compactor{sess: sess}
in := []llm.Message{userText("one"), userText("two")}
out := c.Pre(t.Context(), in, 12345)
if len(out) != len(in) {
t.Fatalf("Pre returned %d messages, want the %d it was given", len(out), len(in))
}
for i := range in {
if out[i].Text() != in[i].Text() {
t.Fatalf("Pre rewrote message %d: %q -> %q", i, in[i].Text(), out[i].Text())
}
}
// The provider's own count is more accurate than any estimate, so it must be
// taken when offered — resolveTokenCount prefers it over estimateCoreTokens
// whenever it is fresh and close.
sess.mu.Lock()
got := sess.providerTokens
sess.mu.Unlock()
if got != 12345 {
t.Fatalf("Pre recorded providerTokens = %d, want 12345; the pressure ladder keeps "+
"running on estimates when a measured number was available", got)
}
}
// A zero count means the provider did not report one — it must not be recorded
// as "the context is empty".
func TestPreIgnoresAnUnreportedTokenCount(t *testing.T) {
sess := simSession(t, 40000)
c := &Compactor{sess: sess}
c.Pre(t.Context(), nil, 7000)
before := sess.tokensBefore()
c.Pre(t.Context(), nil, 0)
if sess.tokensBefore() != before {
t.Fatalf("a zero token count overwrote the last known size %d with %d",
before, sess.tokensBefore())
}
}
// IsOverflow decides whether Reactive runs at all. Getting it wrong in one
// direction wastes a recovery attempt; in the other it turns a recoverable
// prompt-too-long into a failed run.
func TestIsOverflowRecognisesProviderPhrasings(t *testing.T) {
c := &Compactor{sess: simSession(t, 40000)}
overflow := []string{
"This model's maximum context length is 200000 tokens, however you requested 214000",
"prompt is too long: 215000 tokens > 200000 maximum",
"error: context_length_exceeded",
"anthropic: status 413",
}
for _, msg := range overflow {
if !c.IsOverflow(errors.New(msg)) {
t.Errorf("IsOverflow(%q) = false; the run fails instead of recovering", msg)
}
}
other := []string{"rate limit exceeded", "connection reset by peer", "invalid api key"}
for _, msg := range other {
if c.IsOverflow(errors.New(msg)) {
t.Errorf("IsOverflow(%q) = true; a recovery attempt is spent on an unrelated failure", msg)
}
}
if c.IsOverflow(nil) {
t.Error("IsOverflow(nil) = true")
}
}
// overflowState documents itself as mining the error for the provider's real
// window — "rather than guessing again next turn, the error is mined for the
// actual number and the mechanical valve is armed so the next view is built to
// fit."
//
// Nothing does that. ParseOverflowWindow and overflowState.learn have no callers
// anywhere in the tree: harness.Compactor.Reactive receives only the message
// array, and IsOverflow — the one method that does see the error — throws it
// away. So arm() always falls back to the CONFIGURED limit, which is exactly the
// number the provider just rejected.
//
// Either wire learning in (IsOverflow is the natural place: it already has the
// error) or delete the mechanism and the comment that promises it. Leaving it is
// the worst option, because the comment describes behaviour the code does not
// have.
func TestOverflowLearningIsWiredIn(t *testing.T) {
c := &Compactor{sess: simSession(t, 200000)}
// The provider says its real window is 128000, not the configured 200000.
err := errors.New("This model's maximum context length is 128000 tokens, however you requested 214000")
if n := ParseOverflowWindow(err.Error()); n != 128000 {
t.Fatalf("ParseOverflowWindow = %d, want 128000 — the parser itself is broken", n)
}
// The loop's actual sequence: detect, then recover.
c.IsOverflow(err)
c.Reactive(t.Context(), nil)
floor := c.overflow.armedFloor()
if floor == 0 {
t.Skip("Reactive disarmed because it could not shrink an empty view")
}
want := int(float64(128000) * 0.95)
if floor != want {
t.Fatalf("the armed floor is %d (95%% of the CONFIGURED %d), not %d (95%% of the %d "+
"the provider reported). ParseOverflowWindow and overflowState.learn have no "+
"callers, so the learned window is never learned and the next view is rebuilt to "+
"a limit the provider has already rejected.",
floor, c.sess.Config().ModelContextLimit, want, 128000)
}
}
// The parser itself, over the phrasings it claims to cover.
func TestParseOverflowWindowCoversItsPatterns(t *testing.T) {
cases := map[string]int{
"This model's maximum context length is 200000 tokens": 200000,
"context window of 131072 exceeded": 131072,
"max_tokens must be less than 8192": 8192,
"requests are limited to 32000 tokens": 32000,
"rate limit exceeded": 0,
"maximum context length is zero": 0,
}
for msg, want := range cases {
if got := ParseOverflowWindow(msg); got != want {
t.Errorf("ParseOverflowWindow(%q) = %d, want %d", msg, got, want)
}
}
}
// Reactive must never claim success it cannot deliver: returning true promises
// the harness a smaller request, and if the request is not smaller the retry
// hits the same 413 and the loop spins.
func TestReactiveRefusesWhenItCannotShrink(t *testing.T) {
sess := simSession(t, 40000)
c := &Compactor{sess: sess}
// Nothing sent yet and nothing to cut.
msgs := []llm.Message{userText("short")}
if _, ok := c.Reactive(context.Background(), msgs); ok {
if est := estimateMessages(c.View(context.Background(), msgs)); est > 0 {
t.Logf("Reactive accepted a %d-token view under an armed floor", est)
}
}
// Whatever it decided, it must leave the emergency floor consistent with that
// decision: a refusal that left the valve armed would shrink every later view
// for no reason.
if !c.overflow.armed && c.overflow.armedFloor() != 0 {
t.Fatal("disarmed but still reporting a floor")
}
}
+309
View File
@@ -0,0 +1,309 @@
package noaadapter
import (
"encoding/json"
"strings"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/noa"
)
// origin records where a projected core came from, so reassembly can put it
// back into the right host message and block.
type origin struct {
msgIdx int
blkIdx int
}
// Sidecar carries what the flat representation cannot: provider-internal data
// that must survive the round trip untouched.
type Sidecar struct {
// Signatures holds each thinking block's provider signature, keyed by core
// id. Anthropic validates it on replay, so it must come back byte-identical.
Signatures map[string]string
// Origins maps a core id back to its source position.
Origins map[string]origin
// ToolResultIsError preserves the error flag of a tool result.
ToolResultIsError map[string]bool
}
func newSidecar() *Sidecar {
return &Sidecar{
Signatures: map[string]string{},
Origins: map[string]origin{},
ToolResultIsError: map[string]bool{},
}
}
// Project flattens the host's history into noa's representation.
//
// Boundary inheritance: a session that previously ran the built-in compaction
// carries a compact_boundary, and everything before it has already been
// summarised into the message that follows. noa's View does not go through
// llm.MessagesForAPI, so without this slice those pre-boundary originals would
// come back — alongside the summary that replaced them, doubling the context.
func Project(msgs []llm.Message) ([]noa.CoreMessage, *Sidecar) {
if i := llm.LastBoundaryIndex(msgs); i >= 0 {
msgs = msgs[i+1:]
}
sc := newSidecar()
cc := NewClusterCounter()
var out []noa.CoreMessage
// Tool results carry no tool name; recover it from the call they answer.
toolNameByCallID := map[string]string{}
for _, m := range msgs {
for _, b := range m.Content {
if b.Type == llm.BlockToolUse {
toolNameByCallID[b.ID] = b.Name
}
}
}
for mi, m := range msgs {
for bi, b := range m.Content {
core, ok := projectBlock(m.Role, b, toolNameByCallID)
if !ok {
continue
}
core.ID = cc.Next(DeriveMessageID(core.Role, core.ContentType, core.Text, core.ToolCallID, core.ToolName))
sc.Origins[core.ID] = origin{msgIdx: mi, blkIdx: bi}
if b.Type == llm.BlockThinking {
sc.Signatures[core.ID] = b.Signature
}
if b.Type == llm.BlockToolResult && b.IsError {
sc.ToolResultIsError[core.ID] = true
}
out = append(out, core)
}
}
return out, sc
}
// projectBlock maps one content block; ok=false means the block has no
// representation in the flat model.
func projectBlock(role llm.Role, b llm.ContentBlock, toolNames map[string]string) (noa.CoreMessage, bool) {
switch b.Type {
case llm.BlockText:
r := noa.RoleAssistant
text := b.Text
if role == llm.RoleUser {
r = noa.RoleUser
// Only user text carries a tag, and it must not reach the hash.
text = StripRefTag(text)
}
return noa.CoreMessage{Role: r, ContentType: noa.CTText, Text: text}, true
case llm.BlockThinking:
return noa.CoreMessage{Role: noa.RoleAssistant, ContentType: noa.CTReasoning, Text: b.Thinking}, true
case llm.BlockToolUse:
return noa.CoreMessage{
Role: noa.RoleAssistant, ContentType: noa.CTToolCall,
ToolName: b.Name, ToolCallID: b.ID, Text: string(b.Input),
}, true
case llm.BlockToolResult:
return noa.CoreMessage{
Role: noa.RoleTool, ContentType: noa.CTToolResult,
ToolCallID: b.ToolUseID, ToolName: toolNames[b.ToolUseID],
Text: StripRefTag(flattenToolResult(b.Content)),
}, true
default:
// compact_boundary and anything else the host may add: not content.
return noa.CoreMessage{}, false
}
}
// flattenToolResult joins a tool result's nested blocks into one body.
func flattenToolResult(blocks []llm.ContentBlock) string {
var parts []string
for _, b := range blocks {
if b.Type == llm.BlockText && b.Text != "" {
parts = append(parts, b.Text)
}
}
return strings.Join(parts, "\n")
}
// ReassembleOptions controls how cores are rebuilt into host messages.
type ReassembleOptions struct {
// State supplies the ref map and token snapshot for tagging.
State *noa.CompressionState
// Tag enables ref tags. Materialize turns them off: they point at an
// addressing scheme that is no longer running.
Tag bool
}
// Reassemble rebuilds host messages from a projected, pruned view.
//
// The output is for one request only. It is never written back to the host's
// history — message identity is a content hash, and writing a tagged or
// truncated body back would change every id derived from it.
func Reassemble(cores []noa.CoreMessage, originals []llm.Message, sc *Sidecar, opts ReassembleOptions) []llm.Message {
// Boundary inheritance must match Project's, or origins would be offset.
if i := llm.LastBoundaryIndex(originals); i >= 0 {
originals = originals[i+1:]
}
var out []llm.Message
i := 0
for i < len(cores) {
c := cores[i]
// Synthetic messages (summaries, the nudge) have no original to rebuild
// from — they become standalone user messages.
if isSynthetic(c) {
out = append(out, llm.Message{
Role: llm.RoleUser,
Content: []llm.ContentBlock{llm.TextBlock(c.Text)},
})
i++
continue
}
o, known := sc.Origins[c.ID]
if !known || o.msgIdx >= len(originals) {
// An unrecognised core still has to reach the model; drop it into a
// plain message rather than losing it.
out = append(out, llm.Message{
Role: roleToLLM(c.Role),
Content: []llm.ContentBlock{llm.TextBlock(c.Text)},
})
i++
continue
}
// Gather the run of cores that came from this same host message, so its
// blocks are rebuilt together and in order.
group := []noa.CoreMessage{c}
j := i + 1
for j < len(cores) && !isSynthetic(cores[j]) {
oj, ok := sc.Origins[cores[j].ID]
if !ok || oj.msgIdx != o.msgIdx {
break
}
group = append(group, cores[j])
j++
}
i = j
if rebuilt, ok := rebuildMessage(originals[o.msgIdx], group, sc, opts); ok {
out = append(out, rebuilt)
}
}
// A range that ended mid-exchange can leave a tool block without its
// counterpart; strict providers reject that outright.
out = llm.PairToolBlocks(out)
return dropEmpty(out)
}
// rebuildMessage reconstructs one host message from the cores that survived.
func rebuildMessage(orig llm.Message, group []noa.CoreMessage, sc *Sidecar, opts ReassembleOptions) (llm.Message, bool) {
var content []llm.ContentBlock
for _, c := range group {
o, ok := sc.Origins[c.ID]
if !ok || o.blkIdx >= len(orig.Content) {
continue
}
b := orig.Content[o.blkIdx]
content = append(content, rebuildBlock(b, c, sc, opts))
}
if len(content) == 0 {
return llm.Message{}, false
}
return llm.Message{Role: orig.Role, Content: content}, true
}
// rebuildBlock restores one content block, writing back any rewrite the
// pipeline performed and re-attaching the ref tag.
func rebuildBlock(b llm.ContentBlock, c noa.CoreMessage, sc *Sidecar, opts ReassembleOptions) llm.ContentBlock {
switch b.Type {
case llm.BlockText:
body := c.Text
if opts.Tag && c.Role == noa.RoleUser {
body = tagged(body, c, opts)
}
b.Text = body
case llm.BlockThinking:
b.Thinking = c.Text
// The signature is restored verbatim. Rewriting thinking text while
// keeping the old signature makes Anthropic reject the request, so the
// two must move together or not at all.
b.Signature = sc.Signatures[c.ID]
case llm.BlockToolUse:
// Only replace the arguments if the rewrite is still valid JSON.
// Writing a malformed payload back would break the call itself.
if c.Text != string(b.Input) && json.Valid([]byte(c.Text)) {
b.Input = json.RawMessage(c.Text)
}
case llm.BlockToolResult:
body := c.Text
if opts.Tag {
body = tagged(body, c, opts)
}
b.Content = []llm.ContentBlock{llm.TextBlock(body)}
b.IsError = sc.ToolResultIsError[c.ID]
}
return b
}
// tagged appends the ref tag when the message has an addressable ref.
//
// Assistant messages are never tagged: the model copies its own previous output
// far more readily than it copies host chrome, and an echoed tag shows up as
// XML debris in the terminal. It costs nothing — ranges are inclusive spans, so
// anything between two tagged endpoints is included anyway.
func tagged(body string, c noa.CoreMessage, opts ReassembleOptions) string {
if opts.State == nil {
return body
}
ref, ok := opts.State.MessageRefs.ByRaw[c.ID]
if !ok || ref == noa.BlockedRef {
return body
}
tokens := tokenForRef(opts.State.TokenSnapshot, ref, body)
return AppendRefTag(body, RefTag(ref, c, tokens))
}
func isSynthetic(c noa.CoreMessage) bool {
return strings.HasPrefix(c.ID, noa.SummaryIDPrefix) || c.ID == noa.NudgeMessageID
}
func roleToLLM(r noa.Role) llm.Role {
if r == noa.RoleAssistant {
return llm.RoleAssistant
}
return llm.RoleUser
}
// dropEmpty removes messages with no content, and assistant messages with
// neither text nor a tool call — OpenAI-compatible providers reject those.
func dropEmpty(msgs []llm.Message) []llm.Message {
out := make([]llm.Message, 0, len(msgs))
for _, m := range msgs {
if len(m.Content) == 0 {
continue
}
if m.Role == llm.RoleAssistant && m.Text() == "" && len(m.ToolUses()) == 0 {
hasThinking := false
for _, b := range m.Content {
if b.Type == llm.BlockThinking {
hasThinking = true
break
}
}
if !hasThinking {
continue
}
}
out = append(out, m)
}
return out
}
+342
View File
@@ -0,0 +1,342 @@
package noaadapter
import (
"encoding/json"
"strings"
"testing"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/noa"
)
func userText(s string) llm.Message {
return llm.Message{Role: llm.RoleUser, Content: []llm.ContentBlock{llm.TextBlock(s)}}
}
func assistantWith(blocks ...llm.ContentBlock) llm.Message {
return llm.Message{Role: llm.RoleAssistant, Content: blocks}
}
func toolUse(id, name, input string) llm.ContentBlock {
return llm.ContentBlock{Type: llm.BlockToolUse, ID: id, Name: name, Input: json.RawMessage(input)}
}
func toolResult(useID, text string) llm.Message {
return llm.Message{Role: llm.RoleUser, Content: []llm.ContentBlock{{
Type: llm.BlockToolResult, ToolUseID: useID,
Content: []llm.ContentBlock{llm.TextBlock(text)},
}}}
}
func TestProjectFlattensBlocks(t *testing.T) {
msgs := []llm.Message{
userText("the task"),
assistantWith(
llm.ContentBlock{Type: llm.BlockThinking, Thinking: "let me look", Signature: "sig-abc"},
llm.TextBlock("I'll read it"),
toolUse("t1", "Read", `{"file_path":"/x.go"}`),
),
toolResult("t1", "package main"),
}
cores, sc := Project(msgs)
if len(cores) != 5 {
t.Fatalf("got %d cores, want 5 (user, thinking, text, tool_use, tool_result)", len(cores))
}
want := []struct {
role noa.Role
ct noa.ContentType
}{
{noa.RoleUser, noa.CTText},
{noa.RoleAssistant, noa.CTReasoning},
{noa.RoleAssistant, noa.CTText},
{noa.RoleAssistant, noa.CTToolCall},
{noa.RoleTool, noa.CTToolResult},
}
for i, w := range want {
if cores[i].Role != w.role || cores[i].ContentType != w.ct {
t.Errorf("core %d = %s/%s, want %s/%s", i, cores[i].Role, cores[i].ContentType, w.role, w.ct)
}
}
if sc.Signatures[cores[1].ID] != "sig-abc" {
t.Fatalf("thinking signature = %q, want it captured in the sidecar", sc.Signatures[cores[1].ID])
}
// A tool result carries no name of its own; it must be recovered from the call.
if cores[4].ToolName != "Read" {
t.Fatalf("tool result name = %q, want it resolved from the tool_use", cores[4].ToolName)
}
}
// A message's identity must not depend on the tag, or the id would change every
// turn the tag is re-rendered.
func TestProjectStripsRefTagBeforeHashing(t *testing.T) {
plain, _ := Project([]llm.Message{userText("hello world")})
tagged, _ := Project([]llm.Message{userText("hello world\n<noa-ref id=\"m00001\" tokens=\"3\"/>")})
if plain[0].ID != tagged[0].ID {
t.Fatalf("id changed with the tag present: %q vs %q", plain[0].ID, tagged[0].ID)
}
if strings.Contains(tagged[0].Text, "noa-ref") {
t.Fatalf("projected text still carries the tag: %q", tagged[0].Text)
}
}
func TestProjectDisambiguatesIdenticalMessages(t *testing.T) {
cores, _ := Project([]llm.Message{userText("git status"), userText("git status")})
if cores[0].ID == cores[1].ID {
t.Fatal("two identical messages collapsed onto one id")
}
if strings.HasSuffix(cores[0].ID, "_1") {
t.Fatalf("first occurrence = %q, want the bare hash so an unchanged history projects unchanged", cores[0].ID)
}
if !strings.HasSuffix(cores[1].ID, "_1") {
t.Fatalf("second occurrence = %q, want an occurrence suffix", cores[1].ID)
}
}
// Everything before a compaction boundary was already summarised into the
// message that follows it; re-projecting it would duplicate the content.
func TestProjectInheritsCompactionBoundary(t *testing.T) {
msgs := []llm.Message{
userText("ancient history"),
llm.BoundaryMessage(llm.BoundaryMeta{Trigger: "auto"}),
userText("the summary of it"),
userText("recent"),
}
cores, _ := Project(msgs)
if len(cores) != 2 {
t.Fatalf("got %d cores, want 2 — pre-boundary content must not be resurrected", len(cores))
}
if cores[0].Text != "the summary of it" {
t.Fatalf("first core = %q, want projection to start after the boundary", cores[0].Text)
}
}
func TestProjectSkipsBoundaryMarker(t *testing.T) {
cores, _ := Project([]llm.Message{llm.BoundaryMessage(llm.BoundaryMeta{}), userText("after")})
if len(cores) != 1 {
t.Fatalf("got %d cores, want only the real message", len(cores))
}
}
func TestReassembleRoundTripsUnchanged(t *testing.T) {
msgs := []llm.Message{
userText("the task"),
assistantWith(
llm.ContentBlock{Type: llm.BlockThinking, Thinking: "hmm", Signature: "sig-1"},
toolUse("t1", "Read", `{"file_path":"/x.go"}`),
),
toolResult("t1", "contents"),
}
cores, sc := Project(msgs)
out := Reassemble(cores, msgs, sc, ReassembleOptions{})
if len(out) != len(msgs) {
t.Fatalf("round trip produced %d messages, want %d", len(out), len(msgs))
}
if out[0].Text() != "the task" {
t.Fatalf("user text = %q", out[0].Text())
}
if out[1].Content[0].Signature != "sig-1" {
t.Fatalf("thinking signature = %q, want it restored verbatim — Anthropic validates it on replay",
out[1].Content[0].Signature)
}
if string(out[1].Content[1].Input) != `{"file_path":"/x.go"}` {
t.Fatalf("tool_use input = %q, want it unchanged", out[1].Content[1].Input)
}
if out[2].Content[0].Content[0].Text != "contents" {
t.Fatalf("tool result = %q", out[2].Content[0].Content[0].Text)
}
}
func TestReassembleDropsPrunedBlocks(t *testing.T) {
msgs := []llm.Message{
userText("keep"),
userText("drop"),
userText("keep too"),
}
cores, sc := Project(msgs)
kept := []noa.CoreMessage{cores[0], cores[2]}
out := Reassemble(kept, msgs, sc, ReassembleOptions{})
if len(out) != 2 {
t.Fatalf("got %d messages, want the pruned one dropped", len(out))
}
if out[0].Text() != "keep" || out[1].Text() != "keep too" {
t.Fatalf("out = %q, %q", out[0].Text(), out[1].Text())
}
}
// A partially pruned host message keeps only its surviving blocks.
func TestReassemblePartialMessageSurvival(t *testing.T) {
msgs := []llm.Message{
assistantWith(llm.TextBlock("explain"), toolUse("t1", "Read", `{}`)),
toolResult("t1", "result"),
}
cores, sc := Project(msgs)
// Drop the text block, keep the tool call and its result.
out := Reassemble([]noa.CoreMessage{cores[1], cores[2]}, msgs, sc, ReassembleOptions{})
if len(out) != 2 {
t.Fatalf("got %d messages, want 2", len(out))
}
if len(out[0].Content) != 1 || out[0].Content[0].Type != llm.BlockToolUse {
t.Fatalf("rebuilt assistant = %+v, want only the tool_use block", out[0].Content)
}
}
func TestReassembleSyntheticBecomesUserMessage(t *testing.T) {
msgs := []llm.Message{userText("real")}
cores, sc := Project(msgs)
withSummary := []noa.CoreMessage{
{ID: noa.SummaryMessageID("b1"), Role: noa.RoleUser, ContentType: noa.CTText,
Text: noa.SummaryHeader + "\nsummary body"},
cores[0],
}
out := Reassemble(withSummary, msgs, sc, ReassembleOptions{})
if len(out) != 2 {
t.Fatalf("got %d messages, want the summary plus the real one", len(out))
}
if out[0].Role != llm.RoleUser || !strings.HasPrefix(out[0].Text(), noa.SummaryHeader) {
t.Fatalf("summary message = %+v, want a user message carrying the header", out[0])
}
}
// Rewritten tool arguments are only written back when they are still valid
// JSON; a malformed payload would break the call.
func TestReassembleRejectsInvalidToolInput(t *testing.T) {
msgs := []llm.Message{assistantWith(toolUse("t1", "Read", `{"file_path":"/x.go"}`)), toolResult("t1", "ok")}
cores, sc := Project(msgs)
cores[0].Text = `{"file_path": truncated...`
out := Reassemble(cores, msgs, sc, ReassembleOptions{})
if string(out[0].Content[0].Input) != `{"file_path":"/x.go"}` {
t.Fatalf("input = %q, want the original kept when the rewrite is not valid JSON", out[0].Content[0].Input)
}
}
func TestReassembleRepairsUnpairedToolBlocks(t *testing.T) {
msgs := []llm.Message{
assistantWith(toolUse("t1", "Read", `{}`)),
toolResult("t1", "result"),
}
cores, sc := Project(msgs)
// Keep only the result — its call is gone.
out := Reassemble([]noa.CoreMessage{cores[1]}, msgs, sc, ReassembleOptions{})
for _, m := range out {
for _, b := range m.Content {
if b.Type == llm.BlockToolResult {
t.Fatalf("an unpaired tool_result survived: %+v", b)
}
}
}
}
func TestReassembleTagsUserAndToolResultOnly(t *testing.T) {
msgs := []llm.Message{
userText("ask"),
assistantWith(llm.TextBlock("reply"), toolUse("t1", "Read", `{}`)),
toolResult("t1", "output"),
}
cores, sc := Project(msgs)
st := noa.CreateInitialState("s", "/a")
pt := noa.ProcessTurn(noa.ProcessTurnInput{Messages: cores, State: st, Config: noa.DefaultConfig(200000)})
out := Reassemble(pt.Messages, msgs, sc, ReassembleOptions{State: &pt.State, Tag: true})
if !strings.Contains(out[0].Text(), "<noa-ref id=") {
t.Fatalf("user message must carry a tag: %q", out[0].Text())
}
if strings.Contains(out[1].Text(), "noa-ref") {
t.Fatalf("assistant message must NOT be tagged — the model echoes its own output: %q", out[1].Text())
}
body := out[2].Content[0].Content[0].Text
if !strings.Contains(body, "<noa-ref id=") || !strings.Contains(body, `src="Read"`) {
t.Fatalf("tool result tag = %q, want it tagged with its source tool", body)
}
// src exists only on tool output; its presence is the signal.
if strings.Contains(out[0].Text(), "src=") {
t.Fatalf("user text tag must omit src: %q", out[0].Text())
}
}
// The tag number is frozen at first render: a moving number is a moving byte,
// and that invalidates the prefix cache from there on.
func TestReassembleTagTokensAreFrozen(t *testing.T) {
msgs := []llm.Message{userText(strings.Repeat("x", 400))}
cores, sc := Project(msgs)
st := noa.CreateInitialState("s", "/a")
pt := noa.ProcessTurn(noa.ProcessTurnInput{Messages: cores, State: st, Config: noa.DefaultConfig(200000)})
first := Reassemble(pt.Messages, msgs, sc, ReassembleOptions{State: &pt.State, Tag: true})
firstTag := MessageRef(first[0])
// Simulate a later truncation of the same message.
shortened := append([]noa.CoreMessage(nil), pt.Messages...)
shortened[0].Text = "tiny"
second := Reassemble(shortened, msgs, sc, ReassembleOptions{State: &pt.State, Tag: true})
if MessageRef(second[0]) != firstTag {
t.Fatalf("ref changed: %q -> %q", firstTag, MessageRef(second[0]))
}
if !strings.Contains(second[0].Text(), `tokens="100"`) {
t.Fatalf("tag = %q, want the frozen token count (100) even though the body shrank", second[0].Text())
}
}
func TestReassembleWithoutTagging(t *testing.T) {
msgs := []llm.Message{userText("ask")}
cores, sc := Project(msgs)
st := noa.CreateInitialState("s", "/a")
pt := noa.ProcessTurn(noa.ProcessTurnInput{Messages: cores, State: st, Config: noa.DefaultConfig(200000)})
out := Reassemble(pt.Messages, msgs, sc, ReassembleOptions{State: &pt.State, Tag: false})
if strings.Contains(out[0].Text(), "noa-ref") {
t.Fatalf("Tag=false must produce no tags: %q", out[0].Text())
}
}
func TestStripRefTag(t *testing.T) {
cases := map[string]string{
"body\n<noa-ref id=\"m00001\" tokens=\"5\"/>": "body",
// Only the trailing form is ever produced, so only it is stripped; a
// leading one is left alone rather than risk eating user content that
// opens with tag-shaped text.
"<noa-ref id=\"m00001\" tokens=\"5\"/>\nbody": "<noa-ref id=\"m00001\" tokens=\"5\"/>\nbody",
"body with no tag": "body with no tag",
"body\n<noa-ref id=\"m00042\" tokens=\"1.2K\" src=\"Read\"/>": "body",
}
for in, want := range cases {
if got := StripRefTag(in); got != want {
t.Errorf("StripRefTag(%q) = %q, want %q", in, got, want)
}
}
}
// The real contract: whatever Reassemble appends, Project removes — exactly.
func TestTagAppendStripRoundTrip(t *testing.T) {
for _, body := range []string{
"plain body",
"body\nwith newlines\n",
"中文正文 🔐",
"",
"body that mentions <noa-ref> in passing",
} {
tagged := AppendRefTag(body, RefTag("m00042", noa.CoreMessage{ContentType: noa.CTText}, 120))
if got := StripRefTag(tagged); got != body {
t.Errorf("round trip lost content:\n body: %q\n tagged: %q\n back: %q", body, tagged, got)
}
}
}
// The regexes anchor on the id format as well as the element name, so a
// <noa-ref> appearing inside a file the agent read is left alone.
func TestStripRefTagLeavesForeignTagsAlone(t *testing.T) {
in := "config:\n<noa-ref id=\"user-service\"/>"
if got := StripRefTag(in); got != in {
t.Fatalf("StripRefTag mangled a foreign tag: %q", got)
}
}
// The archive tag must not be mistaken for a ref tag.
func TestStripRefTagLeavesArchiveTagAlone(t *testing.T) {
in := noa.SummaryHeader + "\nsummary\n\n" +
noa.ArchiveTag(noa.CompressionBlock{BlockID: "b1", Tier: 1, StartRef: "m00001", EndRef: "m00009", ArchivePath: "/p.md"})
if got := StripRefTag(in); got != in {
t.Fatalf("StripRefTag stripped the archive tag: %q", got)
}
}
+374
View File
@@ -0,0 +1,374 @@
package noaadapter
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/noa"
)
// buildWorkingSession runs a cooperative session far enough to have real blocks,
// real archives and a real ref map, and returns it with its history.
func buildWorkingSession(t *testing.T, dir string, turns int) (*Session, []llm.Message) {
t.Helper()
opts := baseOptions()
cfg := noa.DefaultConfig(40000)
sess, err := EnableWithSession(&opts, Options{
ArchiveBaseDir: dir, SessionID: "resume", Config: &cfg,
})
if err != nil {
t.Fatalf("EnableWithSession: %v", err)
}
a := newSimAgent(t, sess, 1)
for range turns {
a.work(4000)
a.observe()
}
if len(noa.ActiveBlocks(sess.State())) == 0 {
t.Fatalf("%d turns produced no active block; the fixture cannot test recovery", turns)
}
return sess, a.history
}
// renderView flattens a view to comparable text.
func renderView(msgs []llm.Message) string {
var b strings.Builder
for _, m := range msgs {
fmt.Fprintf(&b, "[%s]", m.Role)
for _, c := range m.Content {
fmt.Fprintf(&b, "<%s|%s|%s|%s|%s>", c.Type, c.ID, c.ToolUseID, c.Text, c.Input)
for _, inner := range c.Content {
fmt.Fprintf(&b, "(%s)", inner.Text)
}
}
b.WriteString("\n")
}
return b.String()
}
// The everyday resume: the process restarts, a new Session is built over the
// same archive directory, and the conversation continues. The model must see
// exactly what it saw before — different refs would invalidate every id it is
// holding, and lost blocks would resurrect content that was already summarised.
func TestResumeFromDiskReproducesTheSameView(t *testing.T) {
dir := t.TempDir()
sess, history := buildWorkingSession(t, dir, 45)
want := renderView(sess.View(history))
wantBlocks := len(noa.ActiveBlocks(sess.State()))
opts := baseOptions()
cfg := noa.DefaultConfig(40000)
resumed, err := EnableWithSession(&opts, Options{
ArchiveBaseDir: dir, SessionID: "resume", Config: &cfg,
})
if err != nil {
t.Fatalf("resume: %v", err)
}
if got := len(noa.ActiveBlocks(resumed.State())); got != wantBlocks {
t.Fatalf("resumed with %d active blocks, want %d", got, wantBlocks)
}
if got := renderView(resumed.View(history)); got != want {
t.Fatalf("the resumed view differs from the original.\nwant %d bytes\ngot %d bytes\n"+
"first divergence at byte %d", len(want), len(got), firstDiff(want, got))
}
}
// The state file is the only thing that is not derivable, so losing it is the
// interesting failure. RebuildFromHistory replays the recorded Compress calls;
// because the summaries were arguments the model wrote, the replay returns the
// same bytes rather than an approximation.
func TestRebuildAfterStateLossReproducesTheSameView(t *testing.T) {
dir := t.TempDir()
sess, history := buildWorkingSession(t, dir, 45)
want := renderView(sess.View(history))
wantBlocks := noa.ActiveBlocks(sess.State())
// Lose the state file the way an import or a botched copy would.
var removed int
err := filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(p, ".json") {
return err
}
if err := os.Remove(p); err != nil {
return err
}
removed++
return nil
})
if err != nil {
t.Fatalf("walk: %v", err)
}
if removed == 0 {
t.Fatal("no state file was found to remove; the test is not exercising recovery")
}
cfg := noa.DefaultConfig(40000)
rebuilt, err := RebuildFromHistory(history, Options{
ArchiveBaseDir: dir, SessionID: "resume", Config: &cfg,
})
if err != nil {
t.Fatalf("RebuildFromHistory: %v", err)
}
gotBlocks := noa.ActiveBlocks(rebuilt.State())
if len(gotBlocks) != len(wantBlocks) {
t.Fatalf("rebuilt %d active blocks from the log, want %d", len(gotBlocks), len(wantBlocks))
}
for i := range gotBlocks {
if gotBlocks[i].Summary != wantBlocks[i].Summary {
t.Fatalf("block %d summary changed on replay — the whole point of replaying the "+
"call arguments is that it cannot:\nwant %q\ngot %q",
i, head(wantBlocks[i].Summary, 120), head(gotBlocks[i].Summary, 120))
}
if gotBlocks[i].Tier != wantBlocks[i].Tier {
t.Fatalf("block %d came back at tier %d, was tier %d", i, gotBlocks[i].Tier, wantBlocks[i].Tier)
}
}
if got := renderView(rebuilt.View(history)); got != want {
t.Fatalf("the rebuilt view differs from the original at byte %d", firstDiff(want, got))
}
}
// Materialize is the "switch noa off and keep going" path. It must leave a
// history the provider accepts and small enough to be worth doing, and it must
// not mention a ref scheme that is no longer running.
func TestMaterializeLeavesAUsableHistory(t *testing.T) {
dir := t.TempDir()
sess, history := buildWorkingSession(t, dir, 45)
cfg := noa.DefaultConfig(40000)
out, err := Materialize(history, Options{ArchiveBaseDir: dir, SessionID: "resume", Config: &cfg})
if err != nil {
t.Fatalf("Materialize: %v", err)
}
assertValidRequest(t, out, 0)
raw := estimateMessages(history)
got := estimateMessages(out)
if got >= raw {
t.Fatalf("materialized history is %d tokens against the raw %d; nothing was applied", got, raw)
}
for _, m := range out {
for _, c := range m.Content {
if strings.Contains(c.Text, "<noa-ref") {
t.Fatalf("a ref tag survived into the materialized history: %s", head(c.Text, 160))
}
}
}
// The archives the summaries point at must still be readable — that is the
// promise that makes switching noa off safe.
for _, b := range noa.ActiveBlocks(sess.State()) {
if _, err := os.ReadFile(b.ArchivePath); err != nil {
t.Fatalf("archive for %s unreadable after materialize: %v", b.BlockID, err)
}
}
t.Logf("materialized %d tokens down from %d", got, raw)
}
// The prefix cache is why the token count in a ref tag is frozen. If the bytes
// of an already-sent message can change between turns, the cache is invalidated
// from that point on and the saving is lost.
func TestViewPrefixIsStableAcrossTurns(t *testing.T) {
sess := simSession(t, 40000)
a := newSimAgent(t, sess, 1)
prev := ""
prevLen := 0
for turn := range 40 {
a.work(4000)
a.observe()
cur := renderView(sess.View(a.history))
// A compression legitimately rewrites the prefix: that is the whole point.
// What must not happen is the prefix changing on a turn where it did not.
blocksBefore := len(sess.State().Blocks)
_ = blocksBefore
if prev != "" && len(cur) >= prevLen && strings.HasPrefix(cur, prev) {
prev, prevLen = cur, len(cur)
continue
}
if prev != "" {
d := firstDiff(prev, cur)
// Everything before the first divergence was re-sent byte-identically.
// Report how much was thrown away so a regression shows up as a number.
t.Logf("turn %d: prefix held for %d of %d bytes (%.0f%%)",
turn, d, prevLen, float64(d)*100/float64(max(prevLen, 1)))
if d == 0 {
t.Fatalf("turn %d: the view changed from its very first byte; nothing of the "+
"prefix cache survives", turn)
}
}
prev, prevLen = cur, len(cur)
}
}
// Two goroutines calling View while a compression runs is the ordinary shape of
// a streaming turn. Run with -race, this is the test that catches a missing
// lock.
func TestConcurrentViewAndCompressAreSafe(t *testing.T) {
sess := simSession(t, 40000)
a := newSimAgent(t, sess, 1000000)
for range 25 {
a.work(4000)
a.observe()
}
var wg sync.WaitGroup
for i := range 4 {
wg.Add(1)
go func() {
defer wg.Done()
for range 20 {
_ = sess.View(a.history)
}
}()
wg.Add(1)
go func() {
defer wg.Done()
args, _ := json.Marshal(map[string]any{"content": []map[string]any{{
"startId": noa.IndexToRef(2), "endId": noa.IndexToRef(13),
"summary": a.summary(fmt.Sprintf("racer %d", i)),
}}})
if _, err := runCompress(sess, args, nil); err != nil {
t.Errorf("concurrent Compress: %v", err)
}
}()
}
wg.Wait()
// Whatever interleaving happened, the ledger must still be coherent.
checkInvariants(t, sess, a.history, "after concurrent access")
}
// An archive is only useful if the original text is actually in it. Checking the
// front matter proves the file was written; this checks it was written with the
// content the summary replaced.
func TestTier1ArchivesContainTheOriginalText(t *testing.T) {
sess := simSession(t, 40000)
a := newSimAgent(t, sess, 1)
for range 45 {
a.work(4000)
a.observe()
}
// Every original body, by ref.
cores, _ := Project(a.history)
byID := map[string]noa.CoreMessage{}
for _, c := range cores {
byID[c.ID] = c
}
checked := 0
for _, b := range noa.ActiveBlocks(sess.State()) {
if b.Tier != 1 {
continue
}
raw, err := os.ReadFile(b.ArchivePath)
if err != nil {
t.Fatalf("block %s: %v", b.BlockID, err)
}
body := string(raw)
for _, id := range b.DirectMessageIDs {
m, ok := byID[id]
if !ok || len(m.Text) < 200 {
continue
}
// A distinctive slice from the middle, past any header the archive adds.
probe := m.Text[100:200]
if !strings.Contains(body, probe) {
t.Fatalf("block %s (%s): the archive does not contain the original body of "+
"message %s. A summary that points at an archive missing its own content "+
"is a silent loss.\nprobe: %q", b.BlockID, b.ArchivePath, id, probe)
}
checked++
}
}
if checked == 0 {
t.Fatal("no tier-1 message body was checked; the fixture is not exercising archiving")
}
t.Logf("verified %d original message bodies are present in their archives", checked)
}
// Following the tier chain from a top-tier block must reach the raw originals.
// If a link is broken, a summary points at a file that points nowhere, and the
// content is unreachable even though it is still on disk.
func TestArchiveChainReachesRawContentFromEveryTier(t *testing.T) {
// 128K: the smallest window where consolidation actually fires, so the chain
// has more than one link to walk. See TestTierTwoIsUnreachableOnSmallWindows.
sess := simSession(t, 128_000)
a := newSimAgent(t, sess, 1)
for range 182 {
a.work(4000)
a.observe()
}
st := sess.State()
byID := map[string]noa.CompressionBlock{}
for _, b := range st.Blocks {
byID[b.BlockID] = b
}
highest := 0
for _, b := range noa.ActiveBlocks(st) {
highest = max(highest, int(b.Tier))
}
if highest < 2 {
t.Skip("no block reached tier 2; the chain is not exercised")
}
var walk func(b noa.CompressionBlock, depth int) bool
walk = func(b noa.CompressionBlock, depth int) bool {
if depth > 10 {
t.Fatalf("the archive chain from %s is more than ten deep; it is probably a cycle", b.BlockID)
}
raw, err := os.ReadFile(b.ArchivePath)
if err != nil {
t.Fatalf("block %s (tier %d): archive unreadable: %v", b.BlockID, b.Tier, err)
}
if b.Tier == 1 {
return len(b.DirectMessageIDs) > 0 && len(raw) > 0
}
if len(b.DirectBlockIDs) == 0 {
t.Fatalf("block %s is tier %d but names no child block; the chain stops here and "+
"the originals underneath it are unreachable", b.BlockID, b.Tier)
}
for _, childID := range b.DirectBlockIDs {
child, ok := byID[childID]
if !ok {
t.Fatalf("block %s names child %s, which is not in the ledger", b.BlockID, childID)
}
// The parent archive must actually cite the child's file, or a reader
// following the chain by hand cannot get there.
if !strings.Contains(string(raw), filepath.Base(child.ArchivePath)) {
t.Fatalf("the tier-%d archive for %s does not cite its child %s (%s); the chain "+
"is broken for a human or an agent following it with Read",
b.Tier, b.BlockID, childID, filepath.Base(child.ArchivePath))
}
if !walk(child, depth+1) {
return false
}
}
return true
}
for _, b := range noa.ActiveBlocks(st) {
if int(b.Tier) == highest {
walk(b, 0)
}
}
}
func firstDiff(a, b string) int {
n := min(len(a), len(b))
for i := range n {
if a[i] != b[i] {
return i
}
}
return n
}
+380
View File
@@ -0,0 +1,380 @@
package noaadapter
import (
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/noa"
"github.com/Autumn-27/norma/tool"
)
// Every pressure decision noa makes keys off ONE number: the token count View
// hands to ProcessTurn. Which tier to nudge, whether to nudge at all, when to
// start mechanically shredding tool results — all of it reads that number and
// nothing else.
//
// These tests pin what it is allowed to measure. Getting it wrong does not fail
// loudly: the system keeps working, the requests stay valid, and the only
// symptom is that a long session compresses over and over on a context that was
// never full.
//
// Upstream hit this as issue #289 and fixed it in two layers
// (billion-context-pi src/tokens.ts):
//
// estimateTokens(msgs, coveredIds, …) skip messages an active block covers
// sentViewTokenCount(…) re-measure on the post-processTurn view,
// because prune ALSO strips uncovered
// messages (orphaned tool pairs, absorbed
// and filtered messages) every turn
//
// Norma's Session.resolveTokenCount does neither: it sums Project(msgs) — the
// whole raw history — so the number only ever grows and a compression that
// removes 40k tokens from the request leaves it untouched.
// ladderTokens is the number View actually passed to ProcessTurn this turn.
func ladderTokens(sess *Session) int { return sess.tokensBefore() }
// refOfCore finds the ref assigned to the core matching pick. Refs are handed
// out inside View, so call this after at least one View.
func refOfCore(t *testing.T, sess *Session, msgs []llm.Message, pick func(noa.CoreMessage) bool) string {
t.Helper()
cores, _ := Project(msgs)
st := sess.State()
for _, c := range cores {
if !pick(c) {
continue
}
if ref, ok := st.MessageRefs.ByRaw[c.ID]; ok && ref != noa.BlockedRef {
return ref
}
t.Fatalf("the core matching the predicate (%s/%s) has no usable ref", c.ContentType, c.ToolCallID)
}
t.Fatal("no core matched the predicate")
return ""
}
// compressRange drives the real Compress tool the way the model would.
func compressRange(t *testing.T, sess *Session, callID, startRef, endRef string) string {
t.Helper()
args, _ := json.Marshal(map[string]any{"content": []map[string]any{{
"startId": startRef, "endId": endRef, "topic": "work batch",
"summary": "Summary of " + startRef + "–" + endRef + ": read and reviewed several " +
"modules under /src. Key files: auth/jwt.go:42, auth/middleware.go:18. " +
"Decision: keep JWT with refresh tokens. Open: clock-skew leeway hard-coded at 60s.",
}}})
res, err := runCompress(sess, args, &tool.ToolContext{ToolUseID: callID})
if err != nil {
t.Fatalf("Compress errored: %v", err)
}
return res.Content[0].Text
}
// ---------------------------------------------------------------------------
// Layer 1: content hidden behind a summary must leave the count.
// ---------------------------------------------------------------------------
// The minimal statement of the bug. Compress a range, and the number driving
// every pressure decision must fall — that is the entire point of compressing.
func TestLadderFallsWhenAnActiveBlockHidesContent(t *testing.T) {
window := 200_000
sess := simSession(t, window)
var msgs []llm.Message
msgs = append(msgs, userText("Refactor the authentication subsystem."))
for i := range 12 {
call := fmt.Sprintf("call_%d", i)
msgs = append(msgs,
assistantWith(toolUse(call, "Bash", `{"command":"go test ./..."}`)),
toolResult(call, fmt.Sprintf("run %d\n", i)+strings.Repeat("output line of a test run. ", 400)),
)
}
// Six more turns so the early ones fall out of the protected tail.
for i := 12; i < 18; i++ {
call := fmt.Sprintf("call_%d", i)
msgs = append(msgs,
assistantWith(toolUse(call, "Bash", `{"command":"go build ./..."}`)),
toolResult(call, fmt.Sprintf("run %d ok", i)),
)
}
sess.View(msgs)
before := ladderTokens(sess)
startRef := refOfCore(t, sess, msgs, func(c noa.CoreMessage) bool { return c.ToolCallID == "call_1" })
endRef := refOfCore(t, sess, msgs, func(c noa.CoreMessage) bool {
return c.ToolCallID == "call_8" && c.ContentType == noa.CTToolResult
})
panel := compressRange(t, sess, "tc1", startRef, endRef)
if noa.PanelBlockCount(panel) == 0 {
t.Fatalf("the compression did not form a block, so there is nothing to measure:\n%s", panel)
}
msgs = append(msgs,
assistantWith(toolUse("tc1", noa.CompressToolName, `{}`)),
toolResult("tc1", panel),
)
sent := estimateMessages(sess.View(msgs))
after := ladderTokens(sess)
if after >= before {
t.Fatalf("a block now hides eight turns of output, and the pressure ladder still reads "+
"%d tokens (was %d). The request it describes weighs %d.\n"+
"Session.resolveTokenCount sums Project(msgs) — the raw history — and prune replaces "+
"the covered messages AFTER that, inside ProcessTurn. So the number never falls when a "+
"compression lands. Upstream's first layer is estimateTokens(msgs, coveredIds, …), "+
"which skips every message an active block covers.",
after, before, sent)
}
}
// ---------------------------------------------------------------------------
// Layer 2: content prune strips without a block covering it.
// ---------------------------------------------------------------------------
// Subtracting block coverage is not enough, which is why upstream needed a
// second layer. prune also removes messages NO block covers: a tool result
// whose paired call was compressed away is orphaned and stripped from every
// request, forever, while a coverage-based estimate keeps counting it.
//
// The layout below produces exactly that. One assistant message carries 21 tool
// calls; their results follow. The first call's result therefore sits 21
// positions past it — one beyond noa.ToolPairMaxScan — so boundary adjustment
// cannot pull it into the range, and compressing the call alone orphans the
// result. This is upstream's #289 Fix A discriminator, ported.
func TestLadderStopsCountingOrphansPruneStripsEveryTurn(t *testing.T) {
window := 200_000
sess := simSession(t, window)
const fanout = noa.ToolPairMaxScan + 1
bigCommand := `{"command":"` + strings.Repeat("x", 30_000) + `"}`
calls := []llm.ContentBlock{toolUse("c1", "Bash", bigCommand)}
for i := 2; i <= fanout; i++ {
calls = append(calls, toolUse(fmt.Sprintf("c%d", i), "Bash", `{"command":"ls"}`))
}
msgs := []llm.Message{userText("Audit the build.")}
msgs = append(msgs, assistantWith(calls...))
msgs = append(msgs, toolResult("c1", strings.Repeat("y", 100_000)))
for i := 2; i <= fanout; i++ {
msgs = append(msgs, toolResult(fmt.Sprintf("c%d", i), "ok"))
}
// Trailing work so c1's exchange is outside the protected recent window.
for i := range 6 {
call := fmt.Sprintf("t%d", i)
msgs = append(msgs,
assistantWith(toolUse(call, "Bash", `{"command":"go vet ./..."}`)),
toolResult(call, "clean"),
)
}
sess.View(msgs)
ref := refOfCore(t, sess, msgs, func(c noa.CoreMessage) bool {
return c.ToolCallID == "c1" && c.ContentType == noa.CTToolCall
})
panel := compressRange(t, sess, "tc1", ref, ref)
if noa.PanelBlockCount(panel) == 0 {
t.Fatalf("compressing c1's call alone did not form a block:\n%s", panel)
}
msgs = append(msgs,
assistantWith(toolUse("tc1", noa.CompressToolName, `{}`)),
toolResult("tc1", panel),
)
view := sess.View(msgs)
sent := estimateMessages(view)
ladder := ladderTokens(sess)
// The premise: c1's result really is gone from the request, and really is
// not covered by the block. If either stops holding, the fixture has drifted
// and the assertion below would be meaningless.
if strings.Contains(strings.Join(textOf(view), "\n"), strings.Repeat("y", 1000)) {
t.Fatal("c1's tool result is still in the request; the orphan layout did not take")
}
covered := noa.CoveredMessageIDs(sess.State())
cores, _ := Project(msgs)
var orphanID string
for _, c := range cores {
if c.ToolCallID == "c1" && c.ContentType == noa.CTToolResult {
orphanID = c.ID
}
}
if orphanID == "" {
t.Fatal("c1's tool result vanished from the projection; the fixture is wrong")
}
if covered[orphanID] {
t.Skip("boundary adjustment pulled c1's result into the block after all — " +
"the orphan case is not exercised and this discriminator does not apply")
}
if ladder > sent*2 {
t.Fatalf("c1's 100k-char result is stripped from every request and covered by no block, "+
"yet the ladder reads %d tokens for a request weighing %d.\n"+
"Subtracting block coverage alone would not fix this: nothing covers the orphan. "+
"Upstream's second layer (sentViewTokenCount) re-measures on the actual "+
"post-processTurn view for exactly this reason.",
ladder, sent)
}
}
// textOf flattens a request for substring checks.
func textOf(msgs []llm.Message) []string {
out := make([]string, 0, len(msgs))
for _, m := range msgs {
out = append(out, m.Text())
for _, b := range m.Content {
for _, inner := range b.Content {
out = append(out, inner.Text)
}
}
}
return out
}
// ---------------------------------------------------------------------------
// What the mis-measurement does, observed end to end.
// ---------------------------------------------------------------------------
// The reported symptom. A cooperative model on a large window is asked to stop
// and write summaries every few turns, indefinitely, on a context that is
// nowhere near full.
//
// The mechanism is the pressure band. Past MaxContextLimitPct DecideNudge
// deliberately drops the growth gate — "waiting for it to grow further is not a
// strategy" — leaving only minPressureBenefit (5000 tokens by default). With a
// count that never falls, the session enters that band once and never leaves,
// so every time ~5000 tokens of fresh compressible content accumulate it fires
// again. At ~1k tokens a turn that is one nudge per five turns, forever.
func TestPressureBandDoesNotRenudgeEveryFewTurns(t *testing.T) {
window := 128_000
sess := simSession(t, window)
a := newSimAgent(t, sess, 1)
const turns = 120
var nudgeTurns []int
prev := 0
for i := range turns {
a.work(4000)
a.observe()
if a.nudgesSeen > prev {
nudgeTurns = append(nudgeTurns, i)
prev = a.nudgesSeen
}
}
if a.compressions == 0 {
t.Fatal("nothing was compressed; the fixture is not exercising the ladder")
}
// The total is not the tell — the tail is. A ladder stuck in the pressure
// band re-fires as soon as the benefit floor is cleared again, so it is the
// SMALLEST gap that exposes it.
minGap := turns
for i := 1; i < len(nudgeTurns); i++ {
minGap = min(minGap, nudgeTurns[i]-nudgeTurns[i-1])
}
if len(nudgeTurns) > 1 && minGap < 10 {
t.Fatalf("nudges at turns %v over %d turns: two are only %d turns apart, and the gaps "+
"tighten as the session goes on. The model is being told to stop and write summaries "+
"on a context that is not full.", nudgeTurns, turns, minGap)
}
t.Logf("nudges at turns %v (smallest gap %d)", nudgeTurns, minGap)
}
// Emergency truncation destroys content in the request: it replaces a tool
// result's body with head+tail and a marker. It must therefore fire on the size
// of the request. A session whose view comfortably fits keeps its tool results
// whole, however long the underlying history has grown.
func TestTruncationDoesNotFireOnARequestThatFits(t *testing.T) {
window := 128_000
sess := simSession(t, window)
a := newSimAgent(t, sess, 1)
for range 120 {
a.work(4000)
a.observe()
sent := estimateMessages(sess.View(a.history))
if sess.lastTruncatedCount > 0 && sent < window/2 {
t.Fatalf("turn %d: %d tool result(s) were cut down while the request weighed %d of a "+
"%d window (%.0f%%). emergency-truncate reads the same count the nudge does, so a "+
"count pinned above the 95%% threshold shreds output out of a request that fits.",
a.turn, sess.lastTruncatedCount, sent, window, float64(sent)*100/float64(window))
}
}
}
// ---------------------------------------------------------------------------
// The provider tells us the truth and we throw it away.
// ---------------------------------------------------------------------------
// Compactor.Pre feeds the provider's real reported input size into the session.
// It is the one authoritative number available — it describes the array the
// provider actually received.
//
// resolveTokenCount compares it against the local estimate and discards it when
// they diverge by more than max(1000, est/10). Because the estimate is the raw
// history, the divergence is enormous in exactly the sessions where the
// provider figure matters most, so the truth is discarded every turn.
//
// Upstream treats the host's reported usage as a raise-only FLOOR
// (applyFloors in src/index.ts), never as something that can be outvoted by an
// estimate that reads high.
func TestProviderReportedSizeIsNotDiscardedAsDrift(t *testing.T) {
window := 128_000
sess := simSession(t, window)
a := newSimAgent(t, sess, 1)
for range 80 {
a.work(4000)
a.observe()
}
// What the provider would have reported for the last request we built.
real := sess.sentTokens()
if real == 0 {
t.Fatal("no request was built; the fixture is wrong")
}
c := &Compactor{sess: sess}
c.Pre(t.Context(), a.history, real)
sess.View(a.history)
ladder := ladderTokens(sess)
if ladder > real*2 {
t.Fatalf("the provider reported %d input tokens and the ladder still reads %d.\n"+
"resolveTokenCount's drift test compares the reported figure against the raw-history "+
"estimate; the gap is far past max(1000, est/10), so the honest number is rejected as "+
"drift and the inflated one wins.", real, ladder)
}
}
// ---------------------------------------------------------------------------
// The same number is what the user is shown.
// ---------------------------------------------------------------------------
// Upstream fixed the reporting surfaces alongside the transform (#289 Fix B:
// acp_status must read the sent view, not the raw estimate). Norma's equivalent
// is Session.tokensBefore, which the Compress panel prints as its headline
// "before" figure — so a wrong count is not only acted on, it is reported to
// the model and to the user as fact.
func TestPanelHeadlineReportsTheRequestSize(t *testing.T) {
window := 128_000
sess := simSession(t, window)
a := newSimAgent(t, sess, 1)
for range 80 {
a.work(4000)
a.observe()
}
sent := estimateMessages(sess.View(a.history))
shown := sess.tokensBefore()
if shown > sent*2 {
t.Fatalf("the panel headline would report %d tokens for a request that weighs %d "+
"(%.0f%% vs %.0f%% of the %d window). Whatever the ladder decides on, the number "+
"shown has to describe the request.",
shown, sent, float64(shown)*100/float64(window), float64(sent)*100/float64(window), window)
}
}
+455
View File
@@ -0,0 +1,455 @@
package noaadapter
import (
"errors"
"path/filepath"
"strconv"
"sync"
"time"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/noa"
)
// Options configures one noa-managed session.
type Options struct {
// ArchiveBaseDir is where archives and state live. REQUIRED: noa refuses to
// guess. The archive is the only route back to compressed originals, so
// where it lands must be the host's explicit decision — never a silent
// fallback to a temp directory that may be swept away.
ArchiveBaseDir string
// SessionID names the subdirectory under ArchiveBaseDir.
SessionID string
// Config overrides the defaults; the zero value means DefaultConfig.
Config *noa.Config
// ModelContextLimit sizes the default config when Config is nil.
ModelContextLimit int
// ParentSessionIDs are ancestors to inherit a ledger from when this session
// has none of its own, nearest first. A fork, a subagent, or a transcript
// copied without its sidecar would otherwise start from zero and re-compress
// everything the ancestor already did. At most maxInheritDepth are tried.
ParentSessionIDs []string
// OnWarn receives non-fatal diagnostics. noa writes nothing to stdout or
// stderr on its own.
OnWarn func(string)
// Now overrides the clock, for tests.
Now func() time.Time
}
// ErrNoArchiveDir is returned when ArchiveBaseDir is empty.
var ErrNoArchiveDir = errors.New("noaadapter: ArchiveBaseDir is required — compression must not run without a durable place for the originals")
// Session is the state the compactor and the Compress tool share.
//
// They are two entry points into one system and must see the same data:
//
// - state: the tool creates blocks, the view hides them. If they diverge, the
// model compresses into a void — the panel reports success and the next
// request still carries the full history.
// - lastView: the refs the model used were resolved against the array the
// view produced. Re-deriving it in the tool could yield a different array
// and therefore a misaligned range.
// - attempts: the tool counts failures, the view reads the count to decide
// whether to keep nudging.
type Session struct {
mu sync.Mutex
state noa.CompressionState
lastView []noa.CoreMessage
sidecar *Sidecar
// lastTokenCount is the measured size of the PROJECTED history this turn,
// before prune and truncation.
lastTokenCount int
// lastSentTokens is the size of the array actually handed to the provider.
// Overflow recovery compares against this, not the raw projection: the
// projection is always larger, so comparing to it would report progress on
// every attempt and never admit defeat.
lastSentTokens int
// attempts counts consecutive failed or ignored compression prompts.
attempts int
// suppressedAtTokens records where suppression began, so it can lift once
// the context has grown enough for the situation to have changed.
suppressedAtTokens int
// nudgedLastTurn lets the view notice a nudge that was ignored outright.
nudgedLastTurn bool
// lastTruncatedCount is how many tool results were mechanically shortened.
lastTruncatedCount int
// providerTokens is the input size the provider last reported. It is
// authoritative where available: a local estimate can drift, and the whole
// pressure ladder keys off this number.
providerTokens int
// emergencyFloor, when non-zero, forces the view to build under this ceiling
// after a prompt-too-long error taught us the real window.
emergencyFloor int
// deadRange refuses a range set the model keeps resubmitting.
deadRange *DeadRangeTracker
// lastCompressAt is Stats.CompressionCount at the last successful
// compression, used to spot a stale provider token anchor.
lastCompressAt int
// providerTokensAt is the compression count when providerTokens was
// reported, so a figure that predates a compression can be recognised.
providerTokensAt int
cfg noa.Config
store *StateStore
archiver noa.Archiver
root string
now func() time.Time
onWarn func(string)
}
func newSession(o Options) (*Session, error) {
if o.ArchiveBaseDir == "" {
return nil, ErrNoArchiveDir
}
cfg := noa.DefaultConfig(o.ModelContextLimit)
if o.Config != nil {
cfg = *o.Config
}
if cfg.ModelContextLimit <= 0 {
cfg.ModelContextLimit = 200000
}
now := o.Now
if now == nil {
now = time.Now
}
root := filepath.Join(o.ArchiveBaseDir, o.SessionID)
s := &Session{
cfg: cfg,
store: NewStateStore(root),
archiver: NewFileArchiver(root),
root: root,
now: now,
onWarn: o.OnWarn,
deadRange: NewDeadRangeTracker(),
}
for _, w := range noa.ValidateConfig(cfg) {
s.warn("config: " + w)
}
st, err := s.store.Load(o.SessionID, root)
if err != nil {
// A damaged state file is recoverable: blocks can be replayed from the
// transcript. Starting fresh beats refusing to run.
s.warn("state: " + err.Error() + " — starting from an empty state")
st = noa.CreateInitialState(o.SessionID, root)
}
if len(st.Blocks) == 0 && len(o.ParentSessionIDs) > 0 {
if inherited, from, ok := InheritState(InheritOptions{
ArchiveBaseDir: o.ArchiveBaseDir, SessionID: o.SessionID, ParentIDs: o.ParentSessionIDs,
}); ok {
s.warn("inherited " + itoa(len(inherited.Blocks)) + " block(s) from session " + from)
st = inherited
}
}
s.state = st
return s, nil
}
func itoa(n int) string { return strconv.Itoa(n) }
func (s *Session) warn(msg string) {
if s.onWarn != nil {
s.onWarn("noa: " + msg)
}
}
// ArchiveRoot is where this session's archives and state live.
func (s *Session) ArchiveRoot() string { return s.root }
// Config returns the resolved configuration.
func (s *Session) Config() noa.Config { return s.cfg }
// State returns a copy of the current compression state.
func (s *Session) State() noa.CompressionState {
s.mu.Lock()
defer s.mu.Unlock()
return noa.CloneState(s.state)
}
// View projects the history for one request.
//
// Pure with respect to msgs: the returned slice is for this request only and is
// never written back. Message identity is a content hash, so writing a tagged
// or truncated body back would change every id derived from it.
func (s *Session) View(msgs []llm.Message) []llm.Message {
s.mu.Lock()
defer s.mu.Unlock()
cores, sc := Project(msgs)
tokens := s.resolveTokenCount(cores)
s.lastTokenCount = tokens
// A new user turn means the situation changed; give the model a clean slate
// before deciding whether to nudge.
s.notePriorTurnOutcome(msgs)
cfg := s.cfg
if s.emergencyFloor > 0 {
// A prompt-too-long error taught us the real window. Build to it, rather
// than to the configured one that just failed.
cfg.ModelContextLimit = s.emergencyFloor
}
res := noa.ProcessTurn(noa.ProcessTurnInput{
Messages: cores,
State: s.state,
Config: cfg,
TokenCount: tokens,
})
s.state = res.State
s.sidecar = sc
s.lastTruncatedCount = res.TruncatedCount
view := res.Messages
s.nudgedLastTurn = false
if res.Nudge != nil && s.nudgeAllowed(tokens) {
voice, text := noa.RenderNudgeText(*res.Nudge, noa.NudgeSections{})
_ = voice
view = append(view, noa.CoreMessage{
ID: noa.NudgeMessageID, Role: noa.RoleUser, ContentType: noa.CTText, Text: text,
})
s.nudgedLastTurn = true
}
// lastView is what the model's refs will be resolved against, so it must be
// the array the model actually sees — nudge included.
s.lastView = view
out := Reassemble(view, msgs, sc, ReassembleOptions{State: &s.state, Tag: true})
s.lastSentTokens = estimateMessages(out)
return out
}
// nudgeAllowed gates injection on the failure ladder.
//
// After MaxCompressAttempts consecutive failures or outright refusals, nudging
// stops: each one costs a couple of thousand tokens, and replaying it into a
// context that is already too big makes the problem it describes worse.
//
// Suppression is not permanent. It lifts once the context has grown by a full
// cadence step, because by then the situation genuinely differs from the one
// the model declined to act on. Without that release the first three failures
// in a session would silence nudging for good. Callers hold the lock.
func (s *Session) nudgeAllowed(tokenCount int) bool {
if s.attempts < s.cfg.MaxCompressAttempts {
return true
}
floor := noa.NudgeGrowthFloor(s.cfg)
if tokenCount-s.suppressedAtTokens >= floor {
s.attempts = 0
s.suppressedAtTokens = 0
return true
}
return false
}
// notePriorTurnOutcome reacts to what happened since the last view.
//
// Two things reset or advance the ladder here:
//
// - A genuine new user message means new instructions and a new situation, so
// the model deserves a fresh start.
// - A nudge that drew no Compress call at all counts as a failure. Upstream
// only counts calls that FAILED, which leaves the cheapest way to ignore a
// nudge — not calling the tool — entirely uncounted, and an emergency nudge
// then repeats on every request forever.
//
// Callers hold the lock.
func (s *Session) notePriorTurnOutcome(msgs []llm.Message) {
if len(msgs) == 0 {
return
}
last := msgs[len(msgs)-1]
if isRealUserTurn(last) {
s.attempts = 0
s.suppressedAtTokens = 0
s.nudgedLastTurn = false
return
}
if s.nudgedLastTurn && !lastAssistantCalledCompress(msgs) {
s.noteFailedAttempt()
s.nudgedLastTurn = false
}
}
// isRealUserTurn distinguishes a person speaking from a packaged tool result.
//
// Norma carries tool results in Role: user messages, so the role alone says
// nothing; the absence of any tool_result block is what marks a real turn.
func isRealUserTurn(m llm.Message) bool {
if m.Role != llm.RoleUser {
return false
}
for _, b := range m.Content {
if b.Type == llm.BlockToolResult {
return false
}
}
return len(m.Content) > 0
}
// lastAssistantCalledCompress reports whether the most recent assistant message
// invoked Compress.
func lastAssistantCalledCompress(msgs []llm.Message) bool {
for i := len(msgs) - 1; i >= 0; i-- {
if msgs[i].Role != llm.RoleAssistant {
continue
}
for _, b := range msgs[i].Content {
if b.Type == llm.BlockToolUse && b.Name == noa.CompressToolName {
return true
}
}
return false
}
return false
}
// resolveTokenCount decides what this turn's context size is.
//
// The base is the size of the PRUNED view — the request that will actually be
// sent — not the raw history. Counting the raw history is the pressure ladder's
// original sin: it holds everything prune replaces with a summary and every
// orphan prune strips, so the figure only ever grows and a compression that
// removes tens of thousands of tokens from the request leaves it unchanged. The
// ladder then pins to the pressure band forever and nudges on every turn (the
// session-847926 compression loop). ProjectedTokenCount measures the pruned
// view instead.
//
// The provider's reported input size is then applied as a raise-only FLOOR, not
// as something the estimate can outvote. It is authoritative — it describes the
// array the provider actually received — and it includes overhead the
// projection omits (system prompt, tool definitions). A gap between the two
// means the estimate is MISSING real tokens, so the safe response is to raise
// to the provider's number, never to discard it as "drift". Callers hold the
// lock.
func (s *Session) resolveTokenCount(cores []noa.CoreMessage) int {
est := estimateProjectedTokens(cores, s.state, s.cfg)
p := s.providerTokens
if p <= 0 {
return est
}
// Floor-stale: the provider figure was reported before the most recent
// compression, so it describes a context that no longer exists. Trusting it
// would keep the pressure ladder pinned at the pre-compression size and
// re-trigger an emergency the model already resolved.
if s.providerTokensAt < s.lastCompressAt {
return est
}
return max(est, p)
}
// estimateProjectedTokens sizes the view that will actually be SENT: the pruned
// projection, with covered content hidden and orphans stripped.
//
// Sizing the sent view rather than raw history is the whole point — the raw
// array still contains everything prune removes, so counting it pins the figure
// high forever and drives compression that reclaims nothing.
func estimateProjectedTokens(cores []noa.CoreMessage, state noa.CompressionState, cfg noa.Config) int {
return noa.ProjectedTokenCount(cores, state, cfg, nil)
}
// estimateCoreTokens sums the RAW projection, ignoring what prune would hide.
// Use it only where the raw history size is genuinely the question (e.g.
// measuring how much emergency-truncate removed); the pressure ladder must use
// estimateProjectedTokens instead.
func estimateCoreTokens(cores []noa.CoreMessage) int {
total := 0
for _, c := range cores {
total += noa.DefaultCountTokens(c.Text)
}
return total
}
// applyCompression runs one Compress call against the shared state.
func (s *Session) applyCompression(ranges []noa.CompressRange, callID string) noa.ApplyResult {
s.mu.Lock()
defer s.mu.Unlock()
now := s.now()
res := noa.ApplyCompression(noa.ApplyInput{
Ranges: ranges,
Messages: s.lastView,
State: s.state,
Config: s.cfg,
CallID: callID,
Archiver: s.archiver,
CreatedAt: now.Format(time.RFC3339),
Now: now.Unix(),
})
if len(res.BlocksCreated) > 0 {
s.state = res.State
s.attempts = 0
s.suppressedAtTokens = 0
s.lastCompressAt = s.state.Stats.CompressionCount
// The view changed, so a range that was dead before may not be now.
s.deadRange.Reset()
if err := s.store.Save(s.state); err != nil {
// The compression itself succeeded and the archives are on disk;
// losing the state file costs a rebuild, not data.
s.warn("state save failed: " + err.Error())
}
} else {
s.noteFailedAttempt()
s.deadRange.Record(ranges)
}
return res
}
// checkDeadRange refuses a range set the model keeps resubmitting.
func (s *Session) checkDeadRange(ranges []noa.CompressRange) string {
s.mu.Lock()
defer s.mu.Unlock()
return s.deadRange.Check(ranges, s.state)
}
// recordParseFailure counts arguments that could not be parsed at all.
//
// Malformed arguments count against the same ladder as an empty result: from
// the context's point of view nothing was reclaimed either way, and a model
// stuck producing unusable JSON loops just as expensively as one producing
// unusable ranges.
func (s *Session) recordParseFailure() {
s.mu.Lock()
defer s.mu.Unlock()
s.noteFailedAttempt()
}
// noteFailedAttempt records an attempt that reclaimed nothing. Callers hold the
// lock.
func (s *Session) noteFailedAttempt() {
s.attempts++
if s.attempts == s.cfg.MaxCompressAttempts {
s.suppressedAtTokens = s.lastTokenCount
}
}
// noteProviderTokens records the input size the provider reported.
func (s *Session) noteProviderTokens(n int) {
s.mu.Lock()
defer s.mu.Unlock()
s.providerTokens = n
s.providerTokensAt = s.state.Stats.CompressionCount
}
// setEmergencyFloor arms or clears the post-overflow ceiling.
func (s *Session) setEmergencyFloor(n int) {
s.mu.Lock()
defer s.mu.Unlock()
s.emergencyFloor = n
}
// tokensBefore reports the current view's size, for the panel headline.
func (s *Session) tokensBefore() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.lastTokenCount
}
// sentTokens reports the size of the last array handed to the provider.
func (s *Session) sentTokens() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.lastSentTokens
}
+246
View File
@@ -0,0 +1,246 @@
package noaadapter
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sync"
"github.com/Autumn-27/norma/noa"
)
// stateFileVersion guards against silently misreading a future format.
const stateFileVersion = 1
// stateFile is the on-disk shape of the compression state.
type stateFile struct {
Version int `json:"version"`
SessionID string `json:"sessionId"`
NextBlockID int `json:"nextBlockId"`
Blocks []blockJSON `json:"blocks"`
MessageRefs refMapJSON `json:"messageRefs"`
TokenSnapshot map[string]int `json:"tokenSnapshot,omitempty"`
Nudge nudgeJSON `json:"nudge"`
Stats statsJSON `json:"stats"`
DerivedFrom string `json:"derivedFrom,omitempty"`
}
type blockJSON struct {
BlockID string `json:"blockId"`
Tier int `json:"tier"`
Topic string `json:"topic,omitempty"`
Summary string `json:"summary"`
DirectMessageIDs []string `json:"directMessageIds,omitempty"`
EffectiveMessageIDs []string `json:"effectiveMessageIds,omitempty"`
DirectBlockIDs []string `json:"directBlockIds,omitempty"`
ArchivePath string `json:"archivePath,omitempty"`
ArchiveRel string `json:"archiveRel,omitempty"`
CompressedTokens int `json:"compressedTokens"`
StartRef string `json:"startRef,omitempty"`
EndRef string `json:"endRef,omitempty"`
CreatedAt int64 `json:"createdAt,omitempty"`
Active bool `json:"active"`
CompressCallID string `json:"compressCallId,omitempty"`
}
type refMapJSON struct {
ByRaw map[string]string `json:"byRaw"`
ByRef map[string]string `json:"byRef"`
}
type nudgeJSON struct {
LastPerMessageNudgeTokens int `json:"lastPerMessageNudgeTokens"`
LastNudgeShownTokens int `json:"lastNudgeShownTokens"`
LastShownByTier map[string]int `json:"lastShownByTier,omitempty"`
}
type statsJSON struct {
TokensCompressed int `json:"tokensCompressed"`
CompressionCount int `json:"compressionCount"`
}
// StateStore persists compression state beside the archives.
type StateStore struct {
mu sync.Mutex
// path is "" for a session with no durable location.
path string
// cache is the authoritative in-process copy.
cache noa.CompressionState
// loaded marks the cache as populated.
loaded bool
}
// NewStateStore returns a store writing to <root>/state.json. An empty root
// yields a memory-only store.
func NewStateStore(root string) *StateStore {
if root == "" {
return &StateStore{}
}
return &StateStore{path: filepath.Join(root, "state.json")}
}
// Save records the state.
//
// The cache is updated BEFORE the early return for a location-less store. A
// store that skipped the cache when it had no file would hand back a zero state
// on the next load, and the model would re-compress the same range every turn.
func (s *StateStore) Save(st noa.CompressionState) error {
s.mu.Lock()
defer s.mu.Unlock()
s.cache = noa.CloneState(st)
s.loaded = true
if s.path == "" {
return nil
}
return s.writeAtomic(st)
}
// Load returns the state, preferring the in-process cache.
func (s *StateStore) Load(sessionID, archiveRoot string) (noa.CompressionState, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.loaded {
return noa.CloneState(s.cache), nil
}
if s.path == "" {
st := noa.CreateInitialState(sessionID, archiveRoot)
s.cache, s.loaded = noa.CloneState(st), true
return st, nil
}
st, err := s.readFile(sessionID, archiveRoot)
if err != nil {
return noa.CreateInitialState(sessionID, archiveRoot), err
}
s.cache, s.loaded = noa.CloneState(st), true
return st, nil
}
// Exists reports whether a persisted state file is present.
func (s *StateStore) Exists() bool {
if s.path == "" {
return false
}
_, err := os.Stat(s.path)
return err == nil
}
func (s *StateStore) readFile(sessionID, archiveRoot string) (noa.CompressionState, error) {
raw, err := os.ReadFile(s.path)
if err != nil {
if os.IsNotExist(err) {
return noa.CreateInitialState(sessionID, archiveRoot), nil
}
return noa.CreateInitialState(sessionID, archiveRoot), err
}
var f stateFile
if err := json.Unmarshal(raw, &f); err != nil {
return noa.CreateInitialState(sessionID, archiveRoot), fmt.Errorf("parse state file: %w", err)
}
if f.Version != stateFileVersion {
return noa.CreateInitialState(sessionID, archiveRoot),
fmt.Errorf("state file version %d, want %d", f.Version, stateFileVersion)
}
return fromFile(f, sessionID, archiveRoot), nil
}
// writeAtomic replaces the state file via temp + rename, so a crash mid-write
// cannot leave a truncated file where a valid one was.
func (s *StateStore) writeAtomic(st noa.CompressionState) error {
if err := os.MkdirAll(filepath.Dir(s.path), 0o755); err != nil {
return fmt.Errorf("create state dir: %w", err)
}
data, err := json.MarshalIndent(toFile(st), "", " ")
if err != nil {
return fmt.Errorf("encode state: %w", err)
}
tmp, err := os.CreateTemp(filepath.Dir(s.path), ".noa-state-*.tmp")
if err != nil {
return fmt.Errorf("create temp state: %w", err)
}
name := tmp.Name()
if _, err := tmp.Write(data); err != nil {
tmp.Close()
os.Remove(name)
return fmt.Errorf("write state: %w", err)
}
if err := tmp.Close(); err != nil {
os.Remove(name)
return fmt.Errorf("close state: %w", err)
}
if err := os.Chmod(name, 0o644); err != nil {
os.Remove(name)
return err
}
if err := os.Rename(name, s.path); err != nil {
os.Remove(name)
return fmt.Errorf("install state: %w", err)
}
return nil
}
func toFile(st noa.CompressionState) stateFile {
f := stateFile{
Version: stateFileVersion,
SessionID: st.SessionID,
NextBlockID: st.NextBlockID,
MessageRefs: refMapJSON{ByRaw: st.MessageRefs.ByRaw, ByRef: st.MessageRefs.ByRef},
TokenSnapshot: st.TokenSnapshot,
Nudge: nudgeJSON{
LastPerMessageNudgeTokens: st.Nudge.LastPerMessageNudgeTokens,
LastNudgeShownTokens: st.Nudge.LastNudgeShownTokens,
LastShownByTier: map[string]int{},
},
Stats: statsJSON{TokensCompressed: st.Stats.TokensCompressed, CompressionCount: st.Stats.CompressionCount},
}
for tier, n := range st.Nudge.LastShownByTier {
f.Nudge.LastShownByTier[fmt.Sprintf("%d", tier)] = n
}
for _, b := range st.Blocks {
f.Blocks = append(f.Blocks, blockJSON{
BlockID: b.BlockID, Tier: int(b.Tier), Topic: b.Topic, Summary: b.Summary,
DirectMessageIDs: b.DirectMessageIDs, EffectiveMessageIDs: b.EffectiveMessageIDs,
DirectBlockIDs: b.DirectBlockIDs, ArchivePath: b.ArchivePath, ArchiveRel: b.ArchiveRel,
CompressedTokens: b.CompressedTokens, StartRef: b.StartRef, EndRef: b.EndRef,
CreatedAt: b.CreatedAt, Active: b.Active, CompressCallID: b.CompressCallID,
})
}
return f
}
func fromFile(f stateFile, sessionID, archiveRoot string) noa.CompressionState {
st := noa.CreateInitialState(sessionID, archiveRoot)
if f.SessionID != "" {
st.SessionID = f.SessionID
}
st.NextBlockID = max(f.NextBlockID, 1)
if f.MessageRefs.ByRaw != nil {
st.MessageRefs.ByRaw = f.MessageRefs.ByRaw
}
if f.MessageRefs.ByRef != nil {
st.MessageRefs.ByRef = f.MessageRefs.ByRef
}
if f.TokenSnapshot != nil {
st.TokenSnapshot = f.TokenSnapshot
}
st.Nudge.LastPerMessageNudgeTokens = f.Nudge.LastPerMessageNudgeTokens
st.Nudge.LastNudgeShownTokens = f.Nudge.LastNudgeShownTokens
for k, v := range f.Nudge.LastShownByTier {
var tier int
if _, err := fmt.Sscanf(k, "%d", &tier); err == nil {
st.Nudge.LastShownByTier[noa.Tier(tier)] = v
}
}
st.Stats.TokensCompressed = f.Stats.TokensCompressed
st.Stats.CompressionCount = f.Stats.CompressionCount
for _, b := range f.Blocks {
st.Blocks = append(st.Blocks, noa.CompressionBlock{
BlockID: b.BlockID, Tier: noa.Tier(b.Tier), Topic: b.Topic, Summary: b.Summary,
DirectMessageIDs: b.DirectMessageIDs, EffectiveMessageIDs: b.EffectiveMessageIDs,
DirectBlockIDs: b.DirectBlockIDs, ArchivePath: b.ArchivePath, ArchiveRel: b.ArchiveRel,
CompressedTokens: b.CompressedTokens, StartRef: b.StartRef, EndRef: b.EndRef,
CreatedAt: b.CreatedAt, Active: b.Active, CompressCallID: b.CompressCallID,
})
}
return st
}
+196
View File
@@ -0,0 +1,196 @@
package noaadapter
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/Autumn-27/norma/noa"
)
func sampleState() noa.CompressionState {
st := noa.CreateInitialState("sess", "/archive/sess")
st.NextBlockID = 3
st.MessageRefs.ByRaw = map[string]string{"h_abc": "m00001", "h_def": "m00002"}
st.MessageRefs.ByRef = map[string]string{"m00001": "h_abc", "m00002": "h_def"}
st.TokenSnapshot = map[string]int{"m00001": 120, "m00002": 4100}
st.Nudge.LastPerMessageNudgeTokens = 118000
st.Nudge.LastNudgeShownTokens = 116000
st.Nudge.LastShownByTier = map[noa.Tier]int{2: 110000}
st.Stats = noa.Stats{TokensCompressed: 48200, CompressionCount: 7}
st.Blocks = []noa.CompressionBlock{{
BlockID: "b1", Tier: 1, Topic: "auth", Summary: "decided on JWT",
DirectMessageIDs: []string{"h_abc"}, EffectiveMessageIDs: []string{"h_abc", "h_def"},
DirectBlockIDs: nil, ArchivePath: "/archive/sess/tier1/b1.md", ArchiveRel: "tier1/b1.md",
CompressedTokens: 12480, StartRef: "m00001", EndRef: "m00002",
CreatedAt: 1789000000, Active: true, CompressCallID: "toolu_1",
}}
return st
}
func TestStateStoreRoundTrip(t *testing.T) {
root := t.TempDir()
s := NewStateStore(root)
want := sampleState()
if err := s.Save(want); err != nil {
t.Fatalf("Save: %v", err)
}
// A fresh store reads from disk rather than the cache.
got, err := NewStateStore(root).Load("sess", "/archive/sess")
if err != nil {
t.Fatalf("Load: %v", err)
}
if got.NextBlockID != want.NextBlockID || got.SessionID != want.SessionID {
t.Fatalf("identity lost: %+v", got)
}
if len(got.Blocks) != 1 {
t.Fatalf("got %d blocks, want 1", len(got.Blocks))
}
b := got.Blocks[0]
w := want.Blocks[0]
if b.BlockID != w.BlockID || b.Tier != w.Tier || b.Summary != w.Summary ||
b.ArchivePath != w.ArchivePath || b.CompressCallID != w.CompressCallID {
t.Fatalf("block round trip lost fields:\ngot %+v\nwant %+v", b, w)
}
if got.TokenSnapshot["m00002"] != 4100 {
t.Fatalf("token snapshot = %v, want the frozen numbers preserved", got.TokenSnapshot)
}
if got.Nudge.LastShownByTier[2] != 110000 {
t.Fatalf("per-tier stamps = %v", got.Nudge.LastShownByTier)
}
if got.Stats != want.Stats {
t.Fatalf("stats = %+v, want %+v", got.Stats, want.Stats)
}
}
// The cache must be written even when there is nowhere to persist to. A store
// that skipped it would hand back a zero state next time, and the model would
// re-compress the same range every single turn.
func TestStateStoreCachesWithoutAFile(t *testing.T) {
s := NewStateStore("")
st := sampleState()
if err := s.Save(st); err != nil {
t.Fatalf("Save: %v", err)
}
got, err := s.Load("sess", "/archive/sess")
if err != nil {
t.Fatalf("Load: %v", err)
}
if len(got.Blocks) != 1 {
t.Fatalf("got %d blocks from the in-memory store, want 1", len(got.Blocks))
}
}
func TestStateStoreMissingFileIsFresh(t *testing.T) {
got, err := NewStateStore(t.TempDir()).Load("sess", "/a")
if err != nil {
t.Fatalf("Load of a missing file = %v, want a clean fresh state", err)
}
if len(got.Blocks) != 0 || got.NextBlockID != 1 {
t.Fatalf("fresh state = %+v", got)
}
}
// A damaged state file is recoverable by replay, so it must surface as an error
// rather than taking the session down.
func TestStateStoreCorruptFileReportsError(t *testing.T) {
root := t.TempDir()
if err := os.WriteFile(filepath.Join(root, "state.json"), []byte("{not json"), 0o644); err != nil {
t.Fatal(err)
}
got, err := NewStateStore(root).Load("sess", "/a")
if err == nil {
t.Fatal("a corrupt state file was accepted")
}
if len(got.Blocks) != 0 {
t.Fatal("a fresh state must be returned alongside the error")
}
}
func TestStateStoreRejectsUnknownVersion(t *testing.T) {
root := t.TempDir()
if err := os.WriteFile(filepath.Join(root, "state.json"), []byte(`{"version":999}`), 0o644); err != nil {
t.Fatal(err)
}
_, err := NewStateStore(root).Load("sess", "/a")
if err == nil || !strings.Contains(err.Error(), "version") {
t.Fatalf("err = %v, want a version mismatch", err)
}
}
// Temp + rename: a crash mid-write must not leave a truncated file where a
// valid one was.
func TestStateStoreWriteIsAtomic(t *testing.T) {
root := t.TempDir()
s := NewStateStore(root)
if err := s.Save(sampleState()); err != nil {
t.Fatalf("Save: %v", err)
}
entries, err := os.ReadDir(root)
if err != nil {
t.Fatal(err)
}
for _, e := range entries {
if strings.HasPrefix(e.Name(), ".noa-state-") {
t.Fatalf("a temp file survived: %s", e.Name())
}
}
if !s.Exists() {
t.Fatal("Exists reports no state file after a successful save")
}
}
// A session that starts up damaged must still run — the state is rebuildable.
func TestSessionSurvivesCorruptState(t *testing.T) {
root := t.TempDir()
dir := filepath.Join(root, "sess")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "state.json"), []byte("{broken"), 0o644); err != nil {
t.Fatal(err)
}
var warns []string
sess, err := newSession(Options{
ArchiveBaseDir: root, SessionID: "sess",
OnWarn: func(m string) { warns = append(warns, m) },
})
if err != nil {
t.Fatalf("newSession refused to start over a damaged state file: %v", err)
}
if len(sess.State().Blocks) != 0 {
t.Fatal("a damaged state must yield an empty one")
}
if len(warns) == 0 {
t.Fatal("the host was not told the state file was unreadable")
}
}
func TestSessionArchiveRootIncludesSessionID(t *testing.T) {
base := t.TempDir()
sess, err := newSession(Options{ArchiveBaseDir: base, SessionID: "abc123"})
if err != nil {
t.Fatalf("newSession: %v", err)
}
if sess.ArchiveRoot() != filepath.Join(base, "abc123") {
t.Fatalf("archive root = %q, want the base joined with the session id", sess.ArchiveRoot())
}
}
func TestSessionReportsConfigWarnings(t *testing.T) {
cfg := noa.DefaultConfig(200000)
cfg.Tiers.MaxTier = 7 // outside the range the tier prompts cover
var warns []string
if _, err := newSession(Options{
ArchiveBaseDir: t.TempDir(), SessionID: "s", Config: &cfg,
OnWarn: func(m string) { warns = append(warns, m) },
}); err != nil {
t.Fatalf("newSession: %v", err)
}
joined := strings.Join(warns, "\n")
if !strings.Contains(joined, "MaxTier") {
t.Fatalf("warnings = %v, want one naming MaxTier", warns)
}
}
+119
View File
@@ -0,0 +1,119 @@
package noaadapter
import (
"fmt"
"regexp"
"strings"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/noa"
)
// The ref tag tells the model how to address a message when compressing.
//
// Shape decisions, each load-bearing:
// - Self-closing, so a truncated model response cannot leave an orphaned
// </noa-ref> polluting the context.
// - A hyphenated custom element, which models read as host-injected structure
// rather than content, and which cannot collide with a <ref> or <msg> the
// agent read out of a file.
// - src only on tool output. Its presence IS the signal; writing src="text"
// on every user message would spend bytes to say nothing.
//
// The regexes anchor on BOTH the element name and the id format. Matching the
// name alone would let a <noa-ref> appearing inside a file the agent read be
// stripped out of that file's content.
var (
// Only the TRAILING form is stripped, because only the trailing form is ever
// produced (see AppendRefTag). Stripping a leading one as well would defend
// against a shape noa never emits, at the cost of silently eating a user
// message that legitimately opens with tag-shaped text — a transcript
// pasted back in, say. A silent corruption of real content is worse than the
// theoretical id drift it would prevent, and that drift is at least visible
// as a dangling ref.
// Exactly ONE separator is consumed, matching the single newline
// AppendRefTag inserts. A greedy `\n*` would also swallow a newline the body
// itself ended with, so tagging and stripping would not round-trip and the
// content would quietly change.
trailingTagRE = regexp.MustCompile(`(?:^|\n)<noa-ref\s+id="m\d{5}"[^>]*/>\s*$`)
anyRefTagRE = regexp.MustCompile(`<noa-ref\s+id="(m\d{5})"[^>]*/>`)
)
// StripRefTag removes the ref tag from the end of a body.
//
// Projection calls this before hashing: a tag inside the identity would make
// the id drift every turn the tag is re-rendered.
func StripRefTag(s string) string {
return trailingTagRE.ReplaceAllString(s, "")
}
// MessageRef reads a ref back out of a message's text, if it carries one.
func MessageRef(m llm.Message) string {
for _, b := range m.Content {
if match := anyRefTagRE.FindStringSubmatch(b.Text); match != nil {
return match[1]
}
}
return ""
}
// srcOf returns the tag's src attribute; "" means omit it.
//
// Note the value space: because assistant messages carry no tag at all (see
// InjectRefTag), only user text and tool results reach this function. So src is
// either "" or a tool name. The reasoning and tool-call branches are defensive
// — if assistant tagging is ever enabled, this function needs no change.
func srcOf(m noa.CoreMessage) string {
switch m.ContentType {
case noa.CTToolCall, noa.CTToolResult:
if m.ToolName != "" {
return m.ToolName
}
return "tool"
case noa.CTText:
return ""
default:
return string(m.ContentType)
}
}
// RefTag renders the tag for one message.
//
// tokens is a pure function of the body AT FIRST RENDER, frozen thereafter in
// the token snapshot. A tag whose number moves is a byte that moves, and a byte
// that moves invalidates the whole prefix cache from that point on — so the
// number describes what the model first saw, not what is there now.
func RefTag(ref string, m noa.CoreMessage, tokens int) string {
var b strings.Builder
fmt.Fprintf(&b, `<noa-ref id=%q tokens=%q`, ref, noa.FormatTokens(tokens))
if s := srcOf(m); s != "" {
fmt.Fprintf(&b, ` src=%q`, s)
}
b.WriteString("/>")
return b.String()
}
// tokenForRef resolves a ref's frozen token count, computing and freezing it on
// first sight.
func tokenForRef(snapshot map[string]int, ref, body string) int {
if n, ok := snapshot[ref]; ok {
return n
}
n := noa.DefaultCountTokens(body)
if snapshot != nil {
snapshot[ref] = n
}
return n
}
// AppendRefTag puts the tag at the END of a body.
//
// Trailing rather than leading: a leading tag would corrupt a tool_use's JSON
// arguments, and models are markedly more likely to echo something that opens a
// message than something that closes it.
func AppendRefTag(body, tag string) string {
if body == "" {
return tag
}
return body + "\n" + tag
}
+216
View File
@@ -0,0 +1,216 @@
package noaadapter
import (
"encoding/json"
"os"
"strings"
"testing"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/noa"
"github.com/Autumn-27/norma/tool"
)
// compress runs one Compress call and returns the panel.
func compress(t *testing.T, sess *Session, callID string, ranges ...map[string]any) string {
t.Helper()
args, _ := json.Marshal(map[string]any{"content": ranges})
res, err := runCompress(sess, args, &tool.ToolContext{ToolUseID: callID})
if err != nil {
t.Fatalf("runCompress: %v", err)
}
return res.Content[0].Text
}
// A tier-2 archive must be a step in a chain, not a dead end: it holds the
// absorbed summaries, each pointing at its own archive, so a reader can walk
// down to the original messages one level at a time.
func TestTierChainIsTraceableToOriginals(t *testing.T) {
opts := baseOptions()
sess, err := EnableWithSession(&opts, Options{ArchiveBaseDir: t.TempDir(), SessionID: "chain"})
if err != nil {
t.Fatalf("EnableWithSession: %v", err)
}
unique := "UNIQUE-ORIGINAL-MARKER"
body := strings.Repeat("filler content. ", 300)
tail := strings.Repeat("recent tail. ", 400)
msgs := []llm.Message{userText("the task")}
for i := range 6 {
text := body
if i == 0 {
text = unique + " " + body
}
msgs = append(msgs, llm.Message{Role: llm.RoleAssistant,
Content: []llm.ContentBlock{llm.TextBlock(text)}})
}
for range 6 {
msgs = append(msgs, userText(tail))
}
// Two tier-1 compressions.
sess.View(msgs)
p1 := compress(t, sess, "c1", map[string]any{
"startId": "m00002", "endId": "m00004", "summary": longSummary, "topic": "first half",
})
if noa.PanelBlockCount(p1) != 1 {
t.Fatalf("first compression produced no block:\n%s", p1)
}
sess.View(msgs)
p2 := compress(t, sess, "c2", map[string]any{
"startId": "m00005", "endId": "m00007", "summary": longSummary, "topic": "second half",
})
if noa.PanelBlockCount(p2) != 1 {
t.Fatalf("second compression produced no block:\n%s", p2)
}
blocks := sess.State().Blocks
if len(blocks) != 2 {
t.Fatalf("got %d blocks, want 2 tier-1 blocks", len(blocks))
}
// Consolidate them into a tier-2 block.
sess.View(msgs)
p3 := compress(t, sess, "c3", map[string]any{
"startId": blocks[0].BlockID, "endId": blocks[1].BlockID,
"summary": longSummary, "topic": "consolidated",
})
if noa.PanelBlockCount(p3) != 1 {
t.Fatalf("consolidation produced no block:\n%s", p3)
}
var t2 *noa.CompressionBlock
for i, b := range sess.State().Blocks {
if b.Tier == 2 && b.Active {
t2 = &sess.State().Blocks[i]
}
}
if t2 == nil {
t.Fatalf("no active tier-2 block after consolidation: %+v", sess.State().Blocks)
}
if len(t2.DirectBlockIDs) != 2 {
t.Fatalf("the tier-2 block absorbed %d blocks, want 2", len(t2.DirectBlockIDs))
}
for _, id := range t2.DirectBlockIDs {
if b := noa.FindBlock(ptr(sess.State()), id); b == nil || b.Active {
t.Fatalf("absorbed block %s is still active", id)
}
}
// Walk the chain: tier-2 archive -> tier-1 archive -> the original text.
t2body, err := os.ReadFile(t2.ArchivePath)
if err != nil {
t.Fatalf("read tier-2 archive: %v", err)
}
if strings.Contains(string(t2body), unique) {
t.Fatal("the tier-2 archive holds raw message text; it should hold the absorbed summaries and point onward")
}
var childPaths []string
for _, line := range strings.Split(string(t2body), "\n") {
if strings.HasPrefix(line, "> 绝对路径:`") {
p := strings.TrimSuffix(strings.TrimPrefix(line, "> 绝对路径:`"), "`")
childPaths = append(childPaths, p)
}
}
if len(childPaths) != 2 {
t.Fatalf("the tier-2 archive names %d child archives, want 2:\n%s", len(childPaths), t2body)
}
foundOriginal := false
for _, p := range childPaths {
raw, err := os.ReadFile(p)
if err != nil {
t.Fatalf("read child archive %s: %v", p, err)
}
if strings.Contains(string(raw), unique) {
foundOriginal = true
}
}
if !foundOriginal {
t.Fatal("the original text is not reachable by following the archive chain")
}
}
// Mixing tiers in one range absorbs only the lowest; the higher-tier block
// stays active and the panel explains why.
func TestMixedTierCompressionLeavesHigherTierActive(t *testing.T) {
opts := baseOptions()
sess, err := EnableWithSession(&opts, Options{ArchiveBaseDir: t.TempDir(), SessionID: "mixed"})
if err != nil {
t.Fatalf("EnableWithSession: %v", err)
}
body := strings.Repeat("filler content. ", 300)
tail := strings.Repeat("recent tail. ", 400)
msgs := []llm.Message{userText("the task")}
for range 9 {
msgs = append(msgs, llm.Message{Role: llm.RoleAssistant,
Content: []llm.ContentBlock{llm.TextBlock(body)}})
}
for range 6 {
msgs = append(msgs, userText(tail))
}
// Three tier-1 blocks.
for i, span := range [][2]string{{"m00002", "m00003"}, {"m00004", "m00005"}, {"m00006", "m00007"}} {
sess.View(msgs)
p := compress(t, sess, "c"+string(rune('1'+i)), map[string]any{
"startId": span[0], "endId": span[1], "summary": longSummary,
})
if noa.PanelBlockCount(p) != 1 {
t.Fatalf("compression %d produced no block:\n%s", i, p)
}
}
ids := blockIDs(sess.State(), 1)
if len(ids) != 3 {
t.Fatalf("got %v, want three tier-1 blocks", ids)
}
// Promote the middle one to tier 2 on its own.
sess.View(msgs)
p := compress(t, sess, "promote", map[string]any{
"startId": ids[1], "endId": ids[1], "summary": longSummary,
})
if noa.PanelBlockCount(p) != 1 {
t.Fatalf("promotion produced no block:\n%s", p)
}
t2ids := blockIDs(sess.State(), 2)
if len(t2ids) != 1 {
t.Fatalf("got %v tier-2 blocks, want exactly one", t2ids)
}
// Now span everything: the tier-2 block sits inside the range but must not
// be absorbed.
remaining := blockIDs(sess.State(), 1)
if len(remaining) != 2 {
t.Fatalf("got %v remaining tier-1 blocks, want 2", remaining)
}
sess.View(msgs)
panel := compress(t, sess, "mix", map[string]any{
"startId": remaining[0], "endId": remaining[len(remaining)-1],
"summary": longSummary, "topic": "mixed span",
})
if noa.PanelBlockCount(panel) != 1 {
t.Fatalf("the mixed-tier compression produced no block:\n%s", panel)
}
if b := noa.FindBlock(ptr(sess.State()), t2ids[0]); b == nil || !b.Active {
t.Fatalf("%s is a tier above the target and must stay active", t2ids[0])
}
if !strings.Contains(panel, "was inside the requested range but was not consumed") {
t.Fatalf("the panel must explain why the higher-tier block survived:\n%s", panel)
}
}
func blockIDs(st noa.CompressionState, tier noa.Tier) []string {
var out []string
for _, b := range st.Blocks {
if b.Active && b.Tier == tier {
out = append(out, b.BlockID)
}
}
return out
}
func ptr(st noa.CompressionState) *noa.CompressionState { return &st }
+187
View File
@@ -0,0 +1,187 @@
package noaadapter
import (
"strings"
"testing"
"github.com/Autumn-27/norma/noa"
)
// Multi-tier compression is what keeps summaries from accumulating without
// bound: tier 1 replaces raw messages, tier 2 replaces tier-1 summaries, tier 3
// replaces tier-2 summaries.
//
// The ladder is driven entirely by the model: a tier-2 nudge names the blocks to
// consolidate and the model calls Compress on them. So "does tiering work" is
// really two questions — does the nudge fire, and can an agent act on what it
// says. These tests cover both, because a nudge nobody can parse is the same as
// no nudge at all.
// The end-to-end property: a long cooperative session advances past tier 1.
func TestLongSessionReachesTierTwo(t *testing.T) {
// 128K is the smallest shipped window where this holds; see
// TestTierTwoIsUnreachableOnSmallWindows for why 40K does not.
sess := simSession(t, 128_000)
a := newSimAgent(t, sess, 1)
for range 182 {
a.work(4000)
a.observe()
}
byTier := map[noa.Tier]int{}
for _, b := range noa.ActiveBlocks(sess.State()) {
byTier[b.Tier]++
}
if byTier[2] == 0 {
t.Fatalf("a long cooperative session produced %d tier-1 blocks and no tier-2 block "+
"(Tier2Trigger=%d). Either the tier-2 nudge stopped firing, or its target list "+
"changed shape and tierTargets no longer reads it.",
byTier[1], sess.Config().Tiers.Tier2Trigger)
}
t.Logf("active blocks by tier: %v", byTier)
}
// The tier nudge's target list is a different format from the block map
// (FormatTierTargetBlocks vs FormatBlockMap). An agent that reads the wrong one
// finds nothing and silently does nothing — the whole ladder then looks broken
// while every decision underneath it is correct.
//
// This pins the format the nudge actually emits, so a change to it fails here
// rather than showing up as "tiering doesn't work" much later.
func TestTierNudgeNamesItsTargetsInAReadableFormat(t *testing.T) {
sess := simSession(t, 128_000)
a := newSimAgent(t, sess, 1)
for range 182 {
a.work(4000)
view := sess.View(a.history)
nudge := findNudge(view)
if nudge == "" {
a.observe()
continue
}
if !isTierNudge(nudge) {
a.act(nudge)
continue
}
targets := tierTargets(nudge)
if len(targets) < 2 {
t.Fatalf("a tier nudge named %d target blocks; an agent has nothing to act on.\n"+
"nudge tail:\n%s", len(targets), tail(nudge, 600))
}
// Every named target must be a block that exists and is active, or the
// model is being pointed at something it cannot compress.
active := map[string]noa.Tier{}
for _, b := range noa.ActiveBlocks(sess.State()) {
active[b.BlockID] = b.Tier
}
for _, id := range targets {
if _, ok := active[id]; !ok {
t.Fatalf("the tier nudge names %s, which is not an active block", id)
}
}
return
}
t.Skip("no tier nudge fired in this run")
}
// The gap that remains: on a small window tier 2 never fires, for two reasons
// that are both absolute constants sized for a 200K window.
//
// - The session lives above MaxContextLimitPct, so decidePressure runs, and it
// picks the tier with the most pending tokens. Tier 1 is raw content and
// tier 2 is the ~10:1 summary of it, so tier 1 wins every comparison. (The
// count-based Tier2Trigger that exists precisely to correct this lives only
// in decideGrowth, which pressure skips.)
// - When tier 1 IS exhausted, the tier-1 summaries total a few thousand tokens
// — a large share of a small window, but under the flat 5000-token
// minPressureBenefit, so the nudge is declined as not worth a turn.
//
// This test documents the boundary rather than asserting a fix. If a window this
// small is not a supported configuration, it can be deleted; if it is, the two
// constants need to scale (see noa.TestSuppressionReleaseFitsInsideTheWindow for
// the same pattern in the nudge cadence).
func TestTierTwoIsUnreachableOnSmallWindows(t *testing.T) {
const window = 40_000
sess := simSession(t, window)
a := newSimAgent(t, sess, 1)
for range 120 {
a.work(4000)
a.observe()
}
byTier := map[noa.Tier]int{}
summaryTokens := 0
for _, b := range noa.ActiveBlocks(sess.State()) {
byTier[b.Tier]++
if b.Tier == 1 {
summaryTokens += noa.DefaultCountTokens(b.Summary)
}
}
minBen := max(5000, window/100)
if byTier[2] > 0 {
t.Fatalf("tier 2 now fires at a %d window (blocks %v) — the documented limitation is "+
"fixed and this test should be replaced by an assertion that it keeps working",
window, byTier)
}
t.Logf("window=%d: %d tier-1 blocks holding %d summary tokens (%.0f%% of the window), "+
"below the flat minPressureBenefit of %d — tier 2 is declined as not worth a turn",
window, byTier[1], summaryTokens, float64(summaryTokens)*100/window, minBen)
}
// Consolidation must actually pay: a tier-2 block has to be smaller than the
// tier-1 summaries it absorbed, or the ladder costs turns and reclaims nothing.
func TestTierTwoConsolidationReclaimsTokens(t *testing.T) {
sess := simSession(t, 200_000)
a := newSimAgent(t, sess, 1)
for range 285 {
a.work(4000)
a.observe()
}
st := sess.State()
byID := map[string]noa.CompressionBlock{}
for _, b := range st.Blocks {
byID[b.BlockID] = b
}
checked := 0
for _, b := range noa.ActiveBlocks(st) {
if b.Tier < 2 {
continue
}
absorbed := 0
for _, childID := range b.DirectBlockIDs {
child, ok := byID[childID]
if !ok {
t.Fatalf("block %s names child %s, which is not in the ledger", b.BlockID, childID)
}
absorbed += noa.DefaultCountTokens(child.Summary)
}
own := noa.DefaultCountTokens(b.Summary)
if absorbed == 0 {
t.Fatalf("tier-%d block %s absorbed no child summaries", b.Tier, b.BlockID)
}
if own >= absorbed {
t.Fatalf("tier-%d block %s costs %d tokens to replace %d tokens of tier-1 summaries; "+
"consolidation made the context bigger", b.Tier, b.BlockID, own, absorbed)
}
checked++
t.Logf("%s (T%d): %d child summaries, %d → %d tokens (%.1fx)",
b.BlockID, b.Tier, len(b.DirectBlockIDs), absorbed, own, float64(absorbed)/float64(own))
}
if checked == 0 {
t.Skip("no tier-2 block formed in this run")
}
}
func isTierNudge(nudge string) bool {
return strings.Contains(nudge, "DISTILLATION TRIGGER") ||
strings.Contains(nudge, "CONDENSATION TRIGGER")
}
func tail(s string, n int) string {
if len(s) <= n {
return s
}
return "…" + s[len(s)-n:]
}
+136
View File
@@ -0,0 +1,136 @@
package noaadapter
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/noa"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
)
// newCompressTool builds the one tool noa exposes.
func newCompressTool(sess *Session) tool.CoreTool {
return tool.Build(tool.Spec{
Name: noa.CompressToolName,
Description: noa.CompressToolDescription,
Schema: noa.CompressToolSchema(),
// The model's arguments reach runCompress exactly as they arrived.
//
// ParseCompressArgs exists to recover ranges from a call a provider
// mangled — truncated mid-object, wrapped in a code fence, carrying a
// trailing comma, or with the array stringified. None of those is valid
// JSON, so the harness's schema check would reject them first and the
// recovery would never run; the model would get "invalid tool input"
// instead of the shape guidance formatParseError writes, and the turn's
// one compression attempt would be spent on a validation error.
//
// The schema is still advertised (Schema above), so the model knows what
// to aim for. This only removes the gate, not the instruction.
RawInput: true,
// Not read-only: it mutates session state and writes archives.
ReadOnly: func(json.RawMessage) bool { return false },
// Not concurrency-safe: two compressions racing on the same state would
// interleave block allocation and coverage.
Concurrent: func(json.RawMessage) bool { return false },
// No permission prompt: it touches only noa's own archive directory, and
// asking would interrupt the very flow it exists to keep smooth.
Permissions: func(context.Context, json.RawMessage, permission.Context) permission.Decision {
return permission.Decision{Behavior: permission.Allow}
},
Run: func(ctx context.Context, input json.RawMessage, tc *tool.ToolContext) (tool.Result, error) {
return runCompress(sess, input, tc)
},
})
}
func runCompress(sess *Session, input json.RawMessage, tc *tool.ToolContext) (tool.Result, error) {
parsed := noa.ParseCompressArgs(input)
// A parse failure is a real error: the model produced something unusable and
// must see that, so it corrects the shape rather than the content.
if !parsed.Diagnostics.Ok && len(parsed.Ranges) == 0 {
sess.recordParseFailure()
return errorResult(formatParseError(parsed.Diagnostics)), nil
}
if len(parsed.Ranges) == 0 {
// Neither success nor failure: a valid question with a valid answer.
// Counting it either way would distort the failure ladder.
return textResult(noa.NoRangesMessage), nil
}
// A range set that has already failed twice will fail identically again;
// refusing it outright costs one short message instead of a whole turn.
if refusal := sess.checkDeadRange(parsed.Ranges); refusal != "" {
sess.recordParseFailure()
return errorResult(refusal), nil
}
callID := ""
if tc != nil {
callID = tc.ToolUseID
}
before := sess.tokensBefore()
res := sess.applyCompression(parsed.Ranges, callID)
after := before - res.TokensCompressed
panel := noa.FormatPanel(noa.PanelInput{
Result: res, BeforeTokens: before, AfterTokens: max(after, 0),
})
if parsed.Diagnostics.Salvaged || parsed.Diagnostics.TailRepaired {
panel += "\n note: the arguments were malformed and were repaired before parsing; " +
"check the call shape if this recurs."
}
// A panel is not an error even when it reports nothing created — the call was
// well-formed. But it reclaimed nothing, so the failure ladder must still
// count it, which applyCompression already did.
return textResult(panel), nil
}
// formatParseError tells the model what shape its arguments arrived in.
func formatParseError(d noa.CompressParseDiagnostics) string {
var b strings.Builder
switch d.Kind {
case noa.ParseEmptyInput:
b.WriteString("Compress received no arguments.")
case noa.ParseMissingContent:
b.WriteString("Compress arguments have no `content` field.")
case noa.ParseContentNotList:
b.WriteString("Compress `content` is neither an array of ranges nor a JSON-encoded one.")
case noa.ParseNoValidRanges:
b.WriteString("No usable ranges: every entry was missing startId, endId or summary.")
case noa.ParseTruncated:
b.WriteString("The arguments were cut off mid-object and could not be salvaged.")
default:
b.WriteString("Compress arguments could not be parsed as JSON.")
}
b.WriteString(" Expected shape: " +
`{ "content": [{ "startId": "m00012", "endId": "m00045", "summary": "..." }] }`)
if d.InvalidItems > 0 {
fmt.Fprintf(&b, "\n%d entr%s dropped: %s", d.InvalidItems,
plural(d.InvalidItems, "y was", "ies were"), strings.Join(d.InvalidReasons, "; "))
}
if d.RawPrefix != "" {
fmt.Fprintf(&b, "\nReceived (first %d chars): %s", len(d.RawPrefix), d.RawPrefix)
}
return b.String()
}
func plural(n int, one, many string) string {
if n == 1 {
return one
}
return many
}
func textResult(s string) tool.Result {
return tool.Result{Content: []llm.ContentBlock{llm.TextBlock(s)}}
}
func errorResult(s string) tool.Result {
return tool.Result{Content: []llm.ContentBlock{llm.TextBlock(s)}, IsError: true}
}
+212
View File
@@ -0,0 +1,212 @@
package noaadapter
import (
"encoding/json"
"strings"
"testing"
"github.com/Autumn-27/norma/noa"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
)
// harness.execOne validates a call against the tool's InputSchema before
// dispatching it (harness/tools.go), so a test that calls runCompress directly
// is testing a path the model may not be able to reach. These tests put the
// arguments through the same gate the harness uses, so the lenient parsing the
// rest of the suite exercises is known to be reachable in production.
//
// Compress opts out of that gate (tool.Spec.RawInput) because the shapes it
// exists to repair are, by definition, not valid JSON. The opt-out is asserted
// here rather than assumed.
// gate mirrors harness.execOne's validation step exactly, including the
// AcceptsRawInput opt-out the harness consults first.
func gate(t *testing.T, input string) error {
t.Helper()
ct := newCompressTool(simSession(t, 40000))
if r, ok := ct.(interface{ AcceptsRawInput() bool }); ok && r.AcceptsRawInput() {
return nil
}
return tool.ValidateInput(ct.InputSchema(), json.RawMessage(input))
}
// The opt-out has to be on, or every lenient-parsing test below is testing a
// path production cannot reach.
func TestCompressOptsOutOfSchemaValidation(t *testing.T) {
ct := newCompressTool(simSession(t, 40000))
r, ok := ct.(interface{ AcceptsRawInput() bool })
if !ok || !r.AcceptsRawInput() {
t.Fatal("Compress does not report AcceptsRawInput, so harness.execOne validates its " +
"arguments and ParseCompressArgs never sees a malformed call")
}
// The schema must still be advertised: it is what tells the model the shape
// to aim for, and dropping it would be a much worse trade than the gate.
if ct.InputSchema() == nil {
t.Fatal("Compress advertises no schema; the model has nothing to aim for")
}
if _, ok := ct.InputSchema()["properties"]; !ok {
t.Fatalf("the advertised schema has no properties: %v", ct.InputSchema())
}
}
// The lenient parser exists to recover ranges from arguments a provider mangled.
// That recovery is only worth anything if the mangled arguments can REACH it.
//
// So: anything ParseCompressArgs can salvage must survive the schema gate.
// Where it does not, the salvage code is unreachable in production and the model
// gets the harness's terse validation error instead of noa's repair guidance.
func TestSalvageableArgumentsSurviveTheSchemaGate(t *testing.T) {
// Every one of these is a shape ParseCompressArgs is built to repair.
corpus := map[string]string{
"array of ranges": `{"content":[{"startId":"m00001","endId":"m00009","summary":"s"}]}`,
"JSON-encoded array": `{"content":"[{\"startId\":\"m00001\",\"endId\":\"m00009\",\"summary\":\"s\"}]"}`,
"trailing commas": `{"content":[{"startId":"m00001","endId":"m00009","summary":"s",},],}`,
"fenced in markdown": "```json\n{\"content\":[{\"startId\":\"m00001\",\"endId\":\"m00009\",\"summary\":\"s\"}]}\n```",
"truncated mid-object": `{"content":[{"startId":"m00001","endId":"m00009","summary":"first"},{"startId":"m00010","end`,
"double-encoded whole": `"{\"content\":[{\"startId\":\"m00001\",\"endId\":\"m00009\",\"summary\":\"s\"}]}"`,
"unterminated inner": `{"content":"[{\"startId\":\"m00001\",\"endId\":\"m00009\",\"summary\":\"s\"]"}`,
"raw newline in summary": "{\"content\":[{\"startId\":\"m00001\",\"endId\":\"m00009\",\"summary\":\"line one\nline two\"}]}",
}
var blocked []string
for name, args := range corpus {
parsed := noa.ParseCompressArgs([]byte(args))
if len(parsed.Ranges) == 0 {
t.Errorf("%s: the parser recovered nothing; the corpus entry is wrong", name)
continue
}
if err := gate(t, args); err != nil {
blocked = append(blocked, name+": "+err.Error())
}
}
if len(blocked) > 0 {
t.Fatalf("the schema gate rejects %d argument shapes the parser can repair, so the "+
"repair never runs in production and the model sees a bare validation error "+
"instead of noa's guidance:\n %s", len(blocked), strings.Join(blocked, "\n "))
}
}
// The other half: shapes the parser correctly REJECTS must still reach it, so
// the model gets formatParseError's "expected shape" — which names Compress's
// contract — rather than a schema message that does not.
func TestUnparseableArgumentsReachNoasDiagnostics(t *testing.T) {
corpus := map[string]string{
"no content field": `{"topic":"t"}`,
"content is object": `{"content":{"startId":"m00001"}}`,
"empty input": ``,
"ranges incomplete": `{"content":[{"startId":"m00001"}]}`,
}
for name, args := range corpus {
t.Run(name, func(t *testing.T) {
if err := gate(t, args); err != nil {
t.Fatalf("the gate answered before noa did (%v), so formatParseError never runs "+
"and the model is told nothing about the shape Compress wants", err)
}
res, err := runCompress(simSession(t, 40000), json.RawMessage(args), nil)
if err != nil {
t.Fatalf("runCompress returned a Go error: %v", err)
}
if !res.IsError {
t.Fatalf("unparseable arguments produced a success result: %s", res.Content[0].Text)
}
if !strings.Contains(res.Content[0].Text, "Expected shape:") {
t.Fatalf("the model is not told the expected shape:\n%s", res.Content[0].Text)
}
})
}
}
// A parse failure feeds the failure ladder (recordParseFailure). If the gate
// answers first, the ladder never counts it — so a model stuck emitting a broken
// shape is never detected as stuck by the mechanism built to detect exactly that.
func TestParseFailuresReachTheFailureLadder(t *testing.T) {
sess := simSession(t, 40000)
broken := `{"content":[{"startId":"m00001","endId":"m00009","summ`
if err := gate(t, broken); err != nil {
t.Skipf("the gate rejects this before the tool runs (%v); "+
"TestSalvageableArgumentsSurviveTheSchemaGate is the test that covers the consequence", err)
}
before := sess.attempts
if _, err := runCompress(sess, json.RawMessage(broken), nil); err != nil {
t.Fatalf("runCompress returned a Go error: %v", err)
}
if sess.attempts <= before {
t.Fatalf("the attempt counter stayed at %d after an unparseable call; "+
"the ladder cannot notice a model that is stuck", before)
}
}
// The full production path, exercised the way the harness does it: resolve the
// built tool, validate, check permissions and concurrency, then Run with a real
// ToolContext. Tests that call runCompress skip all of this.
func TestCompressToolThroughTheBuiltToolInterface(t *testing.T) {
sess := simSession(t, 40000)
a := newSimAgent(t, sess, 1000000) // build history without compressing
for range 12 {
a.work(4000)
a.observe()
}
ct := newCompressTool(sess)
if ct.Name() != noa.CompressToolName {
t.Fatalf("tool name = %q, want %q", ct.Name(), noa.CompressToolName)
}
// A range wide enough to clear the minimum-content rule, well clear of the
// protected tail.
refs := sess.State().MessageRefs
if len(refs.ByRef) < 16 {
t.Fatalf("only %d refs assigned; the fixture is too short", len(refs.ByRef))
}
args, _ := json.Marshal(map[string]any{"content": []map[string]any{{
"startId": noa.IndexToRef(2), "endId": noa.IndexToRef(13),
"summary": a.summary("through the tool interface"),
}}})
if err := tool.ValidateInput(ct.InputSchema(), args); err != nil {
t.Fatalf("a well-formed call failed schema validation: %v", err)
}
if ct.IsReadOnly(args) {
t.Fatal("Compress reports read-only; it writes archives and mutates state")
}
if ct.IsConcurrencySafe(args) {
t.Fatal("Compress reports concurrency-safe; two racing compressions would interleave block allocation")
}
res, err := ct.Call(t.Context(), args, &tool.ToolContext{ToolUseID: "toolu_gate_1"})
if err != nil {
t.Fatalf("Run: %v", err)
}
if res.IsError {
t.Fatalf("a well-formed compression reported an error: %s", res.Content[0].Text)
}
if n := noa.PanelBlockCount(res.Content[0].Text); n != 1 {
t.Fatalf("panel reports %d blocks, want 1:\n%s", n, res.Content[0].Text)
}
// The ToolUseID must have been carried into the block, or hide-compress-calls
// cannot find the call to hide and RebuildStateFromLog cannot replay it.
blocks := noa.ActiveBlocks(sess.State())
if len(blocks) != 1 {
t.Fatalf("%d active blocks, want 1", len(blocks))
}
if blocks[0].CompressCallID != "toolu_gate_1" {
t.Fatalf("block records CompressCallID %q, want the ToolContext's %q — "+
"without it the call cannot be hidden or replayed",
blocks[0].CompressCallID, "toolu_gate_1")
}
}
// The permission decision must be Allow without asking. A prompt here would
// interrupt the flow the tool exists to keep smooth, and in a headless run it
// would hang.
func TestCompressNeverPromptsForPermission(t *testing.T) {
sess := simSession(t, 40000)
ct := newCompressTool(sess)
dec := ct.CheckPermissions(t.Context(), json.RawMessage(`{"content":[]}`), permission.Context{})
if dec.Behavior != permission.Allow {
t.Fatalf("permission behavior = %s, want allow", dec.Behavior)
}
}