Class: Kward::Memory::Manager
- Inherits:
-
Object
- Object
- Kward::Memory::Manager
- Defined in:
- lib/kward/memory/manager.rb
Overview
Manages Kward's opt-in structured memory store.
Core memories are explicit, high-trust instructions. Soft memories are confidence-scored contextual hints. Session memory is handled by session persistence, while this manager owns global/workspace JSON and JSONL files plus the audit event log.
Constant Summary collapse
- CORE_LIMIT =
6- SOFT_LIMIT =
6- DEFAULT_SOFT_TTL_DAYS =
60- DEFAULT_SOFT_CONFIDENCE =
0.65- EMOTIONAL_PATTERN =
/\b(love|loves|romantic|intimate|dependency|depend on me|need me|flirty|crush)\b/i
Instance Attribute Summary collapse
-
#last_retrieval ⇒ Object
readonly
Details for the most recent retrieval, used by
/memory why.
Class Method Summary collapse
Instance Method Summary collapse
-
#add_core(text, scope: "global", tags: [], source: "explicit_user_instruction", pinned: true) ⇒ Hash
Stores an explicit high-trust memory.
-
#add_soft(text, scope: "global", tags: [], confidence: DEFAULT_SOFT_CONFIDENCE, ttl_days: DEFAULT_SOFT_TTL_DAYS, source: "manual") ⇒ Hash
Stores a contextual hint with confidence and optional expiry.
- #auto_summary_disable ⇒ Object
- #auto_summary_enable ⇒ Object
- #auto_summary_enabled=(value) ⇒ Object
- #auto_summary_enabled? ⇒ Boolean
- #default_client ⇒ Object
- #disable ⇒ Object
- #enable ⇒ Object
-
#enabled? ⇒ Boolean
Whether memory prompt injection is enabled.
-
#explain_retrieval ⇒ Hash
Explanation data for the most recent retrieval.
- #forget_memory(id) ⇒ Object
- #hierarchy(workspace_root: Dir.pwd, include_inactive: false) ⇒ Object
- #infer_soft_from_text(text, workspace_root: Dir.pwd, client: nil, existing_texts: []) ⇒ Object
-
#initialize(config_path: ConfigFiles.config_path, core_path: ConfigFiles.memory_core_path, soft_path: ConfigFiles.memory_soft_path, events_path: ConfigFiles.memory_events_path, now: nil) ⇒ Manager
constructor
Creates an object for memory storage and retrieval.
- #inspect_memory ⇒ Object
- #list(include_inactive: false) ⇒ Object
- #llm_summarize(client, text) ⇒ Object
-
#memory_block(retrieval) ⇒ Object
Formats retrieved memories for system prompt injection.
- #paths ⇒ Object
- #promote_memory(id) ⇒ Object
- #promote_soft_to_core(id) ⇒ Object
- #relax_core(id, workspace_root: Dir.pwd) ⇒ Object
-
#retrieve_relevant(input:, workspace_root: Dir.pwd, max_core: CORE_LIMIT, max_soft: SOFT_LIMIT) ⇒ Hash
Selects bounded core and soft memories relevant to an interactive turn.
- #set_auto_summary(value) ⇒ Object
- #should_use_llm_summarization? ⇒ Boolean
-
#summarize_conversation(conversation, client: nil) ⇒ Object
Infers bounded session/workspace soft memories from a conversation.
- #summarize_text(text, client: nil) ⇒ Object
Constructor Details
#initialize(config_path: ConfigFiles.config_path, core_path: ConfigFiles.memory_core_path, soft_path: ConfigFiles.memory_soft_path, events_path: ConfigFiles.memory_events_path, now: nil) ⇒ Manager
Creates an object for memory storage and retrieval.
41 42 43 44 45 46 47 48 |
# File 'lib/kward/memory/manager.rb', line 41 def initialize(config_path: ConfigFiles.config_path, core_path: ConfigFiles.memory_core_path, soft_path: ConfigFiles.memory_soft_path, events_path: ConfigFiles.memory_events_path, now: nil) @config_path = config_path @core_path = core_path @soft_path = soft_path @events_path = events_path @now = now @last_retrieval = nil end |
Instance Attribute Details
#last_retrieval ⇒ Object (readonly)
Details for the most recent retrieval, used by /memory why.
28 29 30 |
# File 'lib/kward/memory/manager.rb', line 28 def last_retrieval @last_retrieval end |
Class Method Details
.for_config_dir(config_dir, now: nil) ⇒ Object
30 31 32 33 34 35 36 37 38 |
# File 'lib/kward/memory/manager.rb', line 30 def self.for_config_dir(config_dir, now: nil) new( config_path: File.join(config_dir, "config.json"), core_path: File.join(config_dir, "memory", "core.json"), soft_path: File.join(config_dir, "memory", "soft.jsonl"), events_path: File.join(config_dir, "memory", "events.jsonl"), now: now ) end |
Instance Method Details
#add_core(text, scope: "global", tags: [], source: "explicit_user_instruction", pinned: true) ⇒ Hash
Stores an explicit high-trust memory.
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 |
# File 'lib/kward/memory/manager.rb', line 122 def add_core(text, scope: "global", tags: [], source: "explicit_user_instruction", pinned: true) record = { "id" => next_id("core", core_memories.map { |item| item["id"] }), "text" => clean_text(normalize_memory_text(text)), "scope" => clean_scope(scope), "tags" => (), "created_at" => , "updated_at" => , "source" => source, "pinned" => pinned ? true : false } raise ArgumentError, "Memory text cannot be empty" if record["text"].empty? memories = core_memories memories << record write_core(memories) append_event("add", event_ref(record, layer: "core")) record end |
#add_soft(text, scope: "global", tags: [], confidence: DEFAULT_SOFT_CONFIDENCE, ttl_days: DEFAULT_SOFT_TTL_DAYS, source: "manual") ⇒ Hash
Stores a contextual hint with confidence and optional expiry.
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 |
# File 'lib/kward/memory/manager.rb', line 150 def add_soft(text, scope: "global", tags: [], confidence: DEFAULT_SOFT_CONFIDENCE, ttl_days: DEFAULT_SOFT_TTL_DAYS, source: "manual") record = { "id" => next_id("soft", soft_memories(include_inactive: true).map { |item| item["id"] }), "text" => clean_text(normalize_memory_text(text)), "scope" => clean_scope(scope), "tags" => (), "confidence" => [[confidence.to_f, 0.0].max, 1.0].min, "hits" => 0, "created_at" => , "updated_at" => , "last_seen_at" => , "ttl_days" => ttl_days.to_i <= 0 ? DEFAULT_SOFT_TTL_DAYS : ttl_days.to_i, "source" => source, "status" => "active" } raise ArgumentError, "Memory text cannot be empty" if record["text"].empty? raise ArgumentError, "Refusing to persist emotional or dependency-forming memory automatically" if source == "inferred" && unsafe_soft_text?(record["text"]) append_soft(record) append_event("add", event_ref(record, layer: "soft")) record end |
#auto_summary_disable ⇒ Object
112 113 114 |
# File 'lib/kward/memory/manager.rb', line 112 def auto_summary_disable set_auto_summary(false) end |
#auto_summary_enable ⇒ Object
108 109 110 |
# File 'lib/kward/memory/manager.rb', line 108 def auto_summary_enable set_auto_summary(true) end |
#auto_summary_enabled=(value) ⇒ Object
88 89 90 |
# File 'lib/kward/memory/manager.rb', line 88 def auto_summary_enabled=(value) set_auto_summary(value) end |
#auto_summary_enabled? ⇒ Boolean
80 81 82 83 84 85 86 |
# File 'lib/kward/memory/manager.rb', line 80 def auto_summary_enabled? config = ConfigFiles.read_config(@config_path) memory = config["memory"] memory.is_a?(Hash) && memory["auto_summary"] == true rescue StandardError false end |
#default_client ⇒ Object
395 396 397 398 399 |
# File 'lib/kward/memory/manager.rb', line 395 def default_client @default_client ||= Kward::Client.new rescue StandardError nil end |
#disable ⇒ Object
70 71 72 73 74 75 76 77 78 |
# File 'lib/kward/memory/manager.rb', line 70 def disable config = ConfigFiles.read_config(@config_path) memory = config["memory"].is_a?(Hash) ? config["memory"].dup : {} memory["enabled"] = false config["memory"] = memory ConfigFiles.write_config(config, @config_path) append_event("disable", {}) true end |
#enable ⇒ Object
59 60 61 62 63 64 65 66 67 68 |
# File 'lib/kward/memory/manager.rb', line 59 def enable config = ConfigFiles.read_config(@config_path) memory = config["memory"].is_a?(Hash) ? config["memory"].dup : {} memory["enabled"] = true config["memory"] = memory ConfigFiles.write_config(config, @config_path) ensure_storage! append_event("enable", {}) true end |
#enabled? ⇒ Boolean
Returns whether memory prompt injection is enabled.
51 52 53 54 55 56 57 |
# File 'lib/kward/memory/manager.rb', line 51 def enabled? config = ConfigFiles.read_config(@config_path) memory = config["memory"] memory.is_a?(Hash) && memory["enabled"] == true rescue StandardError false end |
#explain_retrieval ⇒ Hash
Returns explanation data for the most recent retrieval.
301 302 303 |
# File 'lib/kward/memory/manager.rb', line 301 def explain_retrieval @last_retrieval || { "enabled" => enabled?, "core" => [], "soft" => [], "reasons" => [], "message" => "No memory retrieval has run yet." } end |
#forget_memory(id) ⇒ Object
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 |
# File 'lib/kward/memory/manager.rb', line 205 def forget_memory(id) id = id.to_s memories = core_memories if memories.any? { |item| item["id"] == id } write_core(memories.reject { |item| item["id"] == id }) append_event("forget", { "id" => id, "layer" => "core" }) return true end records = soft_memories(include_inactive: true) found = false records.each do |item| next unless item["id"] == id && item["status"] != "forgotten" item["text"] = "[forgotten]" item["tags"] = [] item["confidence"] = 0.0 item["hits"] = 0 item["status"] = "forgotten" item["updated_at"] = found = true end if found write_soft(records) append_event("forget", { "id" => id, "layer" => "soft" }) end found end |
#hierarchy(workspace_root: Dir.pwd, include_inactive: false) ⇒ Object
238 239 240 241 242 243 244 245 246 |
# File 'lib/kward/memory/manager.rb', line 238 def hierarchy(workspace_root: Dir.pwd, include_inactive: false) workspace = workspace_scope(workspace_root) core = core_memories { "global_core" => core.select { |item| item["scope"] == "global" }, "workspace_core" => core.select { |item| item["scope"] == workspace }, "workspace_soft" => soft_memories(include_inactive: include_inactive).select { |item| item["scope"] == workspace } } end |
#infer_soft_from_text(text, workspace_root: Dir.pwd, client: nil, existing_texts: []) ⇒ Object
354 355 356 357 358 359 360 361 362 363 364 365 366 |
# File 'lib/kward/memory/manager.rb', line 354 def infer_soft_from_text(text, workspace_root: Dir.pwd, client: nil, existing_texts: []) candidates = heuristic_candidates(text) existing_set = Set.new(existing_texts.map { |t| normalize_for_comparison(t) }) candidates.filter_map do |candidate| summarized = summarize_text(candidate, client: client) normalized = normalize_for_comparison(summarized) # Skip if this text already exists in provided list or existing soft memories next if existing_set.include?(normalized) next if soft_memories.any? { |m| normalize_for_comparison(m["text"]) == normalized } add_soft(summarized, scope: workspace_scope(workspace_root), tags: ["workflow"], confidence: 0.55, source: "inferred") end end |
#inspect_memory ⇒ Object
248 249 250 |
# File 'lib/kward/memory/manager.rb', line 248 def inspect_memory list(include_inactive: true).merge("enabled" => enabled?, "paths" => paths) end |
#list(include_inactive: false) ⇒ Object
234 235 236 |
# File 'lib/kward/memory/manager.rb', line 234 def list(include_inactive: false) { "core" => core_memories, "soft" => soft_memories(include_inactive: include_inactive) } end |
#llm_summarize(client, text) ⇒ Object
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 |
# File 'lib/kward/memory/manager.rb', line 401 def llm_summarize(client, text) = [ { role: "system", content: <<~SYSTEM }, You are a memory text reformulation assistant. Your task is to transform user-generated text into proper third-person descriptive memory statements. Rules: - Convert first-person statements ("I like", "we prefer") to third-person ("The captain likes", "The user prefers") - Remove conversational filler, preambles, and action descriptions - Keep only the factual preference or fact - Use "The captain" or "The user" as the subject for personal preferences - Preserve workflow-related technical preferences as-is - Keep the text concise (under 100 characters) - If the text is already a good memory statement, return it unchanged Examples: - "I like to eat the most important meal today: steak" → "The captain likes eating steak" - "We should prefer TDD for this project" → "Prefer TDD for this project" - "Remember that the user prefers minitest" → "The user prefers minitest" - "But first we need to remember that we are using TDD" → "Use TDD" - "The user usually asks for tests" → "The user usually asks for tests" - "Prefer evidence from code, tests, logs" → "Prefer evidence from code, tests, logs" SYSTEM { role: "user", content: "Reformulate this as a memory statement: #{text}" } ] response = client.chat(, max_tokens: 100, reasoning: false) content = response.dig("content") || response[:content] return text unless content content.strip rescue StandardError text end |
#memory_block(retrieval) ⇒ Object
Formats retrieved memories for system prompt injection.
Keep this block compact and explicit: it is read by the model, shown in
transcripts, and explained by /memory why. Do not include inactive or
forgotten memories here; retrieval already decides the active set.
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 |
# File 'lib/kward/memory/manager.rb', line 310 def memory_block(retrieval) core = Array(retrieval["core"]) soft = Array(retrieval["soft"]) return nil if core.empty? && soft.empty? global_core = core.select { |item| item["scope"] == "global" } workspace_core = core.reject { |item| item["scope"] == "global" } lines = ["<kward_memory>"] unless global_core.empty? lines << "Global Core Memories:" global_core.each { |item| lines << "- [#{item["id"]}] #{item["text"]}" } lines << "" end unless workspace_core.empty? lines << "Workspace Core Memories:" workspace_core.each { |item| lines << "- [#{item["id"]}] #{item["text"]}" } lines << "" end unless soft.empty? lines << "Workspace Soft Memories:" soft.each { |item| lines << "- [#{item["id"]}] #{item["text"]}" } lines << "" end lines << "Rules:" lines << "- Core memories override soft memories." lines << "- Soft memories are contextual hints, not guaranteed facts." lines << "</kward_memory>" lines.join("\n") end |
#paths ⇒ Object
435 436 437 |
# File 'lib/kward/memory/manager.rb', line 435 def paths { "core" => @core_path, "soft" => @soft_path, "events" => @events_path } end |
#promote_memory(id) ⇒ Object
173 174 175 176 177 178 179 |
# File 'lib/kward/memory/manager.rb', line 173 def promote_memory(id) id = id.to_s core = core_memories.find { |item| item["id"] == id } return promote_core_to_global(core) if core promote_soft_to_core(id) end |
#promote_soft_to_core(id) ⇒ Object
181 182 183 184 185 186 187 188 189 |
# File 'lib/kward/memory/manager.rb', line 181 def promote_soft_to_core(id) soft = soft_memories.find { |item| item["id"] == id.to_s } raise ArgumentError, "Unknown active soft memory or workspace core memory: #{id}" unless soft core = add_core(soft["text"], scope: soft["scope"], tags: soft["tags"], source: "promoted_soft_memory", pinned: true) forget_memory(id) append_event("promote", { "from_id" => soft["id"], "to_id" => core["id"] }) core end |
#relax_core(id, workspace_root: Dir.pwd) ⇒ Object
191 192 193 194 195 196 197 198 199 200 201 202 203 |
# File 'lib/kward/memory/manager.rb', line 191 def relax_core(id, workspace_root: Dir.pwd) id = id.to_s memories = core_memories core = memories.find { |item| item["id"] == id } raise ArgumentError, "Unknown core memory: #{id}" unless core raise ArgumentError, "Only global core memories can be relaxed" unless core["scope"] == "global" core["scope"] = workspace_scope(workspace_root) core["updated_at"] = write_core(memories) append_event("relax", event_ref(core, layer: "core")) core end |
#retrieve_relevant(input:, workspace_root: Dir.pwd, max_core: CORE_LIMIT, max_soft: SOFT_LIMIT) ⇒ Hash
Selects bounded core and soft memories relevant to an interactive turn.
Retrieval is scoped to global and workspace memories, prefers core memories, and scores soft memories by text/tag overlap, confidence, and expiry.
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 |
# File 'lib/kward/memory/manager.rb', line 261 def retrieve_relevant(input:, workspace_root: Dir.pwd, max_core: CORE_LIMIT, max_soft: SOFT_LIMIT) unless enabled? @last_retrieval = { "enabled" => false, "core" => [], "soft" => [], "reasons" => [] } return @last_retrieval end scopes = scopes_for(workspace_root) workspace = workspace_scope(workspace_root) terms = terms_for(input) core = ranked_core_memories(workspace).first(max_core) core_reasons = core.map { |item| reason_for(item, layer: "core", score: 1.0, reasons: ["scope match", "core memories are preferred"]) } soft_records_all = soft_memories(include_inactive: true) soft_scored = soft_records_all.filter_map do |item| next unless item["status"] == "active" next unless item["scope"] == workspace next if expired?(item) score, reasons = soft_score(item, terms) next if score <= 0 [item, score, reasons] end soft = soft_scored.sort_by { |item, score, _reasons| [-score, -item["confidence"].to_f, item["id"].to_s] }.first(max_soft) soft_records = soft.map(&:first) touch_soft_records(soft_records_all, soft_records) soft_reasons = soft.map { |item, score, reasons| reason_for(item, layer: "soft", score: score, reasons: reasons) } @last_retrieval = { "enabled" => true, "scopes" => scopes, "core" => core, "soft" => soft_records, "reasons" => core_reasons + soft_reasons } append_event("retrieve", { "core_ids" => core.map { |item| item["id"] }, "soft_ids" => soft_records.map { |item| item["id"] }, "scopes" => scopes }) @last_retrieval end |
#set_auto_summary(value) ⇒ Object
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
# File 'lib/kward/memory/manager.rb', line 92 def set_auto_summary(value) config = ConfigFiles.read_config(@config_path) memory = config["memory"].is_a?(Hash) ? config["memory"].dup : {} enabled = value ? true : false previous = memory["auto_summary"] == true if enabled memory["auto_summary"] = true else memory.delete("auto_summary") end config["memory"] = memory ConfigFiles.write_config(config, @config_path) append_event(enabled ? "auto_summary_enable" : "auto_summary_disable", {}) unless previous == enabled auto_summary_enabled? end |
#should_use_llm_summarization? ⇒ Boolean
382 383 384 385 386 387 388 389 390 391 392 393 |
# File 'lib/kward/memory/manager.rb', line 382 def should_use_llm_summarization? # Check if we have valid credentials to make LLM calls client = default_client return false unless client token = client.instance_variable_get(:@openai_access_token) || client.instance_variable_get(:@openrouter_api_key) || client.send(:github_access_token) token.to_s.length > 10 rescue StandardError false end |
#summarize_conversation(conversation, client: nil) ⇒ Object
Infers bounded session/workspace soft memories from a conversation.
This is best-effort and intentionally conservative. It may use an LLM when configured, but failures fall back to heuristic text or no-op behavior so memory summarization never blocks normal session flow.
346 347 348 349 350 351 352 |
# File 'lib/kward/memory/manager.rb', line 346 def summarize_conversation(conversation, client: nil) text = (conversation).map { || MessageAccess.content() }.compact.join("\n") existing_texts = Array(conversation.session_memories).map { |memory| memory["text"] } records = infer_soft_from_text(text, workspace_root: conversation.workspace_root, client: client, existing_texts: existing_texts) conversation.session_memories.concat(records.map { |record| record.slice("id", "text", "scope", "tags") }) if conversation.session_memories.respond_to?(:concat) records end |
#summarize_text(text, client: nil) ⇒ Object
368 369 370 371 372 373 374 375 376 377 378 379 380 |
# File 'lib/kward/memory/manager.rb', line 368 def summarize_text(text, client: nil) summarizer_client = client unless summarizer_client return text unless should_use_llm_summarization? summarizer_client = default_client end summary = llm_summarize(summarizer_client, text) summary.empty? ? text : summary rescue StandardError text end |