samagotchi 0.139.1 → 0.141.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 (65) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +56 -1
  3. data/README.md +2 -1
  4. data/docs/architecture.md +8 -6
  5. data/docs/cli.md +3 -1
  6. data/docs/configuration.md +33 -1
  7. data/docs/context.md +249 -46
  8. data/docs/guardrails.md +11 -0
  9. data/docs/internals/engine.md +7 -1
  10. data/docs/internals/prompt-caching.md +10 -1
  11. data/docs/internals/remote-sessions.md +4 -1
  12. data/docs/plugins.md +75 -18
  13. data/docs/sessions.md +3 -2
  14. data/lib/samagotchi/bridge/turn_accumulator.rb +4 -1
  15. data/lib/samagotchi/bundles/claude-peer/manifest.yml +2 -2
  16. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +14 -0
  17. data/lib/samagotchi/bundles/codex-peer/manifest.yml +2 -2
  18. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +15 -1
  19. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  20. data/lib/samagotchi/bundles/github-pr/manifest.yml +4 -4
  21. data/lib/samagotchi/bundles/github-pr/plugin.rb +72 -176
  22. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  23. data/lib/samagotchi/config.rb +8 -0
  24. data/lib/samagotchi/context_candidate_choice.rb +154 -0
  25. data/lib/samagotchi/context_candidates.rb +259 -0
  26. data/lib/samagotchi/context_candidates_log.rb +90 -0
  27. data/lib/samagotchi/context_command.rb +65 -17
  28. data/lib/samagotchi/context_judge.rb +194 -0
  29. data/lib/samagotchi/context_move.rb +31 -0
  30. data/lib/samagotchi/context_report_command.rb +161 -0
  31. data/lib/samagotchi/context_sources.rb +311 -29
  32. data/lib/samagotchi/engine.rb +189 -32
  33. data/lib/samagotchi/owner_prompt.rb +39 -0
  34. data/lib/samagotchi/plugin/api.rb +1 -0
  35. data/lib/samagotchi/plugin/attached_context.rb +105 -13
  36. data/lib/samagotchi/plugin/context.rb +12 -1
  37. data/lib/samagotchi/plugin/peer.rb +53 -0
  38. data/lib/samagotchi/plugin/sessions.rb +9 -2
  39. data/lib/samagotchi/prompt_warmup.rb +9 -1
  40. data/lib/samagotchi/send_command.rb +3 -1
  41. data/lib/samagotchi/session.rb +4 -0
  42. data/lib/samagotchi/session_access/contract.rb +4 -0
  43. data/lib/samagotchi/session_access/local.rb +34 -3
  44. data/lib/samagotchi/session_access/remote.rb +33 -8
  45. data/lib/samagotchi/session_access.rb +31 -6
  46. data/lib/samagotchi/session_commands.rb +28 -5
  47. data/lib/samagotchi/session_continue.rb +9 -2
  48. data/lib/samagotchi/side_judgments.rb +84 -0
  49. data/lib/samagotchi/terminal_ui.rb +15 -0
  50. data/lib/samagotchi/testing/boundary.rb +5 -1
  51. data/lib/samagotchi/testing/host.rb +4 -1
  52. data/lib/samagotchi/toolkit_report_command.rb +2 -1
  53. data/lib/samagotchi/toolkit_suggest.rb +3 -18
  54. data/lib/samagotchi/version.rb +1 -1
  55. data/lib/samagotchi/web/app.rb +24 -11
  56. data/lib/samagotchi/web/auto_update.rb +8 -1
  57. data/lib/samagotchi/web/public/app.js +8 -2
  58. data/lib/samagotchi/web/public/chains.js +10 -2
  59. data/lib/samagotchi/web/public/update_notice.js +21 -8
  60. data/lib/samagotchi/web/session_access_routes.rb +8 -3
  61. data/lib/samagotchi/web/session_create.rb +1 -0
  62. data/lib/samagotchi/web/session_hub.rb +5 -2
  63. data/lib/samagotchi/web/update_check.rb +14 -8
  64. data/lib/samagotchi/worker.rb +5 -0
  65. metadata +9 -1
