Class: Kward::SessionStore

Inherits:
Object
  • Object
show all
Defined in:
lib/kward/session_store.rb

Defined Under Namespace

Classes: Session, SessionInfo

Constant Summary collapse

VERSION =
2
LAST_SESSION_FILENAME =
"last_session.json"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config_dir: ConfigFiles.config_dir, cwd: Dir.pwd) ⇒ SessionStore

Returns a new instance of SessionStore.



112
113
114
115
# File 'lib/kward/session_store.rb', line 112

def initialize(config_dir: ConfigFiles.config_dir, cwd: Dir.pwd)
  @config_dir = config_dir
  @cwd = File.expand_path(cwd)
end

Instance Attribute Details

#cwdObject (readonly)

Returns the value of attribute cwd.



117
118
119
# File 'lib/kward/session_store.rb', line 117

def cwd
  @cwd
end

Class Method Details

.safe_cwd(cwd) ⇒ Object



328
329
330
# File 'lib/kward/session_store.rb', line 328

def self.safe_cwd(cwd)
  "--#{File.expand_path(cwd).sub(%r{\A[/\\]}, "").gsub(%r{[/\\:]}, "-")}--"
end

Instance Method Details

#append_label_change(path, entry_id, label) ⇒ Object



285
286
287
288
289
290
291
292
293
# File 'lib/kward/session_store.rb', line 285

def append_label_change(path, entry_id, label)
  append_record(path, {
    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
  })
end

#append_leaf_change(path, leaf_id) ⇒ Object



277
278
279
280
281
282
283
# File 'lib/kward/session_store.rb', line 277

def append_leaf_change(path, leaf_id)
  append_record(path, {
    type: "leaf",
    timestamp: Time.now.utc.iso8601(3),
    targetId: leaf_id
  })
end

#append_record(path, record) ⇒ Object



321
322
323
324
325
326
# File 'lib/kward/session_store.rb', line 321

def append_record(path, record)
  File.open(path, "a", 0o600) do |file|
    file.write(JSON.generate(record))
    file.write("\n")
  end
end

#build_tree_record(path, type, parent_id, fields = {}) ⇒ Object



265
266
267
268
269
270
271
272
273
274
275
# File 'lib/kward/session_store.rb', line 265

def build_tree_record(path, type, parent_id, fields = {})
  message = fields[:message]
  id = message_entry_id(message) || next_entry_id(path)
  assign_message_entry_id(message, id) if message.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

#create(model: nil, reasoning_effort: nil, parent_id: nil, parent_path: nil) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/kward/session_store.rb', line 119

def create(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,
    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)
end

#create_from_conversation(conversation, parent_session: nil) ⇒ Object



146
147
148
149
150
151
152
# File 'lib/kward/session_store.rb', line 146

