samagotchi 0.194.0 → 0.195.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 (82) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +40 -1
  3. data/docs/bundle-authoring.md +1 -1
  4. data/docs/bundles.md +192 -6
  5. data/docs/cli.md +1 -1
  6. data/docs/configuration.md +25 -4
  7. data/docs/internals/attached-context.md +2 -0
  8. data/docs/internals/bridge.md +4 -0
  9. data/docs/internals/engine.md +13 -1
  10. data/docs/internals/knowledge.md +205 -0
  11. data/docs/internals/pages.md +17 -9
  12. data/docs/internals/panes.md +51 -13
  13. data/docs/internals/peers.md +2 -1
  14. data/docs/memory.md +4 -2
  15. data/docs/pages.md +72 -1
  16. data/docs/peers.md +24 -13
  17. data/docs/plugins.md +59 -3
  18. data/docs/releasing.md +1 -1
  19. data/docs/scheduling.md +4 -0
  20. data/docs/sessions.md +8 -1
  21. data/docs/testing.md +3 -1
  22. data/lib/samagotchi/bundles/claude-peer/manifest.yml +8 -5
  23. data/lib/samagotchi/bundles/claude-peer/plugin.rb +2 -2
  24. data/lib/samagotchi/bundles/codex-peer/manifest.yml +8 -5
  25. data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
  26. data/lib/samagotchi/bundles/coordinator/manifest.yml +7 -4
  27. data/lib/samagotchi/bundles/coordinator/plugin.rb +15 -5
  28. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +10 -0
  29. data/lib/samagotchi/bundles/dev/manifest.yml +3 -2
  30. data/lib/samagotchi/bundles/knowledge/adapters.rb +205 -0
  31. data/lib/samagotchi/bundles/knowledge/catalog.rb +151 -0
  32. data/lib/samagotchi/bundles/knowledge/chi_adapters.rb +160 -0
  33. data/lib/samagotchi/bundles/knowledge/chunker.rb +55 -0
  34. data/lib/samagotchi/bundles/knowledge/github.rb +246 -0
  35. data/lib/samagotchi/bundles/knowledge/manifest.yml +25 -0
  36. data/lib/samagotchi/bundles/knowledge/plugin.rb +788 -0
  37. data/lib/samagotchi/bundles/knowledge/query.rb +30 -0
  38. data/lib/samagotchi/bundles/knowledge/query_log.rb +55 -0
  39. data/lib/samagotchi/bundles/knowledge/refresh.rb +133 -0
  40. data/lib/samagotchi/bundles/knowledge/store.rb +264 -0
  41. data/lib/samagotchi/bundles/reflect/manifest.yml +17 -0
  42. data/lib/samagotchi/bundles/reflect/scripts/reflect.rb +439 -0
  43. data/lib/samagotchi/bundles/reflect/skill_reflect.md +100 -0
  44. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  45. data/lib/samagotchi/guardrails/review_paths.rb +13 -3
  46. data/lib/samagotchi/guardrails_command.rb +3 -9
  47. data/lib/samagotchi/hook_label.rb +19 -0
  48. data/lib/samagotchi/hook_routes.rb +3 -2
  49. data/lib/samagotchi/page_command.rb +90 -6
  50. data/lib/samagotchi/pages/launch.rb +16 -8
  51. data/lib/samagotchi/pages/runner.rb +7 -2
  52. data/lib/samagotchi/pages/runtime.rb +62 -2
  53. data/lib/samagotchi/pages.rb +4 -0
  54. data/lib/samagotchi/panes/kitty.rb +20 -5
  55. data/lib/samagotchi/panes.rb +81 -12
  56. data/lib/samagotchi/plugin/api.rb +7 -1
  57. data/lib/samagotchi/plugin/attached_context.rb +46 -1
  58. data/lib/samagotchi/plugin/context.rb +24 -7
  59. data/lib/samagotchi/plugin/panes.rb +52 -9
  60. data/lib/samagotchi/plugin/peer_start.rb +60 -35
  61. data/lib/samagotchi/plugin/peers.rb +1 -1
  62. data/lib/samagotchi/plugin/project.rb +63 -0
  63. data/lib/samagotchi/plugin/sessions.rb +36 -1
  64. data/lib/samagotchi/plugin/tool_spec.rb +16 -7
  65. data/lib/samagotchi/session.rb +22 -9
  66. data/lib/samagotchi/session_stats.rb +436 -0
  67. data/lib/samagotchi/session_window.rb +30 -0
  68. data/lib/samagotchi/system_one/approval_choice.rb +22 -0
  69. data/lib/samagotchi/system_one/approval_label.rb +4 -6
  70. data/lib/samagotchi/system_prompt.rb +3 -1
  71. data/lib/samagotchi/terminal_ui/attach_launcher.rb +30 -0
  72. data/lib/samagotchi/testing/boundary.rb +17 -4
  73. data/lib/samagotchi/testing/sessions.rb +11 -3
  74. data/lib/samagotchi/toolkit.rb +11 -4
  75. data/lib/samagotchi/toolkit_report_command.rb +14 -18
  76. data/lib/samagotchi/toolkit_suggest.rb +9 -2
  77. data/lib/samagotchi/tools/registry.rb +43 -18
  78. data/lib/samagotchi/tools/tool_index.rb +6 -2
  79. data/lib/samagotchi/turn_excerpts.rb +298 -0
  80. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +9 -0
  81. data/lib/samagotchi/version.rb +1 -1
  82. metadata +22 -1
