samagotchi 0.166.0 → 0.168.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 (94) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +89 -1
  3. data/docs/architecture.md +1 -0
  4. data/docs/cli.md +24 -15
  5. data/docs/configuration.md +1 -0
  6. data/docs/guardrails.md +5 -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 +85 -40
  13. data/docs/memory.md +1 -2
  14. data/docs/sessions.md +20 -2
  15. data/docs/testing.md +3 -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 +35 -12
  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 +1 -13
  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 +15 -16
  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/dock_reserve.js +12 -2
  59. data/lib/samagotchi/web/public/history_end.js +16 -0
  60. data/lib/samagotchi/web/public/index.html +74 -22
  61. data/lib/samagotchi/web/public/info_bar_model.js +3 -1
  62. data/lib/samagotchi/web/public/no_contact_fill.js +29 -0
  63. data/lib/samagotchi/web/public/objectives.css +14 -0
  64. data/lib/samagotchi/web/public/objectives_moves.js +82 -9
  65. data/lib/samagotchi/web/public/objectives_state.js +42 -0
  66. data/lib/samagotchi/web/public/objectives_strip.js +33 -9
  67. data/lib/samagotchi/web/public/objectives_track.js +52 -0
  68. data/lib/samagotchi/web/public/objectives_wiring.js +16 -1
  69. data/lib/samagotchi/web/public/participant.html +1 -1
  70. data/lib/samagotchi/web/public/participants_panel.js +14 -7
  71. data/lib/samagotchi/web/public/question_cards.js +8 -13
  72. data/lib/samagotchi/web/public/refs.js +4 -1
  73. data/lib/samagotchi/web/public/reload_check.js +5 -4
  74. data/lib/samagotchi/web/public/resync_reach.js +10 -6
  75. data/lib/samagotchi/web/public/scope.js +3 -3
  76. data/lib/samagotchi/web/public/session_rename.js +6 -2
  77. data/lib/samagotchi/web/public/session_state.js +1 -1
  78. data/lib/samagotchi/web/public/session_sync.js +249 -0
  79. data/lib/samagotchi/web/public/session_view.js +279 -0
  80. data/lib/samagotchi/web/public/stage_cards.js +20 -0
  81. data/lib/samagotchi/web/public/stage_frame.js +14 -16
  82. data/lib/samagotchi/web/public/stage_model.js +11 -4
  83. data/lib/samagotchi/web/public/stage_opened.js +229 -0
  84. data/lib/samagotchi/web/public/stage_slots.js +2 -3
  85. data/lib/samagotchi/web/public/stage_view.js +219 -147
  86. data/lib/samagotchi/web/public/stage_watch.js +8 -4
  87. data/lib/samagotchi/web/public/stream_handlers.js +1 -1
  88. data/lib/samagotchi/web/public/tokens.css +2 -2
  89. data/lib/samagotchi/web/public/turn_block.js +22 -2
  90. data/lib/samagotchi/web/public/turn_html.js +1 -1
  91. data/lib/samagotchi/web/public/widget_picks.js +3 -0
  92. data/lib/samagotchi/web/public/working_set_view.js +1 -1
  93. data/lib/samagotchi/web/session_access_routes.rb +4 -15
  94. metadata +13 -1
@@ -5,7 +5,7 @@ module Samagotchi
5
5
  # The session's objectives (TurnStages::Objectives, forwarded): the view
6
6
  # announced when it changed, the model's proposals kept as cards until
7
7
  # the turn is over, System 1's audit of them (ObjectivesAudit); and
8
- # Check this's side request. Reads @objectives_stage, @side_judgments,
8
+ # Check this's and the tracker's side requests. Reads @objectives_stage, @side_judgments,
9
9
  # @host_registry, @session.
10
10
  module ObjectivesPart
11
11
  # The session's objectives as the page draws them, when that differs
@@ -36,6 +36,15 @@ module Samagotchi
36
36
  cancel_controller: nil, model: model, source: ObjectivesCheck::SOURCE)
37
37
  end
38
38
 
