samagotchi 0.183.0 → 0.185.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +84 -1
  3. data/docs/architecture.md +12 -11
  4. data/docs/bundles.md +63 -36
  5. data/docs/cli.md +10 -1
  6. data/docs/configuration.md +3 -2
  7. data/docs/context.md +76 -10
  8. data/docs/guardrails.md +7 -2
  9. data/docs/hooks.md +1 -0
  10. data/docs/internals/block-renderers.md +4 -2
  11. data/docs/internals/bridge.md +7 -3
  12. data/docs/internals/bundles.md +6 -2
  13. data/docs/internals/engine.md +2 -1
  14. data/docs/internals/llm-context-forget.md +6 -0
  15. data/docs/internals/participants.md +5 -2
  16. data/docs/internals/prompt-caching.md +8 -1
  17. data/docs/internals/remote-sessions.md +22 -4
  18. data/docs/internals/session-lifecycle.md +1 -1
  19. data/docs/internals/web-frontend.md +37 -15
  20. data/docs/internals/web-push.md +11 -0
  21. data/docs/internals/working-set.md +238 -6
  22. data/docs/mcp-server.md +11 -3
  23. data/docs/memory.md +2 -1
  24. data/docs/plugins.md +6 -6
  25. data/docs/scheduling.md +19 -0
  26. data/docs/sessions.md +13 -3
  27. data/docs/sub-agent.md +48 -3
  28. data/docs/thin-clients.md +38 -12
  29. data/lib/samagotchi/agent_caller.rb +97 -0
  30. data/lib/samagotchi/bridge.rb +7 -7
  31. data/lib/samagotchi/bridge_client.rb +12 -4
  32. data/lib/samagotchi/bundle_command/check.rb +20 -2
  33. data/lib/samagotchi/bundle_manifest.rb +5 -1
  34. data/lib/samagotchi/bundles/claude-peer/manifest.yml +14 -8
  35. data/lib/samagotchi/bundles/claude-peer/plugin.rb +3 -3
  36. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +49 -30
  37. data/lib/samagotchi/bundles/claude-peer/scripts/pair +2 -2
  38. data/lib/samagotchi/bundles/claude-peer/scripts/pair-remote +123 -0
  39. data/lib/samagotchi/bundles/claude-peer/skill_claude_peer.md +11 -3
  40. data/lib/samagotchi/bundles/codex-peer/manifest.yml +10 -8
  41. data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
  42. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +29 -8
  43. data/lib/samagotchi/bundles/codex-peer/scripts/pair +1 -1
  44. data/lib/samagotchi/bundles/codex-peer/skill_codex_peer.md +11 -3
  45. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  46. data/lib/samagotchi/bundles/mcp/http_client.rb +96 -54
  47. data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
  48. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  49. data/lib/samagotchi/bundles/system/self_map.md +9 -2
  50. data/lib/samagotchi/client_id.rb +61 -1
  51. data/lib/samagotchi/command_intake.rb +16 -8
  52. data/lib/samagotchi/context_absorber.rb +212 -46
  53. data/lib/samagotchi/delivery.rb +15 -0
  54. data/lib/samagotchi/driver_command.rb +68 -0
  55. data/lib/samagotchi/engine/block_fix.rb +2 -2
  56. data/lib/samagotchi/engine/session.rb +14 -6
  57. data/lib/samagotchi/engine/turn_helpers.rb +4 -3
  58. data/lib/samagotchi/engine.rb +13 -5
  59. data/lib/samagotchi/engine_peers.rb +6 -0
  60. data/lib/samagotchi/guardrails/pair_boundary.rb +1 -1
  61. data/lib/samagotchi/mcp_command.rb +7 -2
  62. data/lib/samagotchi/mcp_server/http.rb +3 -3
  63. data/lib/samagotchi/mcp_server/protocol.rb +23 -4
  64. data/lib/samagotchi/mcp_server/stdio.rb +1 -0
  65. data/lib/samagotchi/mcp_server/tools.rb +11 -4
  66. data/lib/samagotchi/model_notes.rb +34 -12
  67. data/lib/samagotchi/objectives_track.rb +2 -1
  68. data/lib/samagotchi/owner_prompt.rb +5 -1
  69. data/lib/samagotchi/parent_report.rb +9 -5
  70. data/lib/samagotchi/plugin/peer.rb +10 -4
  71. data/lib/samagotchi/prompt_files.rb +11 -4
  72. data/lib/samagotchi/prompt_layout.rb +88 -0
  73. data/lib/samagotchi/prompt_part.rb +82 -20
  74. data/lib/samagotchi/reply_wait.rb +16 -4
  75. data/lib/samagotchi/schedule_command.rb +18 -4
  76. data/lib/samagotchi/schedules.rb +49 -14
  77. data/lib/samagotchi/send_command/parent_gate.rb +3 -1
  78. data/lib/samagotchi/send_command.rb +45 -8
  79. data/lib/samagotchi/session.rb +9 -1
  80. data/lib/samagotchi/session_access/ask.rb +58 -14
  81. data/lib/samagotchi/session_access/contract.rb +2 -0
  82. data/lib/samagotchi/session_access/exchange.rb +5 -2
  83. data/lib/samagotchi/session_access/local.rb +13 -3
  84. data/lib/samagotchi/session_access/remote.rb +18 -2
  85. data/lib/samagotchi/session_access.rb +4 -2
  86. data/lib/samagotchi/session_command_catalog.rb +8 -0
  87. data/lib/samagotchi/session_commands.rb +9 -0
  88. data/lib/samagotchi/session_continue.rb +4 -1
  89. data/lib/samagotchi/session_inbox.rb +17 -0
  90. data/lib/samagotchi/session_inbox_delivery.rb +4 -2
  91. data/lib/samagotchi/session_manager/delivery.rb +58 -9
  92. data/lib/samagotchi/session_manager/spawn.rb +7 -1
  93. data/lib/samagotchi/steer.rb +95 -20
  94. data/lib/samagotchi/system_prompt.rb +196 -161
  95. data/lib/samagotchi/terminal_ui/formatting.rb +12 -2
  96. data/lib/samagotchi/tool_activity.rb +4 -0
  97. data/lib/samagotchi/tool_declarations.rb +22 -1
  98. data/lib/samagotchi/tool_names.rb +4 -0
  99. data/lib/samagotchi/toolkit.rb +3 -2
  100. data/lib/samagotchi/tools/ask_session.rb +208 -0
  101. data/lib/samagotchi/tools/builtin_calls.rb +1 -0
  102. data/lib/samagotchi/tools/builtins.rb +5 -0
  103. data/lib/samagotchi/tools/memory.rb +11 -3
  104. data/lib/samagotchi/turn_checkpoint.rb +19 -2
  105. data/lib/samagotchi/turn_stages/context_judge.rb +3 -1
  106. data/lib/samagotchi/turn_stages/objectives.rb +4 -2
  107. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +3 -0
  108. data/lib/samagotchi/turn_stages/warmup.rb +2 -2
  109. data/lib/samagotchi/version.rb +1 -1
  110. data/lib/samagotchi/visitor.rb +37 -0
  111. data/lib/samagotchi/web/app.rb +2 -3
  112. data/lib/samagotchi/web/ask_routes.rb +95 -23
  113. data/lib/samagotchi/web/mcp_route.rb +7 -4
  114. data/lib/samagotchi/web/message_display.rb +15 -2
  115. data/lib/samagotchi/web/public/app.js +1 -1
  116. data/lib/samagotchi/web/public/block_fix.js +11 -3
  117. data/lib/samagotchi/web/public/delete_sheet.js +20 -18
  118. data/lib/samagotchi/web/public/history_shape.js +3 -1
  119. data/lib/samagotchi/web/public/index.html +8 -0
  120. data/lib/samagotchi/web/public/peer_links.js +27 -4
  121. data/lib/samagotchi/web/public/peer_note.js +19 -3
  122. data/lib/samagotchi/web/public/peer_text.js +45 -0
  123. data/lib/samagotchi/web/public/picture_regions.js +2 -2
  124. data/lib/samagotchi/web/public/removal_sheet_model.js +3 -4
  125. data/lib/samagotchi/web/public/running_tasks.js +0 -16
  126. data/lib/samagotchi/web/public/session_actions.js +0 -9
  127. data/lib/samagotchi/web/public/turn_events.js +19 -0
  128. data/lib/samagotchi/web/public/working_set_view.js +178 -23
  129. data/lib/samagotchi/web/public/ws_part_peek.js +277 -0
  130. data/lib/samagotchi/web/public/ws_peek.js +3 -1
  131. data/lib/samagotchi/web/public/ws_preview.css +30 -0
  132. data/lib/samagotchi/web/public/ws_reader.js +7 -3
  133. data/lib/samagotchi/web/public/ws_sections.js +37 -7
  134. data/lib/samagotchi/web/push/notifier.rb +33 -6
  135. data/lib/samagotchi/web/server.rb +1 -1
  136. data/lib/samagotchi/web/session_control.rb +1 -1
  137. data/lib/samagotchi/web/session_create.rb +11 -7
  138. data/lib/samagotchi/web/session_hub.rb +26 -4
  139. data/lib/samagotchi/web/working_set_routes.rb +93 -5
  140. data/lib/samagotchi/worker/command_queue.rb +5 -2
  141. data/lib/samagotchi/worker/senders.rb +79 -0
  142. data/lib/samagotchi/worker.rb +21 -18
  143. data/lib/samagotchi/worker_inbound.rb +12 -4
  144. data/lib/samagotchi/worker_link.rb +2 -2
  145. data/lib/samagotchi/worker_participant_gate.rb +1 -3
  146. data/lib/samagotchi/worker_wakes.rb +12 -0
  147. data/lib/samagotchi/working_set.rb +162 -90
  148. data/lib/samagotchi/working_set_locator.rb +221 -0
  149. data/lib/samagotchi/working_set_own_changes.rb +221 -0
  150. data/lib/samagotchi/working_set_part.rb +281 -0
  151. metadata +13 -1
