Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Session Management
Luna persists conversations in dual-write mode: JSONL (human/stream replay) + SQLite/FTS5 (search + cross-session memory). Each JSONL line is a message, tool call, or tool result.
Session Location
~/.luna/sessions/<timestamp>-<hash>.jsonl
Example: ~/.luna/sessions/2026-04-22-143052-a3f8.jsonl
Session Lifecycle
- New session created on startup (unless
--resumeis used) - Messages appended incrementally during conversation — no rewriting the entire file
- Session rotation when file exceeds 256KB — current context preserved, old file archived
- Old sessions remain in
~/.luna/sessions/for future reference (retain-forever unless the opt-in sweep below is run)
Starting a Session
# New session (default; configure a provider key or connect to Sol first)
luajit client/main.lua --connect tcp://127.0.0.1:5555
# Resume last session
luajit client/main.lua --resume
# Resume specific session file
luajit client/main.lua --session ~/.luna/sessions/2026-04-22-143052-a3f8.jsonl
Session trees, branching, and retention
Messages carry parent_id plus an optional branch; a session keeps a
leaf_id and active_branch. Session:branch(from_id, name) creates a
named in-file branch at an existing message and checks it out;
Session:switch_leaf(id) time-travels to any message; Session:switch_branch
resumes a branch’s tip (not its root), including main. A fork
(fork_to_file) snapshots the leaf→root view, drops compacted blocks, and
carries the leaf, active branch, branch entries, and title. /rename NAME
sets the session display name (persisted in the JSONL session_meta/title);
/tree, /branch, and /switch N|NAME expose the same tree locally.
Retention/GC (; supersedes the retain-forever-only
posture): session corpora remain retain-forever by default — no
automatic age/TTL sweep runs unless session_gc.enabled=true (off by
default) or an operator explicitly invokes a sweep. The sweep is
whole-session only:
luna --gc-sessions # dry run: list eligible corpus
luna --gc-apply # apply (age/idle/lease guarded)
luna --gc-max-age-days 30 --gc-limit 100
Inside the TUI: /gc is a dry run; /gc run [DAYS] applies (an explicit
run is required). Config: session_gc.{enabled,max_age_days, min_idle_seconds,page_size,dry_run,delete_trajectory,delete_orphan_tmp}.
One candidate = the primary <id>.jsonl plus its rotations (.1, .2),
a stranded .rotate.tmp, trajectory_<id>.jsonl (default on), and the
stale <id>.jsonl.active lease. A sweep deletes, in order: the SQLite
sessions/messages rows (both FTS tables are maintained by the DELETE
triggers), the JSON index entry, then the files. It also removes
age-gated orphan .luna_session_* / .luna_edit_* temps. It is
idempotent and re-checks eligibility immediately before mutation.
Explicit exclusions (owned by other planes, never deleted by session GC):
content-addressed blobs (core.blob_store’s own 30-day GC owns them)
analytics rows (~/.luna/analytics.db)
git snapshots (core.git_snapshot retention)
session-scoped memory
Guards: the current in-process session, a held .active lease (live
processes hold one from attach/save until close; the kernel drops it on
crash), corpora active within min_idle_seconds, anything newer than
max_age_days, and symlinked artifacts are all skipped/refused. A
destructive sweep serializes through <sessions>/.gc.lock.
/delete now uses the same whole-session path for the current session
(primary, rotations, trajectory, SQLite rows, index entry) and then
starts a replacement session; the old single-file removal left the
rotated generations and the search rows behind.
Secure-deletion limits: this is an unlink/truncate-level sweep, not cryptographic erasure. Filesystem journals, copy-on-write layers, SSD wear-levelling, snapshots, and backups can retain prior bytes after the path disappears; SQLite pages may survive in copies/backups (the live WAL is checkpoint-truncated per batch). Use full-disk encryption and backup expiry if the threat model requires physical erasure.
Branch pruning remains an explicit operator action with the branch root and any shared prefix retained; automatic per-branch tree GC is a successor (residual register). The tree metadata above is the prerequisite for that sweep.
Editor chat sessions
:ZergChat in example/vim is a real Luna session, not an in-memory
bridge conversation. The store-location decision for the long view §9 is:
Operator home, per project: ~/.luna/sessions/editor-chat-<name>-<hash>.jsonl.
Sessions are private operator data; project .luna/ is repo-controlled
configuration and must not carry a conversation log. The <hash> is
derived from the resolved workspace root (git rev-parse --show-toplevel
when available, the working directory otherwise), so the same project
resumes its chat across editor restarts while another project gets a
fresh one — no cross-project leakage.
Format: the standard session JSONL above (tree metadata, leaf pointer,
branches, compaction records). Resume is Session.load_from_path; the
compaction no-resurrection property is the session plane’s standing
contract. A corrupt/unloadable editor session is a typed
session_load_failed, never a silent fresh start.
Checkpoint ownership: standalone/stdio chats checkpoint in the local
Luna store. When the editor is Sol-bound (:ZergConnect), the chat
session and its checkpoints are Sol-owned (’s session-control
plane); the local store is not the authority there.
g:mocha_zerg_chat_session overrides the path; --session PATH on
example/vim/luna-local.lua --chat does the same from the CLI.
Ops console: session tree & snapshots
Limon’s chat sidebar renders the active worker’s headless surface through
Sol’s /api/v1/chat/:id/branches|snapshots|snapshots/:snapshot_id/diff
reads and the two mutation routes:
Branches lists main plus every named branch (root/leaf counts,
active marker, title). Admin operators can check out a branch; the
console confirms first and the server strict-audits
session_branch_checkout.
Snapshots lists git snapshots recorded by the worker
(id/timestamp/tool/description/files). Admin operators can
restore one after confirmation; the server strict-audits
session_snapshot_restore (snapshot id + file count, never file
bodies). The diff view is a bounded summary (files/insertions/
deletions, 8 KiB diff cap).
Both mutations carry the caller’s identity and are refused with the typed
session_busy (409) while a turn is running — the UI surfaces that
verdict instead of silently retrying. A worker with no task session yet
renders the typed no_active_session empty state; a workspace that is not
a git repository renders snapshot_unavailable — never an empty list that
looks like success. See the API reference for the full route/status table
and the session_control wire lines.
Session Branching
Branch a conversation at any point. The branch creates a new session file with messages up to the branch point, then continues independently from the original.
This is useful for: Exploring alternative approaches without losing context Testing different solutions to the same problem Creating parallel investigations
Tree-Structured JSONL
Sessions use a tree-structured JSONL format with parentId and branch fields:
Each entry has a parentId referencing the previous entry in the conversation
Branches are named and can be navigated independently
Typed entries include: mode_change, model_change, compaction, branch_summary, checkpoint, label
Branch CRUD
/branch [name] — Create a named branch at the current position
/switch <name> — Switch to an existing branch
/tree — Display the full branch tree with entry counts
Branches can be merged back into the main conversation
Checkpoint/Restore
Automatic checkpoints are created at key moments (before background tasks, before risky operations)
Use checkpoints to restore session state to a known point
Checkpoint metadata includes mode, model, and message count for full recovery
Git position: when the session has a workspace_root
that is a git repo, checkpoints record the working-tree HEAD hash
(capture_hash — no commit is performed; snapshots are separate
commits) and restore_checkpoint restores the working tree to that
position (git checkout <hash> --.). Git capture is scoped to the
session’s workspace — a session without a workspace root records
git_hash = nil.
Session Sharing
Sessions can be shared via public links (Mnesia-backed with a TTL):
POST /api/v1/sessions — create a share link. Body: session_data
(REQUIRED, 400 session_data_required without it), optional format
and ttl_days. Returns 201 with the share id. (The old documented
POST /api/v1/sessions/:id/share / GET /api/v1/sessions/share/:token
pair returned 405 — the GET route did not exist.)
GET /api/v1/shares/:share_id — retrieve the shared session:
{data, format, created_at} (200), 404 when expired or unknown
.
DELETE /api/v1/sessions/:share_id — delete a share (owner/admin).
Session Bundles — local export/import
A signed .zergsession bundle moves a session tree plus a bounded
memory subset and inert snapshot refs between Luna homes. It is the
portable unit behind core.session_export; the upload/download half is
Design only (see plan/session-export-format.md and the
SESSION-BUNDLE-CROSSNODE-SECURITY-REVIEW exit gate).
Contents: the session’s own JSONL record set (messages, branches,
leaf, active branch, title, labels, notes, checkpoints, compaction
records), a scoped memory subset, and git_snapshot refs. The source
workspace_root and local blob refs are not exported.
No credentials, ever: every string (values and keys) passes through
the shared core.redaction contract; a second pass refuses anything that
still looks secret (secret_material_detected). Import enforces the same
gate.
Trust: the bundle header records issuer mango, exporter, recipient,
issued/expiry timestamps, audience, nonce, and a key_id derived from
the Mango bearer token. The token itself is never stored; the HMAC key is
derived from it (or from an explicit offline signing_key). Import
refuses expired_trust, wrong_recipient, bad_signature, and
bad_content_hash.
Integrity: canonical JSON content hash + HMAC-SHA256 with a fixed
verification order. Size caps: 8 MiB bundle, 5,000 records, 1,000 memory
entries, 200 snapshot refs.
Local import: writes <session_id>.jsonl atomically (0600, fsync,
rename, dir fsync), merges the memory subset through the JSON memory
backend, reopens the session, and verifies the tree header before
reporting success. Snapshot refs are returned as metadata and are never
replayed into git.
Cross-node: proposed POST/GET/DELETE /api/v1/session-bundles… routes
with Mango identity checks, the same caps, and content-free audit rows.
Nothing server-side ships until the named security review passes.
The local spike lives in client/tests/test_session_export.lua
(two temp homes: export → import → reopen → compare); the corpus-grep
contract is tests/test_session_export_grep.py.
Session Events Bridge
Session events are driven by ZMQ workflow events:
session_events.lua subscribes to workflow lifecycle events
Checkpoints are automatically created on workflow.started, step.started, completed, and failed events
Workflow state is tracked alongside session state for full auditability
Agent Turn Event Stream (Luna in-process)
Luna publishes one typed AgentEvent per turn milestone on the EventBus /
Hooks channel agent.event (in-process only — it is not a wire frame).
The envelope is {schema, type, seq, ts_ms, agent_id, session_id, turn_id, parent_id, iteration, data}; seq is per-turn monotonic from 1.
| Type | When | Key data fields | Terminal |
|---|---|---|---|
agent.started | after the system prompt is ensured, before the first request | mode, model, provider, session_id, input_length, max_iterations, parent_id | no |
agent.stream | each text/thinking delta | channel ("text"|"thinking"), text, accumulated_length | no |
agent.tool_start | dispatch entry (post-gate for execution) | tool_call_id, name, input | no |
agent.tool_end | each tool result/refusal | tool_call_id, name | no |
agent.compacted | a compaction stage completed | trigger (proactive|overflow|post_tools|auto|pre_stream), messages_removed, messages_preserved, summary_length | no |
agent.interrupted | the interrupt latch is consumed | reason (stream_interrupted|followup_interrupted) | no |
agent.ended | the turn’s terminal turn_done | success, error, reason, interrupted, output_length, iterations, duration_ms | yes, exactly once |
agent.tool_end guarantees a prior agent.tool_start with the same
tool_call_id (a synthetic start is emitted for pre-dispatch refusals).
The legacy yield stream and the existing agent.turn_* / provider.*
events are unchanged; the canonical stream is additive and subscriber-gated.
Context Compaction
When the conversation context exceeds the model’s token threshold, Luna compacts the session:
- Preserves system prompt and recent messages
- Summarizes older messages into a compact form
- Tool use/results are preserved or summarized depending on relevance
- All messages remain in
_all_messagesfor full history access
Compaction happens automatically — no user action needed.
Session Format (JSONL)
Each line is a JSON object with a type field:
{"type":"user","content":"Fix the bug in main.rs"}
{"type":"assistant","content":"I'll look at the file first.","tool_uses":[{"id":"tu_1","name":"read_file","input":{"path":"src/main.rs"}}]}
{"type":"tool_result","tool_use_id":"tu_1","content":"fn main() {\n println!(\"Hello\");\n}"}
{"type":"assistant","content":"The issue is on line 2. Let me fix it.","tool_uses":[{"id":"tu_2","name":"edit_file","input":{"path":"src/main.rs","old_text":"Hello","new_text":"Hello, world"}}]}
{"type":"tool_result","tool_use_id":"tu_2","content":"File edited successfully"}
{"type":"assistant","content":"Fixed! The bug was a missing greeting."}
Message Types
| Type | Fields | Description |
|---|---|---|
user | content | User input message |
assistant | content, tool_uses | Agent response (may include tool calls) |
tool_result | tool_use_id, content | Result of a tool execution |
Session Files
Sessions are stored as plain JSONL text files. You can:
Inspect them with any text editor or jq
Search them with grep
Archive them by moving files out of ~/.luna/sessions/
Share them as conversation logs
Rotation and recovery
Large session files rotate: when the append file exceeds ~256 KiB
(ROTATE_AFTER_BYTES) the current file becomes path.1, the previous
.1 becomes .2 (older generations are dropped). A torn or empty
primary file is recovered on load by falling back through the rotated
generations in that order — .1 (newest) then .2. Recovery carries the
rotated generation’s compaction record and labels.
Close is a synchronous flush point
Session:close flushes any pending deferred save INLINE before the
SQLite backend closes — the dual write (JSONL + SQLite) completes at
teardown even when an event loop is present (the normal save path may
defer to the loop; close must not).
Session Mode Persistence
The current agent mode is saved in the session and restored when resuming:
# Session was in "explore" mode when last used
luajit client/main.lua --resume
# Agent continues in "explore" mode
Mode is stored as the mode field in session metadata.
Auto-Generated Session Titles
Sessions automatically get a descriptive title generated by a hidden utility agent:
- After the first assistant response, a title generation agent runs in the background
- Uses a lightweight LLM call to summarize the conversation into a short title
- Falls back to truncating the first user message if the LLM call fails
- Title is stored in session metadata and used by
--sessionsand--search
TUI slash commands
The Luna TUI exposes slash commands that are not zerg CLI commands.
They operate on the live session/agent in the terminal. /help prints the
current list; extension commands are added by /skills and plugins.
| Command | Purpose |
|---|---|
/help, /h | Show the command list |
/quit, /q | Exit Luna |
/new | Start a new session |
/clear | Clear the chat view |
/status | Show session status |
/compact | Compact the session context |
/model [NAME] | Get or set the model |
/mode [NAME] | Cycle or switch the agent mode |
/modes, /agents | List available modes |
/thinking [LVL] | Get or set the thinking level |
/build, /plan, /explore, /review, /general | Switch mode |
/agent, /mode | Switch or inspect the active mode |
/history | Show command history |
/menu, /m | Open the command menu |
/mcp | List MCP servers and tools |
/cost | Show token usage and cost |
/copy, /copyall | Copy the last message / full transcript |
/export [FILE] | Export the transcript |
/delete | Delete the current session and its artifacts |
/gc, /gc run [DAYS] | Dry-run or apply session-corpus GC |
/rename NAME | Rename the current session/branch |
/tree | List branches with the active marker |
/branch [NAME], /fork [NAME] | Create a branch at the current leaf |
/switch N, /jump N | Switch to a branch by index |
/rollback [N] | Drop the last N turns (default 1), auto-branching first |
/image [PATH] | Display an image inline |
/tutorial [reset] | Start or reset the interactive tutorial |
/tools-list, /tools-reload | List or hot-reload workspace tools |
/skills | List/install/manage skills |
/sandbox | Inspect or change the sandbox posture |
/install <dep> | Install an allowlisted dependency |
/theme [NAME] | Get or set the color theme |
/keymaps, /keys | Show current keybindings |
/configure | Run the configuration wizard |
/info | Show diagnostic information |
/docs | Open the canonical docs at https://docs.zergs.net/ |
/interrupt | Interrupt the running agent turn |
Session Search
Search past sessions by content, model, or workspace:
# Search sessions matching a keyword
luajit client/main.lua --search "quicksort"
# List recent sessions
luajit client/main.lua --sessions
# Resume the most recent session
luajit client/main.lua --resume-latest
Sessions are indexed by message content, model name, and workspace path. Index is built lazily on first search.
Disk Usage
Average session: 10-100KB
Large sessions (with many tool calls): up to 256KB before rotation
Sessions rotate automatically but are retained by default — use the
opt-in sweep above (--gc-apply or /gc run [DAYS]) to reclaim space
In-memory/JSONL record retention is bounded by MAX_ALL_MESSAGES
(LUNA_SESSION_MAX_MESSAGES, default 1000; the drop is counted and
logged). This is a per-session record cap, not a corpus GC.
Corruption visibility
JSONL load: session.load_dropped_lines counts dropped/torn lines after a
load; the log carries the count + a first-line snippet. Silent data loss is now
measurable.
SQLite: the FTS index rebuilds only when the fingerprint changes (not every
open); session_sqlite:integrity_check runs PRAGMA integrity_check on demand
(operator surface — no CLI command yet); PRAGMA optimize fires on close.
Blobs: LUNA_BLOB_MAX_BYTES (default 10 MB) rejects oversized stores loudly;
a torn blob (content-hash mismatch) raises on retrieve — never a silent nil.