Class: Kward::SessionStore
- Inherits:
-
Object
- Object
- Kward::SessionStore
- Defined in:
- lib/kward/session_store.rb
Overview
JSONL-backed persistence for CLI and RPC conversations.
A session file is an append-only event log: a header record, message/tree
records, metadata changes, memory state, tool execution metadata, labels, and
branch navigation. SessionStore owns disk layout and reconstruction of a
Conversation; frontends own when to create, resume, clone, compact, or
delete sessions.
The tree fields (id, parentId, leaf records, labels) are part of the
persisted user-data contract. Keep backward compatibility in mind before
changing record shapes, and prefer adding records over rewriting existing
files.
Defined Under Namespace
Classes: Session, SessionInfo
Constant Summary collapse
- VERSION =
2- LAST_SESSION_FILENAME =
"last_session.json"- NON_ACTIVITY_RECORD_TYPES =
%w[session session_info system_prompt].freeze
- RECORD_TYPE_PATTERN =
/\A\{\s*"type"\s*:\s*"([^"]+)"/- RECORD_TIMESTAMP_PATTERN =
/"timestamp"\s*:\s*"([^"]+)"/
Instance Attribute Summary collapse
-
#config_dir ⇒ String
readonly
Configuration directory containing session and tab files.
-
#cwd ⇒ String
readonly
Workspace directory this store lists and creates sessions for.
Class Method Summary collapse
Instance Method Summary collapse
- #append_label_change(path, entry_id, label) ⇒ Object
- #append_leaf_change(path, leaf_id) ⇒ Object
- #append_record(path, record) ⇒ Object
- #append_system_prompt_snapshot(path, system_message, reason: "changed", latest_hash: nil) ⇒ Object
-
#build_tree_record(path, type, parent_id, fields = {}) ⇒ Hash
Builds a persisted tree record and assigns a stable entry id to messages.
-
#capture_branch(path) ⇒ Hash
Returns the complete persisted active branch for an explicit export-like consumer.
-
#capture_candidates ⇒ Object
Lists all persisted sessions under this config directory for an explicit user-selected operation such as skill capture.
-
#create(provider: nil, model: nil, reasoning_effort: nil, parent_id: nil, parent_path: nil) ⇒ Object
Creates a new empty session file for the store's workspace directory.
- #create_from_conversation(conversation, parent_session: nil) ⇒ Object
- #create_independent_from_conversation(conversation, parent_session: nil) ⇒ Object
-
#create_independent_from_messages(messages, read_paths: [], provider: nil, model: nil, reasoning_effort: nil, parent_session: nil) ⇒ Array(Session, Conversation)
Creates a new session containing an independent copy of selected messages.
-
#current_leaf(path) ⇒ String?
Current active tree leaf id.
-
#delete_unused_session(session) ⇒ Boolean
Deletes an empty unnamed session file.
-
#initialize(config_dir: ConfigFiles.config_dir, cwd: Dir.pwd) ⇒ SessionStore
constructor
Creates an object for JSONL session persistence.
- #last_session_path ⇒ Object
-
#load(path, workspace: Workspace.new, provider: nil, model: nil, reasoning_effort: nil, project_skill_paths: nil) ⇒ Object
Loads a session file and reconstructs its current conversation leaf.
-
#recent(limit: 20, keep_empty_path: nil) ⇒ Array<SessionInfo>
Lists recent non-empty sessions for this workspace.
-
#recent_tree(limit: 20, keep_empty_path: nil) ⇒ Array<SessionInfo>
Lists recent sessions decorated with parent/branch display metadata.
-
#remember_last_session(session) ⇒ Object
Persists the last active session pointer for workspace auto-resume.
-
#remembered_last_session_path ⇒ String?
Remembered session path when the file still exists.
- #session_dir ⇒ Object
-
#session_entries(path) ⇒ Array<Hash>
Flat tree records with resolved labels attached.
-
#session_entry(path, entry_id) ⇒ Hash?
Finds one persisted tree entry by id.
-
#session_location(path) ⇒ Hash
Resolves a user-provided path and returns the stored workspace location.
-
#session_tree(path) ⇒ Array<Hash>
Nested session tree roots for the given session file.
Constructor Details
#initialize(config_dir: ConfigFiles.config_dir, cwd: Dir.pwd) ⇒ SessionStore
Creates an object for JSONL session persistence.
205 206 207 208 209 |
# File 'lib/kward/session_store.rb', line 205 def initialize(config_dir: ConfigFiles.config_dir, cwd: Dir.pwd) @config_dir = config_dir @cwd = File.(cwd) @session_catalog = SessionCatalog.new(session_dir: session_dir) end |
Instance Attribute Details
#config_dir ⇒ String (readonly)
Returns configuration directory containing session and tab files.
215 216 217 |
# File 'lib/kward/session_store.rb', line 215 def config_dir @config_dir end |
#cwd ⇒ String (readonly)
Returns workspace directory this store lists and creates sessions for.
212 213 214 |
# File 'lib/kward/session_store.rb', line 212 def cwd @cwd end |
Class Method Details
.safe_cwd(cwd) ⇒ Object
526 527 528 |
# File 'lib/kward/session_store.rb', line 526 def self.safe_cwd(cwd) "--#{File.(cwd).sub(%r{\A[/\\]}, "").gsub(%r{[/\\:]}, "-")}--" end |
Instance Method Details
#append_label_change(path, entry_id, label) ⇒ Object
441 442 443 444 445 446 447 448 449 450 451 |
# File 'lib/kward/session_store.rb', line 441 def append_label_change(path, entry_id, label) record = { type: "label", id: next_entry_id(path), timestamp: Time.now.utc.iso8601(3), targetId: entry_id.to_s, label: label.to_s.strip.empty? ? nil : label.to_s.strip } append_record(path, record) record end |
#append_leaf_change(path, leaf_id) ⇒ Object
431 432 433 434 435 436 437 438 439 |
# File 'lib/kward/session_store.rb', line 431 def append_leaf_change(path, leaf_id) record = { type: "leaf", timestamp: Time.now.utc.iso8601(3), targetId: leaf_id } append_record(path, record) record end |
#append_record(path, record) ⇒ Object
501 502 503 504 505 506 |
# File 'lib/kward/session_store.rb', line 501 def append_record(path, record) File.open(path, "a", 0o600) do |file| file.write(JSON.generate(record)) file.write("\n") end end |
#append_system_prompt_snapshot(path, system_message, reason: "changed", latest_hash: nil) ⇒ Object
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 |
# File 'lib/kward/session_store.rb', line 508 def append_system_prompt_snapshot(path, , reason: "changed", latest_hash: nil) content = MessageAccess.content().to_s return latest_hash if content.empty? hash = system_prompt_hash(content) latest_hash ||= latest_system_prompt_hash(records_from_file(path)) return latest_hash if latest_hash == hash append_record(path, { type: "system_prompt", timestamp: Time.now.utc.iso8601(3), reason: reason.to_s, hash: hash, content: content }) hash end |
#build_tree_record(path, type, parent_id, fields = {}) ⇒ Hash
Builds a persisted tree record and assigns a stable entry id to messages.
419 420 421 422 423 424 425 426 427 428 429 |
# File 'lib/kward/session_store.rb', line 419 def build_tree_record(path, type, parent_id, fields = {}) = fields[:message] id = () || next_entry_id(path) (, id) if .is_a?(Hash) { type: type, id: id, parentId: parent_id, timestamp: Time.now.utc.iso8601(3) }.merge(fields).delete_if { |_key, value| value.nil? } end |
#capture_branch(path) ⇒ Hash
Returns the complete persisted active branch for an explicit export-like consumer. Unlike #load, this does not attach a conversation or mutate the session file.
490 491 492 493 494 495 496 497 498 499 |
# File 'lib/kward/session_store.rb', line 490 def capture_branch(path) resolved_path = resolve_session_path(path) records = records_from_file(resolved_path) { path: resolved_path, header: session_header(records, resolved_path), system_prompts: records.select { |record| record["type"] == "system_prompt" }, entries: branch_records(records) } end |
#capture_candidates ⇒ Object
Lists all persisted sessions under this config directory for an explicit user-selected operation such as skill capture. Unlike #recent, this is not scoped to the store's current workspace.
357 358 359 360 361 362 |
# File 'lib/kward/session_store.rb', line 357 def capture_candidates pattern = File.join(@config_dir, "sessions", "**", "*.jsonl") Dir.glob(pattern).filter_map { |path| session_info(path) }.sort_by(&:modified_at).reverse rescue StandardError [] end |
#create(provider: nil, model: nil, reasoning_effort: nil, parent_id: nil, parent_path: nil) ⇒ Object
Creates a new empty session file for the store's workspace directory.
Parent fields record clone/fork ancestry; they do not imply live coupling between files after creation.
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 |
# File 'lib/kward/session_store.rb', line 221 def create(provider: nil, model: nil, reasoning_effort: nil, parent_id: nil, parent_path: nil) dir = session_dir FileUtils.mkdir_p(dir, mode: 0o700) created_at = Time.now.utc id = SecureRandom.uuid path = File.join(dir, "#{created_at.iso8601(3).tr(':', '-')}_#{id}.jsonl") header = { type: "session", version: VERSION, id: id, timestamp: created_at.iso8601(3), cwd: @cwd, provider: provider.to_s, model: model.to_s, reasoningEffort: reasoning_effort.to_s, parentId: parent_id.to_s, parentPath: parent_path.to_s }.delete_if { |_key, value| value.to_s.empty? } File.open(path, File::WRONLY | File::CREAT | File::EXCL, 0o600) do |file| file.write(JSON.generate(header)) file.write("\n") end File.chmod(0o600, path) Session.new(store: self, id: id, path: path, cwd: @cwd, created_at: created_at, parent_id: parent_id, parent_path: parent_path, leaf_id: nil, modified_at: created_at) end |
#create_from_conversation(conversation, parent_session: nil) ⇒ Object
249 250 251 252 253 254 255 |
# File 'lib/kward/session_store.rb', line 249 def create_from_conversation(conversation, parent_session: nil) session = create(provider: conversation.provider, model: conversation.model, reasoning_effort: conversation.reasoning_effort, parent_id: parent_session&.id, parent_path: parent_session&.path) session.rename(parent_session.name) unless parent_session&.name.to_s.strip.empty? (conversation).each { || session.() } session.attach(conversation) session end |
#create_independent_from_conversation(conversation, parent_session: nil) ⇒ Object
257 258 259 260 261 262 263 264 265 266 |
# File 'lib/kward/session_store.rb', line 257 def create_independent_from_conversation(conversation, parent_session: nil) ( (conversation), read_paths: Array(conversation.read_paths), provider: conversation.provider, model: conversation.model, reasoning_effort: conversation.reasoning_effort, parent_session: parent_session ) end |
#create_independent_from_messages(messages, read_paths: [], provider: nil, model: nil, reasoning_effort: nil, parent_session: nil) ⇒ Array(Session, Conversation)
Creates a new session containing an independent copy of selected messages.
Used by clone/fork flows where the new conversation must preserve selected history but then diverge without mutating the source session file.
277 278 279 280 281 282 283 284 285 |
# File 'lib/kward/session_store.rb', line 277 def (, read_paths: [], provider: nil, model: nil, reasoning_effort: nil, parent_session: nil) session = create(provider: provider, model: model, reasoning_effort: reasoning_effort, parent_id: parent_session&.id, parent_path: parent_session&.path) session.rename(parent_session.name) unless parent_session&.name.to_s.strip.empty? persisted = persistence_copy() persisted.each { || session.() } conversation = Conversation.new(messages: persistence_copy(persisted), read_paths: read_paths, workspace_root: @cwd, provider: provider, model: model, reasoning_effort: reasoning_effort) session.attach(conversation) [session, conversation] end |
#current_leaf(path) ⇒ String?
Returns current active tree leaf id.
481 482 483 |
# File 'lib/kward/session_store.rb', line 481 def current_leaf(path) current_leaf_id(records_from_file(resolve_session_path(path))) end |
#delete_unused_session(session) ⇒ Boolean
Deletes an empty unnamed session file.
398 399 400 401 402 403 404 405 406 407 408 409 |
# File 'lib/kward/session_store.rb', line 398 def delete_unused_session(session) path = session.path return false if session_named?(session) return false unless unused_session_file?(path) File.delete(path) @session_catalog.remove(path) @session_catalog.flush true rescue StandardError false end |
#last_session_path ⇒ Object
372 373 374 |
# File 'lib/kward/session_store.rb', line 372 def last_session_path File.join(session_dir, LAST_SESSION_FILENAME) end |
#load(path, workspace: Workspace.new, provider: nil, model: nil, reasoning_effort: nil, project_skill_paths: nil) ⇒ Object
Loads a session file and reconstructs its current conversation leaf.
workspace is used both for the active root and to restore read-before-write
paths from successful read tool results. If a session moved workspaces, load
it through session_location first so the original cwd is respected.
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 |
# File 'lib/kward/session_store.rb', line 302 def load(path, workspace: Workspace.new, provider: nil, model: nil, reasoning_effort: nil, project_skill_paths: nil) resolved_path = resolve_session_path(path) records = records_from_file(resolved_path) header = session_header(records, resolved_path) leaf_id = current_leaf_id(records) = (records) name = session_name(records) read_paths = restored_read_paths(, workspace) memory_state = restored_memory_state(records) runtime = session_runtime(records, header) conversation = Conversation.new( messages: , read_paths: read_paths, workspace_root: workspace.root, provider: runtime["provider"] || provider, model: runtime["model"] || model, reasoning_effort: runtime["reasoningEffort"] || reasoning_effort, session_memories: memory_state["sessionMemories"], last_memory_retrieval: memory_state["lastRetrieval"], project_skill_paths: project_skill_paths ) restore_tool_output_artifacts(records, conversation) conversation.mark_last_entry_compaction! if latest_record_type(records) == "compaction" created_at = parse_time(header["timestamp"]) || File.mtime(resolved_path) session = Session.new( store: self, id: header["id"], path: resolved_path, cwd: header["cwd"].to_s, created_at: created_at, name: name, parent_id: header["parentId"], parent_path: header["parentPath"], leaf_id: leaf_id, modified_at: session_modified_at(records, fallback: created_at), system_prompt_hash: latest_system_prompt_hash(records) ) session.attach(conversation) [session, conversation] end |
#recent(limit: 20, keep_empty_path: nil) ⇒ Array<SessionInfo>
Lists recent non-empty sessions for this workspace.
350 351 352 |
# File 'lib/kward/session_store.rb', line 350 def recent(limit: 20, keep_empty_path: nil) recent_sessions(limit: limit, keep_empty_path: keep_empty_path) end |
#recent_tree(limit: 20, keep_empty_path: nil) ⇒ Array<SessionInfo>
Lists recent sessions decorated with parent/branch display metadata.
391 392 393 |
# File 'lib/kward/session_store.rb', line 391 def recent_tree(limit: 20, keep_empty_path: nil) decorate_tree(recent_sessions(limit: limit, keep_empty_path: keep_empty_path)) end |
#remember_last_session(session) ⇒ Object
Persists the last active session pointer for workspace auto-resume.
365 366 367 368 369 370 |
# File 'lib/kward/session_store.rb', line 365 def remember_last_session(session) return unless session&.path FileUtils.mkdir_p(session_dir, mode: 0o700) PrivateFile.write_json(last_session_path, { "path" => File.(session.path), "timestamp" => Time.now.utc.iso8601(3) }) end |
#remembered_last_session_path ⇒ String?
Returns remembered session path when the file still exists.
377 378 379 380 381 382 383 384 385 386 |
# File 'lib/kward/session_store.rb', line 377 def remembered_last_session_path return nil unless File.file?(last_session_path) path = JSON.parse(File.read(last_session_path))["path"].to_s return nil if path.empty? || !File.file?(path) path rescue JSON::ParserError nil end |
#session_dir ⇒ Object
411 412 413 |
# File 'lib/kward/session_store.rb', line 411 def session_dir File.join(@config_dir, "sessions", self.class.safe_cwd(@cwd)) end |
#session_entries(path) ⇒ Array<Hash>
Returns flat tree records with resolved labels attached.
460 461 462 463 464 465 466 467 468 469 470 471 |
# File 'lib/kward/session_store.rb', line 460 def session_entries(path) records = records_from_file(resolve_session_path(path)) labels = labels_by_target(records) = (records) records.select { |record| tree_entry_record?(record) }.map do |record| id = record["id"].to_s record.dup.tap do |copy| copy["resolvedLabel"] = labels[id] if labels.key?(id) copy["labelTimestamp"] = [id] if .key?(id) end end end |
#session_entry(path, entry_id) ⇒ Hash?
Finds one persisted tree entry by id.
476 477 478 |
# File 'lib/kward/session_store.rb', line 476 def session_entry(path, entry_id) session_entries(path).find { |record| record["id"].to_s == entry_id.to_s } end |
#session_location(path) ⇒ Hash
Resolves a user-provided path and returns the stored workspace location.
290 291 292 293 294 295 |
# File 'lib/kward/session_store.rb', line 290 def session_location(path) resolved_path = resolve_session_path(path) records = records_from_file(resolved_path) header = session_header(records, resolved_path) { path: resolved_path, cwd: header["cwd"].to_s.empty? ? @cwd : header["cwd"].to_s } end |
#session_tree(path) ⇒ Array<Hash>
Returns nested session tree roots for the given session file.
454 455 456 457 |
# File 'lib/kward/session_store.rb', line 454 def session_tree(path) records = records_from_file(resolve_session_path(path)) build_session_tree(records) end |