samagotchi 0.164.0 → 0.166.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 (100) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +88 -1
  3. data/docs/architecture.md +7 -5
  4. data/docs/cli.md +23 -12
  5. data/docs/configuration.md +8 -2
  6. data/docs/guardrails.md +19 -18
  7. data/docs/internals/block-renderers.md +1 -1
  8. data/docs/internals/bridge.md +10 -3
  9. data/docs/internals/bundles.md +4 -2
  10. data/docs/internals/inline-widgets.md +8 -1
  11. data/docs/internals/remote-sessions.md +1 -1
  12. data/docs/internals/web-frontend.md +73 -13
  13. data/docs/memory.md +12 -7
  14. data/docs/plugins.md +6 -4
  15. data/docs/releasing.md +17 -4
  16. data/docs/scheduling.md +25 -3
  17. data/docs/sessions.md +12 -10
  18. data/docs/testing.md +37 -4
  19. data/lib/samagotchi/block_renderers.rb +3 -6
  20. data/lib/samagotchi/bridge/card_store.rb +2 -1
  21. data/lib/samagotchi/bridge/turn_accumulator.rb +7 -8
  22. data/lib/samagotchi/bridge.rb +45 -3
  23. data/lib/samagotchi/bundle_command/installed_check.rb +2 -1
  24. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  25. data/lib/samagotchi/chi_home.rb +44 -2
  26. data/lib/samagotchi/client_id.rb +34 -3
  27. data/lib/samagotchi/compat.rb +34 -0
  28. data/lib/samagotchi/context_command.rb +3 -0
  29. data/lib/samagotchi/context_providers.rb +5 -6
  30. data/lib/samagotchi/context_sources.rb +2 -2
  31. data/lib/samagotchi/continue_intent.rb +50 -5
  32. data/lib/samagotchi/events.rb +4 -4
  33. data/lib/samagotchi/extension_load.rb +2 -1
  34. data/lib/samagotchi/guardrails/approvals.rb +36 -9
  35. data/lib/samagotchi/guardrails/child_boundary.rb +7 -27
  36. data/lib/samagotchi/guardrails/rules.rb +11 -9
  37. data/lib/samagotchi/guardrails/targets.rb +3 -4
  38. data/lib/samagotchi/inline_widgets.rb +16 -1
  39. data/lib/samagotchi/memory_bundle/provenance.rb +46 -4
  40. data/lib/samagotchi/memory_bundle/status.rb +2 -1
  41. data/lib/samagotchi/memory_command.rb +3 -0
  42. data/lib/samagotchi/memory_orphans.rb +4 -7
  43. data/lib/samagotchi/memory_paths.rb +64 -7
  44. data/lib/samagotchi/memory_usage.rb +1 -1
  45. data/lib/samagotchi/plugin/sessions.rb +8 -3
  46. data/lib/samagotchi/project_command.rb +4 -1
  47. data/lib/samagotchi/project_id_clash.rb +37 -26
  48. data/lib/samagotchi/project_init.rb +24 -7
  49. data/lib/samagotchi/reply_wait/poll.rb +4 -14
  50. data/lib/samagotchi/reply_wait.rb +0 -23
  51. data/lib/samagotchi/run_options.rb +1 -1
  52. data/lib/samagotchi/schedules.rb +124 -106
  53. data/lib/samagotchi/send_command.rb +71 -18
  54. data/lib/samagotchi/session.rb +3 -2
  55. data/lib/samagotchi/session_access/local.rb +19 -2
  56. data/lib/samagotchi/session_access/remote.rb +13 -17
  57. data/lib/samagotchi/session_chain/links.rb +109 -0
  58. data/lib/samagotchi/session_chain.rb +7 -19
  59. data/lib/samagotchi/session_continue.rb +138 -54
  60. data/lib/samagotchi/session_inbox.rb +1 -1
  61. data/lib/samagotchi/session_inbox_delivery.rb +57 -38
  62. data/lib/samagotchi/session_manager/delivery.rb +104 -18
  63. data/lib/samagotchi/session_manager/removal.rb +13 -7
  64. data/lib/samagotchi/session_manager.rb +1 -0
  65. data/lib/samagotchi/session_retention.rb +20 -10
  66. data/lib/samagotchi/session_setup.rb +31 -1
  67. data/lib/samagotchi/state_format.rb +12 -8
  68. data/lib/samagotchi/terminal_ui/attach_launcher.rb +6 -7
  69. data/lib/samagotchi/terminal_ui.rb +20 -9
  70. data/lib/samagotchi/tools/delegate.rb +2 -3
  71. data/lib/samagotchi/verify_fresh.rb +4 -1
  72. data/lib/samagotchi/version.rb +1 -1
  73. data/lib/samagotchi/web/public/activity.js +2 -2
  74. data/lib/samagotchi/web/public/app.js +28 -21
  75. data/lib/samagotchi/web/public/auth_lost.js +3 -1
  76. data/lib/samagotchi/web/public/bar_fold.js +293 -0
  77. data/lib/samagotchi/web/public/card.js +1 -1
  78. data/lib/samagotchi/web/public/chip_popover.js +5 -1
  79. data/lib/samagotchi/web/public/composer_mode.js +5 -7
  80. data/lib/samagotchi/web/public/delivery_line.js +19 -4
  81. data/lib/samagotchi/web/public/index.html +242 -94
  82. data/lib/samagotchi/web/public/info_bar.js +28 -16
  83. data/lib/samagotchi/web/public/info_bar_model.js +76 -2
  84. data/lib/samagotchi/web/public/live_timing.js +3 -0
  85. data/lib/samagotchi/web/public/more_sheet.js +98 -40
  86. data/lib/samagotchi/web/public/resync_reach.js +59 -0
  87. data/lib/samagotchi/web/public/session_fields.js +1 -0
  88. data/lib/samagotchi/web/public/session_state.js +5 -0
  89. data/lib/samagotchi/web/public/stage_frame.js +4 -2
  90. data/lib/samagotchi/web/public/stage_stall.js +134 -0
  91. data/lib/samagotchi/web/public/stage_view.js +78 -7
  92. data/lib/samagotchi/web/public/stream_handlers.js +1 -1
  93. data/lib/samagotchi/web/public/turn_events.js +0 -122
  94. data/lib/samagotchi/web/public/turn_model.js +1 -1
  95. data/lib/samagotchi/web/public/widget_picks.js +18 -3
  96. data/lib/samagotchi/web/session_control.rb +15 -2
  97. data/lib/samagotchi/web/session_create.rb +4 -2
  98. data/lib/samagotchi/web/token.rb +2 -2
  99. data/lib/samagotchi/web/update_check.rb +27 -8
  100. metadata +5 -1
