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

+554
View File
@@ -0,0 +1,554 @@
// Package agentcore is the public entry point of the SDK. It aggregates the
// provider, tools, permission policy, and hooks into a stateful Session whose
// Prompt method streams the agent loop as a range-over-func iterator. The SDK
// injects no preset system prompt: the host controls it entirely via
// Options.SystemPrompt (design decision 1).
package agentcore
import (
"context"
"errors"
"iter"
"strings"
"time"
"github.com/Autumn-27/norma/compaction"
"github.com/Autumn-27/norma/harness"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/memory"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/plan"
"github.com/Autumn-27/norma/skill"
"github.com/Autumn-27/norma/tool"
"github.com/Autumn-27/norma/transcript"
)
// Options configures a Session (FR-07).
type Options struct {
// Provider is the LLM backend (any Anthropic- or OpenAI-format endpoint, or
// a custom implementation).
Provider llm.Provider
// SystemPrompt is the host-controlled system prompt, in segments. The SDK
// injects nothing of its own. AppendSystemPrompt is added after it (e.g. for
// SDK-managed dynamic context). DynamicBoundary marks the cacheable prefix.
SystemPrompt []string
AppendSystemPrompt []string
DynamicBoundary int
// Tools the agent may call. Defaults to tool.DefaultTools().
Tools []tool.CoreTool
// DeferredTools names tools whose schemas are withheld from the model (only
// their names surface, e.g. via tool.RenderDeferredToolsBlock placed in the
// system prompt). They stay callable through the auto-added ExecuteExtraTool
// after discovery via SearchExtraTools. When non-empty the SDK auto-adds those
// two access tools. Empty = classic behavior (all tool schemas sent).
DeferredTools []string
// UnlockSet gates which deferred tools are currently callable via
// ExecuteExtraTool. Nil + non-empty DeferredTools → the SDK seeds one with all
// DeferredTools unlocked. Hosts doing skill-gated disclosure pass their own set
// (seeded with the globally-available subset) and Add() to it when a skill loads.
UnlockSet *tool.UnlockSet
// Permission policy.
CanUseTool permission.CanUseTool
AllowedTools []string
DisallowedTools []string
PermissionMode permission.Mode
// Hooks is optional lifecycle instrumentation (Phase 3).
Hooks harness.HookRunner
// Compaction, when non-nil, enables automatic context-window management,
// summarizing with the same Provider. Ignored when Compactor is set.
Compaction *compaction.Config
// Compactor lets the host take over context management entirely. Setting it
// means "I manage the context myself": the built-in Compaction is IGNORED.
// The two are mutually exclusive — the session holds a single compactor, so
// they can never both run.
//
// A Compactor that also implements harness.ContextView builds the request
// message array itself, replacing llm.MessagesForAPI.
Compactor harness.Compactor
// OnWarn, when set, receives configuration warnings raised while building the
// session — misconfigurations the SDK works around rather than rejecting. The
// SDK writes nothing to stdout/stderr on its own, so a host that wants to see
// these must wire them somewhere (log.Printf, a structured logger, a test
// buffer). Called synchronously during NewSession.
OnWarn func(string)
// Plan, when non-nil, enables plan mode (read-only exploration → approval →
// implementation) with EnterPlanMode/ExitPlanMode tools.
Plan *PlanOptions
// Memory, when non-nil, enables persistent long-term memory with
// RecallMemory/RecordMemory tools and optional auto-injection.
Memory *MemoryOptions
// Skills, when non-nil, exposes a Skill tool for invoking named procedures.
Skills *skill.Registry
// EnableWebFetch adds the network-facing WebFetch tool (permission-gated).
EnableWebFetch bool
// WebFetchProxy, when set, routes WebFetch requests through this http(s) proxy
// URL (e.g. a recording/intercepting proxy). Empty = direct connection.
WebFetchProxy string
// WebFetchCACert is a path to a PEM CA cert WebFetch adds to the system trust
// pool — verifies HTTPS through a MITM proxy without disabling TLS (preferred
// over WebFetchInsecureTLS).
WebFetchCACert string
// WebFetchInsecureTLS skips TLS verification for WebFetch (curl -k). Blunt
// fallback when no CA cert is available; prefer WebFetchCACert.
WebFetchInsecureTLS bool
// EnableWebSearch adds the network-facing web_search tool (permission-gated).
EnableWebSearch bool
// WebSearchBackend selects the search backend: "ddgs" (DuckDuckGo, no key),
// "brave-free" (Brave Search API), "tavily" (Tavily Search API), or
// "deepseek" (DeepSeek's server-side search). Empty defaults to "ddgs".
WebSearchBackend string
// BraveSearchAPIKey authenticates the "brave-free" backend. Required only when
// WebSearchBackend == "brave-free".
BraveSearchAPIKey string
// TavilySearchAPIKey authenticates the "tavily" backend. Required only when
// WebSearchBackend == "tavily".
TavilySearchAPIKey string
// DeepSeekSearch* configure the "deepseek" backend, which has no search API
// of its own: it spends one call on DeepSeek's Anthropic-format messages
// endpoint per search (the web_search_20250305 server tool). BaseURL must be
// the Anthropic-format root — DeepSeek's OpenAI-format endpoint rejects
// server tools. All three are required when WebSearchBackend == "deepseek".
DeepSeekSearchBaseURL string
DeepSeekSearchAPIKey string
DeepSeekSearchModel string
// WebSearchProxy, when set, routes web_search requests through this http(s)
// proxy URL — useful when the search endpoint is only reachable via a proxy.
WebSearchProxy string
// WebSearchCACert / WebSearchInsecureTLS mirror the WebFetch TLS options for
// web_search when it runs through a MITM/recording proxy (prefer the CA cert).
WebSearchCACert string
WebSearchInsecureTLS bool
// Todos, when non-nil, adds the TodoWrite tool backed by this store, letting
// the host observe the agent's plan/progress via Todos.List().
Todos *tool.TodoStore
// AskUser, when non-nil, adds the AskUserQuestion tool so the agent can pause
// a long task to ask the user a structured multiple-choice question.
AskUser tool.AskUserFunc
// SystemReminderFunc, when set, is called before each Prompt and its return
// value is included in the <system-reminder> prepended to the conversation.
// The SDK always injects today's date into the reminder regardless of whether
// this is set. Return "" to include only the date.
SystemReminderFunc func() string
MaxTurns int
// MaxDuration bounds wall-clock run time, checked at the turn boundary (never
// mid-stream), so a run ends cleanly rather than being aborted in flight (0 = off).
MaxDuration time.Duration
// Settlement, when set with a Prompt, runs a bounded wrap-up phase when a budget
// (MaxTurns/MaxDuration) is hit — injecting the prompt and hiding DisabledTools —
// so a budget-terminated run checkpoints its findings. See harness.Settlement.
Settlement *harness.Settlement
MaxTokens int
Temperature *float64
MaxConcurrency int
WorkingDir string
// ToolOutputDir, when set, makes oversized tool output spill to a file there
// (full content preserved) and the tool return a head + pointer instead of
// discarding the overflow (tool.Capture). MaxToolOutputChars caps the head
// size fed to the model (0 = default 30000).
ToolOutputDir string
MaxToolOutputChars int
// BashEnv holds extra "KEY=VALUE" entries injected into the environment of
// Bash subprocesses (foreground + background), overriding inherited values.
// The agent's own process env is untouched. Empty = inherit unchanged. Used
// e.g. to route child-command HTTP through a proxy and trust its CA.
BashEnv []string
// Transcript, when non-nil, persists the conversation to an append-only
// JSONL log so the session can be resumed (see Session.Resume). Subagents
// write their own sidechain files under the same store.
Transcript *transcript.Store
// SessionID names the transcript file. Empty generates a fresh id (read it
// back via Session.SessionID).
SessionID string
// TokenBudget, when > 0, lets the agent keep working (with budget nudges)
// after it would otherwise stop, until ~90% of the output-token budget or
// diminishing returns.
TokenBudget int
// EscalateMaxTokens retries a max_tokens truncation with a raised output cap
// before falling back to resume-recovery.
EscalateMaxTokens bool
// DisableBackgroundTasks, when true, prevents the SDK from injecting the
// background-task management tools (TaskOutput, TaskStop, TaskList, Monitor)
// into this session's registry. Use for focused single-purpose agents (e.g.
// goal decomposers, structured-output callers) that should only see the tools
// explicitly provided in Options.Tools. The global AGENT_CORE_DISABLE_BACKGROUND_TASKS
// env var disables them for every session; this field is the per-session equivalent.
DisableBackgroundTasks bool
// NonStreaming runs every model call as a single non-streaming request
// (Provider.Complete) instead of a token stream. The host still receives the
// same event sequence (text/thinking/tool_use/usage), just delivered when the
// full response arrives rather than incrementally. Zero value = streaming.
NonStreaming bool
// Deps optionally overrides side-effect boundaries (testing/advanced use).
Deps harness.QueryDeps
}
// PlanOptions configures plan mode.
type PlanOptions struct {
// Approver decides whether a presented plan is accepted. Nil auto-approves.
Approver plan.Approver
// StartInPlanMode begins the session read-only (the agent must ExitPlanMode
// to implement). If false, the agent enters plan mode itself via EnterPlanMode.
StartInPlanMode bool
// TargetMode is the permission mode after approval (default acceptEdits).
TargetMode permission.Mode
}
// MemoryOptions configures long-term memory.
type MemoryOptions struct {
Store *memory.Store
// AutoInject prepends memories relevant to each prompt into the conversation.
AutoInject bool
// MaxInject caps auto-injected memories (default 3).
MaxInject int
// IncludeIndexInPrompt adds the memory index to the system prompt.
IncludeIndexInPrompt bool
}
// Session is a long-lived conversation. Call Prompt repeatedly; state
// (messages, usage) persists across calls (FR-07.1/2). Not safe for concurrent
// Prompt calls on the same Session.
type Session struct {
opts Options
registry *tool.Registry
compactor harness.Compactor
planCtrl *plan.Controller
messages []llm.Message
usage llm.Usage
sessionID string
store *transcript.Store
writer *transcript.Writer
tasks *tool.Manager
unlock *tool.UnlockSet // deferred-tool call gate (nil when no deferred tools)
}
// NewSession builds a Session, applying defaults.
func NewSession(opts Options) *Session {
tools := opts.Tools
if tools == nil {
tools = tool.DefaultTools()
}
if opts.PermissionMode == "" {
opts.PermissionMode = permission.ModeDefault
}
s := &Session{opts: opts}
// Exactly one context manager. Compactor (host-supplied) wins over the
// built-in Compaction: a session holds a single compactor, so the two can
// never both run — which matters because they have incompatible contracts
// (Compaction rewrites l.messages in place; a ContextView must not).
if opts.Compactor != nil {
if opts.Compaction != nil {
s.warn("both Compactor and Compaction are set — Compaction is IGNORED. " +
"They are mutually exclusive context managers; set only one.")
}
s.compactor = opts.Compactor
} else if opts.Compaction != nil {
s.compactor = compaction.New(*opts.Compaction, compaction.ProviderSummarizer(opts.Provider, opts.MaxTokens, opts.NonStreaming))
}
if opts.Plan != nil {
start := opts.PermissionMode
if opts.Plan.StartInPlanMode {
start = permission.ModePlan
}
s.planCtrl = plan.NewController(start, opts.Plan.TargetMode)
tools = append(tools, plan.Tools(s.planCtrl, opts.Plan.Approver)...)
}
if opts.Memory != nil && opts.Memory.Store != nil {
tools = append(tools, memory.Tools(opts.Memory.Store)...)
}
if opts.Skills != nil {
tools = append(tools, opts.Skills.Tool())
}
if opts.EnableWebFetch {
tools = append(tools, tool.NewWebFetch(tool.WebFetchConfig{Proxy: opts.WebFetchProxy, CACert: opts.WebFetchCACert, InsecureTLS: opts.WebFetchInsecureTLS}))
}
if opts.EnableWebSearch {
// A misconfigured backend (unknown name, or brave-free without a key)
// drops the tool rather than failing the whole session — the rest of the
// agent stays usable and the missing tool surfaces the misconfig.
if ws, err := tool.NewWebSearch(tool.WebSearchConfig{Backend: opts.WebSearchBackend, BraveAPIKey: opts.BraveSearchAPIKey, TavilyAPIKey: opts.TavilySearchAPIKey, DeepSeekBaseURL: opts.DeepSeekSearchBaseURL, DeepSeekAPIKey: opts.DeepSeekSearchAPIKey, DeepSeekModel: opts.DeepSeekSearchModel, Proxy: opts.WebSearchProxy, CACert: opts.WebSearchCACert, InsecureTLS: opts.WebSearchInsecureTLS}); err == nil {
tools = append(tools, ws)
}
}
if opts.Todos != nil {
tools = append(tools, opts.Todos.Tool())
}
if opts.AskUser != nil {
tools = append(tools, tool.NewAskUserQuestion(opts.AskUser))
}
// A session id is always needed (it names the background-task temp dir, and
// the transcript file when persistence is on).
s.sessionID = opts.SessionID
if s.sessionID == "" {
s.sessionID = transcript.NewSessionID()
}
// Background task execution: a per-session manager plus the tools that read and
// control it. Disabled by the global AGENT_CORE_DISABLE_BACKGROUND_TASKS env var
// or by setting Options.DisableBackgroundTasks for this session only.
if !tool.BackgroundTasksDisabled() && !opts.DisableBackgroundTasks {
if mgr, err := tool.NewManager(s.sessionID); err == nil {
s.tasks = mgr
tools = append(tools, tool.NewTaskOutput(), tool.NewTaskStop(), tool.NewTaskList(), tool.NewMonitor())
}
}
s.registry = tool.NewRegistry(tools...)
// Deferred tools: withhold their schemas (harness filters by opts.DeferredTools)
// but keep them callable via the two always-loaded access tools. Both close over
// the registry (which already holds the deferred tools) and are added to it.
if len(opts.DeferredTools) > 0 {
s.unlock = opts.UnlockSet
if s.unlock == nil {
s.unlock = tool.NewUnlockSet(opts.DeferredTools...)
}
s.registry.Add(tool.NewSearchExtraTools(s.registry, opts.DeferredTools))
s.registry.Add(tool.NewExecuteExtraTool(s.registry, s.unlock))
}
if opts.Transcript != nil {
s.store = opts.Transcript
s.writer = s.store.NewWriter(s.sessionID, "")
}
return s
}
// Close releases session resources, killing any background tasks and removing
// their temporary output directory. Safe to call multiple times. Hosts running a
// long-lived Session should defer Close; Run does so automatically.
func (s *Session) Close() error {
if s.tasks != nil {
s.tasks.Cleanup()
s.tasks = nil
}
return nil
}
// Messages returns the conversation history.
func (s *Session) Messages() []llm.Message { return s.messages }
// Usage returns cumulative token usage.
func (s *Session) Usage() llm.Usage { return s.usage }
// Reset clears the conversation.
func (s *Session) Reset() { s.messages = nil; s.usage = llm.Usage{} }
// SessionID returns the transcript session id (empty if persistence is off).
func (s *Session) SessionID() string { return s.sessionID }
// UnlockSet returns the session's deferred-tool call gate (nil when no deferred
// tools). Hosts Add() to it to unlock skill-gated tools at runtime.
func (s *Session) UnlockSet() *tool.UnlockSet { return s.unlock }
// Resume reloads a prior conversation from the transcript store, rebuilding the
// message history and cumulative usage so the next Prompt continues it. Requires
// Options.Transcript to be set. Subsequent messages append to the same file.
func (s *Session) Resume(sessionID string) error {
if s.store == nil {
return errors.New("agentcore: Resume requires Options.Transcript")
}
recs, err := s.store.Load(s.store.MainPath(sessionID))
if err != nil {
return err
}
msgs, usage := transcript.Messages(recs)
s.messages = cleanResumed(msgs)
s.usage = usage
s.sessionID = sessionID
s.writer = s.store.ResumeWriter(sessionID, transcript.LastUUID(recs))
return nil
}
// cleanResumed drops trailing assistant tool calls whose results were never
// persisted — a crash mid-tool would otherwise leave a dangling tool_use that
// the API rejects.
func cleanResumed(msgs []llm.Message) []llm.Message {
for len(msgs) > 0 {
last := msgs[len(msgs)-1]
if last.Role == llm.RoleAssistant && len(last.ToolUses()) > 0 {
msgs = msgs[:len(msgs)-1]
continue
}
break
}
return msgs
}
// buildSystemReminder assembles the <system-reminder> content. Today's date is
// always included; extra is appended when non-empty.
func buildSystemReminder(extra string) string {
date := time.Now().Format("2006-01-02")
var b strings.Builder
b.WriteString("<system-reminder>\n# currentDate\nToday's date is ")
b.WriteString(date)
b.WriteString(".")
if extra != "" {
b.WriteString("\n")
b.WriteString(extra)
}
b.WriteString("\n</system-reminder>")
return b.String()
}
// warn reports a configuration warning to the host, if it asked for them.
func (s *Session) warn(msg string) {
if s.opts.OnWarn != nil {
s.opts.OnWarn("agentcore: " + msg)
}
}
func (s *Session) system() []string {
out := append([]string(nil), s.opts.SystemPrompt...)
out = append(out, s.opts.AppendSystemPrompt...)
if s.opts.Memory != nil && s.opts.Memory.Store != nil && s.opts.Memory.IncludeIndexInPrompt {
out = append(out, s.opts.Memory.Store.SystemSegment())
}
return out
}
// hookFirer is the optional host-fired subset of the hook system.
type hookFirer interface {
FireSessionStart(context.Context)
FireUserPromptSubmit(context.Context, string) string
}
// Prompt appends a user message and streams the agent loop to completion. The
// final event is KindResult; Session state is updated when the consumer reaches
// it (FR-07.3).
func (s *Session) Prompt(ctx context.Context, input string) iter.Seq2[harness.Event, error] {
// Auto-inject memories relevant to this prompt (Phase 4).
if s.opts.Memory != nil && s.opts.Memory.AutoInject && s.opts.Memory.Store != nil {
max := s.opts.Memory.MaxInject
if max <= 0 {
max = 3
}
if mems := s.opts.Memory.Store.Relevant(input, max); len(mems) > 0 {
input = input + "\n\n" + memory.RenderForInjection(mems, time.Now())
}
}
// UserPromptSubmit hooks may inject additional context (FR-08.2).
if hf, ok := s.opts.Hooks.(hookFirer); ok {
if len(s.messages) == 0 {
hf.FireSessionStart(ctx)
}
if extra := hf.FireUserPromptSubmit(ctx, input); extra != "" {
input = input + "\n\n" + extra
}
}
// Surface any background-task completions that landed since the previous turn
// returned, before the new user message.
if s.tasks != nil {
if notes := s.tasks.DrainNotifications(); len(notes) > 0 {
var b strings.Builder
for i, n := range notes {
if i > 0 {
b.WriteString("\n")
}
b.WriteString(n.String())
}
nm := llm.UserText(b.String())
s.messages = append(s.messages, nm)
if s.writer != nil {
s.writer.RecordMessage(nm, llm.Usage{})
}
}
}
userMsg := llm.UserText(input)
s.messages = append(s.messages, userMsg)
if s.writer != nil {
s.writer.RecordMessage(userMsg, llm.Usage{})
ctx = transcript.WithSessionID(ctx, s.sessionID)
}
var reminderExtra string
if s.opts.SystemReminderFunc != nil {
reminderExtra = s.opts.SystemReminderFunc()
}
in := harness.QueryInput{
Provider: s.opts.Provider,
System: s.system(),
DynamicBoundary: s.opts.DynamicBoundary,
Messages: s.messages,
SystemReminder: buildSystemReminder(reminderExtra),
Tools: s.registry,
DeferredTools: s.opts.DeferredTools,
MaxTokens: s.opts.MaxTokens,
Temperature: s.opts.Temperature,
MaxTurns: s.opts.MaxTurns,
MaxDuration: s.opts.MaxDuration,
Settlement: s.opts.Settlement,
MaxConcurrency: s.opts.MaxConcurrency,
WorkingDir: s.opts.WorkingDir,
Todos: s.opts.Todos,
ToolOutputDir: s.opts.ToolOutputDir,
MaxToolOutputChars: s.opts.MaxToolOutputChars,
Tasks: s.tasks,
BashEnv: s.opts.BashEnv,
PermissionMode: s.opts.PermissionMode,
Allowed: s.opts.AllowedTools,
Disallowed: s.opts.DisallowedTools,
CanUseTool: s.opts.CanUseTool,
Hooks: s.opts.Hooks,
Compactor: s.compactor,
TokenBudget: s.opts.TokenBudget,
EscalateMaxTokens: s.opts.EscalateMaxTokens,
NonStreaming: s.opts.NonStreaming,
}
if s.writer != nil {
in.Recorder = s.writer
}
if s.planCtrl != nil {
in.PermissionModeFunc = s.planCtrl.Mode
}
inner := harness.Query(ctx, in, s.opts.Deps)
return func(yield func(harness.Event, error) bool) {
for ev, err := range inner {
if ev.Kind == harness.KindResult && ev.Terminal != nil {
s.messages = ev.Terminal.Messages
s.usage = ev.Terminal.Usage
}
if !yield(ev, err) {
return
}
}
}
}
// Run is a one-shot convenience: it creates a Session, runs a single prompt to
// completion, and returns the assistant's final text (FR-07.4).
func Run(ctx context.Context, opts Options, input string) (string, error) {
s := NewSession(opts)
defer s.Close()
var text string
var rerr error
for ev, err := range s.Prompt(ctx, input) {
if err != nil {
return "", err
}
if ev.Kind == harness.KindResult && ev.Terminal != nil {
text = ev.Terminal.Text
if ev.Terminal.Err != nil {
rerr = ev.Terminal.Err
}
}
}
return text, rerr
}
+95
View File
@@ -0,0 +1,95 @@
package agentcore
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"github.com/Autumn-27/norma/harness"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
)
func sse(lines ...string) string { return strings.Join(lines, "\n") + "\n" }
// TestEndToEnd drives the whole stack: agentcore.Session → harness loop → real
// Anthropic HTTP provider (fake SSE server) → real Bash tool, over two turns.
func TestEndToEnd(t *testing.T) {
var calls int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
n := atomic.AddInt32(&calls, 1)
if n == 1 {
w.Write([]byte(sse(
`data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"tu1","name":"Bash"}}`, ``,
`data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"command\":\"echo loop-works\"}"}}`, ``,
`data: {"type":"message_delta","delta":{"stop_reason":"tool_use"}}`, ``,
`data: {"type":"message_stop"}`, ``,
)))
return
}
body := make([]byte, r.ContentLength)
r.Body.Read(body)
if !strings.Contains(string(body), "loop-works") {
t.Errorf("second request missing tool_result")
}
w.Write([]byte(sse(
`data: {"type":"content_block_start","index":0,"content_block":{"type":"text"}}`, ``,
`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"The command ran."}}`, ``,
`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}`, ``,
`data: {"type":"message_stop"}`, ``,
)))
}))
defer srv.Close()
prov, _ := llm.NewProvider(llm.Config{Format: llm.FormatAnthropic, BaseURL: srv.URL, APIKey: "k", Model: "m"})
opts := Options{
Provider: prov,
SystemPrompt: []string{"You are a test agent."},
Tools: []tool.CoreTool{tool.NewBash()},
PermissionMode: permission.ModeBypass,
WorkingDir: t.TempDir(),
}
var sawText string
s := NewSession(opts)
for ev, err := range s.Prompt(context.Background(), "run echo") {
if err != nil {
t.Fatalf("err: %v", err)
}
if ev.Kind == harness.KindText {
sawText += ev.Text
}
}
if sawText != "The command ran." {
t.Fatalf("streamed text=%q", sawText)
}
if atomic.LoadInt32(&calls) != 2 {
t.Fatalf("model calls=%d", calls)
}
if len(s.Messages()) != 4 {
t.Fatalf("messages=%d", len(s.Messages()))
}
}
func TestRunConvenience(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte(sse(
`data: {"choices":[{"delta":{"content":"hello"},"finish_reason":null}]}`, ``,
`data: {"choices":[{"delta":{},"finish_reason":"stop"}]}`, ``,
`data: [DONE]`, ``,
)))
}))
defer srv.Close()
prov, _ := llm.NewProvider(llm.Config{Format: llm.FormatOpenAI, BaseURL: srv.URL, APIKey: "k", Model: "m"})
out, err := Run(context.Background(), Options{Provider: prov, SystemPrompt: []string{"hi"}, Tools: []tool.CoreTool{}}, "say hello")
if err != nil {
t.Fatalf("Run: %v", err)
}
if out != "hello" {
t.Fatalf("out=%q", out)
}
}
+108
View File
@@ -0,0 +1,108 @@
package agentcore
import (
"context"
"strings"
"testing"
"github.com/Autumn-27/norma/compaction"
"github.com/Autumn-27/norma/harness"
"github.com/Autumn-27/norma/llm"
)
type stubCompactor struct{}
func (stubCompactor) Pre(_ context.Context, msgs []llm.Message, _ int) []llm.Message { return msgs }
func (stubCompactor) Reactive(_ context.Context, msgs []llm.Message) ([]llm.Message, bool) {
return msgs, false
}
func (stubCompactor) IsOverflow(error) bool { return false }
// Compactor and Compaction are mutually exclusive context managers. The session
// holds exactly one, so they can never both run.
func TestCompactorWinsOverCompaction(t *testing.T) {
var warns []string
s := NewSession(Options{
Compactor: stubCompactor{},
Compaction: &compaction.Config{ContextWindow: 200000},
OnWarn: func(m string) { warns = append(warns, m) },
})
if s.compactor == nil {
t.Fatal("session has no compactor")
}
if _, ok := s.compactor.(stubCompactor); !ok {
t.Fatalf("compactor = %T, want the host-supplied stubCompactor (Compaction must be ignored)", s.compactor)
}
if len(warns) != 1 {
t.Fatalf("OnWarn called %d times, want 1 for the Compactor+Compaction clash: %v", len(warns), warns)
}
if !strings.Contains(warns[0], "Compaction is IGNORED") {
t.Fatalf("warning = %q, want it to say Compaction is ignored", warns[0])
}
}
// Setting only one of them is not a misconfiguration — no warning.
func TestNoWarnWhenOnlyOneContextManager(t *testing.T) {
for name, opts := range map[string]Options{
"compactor only": {Compactor: stubCompactor{}},
"compaction only": {Compaction: &compaction.Config{ContextWindow: 200000}},
"neither": {},
} {
var warns []string
o := opts
o.OnWarn = func(m string) { warns = append(warns, m) }
NewSession(o)
if len(warns) != 0 {
t.Fatalf("%s: OnWarn called with %v, want no warnings", name, warns)
}
}
}
// The SDK must stay silent when the host did not ask for warnings.
func TestNilOnWarnIsSafe(t *testing.T) {
s := NewSession(Options{
Compactor: stubCompactor{},
Compaction: &compaction.Config{ContextWindow: 200000},
})
if _, ok := s.compactor.(stubCompactor); !ok {
t.Fatalf("compactor = %T, want stubCompactor", s.compactor)
}
}
func TestCompactorOnly(t *testing.T) {
s := NewSession(Options{Compactor: stubCompactor{}})
if _, ok := s.compactor.(stubCompactor); !ok {
t.Fatalf("compactor = %T, want stubCompactor", s.compactor)
}
}
// Without Compactor the built-in compaction is used — the pre-noa behaviour.
func TestCompactionUsedWhenNoCompactor(t *testing.T) {
s := NewSession(Options{Compaction: &compaction.Config{ContextWindow: 200000}})
if s.compactor == nil {
t.Fatal("Compaction set but session has no compactor")
}
if _, ok := s.compactor.(*compaction.Compactor); !ok {
t.Fatalf("compactor = %T, want *compaction.Compactor", s.compactor)
}
}
func TestNoContextManagerByDefault(t *testing.T) {
s := NewSession(Options{})
if s.compactor != nil {
t.Fatalf("compactor = %T, want nil when neither Compactor nor Compaction is set", s.compactor)
}
}
// A plain Compactor must not accidentally satisfy ContextView: hosts opt into
// taking over the projection by implementing the extra method.
func TestPlainCompactorIsNotContextView(t *testing.T) {
var c harness.Compactor = stubCompactor{}
if _, ok := c.(harness.ContextView); ok {
t.Fatal("stubCompactor unexpectedly satisfies harness.ContextView")
}
var built harness.Compactor = compaction.New(compaction.Config{}, nil)
if _, ok := built.(harness.ContextView); ok {
t.Fatal("compaction.Compactor must not satisfy harness.ContextView — its Pre rewrites messages in place")
}
}
+143
View File
@@ -0,0 +1,143 @@
package agentcore
import (
"context"
"encoding/json"
"iter"
"testing"
"github.com/Autumn-27/norma/harness"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
)
func deferredEcho() tool.CoreTool {
return tool.Build(tool.Spec{
Name: "echo",
Description: "Echoes msg.",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{"msg": map[string]any{"type": "string"}},
"required": []any{"msg"},
},
Permissions: func(context.Context, json.RawMessage, permission.Context) permission.Decision {
return permission.Allowed()
},
Run: func(_ context.Context, in json.RawMessage, _ *tool.ToolContext) (tool.Result, error) {
var a struct {
Msg string `json:"msg"`
}
_ = json.Unmarshal(in, &a)
return tool.Text("echo:" + a.Msg), nil
},
})
}
// TestDeferredToolsWithheldButCallable proves the deferred mechanism end-to-end:
// the deferred tool's schema is NOT sent to the model, the two access tools ARE,
// and the model can still invoke the deferred tool via ExecuteExtraTool.
func TestDeferredToolsWithheldButCallable(t *testing.T) {
turns := [][]llm.StreamEvent{
toolTurn("e1", tool.ExecuteExtraToolName, `{"tool_name":"echo","params":{"msg":"hi"}}`),
textTurn("done"),
}
var sentSchemas []llm.ToolSchema
var n int
callModel := func(_ context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
if n == 0 {
sentSchemas = req.Tools // capture what the model was offered on turn 1
}
evs := turns[n]
n++
return func(yield func(llm.StreamEvent, error) bool) {
for _, e := range evs {
if !yield(e, nil) {
return
}
}
}
}
sess := NewSession(Options{
SystemPrompt: []string{"sys"},
Tools: []tool.CoreTool{deferredEcho()},
DeferredTools: []string{"echo"},
PermissionMode: permission.ModeBypass,
Deps: harness.QueryDeps{CallModel: callModel},
})
var results []llm.ContentBlock
for ev, err := range sess.Prompt(context.Background(), "echo hi") {
if err != nil {
t.Fatalf("err: %v", err)
}
if ev.Kind == harness.KindToolResult {
results = append(results, *ev.ToolResult)
}
}
// Schema list: echo withheld; the two access tools present.
has := func(name string) bool {
for _, s := range sentSchemas {
if s.Name == name {
return true
}
}
return false
}
if has("echo") {
t.Fatal("deferred tool 'echo' schema should be withheld from the model")
}
if !has(tool.SearchExtraToolsName) || !has(tool.ExecuteExtraToolName) {
t.Fatalf("access tools missing from schema list: %+v", sentSchemas)
}
// The deferred tool still ran via ExecuteExtraTool.
if len(results) == 0 || results[0].IsError || results[0].Content[0].Text != "echo:hi" {
t.Fatalf("ExecuteExtraTool should have run echo, got %+v", results)
}
}
// TestDeferredLockedToolRejected proves unlock-set gating: a deferred tool not in
// the unlock set is refused by ExecuteExtraTool.
func TestDeferredLockedToolRejected(t *testing.T) {
turns := [][]llm.StreamEvent{
toolTurn("e1", tool.ExecuteExtraToolName, `{"tool_name":"echo","params":{"msg":"hi"}}`),
textTurn("done"),
}
var n int
callModel := func(_ context.Context, _ llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
evs := turns[n]
n++
return func(yield func(llm.StreamEvent, error) bool) {
for _, e := range evs {
if !yield(e, nil) {
return
}
}
}
}
sess := NewSession(Options{
SystemPrompt: []string{"sys"},
Tools: []tool.CoreTool{deferredEcho()},
DeferredTools: []string{"echo"},
UnlockSet: tool.NewUnlockSet(), // echo deferred but LOCKED
PermissionMode: permission.ModeBypass,
Deps: harness.QueryDeps{CallModel: callModel},
})
var results []llm.ContentBlock
for ev, err := range sess.Prompt(context.Background(), "echo hi") {
if err != nil {
t.Fatalf("err: %v", err)
}
if ev.Kind == harness.KindToolResult {
results = append(results, *ev.ToolResult)
}
}
if len(results) == 0 || !results[0].IsError {
t.Fatalf("locked deferred tool should be rejected, got %+v", results)
}
}
+125
View File
@@ -0,0 +1,125 @@
package agentcore
import (
"testing"
"github.com/Autumn-27/norma/compaction"
"github.com/Autumn-27/norma/harness"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/tool"
)
// noa is opt-in: a host that never calls noaadapter.Enable must get exactly the
// pre-noa behaviour. Every hook noa needed is additive and inert by default, and
// each of these tests pins one of them — because "inert by default" is the kind
// of property that stays true until someone adds a method.
// The load-bearing one. harness.requestMessages takes the ContextView path only
// if the compactor implements View. The built-in compaction must not: if it ever
// grew a View method, every session would silently switch to a projection that
// bypasses the boundary slice, with no config change and no error.
func TestBuiltinCompactionIsNotAContextView(t *testing.T) {
c := compaction.New(compaction.Config{ContextWindow: 200000}, nil)
if _, ok := any(c).(harness.ContextView); ok {
t.Fatal("compaction.Compactor now implements harness.ContextView, so the default " +
"session builds its requests through View instead of llm.MessagesForAPI — " +
"a silent behaviour change for every host that never opted into noa")
}
}
// Without Compactor the session must hold the built-in compaction, unwarned.
func TestNoCompactorMeansBuiltinCompactionUnchanged(t *testing.T) {
var warns []string
s := NewSession(Options{
Compaction: &compaction.Config{ContextWindow: 200000},
OnWarn: func(m string) { warns = append(warns, m) },
})
if s.compactor == nil {
t.Fatal("no compactor was installed")
}
if _, isNoa := s.compactor.(harness.ContextView); isNoa {
t.Fatal("the session installed a ContextView without being asked for one")
}
if len(warns) != 0 {
t.Fatalf("a plain Compaction setup produced warnings: %v", warns)
}
}
// Neither set is also a supported configuration and must stay silent.
func TestNoContextManagerAtAllIsSilent(t *testing.T) {
var warns []string
s := NewSession(Options{OnWarn: func(m string) { warns = append(warns, m) }})
if s.compactor != nil {
t.Fatalf("a session with no context manager installed %T", s.compactor)
}
if len(warns) != 0 {
t.Fatalf("warnings with no context manager configured: %v", warns)
}
}
// The schema gate opt-out (tool.Spec.RawInput) defaults off. Every tool that
// does not ask for it keeps being validated exactly as before.
func TestToolsDefaultToSchemaValidation(t *testing.T) {
plain := tool.Build(tool.Spec{Name: "Plain", Schema: map[string]any{"type": "object"}})
r, ok := plain.(interface{ AcceptsRawInput() bool })
if !ok {
t.Fatal("built tools no longer expose AcceptsRawInput; the harness assertion cannot work")
}
if r.AcceptsRawInput() {
t.Fatal("a tool that never set RawInput reports that it accepts raw input; " +
"schema validation is off for tools that never asked")
}
}
// The default tool set ships without the opt-out. A tool that quietly gains it
// loses its input validation, which is a security-relevant change for anything
// that shells out or touches the filesystem.
func TestDefaultToolsDoNotOptOutOfValidation(t *testing.T) {
s := NewSession(Options{WorkingDir: t.TempDir()})
if s.registry == nil {
t.Skip("no tool registry on a bare session")
}
for _, sc := range s.registry.Schemas() {
ct, ok := s.registry.Get(sc.Name)
if !ok {
continue
}
if r, ok := ct.(interface{ AcceptsRawInput() bool }); ok && r.AcceptsRawInput() {
t.Errorf("built-in tool %q accepts raw input; its arguments are no longer "+
"schema-checked before it runs", sc.Name)
}
}
}
// ToolContext gained ToolUseID for noa's benefit. It must be populated for every
// tool, not just noa's, and its presence must not change anything else.
func TestToolContextIsUnchangedApartFromToolUseID(t *testing.T) {
// A zero ToolContext is still valid: tools that ignore the field see nothing
// different from before.
tc := &tool.ToolContext{}
if tc.ToolUseID != "" {
t.Fatalf("a zero ToolContext carries ToolUseID %q", tc.ToolUseID)
}
if tc.WorkingDir != "" || tc.AgentID != "" {
t.Fatal("a zero ToolContext is no longer zero")
}
}
// llm.PairToolBlocks was exported for noa. The default request path must still
// route through it, or unpaired tool blocks would reach the provider.
func TestMessagesForAPIStillDropsUnpairedToolBlocks(t *testing.T) {
msgs := []llm.Message{
llm.UserText("hi"),
{Role: llm.RoleAssistant, Content: []llm.ContentBlock{
{Type: llm.BlockToolUse, ID: "call_orphan", Name: "Read", Input: []byte(`{}`)},
}},
}
out := llm.MessagesForAPI(msgs)
for _, m := range out {
for _, b := range m.Content {
if b.Type == llm.BlockToolUse && b.ID == "call_orphan" {
t.Fatal("an unpaired tool_use survived MessagesForAPI; providers reject those")
}
}
}
}
+92
View File
@@ -0,0 +1,92 @@
package agentcore
import (
"context"
"iter"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Autumn-27/norma/harness"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
)
// TestPlanModeGatesThenAllowsWrites proves the plan-mode lifecycle: a write is
// denied while planning, and the same write succeeds after ExitPlanMode approval
// flips the permission mode mid-loop.
func TestPlanModeGatesThenAllowsWrites(t *testing.T) {
dir := t.TempDir()
target := filepath.Join(dir, "out.txt")
turns := [][]llm.StreamEvent{
toolTurn("w1", "Write", `{"file_path":"`+jsonEsc(target)+`","content":"first"}`), // denied (plan mode)
toolTurn("p1", "ExitPlanMode", `{"plan":"write the file"}`), // approved → mode flips
toolTurn("w2", "Write", `{"file_path":"`+jsonEsc(target)+`","content":"second"}`), // now allowed
textTurn("done"),
}
var n int
callModel := func(_ context.Context, _ llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
evs := turns[n]
n++
return func(yield func(llm.StreamEvent, error) bool) {
for _, e := range evs {
if !yield(e, nil) {
return
}
}
}
}
sess := NewSession(Options{
SystemPrompt: []string{"plan first"},
Tools: []tool.CoreTool{tool.NewWrite()},
PermissionMode: permission.ModeDefault,
WorkingDir: dir,
Plan: &PlanOptions{
StartInPlanMode: true,
Approver: func(_ context.Context, _ string) (bool, string) { return true, "" },
TargetMode: permission.ModeAcceptEdits,
},
Deps: harness.QueryDeps{CallModel: callModel},
})
var results []llm.ContentBlock
for ev, err := range sess.Prompt(context.Background(), "create the file") {
if err != nil {
t.Fatalf("err: %v", err)
}
if ev.Kind == harness.KindToolResult {
results = append(results, *ev.ToolResult)
}
}
// First Write denied in plan mode.
if !results[0].IsError || !strings.Contains(results[0].Content[0].Text, "not permitted") {
t.Fatalf("first write should be denied: %+v", results[0])
}
// Second Write (after approval) succeeded.
if results[2].IsError {
t.Fatalf("second write should succeed: %+v", results[2])
}
if b, _ := os.ReadFile(target); string(b) != "second" {
t.Fatalf("file content=%q, want %q", b, "second")
}
}
func jsonEsc(s string) string { return strings.ReplaceAll(s, `\`, `\\`) }
func textTurn(s string) []llm.StreamEvent {
return []llm.StreamEvent{{Type: llm.SETextDelta, Text: s}, {Type: llm.SEMessageDelta, StopReason: "end_turn"}, {Type: llm.SEMessageStop}}
}
func toolTurn(id, name, input string) []llm.StreamEvent {
return []llm.StreamEvent{
{Type: llm.SEToolUseStart, ToolID: id, ToolName: name},
{Type: llm.SEToolInputJSON, Text: input},
{Type: llm.SEMessageDelta, StopReason: "tool_use"},
{Type: llm.SEMessageStop},
}
}
+111
View File
@@ -0,0 +1,111 @@
package agentcore
import (
"context"
"iter"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/Autumn-27/norma/harness"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
)
// TestBackgroundTaskEndToEnd proves the full Session path: a backgrounded Bash
// command is launched in one prompt, its completion notification is surfaced at
// the start of the next prompt, and Close removes the session's task directory.
func TestBackgroundTaskEndToEnd(t *testing.T) {
dir := t.TempDir()
turns := [][]llm.StreamEvent{
toolTurn("b1", "Bash", `{"command":"sleep 1; echo e2e-out","run_in_background":true}`),
textTurn("launched"), // completes prompt #1 while the task is still running
textTurn("ack"), // prompt #2; the notification is drained before this turn
}
var n int
callModel := func(_ context.Context, _ llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
evs := turns[n]
n++
return func(yield func(llm.StreamEvent, error) bool) {
for _, e := range evs {
if !yield(e, nil) {
return
}
}
}
}
sess := NewSession(Options{
SystemPrompt: []string{"go"},
Tools: []tool.CoreTool{tool.NewBash()},
PermissionMode: permission.ModeBypass,
WorkingDir: dir,
Deps: harness.QueryDeps{CallModel: callModel},
})
// The task tools are auto-registered alongside Bash.
for _, name := range []string{"TaskOutput", "TaskStop", "TaskList", "Monitor"} {
if _, ok := sess.registry.Get(name); !ok {
t.Fatalf("expected %s tool to be registered", name)
}
}
// Prompt #1: launch the background command.
var launchText string
for ev := range mustEvents(t, sess, "start the scan") {
if ev.Kind == harness.KindToolResult {
launchText = ev.ToolResult.Content[0].Text
}
}
if !strings.Contains(launchText, "background") {
t.Fatalf("expected background launch result, got %q", launchText)
}
// The session's task temp dir exists while the task runs.
taskDir := filepath.Join(os.TempDir(), "norma", sess.SessionID())
if _, err := os.Stat(taskDir); err != nil {
t.Fatalf("task dir should exist: %v", err)
}
// Wait for the command to finish so its notification is queued.
time.Sleep(1500 * time.Millisecond)
// Prompt #2: the completion notification is injected before the new turn.
for range mustEvents(t, sess, "anything new?") {
}
var found bool
for _, m := range sess.Messages() {
if strings.Contains(m.Text(), "<task-notification>") && strings.Contains(m.Text(), "completed") {
found = true
}
}
if !found {
t.Fatal("background completion notification was not surfaced into the conversation")
}
// Close removes the task directory.
if err := sess.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
if _, err := os.Stat(taskDir); !os.IsNotExist(err) {
t.Fatalf("task dir should be removed after Close: %v", err)
}
}
func mustEvents(t *testing.T, s *Session, input string) iter.Seq[harness.Event] {
t.Helper()
return func(yield func(harness.Event) bool) {
for ev, err := range s.Prompt(context.Background(), input) {
if err != nil {
t.Fatalf("prompt err: %v", err)
}
if !yield(ev) {
return
}
}
}
}
+183
View File
@@ -0,0 +1,183 @@
package agentcore
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Autumn-27/norma/harness"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
"github.com/Autumn-27/norma/transcript"
)
// textServer replies with a single end_turn text message carrying usage.
func textServer(t *testing.T, text string) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte(sse(
`data: {"type":"message_start","message":{"usage":{"input_tokens":10,"output_tokens":0}}}`, ``,
`data: {"type":"content_block_start","index":0,"content_block":{"type":"text"}}`, ``,
`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"`+text+`"}}`, ``,
`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":5}}`, ``,
`data: {"type":"message_stop"}`, ``,
)))
}))
}
func drainPrompt(t *testing.T, s *Session, input string) {
t.Helper()
for _, err := range s.Prompt(context.Background(), input) {
if err != nil {
t.Fatalf("prompt: %v", err)
}
}
}
// TestTranscriptPersistAndResume drives a Session with a transcript store, then
// resumes a fresh Session from disk and continues the conversation.
func TestTranscriptPersistAndResume(t *testing.T) {
srv := textServer(t, "first answer")
defer srv.Close()
prov, _ := llm.NewProvider(llm.Config{Format: llm.FormatAnthropic, BaseURL: srv.URL, APIKey: "k", Model: "m"})
store := transcript.NewStore(t.TempDir())
s := NewSession(Options{
Provider: prov,
SystemPrompt: []string{"test"},
Tools: []tool.CoreTool{},
PermissionMode: permission.ModeBypass,
Transcript: store,
})
sid := s.SessionID()
if sid == "" {
t.Fatal("expected a generated session id")
}
drainPrompt(t, s, "first question")
// On-disk records: user + assistant, assistant carries usage.
recs, err := store.Load(store.MainPath(sid))
if err != nil {
t.Fatalf("load: %v", err)
}
if len(recs) != 2 {
t.Fatalf("records=%d, want 2", len(recs))
}
if recs[0].Message.Role != llm.RoleUser || recs[1].Message.Role != llm.RoleAssistant {
t.Fatalf("roles=%v,%v", recs[0].Message.Role, recs[1].Message.Role)
}
if recs[1].ParentUUID != recs[0].UUID {
t.Fatal("assistant record not chained to user record")
}
if recs[1].Usage == nil || recs[1].Usage.OutputTokens != 5 {
t.Fatalf("assistant usage = %+v, want output=5", recs[1].Usage)
}
// Resume into a fresh Session and verify history is rebuilt.
srv2 := textServer(t, "second answer")
defer srv2.Close()
prov2, _ := llm.NewProvider(llm.Config{Format: llm.FormatAnthropic, BaseURL: srv2.URL, APIKey: "k", Model: "m"})
resumed := NewSession(Options{
Provider: prov2,
SystemPrompt: []string{"test"},
Tools: []tool.CoreTool{},
PermissionMode: permission.ModeBypass,
Transcript: store,
})
if err := resumed.Resume(sid); err != nil {
t.Fatalf("resume: %v", err)
}
if len(resumed.Messages()) != 2 {
t.Fatalf("resumed messages=%d, want 2", len(resumed.Messages()))
}
if got := resumed.Messages()[1].Text(); got != "first answer" {
t.Fatalf("resumed assistant text=%q", got)
}
// Continue the resumed conversation; new records append to the same file.
drainPrompt(t, resumed, "second question")
recs2, _ := store.Load(store.MainPath(sid))
if len(recs2) != 4 {
t.Fatalf("records after continue=%d, want 4", len(recs2))
}
if recs2[2].ParentUUID != recs2[1].UUID {
t.Fatal("continued chain broken across resume")
}
}
// TestRecorderFiresForSubagentSidechain checks the harness Recorder is invoked
// for each new message and that boundary records are skipped on reconstruction.
func TestTranscriptMessagesSkipsBoundary(t *testing.T) {
recs := []transcript.Record{
{Type: "message", Message: ptr(llm.UserText("q")), UUID: "1"},
{Type: "boundary", Boundary: &llm.BoundaryMeta{Trigger: "auto", PreTokens: 100}, UUID: "2"},
{Type: "message", Message: ptr(llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{llm.TextBlock("a")}}),
Usage: &llm.Usage{OutputTokens: 7}, UUID: "3"},
}
msgs, usage := transcript.Messages(recs)
if len(msgs) != 2 {
t.Fatalf("messages=%d, want 2 (boundary skipped)", len(msgs))
}
if usage.OutputTokens != 7 {
t.Fatalf("summed usage=%d, want 7", usage.OutputTokens)
}
}
var _ harness.Recorder = (*transcript.Writer)(nil)
func ptr(m llm.Message) *llm.Message { return &m }
// TestResumeRestoresCompactedView writes a transcript shaped like one a compacted
// session produces — raw births, then the persisted post-boundary working set
// (boundary marker + summary + re-recorded tail) — and verifies a cold-start
// Resume rebuilds an array whose API view is the COMPACTED one (summary + tail),
// NOT the full raw history. This is the "don't re-summarize on resume" guarantee.
func TestResumeRestoresCompactedView(t *testing.T) {
store := transcript.NewStore(t.TempDir())
sid := transcript.NewSessionID()
w := store.NewWriter(sid, "")
// Raw births (the full history, retained on disk for audit).
w.RecordMessage(llm.UserText("q1"), llm.Usage{})
w.RecordMessage(llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{llm.TextBlock("a1")}}, llm.Usage{})
w.RecordMessage(llm.UserText("q2"), llm.Usage{}) // becomes the kept tail
// Compaction fires: persist the post-boundary working set (mirrors recordNewBoundary).
w.RecordBoundary(llm.BoundaryMeta{Trigger: "auto", PreTokens: 5000}) // observability (skipped on replay)
w.RecordMessage(llm.BoundaryMessage(llm.BoundaryMeta{Trigger: "auto", PreTokens: 5000}), llm.Usage{})
w.RecordMessage(llm.Message{Role: llm.RoleUser, Content: []llm.ContentBlock{llm.TextBlock("[summary] DIGEST")}}, llm.Usage{})
w.RecordMessage(llm.UserText("q2"), llm.Usage{}) // tail re-recorded after the boundary
if err := w.Err(); err != nil {
t.Fatalf("write: %v", err)
}
srv := textServer(t, "next")
defer srv.Close()
prov, _ := llm.NewProvider(llm.Config{Format: llm.FormatAnthropic, BaseURL: srv.URL, APIKey: "k", Model: "m"})
s := NewSession(Options{
Provider: prov,
SystemPrompt: []string{"test"},
Tools: []tool.CoreTool{},
PermissionMode: permission.ModeBypass,
Transcript: store,
})
if err := s.Resume(sid); err != nil {
t.Fatalf("resume: %v", err)
}
// The boundary marker survived reconstruction (persisted as a message, not skipped).
full := s.Messages()
if llm.LastBoundaryIndex(full) < 0 {
t.Fatal("resumed array lost the compaction boundary")
}
// The API view is the compacted one: [summary, tail] — not the raw q1/a1/q2.
api := llm.MessagesForAPI(full)
if len(api) != 2 {
t.Fatalf("compacted API view = %d msgs, want 2 (summary + tail); resume re-exposed raw history", len(api))
}
if !strings.Contains(api[0].Text(), "DIGEST") || api[1].Text() != "q2" {
t.Fatalf("API view = %q,%q; want summary then tail", api[0].Text(), api[1].Text())
}
}