@@ -143,8 +143,16 @@ module Samagotchi
143
143
  conversation = Array(conversation)
144
144
  view = LLMContextView.new(strategy: strategy)
145
145
  pinned = pins.to_set { |pin| [pin.kind, pin.key] }
146
- items = all_touches(conversation, cwd, view).group_by { |touch| [touch.kind, touch.key] }.map do |(kind, key), group|
147
- item(kind, key, group, conversation, view, stat, pinned.include?([kind, key]), root)
146
+ runs = LLMContextStale.paired_runs(conversation)
147
+ # chi's own changes, built from the same runs only when a memory item needs them (no second walk).
148
+ own = nil
149
+ # Required here, not at load: it requires this file (and the testing kit keeps a file budget, sandbox_spec).
150
+ own_of = lambda do
151
+ require_relative "working_set_own_changes"
152
+ own ||= OwnChanges.from_runs(runs, conversation, cwd: cwd)
153
+ end
154
+ items = all_touches(conversation, cwd, view, runs: runs).group_by { |touch| [touch.kind, touch.key] }.map do |(kind, key), group|
155
+ item(kind, key, group, conversation, view, stat, pinned.include?([kind, key]), root, own_of)
148
156
  end
149
157
  Snapshot.new(items: items, at: conversation.size, adds: pending_adds(conversation))