@@ -22,14 +22,15 @@ module Samagotchi
22
22
  # sessions/<id>/subscriptions.json {name => Subscription}; the worker writes it
23
23
  # sessions/<id>/muted/<name> a marker: this session ignores <name>
24
24
  # sessions/<id>/declined/<name> a marker (its hint inside): the user removed <name>
25
- # sessions/<id>/offered/<name> a marker ({hint, why, at}): a plugin offered <name> (ctx.context.mark_offered)
25
+ # sessions/<id>/candidates/<name>.json a Candidate: a source a plugin proposed here (ctx.context.propose)
26
+ # sessions/<id>/left.json [Left]: what a continue left with the previous link (.move)
26
27
  # The guardrails protect the root (ProtectedPaths, CHI_TEXT): a source's
27
28
  # command runs later, outside the gate.
28
29
  module ContextSources
29
30
  DIR = "context"
30
31
  NAME_RE = /\A[a-z0-9][a-z0-9-]{0,39}\z/
31
- # subscriptions.json shares a session's folder with its sources.
32
- RESERVED_NAMES = %w[subscriptions].freeze
32
+ # subscriptions.json and left.json share a session's folder with its sources.
33
+ RESERVED_NAMES = %w[subscriptions left].freeze
33
34
  SCOPES = %w[session project].freeze
34
35
  MIN_EVERY_SECONDS = 30
35
36
  DEFAULT_EVERY_SECONDS = 300
@@ -38,9 +39,13 @@ module Samagotchi
38
39
  LINE_MAX_CHARS = 300
39
40
  SNAPSHOT_SUFFIX = ".snapshot.json"
40
41
  SUBSCRIPTIONS_FILE = "subscriptions.json"
42
+ LEFT_FILE = "left.json"
41
43
  MUTED_DIR = "muted"
42
44
  DECLINED_DIR = "declined"
43
- OFFERED_DIR = "offered"
45
+ CANDIDATES_DIR = "candidates"
46
+ # A candidate keeps this many mentions, each one line of up to LINE_MAX_CHARS.
47
+ MENTIONS_MAX = 10
48
+ DESCRIBE_MAX_CHARS = 1000
44
49
 
45
50
  # A name, a command, a value the store can't take.
46
51
  class Invalid < ArgumentError; end
@@ -48,20 +53,34 @@ module Samagotchi
48
53
  # A source's definition. +cmd+ nil: pushed only (chi context push).
49
54
  # +provider+: the bundle whose context provider made it (a URL), whose
50
55
  # folder its cmd's {bundle_dir} names (ContextProviders.command_for).
51
- Source = Data.define(:name, :cmd, :every_seconds, :why, :hint, :scope, :added_by, :created_at, :provider) do
52
- def initialize(name:, cmd:, every_seconds:, why:, hint:, scope:, added_by:, created_at:, provider: nil) = super
56
+ # +title+: what a person reads it as (a candidate's, when one was
57
+ # attached; nil for most).
58
+ # +movable+: whether a continue or a fork takes it to the new session
59
+ # (ContextSources.move); nil derives it (#movable?).
60
+ Source = Data.define(:name, :cmd, :every_seconds, :why, :hint, :scope, :added_by, :created_at, :provider, :title,
61
+ :movable) do
62
+ def initialize(name:, cmd:, every_seconds:, why:, hint:, scope:, added_by:, created_at:, provider: nil, title: nil,
63
+ movable: nil) = super
53
64
 
54
65
  def push? = cmd.nil?
55
66
 
