samagotchi 0.166.0 → 0.167.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 (83) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +63 -1
  3. data/docs/architecture.md +1 -0
  4. data/docs/cli.md +10 -5
  5. data/docs/configuration.md +1 -0
  6. data/docs/guardrails.md +6 -5
  7. data/docs/hooks.md +4 -6
  8. data/docs/internals/bundles.md +2 -4
  9. data/docs/internals/engine.md +4 -5
  10. data/docs/internals/objectives.md +141 -9
  11. data/docs/internals/remote-sessions.md +5 -6
  12. data/docs/internals/web-frontend.md +30 -25
  13. data/docs/memory.md +1 -2
  14. data/docs/sessions.md +20 -2
  15. data/docs/testing.md +4 -3
  16. data/lib/samagotchi/bridge.rb +1 -1
  17. data/lib/samagotchi/bundle_command/installed_check.rb +2 -14
  18. data/lib/samagotchi/bundle_command.rb +19 -11
  19. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  20. data/lib/samagotchi/cli/command.rb +10 -0
  21. data/lib/samagotchi/compat.rb +3 -11
  22. data/lib/samagotchi/config.rb +3 -0
  23. data/lib/samagotchi/context_command.rb +2 -1
  24. data/lib/samagotchi/engine/objectives.rb +20 -1
  25. data/lib/samagotchi/engine/side_requests.rb +3 -2
  26. data/lib/samagotchi/engine/turn_end.rb +4 -1
  27. data/lib/samagotchi/engine.rb +3 -0
  28. data/lib/samagotchi/extension_load.rb +2 -26
  29. data/lib/samagotchi/guardrails/approvals.rb +36 -13
  30. data/lib/samagotchi/jsonl_store.rb +61 -0
  31. data/lib/samagotchi/memory_bundle/status.rb +3 -15
  32. data/lib/samagotchi/memory_bundle/system_bundle.rb +16 -10
  33. data/lib/samagotchi/memory_command.rb +4 -2
  34. data/lib/samagotchi/objectives.rb +43 -14
  35. data/lib/samagotchi/objectives_backing.rb +124 -0
  36. data/lib/samagotchi/objectives_check.rb +19 -126
  37. data/lib/samagotchi/objectives_command.rb +14 -7
  38. data/lib/samagotchi/objectives_record.rb +104 -0
  39. data/lib/samagotchi/objectives_track.rb +353 -0
  40. data/lib/samagotchi/push_command.rb +2 -1
  41. data/lib/samagotchi/remote_command.rb +2 -1
  42. data/lib/samagotchi/reply_wait/poll.rb +6 -6
  43. data/lib/samagotchi/reply_wait.rb +4 -24
  44. data/lib/samagotchi/schedule_command.rb +6 -0
  45. data/lib/samagotchi/schedules.rb +1 -1
  46. data/lib/samagotchi/session_access/remote.rb +3 -5
  47. data/lib/samagotchi/session_commands.rb +1 -1
  48. data/lib/samagotchi/sessions_command.rb +12 -6
  49. data/lib/samagotchi/share_command.rb +2 -1
  50. data/lib/samagotchi/tool_activity.rb +11 -1
  51. data/lib/samagotchi/tool_declarations.rb +5 -1
  52. data/lib/samagotchi/tools/objectives_tool.rb +19 -2
  53. data/lib/samagotchi/turn_stages/objectives.rb +46 -3
  54. data/lib/samagotchi/version.rb +1 -1
  55. data/lib/samagotchi/web/participant_access.rb +1 -1
  56. data/lib/samagotchi/web/public/app.js +52 -424
  57. data/lib/samagotchi/web/public/copy.js +2 -1
  58. data/lib/samagotchi/web/public/index.html +35 -9
  59. data/lib/samagotchi/web/public/info_bar_model.js +3 -1
  60. data/lib/samagotchi/web/public/no_contact_fill.js +29 -0
  61. data/lib/samagotchi/web/public/objectives.css +14 -0
  62. data/lib/samagotchi/web/public/objectives_moves.js +82 -9
  63. data/lib/samagotchi/web/public/objectives_state.js +42 -0
  64. data/lib/samagotchi/web/public/objectives_strip.js +33 -9
  65. data/lib/samagotchi/web/public/objectives_track.js +52 -0
  66. data/lib/samagotchi/web/public/objectives_wiring.js +16 -1
  67. data/lib/samagotchi/web/public/participant.html +1 -1
  68. data/lib/samagotchi/web/public/participants_panel.js +14 -7
  69. data/lib/samagotchi/web/public/question_cards.js +7 -12
  70. data/lib/samagotchi/web/public/resync_reach.js +10 -6
  71. data/lib/samagotchi/web/public/scope.js +3 -3
  72. data/lib/samagotchi/web/public/session_rename.js +6 -2
  73. data/lib/samagotchi/web/public/session_state.js +1 -1
  74. data/lib/samagotchi/web/public/session_sync.js +249 -0
  75. data/lib/samagotchi/web/public/session_view.js +279 -0
  76. data/lib/samagotchi/web/public/stream_handlers.js +1 -1
  77. data/lib/samagotchi/web/public/tokens.css +2 -2
  78. data/lib/samagotchi/web/public/turn_block.js +8 -0
  79. data/lib/samagotchi/web/public/turn_html.js +1 -1
  80. data/lib/samagotchi/web/public/widget_picks.js +3 -0
  81. data/lib/samagotchi/web/public/working_set_view.js +1 -1
  82. data/lib/samagotchi/web/session_access_routes.rb +4 -15
  83. metadata +10 -1
