build: 内置 norma 模块,构建不再依赖上游仓库
把 github.com/Autumn-27/norma v0.4.3(commit 320ae32)的源码复制到 third_party/norma,并用 go.mod 的 replace 指向本地副本。上游删除仓库或 改写 tag 都不再影响本仓库构建。 - 已验证 GOPROXY=off 下可完整编译并打出发行包 - go.sum 中该模块的两条校验记录随之删除(本地 replace 不需要哈希) - 升级方法与授权注意事项见 third_party/README.md
This commit is contained in:
1 parent
a819fa3230
commit
f782b612ec
213 files changed
+37401
-2
No files matched your search
+19
@@ -0,0 +1,19 @@
|
||||
package transcript
|
||||
|
||||
import "context"
|
||||
|
||||
type ctxKey int
|
||||
|
||||
const sessionIDKey ctxKey = 0
|
||||
|
||||
// WithSessionID carries the active session id on the context so subagents can
|
||||
// write their sidechain under the parent session's directory.
|
||||
func WithSessionID(ctx context.Context, sessionID string) context.Context {
|
||||
return context.WithValue(ctx, sessionIDKey, sessionID)
|
||||
}
|
||||
|
||||
// SessionIDFrom returns the session id carried on ctx, or "" if none.
|
||||
func SessionIDFrom(ctx context.Context) string {
|
||||
v, _ := ctx.Value(sessionIDKey).(string)
|
||||
return v
|
||||
}
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
// Package transcript persists a conversation to an append-only JSONL log on
|
||||
// disk and reconstructs it for resume. The main session is written to
|
||||
// <dir>/<sessionID>.jsonl; each
|
||||
// subagent is written to its own sidechain file under
|
||||
// <dir>/<sessionID>/subagents/agent-<agentID>.jsonl, so subagent tokens are
|
||||
// counted and stored separately (aggregate them offline if needed).
|
||||
//
|
||||
// The log is the full-fidelity history: every user/assistant/tool message is
|
||||
// recorded as it is born. When compaction inserts a boundary, the post-boundary
|
||||
// working set — the boundary marker, the summary, and the kept recent tail — is
|
||||
// ALSO persisted as messages, so a cold-start resume restores the COMPACTED view
|
||||
// (via llm.MessagesForAPI, which slices from the last boundary) instead of
|
||||
// replaying raw history and re-summarizing. The kept tail
|
||||
// is re-recorded after the boundary (it also exists earlier as births); only the
|
||||
// post-boundary copy reaches the model. Lightweight working-set edits that do not
|
||||
// add a boundary (MicroCompact tool-result clearing) stay ephemeral and
|
||||
// are not persisted. A separate Type=="boundary" record is written for
|
||||
// observability and is skipped during reconstruction.
|
||||
package transcript
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
|
||||
// Record is one line of a JSONL transcript.
|
||||
type Record struct {
|
||||
UUID string `json:"uuid"`
|
||||
ParentUUID string `json:"parent_uuid,omitempty"`
|
||||
SessionID string `json:"session_id"`
|
||||
AgentID string `json:"agent_id,omitempty"`
|
||||
IsSidechain bool `json:"is_sidechain,omitempty"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
Type string `json:"type"` // "message" | "boundary"
|
||||
Message *llm.Message `json:"message,omitempty"`
|
||||
Usage *llm.Usage `json:"usage,omitempty"` // assistant turns only
|
||||
Boundary *llm.BoundaryMeta `json:"boundary,omitempty"` // Type=="boundary"
|
||||
}
|
||||
|
||||
// Store is a directory of session transcripts.
|
||||
type Store struct {
|
||||
dir string
|
||||
mu sync.Mutex // serializes appends across writers in this process
|
||||
}
|
||||
|
||||
// NewStore returns a Store rooted at dir (created lazily on first write).
|
||||
func NewStore(dir string) *Store { return &Store{dir: dir} }
|
||||
|
||||
// MainPath is the JSONL file for a top-level session.
|
||||
func (s *Store) MainPath(sessionID string) string {
|
||||
return filepath.Join(s.dir, sessionID+".jsonl")
|
||||
}
|
||||
|
||||
// AgentPath is the sidechain JSONL file for a subagent of a session.
|
||||
func (s *Store) AgentPath(sessionID, agentID string) string {
|
||||
return filepath.Join(s.dir, sessionID, "subagents", "agent-"+agentID+".jsonl")
|
||||
}
|
||||
|
||||
// Append writes records to path as JSONL, creating parent directories. It is
|
||||
// safe for concurrent use within the process.
|
||||
func (s *Store) Append(path string, recs ...Record) error {
|
||||
if len(recs) == 0 {
|
||||
return nil
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
w := bufio.NewWriter(f)
|
||||
for _, r := range recs {
|
||||
b, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := w.Write(b); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.WriteByte('\n'); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return w.Flush()
|
||||
}
|
||||
|
||||
// Load reads all records from a transcript file. A missing file yields no
|
||||
// records and no error (a fresh session).
|
||||
func (s *Store) Load(path string) ([]Record, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
var recs []Record
|
||||
sc := bufio.NewScanner(f)
|
||||
sc.Buffer(make([]byte, 0, 64*1024), 64*1024*1024) // tolerate large tool results
|
||||
for sc.Scan() {
|
||||
line := sc.Bytes()
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
}
|
||||
var r Record
|
||||
if err := json.Unmarshal(line, &r); err != nil {
|
||||
return nil, fmt.Errorf("transcript: corrupt line: %w", err)
|
||||
}
|
||||
recs = append(recs, r)
|
||||
}
|
||||
return recs, sc.Err()
|
||||
}
|
||||
|
||||
// Messages reconstructs the raw conversation and cumulative usage from records.
|
||||
// Boundary records are skipped — the working set is rebuilt by compaction on the
|
||||
// next turn, not replayed from disk.
|
||||
func Messages(recs []Record) ([]llm.Message, llm.Usage) {
|
||||
var msgs []llm.Message
|
||||
var total llm.Usage
|
||||
for _, r := range recs {
|
||||
if r.Type == "boundary" || r.Message == nil {
|
||||
continue
|
||||
}
|
||||
msgs = append(msgs, *r.Message)
|
||||
if r.Usage != nil {
|
||||
total.Add(*r.Usage)
|
||||
}
|
||||
}
|
||||
return msgs, total
|
||||
}
|
||||
|
||||
// LastUUID returns the UUID of the last record, for continuing the parent chain.
|
||||
func LastUUID(recs []Record) string {
|
||||
if len(recs) == 0 {
|
||||
return ""
|
||||
}
|
||||
return recs[len(recs)-1].UUID
|
||||
}
|
||||
|
||||
// Writer binds a Store, a file path, and a session/agent identity, assigning a
|
||||
// UUID and parent link to each record. It satisfies harness.Recorder. Append
|
||||
// errors are retained (see Err) rather than panicking, so a failing disk
|
||||
// degrades to in-memory operation instead of crashing the agent loop.
|
||||
type Writer struct {
|
||||
store *Store
|
||||
path string
|
||||
sessionID string
|
||||
agentID string
|
||||
isSidechain bool
|
||||
|
||||
mu sync.Mutex
|
||||
last string
|
||||
now func() time.Time
|
||||
err error
|
||||
}
|
||||
|
||||
// NewWriter returns a Writer for a fresh transcript file. agentID == "" writes
|
||||
// the main session file; a non-empty agentID writes a subagent sidechain.
|
||||
func (s *Store) NewWriter(sessionID, agentID string) *Writer {
|
||||
w := &Writer{store: s, sessionID: sessionID, agentID: agentID, now: time.Now}
|
||||
if agentID == "" {
|
||||
w.path = s.MainPath(sessionID)
|
||||
} else {
|
||||
w.path = s.AgentPath(sessionID, agentID)
|
||||
w.isSidechain = true
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
// ResumeWriter returns a Writer that continues an existing main-session file,
|
||||
// chaining new records after lastUUID.
|
||||
func (s *Store) ResumeWriter(sessionID, lastUUID string) *Writer {
|
||||
w := s.NewWriter(sessionID, "")
|
||||
w.last = lastUUID
|
||||
return w
|
||||
}
|
||||
|
||||
// Err returns the first append error encountered, if any.
|
||||
func (w *Writer) Err() error {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.err
|
||||
}
|
||||
|
||||
func (w *Writer) write(r Record) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
r.SessionID = w.sessionID
|
||||
r.AgentID = w.agentID
|
||||
r.IsSidechain = w.isSidechain
|
||||
r.UUID = newID()
|
||||
r.ParentUUID = w.last
|
||||
r.Timestamp = w.now().UTC().Format(time.RFC3339Nano)
|
||||
if err := w.store.Append(w.path, r); err != nil {
|
||||
if w.err == nil {
|
||||
w.err = err
|
||||
}
|
||||
return
|
||||
}
|
||||
w.last = r.UUID
|
||||
}
|
||||
|
||||
// RecordMessage persists a conversation message. usage is attributed to this
|
||||
// turn (zero for non-assistant messages).
|
||||
func (w *Writer) RecordMessage(m llm.Message, usage llm.Usage) {
|
||||
rec := Record{Type: "message", Message: &m}
|
||||
if usage != (llm.Usage{}) {
|
||||
u := usage
|
||||
rec.Usage = &u
|
||||
}
|
||||
w.write(rec)
|
||||
}
|
||||
|
||||
// RecordBoundary persists a compaction boundary for observability.
|
||||
func (w *Writer) RecordBoundary(meta llm.BoundaryMeta) {
|
||||
m := meta
|
||||
w.write(Record{Type: "boundary", Boundary: &m})
|
||||
}
|
||||
|
||||
// newID returns a random 128-bit hex identifier.
|
||||
func newID() string {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
// rand should never fail; fall back to a time-based id to stay unique-ish.
|
||||
return hex.EncodeToString([]byte(time.Now().UTC().Format(time.RFC3339Nano)))
|
||||
}
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
// NewSessionID returns a fresh session identifier.
|
||||
func NewSessionID() string { return newID() }
|
||||
|
||||
// NewAgentID returns a fresh subagent identifier.
|
||||
func NewAgentID() string { return newID() }
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
package transcript
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
|
||||
func TestRecordAndLoadRoundTrip(t *testing.T) {
|
||||
s := NewStore(t.TempDir())
|
||||
w := s.NewWriter("sess", "")
|
||||
w.RecordMessage(llm.UserText("hi"), llm.Usage{})
|
||||
w.RecordMessage(llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{llm.TextBlock("yo")}}, llm.Usage{InputTokens: 10, OutputTokens: 5})
|
||||
if err := w.Err(); err != nil {
|
||||
t.Fatalf("write err: %v", err)
|
||||
}
|
||||
recs, err := s.Load(s.MainPath("sess"))
|
||||
if err != nil {
|
||||
t.Fatalf("load: %v", err)
|
||||
}
|
||||
if len(recs) != 2 {
|
||||
t.Fatalf("want 2 records, got %d", len(recs))
|
||||
}
|
||||
msgs, total := Messages(recs)
|
||||
if len(msgs) != 2 || msgs[0].Text() != "hi" || msgs[1].Text() != "yo" {
|
||||
t.Fatalf("reconstructed messages wrong: %+v", msgs)
|
||||
}
|
||||
if total != (llm.Usage{InputTokens: 10, OutputTokens: 5}) {
|
||||
t.Fatalf("usage accumulation wrong: %+v", total)
|
||||
}
|
||||
}
|
||||
|
||||
// A boundary record is persisted for observability but skipped when
|
||||
// reconstructing the conversation (compaction rebuilds the working set itself).
|
||||
func TestBoundaryRecordSkippedInReconstruction(t *testing.T) {
|
||||
s := NewStore(t.TempDir())
|
||||
w := s.NewWriter("sess", "")
|
||||
w.RecordMessage(llm.UserText("before"), llm.Usage{})
|
||||
w.RecordBoundary(llm.BoundaryMeta{Trigger: "auto", PreTokens: 1234, MessagesSummarized: 3})
|
||||
w.RecordMessage(llm.UserText("after"), llm.Usage{})
|
||||
|
||||
recs, _ := s.Load(s.MainPath("sess"))
|
||||
if len(recs) != 3 {
|
||||
t.Fatalf("want 3 records on disk (incl. boundary), got %d", len(recs))
|
||||
}
|
||||
// The boundary record is present and typed.
|
||||
var sawBoundary bool
|
||||
for _, r := range recs {
|
||||
if r.Type == "boundary" {
|
||||
sawBoundary = true
|
||||
if r.Boundary == nil || r.Boundary.PreTokens != 1234 {
|
||||
t.Fatalf("boundary meta not persisted: %+v", r.Boundary)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !sawBoundary {
|
||||
t.Fatal("boundary record not written")
|
||||
}
|
||||
// But reconstruction skips it.
|
||||
msgs, _ := Messages(recs)
|
||||
if len(msgs) != 2 || msgs[0].Text() != "before" || msgs[1].Text() != "after" {
|
||||
t.Fatalf("boundary should be skipped in Messages: %+v", msgs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParentChainAndLastUUID(t *testing.T) {
|
||||
s := NewStore(t.TempDir())
|
||||
w := s.NewWriter("sess", "")
|
||||
w.RecordMessage(llm.UserText("a"), llm.Usage{})
|
||||
w.RecordMessage(llm.UserText("b"), llm.Usage{})
|
||||
recs, _ := s.Load(s.MainPath("sess"))
|
||||
if recs[0].ParentUUID != "" {
|
||||
t.Fatalf("first record should have no parent, got %q", recs[0].ParentUUID)
|
||||
}
|
||||
if recs[1].ParentUUID != recs[0].UUID {
|
||||
t.Fatalf("chain broken: rec1.parent=%q, rec0.uuid=%q", recs[1].ParentUUID, recs[0].UUID)
|
||||
}
|
||||
if LastUUID(recs) != recs[1].UUID {
|
||||
t.Fatalf("LastUUID mismatch")
|
||||
}
|
||||
if LastUUID(nil) != "" {
|
||||
t.Fatal("LastUUID(nil) should be empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumeWriterContinuesChain(t *testing.T) {
|
||||
s := NewStore(t.TempDir())
|
||||
w := s.NewWriter("sess", "")
|
||||
w.RecordMessage(llm.UserText("first"), llm.Usage{})
|
||||
recs, _ := s.Load(s.MainPath("sess"))
|
||||
last := LastUUID(recs)
|
||||
|
||||
rw := s.ResumeWriter("sess", last)
|
||||
rw.RecordMessage(llm.UserText("second"), llm.Usage{})
|
||||
|
||||
recs2, _ := s.Load(s.MainPath("sess"))
|
||||
if len(recs2) != 2 {
|
||||
t.Fatalf("want 2 records after resume, got %d", len(recs2))
|
||||
}
|
||||
if recs2[1].ParentUUID != last {
|
||||
t.Fatalf("resumed record should chain to %q, got %q", last, recs2[1].ParentUUID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubagentSidechainPath(t *testing.T) {
|
||||
s := NewStore(t.TempDir())
|
||||
w := s.NewWriter("sess", "agent1")
|
||||
w.RecordMessage(llm.UserText("sub"), llm.Usage{})
|
||||
// Written to the sidechain path, not the main file.
|
||||
if recs, _ := s.Load(s.AgentPath("sess", "agent1")); len(recs) != 1 || !recs[0].IsSidechain {
|
||||
t.Fatalf("subagent record not on sidechain: %+v", recs)
|
||||
}
|
||||
if recs, _ := s.Load(s.MainPath("sess")); len(recs) != 0 {
|
||||
t.Fatalf("main file should be empty, got %d", len(recs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadMissingFileIsFreshSession(t *testing.T) {
|
||||
s := NewStore(t.TempDir())
|
||||
recs, err := s.Load(s.MainPath("does-not-exist"))
|
||||
if err != nil || recs != nil {
|
||||
t.Fatalf("missing file should yield (nil, nil), got (%v, %v)", recs, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessagesFiltersNilAndBoundary(t *testing.T) {
|
||||
recs := []Record{
|
||||
{Type: "message", Message: &llm.Message{Role: llm.RoleUser, Content: []llm.ContentBlock{llm.TextBlock("x")}}, Usage: &llm.Usage{InputTokens: 3}},
|
||||
{Type: "boundary", Boundary: &llm.BoundaryMeta{}},
|
||||
{Type: "message", Message: nil}, // defensive: nil message skipped
|
||||
}
|
||||
msgs, total := Messages(recs)
|
||||
if len(msgs) != 1 || total.InputTokens != 3 {
|
||||
t.Fatalf("Messages should keep only the real message: msgs=%d usage=%+v", len(msgs), total)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionIDContextRoundTrip(t *testing.T) {
|
||||
ctx := WithSessionID(context.Background(), "abc123")
|
||||
if got := SessionIDFrom(ctx); got != "abc123" {
|
||||
t.Fatalf("SessionIDFrom=%q, want abc123", got)
|
||||
}
|
||||
if got := SessionIDFrom(context.Background()); got != "" {
|
||||
t.Fatalf("empty context should yield \"\", got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewIDsAreDistinctAndNonEmpty(t *testing.T) {
|
||||
a, b := NewSessionID(), NewSessionID()
|
||||
if a == "" || b == "" || a == b {
|
||||
t.Fatalf("session ids should be non-empty and distinct: %q %q", a, b)
|
||||
}
|
||||
if id := NewAgentID(); id == "" || len(id) != 32 { // 16 random bytes hex-encoded
|
||||
t.Fatalf("agent id malformed: %q", id)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadCorruptLineErrors(t *testing.T) {
|
||||
s := NewStore(t.TempDir())
|
||||
path := s.MainPath("sess")
|
||||
// Write a valid record, then a corrupt (non-JSON) line.
|
||||
w := s.NewWriter("sess", "")
|
||||
w.RecordMessage(llm.UserText("ok"), llm.Usage{})
|
||||
if err := appendRaw(path, "{not valid json\n"); err != nil {
|
||||
t.Fatalf("setup append: %v", err)
|
||||
}
|
||||
if _, err := s.Load(path); err == nil {
|
||||
t.Fatal("Load should error on a corrupt line")
|
||||
}
|
||||
}
|
||||
|
||||
// appendRaw appends a raw line to a transcript file for corruption testing.
|
||||
func appendRaw(path, line string) error {
|
||||
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
_, err = f.WriteString(line)
|
||||
return err
|
||||
}
|
||||
Reference in new issue
Block a user