67
+ # Given (+movable+), else derived from who writes the text: a command
68
+ # source moves (chi runs its command, in the new session too); a
69
+ # pushed one stays (its writer holds the old session's id).
70
+ def movable? = movable.nil? ? !push? : movable
71
+
56
72
  def to_h
57
73
  { "name" => name, "cmd" => cmd, "every_seconds" => every_seconds, "why" => why, "hint" => hint,
58
- "scope" => scope, "added_by" => added_by, "created_at" => created_at, "provider" => provider }.compact
74
+ "scope" => scope, "added_by" => added_by, "created_at" => created_at, "provider" => provider,
75
+ "title" => title, "movable" => movable }.compact
59
76
  end
60
77
 
61
78
  def self.from_h(data)
79
+ movable = data["movable"]
62
80
  new(name: data["name"].to_s, cmd: data["cmd"], every_seconds: data["every_seconds"]&.to_i,
63
81
  why: data["why"], hint: data["hint"], scope: data["scope"].to_s, added_by: data["added_by"],
64
- created_at: data["created_at"], provider: data["provider"])
82
+ created_at: data["created_at"], provider: data["provider"], title: data["title"],
83
+ movable: [true, false].include?(movable) ? movable : nil)
65
84
  end
66
85
  end
67
86
 
@@ -133,10 +152,25 @@ module Samagotchi
133
152
  # What a command printed or a push sent (the contract, ContextSources.parse_output).
134
153
  Fetched = Data.define(:text, :summary, :wake, :hint)
135
154
 
136
- # A plugin's offer of a source to a session (ctx.context.mark_offered):
137
- # +hint+ (often the URL), +why+ (the plugin's reason, for the attach
138
- # that may follow; nil for none) and +at+, when it was offered (ISO 8601).
139
- Offer = Data.define(:name, :hint, :why, :at)
155
+ # A source a plugin proposed for a session, not attached
156
+ # (ctx.context.propose): its spec (+url+, through an installed bundle's
157
+ # provider, or +cmd+), +title+ (what a person or a judge reads),
158
+ # +describe+ (optional, more of the same), +mentions+ (the words in an
159
+ # owner prompt that name it), +proposed_by+ ("plugin:<bundle>") and
160
+ # +at+, when it was proposed (ISO 8601). Written once: whether it is
161
+ # attached or declined is the store's (a source of its name, a declined
162
+ # marker), never kept here.
163
+ Candidate = Data.define(:name, :url, :cmd, :title, :describe, :mentions, :proposed_by, :at) do
164
+ def to_h
165
+ { "url" => url, "cmd" => cmd, "title" => title, "describe" => describe, "mentions" => mentions,
166
+ "proposed_by" => proposed_by, "at" => at }.compact
167
+ end
168
+
169
+ def self.from_h(name, data)
170
+ new(name: name, url: data["url"], cmd: data["cmd"], title: data["title"].to_s, describe: data["describe"],
171
+ mentions: Array(data["mentions"]).map(&:to_s), proposed_by: data["proposed_by"], at: data["at"])
172
+ end
173
+ end
140
174
 
141
175
  # A source as one session sees it: the definition, where it lives, and
142
176
  # +shadowed+ for a project source hidden by a session one of its name.
@@ -158,10 +192,11 @@ module Samagotchi
158
192
  return [] unless Dir.exist?(dir)
159
193
 
160
194
  Dir.children(dir).sort.filter_map do |file|
161
- next unless file.end_with?(".json") && !file.end_with?(SNAPSHOT_SUFFIX) && file != SUBSCRIPTIONS_FILE
195
+ next unless file.end_with?(".json") && !file.end_with?(SNAPSHOT_SUFFIX)
162
196
 
163
197
  name = file.delete_suffix(".json")
164
- name.match?(NAME_RE) ? source(name) : nil
198
+ # subscriptions.json, left.json: not sources.
199
+ name.match?(NAME_RE) && !RESERVED_NAMES.include?(name) ? source(name) : nil
165
200
  end