@@ -11,6 +11,10 @@ module Samagotchi
11
11
  WEB_RESTART = "web:restart"
12
12
  # A web page's first prompt when creating a session.
13
13
  WEB_CREATE = "web:create"
14
+ # The owner's turn or command route (POST /api/sessions/:id/turn,
15
+ # /command) given no client_id (a script, curl with the owner's token):
16
+ # named at that seam, a web tab's rights, never a silent nil.
17
+ WEB_UNNAMED = "web:unnamed"
14
18
  # An attached chi TUI: tui:<pid>.
15
19
  TUI_PREFIX = "tui:"
16
20
  # chi send's turns and commands.
@@ -45,9 +49,13 @@ module Samagotchi
45
49
 
46
50
  # Input a human typed: a web tab, a chi TUI, chi send, a participant
47
51
  # (review:, a person or an agent they run: never automatic input), and
48
- # nil (a worker's initial prompt; a web client may send none). An
49
- # allowlist: delegates, plugins, reminders, context changes and any id
50
- # chi doesn't know are not.
52
+ # nil, which reaches only a worker's own seams: its initial prompt
53
+ # (spawn_session saves no first_turn_client_id for a person's), a Bridge
54
+ # POST /turn naming none (the Bridge's secret holder: a local TUI or chi
55
+ # web, which names its sender) and an input file from an older chi.
56
+ # SessionManager.deliver_turn refuses nil; chi web's turn and command routes
57
+ # name it (WEB_UNNAMED). An allowlist: delegates, plugins, reminders, context
58
+ # changes and any id chi doesn't know are not.
51
59
  HUMAN_PREFIXES = [WEB_PREFIX, TUI_PREFIX, REVIEW_PREFIX].freeze
52
60
  HUMAN_IDS = [CLI_SEND].freeze
53
61
 
@@ -58,6 +66,14 @@ module Samagotchi
58
66
  # A turn's origin by its sender (#origin, LastTurn#origin): the ids chi
59
67
  # runs turns for on its own, by prefix, and a participant's ("review");
60
68
  # system:reminder is "reminder", anything else "client".
69
+ # Which SessionInbox::WakePolicy row a turn delivery from a sender reads
70
+ # (#wake_kind): a person's (:send: un-stops, un-archives) by allowlist,
71
+ # like HUMAN_PREFIXES; the unattended senders' own rows; any other id
72
+ # the safe :automatic row (no un-stop, no un-archive).
73
+ PERSON_WAKE_PREFIXES = [WEB_PREFIX, TUI_PREFIX].freeze
74
+ WAKE_PREFIXES = { SCHEDULE_PREFIX => :schedule, DELEGATE_PREFIX => :delegate,
75
+ REVIEW_PREFIX => :participant }.freeze
76
+
61
77
  ORIGIN_PREFIXES = { DELEGATE_PREFIX => "delegate", CHILD_PREFIX => "delegate_report",
62
78
  CONTEXT_PREFIX => "context", TASK_PREFIX => "task", REVIEW_PREFIX => "review",
63
79
  SCHEDULE_PREFIX => "schedule" }.freeze
@@ -93,6 +109,21 @@ module Samagotchi
93
109
  HUMAN_IDS.include?(id) || HUMAN_PREFIXES.any? { |prefix| id.start_with?(prefix) }
94
110
  end
95
111
 
112
+ # The WakePolicy row a turn delivery from +client_id+ reads (deliver_turn's
113
+ # two liveness checks): :send for a person (a web tab, a chi TUI, chi
114
+ # send), :schedule, :plugin, :delegate or :participant for those
115
+ # senders, :automatic for anything else (nil too: deliver_turn refuses it
116
+ # first). Only :send un-stops a stopped session or starts an archived one.
117
+ # @return [Symbol]
118
+ def wake_kind(client_id)
119
+ id = client_id.to_s
120
+ return :send if id == CLI_SEND || PERSON_WAKE_PREFIXES.any? { |prefix| id.start_with?(prefix) }
121
+ return :plugin if id == PLUGIN
122
+
123
+ WAKE_PREFIXES.each { |prefix, kind| return kind if id.start_with?(prefix) }
124
+ :automatic
125
+ end
126
+
96
127
  # The client id a participant's turn carries (chi web's, from their
97
128
  # grant): review:<participant id>.
