samagotchi 0.194.0 → 0.196.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +80 -1
  3. data/docs/architecture.md +2 -1
  4. data/docs/bundle-authoring.md +23 -23
  5. data/docs/bundles.md +201 -7
  6. data/docs/cli.md +5 -1
  7. data/docs/configuration.md +25 -4
  8. data/docs/context.md +13 -3
  9. data/docs/guardrails.md +6 -4
  10. data/docs/hooks.md +3 -1
  11. data/docs/internals/attached-context.md +2 -0
  12. data/docs/internals/block-renderers.md +4 -1
  13. data/docs/internals/bridge.md +4 -0
  14. data/docs/internals/engine.md +15 -2
  15. data/docs/internals/knowledge.md +215 -0
  16. data/docs/internals/pages.md +17 -9
  17. data/docs/internals/panes.md +51 -13
  18. data/docs/internals/participants.md +15 -3
  19. data/docs/internals/peers.md +14 -9
  20. data/docs/internals/session-lifecycle.md +26 -12
  21. data/docs/internals/web-frontend.md +64 -27
  22. data/docs/memory.md +4 -2
  23. data/docs/pages.md +72 -1
  24. data/docs/peers.md +25 -14
  25. data/docs/plugins.md +132 -6
  26. data/docs/releasing.md +1 -1
  27. data/docs/scheduling.md +4 -0
  28. data/docs/sessions.md +9 -2
  29. data/docs/system-one.md +3 -1
  30. data/docs/testing.md +3 -1
  31. data/lib/samagotchi/bundle_manifest.rb +30 -5
  32. data/lib/samagotchi/bundles/claude-peer/manifest.yml +8 -5
  33. data/lib/samagotchi/bundles/claude-peer/plugin.rb +2 -2
  34. data/lib/samagotchi/bundles/codex-peer/manifest.yml +8 -5
  35. data/lib/samagotchi/bundles/codex-peer/plugin.rb +3 -3
  36. data/lib/samagotchi/bundles/coordinator/manifest.yml +7 -4
  37. data/lib/samagotchi/bundles/coordinator/plugin.rb +15 -5
  38. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +10 -0
  39. data/lib/samagotchi/bundles/core/manifest.yml +2 -2
  40. data/lib/samagotchi/bundles/cost-cap/manifest.yml +4 -4
  41. data/lib/samagotchi/bundles/cost-cap/plugin.rb +54 -3
  42. data/lib/samagotchi/bundles/dev/manifest.yml +3 -2
  43. data/lib/samagotchi/bundles/github-pr/manifest.yml +4 -2
  44. data/lib/samagotchi/bundles/knowledge/adapters.rb +205 -0
  45. data/lib/samagotchi/bundles/knowledge/catalog.rb +151 -0
  46. data/lib/samagotchi/bundles/knowledge/chi_adapters.rb +178 -0
  47. data/lib/samagotchi/bundles/knowledge/chunker.rb +55 -0
  48. data/lib/samagotchi/bundles/knowledge/github.rb +246 -0
  49. data/lib/samagotchi/bundles/knowledge/manifest.yml +27 -0
  50. data/lib/samagotchi/bundles/knowledge/plugin.rb +807 -0
  51. data/lib/samagotchi/bundles/knowledge/query.rb +30 -0
  52. data/lib/samagotchi/bundles/knowledge/query_log.rb +55 -0
  53. data/lib/samagotchi/bundles/knowledge/refresh.rb +133 -0
  54. data/lib/samagotchi/bundles/knowledge/store.rb +264 -0
  55. data/lib/samagotchi/bundles/reflect/manifest.yml +17 -0
  56. data/lib/samagotchi/bundles/reflect/scripts/reflect.rb +439 -0
  57. data/lib/samagotchi/bundles/reflect/skill_reflect.md +100 -0
  58. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  59. data/lib/samagotchi/context_change.rb +44 -0
  60. data/lib/samagotchi/context_note.rb +1 -1
  61. data/lib/samagotchi/context_providers.rb +14 -0
  62. data/lib/samagotchi/context_sources.rb +3 -25
  63. data/lib/samagotchi/engine/plugins.rb +21 -0
  64. data/lib/samagotchi/events.rb +1 -0
  65. data/lib/samagotchi/guardrails/pair_boundary.rb +12 -4
  66. data/lib/samagotchi/guardrails/review_paths.rb +13 -3
  67. data/lib/samagotchi/guardrails/targets.rb +24 -2
  68. data/lib/samagotchi/guardrails_command.rb +3 -9
  69. data/lib/samagotchi/hook_label.rb +19 -0
  70. data/lib/samagotchi/hook_routes.rb +3 -2
  71. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  72. data/lib/samagotchi/memory_bundle/builder.rb +2 -1
  73. data/lib/samagotchi/memory_bundle/installed_copy.rb +2 -1
  74. data/lib/samagotchi/page_command.rb +90 -6
  75. data/lib/samagotchi/pages/launch.rb +16 -8
  76. data/lib/samagotchi/pages/runner.rb +7 -2
  77. data/lib/samagotchi/pages/runtime.rb +62 -2
  78. data/lib/samagotchi/pages.rb +4 -0
  79. data/lib/samagotchi/panes/kitty.rb +20 -5
  80. data/lib/samagotchi/panes.rb +81 -12
  81. data/lib/samagotchi/participants.rb +17 -6
  82. data/lib/samagotchi/peer_exchanges.rb +1 -2
  83. data/lib/samagotchi/peer_note.rb +38 -5
  84. data/lib/samagotchi/peer_presence.rb +20 -7
  85. data/lib/samagotchi/plugin/api.rb +11 -1
  86. data/lib/samagotchi/plugin/attached_context.rb +46 -1
  87. data/lib/samagotchi/plugin/chips.rb +125 -0
  88. data/lib/samagotchi/plugin/context.rb +43 -8
  89. data/lib/samagotchi/plugin/panes.rb +52 -9
  90. data/lib/samagotchi/plugin/peer_pairing.rb +2 -2
  91. data/lib/samagotchi/plugin/peer_start.rb +61 -36
  92. data/lib/samagotchi/plugin/peers.rb +6 -3
  93. data/lib/samagotchi/plugin/project.rb +63 -0
  94. data/lib/samagotchi/plugin/sessions.rb +36 -1
  95. data/lib/samagotchi/plugin/tool_spec.rb +28 -9
  96. data/lib/samagotchi/schedules.rb +8 -2
  97. data/lib/samagotchi/session.rb +22 -9
  98. data/lib/samagotchi/session_access/local.rb +34 -33
  99. data/lib/samagotchi/session_chain/sharing.rb +79 -0
  100. data/lib/samagotchi/session_chain/successor.rb +4 -2
  101. data/lib/samagotchi/session_chips.rb +133 -0
  102. data/lib/samagotchi/session_inbox_delivery.rb +11 -11
  103. data/lib/samagotchi/session_manager/emptiness.rb +4 -1
  104. data/lib/samagotchi/session_observer.rb +1 -1
  105. data/lib/samagotchi/session_stats.rb +437 -0
  106. data/lib/samagotchi/session_stores.rb +3 -0
  107. data/lib/samagotchi/session_window.rb +30 -0
  108. data/lib/samagotchi/speaker.rb +228 -0
  109. data/lib/samagotchi/steer.rb +36 -132
  110. data/lib/samagotchi/system_one/approval_choice.rb +22 -0
  111. data/lib/samagotchi/system_one/approval_label.rb +4 -6
  112. data/lib/samagotchi/system_prompt.rb +3 -1
  113. data/lib/samagotchi/terminal_ui/attach_launcher.rb +30 -0
  114. data/lib/samagotchi/testing/boundary.rb +17 -4
  115. data/lib/samagotchi/testing/bundle.rb +5 -0
  116. data/lib/samagotchi/testing/host.rb +1 -0
  117. data/lib/samagotchi/testing/recorder.rb +10 -0
  118. data/lib/samagotchi/testing/sessions.rb +11 -3
  119. data/lib/samagotchi/toolkit.rb +11 -4
  120. data/lib/samagotchi/toolkit_report_command.rb +14 -18
  121. data/lib/samagotchi/toolkit_suggest.rb +9 -2
  122. data/lib/samagotchi/tools/registry.rb +48 -18
  123. data/lib/samagotchi/tools/tool_index.rb +6 -2
  124. data/lib/samagotchi/turn_excerpts.rb +302 -0
  125. data/lib/samagotchi/turn_stages/toolkit_suggestion.rb +9 -0
  126. data/lib/samagotchi/version.rb +1 -1
  127. data/lib/samagotchi/web/app.rb +21 -10
  128. data/lib/samagotchi/web/participant_view.rb +1 -1
  129. data/lib/samagotchi/web/peer_routes.rb +5 -2
  130. data/lib/samagotchi/web/plugin_chip_rows.rb +39 -0
  131. data/lib/samagotchi/web/public/agent_rows.js +1 -0
  132. data/lib/samagotchi/web/public/app.js +17 -25
  133. data/lib/samagotchi/web/public/chains.js +0 -26
  134. data/lib/samagotchi/web/public/command_list.js +2 -3
  135. data/lib/samagotchi/web/public/composer.js +2 -3
  136. data/lib/samagotchi/web/public/composer_mount.js +3 -6
  137. data/lib/samagotchi/web/public/context_chips.js +240 -93
  138. data/lib/samagotchi/web/public/context_groups.js +84 -0
  139. data/lib/samagotchi/web/public/draft_follow.js +33 -0
  140. data/lib/samagotchi/web/public/drafts.js +26 -22
  141. data/lib/samagotchi/web/public/index.html +32 -0
  142. data/lib/samagotchi/web/public/peer_chip_kind.js +49 -0
  143. data/lib/samagotchi/web/public/peer_note.js +2 -2
  144. data/lib/samagotchi/web/public/peer_row.js +10 -5
  145. data/lib/samagotchi/web/public/peer_wait.js +4 -2
  146. data/lib/samagotchi/web/public/plugin_chip.js +55 -0
  147. data/lib/samagotchi/web/public/plugin_chip_kind.js +48 -0
  148. data/lib/samagotchi/web/public/send_turn.js +8 -21
  149. data/lib/samagotchi/web/public/session_actions.js +10 -23
  150. data/lib/samagotchi/web/public/session_view.js +7 -3
  151. data/lib/samagotchi/web/public/stream_handlers.js +2 -0
  152. metadata +33 -1