@@ -28,12 +28,11 @@ module Samagotchi
28
28
  # approvals.json.corrupt-<UTC time>[-N], with a warning, and the store
29
29
  # starts empty: it only means more asks, and nothing is overwritten.
30
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).
31
+ # The file is a versioned store, {"version", "approvals": [...]}
32
+ # (FORMAT); a write keeps its version and the keys this chi doesn't
33
+ # know. A list of entries (what 0.165 and before write) is read too,
34
+ # and rewritten as the versioned store under the lock on that first
35
+ # read (compat shim approvals_array_read).
37
36
  class Approvals
38
37
  FILE = "approvals.json"
39
38
  COLLECTION = "approvals"
@@ -173,7 +172,8 @@ module Samagotchi
173
172
  def read(locked: false)
174
173
  return [[], nil] unless File.exist?(@path)
175
174
 
176
- parse(File.read(@path))
175
+ list, document = parse(File.read(@path))
176
+ document ? [list, document] : version_list(locked: locked) || [list, nil]
177
177
  rescue JSON::ParserError, SystemCallError => e
178
178
  aside = begin
179
179
  locked ? set_aside : with_lock { set_aside }
@@ -207,6 +207,30 @@ module Samagotchi
207
207
  end
208
208
  end
209
209
 
210
+ # compat shim approvals_array_read: rewrite a list as the versioned
211
+ # store, under the lock, if it is still a list. One that can't be
212
+ # written (a read-only state dir) or changed meanwhile is read as it
213
+ # is this time.
214
+ # @return [Array(Array<Hash>, StateFormat::Document), nil] as #read's; nil when not rewritten
215
+ def version_list(locked:)
216
+ locked ? version_list! : with_lock { version_list! }
217
+ rescue JSON::ParserError, SystemCallError
218
+ nil
219
+ end
220
+
221
+ def version_list!
222
+ list, document = parse(File.read(@path))
223
+ return [list, document] if document
224
+
225
+ document = FORMAT.read({ COLLECTION => list }, collection: COLLECTION)
226
+ write(document)
227
+ [list, document]
228
+ end
229
+
230
+ def write(document)
231
+ AtomicFile.write(@path, JSON.pretty_generate(FORMAT.write(document, collection: COLLECTION, updated_at: nil)))
232
+ end
233
+
210
234
  # Under the lock: rename the file aside if it is still unreadable.
211
235
  # @return [String, :readable] where it went; :readable when another
212
236
  # process replaced or removed it meanwhile
@@ -237,16 +261,15 @@ module Samagotchi
237
261
  end
238
262
  end
239
263
 
240
- # Writes the shape it read: a versioned store keeps its version and
241
- # the keys this chi doesn't know.
264
+ # Writes the versioned store: one read keeps its version and the
265
+ # keys this chi doesn't know; no file (or one that couldn't be
266
+ # rewritten on read) starts at FORMAT's version.
242
267
  def update
243
268
  with_lock do