98
129
  def review(participant_id) = "#{REVIEW_PREFIX}#{participant_id}"
@@ -6,8 +6,42 @@ require_relative "version"
6
6
  module Samagotchi
7
7
  # The compatibility decision for state and bridge data from a chi version.
8
8
  module Compat
9
+ # Code kept only for another chi version's data or protocol, and the
10
+ # release after which it goes. +remove_after+ nil: the owner hasn't
11
+ # decided (kept until then). spec/compat_spec.rb fails once VERSION
12
+ # passes a shim's +remove_after+, naming it. Each Ruby file names its
13
+ # shim's id in a comment ("compat shim <id>").
14
+ # @!attribute files [Array<String>] where the shim lives (from the repository root)
15
+ Shim = Data.define(:id, :added_in, :remove_after, :files, :what)
16
+
17
+ SHIMS = [
18
+ Shim.new(id: :cards_v1_seed, added_in: "0.151.0", remove_after: "0.170.0",
19
+ files: ["lib/samagotchi/bridge/card_store.rb"],
20
+ what: "CardStore#seed_v1 reads a cards.json from before the turn log; its comment says a retention " \
21
+ "period after the release that wrote version 2 (0.151.0, 2026-11-05)"),
22
+ Shim.new(id: :retired_class_file_hooks, added_in: "0.158.0", remove_after: "0.166.0",
23
+ files: ["lib/samagotchi/extension_load.rb", "lib/samagotchi/memory_bundle/status.rb",
24
+ "lib/samagotchi/bundle_command/installed_check.rb"],
25
+ what: "a 0.157 install record's class-file hooks: announced as not loading, shown and checked until " \
26
+ "an upgrade or uninstall clears them (installed state, not protocol)"),
27
+ Shim.new(id: :approvals_array_read, added_in: "0.166.0", remove_after: nil,
28
+ files: ["lib/samagotchi/guardrails/approvals.rb"],
29
+ what: "Approvals#parse reads approvals.json as the list 0.165 and before write, beside the versioned store"),
30
+ Shim.new(id: :approvals_array_write, added_in: "0.166.0", remove_after: "0.166.0",
31
+ files: ["lib/samagotchi/guardrails/approvals.rb"],
32
+ what: "Approvals#update writes a list (or no file) back as a list, since a 0.165 reader sets a " \
33
+ "versioned store aside; from 0.167 a write is versioned (and the corpus records that)")
34
+ ].freeze
35
+
9
36
  module_function
10
37
 
38
+ # The shims +version+ has passed the remove_after of.
39
+ # @return [Array<Shim>]
40
+ def overdue_shims(version: VERSION, shims: SHIMS)
41
+ current = Gem::Version.new(version)
42
+ shims.select { |shim| shim.remove_after && current > Gem::Version.new(shim.remove_after) }
43
+ end
44
+
11
45
  def verdict(worker_version:, version: VERSION, worker_protocol: nil, protocol: nil)
12
46
  return :refused if protocol && worker_protocol.to_i > protocol
13
47
 
@@ -130,6 +130,9 @@ module Samagotchi
130
130
  rescue ContextSources::Invalid => e
131
131
  error_line("#{command_name}: #{e.message}")
132
132
  CLI::Exit::FAILED
133
+ rescue MemoryPaths::ProjectIdConflict => e
134
+ error_line("#{command_name}: #{e.message}")
135
+ CLI::Exit::FAILED
133
136
  end
134
137
 
135
138
  private
@@ -149,8 +149,9 @@ module Samagotchi
149
149
  # installed (they run outside the guardrails gate, as a plugin loads:
150
150
  # checked the same way).
151
151
  # @return [String]
152
- # @raise [Invalid] the bundle is gone, a script changed, or this chi
153
- # doesn't meet the bundle's requires_chi
152
+ # @raise [Invalid] the bundle is gone, a script is gone, unrecorded or
153
+ # changed (Provenance#script_failure), or this chi doesn't meet the
154
+ # bundle's requires_chi
154
155
  def command_for(source)
155
156
  return source.cmd unless source.provider
156
157
 
@@ -165,10 +166,8 @@ module Samagotchi
165
166
  end
166
167
 
167
168
  record.scripts.each do |file, sha|
168
- path = File.join(provenance.scripts_dir, file)
169
- next if File.file?(path) && MemoryBundle::Provenance.sha_matches?(path, sha)
170
-
171
- raise Invalid, "bundle #{source.provider}'s scripts/#{file} differs from the installed one (reinstall the bundle)"
169
+ failure = provenance.script_failure(file, sha)
170
+ raise Invalid, failure if failure
172
171
  end
173
172
  source.cmd.gsub(BUNDLE_DIR) { Shellwords.escape(provenance.bundle_dir) }.gsub(RUBY) { Shellwords.escape(RbConfig.ruby) }
174
173
  end
@@ -636,10 +636,10 @@ module Samagotchi
636
636
  # @param project_root [String, nil] Session#project_root
637
637
  # @param project_id [String, nil] Session#project_id (a marked project's
638
638
  # id keys its folder: MemoryPaths.key_for)
639
- def project_location_for(project_root, project_id: nil, state_dir: nil)
639
+ def project_location_for(project_root, project_id: nil, state_dir: nil, env: ENV)
640
640
  return nil if project_root.to_s.empty?
641
641
 
642
- project_location(MemoryPaths.key_for(root: project_root, id: project_id), state_dir: state_dir)
642
+ project_location(MemoryPaths.key_for(root: project_root, id: project_id, env: env), state_dir: state_dir)
643
643
  end