@@ -85,7 +85,7 @@ class Plugin < Samagotchi::Plugin::Peer
85
85
  STATUS_CARD = "codex"
86
86
  SKILL_CARD = "codex-skill"
87
87
  USAGE = "usage: /codex — whether a Codex session is paired; /codex pair — wait for one (say \"pair with chi\" in " \
88
- "Codex, or, with the start hook, anything in a new Codex); /codex start — open Codex in a kitty tab, its first " \
88
+ "Codex, or, with the start hook, anything in a new Codex); /codex start — open Codex in a kitty window, its first " \
89
89
  "prompt \"pair with chi\" (one Codex turn); /codex unpair — end the pairing or the wait; /codex validate " \
90
90
  "<text> | context <text> — send the text to it; /codex last — send the last answer as context; /codex " \
91
91
  "install-skill — install Codex's chi-peer skill, which pairs; /codex install-hook [--yes] — Codex's start " \
@@ -152,12 +152,12 @@ class Plugin < Samagotchi::Plugin::Peer
152
152
  def hook_written_line
153
153
  "Added to `#{hook_file}`. Codex asks you to review it the next time it starts: choose Review hooks (or `/hooks`) " \
154
154
  "and trust it; until then Codex skips it. A Codex started with `/codex start` stops on that screen in its " \
