Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Preserve context state during session healing

wyt3a4dda8ff73a
diff --git a/src/core-agent/src/agent/persistent-session.ts b/src/core-agent/src/agent/persistent-session.ts
index d2441a54..b762000f 100644
--- a/src/core-agent/src/agent/persistent-session.ts
+++ b/src/core-agent/src/agent/persistent-session.ts
@@ -123,9 +123,13 @@ export class PersistentSession extends Session {
* `model/core-agent/session-store.ts`).
*/
healAndPersist(): boolean {
- const changed = this.healOrphanToolUses();
- if (changed) this.flushToDisk();
- return changed;
+ // Heal the cached in-memory session only. We deliberately do NOT flushToDisk:
+ // by this point memory has been trimmed to the rolling window, and flushToDisk
+ // rewrites the whole jsonl from that window — which would drop history older
+ // than the window from the append-only log. The append log stays intact and
+ // the constructor's load-time heal re-applies the same (idempotent) fix on the
+ // next reload, where memory holds the full history so a flush is lossless.
+ return this.healOrphanToolUses();
}
/**
@@ -325,8 +329,10 @@ export class PersistentSession extends Session {
if (!changed) return false;
- super.clear();
- for (const mm of fixed) super.addMessage(mm.role, mm.content);
+ // Preserve the rolling summary + resources across the merge — clearing and
+ // re-adding would null turnState and drop them (see method doc). On the load
+ // path turnState is still null here, so this is a plain message swap.
+ this.replaceMessagesPreservingContext(fixed);
return true;
}
diff --git a/src/core-agent/src/agent/session.ts b/src/core-agent/src/agent/session.ts
index fa6fb5cd..fc83113a 100644
--- a/src/core-agent/src/agent/session.ts
+++ b/src/core-agent/src/agent/session.ts
@@ -556,6 +556,31 @@ export class Session {
return this.turnState;
}
+ /**
+ * Swap the entire message array (e.g. after healing orphan or merging parallel
+ * tool_result blocks) while keeping the rolling history summary + resources
+ * intact — only the turn *indices* are re-derived from the new messages.
+ *
+ * Without this, a heal that merges the N separate tool_result messages a
+ * multi-tool turn produces would `clear()` (nulling turnState) and the next
+ * turn would rebuild an empty turnState, silently dropping the accumulated
+ * context summary and resource ledger. Merging tool_result blocks does not add
+ * or remove turns, so re-deriving indices keeps summaryThroughTurnId aligned.
+ */
+ protected replaceMessagesPreservingContext(messages: Message[]): void {
+ const prev = this.turnState;
+ this.messages = messages.slice();
+ this.turnState = prev
+ ? this.rebuildTurnStateFromMessages({
+ historySummary: prev.historySummary,
+ summaryVersion: prev.summaryVersion,
+ summaryThroughTurnId: prev.summaryThroughTurnId,
+ resources: prev.resources,
+ nextTurnId: prev.nextTurnId,
+ })
+ : null;
+ }
+
private rebuildTurnStateFromMessages(preserve?: {
historySummary?: string;
summaryVersion?: number;
diff --git a/src/core-agent/test/persistent-session.test.ts b/src/core-agent/test/persistent-session.test.ts
index 8585c0e3..fda610f3 100644
--- a/src/core-agent/test/persistent-session.test.ts
+++ b/src/core-agent/test/persistent-session.test.ts
@@ -468,6 +468,67 @@ describe("PersistentSession", () => {
expect(fresh.getMessages()[2].content[0].type).toBe("tool_result");
});
+ it("heals memory without rewriting the append-only jsonl (P0-1 no truncation)", () => {
+ // A benign multi-tool turn (2 parallel tool_results) makes heal consolidate
+ // the two tool_result messages in memory. healAndPersist must NOT flush that
+ // shorter view over the append-only log — doing so would drop any history
+ // older than the trimmed in-memory window.
+ const s = new PersistentSession({ sessionFile: file });
+ s.beginUserTurn([{ type: "text", text: "go" }]);
+ s.addAssistantMessage([
+ { type: "tool_use", id: "a", name: "a", input: {} },
+ { type: "tool_use", id: "b", name: "b", input: {} },
+ ]);
+ s.addToolResult("a", "ra", undefined, false);
+ s.addToolResult("b", "rb", undefined, false);
+
+ const diskBefore = fs.readFileSync(file, "utf-8").trim().split("\n").length;
+ expect(diskBefore).toBe(4); // user, assistant, tool_result(a), tool_result(b)
+
+ expect(s.healAndPersist()).toBe(true); // merges the two tool_result messages
+ const mem = s.getMessages();
+ expect(mem).toHaveLength(3);
+ expect(
+ mem[2].content.filter((c) => (c as { type?: string }).type === "tool_result"),
+ ).toHaveLength(2);
+
+ // Append log is intact — not rewritten to the merged/trimmed view.
+ const diskAfter = fs.readFileSync(file, "utf-8").trim().split("\n").length;
+ expect(diskAfter).toBe(diskBefore);
+ });
+
+ it("preserves the history summary + resource ledger across a multi-tool heal (P0-1)", () => {
+ const s = new PersistentSession({ sessionFile: file });
+ // Turn 1, then roll it into a summary + record a produced resource.
+ s.beginUserTurn([{ type: "text", text: "turn one" }]);
+ s.addAssistantMessage([{ type: "tool_use", id: "t1", name: "a", input: {} }]);
+ s.addToolResult("t1", "r1", undefined, false);
+ s.completeActiveTurn();
+ s.applyHistorySummary("rolling summary", [1]);
+ s.addHistoryResource({ kind: "final_output", path: "/w/report.mov", name: "report.mov" });
+
+ // Turn 2: two parallel tool_results — the benign heal trigger that used to
+ // clear() and wipe turnState (summary + resources) on the next turn.
+ s.beginUserTurn([{ type: "text", text: "turn two" }]);
+ s.addAssistantMessage([
+ { type: "tool_use", id: "t2a", name: "a", input: {} },
+ { type: "tool_use", id: "t2b", name: "b", input: {} },
+ ]);
+ s.addToolResult("t2a", "r2a", undefined, false);
+ s.addToolResult("t2b", "r2b", undefined, false);
+
+ expect(s.getSerializedContextState()?.historySummary).toBe("rolling summary");
+ expect(s.getSerializedContextState()?.resources).toHaveLength(1);
+
+ expect(s.healAndPersist()).toBe(true);
+
+ const after = s.getSerializedContextState();
+ expect(after?.historySummary).toBe("rolling summary");
+ expect(after?.resources).toHaveLength(1);
+ expect(after?.resources[0].name).toBe("report.mov");
+ expect(JSON.stringify(s.getMessagesForModel())).toContain("rolling summary");
+ });
+
it("merges parallel tool_results split across adjacent user messages", () => {
// The runner's `addToolResult` writes one user message per tool_use_id.
// So an assistant turn with 3 parallel tool_calls produces 3 adjacent