39
+ # The tracker (ObjectivesTrack)'s one side request, under its own kind so
40
+ # /stats counts it apart. +cancel_controller+: the automatic read's, which
41
+ # the owner's next turn cancels (raises LLM::RequestCancelled then).
42
+ # @return [String] the answer
43
+ def ask_objective_track(request, model:, cancel_controller: nil)
44
+ ask_side_model(request, timeout: ObjectivesTrack::TIMEOUT_SECONDS, max_tokens: ObjectivesTrack::MAX_TOKENS,
45
+ cancel_controller: cancel_controller, model: model, source: ObjectivesTrack::SOURCE)
46
+ end
47
+
39
48
  # A change the model proposes (the objectives tool), kept until the turn
40
49
  # is over (TurnStages::Objectives#propose).
41
50
  # @return [Boolean] false past Objectives::PROPOSALS_PER_TURN
@@ -55,6 +64,16 @@ module Samagotchi
55
64
  Log.warn(:turn, "objectives_proposal_failed", error: e.class.name, msg: e.message)
56
65
  end
57
66
 
67
+ # After a completed turn (#complete_turn, beside the stage's outgoing):
68
+ # with objectives.tracker on, the tracker by itself, when the turn did
69
+ # work and recorded no move (TurnStages::Objectives#track). It only
70
+ # informs: a failure is logged.
71
+ def track_objectives_after(turn)
72
+ @objectives_stage.track(turn, engine: self)
73
+ rescue StandardError => e
74
+ Log.warn(:turn, "objectives_track_start_failed", error: e.class.name, msg: e.message)
75
+ end
76
+
58
77
  # The stage over this Engine's side asks (built in #initialize, once
59
78
  # the host registry is). Each call takes its values: the recorder,
60
79
  # the sessions dir, the running conversation.
@@ -41,8 +41,9 @@ module Samagotchi
41
41
  # command's ask_model between turns).
42
42
  # @return [String, nil]
43
43
  def side_author(kind)
44
- # Check this is only ever the owner's, whichever turn runs as it ends.
45
- return nil if kind.to_s == ObjectivesCheck::SOURCE
44
+ # Check this and the tracker are only ever the owner's, whichever turn
45
+ # runs as they end.
46
+ return nil if [ObjectivesCheck::SOURCE, ObjectivesTrack::SOURCE].include?(kind.to_s)
46
47
 
47
48
  # One read each of the published contexts (TurnState): any thread.
48
49
  running = turn_context
@@ -117,7 +117,10 @@ module Samagotchi
117
117
  # a display version of the answer (AnswerDisplay) and event[:refs]
118
118
  # for refs on it (AnswerRefs).
119
119
  session = turn.session
120
- @objectives_stage.outgoing(turn, result, recorder: system_one_recorder) unless canceled || result.exhausted?
120
+ unless canceled || result.exhausted?
121
+ @objectives_stage.outgoing(turn, result, recorder: system_one_recorder)
122
+ track_objectives_after(turn)
123
+ end
121
124
  display = AnswerDisplay.new(session.messages)
122
125
  refs = AnswerRefs.new(session.messages, cwd: session.working_directory)