155
- "background tab the first time: Show it."
155
+ "kitty window the first time: Show it."
156
156
  end
157
157
 
158
158
  def hook_stale_tail = ", then trust it in Codex (it is a changed hook)"
159
159
 
160
- def start_review_hint = "if Codex shows Hooks need review, Show its tab and answer it"
160
+ def start_review_hint = "if Codex shows Hooks need review, Show its window and answer it"
161
161
 
162
162
  # The paired Codex's thread id: the pairing's address.
163
163
  def check_hint!(hint)
@@ -1,16 +1,16 @@
1
1
  ---
2
2
  name: coordinator
3
- version: 0.10.0
3
+ version: 0.11.0
4
4
  scope: system
5
- description: "Coordinate parallel work: the coordinator skill (split the work, one worktree and child session per task, check each report, merges under a guardrail approval (the git-merge rule) or a question, a handoff memory to resume from), /coordinate <goal>, /coordinate resume, /coordinate end and /children; the coordinator toolkit (lean + delegate, delegate_result, list_sessions, objectives) and the coding toolkit for build children (child + be concise)"
5
+ description: "Coordinate parallel work: the coordinator skill (split the work, one worktree and child session per task, check each report, merges under a guardrail approval (the git-merge rule) or a question, a handoff memory to resume from), /coordinate <goal>, /coordinate resume, /coordinate end and /children; the coordinator toolkit (lean + delegate, delegate_result, list_sessions, objectives, and the knowledge catalog tools) and the coding toolkit for build children (child + be concise)"
6
6
  trust_level: reviewed
7
7
  files:
8
8
  skill_coordinator.md:
9
- sha256: sha256:d8adab2c798bd5c5efaf15689c905d601621bee1c186b6e412949790406a5541
9
+ sha256: sha256:b7783de28c307c3fbe594cb527dbdc379261b844f5408b2bfdb570bd0f14e12e
10
10
  description: "Coordinate parallel work: split it, delegate each task wait:false in its own worktree (cwd:), check each report, merge under the git-merge approval or ask the user; resume from a handoff_* memory"
11
11
  plugin:
12
12
  file: plugin.rb
13
- sha256: sha256:406b9827485535a8be17d4f1b291997ebf5c3f7d5616d20812c53b4ea153f601
13
+ sha256: sha256:b0047788e6f3c706943892e7b97e0b643afddda2ec1d134be60044fa5521ca12
14
14
  # the coordinator toolkit needs chi.toolkit and ctx.use_toolkit (0.66.0); the
15
15
  # coding toolkit (chi.toolkit prompt:) and the skill's delegate toolkit: need
16
16
  # the next chi.
@@ -19,3 +19,6 @@ requires_chi: ">= 0.107.0"
19
19
  # live older worker deny every call. A chi without `chi guardrails rule` gives a usage error, and the skill then asks.
20
20
  # Nor for the objectives tool in the kit and the skill: on an older chi the kit's add names nothing (it declares only what
21
21
  # is registered), and a call of it comes back as an unknown tool, no harm.
22
+ # Nor for ctx.project (/coordinate resume reads the project's handoffs through it): on an older chi /coordinate resume
23
+ # says to run chi update. Nor for the knowledge tools in the kit: without the knowledge bundle (or on an older chi) the
24
+ # kit's add names nothing registered.
@@ -35,8 +35,9 @@
35
35
  # itself (the core child-boundary guardrail), in every mode: nothing to set up.
36
36
  #
37
37
  # The coordinator toolkit is lean plus the tools that run children
38
- # (delegate, delegate_result, list_sessions) and objectives (the skill's
39
- # moves). /coordinate puts the session
38
+ # (delegate, delegate_result, list_sessions), objectives (the skill's
39
+ # moves) and the knowledge bundle's catalog tools (knowledge_add,
40
+ # knowledge_list, knowledge_remove: the skill's Knowledge sources). /coordinate puts the session
40
41
  # on it before it asks the model (ctx.use_toolkit), which chi allows only
41
42
  # before the session's first model reply and outside a turn: otherwise it
42
43
  # says to run /toolkit coordinator, unless the session declares delegate
@@ -66,7 +67,11 @@ class Plugin
66
67
  def initialize(_settings = {}); end
67
68
 
68
69
  TOOLKIT = "coordinator"
69
- TOOLKIT_TOOLS = %w[delegate delegate_result list_sessions objectives].freeze
70
+ # The knowledge bundle's catalog tools (chi.tool(declare: :kit)): this kit
71
+ # adds them; knowledge_search is declared everywhere. An add: naming a tool
72
+ # no bundle registered declares nothing (Toolkit::Resolved#declares? sees
73
+ # registered entries only), so without the bundle the kit is as it was.
74
+ TOOLKIT_TOOLS = %w[delegate delegate_result list_sessions objectives knowledge_add knowledge_list knowledge_remove].freeze
70
75
  CODING_TOOLKIT = "coding"