244
269
  list, document = read(locked: true)
245
270
  yield 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))
271
+ document ||= FORMAT.read({}, collection: COLLECTION)
272
+ write(document.with(entries: list))
250
273
  end
251
274
  end
252
275
 
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "json"
5
+ require "time"
6
+
7
+ module Samagotchi
8
+ # One append-only JSONL file beside a session (FILE in its folder, 0600): a
9
+ # line is a Hash stamped with its time, and a broken line reads as none. The
10
+ # generic half of a side reader's state (ObjectivesCheck, ObjectivesTrack):
11
+ # what a line means, and which is the latest, stays with its reader.
12
+ class JsonlStore
13
+ attr_reader :file
14
+
15
+ # @param file [String] the file's name in a session's folder
16
+ def initialize(file)
17
+ @file = file
18
+ end
19
+
20
+ # Append one line, +now+ as its "at".
21
+ def write(session_dir, now: Time.now, **fields)
22
+ FileUtils.mkdir_p(session_dir)
23
+ File.open(File.join(session_dir, file), File::WRONLY | File::APPEND | File::CREAT, 0o600) do |io|
24
+ io.write("#{JSON.generate({ at: now.utc.iso8601(3), **fields })}\n")
25
+ end
26
+ end
27
+
28
+ # Every line that reads as a Hash, oldest first; none with no file.
29
+ # @return [Array<Hash>]
30
+ def lines(session_dir)
31
+ File.readlines(File.join(session_dir, file), chomp: true).filter_map do |raw|
32
+ line = JSON.parse(raw)
33
+ line if line.is_a?(Hash)
34
+ rescue JSON::ParserError
35
+ nil
36
+ end
37
+ rescue SystemCallError
38
+ []
39
+ end
40
+
41
+ # A line's "at"; the epoch for one that has none or a bad one.
42
+ def self.time_of(line)
43
+ Time.iso8601(line["at"].to_s)
44
+ rescue ArgumentError
45
+ Time.at(0)
46
+ end
47
+
48
+ # Whether the worker that wrote a running line still lives: a line with no
49
+ # pid is taken as alive (its time limit still frees it).
50
+ def self.worker_alive?(pid)
51
+ return true unless pid.is_a?(Integer)
52
+
53
+ Process.kill(0, pid)
54
+ true
55
+ rescue Errno::EPERM
56
+ true
57
+ rescue Errno::ESRCH
58
+ false
59
+ end
60
+ end
61
+ end
@@ -17,8 +17,7 @@ module Samagotchi
17
17
  # A bundle as this chi reads it now (what chi bundle status prints):
18
18
  # its stored record, the scope it resolves to (scope_error when it
19
19
  # can't), the folder its files belong in, what each file looks like on
20
- # disk, its installed plugin, the class-file hooks its record still
21
- # has (retired_hooks: they don't load), and its needs
20
+ # disk, its installed plugin, and its needs
22
21
  # with what this process's PATH found. The +files+ entries and +plugin+
23
22
  # stay Hashes: their fields differ per case (an unchecked file has no
24
23
  # paths at all). An entry's behind is its FileStanding::Behind, nil for a
@@ -27,7 +26,7 @@ module Samagotchi
27
26
  # rules and scripts: each recorded one by name, "ok", "modified" or
28
27
  # "missing" (asset_states).
29
28
  Report = Data.define(:provenance, :scope, :scope_error, :target_dir, :files, :plugin,
30
- :rules, :scripts, :retired_hooks, :needs)
29
+ :rules, :scripts, :needs)
31
30
 
32
31
  # A scope this chi can't resolve (a newer chi's, a hand edit) isn't
33
32
  # guessed: scope_error says so, target_dir is nil and each file is
@@ -75,7 +74,7 @@ module Samagotchi
75
74
  target_dir: target_dir, files: details, plugin: plugin_status(provenance, bundle),
76
75
  rules: asset_states(provenance.guardrails_dir, :rule, bundle.guardrails),
77
76
  scripts: asset_states(provenance.scripts_dir, :script, bundle.scripts),
78
- retired_hooks: retired_hooks(provenance, bundle), needs: needs_status(bundle))
77
+ needs: needs_status(bundle))
79
78
  end
80
79
 
81
80
  # A FileState digest as the Report has it: nil for none, or one that
