samagotchi 0.194.0 → 0.196.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 (152) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +80 -1
  3. data/docs/architecture.md +2 -1
  4. data/docs/bundle-authoring.md +23 -23
  5. data/docs/bundles.md +201 -7
  6. data/docs/cli.md +5 -1
  7. data/docs/configuration.md +25 -4
  8. data/docs/context.md +13 -3
  9. data/docs/guardrails.md +6 -4
  10. data/docs/hooks.md +3 -1
  11. data/docs/internals/attached-context.md +2 -0
  12. data/docs/internals/block-renderers.md +4 -1
  13. data/docs/internals/bridge.md +4 -0
  14. data/docs/internals/engine.md +15 -2
  15. data/docs/internals/knowledge.md +215 -0
  16. data/docs/internals/pages.md +17 -9
  17. data/docs/internals/panes.md +51 -13
  18. data/docs/internals/participants.md +15 -3
  19. data/docs/internals/peers.md +14 -9
  20. data/docs/internals/session-lifecycle.md +26 -12
  21. data/docs/internals/web-frontend.md +64 -27
  22. data/docs/memory.md +4 -2
  23. data/docs/pages.md +72 -1
  24. data/docs/peers.md +25 -14
  25. data/docs/plugins.md +132 -6
  26. data/docs/releasing.md +1 -1
  27. data/docs/scheduling.md +4 -0
  28. data/docs/sessions.md +9 -2
  29. data/docs/system-one.md +3 -1
  30. data/docs/testing.md +3 -1
  31. data/lib/samagotchi/bundle_manifest.rb +30 -5
  32. data/lib/samagotchi/bundles/claude-peer/manifest.yml +8 -5
  33. data/lib/samagotchi/bundles/claude-peer/plugin.rb +2 -2
  34. data/lib/samagotchi/bundles/codex-peer/manifest.yml +8 -5
  35. data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
  36. data/lib/samagotchi/bundles/coordinator/manifest.yml +7 -4
  37. data/lib/samagotchi/bundles/coordinator/plugin.rb +15 -5
  38. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +10 -0
  39. data/lib/samagotchi/bundles/core/manifest.yml +2 -2
  40. data/lib/samagotchi/bundles/cost-cap/manifest.yml +4 -4
  41. data/lib/samagotchi/bundles/cost-cap/plugin.rb +54 -3
  42. data/lib/samagotchi/bundles/dev/manifest.yml +3 -2
  43. data/lib/samagotchi/bundles/github-pr/manifest.yml +4 -2
  44. data/lib/samagotchi/bundles/knowledge/adapters.rb +205 -0
  45. data/lib/samagotchi/bundles/knowledge/catalog.rb +151 -0
  46. data/lib/samagotchi/bundles/knowledge/chi_adapters.rb +178 -0
  47. data/lib/samagotchi/bundles/knowledge/chunker.rb +55 -0
  48. data/lib/samagotchi/bundles/knowledge/github.rb +246 -0
  49. data/lib/samagotchi/bundles/knowledge/manifest.yml +27 -0
  50. data/lib/samagotchi/bundles/knowledge/plugin.rb +807 -0
  51. data/lib/samagotchi/bundles/knowledge/query.rb +30 -0
  52. data/lib/samagotchi/bundles/knowledge/query_log.rb +55 -0
  53. data/lib/samagotchi/bundles/knowledge/refresh.rb +133 -0
  54. data/lib/samagotchi/bundles/knowledge/store.rb +264 -0
  55. data/lib/samagotchi/bundles/reflect/manifest.yml +17 -0
  56. data/lib/samagotchi/bundles/reflect/scripts/reflect.rb +439 -0
  57. data/lib/samagotchi/bundles/reflect/skill_reflect.md +100 -0
  58. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  59. data/lib/samagotchi/context_change.rb +44 -0
  60. data/lib/samagotchi/context_note.rb +1 -1
  61. data/lib/samagotchi/context_providers.rb +14 -0
  62. data/lib/samagotchi/context_sources.rb +3 -25
  63. data/lib/samagotchi/engine/plugins.rb +21 -0
  64. data/lib/samagotchi/events.rb +1 -0
  65. data/lib/samagotchi/guardrails/pair_boundary.rb +12 -4
  66. data/lib/samagotchi/guardrails/review_paths.rb +13 -3
  67. data/lib/samagotchi/guardrails/targets.rb +24 -2
  68. data/lib/samagotchi/guardrails_command.rb +3 -9
  69. data/lib/samagotchi/hook_label.rb +19 -0
  70. data/lib/samagotchi/hook_routes.rb +3 -2
  71. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  72. data/lib/samagotchi/memory_bundle/builder.rb +2 -1
  73. data/lib/samagotchi/memory_bundle/installed_copy.rb +2 -1
  74. data/lib/samagotchi/page_command.rb +90 -6
  75. data/lib/samagotchi/pages/launch.rb +16 -8
  76. data/lib/samagotchi/pages/runner.rb +7 -2
  77. data/lib/samagotchi/pages/runtime.rb +62 -2
  78. data/lib/samagotchi/pages.rb +4 -0
  79. data/lib/samagotchi/panes/kitty.rb +20 -5
  80. data/lib/samagotchi/panes.rb +81 -12
  81. data/lib/samagotchi/participants.rb +17 -6
  82. data/lib/samagotchi/peer_exchanges.rb +1 -2
  83. data/lib/samagotchi/peer_note.rb +38 -5
  84. data/lib/samagotchi/peer_presence.rb +20 -7
  85. data/lib/samagotchi/plugin/api.rb +11 -1
  86. data/lib/samagotchi/plugin/attached_context.rb +46 -1
  87. data/lib/samagotchi/plugin/chips.rb +125 -0
  88. data/lib/samagotchi/plugin/context.rb +43 -8
  89. data/lib/samagotchi/plugin/panes.rb +52 -9
  90. data/lib/samagotchi/plugin/peer_pairing.rb +2 -2
  91. data/lib/samagotchi/plugin/peer_start.rb +61 -36
  92. data/lib/samagotchi/plugin/peers.rb +6 -3
  93. data/lib/samagotchi/plugin/project.rb +63 -0
  94. data/lib/samagotchi/plugin/sessions.rb +36 -1
  95. data/lib/samagotchi/plugin/tool_spec.rb +28 -9
  96. data/lib/samagotchi/schedules.rb +8 -2
  97. data/lib/samagotchi/session.rb +22 -9
  98. data/lib/samagotchi/session_access/local.rb +34 -33
  99. data/lib/samagotchi/session_chain/sharing.rb +79 -0
  100. data/lib/samagotchi/session_chain/successor.rb +4 -2
  101. data/lib/samagotchi/session_chips.rb +133 -0
  102. data/lib/samagotchi/session_inbox_delivery.rb +11 -11
  103. data/lib/samagotchi/session_manager/emptiness.rb +4 -1
  104. data/lib/samagotchi/session_observer.rb +1 -1
  105. data/lib/samagotchi/session_stats.rb +437 -0
  106. data/lib/samagotchi/session_stores.rb +3 -0
  107. data/lib/samagotchi/session_window.rb +30 -0
  108. data/lib/samagotchi/speaker.rb +228 -0
  109. data/lib/samagotchi/steer.rb +36 -132
  110. data/lib/samagotchi/system_one/approval_choice.rb +22 -0
  111. data/lib/samagotchi/system_one/approval_label.rb +4 -6
  112. data/lib/samagotchi/system_prompt.rb +3 -1
  113. data/lib/samagotchi/terminal_ui/attach_launcher.rb +30 -0
  114. data/lib/samagotchi/testing/boundary.rb +17 -4
  115. data/lib/samagotchi/testing/bundle.rb +5 -0
  116. data/lib/samagotchi/testing/host.rb +1 -0
  117. data/lib/samagotchi/testing/recorder.rb +10 -0
  118. data/lib/samagotchi/testing/sessions.rb +11 -3
  119. data/lib/samagotchi/toolkit.rb +11 -4
  120. data/lib/samagotchi/toolkit_report_command.rb +14 -18
  121. data/lib/samagotchi/toolkit_suggest.rb +9 -2
  122. data/lib/samagotchi/tools/registry.rb +48 -18
  123. data/lib/samagotchi/tools/tool_index.rb +6 -2
  124. data/lib/samagotchi/turn_excerpts.rb +302 -0
  125. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +9 -0
  126. data/lib/samagotchi/version.rb +1 -1
  127. data/lib/samagotchi/web/app.rb +21 -10
  128. data/lib/samagotchi/web/participant_view.rb +1 -1
  129. data/lib/samagotchi/web/peer_routes.rb +5 -2
  130. data/lib/samagotchi/web/plugin_chip_rows.rb +39 -0
  131. data/lib/samagotchi/web/public/agent_rows.js +1 -0
  132. data/lib/samagotchi/web/public/app.js +17 -25
  133. data/lib/samagotchi/web/public/chains.js +0 -26
  134. data/lib/samagotchi/web/public/command_list.js +2 -3
  135. data/lib/samagotchi/web/public/composer.js +2 -3
  136. data/lib/samagotchi/web/public/composer_mount.js +3 -6
  137. data/lib/samagotchi/web/public/context_chips.js +240 -93
  138. data/lib/samagotchi/web/public/context_groups.js +84 -0
  139. data/lib/samagotchi/web/public/draft_follow.js +33 -0
  140. data/lib/samagotchi/web/public/drafts.js +26 -22
  141. data/lib/samagotchi/web/public/index.html +32 -0
  142. data/lib/samagotchi/web/public/peer_chip_kind.js +49 -0
  143. data/lib/samagotchi/web/public/peer_note.js +2 -2
  144. data/lib/samagotchi/web/public/peer_row.js +10 -5
  145. data/lib/samagotchi/web/public/peer_wait.js +4 -2
  146. data/lib/samagotchi/web/public/plugin_chip.js +55 -0
  147. data/lib/samagotchi/web/public/plugin_chip_kind.js +48 -0
  148. data/lib/samagotchi/web/public/send_turn.js +8 -21
  149. data/lib/samagotchi/web/public/session_actions.js +10 -23
  150. data/lib/samagotchi/web/public/session_view.js +7 -3
  151. data/lib/samagotchi/web/public/stream_handlers.js +2 -0
  152. metadata +33 -1