71
76
  CODING_PROMPT = "- Be concise in your responses\n- Show file paths clearly when working with files"
72
77
 
@@ -154,6 +159,9 @@ class Plugin
154
159
 
155
160
  # /coordinate resume [name]
156
161
  def resume(name, ctx)
162
+ # An older chi (this bundle upgraded alone) has no ctx.project: say so.
163
+ return "/coordinate resume needs a newer chi (ctx.project): run chi update" unless ctx.respond_to?(:project)
164
+
157
165
  open = open_handoffs(ctx)
158
166
  if name.empty?
159
167
  return "no open coordinator handoff (handoff_* memory) in this project" if open.empty?
@@ -193,8 +201,10 @@ class Plugin
193
201
  # The project's handoff_* memories whose index line isn't DONE, in index
194
202
  # order: [{name:, description:}]. A line without its file is left out.
195
203
  def open_handoffs(ctx)
196
- dir = Samagotchi::MemoryPaths.scope_dir("project", cwd: ctx.cwd)
197
- index = File.join(dir.to_s, "index.md")
204
+ dir = ctx.project.memories_dir
205
+ return [] unless dir
206
+
207
+ index = File.join(dir, "index.md")
198
208
  return [] unless File.file?(index)
199
209
 
200
210
  File.read(index, encoding: "UTF-8").each_line.filter_map do |line|
@@ -145,6 +145,14 @@ changed. Do it without asking; chi asks the user to approve a command source, so
145
145
  `chi context rm <name>` when the epic is done (step 8).
146
146
  - Don't poll a source with register_reminder, a schedule or by reading it again each turn.
147
147
 
148
+ ## Knowledge sources
149
+ Keep the epic's sources findable with knowledge_search (the knowledge bundle; skip this if you don't have the
150
+ tool). Its catalog already has the project's docs and memories. When you find a source the epic keeps coming back
151
+ to (a docs folder, a legacy investigation, another checkout), add it once with knowledge_add (kind folder, a
152
+ max_age: 1h for a live folder, 1d for a repo, never for a closed one, and a `why`), and write its name into the
153
+ handoff. A daily review passes its named catalog (catalog: "daily-review") on every knowledge call. Search before
154
+ asking the user something the sources may hold; a hit is a pointer: read it before you rely on it.
155
+
148
156
  ## End of day
149
157
  When the user ends the day (`/coordinate end`, "that's all for today"), before you answer:
150
158
  1. Check where things stand: for each branch in your handoff `git log --oneline <default>..<branch>` and
@@ -192,3 +200,5 @@ Don't start, merge, stop or clean up anything here: a child still running stays
192
200
  - 2026-11-14 Sprint review removed with /coordinate review: chi has no read-only review sessions (0.9.0)
193
201
  - 2026-11-28 Watching what can change the scope: attach an outside source as context (a PR URL, or a script
194
202
  printing stable text, a summary in your own words, a wake rule), never poll it; "Watching:" in the handoff (0.10.0)
203
+ - 2026-11-30 Knowledge sources: keep the epic's catalog with knowledge_add, a daily review's named catalog,
204
+ search before asking (0.11.0)
@@ -1,11 +1,11 @@
1
1
  ---
2
2
  name: core
3
- version: 0.4.4
3
+ version: 0.4.5
4
4
  scope: system
5
5
  description: "Recommended safety set"
6
6
  trust_level: reviewed
7
7
  # Its members' highest floor (work-cap's: ctx.usage, raised at the release)
8
- requires_chi: ">= 0.173.0"
8
+ requires_chi: ">= 0.196.0"
9
9
  includes:
10
10
  - loop-guard
11
11
  - check-in
@@ -1,15 +1,15 @@
1
1
  ---
2
2
  name: cost-cap
3
- version: 0.2.5
3
+ version: 0.3.0
4
4
  scope: system
5
- description: "A per-session $ cap: at the cap the turn pauses on Continue (another cap's worth) / Stop, a warning at 80% goes to the user only; /cap shows or sets it"
5
+ description: "A per-session $ cap: at the cap the turn pauses on Continue (another cap's worth) / Stop, a warning at 80% goes to the user only; /cap shows or sets it; a chip in the web's session bar shows the spend against it"
6
6
  trust_level: reviewed
7
7
  plugin:
8
8
  file: plugin.rb
9
- sha256: sha256:2d1f739ed0246d3d3040e0534cced2a1f621bdc5881fdde8b463df8a0501e477
9
+ sha256: sha256:f8773feba2741f6a149a971c71bad3300e84528af507afc632586a5519c69f17
10
10
  # ctx.cost is new in chi 0.83.0; ask_user's effects: in the next chi
11
11
  # ctx.session_dir is new in 0.143.0
12
- requires_chi: ">= 0.144.0"
12
+ requires_chi: ">= 0.196.0"
13
13
  # session_settings: as a mapping of keys to types is new
14
14
  # chi --set cost-cap.cap=3: a session's own cap (ctx.settings["cap"]), a number or off
15
15
  session_settings: {cap: number}
@@ -25,6 +25,12 @@
25
25
  # cap:, else child: for a delegate, else default:.
26
26
  # The cap is resolved once per session id (ctx.delegate? parses the session
27
27
  # file) and kept until /cap or Continue writes a new one.
28
+ #
29
+ # The web's session bar shows a chip (ctx.chips; skipped on a chi without it):
30
+ # "cap · $4.10 of $5.00", warn at warn_at, error at the cap, its card's
31
+ # buttons raising the cap to twice it or turning it off. Set after each
32
+ # generation (ctx.cost counts it by then) and by /cap and Continue; the same
33
+ # label again writes nothing. None without a cap or a price.
28
34
  require "json"