150
158
  end
@@ -302,12 +310,17 @@ module Samagotchi
302
310
 
303
311
  # What the memory +key+'s latest memory_read would answer now, and its
304
312
  # diff from what that read sent; nil when no read of it has a stamp (a
305
- # session saved before memory stamps). +root+: the memories folder
313
+ # session saved before memory stamps). One Locator (:run) per name the
314
+ # read found: every name is resolved first (refused: nil; no entry
315
+ # answers: gone), then read (a file gone: gone), and the bodies joined
316
+ # as memory_read joins them. +root+: the memories folder
306
317
  # (MemoryPaths.system_dir: the projects' folders are under it); a stamped
307
318
  # or resolved path outside it is never read, nil then. +read+: File.read,
308
319
  # or a stand-in.
309
320
  # @return [Now, nil]
310
321
  def memory_now(conversation, key:, strategy:, cwd:, root:, read: ->(path) { File.read(path, encoding: "UTF-8") })
322
+ # Here, not at load: the testing kit loads WorkingSet and keeps a file budget (sandbox_spec).
323
+ require_relative "working_set_locator"
311
324
  conversation = Array(conversation)
312
325
  view = LLMContextView.new(strategy: strategy)
313
326
  touch = all_touches(conversation, cwd, view).reverse.find do |candidate|
@@ -316,29 +329,19 @@ module Samagotchi
316
329
  entries = touch && memory_entries(touch.run, conversation)
317
330
  return nil unless entries
318
331
 
319
- names = found_names(touch.run)
320
- current_entries = names.map do |name|
321
- entry = entries[name]
322
- return nil unless entry.is_a?(Hash)
323
-
324
- if resolution_metadata?(entry)
325
- resolved = resolve_memory(name, entry, system_dir: root)
326
- if resolved != :stamped_paths
327
- return Now.new(text: nil, diff: nil, gone: true) unless resolved
332
+ locators = found_names(touch.run).map { |name| Locator.of_stamp(name, entries[name]) }
333
+ current_entries = locators.map do |locator|
334
+ found = locator.resolve(root: root)
335
+ return nil if found.nil?
336
+ return Locator::GONE if found == :gone
328
337
 
329
- entry = resolved_memory_entry(resolved)
330
- end
331
- end
332
- return nil unless memory_paths?(entry, root)
333
-
334
- entry
338
+ found
335
339
  end
336
340
 
337
341
  had = body_of(touch.run.text)
338
- bodies = names.zip(current_entries).map { |name, entry| memory_body(name, entry, read) }
339
- return Now.new(text: nil, diff: nil, gone: true) if bodies.any?(&:nil?)
342
+ bodies = locators.zip(current_entries).map { |locator, entry| locator.body(entry, read: read) }
343
+ return Locator::GONE if bodies.any?(&:nil?)
340
344
 
341
- # Here, not at load: the testing kit loads WorkingSet and keeps a file budget (sandbox_spec).
342
345
  require_relative "text_diff"
343
346
  last = had.split(Tools::MemoryRead::SEPARATOR).last.to_s
344
347
  bodies << last if last.match?(MISSING)
@@ -346,44 +349,61 @@ module Samagotchi
346
349
  Now.new(text: now, diff: TextDiff.unified(had, now).merge(new_file: false), gone: false)
347
350
  end
348
351
 
349
- # Whether a stamp entry's file and its overlay's are .md files inside the
350
- # memories folder +root+ (a stamp is the session file's: never read
351
- # what it names elsewhere).
352
- def memory_paths?(entry, root)
353
- overlay = field(entry, :overlay)
354
- paths = [field(entry, :path), overlay.is_a?(Hash) ? field(overlay, :path) : nil].compact
355
- base = File.join(File.expand_path(root.to_s), "")
356
- real = File.exist?(base) ? File.join(File.realpath(base), "") : base
357
- paths.all? do |path|
352
+ # The guard every read of a path a session file names goes through
353
+ # (Locator's fetches, #memory_differs' re-resolve): the paths must be
354
+ # .md files inside chi web's memories folder. Here, not in Locator's
355
+ # file: #build's stale check needs it at load.
356
+ module MemoryGuard
357
+ module_function
358
+
359
+ # Whether +path+ is +root+ or inside it.
360
+ def inside_root?(path, root)
358
361
  expanded = File.expand_path(path.to_s)
359
- next false unless expanded.start_with?(base) && expanded.end_with?(".md")
362
+ base = File.expand_path(root.to_s)
363
+ expanded == base || expanded.start_with?(File.join(base, ""))
364
+ end
360
365
 