@@ -53,9 +53,9 @@ module Samagotchi
53
53
  class Invalid < ArgumentError; end
54
54
 
55
55
  # A change to a session's own sources refused while a transition holds
56
- # the session's lock (#changing): a continue copies them to its new
57
- # link, so one written then would stay behind. Its words name the
58
- # continue's new link, or say busy; try again in a moment.
56
+ # the session's lock (ContextChange.under): a continue copies them to
57
+ # its new link, so one written then would stay behind. Its words name
58
+ # who continues the session, or say who holds it.
59
59
  class Held < Invalid; end
60
60
 
61
61
  # A source's definition. +cmd+ nil: pushed only (chi context push).
@@ -603,28 +603,6 @@ module Samagotchi
603
603
  File.join(File.dirname(state_dir || SessionPaths.default_state_dir), DIR)
604
604
  end
605
605
 
606
- # The block (a change to session +session_id+'s own sources: an add, a
607
- # remove) under a shared hold of the session's transition lock
608
- # (SessionTransition.shared), so a continue (ContextSources.move) can't
609
- # copy them in between. A session whose file is gone takes no hold (its
610
- # folder is not made again).
611
- # @param state_dir [String] the sessions dir
612
- # @raise [Held] a transition holds it now (nothing written)
613
- def changing(session_id, state_dir:)
614
- return yield unless Session.exist?(session_id, state_dir: state_dir)
615
-
616
- require_relative "session_transition"
617
- require_relative "session_chain/successor"
618
- SessionTransition.shared(session_id, state_dir: state_dir) do |free|
619
- next yield if free
620
-
621
- successor = SessionChain::Successor.in_flight(session_id, state_dir: state_dir)
622
- raise Held, SessionTransition::Busy.held(session_id, state_dir: state_dir).message unless successor
623
-
624
- raise Held, "#{SessionChain::Continued.for(session_id, successor).message}; try again in a moment"
625
- end
626
- end
627
-
628
606
  def session_location(session_id, state_dir: nil)