29
35
 
30
36
  class Plugin
@@ -48,9 +54,13 @@ class Plugin
48
54
 
49
55
  def register(chi)
50
56
  chi.on(:before_generation) { |_event, ctx| check(ctx) }
51
- # Only the "can't be enforced" notice: a turn of one generation (or a
52
- # session's last) has no next before_generation to give it.
53
- chi.on(:after_generation) { |_event, ctx| check_known(ctx) }
57
+ # The "can't be enforced" notice (a turn of one generation, or a
58
+ # session's last, has no next before_generation to give it) and the
59
+ # chip: the spend now counts this generation.
60
+ chi.on(:after_generation) do |_event, ctx|
61
+ check_known(ctx)
62
+ show_chip(ctx)
63
+ end
54
64
  chi.command("/cap", "see or set this session's cost cap: /cap, /cap 5, /cap off", anytime: true) do |args, ctx|
55
65
  command(args, ctx)
56
66
  end
@@ -121,6 +131,45 @@ class Plugin
121
131
  ctx.notify("#{money(total)} of #{money(cap)} spent (#{(total / cap * 100).floor}%)", level: :warn)
122
132
  end
123
133
 
134
+ # The session bar's chip, from the cap now and the spend: removed with
135
+ # no cap or no price (as the cap isn't enforced then). Only informs: a
136
+ # failure is logged.
137
+ def show_chip(ctx)
138
+ return unless ctx.respond_to?(:chips)
139
+
140
+ resolved = resolve(ctx)
141
+ cap = resolved[:cap]
142
+ return ctx.chips.remove("cap") unless cap
143
+
144
+ cost = ctx.cost
145
+ return ctx.chips.remove("cap") unless cost.known?
146
+
147
+ total = cost.total
148
+ ctx.chips.set("cap", label: "cap · #{money(total)} of #{money(cap)}", state: chip_state(ctx, total, cap),
149
+ title: "cost-cap: #{(total / cap * 100).floor}% of this session's cap",
150
+ body: "This session has used **#{money(total)}** of its **#{money(cap)}** cap.\n\n" \
151
+ "At the cap the turn pauses and asks: continue for another " \
152
+ "#{round_money(resolved[:step] || cap)}, or stop.",
153
+ actions: [{ label: "Raise to #{round_money(cap * 2)}", command: "/cap #{amount_text(cap * 2)}",
154
+ primary: true },
155
+ { label: "Turn the cap off", command: "/cap off" }])
156
+ rescue StandardError => e
157
+ ctx.log.warn(:cap_chip_failed, error: "#{e.class}: #{e.message}")
158
+ end
159
+
160
+ def chip_state(ctx, total, cap)
161
+ return :error if total >= cap
162
+
163
+ share = warn_share(ctx)
164
+ share && total >= share * cap ? :warn : :ok
165
+ end
166
+
167
+ # "$10" for a whole amount, else money's "$7.50".
168
+ def round_money(value) = money(value).delete_suffix(".00")
169
+
170
+ # An amount as /cap reads it: 10, 7.5, 0.006.
171
+ def amount_text(value) = value == value.round ? value.round.to_s : value.round(6).to_s
172
+
124
173
  def check_known(ctx)
125
174
  resolved = resolve(ctx)
126
175
  return unless resolved[:cap]
@@ -291,6 +340,8 @@ class Plugin
291
340
  replaced(ctx, path) if replacing
292
341
  cap = self.class.amount(data["cap"])
293
342
  @mutex.synchronize { @resolved = { session: session, cap: cap, step: self.class.amount(data["step"]) || cap } }
343
+ # /cap, /cap off and Continue: no generation follows them to update it.
344
+ show_chip(ctx)
294
345
  end
295
346
 
296
347
  # Whether +path+ is there but doesn't read (not JSON, or not a mapping).
@@ -1,10 +1,10 @@
1
1
  ---
2
2
  name: dev
3
- version: 0.7.12
3
+ version: 0.7.14
4
4
  scope: system
5
5
  description: "Developer tools"
6
6
  trust_level: reviewed
7
- requires_chi: ">= 0.194.0"
7
+ requires_chi: ">= 0.196.0"
8
8
  includes:
9
9
  - known-names
10
10
  - mcp
@@ -19,3 +19,4 @@ includes:
19
19
  - model-notes
20
20
  - decision-card
21
21
  - inline-widgets
22
+ - knowledge
@@ -1,10 +1,10 @@
1
1
  ---
2
2
  name: github-pr
3
- version: 0.6.5
3
+ version: 0.6.6
4
4
  scope: system
5
5
  description: Proposes the branch's open GitHub pull request to a session, attached once you mention it (#N, the branch or its URL), and attaches any PR URL with chi context add or the web's "+ URL"; the agent gets a note when reviews, comments, checks or its state change; in the web, a path:line in an answer links to that line of the PR; the auto_attach setting can attach the PR at once instead, or do nothing
6
6
  trust_level: reviewed
7
- requires_chi: ">= 0.150.0"
7
+ requires_chi: ">= 0.196.0"
8
8
  needs:
9
9
  - command: gh
10
10
  why: reads the pull request
@@ -20,5 +20,7 @@ context_providers:
20
20
  cmd: '{ruby} {bundle_dir}/scripts/pr_context.rb {url}'
21
21
  why: GitHub PR
22
22
  every_seconds: 300
23
+ # Two or more of its PRs are one chip in the web's session bar, labelled so.
24
+ context_group: PRs
23
25
  # config.yml bundles: github-pr: (another key warns; an older chi ignores this)