@@ -83,17 +82,6 @@ module Samagotchi
83
82
  def self.digest_or_nil(digest) = digest == :unreadable ? nil : digest
84
83
  private_class_method :digest_or_nil
85
84
 
86
- # The class-file hooks the record still has (a 0.157 install's; chi
87
- # loads none, Manifest::HooksRetired), each "present" or "missing" in
88
- # hooks/, by name; {} for none (compat shim retired_class_file_hooks:
89
- # Compat::SHIMS).
90
- # @return [Hash{String => String}]
91
- def self.retired_hooks(provenance, bundle)
92
- bundle.hooks.keys.sort.to_h do |file|
93
- [file, File.exist?(File.join(provenance.hooks_dir, file)) ? "present" : "missing"]
94
- end
95
- end
96
-
97
85
  # Each recorded rule or script: "missing" (not there), "modified" (its
98
86
  # AssetState is edited: the next install replaces it, a copy kept in
99
87
  # the trash; an edited rule doesn't load) or "ok"; {} for none.
@@ -111,7 +111,7 @@ module Samagotchi
111
111
  from = bundle&.version.to_s
112
112
 
113
113
  if bundle.nil?
114
- dry_run ? result(:installed, to: to) : install_fresh(to)
114
+ dry_run ? planned_install(to) : install_fresh(to)
115
115
  elsif installed_newer?(from, to)
116
116
  # Running an older checkout/gem: never downgrade the user's system memories
117
117
  # (not even to restore a missing file). `chi self` shows installed vs shipped.
@@ -182,18 +182,24 @@ module Samagotchi
182
182
  end
183
183
 
184
184
  def install_fresh(to)
185
- installer = Installer.new(
186
- source: GEM_BUNDLE_DIR,
187
- name: BUNDLE_NAME,
188
- scope: SCOPE,
189
- force: false,
190
- strict: true,
191
- shipped_dir: File.dirname(GEM_BUNDLE_DIR)
192
- )
185
+ installer = fresh_installer
193
186
  installer.run
194
187
  result(:installed, to: to, warnings: installer.warnings)
195
188
  end
196
189
 
190
+ # A dry run's answer for a fresh install: its checksum mismatches, as
191
+ # planned_update gives an upgrade's.
192
+ def planned_install(to)
193
+ installer = fresh_installer(dry_run: true)
194
+ installer.run
195
+ result(:installed, to: to, warnings: installer.warnings.grep(/\AChecksum mismatch/))
196
+ end
197
+
198
+ def fresh_installer(dry_run: false)
199
+ Installer.new(source: GEM_BUNDLE_DIR, name: BUNDLE_NAME, scope: SCOPE, force: false, strict: true,
200
+ dry_run: dry_run, shipped_dir: File.dirname(GEM_BUNDLE_DIR))
201
+ end
202
+
197
203
  # Installer handles fast_forward/keep/noop; a conflict keeps the local
198
204
  # file, and its own warning is left out (behind says it).
199
205
  def upgrade_existing(from, to)
@@ -294,7 +300,7 @@ module Samagotchi
294
300
  dry_run: dry_run, shipped_dir: File.dirname(GEM_BUNDLE_DIR))
295
301
  end
296
302
  private_class_method :with_lock, :note_newer_installed, :install_fresh, :keep_manifest, :upgrade_existing, :verify_files_present, :restore_file, :remerge,
297
- :upgrade_installer, :result, :planned_update
303
+ :upgrade_installer, :result, :planned_update, :planned_install, :fresh_installer
298
304
  end
299
305
  end
300
306
  end
@@ -179,7 +179,8 @@ module Samagotchi
179
179
  return usage_error("ls takes no NAME (unexpected #{args.first})") unless args.empty?
180
180
 
181
181
  format = options[:format]
182
- return usage_error("unknown format #{format.inspect}: use --format text|json") unless [nil, "text", "json"].include?(format)
182
+ refused = format_refusal(format)
183
+ return refused if refused
183
184
 
184
185
  rows = self.class.entries(options[:scope])
185
186
  if format == "json"
@@ -215,7 +216,8 @@ module Samagotchi
215
216
  return usage_error("usage takes no NAME (unexpected #{args.first})") unless args.empty?
216
217
 
217
218
  format = options[:format]