644
644
 
645
645
  # A session's sources: its own, then the project's it doesn't shadow
@@ -1,6 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "fileutils"
3
4
  require "json"
5
+ require_relative "atomic_file"
4
6
  require_relative "session"
5
7
 
6
8
  module Samagotchi
@@ -8,16 +10,44 @@ module Samagotchi
8
10
  # folder while it runs: LOCK, held for the whole continue, and FILE, its
9
11
  # intent (the successor's id), written before the link is archived and
10
12
  # removed once the successor is saved or the continue is undone. A send
11
- # reads them (SessionInbox::Head) to tell a continue in flight from a link
12
- # nobody continues.
13
+ # (SessionInbox::Head) and a schedule tick (Schedules#continuing_reason)
14
+ # read them to tell a continue in flight from a link nobody continues.
13
15
  module ContinueIntent
14
16
  # One continue of a session at a time.
15
17
  LOCK = "continue.lock"
16
18
  # The intent: { successor_id:, previously_archived:, archived_ids: }.
17
19
  FILE = "continue.json"
18
20
 
21
+ # The intent as read: the successor's id (nil when it names no valid
22
+ # one), the ids archived before the continue, and the ones it archived
23
+ # (nil when the file has no list: written before the archive).
24
+ # CROSS-VERSION: another chi's repair reads this file
25
+ # (spec/compat/readers_spec.rb).
26
+ Intent = Data.define(:successor_id, :previously_archived, :archived_ids)
27
+
19
28
  module_function
20
29
 
30
+ # Write the intent at +path+ (the continue's one writer).
31
+ # @param archived_ids [Array<String>, nil] nil: not archived yet (not written)
32
+ def write(path, successor_id:, previously_archived:, archived_ids: nil)
33
+ data = { successor_id: successor_id, previously_archived: previously_archived, archived_ids: archived_ids }.compact
34
+ AtomicFile.write(path, "#{JSON.generate(data)}\n", perm: 0o600)
35
+ end
36
+
37
+ # The intent at +path+; a file that isn't a JSON object reads as one
38
+ # naming nothing.
39
+ # @return [Intent]
40
+ # @raise [JSON::ParserError, SystemCallError] it doesn't parse, or is gone
41
+ def read(path)
42
+ data = JSON.parse(File.read(path))
43
+ data = {} unless data.is_a?(Hash)
44
+ successor = data["successor_id"]
45
+ archived = data["archived_ids"].is_a?(Array) ? data["archived_ids"].select { |id| Session.valid_id?(id) } : nil
46
+ Intent.new(successor_id: Session.valid_id?(successor) ? successor : nil,
47
+ previously_archived: Array(data["previously_archived"]).select { |id| Session.valid_id?(id) },
48
+ archived_ids: archived)
49
+ end
50
+
21
51
  # The successor's id of a continue of +id+ in flight: its intent written
22
52
  # and its lock held. nil when there is none, or the intent is stale (no
23
53
  # continue holds the lock: a crash left it, and
@@ -30,13 +60,28 @@ module Samagotchi
30
60
  path = File.join(dir, FILE)
31
61
  return nil unless File.file?(path) && locked?(File.join(dir, LOCK))
32
62
 
33
- data = JSON.parse(File.read(path))
34
- successor = data["successor_id"] if data.is_a?(Hash)
35
- Session.valid_id?(successor) ? successor : nil
63
+ read(path).successor_id
36
64
  rescue JSON::ParserError, SystemCallError
37
65
  nil
38
66
  end
39
67
 
68
+ # The block under a shared hold of +id+'s continue lock, so no continue
69
+ # of it starts until the block returns (its exclusive lock waits); the
70
+ # block's argument is false when a continue holds the lock now (not
71
+ # waited for: nothing is held then). A followed send's check and the
72
+ # resume that would un-archive the link run inside it
73
+ # (SessionManager.deliver_turn's follow:).
74
+ # @yieldparam held [Boolean]
75
+ def hold(id, state_dir:)
76
+ return yield(false) unless Session.valid_id?(id)
77
+
78
+ dir = Session.session_dir(id, state_dir: state_dir)
79
+ FileUtils.mkdir_p(dir)
80
+ File.open(File.join(dir, LOCK), File::RDWR | File::CREAT, 0o600) do |lock|
81
+ yield(lock.flock(File::LOCK_SH | File::LOCK_NB) ? true : false)
82
+ end
83
+ end
84
+
40
85
  # Whether a continue holds the lock at +path+: a shared try that fails.
41
86
  # The try is let go at once (the file is closed).
42
87
  def locked?(path)
@@ -3,8 +3,8 @@
3
3
  module Samagotchi
4
4
  # The sets of event types more than one place reads (the Worker, the
5
5
  # Bridge's observers, the TUI, the web), kept here once. The web's own
6
- # copies (app.js's stream handlers, turn_events.js's snapshotEvents) are
7
- # checked against these by spec/events_drift_spec.rb.
6
+ # copies (app.js's stream handlers) are checked against these by
7
+ # spec/events_drift_spec.rb.
8
8
  module Events
9
9
  # A turn is over: it completed, was canceled, or failed.
10
10
  TURN_END = %i[turn_completed turn_canceled turn_failed].freeze
@@ -17,8 +17,8 @@ module Samagotchi
17
17
  # turn's drawing: a join takes its cards from CardStore).
18
18
  PART_KINDS = %w[generation thinking text tool input steer reminder notice card].freeze
