diff --git a/runtime/runturn.go b/runtime/runturn.go index 9fa7fe4..86ce9fd 100644 --- a/runtime/runturn.go +++ b/runtime/runturn.go @@ -3,9 +3,11 @@ package runtime import ( "context" "encoding/base64" + "encoding/json" "fmt" "sort" "strings" + "time" "github.com/sausheong/harness/llm" "github.com/sausheong/harness/session" @@ -33,9 +35,11 @@ type TurnEmit func(AgentEvent) // session state on replay. It differs from Run by design: it is headless // (live events go only through the emit callback, never an internal channel), // it dispatches tool calls serially (Run parallelizes concurrency-safe -// batches), and it does NOT perform compaction, knowledge-graph recall/ingest, -// streaming-tool kickoff, or the trace/slog emissions that Run's emitToolResult -// produces. Those remain Run's responsibility. +// batches), and it does NOT perform compaction, streaming-tool kickoff, or the +// trace/slog emissions that Run's emitToolResult produces (those remain Run's +// responsibility). It DOES perform bounded-synchronous knowledge-graph recall on +// the first round of an exchange (folding the hint into the system prompt) and +// async knowledge-graph ingest on the completing round. func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.ImageContent, emit TurnEmit) (TurnResult, error) { if emit == nil { emit = func(AgentEvent) {} @@ -70,7 +74,20 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag sort.SliceStable(toolDefs, func(i, j int) bool { return toolDefs[i].Name < toolDefs[j].Name }) toolDefs, _ = r.LLM.NormalizeToolSchema(toolDefs) + // KG recall (first round of the exchange only): bounded-synchronous so a + // slow embedder cannot stall the turn. The hint is a non-cached suffix — + // it varies per query, so caching it would poison the static prefix cache. + var kgHint string + if r.KG != nil && (userMsg != "" || len(images) > 0) && r.KG.ShouldRecall(userMsg) { + rctx, cancel := context.WithTimeout(ctx, 800*time.Millisecond) + kgHint = r.KG.Recall(rctx, userMsg) + cancel() + } + parts := []llm.SystemPromptPart{{Text: r.StaticSystemPrompt, Cache: true}} + if kgHint != "" { + parts = append(parts, llm.SystemPromptPart{Text: kgHint, Cache: false}) + } req := llm.ChatRequest{ Model: r.Model, Messages: msgs, @@ -122,6 +139,18 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag } if len(toolCalls) == 0 { + // Exchange complete: ingest the full thread once. Background + best-effort + // (the KG spawns its own bounded goroutine), so it never delays the turn. + // context.Background() because the request ctx may be cancelling and the + // ingest goroutine deliberately outlives the turn. Unlike Run, RunTurn does + // not pre-filter trivial threads or gate on IngestSource: the KG impl owns + // its own growth gate (so single-message threads are skipped there), and the + // only RunTurn caller today is the chat serve loop. TODO: if a reviewer or + // subagent path is ever migrated to RunTurn, add an IngestSource-style gate + // here so non-chat transcripts are not ingested. + if r.KG != nil { + r.KG.Ingest(context.Background(), sessionThread(r.Session.View())) + } emit(AgentEvent{Type: EventDone, Usage: lastUsage}) return r.turnSlice(startLen, true, "completed", lastUsage, nil), nil } @@ -153,3 +182,48 @@ func (r *Runtime) turnSlice(startLen int, done bool, reason string, usage *llm.U } return TurnResult{Done: done, StopReason: reason, Entries: delta, Usage: usage, Err: err} } + +// sessionThread converts session history into the minimal []Message the +// KnowledgeGraph ingests, mirroring how Run accumulates its thread: user and +// assistant messages by role+text, tool calls as "[tool: name]\n" +// (assistant), tool results as their output or "[error] " (user). +// Compaction/meta and non-user/assistant message entries are skipped — the +// thread carries only conversation turns and tool exchanges. +// On the runtime's per-turn serve path each call sees one turn's fresh session, +// so a compaction summary's absence here is intentional, not a gap. +func sessionThread(history []session.SessionEntry) []Message { + var thread []Message + for _, e := range history { + switch e.Type { + case session.EntryTypeMessage: + if e.Role != "user" && e.Role != "assistant" { + continue // skip system/summary messages + } + var d session.MessageData + if json.Unmarshal(e.Data, &d) != nil { + continue + } + thread = append(thread, Message{Role: e.Role, Content: d.Text}) + case session.EntryTypeToolCall: + var d session.ToolCallData + if json.Unmarshal(e.Data, &d) != nil { + continue + } + thread = append(thread, Message{ + Role: "assistant", + Content: fmt.Sprintf("[tool: %s]\n%s", d.Tool, string(d.Input)), + }) + case session.EntryTypeToolResult: + var d session.ToolResultData + if json.Unmarshal(e.Data, &d) != nil { + continue + } + content := d.Output + if d.Error != "" { + content = "[error] " + d.Error + } + thread = append(thread, Message{Role: "user", Content: content}) + } + } + return thread +} diff --git a/runtime/runturn_kg_test.go b/runtime/runturn_kg_test.go new file mode 100644 index 0000000..ffcdf65 --- /dev/null +++ b/runtime/runturn_kg_test.go @@ -0,0 +1,216 @@ +package runtime + +import ( + "context" + "encoding/json" + "testing" + "time" + + "github.com/sausheong/harness/llm" + "github.com/sausheong/harness/session" + "github.com/stretchr/testify/require" +) + +func TestSessionThread_RendersEntries(t *testing.T) { + sess := session.NewSession("a", "k") + sess.Append(session.UserMessageEntry("hello")) + sess.Append(session.AssistantMessageEntry("hi there")) + sess.Append(session.ToolCallEntry("tc1", "echo", json.RawMessage(`{"x":1}`))) + sess.Append(session.ToolResultEntry("tc1", "echoed", "", nil)) + sess.Append(session.ToolResultEntry("tc2", "", "boom", nil)) + + thread := sessionThread(sess.View()) + + require.Equal(t, []Message{ + {Role: "user", Content: "hello"}, + {Role: "assistant", Content: "hi there"}, + {Role: "assistant", Content: "[tool: echo]\n{\"x\":1}"}, + {Role: "user", Content: "echoed"}, + {Role: "user", Content: "[error] boom"}, + }, thread) +} + +func TestSessionThread_SkipsCompaction(t *testing.T) { + sess := session.NewSession("a", "k") + // Compaction is appended FIRST so the entries that follow remain on the + // View() walk-back path. View() stops its back-walk at the most recent + // compaction (inclusive), so appending user/assistant AFTER it yields + // View() == [compaction, user, assistant] — the compaction is genuinely + // present in the slice handed to sessionThread, exercising the skip path. + // (Appending compaction last would make it the leaf, and View() would + // return only [compaction], never reaching the messages.) + sess.Append(session.CompactionEntry("summary", "", "", "m", 0, 0, 0)) + sess.Append(session.UserMessageEntry("hello")) + sess.Append(session.AssistantMessageEntry("hi")) + + view := sess.View() + require.Equal(t, session.EntryTypeCompaction, view[0].Type, "View() must include the compaction entry to exercise the skip") + + got := sessionThread(view) + require.Equal(t, []Message{ + {Role: "user", Content: "hello"}, + {Role: "assistant", Content: "hi"}, + }, got) +} + +func TestSessionThread_SkipsUndecodableEntry(t *testing.T) { + history := []session.SessionEntry{ + {Type: session.EntryTypeToolCall, Data: []byte("not json")}, + session.UserMessageEntry("after"), + } + got := sessionThread(history) + require.Equal(t, []Message{{Role: "user", Content: "after"}}, got) +} + +func TestSessionThread_Empty(t *testing.T) { + require.Nil(t, sessionThread(nil)) +} + +// fakeKG is a controllable KnowledgeGraph for RunTurn wiring tests. +type fakeKG struct { + shouldRecall bool + recallReturn string + recallDelay time.Duration + recallCalls int + recallQuery string + + ingestCalls int + ingestThreads [][]Message +} + +func (f *fakeKG) ShouldRecall(q string) bool { return f.shouldRecall } +func (f *fakeKG) Recall(ctx context.Context, q string) string { + f.recallCalls++ + f.recallQuery = q + if f.recallDelay > 0 { + select { + case <-time.After(f.recallDelay): + case <-ctx.Done(): + return "" + } + } + return f.recallReturn +} +func (f *fakeKG) Ingest(_ context.Context, thread []Message) { + f.ingestCalls++ + f.ingestThreads = append(f.ingestThreads, thread) +} + +func TestRunTurn_RecallInjectedIntoPrompt(t *testing.T) { + var captured []llm.SystemPromptPart + cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }} + kg := &fakeKG{shouldRecall: true, recallReturn: "Relevant memories:\n- the user likes tea\n"} + + rt := &Runtime{ + LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"), + AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg, + } + _, err := rt.RunTurn(context.Background(), "what do I like?", nil, nil) + require.NoError(t, err) + require.Equal(t, 1, kg.recallCalls) + require.Equal(t, "what do I like?", kg.recallQuery) + + require.GreaterOrEqual(t, len(captured), 2, "expected static + recall parts") + require.Equal(t, "STATIC", captured[0].Text) + require.True(t, captured[0].Cache) + require.Equal(t, "Relevant memories:\n- the user likes tea\n", captured[len(captured)-1].Text) + require.False(t, captured[len(captured)-1].Cache, "recall hint must NOT be cached") +} + +func TestRunTurn_NoRecallWhenShouldRecallFalse(t *testing.T) { + var captured []llm.SystemPromptPart + cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }} + kg := &fakeKG{shouldRecall: false, recallReturn: "should not appear"} + + rt := &Runtime{ + LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"), + AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg, + } + _, err := rt.RunTurn(context.Background(), "hi", nil, nil) + require.NoError(t, err) + require.Equal(t, 0, kg.recallCalls, "ShouldRecall false ⇒ Recall not called") + require.Len(t, captured, 1, "only the static part") + require.Equal(t, "STATIC", captured[0].Text) +} + +func TestRunTurn_NoRecallOnContinuationRound(t *testing.T) { + var captured []llm.SystemPromptPart + cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }} + kg := &fakeKG{shouldRecall: true, recallReturn: "hint"} + + rt := &Runtime{ + LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"), + AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg, + } + _, err := rt.RunTurn(context.Background(), "", nil, nil) + require.NoError(t, err) + require.Equal(t, 0, kg.recallCalls, "continuation round must not recall") + require.Len(t, captured, 1) +} + +func TestRunTurn_RecallTimeoutInjectsNothing(t *testing.T) { + var captured []llm.SystemPromptPart + cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }} + kg := &fakeKG{shouldRecall: true, recallReturn: "late", recallDelay: 2 * time.Second} + + rt := &Runtime{ + LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"), + AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg, + } + start := time.Now() + _, err := rt.RunTurn(context.Background(), "slow?", nil, nil) + require.NoError(t, err) + require.Less(t, time.Since(start), 1500*time.Millisecond, "recall must be bounded ~800ms") + require.Len(t, captured, 1, "timed-out recall injects nothing") +} + +func TestRunTurn_IngestOnCompletion(t *testing.T) { + llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{ + {typ: llm.EventTextDelta, text: "done"}, + {typ: llm.EventDone}, + }} + kg := &fakeKG{} + rt := &Runtime{ + LLM: llmProvider, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"), + AgentID: "a", Model: "test", StaticSystemPrompt: "S", KG: kg, + } + res, err := rt.RunTurn(context.Background(), "remember I like tea", nil, nil) + require.NoError(t, err) + require.True(t, res.Done) + require.Equal(t, 1, kg.ingestCalls, "ingest fires once on the completing round") + require.NotEmpty(t, kg.ingestThreads[0], "ingest gets a non-empty thread") + require.Equal(t, "user", kg.ingestThreads[0][0].Role) + require.Equal(t, "remember I like tea", kg.ingestThreads[0][0].Content) +} + +func TestRunTurn_NoIngestOnToolRound(t *testing.T) { + tc := &llm.ToolCall{ID: "tc_1", Name: "echo", Input: json.RawMessage(`{"x":1}`)} + llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{ + {typ: llm.EventToolCallStart, toolCall: tc}, + {typ: llm.EventToolCallDone, toolCall: tc}, + {typ: llm.EventDone}, + }} + kg := &fakeKG{} + rt := &Runtime{ + LLM: llmProvider, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"), + AgentID: "a", Model: "test", StaticSystemPrompt: "S", KG: kg, + } + res, err := rt.RunTurn(context.Background(), "use echo", nil, nil) + require.NoError(t, err) + require.False(t, res.Done, "tool round is not terminal") + require.Equal(t, 0, kg.ingestCalls, "no ingest on a round that produced tool calls") +} + +func TestRunTurn_NoIngestWhenKGNil(t *testing.T) { + llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{ + {typ: llm.EventTextDelta, text: "done"}, + {typ: llm.EventDone}, + }} + rt := &Runtime{ + LLM: llmProvider, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"), + AgentID: "a", Model: "test", StaticSystemPrompt: "S", KG: nil, + } + res, err := rt.RunTurn(context.Background(), "hi", nil, nil) + require.NoError(t, err) + require.True(t, res.Done) +}