218
- return usage_error("unknown format #{format.inspect}: use --format text|json") unless [nil, "text", "json"].include?(format)
219
+ refused = format_refusal(format)
220
+ return refused if refused
219
221
  return usage_error("--top must be a positive integer") unless options[:top].nil? || options[:top].to_s.match?(/\A[1-9]\d*\z/)
220
222
  return usage_error("--top must be at most #{TOP_LIMIT}") if options[:top].to_i > TOP_LIMIT
221
223
 
@@ -9,8 +9,10 @@ require_relative "context_note"
9
9
  require_relative "llm_context_stale"
10
10
  require_relative "log"
11
11
  require_relative "message_time"
12
+ require_relative "objectives_backing"
12
13
  require_relative "objectives_check"
13
14
  require_relative "objectives_edit"
15
+ require_relative "objectives_track"
14
16
  require_relative "session"
15
17
  require_relative "session_chain"
16
18
  require_relative "session_inbox"
@@ -72,11 +74,22 @@ module Samagotchi
72
74
  # +ref+ names the call itself, words apart: its run's id and its model
73
75
  # entry's time, so a later move in the same words is another move, and so is
74
76
  # one after a rollback hands the same id out again.
75
- Move = Data.define(:id, :note, :evidence, :ref) do
76
- def initialize(id:, note:, evidence:, ref: nil) = super
77
+ # +state+ where the objective stands in the agent's view
78
+ # (Tools::ObjectivesTool::STATES): PROGRESS for a saved call with none or
79
+ # an unreadable one; DONE is its claim, never the item's status.
80
+ # +backing+ what its turn ran before it (Backing), nil when not read.
81
+ Move = Data.define(:id, :note, :evidence, :ref, :state, :backing) do
82
+ def initialize(id:, note:, evidence:, ref: nil, state: Tools::ObjectivesTool::PROGRESS, backing: nil) = super
77
83
 
78
- def line = evidence.empty? ? note : "#{note} (evidence: #{evidence})"
84
+ # The words a state adds to a move: none for PROGRESS.
85
+ def state_words = STATE_WORDS[state]
86
+
87
+ def line
88
+ text = evidence.empty? ? note : "#{note} (evidence: #{evidence})"
89
+ state_words ? "#{state_words}: #{text}" : text
90
+ end
79
91
  end
92
+ STATE_WORDS = { Tools::ObjectivesTool::BLOCKED => "blocked", Tools::ObjectivesTool::DONE => "claims done" }.freeze
80
93
 
81
94
  # What the user did to one objective between two lists, for the entry's
82
95
  # line: +kind+ added, done, dropped, reopened or reworded; +was+ a
@@ -193,20 +206,29 @@ module Samagotchi
193
206
  # What the note carries, in one key style: strings, as a save leaves them.
194
207
  def to_payload = { "next" => next_number, "items" => items.map(&:to_payload) }
195
208
 
196
- # What the page draws: the items, each with its last move and last check,
197
- # and whether the newest edit is still a file waiting to go in.
209
+ # What the page draws: the items, each with its last move, last check and
210
+ # last track, whether the newest edit is still a file waiting to go in,
211
+ # and +tracking+ only while a track runs.
198
212
  # @param checks [Hash{String => Hash}] ObjectivesCheck.view_of's
199
- def to_view(pending:, checks: {})
200
- { items: items.map { |item| item_view(item, checks[item.id]) }, pending: pending }
213
+ # @param tracks [Hash{String => Hash}] ObjectivesTrack.view_of's
214
+ def to_view(pending:, checks: {}, tracks: {}, tracking: nil)
215
+ view = { items: items.map { |item| item_view(item, checks[item.id], tracks[item.id]) }, pending: pending }
216
+ tracking ? view.merge(tracking: tracking) : view
201
217
  end
202
218
 
203
219
  private
204
220
 
205
- def item_view(item, check)
221
+ def move_view(move)
222
+ view = { "note" => move.note, "evidence" => move.evidence, "state" => move.state }
223
+ move.backing ? view.merge("backing" => move.backing.to_view) : view
224
+ end
225
+
226
+ def item_view(item, check, track)
206
227
  move = moves[item.id]
207
228
  view = item.to_payload