629
607
  Location.new(scope: "session", dir: File.join(root(state_dir: state_dir), "sessions", SessionPaths.check_id!(session_id)),
630
608
  key: session_id)
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "time"
3
4
  require_relative "../answer_display"
4
5
  require_relative "../bundle_settings_check"
5
6
  require_relative "../cache_confirm"
@@ -7,6 +8,7 @@ require_relative "../client_id"
7
8
  require_relative "../log"
8
9
  require_relative "../plugin/context"
9
10
  require_relative "../plugin/loader"
11
+ require_relative "../session_chips"
10
12
  require_relative "../session_setup"
11
13
 
12
14
  module Samagotchi
@@ -176,6 +178,7 @@ module Samagotchi
176
178
  end,
177
179
  state_dir: -> { session_state_dir },
178
180
  secrets_store: ->(bundle) { Plugin::Secrets::FileStore.for_bundle(bundle) },
181
+ chips: -> { plugin_chips_store },
179
182
  sign_in: ->(bundle, **options, &build) { start_sign_in(bundle: bundle, build: build, **options) },
180
183
  scratch: -> { @scratch },
181
184
  setup: -> { SessionSetup.of(@session, forked: true) },
@@ -195,6 +198,24 @@ module Samagotchi
195
198
  )
196
199
  end
197
200
 
201
+ # The session's chip store ctx.chips writes through (SessionChips),
202
+ # nil with no session; a change announces :chips_updated.
203
+ def plugin_chips_store
204
+ id = @session&.id or return nil
205
+
206
+ SessionChips.new(id, state_dir: session_state_dir, on_change: -> { announce_chips(id) })
207
+ end
208
+ private :plugin_chips_store
209
+
210
+ # :chips_updated (no chips in it: an open tab reads GET …/context
211
+ # again), after a bundle's chip change was written. Under the event
212
+ # lock; the write itself is outside it.
213
+ def announce_chips(session_id)
214
+ synchronize_events { announce(type: :chips_updated, session_id: session_id, at: Time.now.utc.iso8601(3)) }
215
+ rescue StandardError => e
216
+ Log.warn(:plugins, "chips_announce_failed", error: e.class.name, msg: e.message)
217
+ end
218
+
198
219
  # The controller a plugin's ctx.http call without cancel: stops with
199
220
  # (docs/plugins.md): an init task's own, else the running turn's for the
200
221
  # turn's own work until the turn has ended (TurnState#own_controller); nil
@@ -36,6 +36,7 @@ module Samagotchi
36
36
  before_tool_call: :internal,
37
37
  before_turn: :internal,
38
38
  card: :row,
39
+ chips_updated: :state, # A bundle's chips changed (ctx.chips): an open tab reads GET …/context again.
39
40
  command_queued: :state,
40
41
  command_ran: :state,
41
42
  context_added: :row, # Reloaded from the session messages, not a turn fold or card store.
@@ -42,7 +42,11 @@ module Samagotchi
42
42
  # list_schedules, context_read); and memory_write: a memory reaches
43
43
  # the owner's later sessions;
44
44
  # - ask_user_question: there is no one on the participant's side to
45
- # answer it here; the model asks in its reply instead.
45
+ # answer it here; the model asks in its reply instead;
46
+ # - a plugin tool its bundle declared chi.tool(participant: :deny)
47
+ # (Targets#participant: by name, and through call_tool, which
48
+ # ToolIndex#unwrap renames to it before the gate): before its path
49
+ # and command checks and before UNTARGETED's ask.
46
50
  # And it asks the owner, always (Verdict#fresh_ask: no stored approval
47
51
  # answers it, and the rules can't lower it), before a write or an edit
48
52
  # that may land outside the session's project root, or a command that
@@ -66,7 +70,8 @@ module Samagotchi
66
70
  # :ask denied (ASK)
67
71
  # :checked goes on to the path and command checks below
68
72
  # A name not here (a plugin's or an MCP server's tool) goes on to them
69
- # too, but a delegate_* one (OWNER_VOICED_PREFIX). call_tool isn't
73
+ # too, but a delegate_* one (OWNER_VOICED_PREFIX), and a plugin tool
74
+ # declared participant: :deny, refused as BUNDLE_OWNER. call_tool isn't
70
75
  # here: ToolIndex#unwrap renames call_tool(chi/list_sessions) to
71
76
  # list_sessions before the guardrails see it.