19
19
  # Types no Engine emits that a UI handles: the Bridge's stream frames
20
- # and the web's one synthetic replay event (a prompt merged into the
21
- # turn, turn_events.js snapshotEvents).
20
+ # and the one synthetic replay event (a prompt merged into the turn,
21
+ # TurnAccumulator.replay_events).
22
22
  STREAM_FRAMES = %i[snapshot reset stream_closed].freeze
23
23
  SYNTHETIC = %i[merged_input].freeze
24
24
 
@@ -35,7 +35,8 @@ module Samagotchi
35
35
  # The hooks: config.yml's (Hooks::Loader; an empty Registry without a
36
36
  # hooks config). An installed record that still has class-file hooks (a
37
37
  # 0.157 install) adds a not-required failure each, which the Engine
38
- # announces at the first turn: they don't load (#tell_retired_hooks).
38
+ # announces at the first turn: they don't load (#tell_retired_hooks;
39
+ # compat shim retired_class_file_hooks: Compat::SHIMS).
39
40
  # @return [Hooks::Registry]
40
41
  def hooks
41
42
  tell_retired_hooks
@@ -6,6 +6,7 @@ require "fileutils"
6
6
  require "time"
7
7
  require_relative "../atomic_file"
8
8
  require_relative "../log"
9
+ require_relative "../state_format"
9
10
  require_relative "approval"
10
11
 
11
12
  module Samagotchi
@@ -26,8 +27,17 @@ module Samagotchi
26
27
  # "once" is never stored. A file that doesn't parse is moved aside to
27
28
  # approvals.json.corrupt-<UTC time>[-N], with a warning, and the store
28
29
  # starts empty: it only means more asks, and nothing is overwritten.
30
+ #
31
+ # The file is either a list of entries (0.165 and before) or a
32
+ # versioned store, {"version", "approvals": [...]} (FORMAT). Both are
33
+ # read; a write keeps the shape it read, and a store with no file is
34
+ # written as a list: a 0.165 reader sets an object aside, so the list
35
+ # stays the written shape until 0.167 (compat shims approvals_array_read
36
+ # and approvals_array_write).
29
37
  class Approvals
30
38
  FILE = "approvals.json"
39
+ COLLECTION = "approvals"
40
+ FORMAT = StateFormat.new(version: 1, members: [StateFormat.required(:scope), StateFormat.extra(:extra, in_version: 1)])
31
41
  STORED_SCOPES = %w[session repo rule].freeze
32
42
  # Rules a stored answer allows only for its session: their asks offer
33
43
  # once/session, and a repo entry for the same call (from another
@@ -50,13 +60,13 @@ module Samagotchi
50
60
 
51
61
  # @return [Array<Hash>] the entries (string keys), oldest first
52
62
  def entries
53
- read
63
+ read.first
54
64
  end
55
65
 
56
66
  # @param verdict [Verdict] an ask with its targets and context
57
67
  # @return [Hash, nil] the first entry that allows it
58
68
  def match(verdict)
59
- self.class.find_in(read, verdict)
69
+ self.class.find_in(read.first, verdict)
60
70
  end
61
71
 
62
72
  # Store the verdict's allowed scope (not "once").
@@ -158,8 +168,10 @@ module Samagotchi
158
168
  private
159
169
 
160
170
  # @param locked [Boolean] the caller holds the store's lock
171
+ # @return [Array(Array<Hash>, StateFormat::Document)] the entries and,
172
+ # for a versioned store, its document (nil for a list or no file)
161
173
  def read(locked: false)
162
- return [] unless File.exist?(@path)
174
+ return [[], nil] unless File.exist?(@path)
163
175
 
164
176
  parse(File.read(@path))
165
177
  rescue JSON::ParserError, SystemCallError => e
@@ -175,14 +187,24 @@ module Samagotchi
175
187
  where = aside ? "moved it to #{aside}" : "left it in place"
176
188
  @warn.call("[samagotchi:guardrails] #{@path} is unreadable (#{e.message}); #{where}, no stored approvals apply")
177
189
  end
178
- []
190
+ [[], nil]
179
191
  end
180
192
 
193
+ # @return [Array(Array<Hash>, StateFormat::Document)] as #read's
181
194
  def parse(text)
182
195
  data = JSON.parse(text)
183
- raise JSON::ParserError, "not a list" unless data.is_a?(Array)
184
-
185
- data.select { |e| e.is_a?(Hash) }
196
+ case data
197
+ when Hash
198
+ raise JSON::ParserError, "#{COLLECTION} is not a list" unless data.fetch(COLLECTION, []).is_a?(Array)
199
+
200
+ document = FORMAT.read(data, collection: COLLECTION)
201
+ # An entry it can't read (no scope) is kept as it is: it matches
202
+ # nothing, and a write keeps it for the chi that wrote it.
203
+ [document.entries.map(&:raw).select { |e| e.is_a?(Hash) }, document]
204
+ # compat shim approvals_array_read: the list 0.165 and before write.
205
+ when Array then [data.select { |e| e.is_a?(Hash) }, nil]
206
+ else raise JSON::ParserError, "not a list or a versioned store"
207
+ end
186
208
  end
187
209
 
188
210
  # Under the lock: rename the file aside if it is still unreadable.
@@ -215,11 +237,16 @@ module Samagotchi
215
237
  end
216
238
  end
217
239
 
240
+ # Writes the shape it read: a versioned store keeps its version and
241
+ # the keys this chi doesn't know.
218
242
  def update
219
243
  with_lock do