361
- !File.exist?(expanded) || File.realpath(expanded).start_with?(real)
366
+ # Whether a stamp entry's file and its overlay's are .md files inside the
367
+ # memories folder +root+ (a stamp is the session file's: never read
368
+ # what it names elsewhere).
369
+ def memory_paths?(entry, root)
370
+ overlay = field(entry, :overlay)
371
+ paths = [field(entry, :path), overlay.is_a?(Hash) ? field(overlay, :path) : nil].compact
372
+ base = File.join(File.expand_path(root.to_s), "")
373
+ real = File.exist?(base) ? File.join(File.realpath(base), "") : base
374
+ paths.all? do |path|
375
+ expanded = File.expand_path(path.to_s)
376
+ next false unless expanded.start_with?(base) && expanded.end_with?(".md")
377
+
378
+ !File.exist?(expanded) || File.realpath(expanded).start_with?(real)
379
+ end
362
380
  end
363
- end
364
381
 
365
- def project_dir_within_root?(path, root)
366
- return true if path.nil?
382
+ def project_dir_within_root?(path, root)
383
+ return true if path.nil?
367
384
 
368
- File.expand_path(path.to_s).start_with?(File.join(File.expand_path(root.to_s), ""))
369
- end
385
+ File.expand_path(path.to_s).start_with?(File.join(File.expand_path(root.to_s), ""))
386
+ end
370
387
 
371
- def resolution_metadata?(entry)
372
- %i[requested_scope model_key fallback_model_key project_dir].all? do |key|
373
- entry.key?(key) || entry.key?(key.to_s)
388
+ def resolution_metadata?(entry)
389
+ %i[requested_scope model_key fallback_model_key project_dir].all? do |key|
390
+ entry.key?(key) || entry.key?(key.to_s)
391
+ end
374
392
  end
375
- end
376
393
 
377
- def resolve_memory(name, entry, system_dir:)
378
- return :stamped_paths unless project_dir_within_root?(field(entry, :project_dir), system_dir)
394
+ def resolve_memory(name, entry, system_dir:)
395
+ return :stamped_paths unless project_dir_within_root?(field(entry, :project_dir), system_dir)
379
396
 
380
- Tools::MemoryRead.resolve(name, scope: field(entry, :requested_scope), model_key: field(entry, :model_key),
381
- fallback_model_key: field(entry, :fallback_model_key),
382
- project_dir: field(entry, :project_dir), system_dir: system_dir)
383
- end
397
+ Tools::MemoryRead.resolve(name, scope: field(entry, :requested_scope), model_key: field(entry, :model_key),
398
+ fallback_model_key: field(entry, :fallback_model_key),
399
+ project_dir: field(entry, :project_dir), system_dir: system_dir)
400
+ end
401
+
402
+ def resolved_memory_entry(resolved)
403
+ { path: resolved.path, overlay: resolved.overlay_path && { path: resolved.overlay_path } }
404
+ end
384
405
 
385
- def resolved_memory_entry(resolved)
386
- { path: resolved.path, overlay: resolved.overlay_path && { path: resolved.overlay_path } }
406
+ def field(hash, key) = hash.key?(key) ? hash[key] : hash[key.to_s]
387
407
  end
388
408
 
389
409
  def event(touch, conversation, view, cwd)
@@ -469,24 +489,9 @@ module Samagotchi
469
489
  # memories/projects/<key>/, a system one's in memories/.
470
490
  def memory_scope(path) = File.basename(File.dirname(path, 2)) == "projects" ? "project" : "system"
471
491
 
472
- # What memory_read would answer now for +name+ (its entry and the overlay
473
- # read with it, as Tools::MemoryRead.call appends it); nil when a file is
474
- # gone.
475
- def memory_body(name, entry, read)
476
- body = read.call(field(entry, :path).to_s)
477
- overlay = field(entry, :overlay)
478
- return body unless overlay.is_a?(Hash)
479
-
480
- overlay_path = field(overlay, :path).to_s
481
- model_key = Tools::MemoryRead.overlay_key(name, overlay_path)
482
- model_key ? Tools::MemoryRead.append_overlay(body, read.call(overlay_path), model_key) : body
483
- rescue SystemCallError
484
- nil
485
- end
486
-
487
492
  # Every paired run's touches, with what +view+ sends of its output.
488
- def all_touches(conversation, cwd, view)
489
- stored = LLMContextStale.paired_runs(conversation)
493
+ def all_touches(conversation, cwd, view, runs: nil)
494
+ stored = runs || LLMContextStale.paired_runs(conversation)
490
495
  # Under none with no drop the view sends the conversation as it is.
491
496
  messages = view.messages(conversation)
492
497
  sent = if messages.equal?(conversation)
@@ -521,7 +526,8 @@ module Samagotchi
521
526
  end
522
527
 
523
528
  # LLMContextStale's failed rule (an "Error" after the "[name]" lead; a
524
- # denied call's "Error:" too), or an interrupted run.
529
+ # denied call's "Error:" too), or an interrupted run. Public: an own
530
+ # change counts only a run that touched (OwnChanges).
525
531
  def failed?(text)
526
532
  ToolResponse.interrupted_text?(text) || text.sub(ToolResponse::LEAD, "").lstrip.start_with?("Error")
527
533
  end
@@ -539,7 +545,7 @@ module Samagotchi
539
545
  names - missing