72
77
  TOOL_CLASSES = {
@@ -96,10 +101,12 @@ module Samagotchi
96
101
  ASK = "a participant's turn can't ask the user: ask in your reply"
97
102
  OWNER_READS = "a participant's turn can't use %s: the owner's other sessions, reminders, schedules and " \
98
103
  "attached context are the owner's to read"
99
- # A denied kind of TOOL_CLASSES → its refusal (one with %s names the
104
+ BUNDLE_OWNER = "a participant's turn can't use %s: its bundle keeps it for the owner"
105
+ # A denied kind of TOOL_CLASSES (and :bundle_owner, a plugin tool
106
+ # declared participant: :deny) → its refusal (one with %s names the
100
107
  # tool).
101
108
  KIND_TEXTS = { owner_voiced: OWNER_ONLY, owner_tasks: OWNER_TASKS, owner_reader: OWNER_READS,
102
- memory_write: MEMORY_WRITE, ask: ASK }.freeze
109
+ memory_write: MEMORY_WRITE, ask: ASK, bundle_owner: BUNDLE_OWNER }.freeze
103
110
  OUTSIDE_WRITE = "a participant's turn writes outside the session's project"
104
111
  NO_PROJECT = "a participant's turn writes, and this session's folder is the home folder or above it (or none): " \
105
112
  "there is no project to keep it in"
@@ -217,6 +224,7 @@ module Samagotchi
217
224
  call = verdict.call || {}
218
225
  tool = call[:name].to_s
219
226
  kind = TOOL_CLASSES.fetch(tool) { :owner_voiced if tool.start_with?(OWNER_VOICED_PREFIX) }
227
+ kind ||= :bundle_owner if verdict.targets&.participant == :deny
220
228
  if (text = KIND_TEXTS[kind])
221
229
  return text.include?("%s") ? format(text, tool) : text
222
230
  end
@@ -122,6 +122,17 @@ module Samagotchi
122
122
  def secret?(path)
123
123
  return true if denied_roots.any? { |root| PathResolve.under?(path, root) }
124
124
 
125
+ ReviewPaths.secret_name?(path)
126
+ end
127
+
128
+ # The denylist's name half, on +path+'s own words (absolute or
129
+ # relative: no dir of it is looked up): a part named like a secret
130
+ # file (SECRET_FILE), mise's local config (SECRET_PATH), a dot dir's
131
+ # token file (SECRET_DIR_FILES) or a config under a .git dir. What a
132
+ # file inside an allowed folder is judged by (ctx.project.secret_name?).
133
+ # @param path [String]
134
+ def self.secret_name?(path)
135
+ path = path.to_s
125
136
  parts = path.split(File::SEPARATOR)
126
137
  return true if parts.any? { |part| SECRET_FILE.match?(part) } || path.match?(SECRET_PATH)
127
138
  return true if parts.each_cons(2).any? { |dir, file| SECRET_DIR_FILES[dir.downcase] == file.downcase }
@@ -129,14 +140,13 @@ module Samagotchi
129
140
  git_config?(parts)
130
141
  end
131
142
 
132
- private
133
-
134
143
  # A config file anywhere under a .git dir (.git/config,
135
144
  # .git/modules/<sub>/config, a worktree's config.worktree).
136
- def git_config?(parts)
145
+ def self.git_config?(parts)
137
146
  git = parts.index { |part| part.casecmp?(GIT_DIR) } or return false
138
147
  parts[(git + 1)..].any? { |part| part.downcase.start_with?("config") }
139
148
  end
149
+ private_class_method :git_config?
140
150
  end
141
151
  end
142
152
  end
@@ -84,6 +84,13 @@ module Samagotchi
84
84
  # call's name.
85
85
  attr_reader :acts_as
86
86
 
87
+ # @return [Symbol, nil] a plugin tool's chi.tool(participant:) (its
88
+ # registered entry's: :deny, :allow; :deny too when the tool its
89
+ # call acts as is: .participant_of); nil for chi's own tools and
90
+ # for a call no entry answers. Guardrails::PairBoundary refuses a
91
+ # :deny one on a participant's turn.
92
+ attr_reader :participant
93
+
87
94
  # @return [String, nil] what a plugin tool's targets: says to name the
88
95
  # call by in the approval question (label:, "github: x"), in place of
89
96
  # the tool's registered label; display only (no rule or approval key
@@ -134,6 +141,7 @@ module Samagotchi
134
141
  cwd = base
135
142
  args = nil
136
143
  acts_as = nil
144
+ participant = nil
137
145
  label = nil
138
146
  writes = false
139
147
  env = {}
@@ -161,13 +169,14 @@ module Samagotchi
161
169
  entry = entry_of(tool, registry, surface)
162
170
  args = given[:args] || call[:args] if entry && !entry.core? && call[:args].is_a?(Hash)
163
171
  acts_as = given[:acts_as]
172
+ participant = participant_of(entry, acts_as, registry, surface)
164
173
  label = given[:label]
165
174
  end
166
175
  memory_remove = tool == "memory_write" && call[:remove].to_s.strip.downcase == "true"
167
176
  memory_overlay = tool == "memory_write" && !memory_remove && call[:current_model_only].to_s.strip.downcase == "true"
168
177
  memory = tool == "memory_write" ? memory_facts(call) : nil