220
- list = read(locked: true)
244
+ list, document = read(locked: true)
221
245
  yield list
222
- AtomicFile.write(@path, JSON.pretty_generate(list))
246
+ # compat shim approvals_array_write: a list (or no file) is written
247
+ # as a list, since a 0.165 reader sets an object aside.
248
+ body = document ? FORMAT.write(document.with(entries: list), collection: COLLECTION, updated_at: nil) : list
249
+ AtomicFile.write(@path, JSON.pretty_generate(body))
223
250
  end
224
251
  end
225
252
 
@@ -21,16 +21,14 @@ module Samagotchi
21
21
  # the call writes (writes: true), the same declaration
22
22
  # ProtectedPaths reads — a call is judged by what its targets say it
23
23
  # acts on, not by its tool's name;
24
- # execute, task_create: mutating git runs in a dir outside root
24
+ # a shell call (execute, task_create, or a plugin tool whose targets:
25
+ # carry a command): mutating git runs in a dir outside root
25
26
  # (ShellGitDirs), or a command that isn't read-only starts outside
26
27
  # root (its cwd:, else Dir.pwd) or names a path in the repository's
27
28
  # other checkouts (the main one and sibling worktrees) or its
28
29
  # common git dir; or it runs git that changes what all checkouts
29
30
  # share, from anywhere (SharedGit: config, update-ref, worktree add,
30
- # stash clear, tags, another branch's delete). A plugin tool's
31
- # declared command: is checked for what chi can read for sure only:
32
- # SharedGit, and whether the call's cwd: is outside root (its text
33
- # may not be shell; Targets#rule_command).
31
+ # stash clear, tags, another branch's delete).
34
32
  # Paths elsewhere in a command (/usr/bin, ~/.gem) don't count, and
35
33
  # read-only commands never ask, nor do ones that only write into a tmp
36
34
  # dir (> / >>, cp's destination, tee; Targets#read_only_but_tmp_writes?). Paths resolve under chi's env and the
@@ -41,8 +39,6 @@ module Samagotchi
41
39
  RULE = "child-boundary"
42
40
  SOURCE = "core"
43
41
  SCOPES = %w[once session].freeze
44
- SHELL_TOOLS = %w[execute task_create].freeze
45
-
46
42
  # @param root [#call] → String, nil: the child's folder (nil: no check)
47
43
  # @param worktrees [#call] → Array<String>: every checkout of root's
48
44
  # repository (GitInfo#worktrees); root's own is left out here
@@ -74,15 +70,15 @@ module Samagotchi
74
70
  def crosses?(targets, root)
75
71
  case targets.tool
76
72
  when "write", "edit" then paths_cross?(targets, root)
77
- when *SHELL_TOOLS then shell_crosses?(targets, root)
78
73
  else
74
+ return true if !Targets::CORE_TOOLS.include?(targets.tool) && targets.writes? && paths_cross?(targets, root)
75
+ return shell_crosses?(targets, root) if targets.shell?
76
+
79
77
  # chi's other own tools (read, memory_write, …) are unchanged:
80
78
  # memory_write carries writes: for ProtectedPaths, but its paths
81
79
  # are memory files (Outside exempts them) and its `..` entry names
82
80
  # asked for nothing here before.
83
- return false if Targets::CORE_TOOLS.include?(targets.tool)
84
-
85
- plugin_crosses?(targets, root)
81
+ false
86
82
  end
87
83
  end
88
84
 
@@ -90,22 +86,6 @@ module Samagotchi
90
86
  targets.paths.any? { |path| Outside.outside?(path, root: root) }
91
87
  end
92
88
 
93
- # A plugin tool, by what its targets: say it acts on (Targets#writes?,
94
- # #command, #cwd), not by its name: paths its targets say it writes
95
- # like a write's, and a declared command like a shell's — but for the
96
- # command only what chi can read for sure: git that changes what every
97
- # checkout shares (SharedGit), and where the call runs (its cwd:). A
98
- # plugin's command text may not be shell (Targets#rule_command), so
99
- # the shell half's git-dir, cd and redirect reads are left out; a
100
- # plugin that wants more can bring a rule of its own.
101
- def plugin_crosses?(targets, root)
102
- return true if targets.writes? && paths_cross?(targets, root)
103
- return :shared if targets.command && SharedGit.changes?(targets.command, own_branch: @branch.call)
104
- return true if targets.command && targets.cwd && Outside.outside?(targets.cwd, root: root)
105
-
106
- false
107
- end
108
-
109
89
  def shell_crosses?(targets, root)
110
90
  return true if targets.git_dirs.any? { |dir| dir.is_a?(String) && Outside.outside?(dir, root: root) }
111
91
  return :shared if SharedGit.changes?(targets.command, own_branch: @branch.call)
@@ -9,10 +9,10 @@ module Samagotchi
9
9
  module Guardrails
10
10
  # Declarative rules from config.yml's `guardrails:` section (and, later,
11
11
  # installed bundles). All the fields a rule gives must match:
12
- # tool: a tool name, a list, or "shell" (execute + task_create);
13
- # a name may be a glob ("mcp_*", "mcp_{git,gh}_*"); it
14
- # matches the call's name or the tool a plugin tool's call
15
- # acts as (Targets#acts_as: an MCP tool behind call_tool)
12
+ # tool: a tool name, a list, or "shell" (a shell call, including a
13
+ # plugin tool whose targets: declare a command); a name may be
14
+ # a glob ("mcp_*", "mcp_{git,gh}_*"); it matches the call's
15
+ # name or the tool a plugin tool's call acts as (Targets#acts_as)
16
16
  # command: a Ruby regex on a shell tool's command, the body of a