540
546
  end
541
547
 
542
- def item(kind, key, group, conversation, view, stat, pinned, root)
548
+ def item(kind, key, group, conversation, view, stat, pinned, root, own_of)
543
549
  first = group.first
544
550
  contents = group.select(&:content)
545
551
  tokens = contents.sum { |touch| touch.sent.length / TokenUsage::CHARS_PER_TOKEN / touch.share }.ceil
@@ -547,7 +553,7 @@ module Samagotchi
547
553
  contents.all? { |touch| dropped?(touch, conversation) } ? DROPPED : FORGOTTEN
548
554
  elsif kind == FILE && changed?(key, group.last.run, conversation, stat)
549
555
  STALE
550
- elsif kind == MEMORY && memory_changed?(key, group.last.run, conversation, stat, root)
556
+ elsif kind == MEMORY && memory_stale?(key, group, conversation, stat, root, own_of)
551
557
  STALE
552
558
  else
553
559
  LIVE
@@ -603,35 +609,102 @@ module Samagotchi
603
609
  differs?(path, stamp, stat)
604
610
  end
605
611
 
606
- # Whether the memory +key+ has changed since +run+'s stamp (the item's
607
- # latest run): re-resolve stamps with request metadata, then compare the
608
- # answering files. Older path-only stamps compare their stamped files.
609
- # No stamp means not changed; a missing entry or overlay is changed.
610
- def memory_changed?(key, run, conversation, stat, root)
612
+ # Whether the memory item +key+ is stale (+group+: its touches; the
613
+ # latest decides). A memory_read's: its stamp's files changed
614
+ # (#memory_differs), unless each changed one holds chi's own later
615
+ # change (OwnChanges: an edit or write of the file, a memory_write;
616
+ # the heartbeat case, a memory read once then edited) - never when the
617
+ # name now answers from another file or overlay (resolved again: stale,
618
+ # as before). A memory_write's: the file it wrote no longer holds its
619
+ # content (someone changed it after chi's write).
620
+ def memory_stale?(key, group, conversation, stat, root, own_of)
621
+ last = group.last
622
+ return written_differs?(key, group, conversation, stat, root, own_of) if last.op == "write"
623
+
624
+ changed = memory_differs(key, last.run, conversation, stat, root)
625
+ return changed == :moved unless changed.is_a?(Array)
626
+ return false if changed.empty?
627
+
628
+ read_at = [last.run.index, last.run.ref.run]
629
+ !changed.all? do |file|
630
+ # A path the stamp names outside the memories folder is never read: no own change, stale (as before).
631
+ next false unless MemoryGuard.memory_paths?({ path: file[:path] }, root)
632
+
633
+ change = own_of.call.for_file(file[:path], role: file[:role], key: file[:key], dirs: file[:dirs])
634
+ change && (change.order <=> read_at) == 1 && own_of.call.current?(change, file[:path], stat: stat)
635
+ end
636
+ end
637
+
638
+ # Whether the memory chi's latest memory_write (+group+'s last run)
639
+ # wrote no longer holds its content: <scope dir>/<name>.md, system
640
+ # from +root+, project from the item's latest read stamp's folder
641
+ # (none: a project memory only written stays live), held to chi's
642
+ # latest own change of that file (the write, or a later edit or write
643
+ # of the file itself). A remove, an overlay or a description-only
644
+ # write: as before, live. Reads only a path the guard lets through.
645
+ def written_differs?(key, group, conversation, stat, root, own_of)
646
+ run = group.last.run
647
+ scope = %w[system project].find do |candidate|
648
+ change = own_of.call.memory(candidate, key)
649
+ change&.tool_id == run.ref.id && change.op == OwnChanges::MEMORY_WRITE
650
+ end
651
+ return false unless scope
652
+
653
+ dir = scope == "system" ? root : read_project_dir(key, group, conversation)
654
+ return false unless dir
655
+
656
+ path = File.join(dir.to_s, "#{key}.md")
657
+ return false unless MemoryGuard.memory_paths?({ path: path }, root)
658
+
659
+ change = own_of.call.for_file(path, role: :base, dirs: { scope => dir })
660
+ !own_of.call.current?(change, path, stat: stat)
661
+ end
662
+
663
+ # The project memories folder the item's latest memory_read stamped.
664
+ def read_project_dir(key, group, conversation)
665
+ touch = group.reverse_each.find { |each| each.op == "read" }
666
+ entries = touch && memory_entries(touch.run, conversation)
667
+ entry = entries && entries[key]
668
+ entry.is_a?(Hash) ? field(entry, :project_dir) : nil
669
+ end
670
+
671
+ # What changed of the memory +key+ since +run+'s stamp (the item's
672
+ # latest run): nil without a stamp (an older session: never stale);
673
+ # :moved when the name now resolves to another file or overlay, or is
674
+ # gone (stamps with request metadata are resolved again); else the
675
+ # stamped files that differ ([{path:, role:, key:, dirs:}], empty when
676
+ # none). Older path-only stamps compare their stamped files.
677
+ def memory_differs(key, run, conversation, stat, root)
611
678
  stamp = stamp_hash(conversation[run.index], run.ref.run)
612
- return false unless stamp
679
+ return nil unless stamp
613
680
 
614
681
  entries = field(stamp, :memories)
615
682
  entry = entries.is_a?(Hash) ? field(entries, key) : nil