24
26
  settings: [auto_attach, line_links]
@@ -0,0 +1,205 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The knowledge bundle's adapters (manifest.yml plugin: parts:): where a
4
+ # source's items come from. Each lists Items (#items: key, sig, title,
5
+ # pointer, path, updated_at; a refresh re-reads only the ones whose sig
6
+ # changed) and reads one's text (#text, nil to skip it).
7
+ # FolderAdapter a folder: inside a git work tree its tracked files
8
+ # only (git ls-files), else a walk; never a symlink, a
9
+ # file whose real path leaves the root, or one named like
10
+ # a secret (ctx.project.secret_name?)
11
+ # MemoriesAdapter chi's memories: the project's and the system ones
12
+ # (ctx.project's dirs), top-level .md files only
13
+ require "find"
14
+ require "open3"
15
+
16
+ class Plugin
17
+ Item = Data.define(:key, :sig, :title, :ptr, :url, :path, :updated_at)
18
+
19
+ class FolderAdapter
20
+ # The text files a folder source reads by default (include:).
21
+ DEFAULT_INCLUDE = ["**/*.{md,txt,rst,adoc,org,rb,py,js,ts,go,rs,java,kt,swift,c,h,yml,yaml,json,toml,sql,sh,html,css}",
22
+ "**/README", "**/README.*", "**/Makefile"].freeze
23
+ # The project's own docs (the project-docs default source).
24
+ DOCS_INCLUDE = ["**/*.{md,txt,rst,adoc}", "README*", "AGENTS.md", "CLAUDE.md", "CHANGELOG*"].freeze
25
+ # A walk (no git) skips these folders, and any dot folder.
26
+ SKIP_DIRS = %w[node_modules vendor tmp].freeze
27
+ MAX_FILE_BYTES = 1024 * 1024
28
+ MAX_FILES = 20_000
29
+ GLOB = File::FNM_PATHNAME | File::FNM_EXTGLOB | File::FNM_DOTMATCH
30
+
31
+ # Why +root+ (absolute) can't be a folder source, nil when it can: /,
32
+ # the home folder or above it, chi's own dirs or memories (chi data
33
+ # goes through kind chi), or a secret root (~/.ssh).
34
+ # @param project [#chi_dirs, #memories_dir, #system_memories_dir, #secret_root?]
35
+ def self.refusal(root, project:, home: Dir.home)
36
+ return "#{root} is not a folder" unless File.directory?(root)
37
+
38
+ real = File.realpath(root)
39
+ home_real = begin File.realpath(home.to_s) rescue home.to_s end
40
+ return "#{root} is /: add a folder inside it" if real == "/"
41
+ return "#{root} holds the home folder: add a folder inside it" if home_real == real || home_real.start_with?("#{real}/")
42
+
43
+ chi = [*project.chi_dirs, project.memories_dir, project.system_memories_dir].compact
44
+ chi = chi.flat_map { |dir| [dir, (File.realpath(dir) if File.exist?(dir))].compact }
45
+ if chi.any? { |dir| real == dir || real.start_with?("#{dir}/") || dir.start_with?("#{real}/") }
46
+ return "#{root} is chi's own data (add memories with kind chi)"
47
+ end
48
+ return "#{root} holds secrets" if project.secret_root?(root) || project.secret_root?(real)
49
+
50
+ nil
51
+ end
52
+
53
+ # The git calls in a folder the user added, which may be a copied
54
+ # repository nobody vetted: its own core.fsmonitor would run a command
55
+ # on ls-files (nothing else in its config runs one for these two).
56
+ GIT = ["git", "-c", "core.fsmonitor=false"].freeze
57
+
58
+ # Whether +root+ is inside a git work tree (a bare repository's dir is not).
59
+ def self.work_tree?(root)
60
+ out, status = Open3.capture2e(Samagotchi::GitEnv::UNSET, *GIT, "-C", root, "rev-parse", "--is-inside-work-tree")
61
+ status.success? && out.strip == "true"
62
+ rescue SystemCallError
63
+ false
64
+ end
65
+
66
+ # The counts #items left out: by a secret name, a symlink (or a path
67
+ # leaving the root), over MAX_FILE_BYTES, past +max_files+.
68
+ attr_reader :skipped
69
+
70
+ # @param root [String] the folder (absolute)
71
+ # @param include [Array<String>] globs on the path relative to +root+
72
+ # @param exclude [Array<String>]
73
+ # @param tracked_only [Boolean] a folder outside git lists nothing (project-docs)
74
+ def initialize(root, project:, include: DEFAULT_INCLUDE, exclude: [], max_files: MAX_FILES, tracked_only: false)
75
+ @root = root
76
+ @real = File.realpath(root)
77
+ @project = project
78
+ @include = include.empty? ? DEFAULT_INCLUDE : include
79
+ @exclude = exclude
80
+ @max_files = max_files
81
+ @tracked_only = tracked_only
82
+ @skipped = { secret: 0, symlink: 0, large: 0, capped: 0 }
83
+ end
84
+
85
+ # @return [Array<Item>]
86
+ def items
87
+ paths = if FolderAdapter.work_tree?(@root)
88
+ tracked
89
+ else
90
+ (@tracked_only ? [] : walked)
91
+ end
92
+ paths = paths.select { |rel| wanted?(rel) }
93
+ if paths.size > @max_files
94
+ @skipped[:capped] = paths.size - @max_files
95
+ paths = paths.first(@max_files)
96
+ end
97
+ paths.filter_map { |rel| item(rel) }
98
+ end
99
+
100
+ # The file's text (scrubbed UTF-8), nil for a binary one or one that
101
+ # changed into a symlink since it was listed.
102
+ def text(item)
103
+ return nil if File.symlink?(item.path)
104
+
105
+ Chunker.clean(File.binread(item.path, MAX_FILE_BYTES))
106
+ rescue SystemCallError
107
+ nil
108
+ end
109
+
110
+ private
111
+
112
+ def tracked
113
+ out, status = Open3.capture2(Samagotchi::GitEnv::UNSET, *GIT, "-C", @root, "ls-files", "-z")
114
+ status.success? ? out.split("\0").reject(&:empty?) : []
115
+ rescue SystemCallError
116
+ []
117
+ end
118
+
119
+ def walked
120
+ found = []
121
+ Find.find(@root) do |path|
122
+ rel = path.delete_prefix("#{@root}/")
123
+ next if path == @root
124
+
125
+ if File.directory?(path) && !File.symlink?(path)
126
+ name = File.basename(path)
127
+ Find.prune if name.start_with?(".") || SKIP_DIRS.include?(name)
128
+ next
129
+ end
130
+ found << rel
131
+ break if found.size > @max_files * 2
132
+ end
133
+ found.sort
134
+ end
135
+
136
+ def wanted?(rel)
137
+ @include.any? { |glob| File.fnmatch?(glob, rel, GLOB) } && @exclude.none? { |glob| File.fnmatch?(glob, rel, GLOB) }
138
+ end
139
+
140
+ def item(rel)
141
+ path = File.join(@root, rel)
142
+ stat = File.lstat(path)
143
+ return skip(:symlink) if stat.symlink?
144
+ return nil unless stat.file?
145
+ return skip(:symlink) unless File.realpath(path).start_with?("#{@real}/")
146
+ return skip(:secret) if @project.secret_name?(rel)
147
+ return skip(:large) if stat.size > MAX_FILE_BYTES
148
+
149
+ Item.new(key: rel, sig: "#{stat.mtime.to_i}:#{stat.size}", title: rel, ptr: path, url: nil, path: path,
150
+ updated_at: stat.mtime.to_i)
151
+ rescue SystemCallError
152
+ nil
153
+ end
154
+
155
+ def skip(why)
156
+ @skipped[why] += 1
157
+ nil
158
+ end
159
+ end
160
+
161
+ class MemoriesAdapter
162
+ # @param dirs [Hash{String => String}] scope => memories dir
163
+ # (ctx.project's: "project" and "system")
164
+ def initialize(dirs)
165
+ @dirs = dirs.compact
166
+ end
167
+
168
+ def skipped = {}
169
+
170
+ # @return [Array<Item>] one per memory file (an overlay too), not index.md
171
+ def items
172
+ @dirs.flat_map do |scope, dir|
173
+ next [] unless File.directory?(dir)
174
+
175
+ Dir.children(dir).sort.filter_map do |file|
176
+ next unless file.end_with?(".md") && file != "index.md" && !file.start_with?(".")
177
+
178
+ path = File.join(dir, file)
179
+ stat = File.lstat(path)
180
+ next unless stat.file?
181
+
182
+ name = memory_name(dir, file.delete_suffix(".md"))
183
+ Item.new(key: "#{scope}:#{file}", sig: "#{stat.mtime.to_i}:#{stat.size}", title: "memory #{name} (#{scope})",
184
+ ptr: "memory_read #{name} #{scope}", url: nil, path: path, updated_at: stat.mtime.to_i)
185
+ rescue SystemCallError
186
+ nil
187
+ end
188
+ end
189
+ end
190
+
191
+ def text(item)
192
+ Chunker.clean(File.binread(item.path, FolderAdapter::MAX_FILE_BYTES))
193
+ rescue SystemCallError
194
+ nil
195
+ end
196
+
197
+ private
198
+
199
+ # An overlay (<name>.<model-key>.md) is read with its memory's name.
200
+ def memory_name(dir, base)
201
+ stem = base.sub(/\.[^.]+\z/, "")
202
+ stem != base && File.file?(File.join(dir, "#{stem}.md")) ? stem : base
203
+ end
204
+ end
205
+ end
@@ -0,0 +1,151 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The knowledge bundle's catalogs (manifest.yml plugin: parts:): which
4
+ # sources a catalog has, their max_age, when each was last refreshed and how
5
+ # that went, in catalog.json beside the catalog's index:
6
+ # <data_dir>/projects/<key>/ a project's (ctx.project.key; worktrees share it)
7
+ # <data_dir>/system/ a session in no project's
8
+ # <data_dir>/catalogs/<name>/ a named catalog (catalog: NAME), shared across projects
9
+ # catalog.json is read without a lock and written (AtomicFile, 0600) only
10
+ # under the catalog's index.lock, which every write to the index takes too.
11
+ require "digest"
12
+ require "fileutils"
13
+ require "json"
14
+
15
+ class Plugin
16
+ class Catalog
17
+ # A catalog name or source name that can't be one: the message says why.
18
+ class Error < StandardError; end
19
+
20
+ FILE = "catalog.json"
21
+ LOCK = "index.lock"
22
+ NAME = /\A[a-z0-9][a-z0-9-]{0,31}\z/
23
+ RESERVED = %w[system projects].freeze
24
+ SOURCE_NAME = /\A[a-z0-9-]{1,32}\z/
25
+ # A project key used as a folder name as it is when it looks like one.
26
+ SAFE_KEY = /\A[A-Za-z0-9][A-Za-z0-9_.-]{0,80}\z/
27
+ AGE = /\A(\d{1,4})([mhd])\z/
28
+ UNITS = { "m" => 60, "h" => 3600, "d" => 86_400 }.freeze
29
+
30
+ # The catalog a call reads: the named one (+name+), else the project's
31
+ # (+project+.key), else the system one.
32
+ # @raise [Error] a name that can't be a catalog's
33
+ def self.locate(data_dir, project:, name: nil)
34
+ unless name.to_s.strip.empty?
35
+ name = name.to_s.strip
36
+ if !name.match?(NAME) || RESERVED.include?(name)
37
+ raise Error, "catalog #{name.inspect} isn't a catalog name (a-z, 0-9 and -, at most 32; not system or projects)"
38
+ end
39
+
40
+ return new(File.join(data_dir, "catalogs", name), kind: :named, label: "catalog #{name}", name: name)
41
+ end
42
+ return new(File.join(data_dir, "system"), kind: :system, label: "system") unless project.key
43
+
44
+ key = project.key.match?(SAFE_KEY) ? project.key : "p_#{Digest::SHA256.hexdigest(project.key)[0, 16]}"
45
+ new(File.join(data_dir, "projects", key), kind: :project, label: "project #{project.key}")
46
+ end
47
+
48
+ # The named catalogs in +data_dir+.
49
+ def self.named(data_dir)
50
+ dir = File.join(data_dir, "catalogs")
51
+ File.directory?(dir) ? Dir.children(dir).select { |name| File.file?(File.join(dir, name, FILE)) }.sort : []
52
+ end
53
+
54
+ # Seconds of a max_age (30m, 6h, 2d), nil for never.
55
+ # @raise [Error] anything else
56
+ def self.max_age_seconds(text)
57
+ text = text.to_s.strip
58
+ return nil if text == "never"
59
+
60
+ match = text.match(AGE) or raise Error, "max_age #{text.inspect} isn't 30m, 6h, 2d … or never"
61
+ match[1].to_i * UNITS.fetch(match[2])
62
+ end
63
+
64
+ attr_reader :dir, :kind, :label, :name
65
+
66
+ def initialize(dir, kind:, label:, name: nil)
67
+ @dir = dir
68
+ @kind = kind
69
+ @label = label
70
+ @name = name
71
+ end
72
+
73
+ def named? = @kind == :named
74
+ def path = File.join(@dir, FILE)
75
+ def exists? = File.file?(path)
76
+
77
+ # The catalog's data: {"sources" => [...], "removed_defaults" => [...],
78
+ # "seeded" => bool, "notes" => [...]}.
79
+ def load
80
+ data = exists? ? JSON.parse(File.read(path)) : {}
81
+ data = {} unless data.is_a?(Hash)
82
+ { "sources" => [], "removed_defaults" => [], "seeded" => false, "notes" => [] }.merge(data)
83
+ rescue JSON::ParserError, SystemCallError
84
+ { "sources" => [], "removed_defaults" => [], "seeded" => false, "notes" => [] }
85
+ end
86
+
87
+ def sources = load["sources"]
88
+
89
+ def source(name) = sources.find { |source| source["name"] == name }
90
+
91
+ # The block, under the catalog's index.lock (made 0700 / 0600).
92
+ def lock
93
+ FileUtils.mkdir_p(@dir, mode: 0o700)
94
+ File.open(File.join(@dir, LOCK), File::RDWR | File::CREAT, 0o600) do |file|
95
+ file.flock(File::LOCK_EX)
96
+ yield
97
+ end
98
+ end
99
+
100
+ # Load, let the block change the data, save it; under the lock.
101
+ # @return the block's value
102
+ def update
103
+ lock do
104
+ data = load
105
+ result = yield data
106
+ Samagotchi::AtomicFile.write(path, "#{JSON.pretty_generate(data)}\n", perm: 0o600)
107
+ result
108
+ end
109
+ end
110
+
111
+ # The block with +source+'s refresh lock held, without waiting: false
112
+ # when another refresh holds it (in this process or another).
113
+ def with_source_lock(source)
114
+ dir = File.join(@dir, "sources")
115
+ FileUtils.mkdir_p(dir, mode: 0o700)
116
+ File.open(File.join(dir, "#{source}.lock"), File::RDWR | File::CREAT, 0o600) do |file|
117
+ return false unless file.flock(File::LOCK_EX | File::LOCK_NB)
118
+
119
+ yield
120
+ true
121
+ end
122
+ end
123
+
124
+ # Whether +source+ is due a refresh at +now+ (epoch seconds): never
125
+ # refreshed, or older than its max_age (never: once indexed, never).
126
+ # Reads the catalog's record only: no walk, no stat.
127
+ def self.stale?(source, now)
128
+ refreshed = source["refreshed_at"]
129
+ return true if refreshed.nil?
130
+
131
+ age = source["max_age_seconds"]
132
+ !age.nil? && now - refreshed.to_i > age
133
+ end
134
+
135
+ # A free source name: +base+, else base-2, base-3 …
136
+ def self.free_name(base, taken)
137
+ return base unless taken.include?(base)
138
+
139
+ (2..).each do |n|
140
+ name = "#{base[0, 32 - n.to_s.size - 1]}-#{n}"
141
+ return name unless taken.include?(name)
142
+ end
143
+ end
144
+
145
+ # +text+ as a source name's words: a-z, 0-9 and -.
146
+ def self.slug(text)
147
+ slug = text.to_s.downcase.gsub(/[^a-z0-9]+/, "-").gsub(/\A-+|-+\z/, "")
148
+ slug.empty? ? "source" : slug[0, 24].sub(/-+\z/, "")
149
+ end
150
+ end
151
+ end