From 67178e018a91a60e2647b1e3b3d4a40bcd72e327 Mon Sep 17 00:00:00 2001 From: sausheong Date: Tue, 9 Jun 2026 23:28:16 +0800 Subject: [PATCH 1/6] feat(runtime): sessionThread helper for KG ingest in RunTurn --- runtime/runturn.go | 44 ++++++++++++++++++++++++++++++++++++++ runtime/runturn_kg_test.go | 44 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 runtime/runturn_kg_test.go diff --git a/runtime/runturn.go b/runtime/runturn.go index 9fa7fe4..3981d24 100644 --- a/runtime/runturn.go +++ b/runtime/runturn.go @@ -3,6 +3,7 @@ package runtime import ( "context" "encoding/base64" + "encoding/json" "fmt" "sort" "strings" @@ -153,3 +154,46 @@ 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. +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..5725f02 --- /dev/null +++ b/runtime/runturn_kg_test.go @@ -0,0 +1,44 @@ +package runtime + +import ( + "encoding/json" + "testing" + + "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") + sess.Append(session.UserMessageEntry("hello")) + sess.Append(session.AssistantMessageEntry("hi")) + // Build the expected from whatever View() returns, minus any compaction/meta. + got := sessionThread(sess.View()) + require.Equal(t, []Message{ + {Role: "user", Content: "hello"}, + {Role: "assistant", Content: "hi"}, + }, got) +} + +func TestSessionThread_Empty(t *testing.T) { + require.Nil(t, sessionThread(nil)) +} From f35070594f82aa7a1a2a198c08ff355ccc4d2ea2 Mon Sep 17 00:00:00 2001 From: sausheong Date: Tue, 9 Jun 2026 23:32:30 +0800 Subject: [PATCH 2/6] test(runtime): strengthen sessionThread compaction-skip + undecodable coverage --- runtime/runturn.go | 2 ++ runtime/runturn_kg_test.go | 24 ++++++++++++++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/runtime/runturn.go b/runtime/runturn.go index 3981d24..9b4e66d 100644 --- a/runtime/runturn.go +++ b/runtime/runturn.go @@ -161,6 +161,8 @@ func (r *Runtime) turnSlice(startLen int, done bool, reason string, usage *llm.U // (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 { diff --git a/runtime/runturn_kg_test.go b/runtime/runturn_kg_test.go index 5725f02..bec0cd5 100644 --- a/runtime/runturn_kg_test.go +++ b/runtime/runturn_kg_test.go @@ -29,16 +29,36 @@ func TestSessionThread_RendersEntries(t *testing.T) { 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")) - // Build the expected from whatever View() returns, minus any compaction/meta. - got := sessionThread(sess.View()) + + 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)) } From fe71e7b36dd3a58722701a4559cc00a6bbfb4939 Mon Sep 17 00:00:00 2001 From: sausheong Date: Tue, 9 Jun 2026 23:34:44 +0800 Subject: [PATCH 3/6] feat(runtime): bounded-synchronous KG recall in RunTurn --- runtime/runturn.go | 14 +++++ runtime/runturn_kg_test.go | 101 +++++++++++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+) diff --git a/runtime/runturn.go b/runtime/runturn.go index 9b4e66d..8ea4165 100644 --- a/runtime/runturn.go +++ b/runtime/runturn.go @@ -7,6 +7,7 @@ import ( "fmt" "sort" "strings" + "time" "github.com/sausheong/harness/llm" "github.com/sausheong/harness/session" @@ -71,7 +72,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, diff --git a/runtime/runturn_kg_test.go b/runtime/runturn_kg_test.go index bec0cd5..6421a74 100644 --- a/runtime/runturn_kg_test.go +++ b/runtime/runturn_kg_test.go @@ -1,9 +1,12 @@ package runtime import ( + "context" "encoding/json" "testing" + "time" + "github.com/sausheong/harness/llm" "github.com/sausheong/harness/session" "github.com/stretchr/testify/require" ) @@ -62,3 +65,101 @@ func TestSessionThread_SkipsUndecodableEntry(t *testing.T) { 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") +} From 8f8d75cd06f3427b2cd68cdeef1345899f3f83a2 Mon Sep 17 00:00:00 2001 From: sausheong Date: Tue, 9 Jun 2026 23:39:26 +0800 Subject: [PATCH 4/6] feat(runtime): KG ingest on RunTurn exchange completion --- runtime/runturn.go | 7 ++++++ runtime/runturn_kg_test.go | 51 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/runtime/runturn.go b/runtime/runturn.go index 8ea4165..41ee493 100644 --- a/runtime/runturn.go +++ b/runtime/runturn.go @@ -137,6 +137,13 @@ 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. + 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 } diff --git a/runtime/runturn_kg_test.go b/runtime/runturn_kg_test.go index 6421a74..ffcdf65 100644 --- a/runtime/runturn_kg_test.go +++ b/runtime/runturn_kg_test.go @@ -163,3 +163,54 @@ func TestRunTurn_RecallTimeoutInjectsNothing(t *testing.T) { 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) +} From b7cbfc584c77ac8fd1c3e31d062547a5198541ac Mon Sep 17 00:00:00 2001 From: sausheong Date: Tue, 9 Jun 2026 23:42:58 +0800 Subject: [PATCH 5/6] docs(runtime): note IngestSource/growth-gate rationale at RunTurn ingest --- runtime/runturn.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/runtime/runturn.go b/runtime/runturn.go index 41ee493..04ed5ae 100644 --- a/runtime/runturn.go +++ b/runtime/runturn.go @@ -140,7 +140,12 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag // 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. + // 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())) } From 5d6326981e5d8e6b62ce2da0496bc7a0f903e55c Mon Sep 17 00:00:00 2001 From: sausheong Date: Tue, 9 Jun 2026 23:58:21 +0800 Subject: [PATCH 6/6] =?UTF-8?q?docs(runtime):=20update=20RunTurn=20contrac?= =?UTF-8?q?t=20=E2=80=94=20it=20now=20does=20KG=20recall/ingest?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- runtime/runturn.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/runtime/runturn.go b/runtime/runturn.go index 04ed5ae..86ce9fd 100644 --- a/runtime/runturn.go +++ b/runtime/runturn.go @@ -35,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) {}