616
- return false unless entry.is_a?(Hash)
683
+ return nil unless entry.is_a?(Hash)
617
684
 
618
- if resolution_metadata?(entry)
619
- resolved = resolve_memory(key, entry, system_dir: root)
685
+ if MemoryGuard.resolution_metadata?(entry)
686
+ resolved = MemoryGuard.resolve_memory(key, entry, system_dir: root)
620
687
  unless resolved == :stamped_paths
621
- return true unless resolved
688
+ return :moved unless resolved
622
689
 
623
- return true unless memory_paths?(resolved_memory_entry(resolved), root)
690
+ return :moved unless MemoryGuard.memory_paths?(MemoryGuard.resolved_memory_entry(resolved), root)
624
691
 
625
692
  stamped_overlay = field(entry, :overlay)
626
693
  stamped_overlay_path = stamped_overlay.is_a?(Hash) ? field(stamped_overlay, :path) : nil
627
- return true unless same_path?(resolved.path, field(entry, :path))
628
- return true unless same_path?(resolved.overlay_path, stamped_overlay_path)
694
+ return :moved unless same_path?(resolved.path, field(entry, :path))
695
+ return :moved unless same_path?(resolved.overlay_path, stamped_overlay_path)
629
696
  end
630
697
  end
631
698
 
699
+ dirs = { "project" => field(entry, :project_dir), "system" => root }
632
700
  overlay = field(entry, :overlay)
633
- differs?(field(entry, :path), entry, stat) ||
634
- (overlay.is_a?(Hash) && differs?(field(overlay, :path), overlay, stat))
701
+ changed = []
702
+ changed << { path: field(entry, :path).to_s, role: :base, key: nil, dirs: dirs } if differs?(field(entry, :path), entry, stat)
703
+ if overlay.is_a?(Hash) && differs?(field(overlay, :path), overlay, stat)
704
+ overlay_path = field(overlay, :path).to_s
705
+ changed << { path: overlay_path, role: :overlay, key: Tools::MemoryRead.overlay_key(key, overlay_path), dirs: dirs }
706
+ end
707
+ changed
635
708
  end
636
709
 
637
710
  def same_path?(left, right)
@@ -641,7 +714,8 @@ module Samagotchi
641
714
  end
642
715
 
643
716
  # Whether the file at +path+ is not what +entry+ ({mtime_ns:, size:}) says
644
- # it was, in mtime or size.
717
+ # it was, in mtime or size. Public: an own edit's "still current" is the
718
+ # same compare (OwnChanges#current?).
645
719
  def differs?(path, entry, stat)
646
720
  now = stat.call(path)
647
721
  mtime_ns = (now.mtime.to_i * 1_000_000_000) + now.mtime.nsec
@@ -670,10 +744,8 @@ module Samagotchi
670
744
 
671
745
  def field(hash, key) = hash.key?(key) ? hash[key] : hash[key.to_s]
672
746
 
673
- private_class_method :all_touches, :touches, :failed?, :shared_with, :item, :still_sent?, :dropped?, :with_id,
674
- :changed?, :memory_changed?, :same_path?, :differs?, :stamp_hash, :stamp_of, :field, :event, :body_of,
675
- :lines_of, :saved_diff, :memory_entries, :memory_paths?, :project_dir_within_root?,
676
- :resolution_metadata?, :resolve_memory, :resolved_memory_entry, :memory_part, :overlay_tail,
677
- :memory_scope, :memory_body, :memory_item_scope
747
+ private_class_method :all_touches, :touches, :shared_with, :item, :still_sent?, :dropped?, :with_id,
748
+ :changed?, :memory_stale?, :written_differs?, :read_project_dir, :memory_differs, :same_path?, :stamp_hash, :stamp_of, :field, :event, :body_of,
749
+ :lines_of, :saved_diff, :memory_entries, :memory_part, :overlay_tail, :memory_scope, :memory_item_scope
678
750
  end
679
751
  end