208
- view = view.merge("move" => { "note" => move.note, "evidence" => move.evidence }) if move
209
- check ? view.merge("check" => check) : view
229
+ view = view.merge("move" => move_view(move)) if move
230
+ view = view.merge("check" => check) if check
231
+ track ? view.merge("track" => track) : view
210
232
  end
211
233
  end
212
234
 
@@ -286,16 +308,20 @@ module Samagotchi
286
308
  # recorded one (LLMContextStale.paired_runs, as the working set reads its
287
309
  # runs: a call_tool's too, both hosts' forms). Tools::ObjectivesTool
288
310
  # .recorded? is the check: a call with no list, a refused, a denied or an
289
- # interrupted one recorded nothing.
311
+ # interrupted one recorded nothing. Each with its Backing: the runs of its
312
+ # own turn before it.
290
313
  # @return [Hash{String => Move}]
291
314
  def moves_in(conversation)
292
- LLMContextStale.paired_runs(conversation).each_with_object({}) do |run, moves|
315
+ runs = LLMContextStale.paired_runs(conversation)
316
+ runs.each_with_index.with_object({}) do |(run, position), moves|
293
317
  next unless run.call[:name] == Tools::ObjectivesTool::NAME
294
318
 
295
319
  id = move_id(run.call)
296
320
  next unless Tools::ObjectivesTool.recorded?(run.text, id)
297
321
 
298
- moves[id] = Move.new(id: id, note: clean(run.call[:note]), evidence: clean(run.call[:evidence]), ref: move_ref(conversation, run))
322
+ state = Tools::ObjectivesTool.state_of(run.call) || Tools::ObjectivesTool::PROGRESS
323
+ moves[id] = Move.new(id: id, note: clean(run.call[:note]), evidence: clean(run.call[:evidence]), ref: move_ref(conversation, run),
324
+ state: state, backing: Backing.of(Backing.turn_runs(conversation, runs, position), state))
299
325
  end
300
326
  end
301
327
 
@@ -324,7 +350,10 @@ module Samagotchi
324
350
  dir = Session.session_dir(session_id, state_dir: state_dir)
325
351
  pending = pending_payload(dir)
326
352
  list = build(conversation, pending: pending, running: running)
327
- list.empty? ? nil : list.to_view(pending: !pending.nil?, checks: ObjectivesCheck.view_of(dir, list))
353
+ return nil if list.empty?
354
+
355
+ tracks, tracking = ObjectivesTrack.view_of(dir, list, conversation)
356
+ list.to_view(pending: !pending.nil?, checks: ObjectivesCheck.view_of(dir, list), tracks: tracks, tracking: tracking)
328
357
  end
329
358
 
330
359
  # One note's list for the page's entry: its items and, when there was a