@@ -0,0 +1,439 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The Reflect page (#/p/reflect, chi page run reflect), from the reflect
4
+ # bundle (docs/bundles.md, "The reflect bundle"): how one project's sessions
5
+ # went over the last 14 days and the last 24 hours, and the worst turns'
6
+ # failing calls. Read-only, no model: counts from runtime.sessions, the
7
+ # failing calls from runtime.turn_excerpts. To make it your own, copy this
8
+ # file to ~/.config/samagotchi/pages/reflect.rb (chi page list --format json
9
+ # gives its path as script) and change it: yours replaces this one.
10
+ #
11
+ # Which project: the folder `chi page run` was typed in (runtime.launch_dir),
12
+ # else the newest session you started (chi web's Refresh has no folder).
13
+ # config.yml `bundles: reflect:` takes include_text (each worst turn's
14
+ # prompt and answer) and mask_names (MCP names and the project masked, no
15
+ # failing calls: keeps your other sessions' failing-call text off the page).
16
+ #
17
+ # The text reads as plain text too (chi web's Markdown is off by default): no
18
+ # headings or bold, only `code`. A table has no title of its own, so each
19
+ # table's first column is named for the table: `chi page run reflect
20
+ # --format lines` shows a reader only the labels.
21
+
22
+ require "time"
23
+
24
+ DAY = 86_400
25
+ # Rows a table shows; the rest are counted in its total (Tools, Approvals).
26
+ TOOL_ROWS = 15
27
+ RULE_ROWS = 15
28
+ PLUGIN_ROWS = 10
29
+ MODEL_ROWS = 10
30
+ WORST_SESSIONS = 10
31
+ # The worst turns whose failing calls the page asks for.
32
+ WORST_TURNS = 12
33
+ # How long a name a cell keeps (an MCP tool, a rule, a bundle, a model).
34
+ NAME_CHARS = 60
35
+ # The page's budget as `--format lines` prints it (40,000 characters and 60
36
+ # KB, what one execute output keeps whole), with a margin for the lines this
37
+ # estimate doesn't count. Past it, the page asks for half the turns, twice
38
+ # at most.
39
+ BUDGET_CHARS = 36_000
40
+ BUDGET_BYTES = 54 * 1024
41
+ HALVINGS = 2
42
+ CELL_CHARS = 300
43
+
44
+ # The helpers below are the script's own (the runner's wrap module keeps
45
+ # them off Object), so the classes after them don't see them.
46
+ def cut(text, chars) = text.size > chars ? "#{text[0, chars - 1]}…" : text
47
+
48
+ def plural(count, word) = "#{count} #{word}#{"s" unless count == 1}"
49
+
50
+ def time_of(iso)
51
+ iso.is_a?(String) ? Time.iso8601(iso) : nil
52
+ rescue ArgumentError
53
+ nil
54
+ end
55
+
56
+ # A time as the page shows it, in this machine's zone; nil for none.
57
+ def clock(iso)
58
+ at = iso.is_a?(Time) ? iso : time_of(iso)
59
+ at&.localtime&.strftime("%Y-%m-%d %H:%M")
60
+ end
61
+
62
+ def day(iso) = time_of(iso)&.localtime&.strftime("%Y-%m-%d")
63
+
64
+ def pct(part, whole) = whole.zero? ? nil : (100.0 * part / whole).round(1)
65
+
66
+ def median(values)
67
+ return nil if values.empty?
68
+
69
+ sorted = values.sort
70
+ mid = sorted.size / 2
71
+ sorted.size.odd? ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2.0
72
+ end
73
+
74
+ def sum_hashes(hashes)
75
+ hashes.each_with_object(Hash.new(0)) { |hash, sums| hash.each { |key, n| sums[key] += n } }
76
+ end
77
+
78
+ # Owner-written MCP names (an mcp__ tool, a <server>/<tool> name) as mcp:1,
79
+ # mcp:2, … in the order they first show on the page, when masked; every
80
+ # other name cut. call_tool is chi's own tool and stays.
81
+ class Names
82
+ def initialize(mask)
83
+ @mask = mask
84
+ @masks = {}
85
+ end
86
+
87
+ def mask? = @mask
88
+
89
+ def self.mcp?(name) = name.start_with?("mcp__") || name.include?("/")
90
+
91
+ def show(name)
92
+ name = name.to_s
93
+ return name.size > NAME_CHARS ? "#{name[0, NAME_CHARS - 1]}…" : name unless @mask && Names.mcp?(name)
94
+
95
+ @masks[name] ||= "mcp:#{@masks.size + 1}"
96
+ end
97
+ end
98
+
99
+ # The page's blocks, kept as data until the end: the budget is checked on
100
+ # them before ui draws them.
101
+ class Blocks
102
+ attr_reader :list
103
+
104
+ def initialize = @list = []
105
+
106
+ def text(text) = @list << [:text, text]
107
+
108
+ def table(rows, columns:, **options)
109
+ # As the table stores them (at most CELL_CHARS), so the size is right.
110
+ rows = rows.map { |row| row.transform_values { |v| v.is_a?(String) && v.size > CELL_CHARS ? "#{v[0, CELL_CHARS - 1]}…" : v } }
111
+ @list << [:table, rows, { columns: columns, **options }]
112
+ end
113
+
114
+ # About what `--format lines` prints of them: [characters, bytes].
115
+ def size
116
+ lines = @list.flat_map do |kind, data, options|
117
+ next data.split("\n", -1) if kind == :text
118
+
119
+ cells = ->(row) { options[:columns].keys.map { |key| cell(row[key]) }.join(" | ") }
120
+ [options[:columns].values.join(" | "), *data.map(&cells), *(cells.call(options[:total]) if options[:total])]
121
+ end
122
+ lines += @list.map { "== block 00: table" }
123
+ [lines.sum { |line| line.size + 1 }, lines.sum { |line| line.bytesize + 1 }]
124
+ end
125
+
126
+ def over? = size.then { |chars, bytes| chars > BUDGET_CHARS || bytes > BUDGET_BYTES }
127
+
128
+ def draw(ui)
129
+ @list.each { |kind, data, options| kind == :text ? ui.text(data) : ui.table(data, **options) }
130
+ end
131
+
132
+ private
133
+
134
+ def cell(value)
135
+ case value
136
+ when nil then "—"
137
+ when Float then format("$%.4f", value)
138
+ else value.to_s
139
+ end
140
+ end
141
+ end
142
+
143
+ # One turn with its session.
144
+ Turn = Struct.new(:session, :counts, :at) do
145
+ def failed? = counts.status == "failed"
146
+ def you? = counts.cancel == "you"
147
+ end
148
+
149
+ def turn_row(label, turns, lines: nil, recent: false)
150
+ row = { "what" => label, "turns" => turns.size, "failed" => turns.count(&:failed?),
151
+ "failed_pct" => pct(turns.count(&:failed?), turns.size), "you" => turns.count(&:you?),
152
+ "hook" => turns.count { |t| t.counts.cancel == "hook" },
153
+ "interrupted" => turns.count { |t| t.counts.cancel == "interrupted" }, "lines" => lines }
154
+ return row unless recent
155
+
156
+ row.merge("tool_errors" => turns.sum { |t| t.counts.tool_errors.to_i }, "cost" => turns.sum { |t| t.counts.cost.to_f })
157
+ end
158
+
159
+ TURN_COLUMNS = { "failed" => "Failed", "failed_pct" => "Failed %", "you" => "Canceled by you", "hook" => "Canceled by a hook",
160
+ "interrupted" => "Interrupted" }.freeze
161
+
162
+ def turn_table(blocks, label, turns, lines:, recent: false)
163
+ # A phone shows no column labels: the 24-hour rows say their window.
164
+ window = recent ? ", 24 hours" : ""
165
+ rows = [turn_row("person turns#{window}", turns.reject { |t| t.counts.automatic }, recent: recent),
166
+ turn_row("automatic turns#{window}", turns.select { |t| t.counts.automatic }, recent: recent),
167
+ turn_row("all#{window}", turns, lines: lines, recent: recent)]
168
+ columns = { "what" => label, "turns" => "Turns", **TURN_COLUMNS, "lines" => "Mid-turn lines from you" }
169
+ columns.merge!("tool_errors" => "Tool errors", "cost" => "Cost") if recent
170
+ blocks.table rows, columns: columns, key: %w[turns failed], format: recent ? { "cost" => :money } : {}
171
+ end
172
+
173
+ # The worst turns, at most WORST_TURNS, no repeats: every failed turn of the
174
+ # last day; the most tool errors (the last day first); canceled by you; the
175
+ # other failed turns.
176
+ def worst_turns(turns, recent_since)
177
+ recent = ->(t) { t.at && t.at >= recent_since }
178
+ newest = ->(list) { list.sort_by { |t| -(t.at || Time.at(0)).to_f } }
179
+ errors = turns.select { |t| t.counts.tool_errors.to_i.positive? }
180
+ by_errors = ->(list) { list.sort_by { |t| [-t.counts.tool_errors.to_i, -(t.at || Time.at(0)).to_f] } }
181
+ picked = newest.call(turns.select { |t| t.failed? && recent.call(t) }) +
182
+ by_errors.call(errors.select(&recent)) + by_errors.call(errors.reject(&recent)) +
183
+ newest.call(turns.select(&:you?)) + newest.call(turns.select(&:failed?))
184
+ picked.uniq { |t| [t.session.id, t.counts.id] }.first(WORST_TURNS)
185
+ end
186
+
187
+ def failing_rows(result, names)
188
+ result.excerpts.flat_map do |excerpt|
189
+ base = { "session" => excerpt.session_id.to_s[0, 8], "turn" => excerpt.turn_id.to_s[0, 8], "when" => clock(excerpt.started_at) }
190
+ calls = excerpt.calls.map do |call|
191
+ tool = call.target ? "#{names.show(call.tool)} → #{call.target}" : names.show(call.tool)
192
+ base.merge("tool" => tool, "status" => excerpt.paired ? call.status : "#{call.status} (unpaired)",
193
+ "args" => call.args, "result" => call.result)
194
+ end
195
+ calls + (excerpt.failure ? [base.merge("tool" => "turn failed", "status" => excerpt.status, "result" => excerpt.failure)] : [])
196
+ end
197
+ end
198
+
199
+ settings = runtime.settings
200
+ include_text = settings["include_text"] == true
201
+ names = Names.new(settings["mask_names"] == true)
202
+ list = runtime.sessions(project: runtime.launch_dir)
203
+ now = Time.now
204
+ since = time_of(list.since) || (now - (14 * DAY))
205
+ recent_since = now - DAY
206
+
207
+ # The reflect chain's own sessions (its links and its anchor, the first
208
+ # manual run) aren't counted: a reflect schedule is one titled "reflect…".
209
+ schedules_note = nil
210
+ reflect = begin
211
+ runtime.schedules.select { |schedule| schedule.title.to_s.downcase.start_with?("reflect") }
212
+ rescue StandardError => e
213
+ schedules_note = "Reflect sessions aren't left out: #{cut(e.message.to_s, 200)}"
214
+ []
215
+ end
216
+ reflect_ids = reflect.map(&:id)
217
+ anchors = reflect.map(&:anchor)
218
+ sessions = list.sessions.reject { |s| reflect_ids.include?(s.schedule_id) || anchors.include?(s.id) }
219
+ left_out = list.sessions.size - sessions.size
220
+
221
+ project = list.project
222
+ project_words = if project.nil? then nil
223
+ elsif names.mask? then "this project"
224
+ else "#{project.name} (#{project.path})"
225
+ end
226
+ title = if project.nil?
227
+ "Reflect"
228
+ else
229
+ "Reflect: #{names.mask? ? "this project" : project.name}"
230
+ end
231
+ picked = { "folder" => "the folder chi page run was typed in", "newest" => "the newest session you started" }[list.picked_by]
232
+
233
+ page title do |ui|
234
+ if project.nil? || sessions.empty?
235
+ head = project ? "Project #{project_words}, picked by #{picked}.\n\n" : ""
236
+ note = left_out.positive? ? " (#{plural(left_out, "reflect session")} left out)" : ""
237
+ ui.text "#{head}No sessions in the last 14 days#{note}."
238
+ next
239
+ end
240
+
241
+ blocks = Blocks.new
242
+ turns = sessions.flat_map { |s| s.turns.map { |t| Turn.new(s, t, time_of(t.started_at)) } }
243
+ recent = turns.select { |t| t.at && t.at >= recent_since }
244
+
245
+ # 1. The header.
246
+ delegates = sessions.count(&:delegate)
247
+ links = sessions.count(&:chain_link)
248
+ header = ["Project #{project_words}, picked by #{picked}.",
249
+ "Last 14 days since #{day(list.since)}; last 24 hours since #{clock(recent_since)}.",
250
+ "#{plural(sessions.size, "session")} (#{plural(delegates, "delegate")}, #{plural(links, "chain link")})" \
251
+ "#{"; #{plural(left_out, "reflect session")} left out" if left_out.positive?}" \
252
+ "#{"; at most #{sessions.size + left_out} sessions read" if list.sessions_capped}."]
253
+ others = list.projects
254
+ unless others.empty?
255
+ header << if names.mask?
256
+ "#{plural(others.size, "other project")} in the window."
257
+ else
258
+ "Other projects: #{others.first(10).map { |p| "#{cut(p.name, NAME_CHARS)} (#{p.session_count})" }.join(", ")}" \
259
+ "#{", and #{others.size - 10} more" if others.size > 10}."
260
+ end
261
+ end
262
+ header << "#{plural(list.unreadable, "file")} didn't read." if list.unreadable.positive?
263
+ header << schedules_note if schedules_note
264
+ blocks.text header.join("\n")
265
+
266
+ # 2-3. Turns, over 14 days and the last 24 hours.
267
+ turn_table(blocks, "Turns (14 days)", turns, lines: sessions.sum(&:mid_turn_lines))
268
+ turn_table(blocks, "Last 24 hours", recent, lines: nil, recent: true)
269
+
270
+ # 4. Failures by kind; clean since: the turns of its last session after it that didn't fail.
271
+ failed = turns.select(&:failed?)
272
+ unless failed.empty?
273
+ rows = failed.group_by { |t| t.counts.failure_kind.to_s }.map do |kind, list_of|
274
+ last = list_of.max_by { |t| t.at.to_f }
275
+ after = turns.select { |t| t.session.equal?(last.session) && t.at && last.at && t.at > last.at && !t.failed? }
276
+ { "kind" => kind, "failed" => list_of.size, "recent" => list_of.count { |t| recent.include?(t) },
277
+ "last" => clock(last.at), "models" => list_of.map { |t| t.counts.model.to_s }.uniq.sort.join(", "),
278
+ "clean" => after.size, "_at" => last.at.to_f }
279
+ end
280
+ rows = rows.sort_by { |row| [-row["_at"], row["kind"]] }.map { |row| row.except("_at") }
281
+ blocks.table rows, columns: { "kind" => "Failure", "failed" => "Failed (14 days)", "recent" => "Failed (24 hours)",
282
+ "last" => "Last seen", "models" => "Models", "clean" => "Clean since" },
283
+ key: %w[failed last]
284
+ end
285
+
286
+ # 5. Tools with an error; clean since: that tool's calls after its last error, project-wide.
287
+ calls = sum_hashes(sessions.map(&:tool_calls_by_tool))
288
+ errors = sum_hashes(sessions.map(&:tool_errors_by_tool))
289
+ unless errors.empty?
290
+ rows = errors.sort_by { |tool, n| [-n, tool] }.first(TOOL_ROWS).map do |tool, n|
291
+ erred = turns.select { |t| t.counts.tool_errors_by_tool[tool].to_i.positive? }
292
+ last = erred.max_by { |t| t.at.to_f }&.at
293
+ clean = last ? turns.select { |t| t.at && t.at > last }.sum { |t| t.counts.tool_calls_by_tool[tool].to_i } : nil
294
+ { "tool" => names.show(tool), "calls" => calls[tool], "errors" => n, "pct" => pct(n, calls[tool]),
295
+ "recent" => recent.sum { |t| t.counts.tool_errors_by_tool[tool].to_i }, "last" => clock(last), "clean" => clean }
296
+ end
297
+ all_calls = calls.values.sum
298
+ all_errors = errors.values.sum
299
+ blocks.table rows, columns: { "tool" => "Tool", "calls" => "Calls", "errors" => "Errors", "pct" => "Error %",
300
+ "recent" => "Errors (24 hours)", "last" => "Last seen", "clean" => "Clean since" },
301
+ format: { "calls" => :count, "errors" => :count }, key: %w[errors last],
302
+ total: { "tool" => "all tools (#{errors.size} with errors)", "calls" => all_calls,
303
+ "errors" => all_errors, "pct" => pct(all_errors, all_calls),
304
+ "recent" => recent.sum { |t| t.counts.tool_errors.to_i } }
305
+ end
306
+
307
+ # 6. Approvals by rule, blocked and auto-allowed.
308
+ rules = sessions.each_with_object({}) do |s, sums|
309
+ s.approvals_by_rule.each do |rule, counts|
310
+ row = sums[rule] ||= Hash.new(0)
311
+ counts.each { |key, n| row[key] += n }
312
+ end
313
+ end
314
+ guard = "#{plural(sessions.sum(&:blocked), "call")} blocked (every guardrail deny: a rule, a hook, you, a parent, the " \
315
+ "toolkit), #{sessions.sum(&:auto_allowed)} allowed by System 1."
316
+ cap = sessions.any?(&:cards_at_cap) ? "At least: a session's cards keep only the last 20 questions and cards.\n" : ""
317
+ if rules.empty?
318
+ blocks.text "#{cap}No approvals asked. #{guard}"
319
+ else
320
+ approval_columns = { "asked" => "Asked", "once" => "Once", "wide" => "Wide", "denied" => "Denied",
321
+ "unanswered" => "Unanswered", "by_parent" => "By a parent" }
322
+ rows = rules.sort_by { |rule, counts| [-counts["asked"], rule] }.first(RULE_ROWS).map do |rule, counts|
323
+ { "rule" => cut(rule, NAME_CHARS), **approval_columns.keys.to_h { |key| [key, counts[key]] } }
324
+ end
325
+ total = approval_columns.keys.to_h { |key| [key, rules.values.sum { |counts| counts[key] }] }
326
+ blocks.table rows, columns: { "rule" => "Approval rule", **approval_columns }, key: %w[asked denied],
327
+ total: { "rule" => "all rules (#{rules.size})", **total }
328
+ blocks.text "#{cap}#{guard}"
329
+ end
330
+
331
+ # 7. Plugins: hook notices, steers and the turns a hook cancelled, by bundle.
332
+ notices = sum_hashes(sessions.map(&:hook_notices_by_bundle))
333
+ steers = sum_hashes(sessions.map(&:steers_by_source))
334
+ cancels = turns.filter_map { |t| t.counts.cancel_bundle if t.counts.cancel == "hook" }.tally
335
+ bundles = (notices.keys + steers.keys + cancels.keys).uniq
336
+ unless bundles.empty?
337
+ rows = bundles.map { |b| { "bundle" => names.show(b), "notices" => notices[b], "steers" => steers[b], "cancels" => cancels[b] || 0 } }
338
+ .sort_by { |row| [-(row["notices"] + row["steers"] + row["cancels"]), row["bundle"]] }
339
+ blocks.table rows.first(PLUGIN_ROWS), columns: { "bundle" => "Plugin", "notices" => "Hook notices", "steers" => "Steers",
340
+ "cancels" => "Turns it cancelled" },
341
+ key: %w[notices steers]
342
+ blocks.text "At least: a session's cards keep only the last 20 notices." if sessions.any?(&:notices_at_cap)
343
+ end
344
+
345
+ # 8. By day (turn cost only).
346
+ rows = turns.group_by { |t| day(t.counts.started_at) }.sort_by { |d, _| d.to_s }.reverse.map do |d, of_day|
347
+ { "day" => d, "turns" => of_day.size, "failed" => of_day.count(&:failed?), "you" => of_day.count(&:you?),
348
+ "errors" => of_day.sum { |t| t.counts.tool_errors.to_i }, "cost" => of_day.sum { |t| t.counts.cost.to_f } }
349
+ end
350
+ blocks.table rows, columns: { "day" => "Day", "turns" => "Turns", "failed" => "Failed", "you" => "Canceled by you",
351
+ "errors" => "Tool errors", "cost" => "Cost" },
352
+ format: { "cost" => :money }, key: %w[turns failed]
353
+
354
+ # 9. By model.
355
+ by_model = turns.group_by { |t| t.counts.model.to_s.empty? ? "(none)" : t.counts.model }
356
+ rows = by_model.sort_by { |model, of_model| [-of_model.size, model] }.first(MODEL_ROWS).map do |model, of_model|
357
+ used = of_model.filter_map { |t| t.counts.context_used_tokens }
358
+ windows = of_model.map(&:session).uniq.filter_map(&:context_window)
359
+ { "model" => names.show(model), "turns" => of_model.size, "failed_pct" => pct(of_model.count(&:failed?), of_model.size),
360
+ "error_pct" => pct(of_model.sum { |t| t.counts.tool_errors.to_i }, of_model.sum { |t| t.counts.tool_calls.to_i }),
361
+ "cost" => of_model.sum { |t| t.counts.cost.to_f }, "median" => median(used)&.round, "max" => used.max, "window" => windows.max }
362
+ end
363
+ blocks.table rows, columns: { "model" => "Model", "turns" => "Turns", "failed_pct" => "Failed %", "error_pct" => "Tool error %",
364
+ "cost" => "Cost", "median" => "Context, median", "max" => "Context, max",
365
+ "window" => "Context window" },
366
+ format: { "cost" => :money, "median" => :count, "max" => :count, "window" => :count },
367
+ key: %w[turns failed_pct]
368
+
369
+ # 10. Worst sessions: failed turns, then canceled by you, tool errors, cost.
370
+ worst = sessions.reject { |s| s.turns.empty? }.map do |s|
371
+ [s, s.turns.count { |t| t.status == "failed" }, s.turns.count { |t| t.cancel == "you" },
372
+ s.turns.sum { |t| t.tool_errors.to_i }, s.turns.sum { |t| t.cost.to_f }]
373
+ end
374
+ worst = worst.sort_by { |s, f, y, e, c| [-f, -y, -e, -c, s.id] }.first(WORST_SESSIONS)
375
+ rows = worst.map do |s, f, y, e, c|
376
+ { "session" => s.id, "failed" => f, "you" => y, "errors" => e, "cost" => c, "turns" => s.turns.size,
377
+ "model" => names.show(s.model_name), "updated" => clock(s.updated_at),
378
+ "context" => s.turns.filter_map(&:context_used_tokens).max }
379
+ end
380
+ blocks.table rows, columns: { "session" => "Worst session", "failed" => "Failed", "you" => "Canceled by you",
381
+ "errors" => "Tool errors", "cost" => "Cost", "turns" => "Turns", "model" => "Model",
382
+ "updated" => "Updated", "context" => "Context, max" },
383
+ format: { "cost" => :money, "context" => :count }, key: %w[failed errors]
384
+
385
+ # 11-12. The worst turns' failing calls (and, with include_text, their text).
386
+ # Kept apart until the budget check: they are the part that can grow.
387
+ tail = lambda do |pairs, asked|
388
+ part = Blocks.new
389
+ if names.mask?
390
+ part.text "Failing calls are left out (reflect.mask_names): it keeps your other sessions' failing-call text off the page."
391
+ next part
392
+ end
393
+ next part if pairs.empty?
394
+
395
+ result = runtime.turn_excerpts(pairs, include_text: include_text)
396
+ rows = failing_rows(result, names)
397
+ unless rows.empty?
398
+ part.table rows, columns: { "session" => "Failing call: session", "turn" => "Turn", "when" => "When", "tool" => "Tool",
399
+ "status" => "Status", "args" => "Args", "result" => "Result" },
400
+ key: %w[tool status]
401
+ end
402
+ notes = []
403
+ notes << "#{plural(result.left_out, "call")} left out (the ~4k-token cap)." if result.left_out.positive?
404
+ notes << "#{plural(result.unpaired, "turn")} unpaired: their calls by tool, with no args or result." if result.unpaired.positive?
405
+ notes << "#{plural(result.unreadable, "file")} didn't read." if result.unreadable.positive?
406
+ notes << "The worst #{pairs.size} of #{asked} turns, to keep the page in its budget." if pairs.size < asked
407
+ notes = ["No failing calls in the worst #{plural(pairs.size, "turn")}."] if rows.empty? && notes.empty?
408
+ part.text notes.join("\n") unless notes.empty?
409
+ if include_text && !result.excerpts.empty?
410
+ part.table result.excerpts.map { |x|
411
+ { "session" => x.session_id.to_s[0, 8], "turn" => x.turn_id.to_s[0, 8], "prompt" => x.prompt, "answer" => x.answer }
412
+ },
413
+ columns: { "session" => "Turn text: session", "turn" => "Turn", "prompt" => "Prompt", "answer" => "Answer" },
414
+ key: %w[turn prompt]
415
+ end
416
+ part
417
+ end
418
+
419
+ # 13. The cost line and the worst sessions' links.
420
+ turn_cost = turns.sum { |t| t.counts.cost.to_f }
421
+ side = sessions.sum { |s| s.side_cost.to_f }
422
+ older = sessions.any? { |s| (at = time_of(s.created_at)) && at < since }
423
+ cost = ["Cost: turns #{format("$%.4f", turn_cost)} (exact for the window), side requests #{format("$%.4f", side)}, " \
424
+ "total #{format("$%.4f", turn_cost + side)}.#{" Side cost is a session total and includes requests before the window." if older}"]
425
+ cost += ["", "The worst sessions:", *worst.map { |s, *| "- #/s/#{s.id}" }] unless worst.empty?
426
+
427
+ pairs = worst_turns(turns, recent_since).map { |t| [t.session.id, t.counts.id] }
428
+ asked = pairs.size
429
+ part = tail.call(pairs, asked)
430
+ HALVINGS.times do
431
+ break unless pairs.size > 1 && Blocks.new.tap { |all| all.list.concat(blocks.list, part.list) }.over?
432
+
433
+ pairs = pairs.first((pairs.size + 1) / 2)
434
+ part = tail.call(pairs, asked)
435
+ end
436
+ blocks.list.concat(part.list)
437
+ blocks.text cost.join("\n")
438
+ blocks.draw(ui)
439
+ end
@@ -0,0 +1,100 @@
1
+ # Skill: reflect
2
+
3
+ Use when a turn asks you to reflect on this project's last day (a nightly reflect session, its schedule's prompt
4
+ names this skill), or the owner replies in a reflect session ("apply 2", "reject 1 (…)"). You read the project's
5
+ Reflect page, pick at most 3 problems, verify each one on disk, and suggest the exact change. You never apply
6
+ anything on your own: the owner decides.
7
+
8
+ ## Steps
9
+ 1. **Read the page**, from the session's folder (the project), with `execute`, exactly as written, with no
10
+ pipe, `head`, `tail` or redirect: `chi page run reflect --format lines`
11
+ - Exit 1 with "already running": run `sleep 30; chi page run reflect --format lines` once. Any other non-zero
12
+ exit (an `error:` line, then the script's stderr): answer with that error line and the ledger (step 5), and
13
+ stop.
14
+ - The output is longer than a tool result: `execute` shows its head and tail, and its gap line reads
15
+ `[cut: lines A-B of the saved file not shown …; the whole output is saved in PATH (… bytes, N lines) …]`. The
16
+ tail it showed does not count as read. `read` PATH with `start_line`/`end_line`, 30 lines a read (a Failing
17
+ call row is long): the first read's `start_line` is A, and each next read's `start_line` is the previous
18
+ read's `end_line` + 1. A read that ends `[cut: … read it in parts]` stopped early: read the same `start_line`
19
+ again with half as many lines. Stop only when a read reaches line N (its `end_line` is N, or it ends
20
+ `[read: end_line … exceeds N lines; returning lines …-N]`), with no `[cut: …]`. Read every part before you
21
+ judge anything, every night: the carry note is no stand-in for the page. Never run the page again to see the
22
+ rest.
23
+ - Its first line is `page reflect: "Reflect: <project>"`. Check that `<project>` is this folder's name, or
24
+ `this project` (the names are masked). If not, say which project it read, and stop.
25
+ - How to read it: `== block N: TYPE` starts a block; a table is its label line, then one row a line with ` | `
26
+ between cells, the first column naming the row. In a cell `\|` is a `|` and `\\` is a `\`. A line starting
27
+ `\== block ` is text, not a block. The header block says the window; "—" is no value. A `total:` line is
28
+ a table's totals row, and `(N rows dropped)` says the table left N rows out. With `reflect.mask_names` on,
29
+ the page has no Failing call rows: step 4 then works from the counts only.
30
+ 2. **Read the carry note** at the top of this session ("This session continues …"), if there is one. It ends with
31
+ the last answer's ledger (step 5): what you suggested before and what the owner answered.
32
+ - Never suggest again what the owner rejected, unless its count has at least doubled since the count its
33
+ ledger line names.
34
+ - One the owner applied but whose problem still happens (step 4's checks) may be suggested again, as one of
35
+ the 3. One still open is not posted again: it stays in the ledger.
36
+ 3. **Pick at most 3 problems**, the strongest first, from the page's rows:
37
+ - a failure kind in the Failure table seen in the last 24 hours;
38
+ - a tool with at least 3 errors and an error rate above the others' (the Tool table);
39
+ - an approval rule asked at least 5 times and always answered once (a candidate allow rule);
40
+ - repeated cancels by you, or mid-turn lines, in one session;
41
+ - a plugin's hook notice repeated across sessions.
42
+
43
+ Each needs its rows in the page. A problem whose last seen is older than 7 days is weak and comes last.
44
+ 4. For each, **read its Failing call rows** (by tool, by session). Then **verify it before posting**, with these
45
+ calls only: `read PATH`, `memory_read NAME`, and in `execute`: `rg -n PATTERN PATH`, `ls -l PATH`,
46
+ `git log -1 --format=%cI -- PATH`, `chi self` (its `config` row is the config file, `memories` and
47
+ `project memories` the memory folders). Run each check as its own command, in the forms above only: no `cd`,
48
+ `cat`, `&&` or `|`.
49
+ - **The target exists**: the memory or skill (`memory_read NAME`), the file (`read` or `rg`), or the config
50
+ key (`rg -n KEY` on the config file `chi self` names).
51
+ - **The claim matches**: the target's text says, or lacks, what your suggestion says it does. Quote the line.
52
+ - **It still happens**:
53
+ - its "Clean since" in the page is under 3, so it has not run clean 3 times since it was last seen. For a
54
+ tool, weigh it by its Error %: one that errs 4 times in 100 runs some 25 clean calls between errors
55
+ anyway, so its errors are fixed only when Clean since is over 3 × 100 / Error % (over 75 at 4.0);
56
+ - its last seen is after the target's last change: the memory's or config file's time in `ls -l`, or the
57
+ file's last commit (`git log -1 --format=%cI -- PATH`);
58
+ - a failure that names a model (`host_model_not_found`, a model's error): the failing session's Model in the
59
+ Worst session table is still the model the Failure row names. A session now on another model was
60
+ switched: the problem is fixed there.
61
+
62
+ A problem that ran clean since, or that hasn't been seen since the target last changed, is fixed or
63
+ passing: drop it. (One failure, then 14 clean turns in the same session, is a fixed problem.)
64
+
65
+ Drop any candidate that fails a check. Never name a file, memory, key or path you have not read in this
66
+ turn.
67
+ 5. **Post** at most 3 suggestions, then the ledger, and nothing else. Each suggestion has:
68
+ - a number and a one-line title;
69
+ - the evidence: counts, window, last seen, and session ids, 8 characters each;
70
+ - the exact change: the target, its current line(s) quoted, and the new text (or the rule YAML, or the
71
+ command).
72
+
73
+ With nothing left, write "Nothing worth changing today", then at most 3 short `Dropped:` lines (the
74
+ strongest candidates, one line each: what and why it was dropped), then the ledger. Zero suggestions is a good
75
+ night when nothing passes. Never pad to 3.
76
+
77
+ **The ledger** ends every answer, this one and each reply to the owner, so the next night's carry note keeps
78
+ it: `Ledger (open / applied / rejected):`, then one line per item, `- open: <title> (<date>)`,
79
+ `- applied: <title> (<date>)` or `- rejected: <title> (<date>, <count> then): <the owner's why>`. Carry the
80
+ previous ledger's lines forward, add tonight's, and keep at most 10 lines (drop the oldest applied ones first,
81
+ then the oldest rejected). When the open ones alone pass 10, keep the 10 newest open and, after
82
+ them, one line `- dropped: N older open`. With none at all, write `Ledger (open / applied / rejected): none`.
83
+ 6. **Never apply on your own.** No `memory_write`, `write`, `edit`, schedule, `chi send` or other change in the
84
+ reflect turn: it only reads.
85
+ 7. **On the owner's reply** in this session:
86
+ - "apply N": make that one change as asked, under the normal guardrails (the owner's request, not an
87
+ auto-apply). When its tool isn't declared here (the recipe leaves out `edit`, `write` and `memory_write`),
88
+ never work around it with `execute`: say so, and that another session in this project (`chi` in its
89
+ folder) can apply it;
90
+ - "reject N (why)": acknowledge in one line;
91
+ - then end with the ledger, updated (N applied, or rejected with the owner's why).
92
+
93
+ ## Gotchas
94
+ - A model may invent a path (`/root/…`) in a failing call: verify before naming it.
95
+ - A session keeps its model when the served model is swapped, so a fixed config can look live in counts alone:
96
+ check "Clean since" and the last change.
97
+ - Don't repeat advice a tool's own result already gives (`find_tools` already says "call it with call_tool").
98
+ - An approval rule answered "once" every time on a merge, push, sudo or delete is the owner checking each one:
99
+ not a candidate allow rule.
100
+ - This is a shipped skill: don't edit it. When a step doesn't fit what you see, say what differed in the answer.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.194.0
3
+ version: 0.195.0
4
4
  scope: system
5
5
  description: Default system memories — identity, self map, config modification protocol, memory guide and the delegated-session rules
6
6
  files:
@@ -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
@@ -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