17
17
  # heredoc its command only reads as data left out
18
18
  # (Targets#rule_command, ShellLex.code_text)
@@ -60,12 +60,13 @@ module Samagotchi
60
60
  MODES = %w[auto strict].freeze
61
61
  GLOB_FLAGS = File::FNM_PATHNAME | File::FNM_DOTMATCH | File::FNM_EXTGLOB
62
62
 
63
- Rule = Struct.new(:id, :tools, :command, :path, :git, :touches, :rm, :memory, :models, :modes, :skip_read_only, :verdict, :reason,
63
+ Rule = Struct.new(:id, :tools, :shell, :command, :path, :git, :touches, :rm, :memory, :models, :modes, :skip_read_only, :verdict, :reason,
64
64
  :scopes, :source, keyword_init: true) do
65
65
  def matches?(targets)
66
66
  return false unless targets
67
67
  return false unless for_model?(targets.model_name, targets.model_key, -> { targets.small_model? })
68
- return false if tools && !tool_matches?(targets.tool) && !(targets.acts_as && tool_matches?(targets.acts_as))
68
+ return false if tools && !tool_matches?(targets.tool) && !(targets.acts_as && tool_matches?(targets.acts_as)) &&
69
+ !(shell && targets.shell?)
69
70
  return false if command && !(targets.rule_command && command.match?(targets.rule_command))
70
71
  return false if path && !path_matches?(targets)
71
72
  return false if git && !targets.git_outside_repo?
@@ -158,7 +159,8 @@ module Samagotchi
158
159
  raise ParseError, "#{label}: give at least one of #{MATCH_KEYS.join(", ")}"
159
160
  end
160
161
 
161
- Rule.new(id: id, tools: tools_of(raw["tool"], label), command: regex_of(raw["command"], label),
162
+ tools, shell = tools_of(raw["tool"], label)
163
+ Rule.new(id: id, tools: tools, shell: shell, command: regex_of(raw["command"], label),
162
164
  path: path_of(raw["path"], label), git: git_of(raw["git"], label),
163
165
  touches: touches_of(raw["touches"], label), rm: rm_of(raw["rm"], label), memory: memory_of(raw["memory"], label),
164
166
  models: models_of(raw["models"], label),
@@ -168,12 +170,12 @@ module Samagotchi
168
170
  end
169
171
 
170
172
  def self.tools_of(value, label)
171
- return nil if value.nil?
173
+ return [nil, false] if value.nil?
172
174
 
173
175
  names = Array(value).map(&:to_s)
174
176
  raise ParseError, "#{label}: tool must be a name or a list of names" if names.empty? || names.any?(&:empty?)
175
177
 
176
- names.flat_map { |n| n == "shell" ? Targets::SHELL_TOOLS : [n] }.uniq
178
+ [names.flat_map { |n| n == "shell" ? Targets::SHELL_TOOLS : [n] }.uniq, names.include?("shell")]
177
179
  end
178
180
 
179
181
  # Whether a rule's tool name is a glob.
@@ -357,7 +357,7 @@ module Samagotchi
357
357
  @repo_root = repo_root
358
358
  end
359
359
 
360
- def shell? = SHELL_TOOLS.include?(@tool)
360
+ def shell? = SHELL_TOOLS.include?(@tool) || !@command.nil?
361
361
 
362
362
  # The homes and environments a shell call's words may resolve
363
363
  # against, as [home, env] pairs: chi's own, and when the call's env:
@@ -381,9 +381,8 @@ module Samagotchi
381
381
  @redefines_shell = self.class.redefines_shell?(@env)
382
382
  end
383
383
 
384
- # What a rule's command: reads: the shell command with the body of each
385
- # heredoc its command only reads as data left out (ShellLex.code_text);
386
- # a plugin tool's own command as given (its text may not be shell).
384
+ # What a rule's command: reads: a shell command with the body of each
385
+ # heredoc its command only reads as data left out (ShellLex.code_text).
387
386
  # Approvals, the approval question and hooks keep #command.
388
387
  def rule_command
389
388
  return @rule_command if defined?(@rule_command)
@@ -46,6 +46,9 @@ module Samagotchi
46
46
  # The deepest legal block nests 6 (root, steps, a step, cases, a case, a
47
47
  # folded option); past this it is refused before the stack can overflow.
48
48
  MAX_DEPTH = 8
49
+ # What a row id may not start with: a shell line's ! and a session
50
+ # command's / (CommandIntake), with the spaces between them.
51
+ COMMAND_LEAD = %r{\A[!/\s]+}
49
52
  # How much of a bad type value an error repeats.
50
53
  MAX_ECHO = 40
51
54
 
@@ -212,7 +215,7 @@ module Samagotchi
212
215
  where = "row #{index + 1}"
213
216
  raise Refused, "#{where} isn't a mapping" unless row.is_a?(Hash)
214
217
 
215
- id = text(row["id"], "#{where}'s id", required: true)
218
+ id = row_id(text(row["id"], "#{where}'s id", required: true), where)
216
219
  where = "row #{id}"
217
220
  options = list(row["options"], "#{where}'s options")
218
221
  raise Refused, "#{where} has #{options.size} options (#{OPTIONS.min}-#{OPTIONS.max})" unless OPTIONS.cover?(options.size)
@@ -230,6 +233,18 @@ module Samagotchi
230
233
  "recommended" => recommended, "why" => text(row["why"], "#{where}'s why", free: true))
231
234
  end
232
235
 
236
+ # A row's id leads the page's filled reply ("<id>: <option>"), so it never
237
+ # starts with ! or / (a shell line, a session command): those are dropped,
238
+ # a mend like a fold, and an id that is nothing else is refused.
239
+ def row_id(id, where)
240
+ safe = id.sub(COMMAND_LEAD, "")
241
+ return id if safe == id
242
+ raise Refused, "#{where}'s id is only ! and /" if safe.empty?
243
+
244
+ @folded = true
245
+ safe
246
+ end
247
+
233
248
  def walk(tree)
234
249
  title = text(tree["title"], "the title", required: true, free: true)
235
250
  actors = list(tree["actors"], "actors").map { |actor| text(actor, "an actor", required: true) }
@@ -66,6 +66,21 @@ module Samagotchi
66
66
  ]
67
67
  )