169
178
  new(tool: tool, command: command, paths: paths.compact, cwd: cwd, env: env, repo_root: context.repo_root(cwd),
170
- repo: context.repo(cwd), args: args, acts_as: acts_as, label: label, writes: writes,
179
+ repo: context.repo(cwd), args: args, acts_as: acts_as, label: label, writes: writes, participant: participant,
171
180
  memory_remove: memory_remove,
172
181
  memory_overlay: memory_overlay, memory: memory,
173
182
  model_name: model_name, model_key: model_key, session_root: context.repo_root(base) || base,
@@ -243,6 +252,18 @@ module Samagotchi
243
252
  surface ? surface.registered[name] : registry&.[](name)
244
253
  end
245
254
 
255
+ # A plugin tool's call's participant: (Registry::Entry#participant):
256
+ # :deny when its entry or the tool its call acts as (call_tool's
257
+ # acts_as: a call whose inner args didn't unwrap) is declared so; else
258
+ # its entry's; nil for chi's own tools and a call with no entry.
259
+ def self.participant_of(entry, acts_as, registry, surface)
260
+ return nil unless entry && !entry.core?
261
+ return :deny if acts_as && entry_of(acts_as, registry, surface)&.participant == :deny
262
+
263
+ entry.participant
264
+ end
265
+ private_class_method :participant_of
266
+
246
267
  # The drops logged, per registry (a session's): each tool's acts_as
247
268
  # once, not at every call (targets run several times a call).
248
269
  DROPS_LOGGED = ObjectSpace::WeakKeyMap.new
@@ -336,8 +357,9 @@ module Samagotchi
336
357
  # @param env [Hash{String=>String}] the call's env: (.env_of)
337
358
  def initialize(tool:, command:, paths:, cwd:, repo_root:, env: {}, repo: nil, args: nil, acts_as: nil,
338
359
  label: nil, model_name: nil, model_key: nil, session_root: nil, chi_dirs: nil,
339
- memory_remove: false, memory_overlay: false, memory: nil, writes: false)
360
+ memory_remove: false, memory_overlay: false, memory: nil, writes: false, participant: nil)
340
361
  @env = env
362
+ @participant = participant
341
363
  @acts_as = acts_as
342
364
  @label = label
343
365
  @writes = writes
@@ -14,6 +14,7 @@ require_relative "guardrails/parent_policy"
14
14
  require_relative "host_registry"
15
15
  require_relative "session"
16
16
  require_relative "system_one"
17
+ require_relative "system_one/approval_choice"
17
18
 
18
19
  module Samagotchi
19
20
  # `chi guardrails`: the guardrails' own maintenance commands, on this
@@ -317,16 +318,9 @@ module Samagotchi
317
318
  # What the user did, as the log's label: the scope they took, a denial
318
319
  # when the answer is not one of the offered scopes, none for an ask that
319
320
  # was cancelled (docs/guardrails.md, "System 1").
321
+ # (SystemOne::ApprovalLabel.choice, which the live label uses too.)
320
322
  def label_for(answer, scopes)
321
- index = answer[:selected_indices]&.first
322
- return "deny" if index.nil?
323
-
324
- scopes = Array(scopes)
325
- if index < scopes.size
326
- scopes[index] == "once" ? "allow_once" : "allow_wide"
327
- else
328
- "deny"
329
- end
323
+ SystemOne::ApprovalLabel.choice(answer[:selected_indices]&.first, Array(scopes))
330
324
  end
331
325
 
332
326
  # Judge one ask, write its two lines unless this is a dry run, and return
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Samagotchi
4
+ # A hook's label as what it is attributed to. No requires, so it loads
5
+ # alone (HookRoutes' own requires are too heavy for a page script).
6
+ module HookLabel
7
+ BUNDLE = /\(bundle (.+)\)\z/
8
+
9
+ module_function
10
+
11
+ # The bundle of a bundle hook's label ("<file> (bundle <name>)"), the
12
+ # label of any other, as a String. HookRoutes#source uses it.
13
+ # @param label [Object]
14
+ # @return [String]
15
+ def source(label)
16
+ label.to_s[BUNDLE, 1] || label.to_s
17
+ end
18
+ end
19
+ end
@@ -2,6 +2,7 @@
2
2
 
3
3
  require_relative "cut"
4
4
  require_relative "event_routes"
5
+ require_relative "hook_label"
5
6
  require_relative "hooks"
6
7
  require_relative "log"
7
8
 
@@ -59,9 +60,9 @@ module Samagotchi
59
60
  end
60
61
 
61
62
  # What a steer is attributed to: the bundle of a bundle hook's label
62
- # ("<file> (bundle <name>)"), the label of any other.
63
+ # ("<file> (bundle <name>)"), the label of any other (HookLabel.source).
63
64
  def source(hook)
64
- hook.to_s[/\(bundle (.+)\)\z/, 1] || hook.to_s
65
+ HookLabel.source(hook)
65
66
  end
66
67
 
67
68
  # One line to the user (:hook_notice). During a turn it is a turn
@@ -42,6 +42,10 @@ module Samagotchi
42
42
  # needs BundleManifest.parse_needs'
43
43
  # script_names the scripts/ files it lists
44
44
  # context_providers Array<ContextProviders::Provider>
45
+ # context_group the label the web's chips fold the bundle's
46
+ # sources under (context_group:): the kept
47
+ # manifest's only, nil from the record (so a
48
+ # missing, stale or edited kept file has none)
45
49
  # block_renderers Array<BlockRenderers::Renderer>
46
50
  # pages the page scripts (pages:, Pages::Bundled): the
47
51
  # kept manifest's only, [] from the record (a
@@ -65,7 +69,7 @@ module Samagotchi
65
69
  # the first chi that read it), {} from the record
66
70
  # origin :kept or :record
67
71
  class Manifest < Data.define(:name, :version, :requires_chi, :trust_level, :description, :needs,
68
- :script_names, :context_providers, :block_renderers, :pages, :session_settings,
72
+ :script_names, :context_providers, :context_group, :block_renderers, :pages, :session_settings,
69
73
  :session_setting_types, :settings, :setting_types, :file_descriptions,
70
74
  :plugin_required, :plugin_parts, :includes, :unknown_keys, :floor_keys, :problems,
71
75
  :origin)