@@ -0,0 +1,221 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "working_set"
4
+ require_relative "tools/memory"
5
+
6
+ module Samagotchi
7
+ module WorkingSet
8
+ # Where a held text came from and how to fetch it again (the plan's D1):
9
+ # the one resolver behind every "now" the working set shows. +origin+
10
+ # says whose record it is, and the guard follows it (the two are not
11
+ # the same and must stay apart):
12
+ # :run a memory_read run's stamp entry (+params+: the entry, +ref+:
13
+ # the name; WorkingSet.memory_now). Resolved with chi web's own
14
+ # folder (+root+), any saved system_dir ignored; an older
15
+ # path-only stamp (or one whose project folder is outside the
16
+ # root) reads its stamped paths; the paths read must pass
17
+ # MemoryGuard.memory_paths?.
18
+ # :prompt a prompt part's saved params (PromptPart#params; +kind+ the
19
+ # part's, +ref+ its ref; WorkingSetPart). A memory resolves
20
+ # with the saved system_dir and project_dir, each inside
21
+ # +root+, and the composer the build used (MemoryRead.compose,
22
+ # ModelNotes.body_at), so an unchanged memory's text is the
23
+ # item's byte for byte; an AGENTS.md only on the session
24
+ # folder's own chain (+cwd+); an appended file never (its path
25
+ # came with a run's flags); base, the kit, a plugin's section,
26
+ # an index and the session lines are chi's own text.
27
+ # #fetch has three outcomes: nil (refused, or nothing to fetch), a Now
28
+ # with gone (the source is gone), a Now with its text (diff nil);
29
+ # #composed adds the files it was read from (a prompt part's own
30
+ # changes are matched to them, WorkingSetPart.states).
31
+ # Not loaded with WorkingSet (the testing kit's file budget,
32
+ # sandbox_spec): WorkingSet.memory_now requires it when it runs.
33
+ Locator = Data.define(:origin, :kind, :ref, :scope, :params)
34
+
35
+ class Locator
36
+ # The prompt kinds whose text is a memory's.
37
+ MEMORY_KINDS = %w[identity preloads notes].freeze
38
+ # The prompt kinds a locator fetches.
39
+ FETCHED = (MEMORY_KINDS + %w[agents]).freeze
40
+ READ = ->(path) { File.read(path, encoding: "UTF-8") }
41
+ GONE = Now.new(text: nil, diff: nil, gone: true)
42
+
43
+ # One file a fetched text was composed from: its +path+, its +role+
44
+ # (:base, the memory's or AGENTS.md's own file; :overlay, the model
45
+ # overlay appended to it) and an overlay's +key+ (the one in its file
46
+ # name).
47
+ Source = Data.define(:path, :role, :key)
48
+ # #composed's answer: the Now #fetch gives and the +files+ (Source,
49
+ # at most two) it was read from. A gone prompt memory's files are the
50
+ # base it was sent from (the build's scope's <ref>.md): chi's remove
51
+ # of it is matched there (WorkingSetPart.states).
52
+ Composed = Data.define(:now, :files)
53
+
54
+ # A prompt part's (PromptPart, its saved params).
55
+ def self.of_part(part)
56
+ new(origin: :prompt, kind: part.kind, ref: part.ref, scope: part.scope, params: part.params)
57
+ end
58
+
59
+ # A memory_read stamp's entry for +name+.
60
+ def self.of_stamp(name, entry)
61
+ new(origin: :run, kind: MEMORY, ref: name, scope: nil, params: entry)
62
+ end
63
+
64
+ # The text now: nil (refused, nothing to fetch), GONE, or a Now with
65
+ # its text. +root+: chi web's memories folder (MemoryPaths.system_dir);
66
+ # +cwd+: the session's folder (an AGENTS.md's chain); +read+: File.read,
67
+ # or a stand-in (a memory's files).
68
+ # @return [Now, nil]
69
+ def fetch(root:, cwd: nil, read: READ) = composed(root: root, cwd: cwd, read: read)&.now
70
+
71
+ # #fetch's Now and the files it read (Composed), nil when #fetch is.
72
+ # @return [Composed, nil]
73
+ def composed(root:, cwd: nil, read: READ)
74
+ return prompt_fetch(root, cwd, read) unless origin == :run
75
+
76
+ found = resolve(root: root)
77
+ return found == :gone ? Composed.new(now: GONE, files: []) : nil unless found.is_a?(Hash)
78
+
79
+ text = body(found, read: read)
80
+ Composed.new(now: text ? Now.new(text: text, diff: nil, gone: false) : GONE, files: run_files(found))
81
+ end
82
+
83
+ # A run's entry as it answers now (:run): the paths to read ({path,
84
+ # overlay}), :gone when no entry answers, nil when refused. Apart from
85
+ # #body so memory_now checks every name before it reads any.
86
+ def resolve(root:)
87
+ entry = params
88
+ return nil unless entry.is_a?(Hash)
89
+
90
+ if MemoryGuard.resolution_metadata?(entry)
91
+ resolved = MemoryGuard.resolve_memory(ref, entry, system_dir: root)
92
+ if resolved != :stamped_paths
93
+ return :gone unless resolved
94
+
95
+ entry = MemoryGuard.resolved_memory_entry(resolved)
96
+ end
97
+ end
98
+ MemoryGuard.memory_paths?(entry, root) ? entry : nil
99
+ end
100
+
101
+ # What memory_read would answer now for a resolved +entry+ (its file
102
+ # and the overlay read with it, as Tools::MemoryRead.call appends
103
+ # it); nil when a file is gone.
104
+ def body(entry, read: READ)
105
+ text = read.call(MemoryGuard.field(entry, :path).to_s)
106
+ overlay = MemoryGuard.field(entry, :overlay)
107
+ return text unless overlay.is_a?(Hash)
108
+
109
+ overlay_path = MemoryGuard.field(overlay, :path).to_s
110
+ model_key = Tools::MemoryRead.overlay_key(ref, overlay_path)
111
+ model_key ? Tools::MemoryRead.append_overlay(text, read.call(overlay_path), model_key) : text
112
+ rescue SystemCallError
113
+ nil
114
+ end
115
+
116
+ private
117
+
118
+ # A resolved run entry's files.
119
+ def run_files(entry)
120
+ overlay = MemoryGuard.field(entry, :overlay)
121
+ overlay_path = overlay.is_a?(Hash) ? MemoryGuard.field(overlay, :path).to_s : nil
122
+ base = [Source.new(path: MemoryGuard.field(entry, :path).to_s, role: :base, key: nil)]
123
+ return base unless overlay_path
124
+
125
+ base + [Source.new(path: overlay_path, role: :overlay, key: Tools::MemoryRead.overlay_key(ref, overlay_path))]
126
+ end
127
+
128
+ def prompt_fetch(root, cwd, read)
129
+ if MEMORY_KINDS.include?(kind)
130
+ memory_fetch(root, read)
131
+ elsif kind == "agents"
132
+ agents_fetch(cwd)
133
+ end
134
+ end
135
+
136
+ # A prompt memory's text with the saved params: no model key or
137
+ # folder is worked out again.
138
+ def memory_fetch(root, read)
139
+ return nil unless params.is_a?(Hash) && MemoryGuard.resolution_metadata?(params)
140
+
141
+ system_dir = MemoryGuard.field(params, :system_dir)
142
+ project_dir = MemoryGuard.field(params, :project_dir)
143
+ return nil unless system_dir && MemoryGuard.inside_root?(system_dir, root) &&
144
+ (project_dir.nil? || MemoryGuard.inside_root?(project_dir, root))
145
+ return nil if ref.to_s.strip.empty? || Tools::MemoryRead.invalid_name?(ref.to_s)
146
+
147
+ kind == "notes" ? note_fetch(system_dir, project_dir, root) : read_fetch(system_dir, project_dir, root, read)
148
+ rescue SystemCallError, ArgumentError
149
+ nil
150
+ end
151
+
152
+ # A gone memory's answer: the base it was sent from, in the scope
153
+ # that answered at build (+dir+), when the guard lets it be named.
154
+ def gone(dir, root)
155
+ return Composed.new(now: GONE, files: []) unless dir
156
+
157
+ path = File.join(dir, "#{ref}.md")
158
+ files = MemoryGuard.memory_paths?({ path: path }, root) ? [Source.new(path: path, role: :base, key: nil)] : []
159
+ Composed.new(now: GONE, files: files)
160
+ end
161
+
162
+ # A preload's or identity's text: resolved as memory_read resolves it.
163
+ def read_fetch(system_dir, project_dir, root, read)
164
+ resolved = MemoryGuard.resolve_memory(ref.to_s, params, system_dir: system_dir)
165
+ return nil if resolved == :stamped_paths
166
+ return gone(kind == "preloads" && scope.to_s == "project" ? project_dir : system_dir, root) unless resolved
167
+ return nil unless MemoryGuard.memory_paths?(MemoryGuard.resolved_memory_entry(resolved), root)
168
+
169
+ files = [Source.new(path: resolved.path, role: :base, key: nil)]
170
+ files << Source.new(path: resolved.overlay_path, role: :overlay, key: resolved.overlay_key) if resolved.overlay_path
171
+ Composed.new(now: Now.new(text: Tools::MemoryRead.compose(resolved, read: read), diff: nil, gone: false), files: files)
172
+ end
173
+
174
+ # A model note's text: its scope's file, its overlay beside it. Every
175
+ # path it may look at (the note, each saved key's overlay) passes the
176
+ # guard before any is looked at: a crafted key refuses whether or not
177
+ # a file is there.
178
+ def note_fetch(system_dir, project_dir, root)
179
+ require_relative "model_notes"
180
+ name = ref.to_s
181
+ dir = MemoryGuard.field(params, :requested_scope).to_s == "project" ? project_dir : system_dir
182
+ return nil unless dir
183
+
184
+ keys = [MemoryGuard.field(params, :model_key), MemoryGuard.field(params, :fallback_model_key)]
185
+ path = File.join(dir, "#{name}.md")
186
+ overlays = keys.compact.map { |key| key.to_s.strip }.reject(&:empty?).map { |key| File.join(dir, "#{name}.#{key}.md") }
187
+ return nil unless [path, *overlays].all? { |candidate| MemoryGuard.memory_paths?({ path: candidate }, root) }
188
+ return gone(dir, root) unless File.file?(path)
189
+
190
+ text = ModelNotes.body_at(path, keys, dir: dir)
191
+ overlay, = ModelNotes.overlay_path(name, keys, dir: dir)
192
+ files = [Source.new(path: path, role: :base, key: nil)]
193
+ files << Source.new(path: overlay, role: :overlay, key: Tools::MemoryRead.overlay_key(name, overlay)) if overlay
194
+ Composed.new(now: Now.new(text: text, diff: nil, gone: text.nil?), files: files)
195
+ end
196
+
197
+ # An AGENTS.md's text, only when it is on +cwd+'s chain.
198
+ def agents_fetch(cwd)
199
+ require_relative "prompt_files"
200
+ path = params.is_a?(Hash) ? params["path"].to_s : ""
201
+ return nil if path.empty? || cwd.to_s.empty?
202
+
203
+ chain = PromptFiles.agents_paths(cwd).map { |candidate| real(candidate) }
204
+ return nil unless chain.include?(real(path))
205
+
206
+ text = PromptFiles.content(path)
207
+ Composed.new(now: Now.new(text: text, diff: nil, gone: text.nil?), files: [Source.new(path: path, role: :base, key: nil)])
208
+ rescue SystemCallError, ArgumentError
209
+ # A path or folder a session file names that no file call takes (a NUL byte): nothing to fetch.
210
+ nil
211
+ end
212
+
213
+ # The same file however it's spelled (/tmp vs /private/tmp on macOS).
214
+ def real(path)
215
+ File.realpath(path)
216
+ rescue SystemCallError
217
+ File.expand_path(path)
218
+ end
219
+ end
220
+ end
221
+ end