68
68
 
69
+ # pending.json's format (#write_pending), in its pending_format key:
70
+ # its version key is the bundle's. A journal with no pending_format is
71
+ # one from before it (the same members); a newer chi's keeps its
72
+ # format and the keys this one doesn't know through a write.
73
+ PENDING_FORMAT_VERSION = 1
74
+ PENDING_FORMAT = StateFormat.new(
75
+ version: PENDING_FORMAT_VERSION,
76
+ members: [
77
+ StateFormat.required(:scope),
78
+ StateFormat.required(:target_dir),
79
+ StateFormat.added(:version, in_version: 1, default: nil),
80
+ StateFormat.added(:files, in_version: 1, default: {})
81
+ ]
82
+ )
83
+
69
84
  def initialize(name:)
70
85
  @name = name
71
86
  @bundle_dir = File.join(self.class.bundles_dir, name)
@@ -98,6 +113,19 @@ module Samagotchi
98
113
  File.join(@bundle_dir, "scripts")
99
114
  end
100
115
 
116
+ # Why the installed scripts/+file+ isn't as installed, nil when it is:
117
+ # the record has no sha for it (+recorded+), it is gone, or it changed.
118
+ # The one check a provider's command and a block renderer's load make
119
+ # before chi runs or serves the file; a --dev install's links pass.
120
+ def script_failure(file, recorded)
121
+ path = File.join(scripts_dir, file)
122
+ return "bundle #{@name}'s scripts/#{file} isn't among its installed scripts (reinstall the bundle)" if self.class.recorded_sha(recorded).empty?
123
+ return "bundle #{@name}'s scripts/#{file} is missing (reinstall the bundle)" unless File.file?(path)
124
+ return nil if self.class.sha_matches?(path, recorded)
125
+
126
+ "bundle #{@name}'s scripts/#{file} differs from the installed one (reinstall the bundle)"
127
+ end
128
+
101
129
  # The intent journal of a run that has not written its record yet
102
130
  # (#write_pending): its scope and target dir, plus the files and sha256s
103
131
  # of the texts a run meant to put there. #write removes it.
@@ -112,9 +140,14 @@ module Samagotchi
112
140
  def write_pending(version:, scope:, target_dir:, files:)
113
141
  shas = pending_files(target_dir: target_dir)
114
142
  files.each { |key, sha| shas[key] = (shas.fetch(key, []) + [sha]).uniq }
143
+ target = File.expand_path(target_dir)
144
+ earlier = pending_metadata
145
+ kept = earlier && earlier["target_dir"] == target ? earlier.except("version", "scope", "target_dir", "files") : {}
146
+ format = [kept.delete("pending_format").to_i, PENDING_FORMAT_VERSION].max
115
147
  FileUtils.mkdir_p(@bundle_dir)
116
148
  AtomicFile.write(pending_path, JSON.pretty_generate(
117
- "version" => version.to_s, "scope" => scope.to_s, "target_dir" => File.expand_path(target_dir), "files" => shas
149
+ kept.merge("pending_format" => format, "version" => version.to_s, "scope" => scope.to_s, "target_dir" => target,
150
+ "files" => shas)
118
151
  ))
119
152
  end
120
153
 
@@ -571,12 +604,21 @@ module Samagotchi
571
604
  files.is_a?(Hash) ? files.to_h { |key, shas| [key, Array(shas).grep(String)] } : {}
572
605
  end
573
606
 
607
+ # The journal as PENDING_FORMAT reads it, string keys, its format under
608
+ # pending_format; nil when there is none or it doesn't read.
574
609
  def pending_metadata
575
610
  data = JSON.parse(File.read(pending_path))
576
- return unless data.is_a?(Hash) && data["scope"].is_a?(String) && data["target_dir"].is_a?(String)
611
+ return unless data.is_a?(Hash)
612
+
613
+ format = data["pending_format"]
614
+ format = nil unless format.is_a?(Integer) && format >= 0
615
+ document = PENDING_FORMAT.read({ "version" => format, "journals" => [data] }, collection: "journals")
616
+ journal = document.entries.first
617
+ return unless journal.readable?
618
+ return unless journal.attributes[:scope].is_a?(String) && journal.attributes[:target_dir].is_a?(String)
577
619
 
578
- data
579
- rescue JSON::ParserError, EncodingError, SystemCallError
620
+ journal.to_h.merge("pending_format" => document.version)
621
+ rescue JSON::ParserError, EncodingError, SystemCallError, StateFormat::InvalidDocument
580
622
  nil
581
623
  end
582
624
  private :pending_files, :pending_metadata