@@ -137,6 +141,7 @@ module Samagotchi
137
141
  needs: pick.call("needs", kept.needs, mirrored.needs),
138
142
  script_names: pick.call("scripts", kept.scripts.keys, mirrored.script_names),
139
143
  context_providers: pick.call("context_providers", kept.context_providers, mirrored.context_providers),
144
+ context_group: pick.call("context_group", kept.context_group, mirrored.context_group),
140
145
  block_renderers: pick.call("block_renderers", kept.block_renderers, mirrored.block_renderers),
141
146
  pages: pick.call("pages", kept.pages, mirrored.pages),
142
147
  session_settings: session.session_settings, session_setting_types: session.session_setting_types,
@@ -163,6 +168,7 @@ module Samagotchi
163
168
  needs: parsed(problems, "needs", [], BundleManifest::ValidationError) { BundleManifest.parse_needs(raw["needs"]) },
164
169
  script_names: bundle.scripts.keys,
165
170
  context_providers: parsed(problems, "context_providers", []) { ContextProviders.parse_list(raw["context_providers"]) },
171
+ context_group: nil,
166
172
  block_renderers: parsed(problems, "block_renderers", []) { BlockRenderers.parse_list(raw["block_renderers"]) },
167
173
  pages: [],
168
174
  session_settings: list(raw["session_settings"]) || [],
@@ -203,7 +203,7 @@ module Samagotchi
203
203
  parts.scripts.each_value { |src| FileUtils.cp(src, File.join(staging, "scripts", File.basename(src))) }
204
204
  end
205
205
 
206
- # manifest.yml for the staged bundle: requires_chi, needs, session_settings and settings (typed) and the
206
+ # manifest.yml for the staged bundle: requires_chi, needs, context_group, session_settings and settings (typed) and the
207
207
  # file descriptions come from the installed bundle's manifest (InstalledBundles::Manifest), the
208
208
  # trust_level and description from the CLI else that manifest. A key of its kept manifest.yml
209
209
  # this chi doesn't know is carried as installed (the build is the bundle again), with a warning.
@@ -227,6 +227,7 @@ module Samagotchi
227
227
  needs: manifest&.needs,
228
228
  scripts: parts.scripts.transform_values { |src| InstalledBundles::FileDigest.sha256(src) },
229
229
  context_providers: parts.context_providers,
230
+ context_group: manifest&.context_group,
230
231
  block_renderers: parts.block_renderers,
231
232
  pages: manifest&.pages || [],
232
233
  file_descriptions: manifest ? manifest.file_descriptions.slice(*files_map.keys) : {},
@@ -49,7 +49,8 @@ module Samagotchi
49
49
  plugin: plugin(bundle, provenance, dir),
50
50
  scripts: copies(bundle.scripts, provenance.scripts_dir, File.join(dir, "scripts")),
51
51
  requires_chi: manifest.requires_chi, needs: manifest.needs,
52
- context_providers: manifest.context_providers, block_renderers: manifest.block_renderers, pages: manifest.pages,
52
+ context_providers: manifest.context_providers, context_group: manifest.context_group, block_renderers: manifest.block_renderers,
53
+ pages: manifest.pages,
53
54
  session_settings: manifest.session_settings, session_setting_types: manifest.session_setting_types,
54
55
  settings: manifest.settings, setting_types: manifest.setting_types
55
56
  )
@@ -23,10 +23,13 @@ module Samagotchi
23
23
  def self.usage(pages_dir: Paths.tilde(Pages.scripts_dir))
24
24
  <<~TEXT
25
25
  Usage: chi page <run|list|rm> [options]
26
- run NAME [--format text|json] run #{pages_dir}/NAME.rb (else an installed bundle's page NAME) in a process of its own (in the
26
+ run NAME [--format text|json|lines] run #{pages_dir}/NAME.rb (else an installed bundle's page NAME) in a process of its own (in the
27
27
  pages folder, cut at #{Pages::TIMEOUT_SECONDS} s with what it started), store what it built and print a summary of