def create_from_conversation(conversation, parent_session: nil)
  session = create(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?
  persisted_messages(conversation).each { |message| session.append_message(message) }
  session.attach(conversation)
  session
end

#create_independent_from_conversation(conversation, parent_session: nil) ⇒ Object



154
155
156
157
158
159
160
161
162
# File 'lib/kward/session_store.rb', line 154

def create_independent_from_conversation(conversation, parent_session: nil)
  create_independent_from_messages(
    persisted_messages(conversation),
    read_paths: Array(conversation.read_paths),
    model: conversation.model,
    reasoning_effort: conversation.reasoning_effort,
    parent_session: parent_session
  )
end

#create_independent_from_messages(messages, read_paths: [], model: nil, reasoning_effort: nil, parent_session: nil) ⇒ Object



164
165
166
167
168
169
170
171
172
# File 'lib/kward/session_store.rb', line 164

def create_independent_from_messages(messages, read_paths: [], model: nil, reasoning_effort: nil, parent_session: nil)
  session = create(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 = deep_copy(messages)
  persisted.each { |message| session.append_message(message) }
  conversation = Conversation.new(messages: deep_copy(persisted), read_paths: read_paths, workspace_root: @cwd, model: model, reasoning_effort: reasoning_effort)
  session.attach(conversation)
  [session, conversation]
end

#current_leaf(path) ⇒ Object



317
318
319
# File 'lib/kward/session_store.rb', line 317

def current_leaf(path)
  current_leaf_id(records_from_file(resolve_session_path(path)))
end

#delete_unused_session(session) ⇒ Object



249
250
251
252
253
254
255
256
257
258
# File 'lib/kward/session_store.rb', line 249

def delete_unused_session(session)
  path = session.path
  return false if session_named?(session)
  return false unless unused_session_file?(path)

  File.delete(path)
  true
rescue StandardError
  false
end

#last_session_pathObject



229
230
231
# File 'lib/kward/session_store.rb', line 229

def last_session_path
  File.join(session_dir, LAST_SESSION_FILENAME)
end

#load(path, workspace: Workspace.new, model: nil, reasoning_effort: nil) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/kward/session_store.rb', line 181

def load(path, workspace: Workspace.new, model: nil, reasoning_effort: 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)
  messages = restored_messages(records)
  name = session_name(records)
  read_paths = restored_read_paths(messages, workspace)
  memory_state = restored_memory_state(records)

  runtime = session_runtime(records, header)
  conversation = Conversation.new(
    messages: messages,
    read_paths: read_paths,
    workspace_root: workspace.root,
    model: runtime["model"] || model,
    reasoning_effort: runtime["reasoningEffort"] || reasoning_effort,
    session_memories: memory_state["sessionMemories"],
    last_memory_retrieval: memory_state["lastRetrieval"]
  )
  conversation.mark_last_entry_compaction! if latest_record_type(records) == "compaction"
  session = Session.new(
    store: self,
    id: header["id"],
    path: resolved_path,
    cwd: header["cwd"].to_s,
    created_at: parse_time(header["timestamp"]) || File.mtime(resolved_path),
    name: name,
    parent_id: header["parentId"],
    parent_path: header["parentPath"],
    leaf_id: leaf_id
  )
  session.attach(conversation)
  [session, conversation]
end

#recent(limit: 20) ⇒ Object



218
219
220
# File 'lib/kward/session_store.rb', line 218

def recent(limit: 20)
  limit ? recent_sessions.first(limit) : recent_sessions
end

#recent_tree(limit: 20) ⇒ Object



244
245
246
247
# File 'lib/kward/session_store.rb', line 244

def recent_tree(limit: 20)
  sessions = limit ? recent_sessions.first(limit) : recent_sessions
  decorate_tree(sessions)
end

#remember_last_session(session) ⇒ Object



222
223
224
225
226
227
# File 'lib/kward/session_store.rb', line 222

def remember_last_session(session)
  return unless session&.path

  FileUtils.mkdir_p(session_dir, mode: 0o700)
  PrivateFile.write_json(last_session_path, { "path" => File.expand_path(session.path), "timestamp" => Time.now.utc.iso8601(3) })
end

#remembered_last_session_pathObject



233
234
235
236
237
238
239
240
241
242
# File 'lib/kward/session_store.rb', line 233

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_dirObject



260
261
262
# File 'lib/kward/session_store.rb', line 260

def session_dir
  File.join(@config_dir, "sessions", self.class.safe_cwd(@cwd))
end

#session_entries(path) ⇒ Object



300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/kward/session_store.rb', line 300

def session_entries(path)
  records = records_from_file(resolve_session_path(path))
  labels = labels_by_target(records)
  timestamps = label_timestamps_by_target(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"] = timestamps[id] if timestamps.key?(id)
    end
  end
end

#session_entry(path, entry_id) ⇒ Object



313
314
315
# File 'lib/kward/session_store.rb', line 313

def session_entry(path, entry_id)
  session_entries(path).find { |record| record["id"].to_s == entry_id.to_s }
end

#session_location(path) ⇒ Object



174
175
176
177
178
179
# File 'lib/kward/session_store.rb', line 174

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) ⇒ Object



295
296
297
298
# File 'lib/kward/session_store.rb', line 295

def session_tree(path)
  records = records_from_file(resolve_session_path(path))
  build_session_tree(records)
end