123
126
  after_turn = { type: :after_turn, status: canceled ? "canceled" : "completed",
@@ -974,6 +974,9 @@ module Samagotchi
974
974
  # cross-thread state is set here and cleared in #release_turn only.
975
975
  def begin_turn(session, prompt, on_event:, cancel_controller:, origin:, continue:, id: nil, verify: nil, revises: nil,
976
976
  input_waiting: nil)
977
+ # The tracker's automatic read still out: any turn's start frees its
978
+ # request first, before this turn's own probes and waits.
979
+ @objectives_stage.cancel_track
977
980
  origin = TurnOrigin.of(origin)
978
981
  # A participant's Verify fresh child: every turn is theirs (their
979
982
  # author, boundary and cap), whoever started it.
@@ -33,15 +33,9 @@ module Samagotchi
33
33
  end
34
34
 
35
35
  # The hooks: config.yml's (Hooks::Loader; an empty Registry without a
36
- # hooks config). An installed record that still has class-file hooks (a
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;
39
- # compat shim retired_class_file_hooks: Compat::SHIMS).
36
+ # hooks config).
40
37
  # @return [Hooks::Registry]
41
- def hooks
42
- tell_retired_hooks
43
- hooks_from_config
44
- end
38
+ def hooks = hooks_from_config
45
39
 
46
40
  # Load the installed bundles' plugins into +registries+; one that fails
47
41
  # goes to +failures+, a required one (a guardrail plugin) to the hook
@@ -71,23 +65,5 @@ module Samagotchi
71
65
 
72
66
  Hooks::Registry.new
73
67
  end
74
-
75
- # One failure per record whose hooks: map isn't empty; an empty
76
- # hooks/ dir is not one, nor a manifest.json that doesn't read (the
77
- # plugin loader and the rules report that: a record holding only hooks/
78
- # with an unreadable manifest.json is silent at start, as its hooks
79
- # wouldn't load anyway; `chi bundle status` lists it unreadable).
80
- def tell_retired_hooks
81
- require_relative "memory_bundle/provenance"
82
- MemoryBundle::Provenance.each_installed(holding: :hooks) do |bundle_name, bundle|
83
- next if bundle.error?
84
-
85
- Log.warn(:hooks, "bundle_hooks_retired", bundle: bundle_name, hooks: bundle.hooks.size)
86
- @hook_failures.add("hooks (bundle #{bundle_name})", MemoryBundle::Manifest::HooksRetired::WORDS, required: false)
87
- end
88
- rescue StandardError => e
89
- Log.error(:hooks, "bundles_load_failed", echo: "[samagotchi:hooks] failed to read the installed bundles: #{e.class}: #{e.message}",
90
- error: e.class.name)
91
- end
92
68
  end
93
69
  end
@@ -28,12 +28,10 @@ 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 bare list of entries (what 0.166 and before wrote) is not
34
+ # a versioned store: it is set aside like an unreadable file.
37
35
  class Approvals
38
36
  FILE = "approvals.json"
39
37
  COLLECTION = "approvals"
@@ -169,7 +167,7 @@ module Samagotchi
169
167
 
170
168
  # @param locked [Boolean] the caller holds the store's lock
171
169
  # @return [Array(Array<Hash>, StateFormat::Document)] the entries and,
172
- # for a versioned store, its document (nil for a list or no file)
170
+ # its document (nil when there is no file)
173
171
  def read(locked: false)
174
172
  return [[], nil] unless File.exist?(@path)
175
173
 
@@ -201,12 +199,14 @@ module Samagotchi
201
199
  # An entry it can't read (no scope) is kept as it is: it matches
202
200
  # nothing, and a write keeps it for the chi that wrote it.
203
201
  [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"
202
+ else raise JSON::ParserError, "not a versioned store"
207
203
  end
208
204
  end
209
205
 
206
+ def write(document)
207
+ AtomicFile.write(@path, JSON.pretty_generate(FORMAT.write(document, collection: COLLECTION, updated_at: nil)))
208
+ end
209
+
210
210
  # Under the lock: rename the file aside if it is still unreadable.
211
211
  # @return [String, :readable] where it went; :readable when another
212
212
  # process replaced or removed it meanwhile
@@ -237,16 +237,15 @@ module Samagotchi
237
237
  end
238
238
  end
239
239
 
240
- # Writes the shape it read: a versioned store keeps its version and
241
- # the keys this chi doesn't know.
240
+ # Writes the versioned store: one read keeps its version and the
241
+ # keys this chi doesn't know; no file (or one that couldn't be
242
+ # rewritten on read) starts at FORMAT's version.
242
243
  def update
243
244
  with_lock do
244
245
  list, document = read(locked: true)
245
246
  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))
247
+ document ||= FORMAT.read({}, collection: COLLECTION)
248
+ write(document.with(entries: list))
250
249
  end
251
250
  end
252
251
 
@@ -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