28
- each block (json: the stored page). A failed run keeps the last good result. Exit 1 when the
29
- script raised, was stopped or broke a limit, when there is no such page or it is already running.
28
+ each block (json: the stored page; lines: the stored page in full, a line per text line and table
29
+ row, `|` between cells (`\\|` and `\\\\` for a `|` and a `\\` in one), `== block N` before each block (a
30
+ block's own line starting `== block ` gets a `\\` before it)). A failed run keeps the last good result.
31
+ Exit 1 when the script raised, was stopped or broke a limit, when there is no such page or it is
32
+ already running.
30
33
  list [--format text|json] every page: its title, when it last ran or failed (and on which line),
31
34
  (never ran), "changed" when the script changed since the result was made, and the bundle a page
32
35
  comes with (json: bundle, and script: the path of the script it runs)
@@ -45,6 +48,9 @@ module Samagotchi
45
48
  "rm" => CLI::Flags.new(help: HELP_WORDS)
46
49
  }.freeze
47
50
 
51
+ # The formats run prints (list: text and json).
52
+ RUN_FORMATS = %w[text json lines].freeze
53
+
48
54
  # How much of a run's summary each block gets.
49
55
  TEXT_LINES = 3
50
56
  TEXT_CHARS = 240
@@ -93,6 +99,74 @@ module Samagotchi
93
99
  end
94
100
  end
95
101
 
102
+ # What starts a block's header in `--format lines`.
103
+ HEADER = "== block "
104
+
105
+ # The stored page as lines, uncut (`--format lines`): what a model reads
106
+ # in parts (a tool's saved output, by start_line) where the one-line
107
+ # JSON can't be. The name and title, when it ran (and the failure since,
108
+ # if any, with the last lines of the failed run's stderr), then
109
+ # `== block N: type` before each block: a text's lines as they are; a
110
+ # table's labels, one row a line (cells as the summary formats them, `|`
111
+ # between, a newline in a cell as a space, `\` and `|` in a cell as `\\`
112
+ # and `\|`) and the total; a walk's title and one step a line. A block's
113
+ # line that starts with `== block ` gets a `\` before it, so no block
114
+ # forges a header.
115
+ # @param page [Pages::Stored]
116
+ # @param stderr [String, nil] a failed run's stderr (its tail follows the error)
117
+ # @return [Array<String>]
118
+ def self.lines(page, stderr: nil)
119
+ head = [%(page #{page.name}: #{page.title.to_s.inspect}), "ran_at: #{page.ran_at || "never"}"]
120
+ error = page.error
121
+ if error
122
+ head << "error: #{"line #{error.line}: " if error.line}#{error.message.to_s.gsub(/[\r\n]+/, " ")}"
123
+ head.concat(stderr_tail(stderr.to_s).map { |line| " #{line}" })
124
+ end
125
+ blocks = Array(page.blocks).each_with_index.flat_map do |block, i|
126
+ ["#{HEADER}#{i + 1}: #{block["type"]}", *block_lines(block).map { |line| line.start_with?(HEADER) ? "\\#{line}" : line }]
127
+ end
128
+ head + blocks
129
+ end
130
+
131
+ # The last non-empty lines of a run's stderr, as a failure prints them.
132
+ def self.stderr_tail(text)
133
+ text.lines.map(&:chomp).reject(&:empty?).last(STDERR_LINES)
134
+ end
135
+
136
+ def self.block_lines(block)
137
+ case block["type"]
138
+ when "text" then block["text"].to_s.split("\n", -1)
139
+ when "table" then table_lines(block)
140
+ when "walk" then walk_lines(block["data"] || {})
141
+ else []
142
+ end
143
+ end
144
+
145
+ # A cell as `--format lines` prints it: one line, `\` and `|` escaped,
146
+ # so a `|` in a cell never reads as another column.
147
+ def self.line_cell(text)
148
+ text.to_s.gsub(/[\r\n]+/, " ").gsub(/[\\|]/) { |c| "\\#{c}" }
149
+ end
150
+
151
+ def self.table_lines(block)
152
+ columns = Array(block["columns"])
153
+ row = ->(cells) { columns.each_with_index.map { |c, i| line_cell(cell(cells[i], c["format"])) }.join(" | ") }
154
+ dropped = block["dropped"].to_i
155
+ [columns.map { |c| line_cell(c["label"]) }.join(" | "), *Array(block["rows"]).map(&row),
156
+ *("total: #{row.call(block["total"])}" if block["total"]), *("(#{dropped} rows dropped)" unless dropped.zero?)]
157
+ end
158
+
159
+ def self.walk_lines(data)
160
+ steps = Array(data["steps"]).map do |step|
161
+ if step.is_a?(Hash)
162
+ step.values.map { |v| line_cell(v.is_a?(String) ? v : JSON.generate(v)) }.join(" | ")
163
+ else
164
+ step.to_s
165
+ end
166
+ end
167
+ ["walk: #{data["title"]}", *steps]
168
+ end
169
+
96
170
  def self.count(value)
97
171
  size = value.abs
98
172
  return value.to_s if size < 1000
@@ -116,15 +190,17 @@ module Samagotchi
116
190
 
117
191
  def run_run(options, args)
118
192
  format = options[:format]
119
- refused = format_refusal(format)
193
+ refused = format_refusal(format, RUN_FORMATS)
120
194
  return refused if refused
121
195
 
122
196
  name = one_name(args)
123
197
  return name if name.is_a?(Integer)
124
198
 
125
- result = Pages::Launch.run(name)
199
+ result = Pages::Launch.run(name, launch_dir: launch_dir)
126
200
  if format == "json"
127
201
  @stdout.puts(JSON.generate(result.page.to_json_hash))
202
+ elsif format == "lines"
203
+ self.class.lines(result.page, stderr: (result.stderr unless result.ok?)).each { |line| @stdout.puts(line) }
128
204
  elsif result.ok?
129
205
  print_summary(result)
130
206
  else
@@ -133,6 +209,14 @@ module Samagotchi
133
209
  result.ok? ? CLI::Exit::OK : CLI::Exit::FAILED
134
210
  end
135
211
 
212
+ # The folder it was typed in: the script's runtime.launch_dir; nil
213
+ # when that folder is gone (the run itself happens in the pages folder).
214
+ def launch_dir
215
+ Dir.pwd
216
+ rescue Errno::ENOENT
217
+ nil
218
+ end
219
+
136
220
  def print_summary(result)
137
221
  page = result.page
138
222
  @stdout.puts(%(page #{page.name}: #{page.title.inspect} (#{Kernel.format("%.1f", result.seconds)} s)))
@@ -175,7 +259,7 @@ module Samagotchi
175
259
  error = page.error
176
260
  @stdout.flush
177
261
  @stderr.puts("error: #{"line #{error.line}: " if error&.line}#{error&.message}")
178
- result.stderr.lines.map(&:chomp).reject(&:empty?).last(STDERR_LINES).each { |line| @stderr.puts(" #{line}") }
262
+ self.class.stderr_tail(result.stderr.to_s).each { |line| @stderr.puts(" #{line}") }
179
263
  @stderr.puts("the result of #{local(page.ran_at)} is kept") if page.ran_at
180
264
  end
181
265
 
@@ -18,6 +18,10 @@ module Samagotchi
18
18
  # absolute) and the lock on fd 3 (the runner holds it too, and has a
19
19
  # deadline of its own for a launcher that dies mid-run), reads its
20
20
  # stdout and stderr through bounded readers, and cuts it at +timeout+.
21
+ # The runner's folder is the pages folder either way; the folder the
22
+ # caller ran in reaches the script only as Pages::LAUNCH_DIR_KEY
23
+ # (`chi page run` passes its own; a Refresh none), never from the
24
+ # launcher's inherited env.
21
25
  # The runner writes the output file; a cut, or a runner that ended without
22
26
  # writing one, is recorded here (Store.record_failure). Whatever the
23
27
  # script left running in its group is killed after any exit.
@@ -50,9 +54,11 @@ module Samagotchi
50
54
  # @param cancelled [#call, nil] polled while the run waits: true stops
51
55
  # the run as the cut does, recorded as "the run was stopped" (chi web
52
56
  # stopping during a Refresh)
57
+ # @param launch_dir [String, nil] the folder the run was asked from
58
+ # (`chi page run`'s), as Pages::LAUNCH_DIR_KEY; nil sets none
53
59
  # @raise [BadName] [Missing] [Busy]
54
60
  # @return [Result]
55
- def run(name, timeout: TIMEOUT_SECONDS, cancelled: nil)
61
+ def run(name, timeout: TIMEOUT_SECONDS, cancelled: nil, launch_dir: nil)
56
62
  Pages.check_name!(name)
57
63
  raise Missing, name unless Pages.exists?(name)
58
64
 
@@ -67,7 +73,7 @@ module Samagotchi
67
73
  refusal = Pages.bundled(name)&.refusal
68
74
  next refused(name, refusal) if refusal
69
75
 
70
- launch(name, timeout, lock, cancelled)
76
+ launch(name, timeout, lock, cancelled, launch_dir)
71
77
  end
72
78
  end
73
79
 
@@ -92,9 +98,11 @@ module Samagotchi
92
98
  # absolute. PWD is set to the pages folder too: spawn's chdir doesn't
93
99
  # change it, and a script reading ENV["PWD"] would otherwise see the
94
100
  # caller's folder, so the terminal and chi web would differ.
95
- # The remote, worker and agent markers (#cleared_keys) are unset too.
96
- def env
101
+ # The remote, worker and agent markers (#cleared_keys) are unset too,
102
+ # and Pages::LAUNCH_DIR_KEY is +launch_dir+ (unset for nil), after them.
103
+ def env(launch_dir = nil)
97
104
  ChildEnv.unbundled.merge(ChildEnv.unset).merge(cleared_keys.to_h { |key| [key, nil] })
105
+ .merge(Pages::LAUNCH_DIR_KEY => launch_dir)
98
106
  .merge(Paths.absolute_xdg).merge("PWD" => Pages.scripts_dir)
99
107
  end
100
108
 
@@ -102,21 +110,21 @@ module Samagotchi
102
110
  # are one path: CHI_REMOTE (a run never goes remote), a worker's
103
111
  # markers (it is no worker's child) and the vendor agent markers (a
104
112
  # script's `chi send` is the owner's, even from a chi web started in an
105
- # agent's pane).
113
+ # agent's pane), and the launch folder (only the caller's own is set).
106
114
  # @return [Array<String>]
107
115
  def cleared_keys(env = ENV)
108
- [SessionAccess::Dispatch::ENV_KEY, *AgentCaller::VENDOR_MARKERS.map(&:first)] +
116
+ [SessionAccess::Dispatch::ENV_KEY, Pages::LAUNCH_DIR_KEY, *AgentCaller::VENDOR_MARKERS.map(&:first)] +
109
117
  env.each_key.select { |key| key.start_with?(ChildEnv::WORKER_PREFIX) }
110
118
  end
111
119
 
112
- def launch(name, timeout, lock, cancelled)
120
+ def launch(name, timeout, lock, cancelled, launch_dir)
113
121
  before = Store.file_id(name)
114
122
  # A bundle's page runs there too: the folder may not exist yet.
115
123
  FileUtils.mkdir_p(Pages.scripts_dir)
116
124
  started = monotonic
117
125
  out_r, out_w = IO.pipe
118
126
  err_r, err_w = IO.pipe
119
- pid = ProcessGroup.spawn(env, *command(name, timeout), chdir: Pages.scripts_dir, in: File::NULL, out: out_w,
127
+ pid = ProcessGroup.spawn(env(launch_dir), *command(name, timeout), chdir: Pages.scripts_dir, in: File::NULL, out: out_w,
120
128
  err: err_w, LOCK_FD => lock)
121
129
  out_w.close
122
130
  err_w.close
@@ -27,6 +27,11 @@ module Samagotchi
27
27
  class Collector
28
28
  attr_reader :builder
29
29
 
30
+ # @param name [String, nil] the page this run is of (Runtime#settings)
31
+ def initialize(name = nil)
32
+ @name = name
33
+ end
34
+
30
35
  def dsl
31
36
  collector = self
32
37
  Module.new do
@@ -37,7 +42,7 @@ module Samagotchi
37
42
  end
38
43
  end
39
44
 
40
- def runtime = @runtime ||= Runtime.new
45
+ def runtime = @runtime ||= Runtime.new(page: @name)
41
46
 
42
47
  def page(title)
43
48
  raise Refused, "a page script calls page once" if @builder
@@ -70,7 +75,7 @@ module Samagotchi
70
75
  arm_deadline(name, timeout, Float(deadline), recording, done) if deadline
71
76
  path = Pages.script_path(name)
72
77
  sha = Digest::SHA256.file(path).hexdigest
73
- collector = Collector.new
78
+ collector = Collector.new(name)
74
79
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
75
80
  begin
76
81
  load(path, collector.dsl)