Class SessionTree

java.lang.Object
io.agentscope.harness.agent.memory.session.SessionTree

public class SessionTree extends Object
Manages an append-only JSONL session tree (pi-mono-inspired).

The session file is a JSONL file where each line is a JSON-serialized SessionEntry. Entries form a tree via id/parentId links. A companion .log.jsonl file stores the full history for grep-ability (dual-file pattern from pi-mono mom).

File layout

   agents/{agentId}/sessions/{sessionId}.jsonl      — LLM context (compacted)
   agents/{agentId}/sessions/{sessionId}.log.jsonl   — full history (append-only, never compacted)
 

Persistence model

The local file is the working copy. Cross-replica durability uses one of:
  • TranscriptStore (preferred) — each flush writes an immutable segment; concurrent writers never overwrite each other.
  • AbstractFilesystem full-file mirror (legacy) — O(N²) uploads and last-writer-wins across replicas; kept for backward compatibility when no TranscriptStore is set.

Deferred persistence

Entries are buffered in memory and only flushed to disk on the first call to flush() (typically after the first assistant message). This avoids partial session files from failed/short interactions.
  • Constructor Details

    • SessionTree

      public SessionTree(Path contextFile, Path workspaceRoot, AbstractFilesystem filesystem)
      Creates a SessionTree backed by the given filesystem for remote mirroring.
      Parameters:
      contextFile - path to the .jsonl context file (LLM-facing, compacted)
      workspaceRoot - root of the agent workspace; used to derive workspace-relative paths
      filesystem - AbstractFilesystem used for remote read/write; may be null to disable remote mirroring (local-only mode)
    • SessionTree

      public SessionTree(Path contextFile, Path workspaceRoot, AbstractFilesystem filesystem, WorkspaceIndex index)
    • SessionTree

      public SessionTree(Path contextFile, Path workspaceRoot, AbstractFilesystem filesystem, WorkspaceIndex index, String contextRelativePath)
      Creates a SessionTree with optional best-effort workspace index support.
      Parameters:
      contextFile - path to the .jsonl context file
      workspaceRoot - root of the agent workspace
      filesystem - remote filesystem; may be null
      index - best-effort workspace index; may be null
      contextRelativePath - workspace-relative path for the context file WITHOUT namespace prefix (e.g. agents/X/sessions/Y.jsonl); when non-null, used for filesystem mirror/restore instead of computing via toWorkspaceRelative(Path)
  • Method Details

    • awaitMirrorQuiescence

      public static boolean awaitMirrorQuiescence(long timeout, TimeUnit unit)
      Blocks until all remote-mirror tasks submitted before this call have finished.

      The mirror executor is single-threaded and serial, so waiting on a sentinel task guarantees that every previously scheduled mirror upload has completed. Intended for graceful shutdown (HarnessAgent.close()) so asynchronous transcript/session mirrors do not race with resource cleanup (e.g., temp workspace deletion).

      Parameters:
      timeout - maximum time to wait
      unit - time unit of timeout
      Returns:
      true if the mirrors quiesced within the timeout
    • setRuntimeContext

      public SessionTree setRuntimeContext(io.agentscope.core.agent.RuntimeContext rc)
      Binds a RuntimeContext to this tree so that all subsequent remote filesystem reads and writes (including async mirror operations) propagate the caller's identity into namespace-aware stores. Defaults to RuntimeContext.empty() when never set.
      Parameters:
      rc - the runtime context to bind; null resets to empty
      Returns:
      this tree, for fluent chaining
    • setTranscriptStore

      public SessionTree setTranscriptStore(TranscriptStore store, TranscriptRef ref)
      Binds a TranscriptStore for segmented remote persistence. When set, flush() writes immutable segments instead of full-file mirrors, and syncFromRemote() merges from listed segments. history UI paths stay aligned with the local workspace. null disables segments
      Parameters:
      store - segment store; null disables segmented persistence
      ref - transcript identity; required when store is non-null
      Returns:
      this tree, for fluent chaining
    • load

      public void load()
      Loads existing entries from the local context file into the in-memory tree.

      This is a local-only, zero-network operation. If the local file is absent, the tree starts empty. To additionally pull and union-merge entries from the remote filesystem (e.g., before a write that may follow a cross-machine handoff), call syncFromRemote() after this method.

      Safe to call multiple times; only loads once.

    • syncFromRemote

      public void syncFromRemote()
      Pulls remote entries and union-merges any not yet present locally.

      When a TranscriptStore is bound, reads immutable segments (no whole-file overwrite race). Otherwise falls back to the legacy full-file remote mirror.

      load() must be called before this method.

    • append

      public SessionEntry append(SessionEntry entry)
      Appends an entry to the in-memory tree. The entry will be written to disk on the next flush() call.
      Returns:
      the entry (for chaining)
    • flush

      public void flush()
      Flushes pending entries to the local context and log files, then schedules asynchronous remote mirrors. When a TranscriptStore is bound, both immutable segments and the canonical context/log files are mirrored. The remote mirror is fire-and-forget: failures are logged as warnings and do not affect the return of this method. The local write is always the primary guarantee.
    • isFlushed

      public boolean isFlushed()
      Returns whether flush() has been called at least once.
    • buildContext

      public List<SessionEntry> buildContext()
      Builds the LLM-visible context from the session tree.

      Returns entries that the LLM should see:

      • If compaction has occurred, starts with the summary entry, then all entries from firstKeptEntryId onward
      • If no compaction, returns all message entries in order
    • getAllEntries

      public List<SessionEntry> getAllEntries()
      Returns all entries in append order (full history).
    • getMessageEntries

      public List<SessionEntry.MessageEntry> getMessageEntries()
      Returns only message entries in append order.
    • size

      public int size()
    • getContextFile

      public Path getContextFile()
    • getLogFile

      public Path getLogFile()
    • syncFromLog

      public int syncFromLog()
      Syncs entries from the log file that are not yet in the context file. This handles offline messages that were appended to the log while the agent was inactive.
      Returns:
      the number of new entries synced