166
201
  end
167
202
 
@@ -288,22 +323,45 @@ module Samagotchi
288
323
  end
289
324
  end
290
325
 
291
- def offered_path(name) = File.join(dir, OFFERED_DIR, ContextSources.check_name!(name))
326
+ def candidate_path(name) = File.join(dir, CANDIDATES_DIR, "#{ContextSources.check_name!(name)}.json")
327
+
328
+ # Session only: records +candidate+ unless one of its name is here
329
+ # already (the first proposal stays as it was). Neither an add nor a
330
+ # decline clears it; deleting the session does.
331
+ # @return [Candidate] the one recorded (+candidate+ or the earlier one)
332
+ def add_candidate(candidate)
333
+ existing = candidate(candidate.name)
334
+ return existing if existing
292
335
 
293
- # Session only: a plugin offered +name+ here (so it doesn't offer it
294
- # again). Neither an add nor a decline clears it.
295
- # @return [Offer]
296
- def mark_offered(name, hint, why: nil, at: Time.now)
297
- offer = Offer.new(name: ContextSources.check_name!(name), hint: hint, why: why, at: at.utc.iso8601)
298
- FileUtils.mkdir_p(File.join(dir, OFFERED_DIR))
299
- AtomicFile.write(offered_path(name), "#{JSON.generate({ "hint" => offer.hint, "why" => offer.why, "at" => offer.at }.compact)}\n")
300
- offer
336
+ FileUtils.mkdir_p(File.join(dir, CANDIDATES_DIR))
337
+ AtomicFile.write(candidate_path(candidate.name), "#{JSON.generate(candidate.to_h)}\n")
338
+ candidate
301
339
  end
302
340
 
303
- # @return [Offer, nil]
304
- def offered(name)
305
- data = ContextSources.read_json(offered_path(name))
306
- data.is_a?(Hash) ? Offer.new(name: name, hint: data["hint"], why: data["why"], at: data["at"]) : nil
341
+ # @return [Candidate, nil]
342
+ def candidate(name)
343
+ data = ContextSources.read_json(candidate_path(name))
344
+ data ? Candidate.from_h(name, data) : nil
345
+ end
346
+
347
+ # Removes the candidate +name+ (an attached source of its name stays).
348
+ # @return [Boolean] whether there was one
349
+ def remove_candidate(name)
350
+ path = candidate_path(name)
351
+ existed = File.exist?(path)
352
+ FileUtils.rm_f(path)
353
+ existed
354
+ end
355
+
356
+ # @return [Array<Candidate>] by name
357
+ def candidates
358
+ folder = File.join(dir, CANDIDATES_DIR)
359
+ return [] unless Dir.exist?(folder)
360
+
361
+ Dir.children(folder).sort.filter_map do |file|
362
+ name = file.delete_suffix(".json")
363
+ candidate(name) if file.end_with?(".json") && name.match?(NAME_RE) && !RESERVED_NAMES.include?(name)
364
+ end
307
365
  end
308
366
 
309
367
  # Session only: the markers and the worker's subscription file.
@@ -330,6 +388,18 @@ module Samagotchi
330
388
  AtomicFile.write(File.join(dir, SUBSCRIPTIONS_FILE), JSON.generate(subs.transform_values(&:to_h)))
331
389
  end
332
390
 
391
+ # What a continue left with the previous link (ContextSources.move).
392
+ # @return [Array<Left>] none without the file
393
+ def left
394
+ rows = ContextSources.read_json_value(File.join(dir, LEFT_FILE))
395
+ Array(rows).filter_map { |row| Left.from_h(row) if row.is_a?(Hash) && row["name"].is_a?(String) }
396
+ end
397
+
398
+ def write_left(rows)
399
+ FileUtils.mkdir_p(dir)
400
+ AtomicFile.write(File.join(dir, LEFT_FILE), JSON.generate(rows.map(&:to_h)))
401
+ end
402
+
333
403
  def update_subscription(name)