@@ -0,0 +1,124 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "steer"
4
+ require_relative "tool_activity"
5
+ require_relative "tool_response"
6
+ require_relative "tools/edit"
7
+ require_relative "tools/execute"
8
+ require_relative "tools/objectives_tool"
9
+ require_relative "tools/task_wait"
10
+ require_relative "tools/write"
11
+
12
+ module Samagotchi
13
+ module Objectives
14
+ # What a move's own turn ran before it, derived by the harness from the
15
+ # record (the model's evidence stays free text): +edits+ the edit and write
16
+ # runs that succeeded; +command+ the status of the last finished execute or
17
+ # task_wait run, OK, FAILED or nil; +edited_after_command+ a successful edit
18
+ # or write came after the last command that itself ran after the turn's
19
+ # first successful edit (false with none: a search before any edit, `rg` →
20
+ # edit → done, checked no edit, so it can't be stale); +unbacked+ the one
21
+ # flag: only for a DONE move after a command ran, when the last command
22
+ # failed or an edit came after the last command that checked an edit. A move that is progress or blocked never flags,
23
+ # and neither does a turn with edits and no command (a docs change would
24
+ # flag every time). Information only, pure. See docs/internals/objectives.md.
25
+ Backing = Data.define(:edits, :command, :edited_after_command, :unbacked) do
26
+ def to_view = { "edits" => edits, "command" => command, "edited_after_command" => edited_after_command, "unbacked" => unbacked }
27
+
28
+ # The /objectives line's and the page's words for a flagged move; nil
29
+ # for one that isn't.
30
+ def flag_words
31
+ return nil unless unbacked
32
+
33
+ command == Backing::FAILED ? "not backed: the last command failed" : "not backed: edited after the last command ran"
34
+ end
35
+ end
36
+
37
+ class Backing
38
+ OK = "ok"
39
+ FAILED = "failed"
40
+ CHANGES = [Tools::Edit::NAME, Tools::Write::NAME].freeze
41
+
42
+ # +runs+ the move's turn's paired runs before it (LLMContextStale.paired_runs'),
43
+ # in order; +state+ the move's.
44
+ # @return [Backing]
45
+ def self.of(runs, state)
46
+ edits = 0
47
+ command = nil
48
+ # A command ran after an edit: only that one could have checked it.
49
+ checked = false
50
+ edited_after = false
51
+ runs.each do |run|
52
+ if edit?(run)
53
+ edits += 1
54
+ edited_after = true if checked
55
+ elsif (status = command_status(run))
56
+ command = status
57
+ checked = true if edits.positive?
58
+ edited_after = false
59
+ end
60
+ end
61
+ unbacked = state == Tools::ObjectivesTool::DONE && !command.nil? && (command == FAILED || edited_after)
62
+ new(edits: edits, command: command, edited_after_command: edited_after, unbacked: unbacked)
63
+ end
64
+
65
+ # The runs of the move at +position+ in +runs+ that are of its own turn:
66
+ # after the nearest turn opening (Steer.turn_prompt?, what bounds a turn's
67
+ # slice) before the move's entry, up to the move. Mid-turn the fold reads
68
+ # the loop's own conversation too (Engine#live_conversation), which holds
69
+ # the running turn's opening. A rollback that drops a turn drops its runs
70
+ # with its moves.
71
+ def self.turn_runs(conversation, runs, position)
72
+ move = runs[position]
73
+ start = (move.index - 1).downto(0).find { |i| Steer.turn_prompt?(conversation[i]) } || -1
74
+ runs[0...position].select { |run| run.index > start }
75
+ end
76
+
77
+ # Work for the tracker's turn gate (ObjectivesTrack.worked_without_move?),
78
+ # as the page's no-move mark counts it: an edit or write that succeeded,
79
+ # an execute that finished ok (a failed, denied, stopped one isn't; one
80
+ # handed over as a task still runs, and isn't either).
81
+ def self.work?(run)
82
+ edit?(run) || (run.call[:name].to_s == Tools::Execute::NAME && command_status(run) == OK)
83
+ end
84
+
85
+ def self.edit?(run)
86
+ return false unless CHANGES.include?(run.call[:name].to_s) && !ToolResponse.interrupted_text?(run.text)
87
+
88
+ ToolActivity.tool_activity_status(ToolActivity.saved_result_text(run.text), run.call[:name].to_s) == "ok"
89
+ end
90
+ private_class_method :edit?
91
+
92
+ # A finished command's status, nil for no command: a call the guardrails
93
+ # denied, one stopped or interrupted, an execute handed over as a task
94
+ # (still running), and a task_wait whose task hadn't finished (a timeout,
95
+ # a waiting message) or that waited on nothing (an Error:).
96
+ def self.command_status(run)
97
+ name = run.call[:name].to_s
98
+ return nil unless [Tools::Execute::NAME, Tools::TaskWait::NAME].include?(name)
99
+ return nil if ToolResponse.interrupted_text?(run.text)
100
+
101
+ text = ToolActivity.saved_result_text(run.text)
102
+ return nil if ToolActivity.guardrail_denied?(text)
103
+ return task_status(text) if name == Tools::TaskWait::NAME
104
+ return nil if ToolActivity.handed_over?(name, text)
105
+
106
+ case ToolActivity.tool_activity_status(text, name, command: run.call[:content])
107
+ when "ok" then OK
108
+ when "error" then FAILED
109
+ end
110
+ end
111
+ private_class_method :command_status
112
+
113
+ def self.task_status(text)
114
+ return nil if text.start_with?("Error:")
115
+
116
+ case text.split(/^output_tail:$/, 2).first.to_s[/^status: (\S+)$/, 1]
117
+ when "completed" then OK
118
+ when "failed" then FAILED
119
+ end
120
+ end
121
+ private_class_method :task_status
122
+ end
123
+ end
124
+ end