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
- #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
A new instance of Manager.
- #inspect_memory ⇒ Object
- #list(include_inactive: false) ⇒ Object
- #llm_summarize(client, text) ⇒ Object
- #memory_block(retrieval) ⇒ Object
- #paths ⇒ Object
- #promote_soft_to_core(id) ⇒ 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
- #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
Returns a new instance of Manager.
38 39 40 41 42 43 44 45 |
# File 'lib/kward/memory/manager.rb', line 38 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.
26 27 28 |
# File 'lib/kward/memory/manager.rb', line 26 def last_retrieval @last_retrieval end |
Class Method Details
.for_config_dir(config_dir, now: nil) ⇒ Object
28 29 30 31 32 33 34 35 36 |
# File 'lib/kward/memory/manager.rb', line 28 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.
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 |
# File 'lib/kward/memory/manager.rb', line 119 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.
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 |
# File 'lib/kward/memory/manager.rb', line 147 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
109 110 111 |
# File 'lib/kward/memory/manager.rb', line 109 def auto_summary_disable set_auto_summary(false) end |
#auto_summary_enable ⇒ Object
105 106 107 |
# File 'lib/kward/memory/manager.rb', line 105 def auto_summary_enable set_auto_summary(true) end |
#auto_summary_enabled=(value) ⇒ Object
85 86 87 |
# File 'lib/kward/memory/manager.rb', line 85 def auto_summary_enabled=(value) set_auto_summary(value) end |
#auto_summary_enabled? ⇒ Boolean
77 78 79 80 81 82 83 |
# File 'lib/kward/memory/manager.rb', line 77 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
341 342 343 344 345 |
# File 'lib/kward/memory/manager.rb', line 341 def default_client @default_client ||= Kward::Client.new rescue StandardError nil end |
#disable ⇒ Object
67 68 69 70 71 72 73 74 75 |
# File 'lib/kward/memory/manager.rb', line 67 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
56 57 58 59 60 61 62 63 64 65 |
# File 'lib/kward/memory/manager.rb', line 56 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.
48 49 50 51 52 53 54 |
# File 'lib/kward/memory/manager.rb', line 48 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.
265 266 267 |
# File 'lib/kward/memory/manager.rb', line 265 def explain_retrieval @last_retrieval || { "enabled" => enabled?, "core" => [], "soft" => [], "reasons" => [], "message" => "No memory retrieval has run yet." } end |
#forget_memory(id) ⇒ Object
180 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 |
# File 'lib/kward/memory/manager.rb', line 180 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 |
#infer_soft_from_text(text, workspace_root: Dir.pwd, client: nil, existing_texts: []) ⇒ Object
300 301 302 303 304 305 306 307 308 309 310 311 312 |
# File 'lib/kward/memory/manager.rb', line 300 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
213 214 215 |
# File 'lib/kward/memory/manager.rb', line 213 def inspect_memory list(include_inactive: true).merge("enabled" => enabled?, "paths" => paths) end |
#list(include_inactive: false) ⇒ Object
209 210 211 |
# File 'lib/kward/memory/manager.rb', line 209 def list(include_inactive: false) { "core" => core_memories, "soft" => soft_memories(include_inactive: include_inactive) } end |
#llm_summarize(client, text) ⇒ Object
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 |
# File 'lib/kward/memory/manager.rb', line 347 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
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 |
# File 'lib/kward/memory/manager.rb', line 269 def memory_block(retrieval) core = Array(retrieval["core"]) soft = Array(retrieval["soft"]) return nil if core.empty? && soft.empty? lines = ["<kward_memory>"] unless core.empty? lines << "Core Memories:" core.each { |item| lines << "- [#{item["id"]}] #{item["text"]}" } lines << "" end unless soft.empty? lines << "Relevant 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
381 382 383 |
# File 'lib/kward/memory/manager.rb', line 381 def paths { "core" => @core_path, "soft" => @soft_path, "events" => @events_path } end |
#promote_soft_to_core(id) ⇒ Object
170 171 172 173 174 175 176 177 178 |
# File 'lib/kward/memory/manager.rb', line 170 def promote_soft_to_core(id) soft = soft_memories.find { |item| item["id"] == id.to_s } raise ArgumentError, "Unknown active soft 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 |
#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.
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 |
# File 'lib/kward/memory/manager.rb', line 226 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) terms = terms_for(input) core = core_memories.select { |item| scopes.include?(item["scope"]) }.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 scopes.include?(item["scope"]) 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
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
# File 'lib/kward/memory/manager.rb', line 89 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
328 329 330 331 332 333 334 335 336 337 338 339 |
# File 'lib/kward/memory/manager.rb', line 328 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
292 293 294 295 296 297 298 |
# File 'lib/kward/memory/manager.rb', line 292 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
314 315 316 317 318 319 320 321 322 323 324 325 326 |
# File 'lib/kward/memory/manager.rb', line 314 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 |