334
404
  subs = subscriptions
335
405
  subs[name] = yield(subs[name] || Subscription.blank(name))
@@ -338,8 +408,215 @@ module Samagotchi
338
408
  end
339
409
  end
340
410
 
411
+ # A source a move left behind (ContextSources.move): its +name+ and
412
+ # +why+, :pushed (derived: its writer holds the old id) or :not_movable
413
+ # (its movable: false).
414
+ Stayed = Data.define(:name, :why) do
415
+ def label = why == :pushed ? "pushed" : "not movable"
416
+
417
+ # The peer whose pairing this is ("Claude"), for a pushed
418
+ # <peer>-inbox or <peer>-outbox (the peer bundles' names: the move
419
+ # runs where no plugin is loaded, so the name is all there is; it
420
+ # only words the note, PeerSources decides what a peer is); nil for
421
+ # any other.
422
+ def peer
423
+ match = why == :pushed && PEER_NAME.match(name)
424
+ match ? match[1].capitalize : nil
425
+ end
426
+
427
+ def inbox? = name.end_with?("-inbox")
428
+ end
429
+ # A source a continue left with the previous link (+from+), as the new
430
+ # link's left.json keeps it: its +name+ and +hint+, the snapshot's (a
431
+ # pushed hint: a peer's re-pair pushes its new inbox there) else the
432
+ # source's. ctx.context.left_behind reads it (Plugin::Peer asks the peer
433
+ # to pair again at that inbox).
434
+ Left = Data.define(:name, :hint, :from) do
435
+ def to_h = { "name" => name, "hint" => hint, "from" => from }.compact
436
+
437
+ def self.from_h(data) = new(name: data["name"].to_s, hint: data["hint"]&.to_s, from: data["from"]&.to_s)
438
+ end
439
+
440
+ PEER_NAME = /\A([a-z][a-z0-9]*)-(?:inbox|outbox)\z/
441
+
442
+ # What ContextSources.move did: the names it took to the new session
443
+ # (+moved+) and the sources it left (+stayed+, Stayed).
444
+ Moved = Data.define(:moved, :stayed) do
445
+ def self.none = new(moved: [], stayed: [])
446
+
447
+ def empty? = moved.empty? && stayed.empty?
448
+
449
+ # The new session's note (one sentence each, no instructions); nil
450
+ # when nothing moved or stayed.
451
+ # @param from [String] the session the sources came from
452
+ def note_text(from)
453
+ return nil if empty?
454
+
455
+ lines = []
456
+ lines << "Context moved with this session: #{moved.join(", ")}." unless moved.empty?
457
+ lines << "Left with #{from.to_s[0, 8]}: #{left_words.join(", ")}." unless stayed.empty?
458
+ lines.join(" ")
459
+ end
460
+
461
+ # Each stayed source with why; a peer's pairing as one group, saying
462
+ # what chi does about it (Plugin::Peer posts the moved message to an
463
+ # inbox left behind; an outbox alone hears of it on its next push's
464
+ # refusal), never whether it worked.
465
+ def left_words
466
+ stayed.group_by { |s| s.peer || s }.values.map do |group|
467
+ peer = group.first.peer
468
+ next "#{group.first.name} (#{group.first.label})" unless peer
469
+
470
+ how = if group.any?(&:inbox?)
471
+ "#{peer}'s pairing: chi asks #{peer} to pair again with this session"
472
+ else
473
+ "#{peer} pairs again when it next answers"
474
+ end
475
+ "#{group.map(&:name).join(", ")} (#{how})"
476
+ end
477
+ end
478
+
479
+ # A UI's few words (chi send --new --continues); nil for nothing.
480
+ def words
481
+ parts = []
482
+ parts << "context moved: #{moved.join(", ")}" unless moved.empty?
483
+ parts << "context stayed: #{stayed.map(&:name).join(", ")}" unless stayed.empty?
484
+ parts.empty? ? nil : parts.join("; ")
485
+ end
486
+
487
+ # chi web's continue answer (moved_context).
488
+ def to_h = { "moved" => moved, "stayed" => stayed.map { |s| { "name" => s.name, "why" => s.label } } }
489
+
490
+ # @param data [Hash, nil] #to_h's; nil (an older chi web): nil
491
+ def self.from_h(data)
492
+ return nil unless data.is_a?(Hash)
493
+
494
+ stayed = Array(data["stayed"]).filter_map do |row|
495
+ next unless row.is_a?(Hash)
496
+
497
+ Stayed.new(name: row["name"].to_s, why: row["why"] == "pushed" ? :pushed : :not_movable)
498
+ end
499
+ new(moved: Array(data["moved"]).map(&:to_s), stayed: stayed)
500
+ end
501
+ end
502
+
341
503
  module_function
342
504
 
505
+ # Takes the movable sources of session +from+'s own location
506
+ # (Source#movable?) to session +to+, the new link of a continue or a
507
+ # plugin fork (+mode+ :continue or :fork), before +to+'s worker starts:
508
+ # each one's source and snapshot (a plain read: writes are AtomicFile
509
+ # renames; never Location#locked, which a fetch holds for its whole
510
+ # command), every declined/ and muted/ marker (the user's choices),
511
+ # and a subscription per source moved. A continue's says nothing seen
512
+ # (the new link's first absorb gives the Attached note) at the
513
+ # snapshot's serial (an old wake doesn't wake it). A fork's is what
514
+ # its +seed+ (the fork's messages) last had: the newest note about the
515
+ # source (its note_id, ContextAbsorber#text_note_id), else as a
516
+ # continue's. Never candidates/, lock files, or a source +to+ has
517
+ # already (it wins). A continue's link keeps what stayed in left.json
518
+ # (Left, Location#left).
519
+ # @param seed [Array<Hash>] a fork's messages
520
+ # @return [Moved]
521
+ def move(from:, to:, mode:, state_dir:, seed: nil)
522
+ raise ArgumentError, "mode is :continue or :fork, not #{mode.inspect}" unless %i[continue fork].include?(mode)
523
+
524
+ source_loc = session_location(from, state_dir: state_dir)
525
+ target = session_location(to, state_dir: state_dir)
526
+ return Moved.none unless Dir.exist?(source_loc.dir)
527
+
528
+ moved = []
529
+ stayed = []
530
+ left = []
531
+ subs = {}
532
+ source_loc.sources.each do |source|
533
+ unless source.movable?
534
+ stayed << Stayed.new(name: source.name, why: source.movable.nil? ? :pushed : :not_movable)
535
+ left << Left.new(name: source.name, hint: source_loc.snapshot(source.name).hint || source.hint, from: from)
536
+ next
537
+ end
538
+ next if File.exist?(target.source_path(source.name))
539
+
540
+ snapshot = copy_source(source, from: source_loc, to: target) or next
541
+ subs[source.name] = moved_subscription(source.name, snapshot, mode == :fork ? seed : nil)
542
+ moved << source.name
543
+ end
544
+ [DECLINED_DIR, MUTED_DIR].each { |folder| copy_markers(source_loc.dir, target.dir, folder) }
545
+ target.write_subscriptions(target.subscriptions.merge(subs)) unless subs.empty?
546
+ target.write_left(left) if mode == :continue && !left.empty?
547
+ Moved.new(moved: moved, stayed: stayed)
548
+ end
549
+
550
+ # The source's file and its snapshot's (when it has one), as they are.
551
+ # @return [Snapshot, nil] the snapshot copied (Snapshot.empty: none);
552
+ # nil when the source went meanwhile (nothing copied)
553
+ def copy_source(source, from:, to:)
554
+ source_raw = File.read(from.source_path(source.name))
555
+ snapshot_path = from.snapshot_path(source.name)
556
+ snapshot_raw = File.file?(snapshot_path) ? File.read(snapshot_path) : nil
557
+ FileUtils.mkdir_p(to.dir)
558
+ AtomicFile.write(to.snapshot_path(source.name), snapshot_raw) if snapshot_raw
559
+ AtomicFile.write(to.source_path(source.name), source_raw)
560
+ data = snapshot_raw && read_json_text(snapshot_raw)
561
+ data ? Snapshot.from_h(data) : Snapshot.empty
562
+ rescue SystemCallError
563
+ nil
564
+ end
565
+
566
+ def read_json_text(raw)
567
+ data = JSON.parse(raw)
568
+ data.is_a?(Hash) ? data : nil
569
+ rescue JSON::ParserError
570
+ nil
571
+ end
572
+
573
+ def copy_markers(from_dir, to_dir, folder)
574
+ source = File.join(from_dir, folder)
575
+ return unless Dir.exist?(source)
576
+
577
+ Dir.children(source).each do |name|
578
+ next unless name.match?(NAME_RE)
579
+
580
+ path = File.join(to_dir, folder, name)
581
+ next if File.exist?(path)
582
+
583
+ FileUtils.mkdir_p(File.dirname(path))
584
+ AtomicFile.write(path, File.read(File.join(source, name)))
585
+ rescue SystemCallError
586
+ next
587
+ end
588
+ end
589
+
590
+ # A moved source's subscription in the new session (#move).
591
+ def moved_subscription(name, snapshot, seed)
592
+ blank = Subscription.blank(name).with(seen_serial: snapshot.serial)
593
+ held = seed && seed_note(name, seed)
594
+ return blank unless held
595
+
596
+ serial, prefix = held
597
+ same = snapshot.serial == serial && snapshot.revision.to_s.start_with?(prefix)
598
+ # A partial revision differs from every full one: an Updated note follows.
599
+ Subscription.blank(name).with(seen: same ? snapshot.revision : prefix, seen_serial: serial)
600
+ end
601
+
602
+ # The serial and revision prefix of the newest text note about +name+
603
+ # in +messages+ (ContextAbsorber's note_id, ctx-<name>-<serial>-<rev12>).
604
+ # @return [Array(Integer, String), nil]
605
+ def seed_note(name, messages)
606
+ pattern = /\Actx-#{Regexp.escape(name)}-(\d+)-(\h{12})\z/
607
+ Array(messages).reverse_each do |message|
608
+ next unless message.is_a?(Hash)
609
+
610
+ context_source = message.key?(:context_source) ? message[:context_source] : message["context_source"]
611
+ next unless context_source == name
612
+
613
+ note_id = (message.key?(:note_id) ? message[:note_id] : message["note_id"]).to_s
614
+ match = pattern.match(note_id) or next
615
+ return [match[1].to_i, match[2]]
616
+ end
617
+ nil
618
+ end
619
+
343
620
  # <state dir>/context; +state_dir+ is the sessions dir (Session.default_state_dir).
344
621
  def root(state_dir: nil)
345
622
  File.join(File.dirname(state_dir || Session.default_state_dir), DIR)
@@ -479,10 +756,15 @@ module Samagotchi
479
756
  end
480
757
 
481
758
  def read_json(path)
759
+ data = read_json_value(path)
760
+ data.is_a?(Hash) ? data : nil
761
+ end
762
+
763
+ # The JSON value in +path+; nil when there is none or it isn't JSON.
764
+ def read_json_value(path)
482
765
  return nil unless File.file?(path)
483
766
 
484
- data = JSON.parse(File.read(path))
485
- data.is_a?(Hash) ? data : nil
767
+ JSON.parse(File.read(path))
486
768
  rescue JSON::ParserError, SystemCallError
487
769
  nil
488
770
  end