openclacky 1.5.21 → 1.5.23

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 (110) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +119 -0
  3. data/docs/secretary-prototype.md +286 -0
  4. data/lib/clacky/agent/session_serializer.rb +15 -11
  5. data/lib/clacky/agent.rb +58 -15
  6. data/lib/clacky/agent_config.rb +3 -1
  7. data/lib/clacky/agent_profile.rb +33 -6
  8. data/lib/clacky/billing/platform_billing.rb +9 -0
  9. data/lib/clacky/default_extensions/advisor/README.md +25 -0
  10. data/lib/clacky/default_extensions/advisor/README.zh.md +25 -0
  11. data/lib/clacky/default_extensions/advisor/ext.yml +1 -1
  12. data/lib/clacky/default_extensions/advisor/icon.svg +14 -0
  13. data/lib/clacky/default_extensions/coding/ext.yml +0 -1
  14. data/lib/clacky/default_extensions/computer-use/README.md +48 -0
  15. data/lib/clacky/default_extensions/computer-use/README.zh.md +48 -0
  16. data/lib/clacky/default_extensions/computer-use/ext.yml +1 -1
  17. data/lib/clacky/default_extensions/computer-use/icon.svg +16 -0
  18. data/lib/clacky/default_extensions/ext-studio/ext.yml +0 -1
  19. data/lib/clacky/default_extensions/general/ext.yml +0 -1
  20. data/lib/clacky/default_extensions/git/README.md +41 -0
  21. data/lib/clacky/default_extensions/git/README.zh.md +41 -0
  22. data/lib/clacky/default_extensions/git/ext.yml +1 -1
  23. data/lib/clacky/default_extensions/git/icon.svg +15 -0
  24. data/lib/clacky/default_extensions/git/panels/git/view.js +1960 -399
  25. data/lib/clacky/default_extensions/meeting/README.md +46 -0
  26. data/lib/clacky/default_extensions/meeting/README.zh.md +47 -0
  27. data/lib/clacky/default_extensions/meeting/ext.yml +1 -1
  28. data/lib/clacky/default_extensions/meeting/icon.svg +13 -0
  29. data/lib/clacky/default_extensions/preview/README.md +29 -0
  30. data/lib/clacky/default_extensions/preview/README.zh.md +29 -0
  31. data/lib/clacky/default_extensions/preview/ext.yml +1 -1
  32. data/lib/clacky/default_extensions/preview/icon.svg +13 -0
  33. data/lib/clacky/default_extensions/preview/panels/preview/view.js +199 -34
  34. data/lib/clacky/default_extensions/secretary/agents/secretary.md +41 -0
  35. data/lib/clacky/default_extensions/secretary/agents/worker.md +35 -0
  36. data/lib/clacky/default_extensions/secretary/api/handler.rb +8 -0
  37. data/lib/clacky/default_extensions/secretary/ext.yml +39 -0
  38. data/lib/clacky/default_extensions/secretary/panels/work/view.js +344 -0
  39. data/lib/clacky/default_extensions/secretary/tools/delegate_work.rb +37 -0
  40. data/lib/clacky/default_extensions/secretary/tools/manage_work.rb +22 -0
  41. data/lib/clacky/default_extensions/secretary/tools/yield_work.rb +35 -0
  42. data/lib/clacky/default_extensions/time_machine/README.md +32 -0
  43. data/lib/clacky/default_extensions/time_machine/README.zh.md +32 -0
  44. data/lib/clacky/default_extensions/time_machine/ext.yml +1 -1
  45. data/lib/clacky/default_extensions/time_machine/icon.svg +14 -0
  46. data/lib/clacky/default_skills/channel-manager/SKILL.md +79 -8
  47. data/lib/clacky/default_skills/channel-manager/discord_setup.rb +5 -1
  48. data/lib/clacky/default_skills/channel-manager/weixin_setup.rb +8 -1
  49. data/lib/clacky/default_skills/cron-task-creator/SKILL.md +183 -206
  50. data/lib/clacky/default_skills/cron-task-creator/evals/evals.json +45 -0
  51. data/lib/clacky/default_skills/media-gen/SKILL.md +17 -8
  52. data/lib/clacky/extension/api_extension.rb +10 -2
  53. data/lib/clacky/extension/loader.rb +2 -0
  54. data/lib/clacky/extension/verifier.rb +2 -2
  55. data/lib/clacky/locales/en.rb +14 -0
  56. data/lib/clacky/locales/zh.rb +14 -0
  57. data/lib/clacky/prompts/base.md +1 -1
  58. data/lib/clacky/providers.rb +68 -31
  59. data/lib/clacky/search_config.rb +33 -11
  60. data/lib/clacky/server/channel/adapters/base.rb +18 -0
  61. data/lib/clacky/server/channel/adapters/feishu/message_parser.rb +1 -0
  62. data/lib/clacky/server/channel/adapters/telegram/adapter.rb +1 -0
  63. data/lib/clacky/server/channel/channel_config.rb +185 -48
  64. data/lib/clacky/server/channel/channel_manager.rb +179 -66
  65. data/lib/clacky/server/git_panel.rb +362 -35
  66. data/lib/clacky/server/http_server.rb +530 -181
  67. data/lib/clacky/server/preview.rb +118 -17
  68. data/lib/clacky/server/scheduler.rb +211 -51
  69. data/lib/clacky/server/web_ui_controller.rb +35 -27
  70. data/lib/clacky/session_manager.rb +56 -6
  71. data/lib/clacky/tools/base.rb +7 -1
  72. data/lib/clacky/utils/file_processor.rb +20 -10
  73. data/lib/clacky/utils/mac_app_detector.rb +8 -7
  74. data/lib/clacky/utils/model_pricing.rb +60 -2
  75. data/lib/clacky/utils/windows_app_detector.rb +3 -1
  76. data/lib/clacky/version.rb +1 -1
  77. data/lib/clacky/web/app.css +1114 -205
  78. data/lib/clacky/web/app.js +143 -8
  79. data/lib/clacky/web/auth.js +1 -1
  80. data/lib/clacky/web/components/code-editor.js +73 -4
  81. data/lib/clacky/web/components/composer.js +107 -8
  82. data/lib/clacky/web/components/image-zoom.js +165 -0
  83. data/lib/clacky/web/components/model-picker.js +7 -5
  84. data/lib/clacky/web/components/notify.js +39 -12
  85. data/lib/clacky/web/components/onboard.js +1 -1
  86. data/lib/clacky/web/core/aside.js +60 -3
  87. data/lib/clacky/web/features/billing/view.js +2 -2
  88. data/lib/clacky/web/features/channels/store.js +19 -4
  89. data/lib/clacky/web/features/channels/view.js +92 -28
  90. data/lib/clacky/web/features/extensions/view.js +17 -10
  91. data/lib/clacky/web/features/new-session/store.js +79 -2
  92. data/lib/clacky/web/features/new-session/view.js +516 -75
  93. data/lib/clacky/web/features/skills/store.js +1 -1
  94. data/lib/clacky/web/features/tasks/store.js +5 -3
  95. data/lib/clacky/web/features/tasks/view.js +249 -66
  96. data/lib/clacky/web/features/workspace/store.js +13 -6
  97. data/lib/clacky/web/features/workspace/view.js +340 -214
  98. data/lib/clacky/web/i18n.js +366 -68
  99. data/lib/clacky/web/index.html +196 -165
  100. data/lib/clacky/web/projects.js +37 -4
  101. data/lib/clacky/web/sessions.js +263 -146
  102. data/lib/clacky/web/settings.js +241 -53
  103. data/lib/clacky/web/skills.js +2 -2
  104. data/lib/clacky/web/theme.js +17 -2
  105. data/lib/clacky/web/utils.js +234 -2
  106. data/lib/clacky/web/weixin-qr.html +2 -1
  107. data/lib/clacky/web/ws-dispatcher.js +14 -31
  108. data/lib/clacky/work/service.rb +542 -0
  109. data/lib/clacky/work/store.rb +57 -0
  110. metadata +31 -1
@@ -8,12 +8,18 @@ module Clacky
8
8
  module Server
9
9
  # Read-mostly git operations scoped to a session's working directory, backing
10
10
  # the official "git" WebUI panel. Commands run with explicit argv (no shell),
11
- # so user-supplied values (paths, messages) cannot inject. Write operations
12
- # are limited to a guarded `commit` and a single-file `restore`;
11
+ # so user-supplied values (paths, messages) cannot inject. The only write
12
+ # operation is a single-file `restore`; committing is left to the agent, and
13
13
  # history-rewriting / remote-mutating commands are never exposed here.
14
14
  module GitPanel
15
15
  module_function
16
16
 
17
+ # Whole-payload diff budget. A branch comparison against a long-lived
18
+ # branch can be 900 files / 200k lines; serialising that and building the
19
+ # DOM for it locks up the browser, so files past this budget are returned
20
+ # without their diff and the UI loads them on demand.
21
+ DEFAULT_MAX_TOTAL_LINES = 12_000
22
+
17
23
  # Run a git subcommand in `dir` with argv-style args (no shell). Returns
18
24
  # [stdout, stderr, success_bool]. Never raises on git failure.
19
25
  #
@@ -22,8 +28,9 @@ module Clacky
22
28
  # bytes the caller passed in. Output is then normalised to UTF-8 because
23
29
  # git inherits the locale, and under a non-UTF-8 locale the raw bytes come
24
30
  # back tagged US-ASCII, where String#split would raise on multibyte paths.
31
+ # LC_ALL=C pins git's messages to English so the UI can recognise them.
25
32
  def git(dir, *args)
26
- out, err, status = Open3.capture3("git", "-C", dir.to_s, "-c", "core.quotePath=false", *args)
33
+ out, err, status = Open3.capture3({ "LC_ALL" => "C" }, "git", "-C", dir.to_s, "-c", "core.quotePath=false", *args)
27
34
  [Utils::Encoding.to_utf8(out), Utils::Encoding.to_utf8(err), status.success?]
28
35
  rescue StandardError => e
29
36
  ["", e.message, false]
@@ -36,9 +43,11 @@ module Clacky
36
43
  end
37
44
 
38
45
  # { branch:, ahead:, behind:, files: [{ path:, x:, y:, staged:, untracked: }] }
39
- # Parsed from `git status --porcelain=v2 --branch`.
46
+ # Parsed from `git status --porcelain=v2 --branch`. Untracked files are
47
+ # listed individually (`--untracked-files=all`): the default collapses a
48
+ # new directory into one `dir/` entry, which the panel cannot diff.
40
49
  def status(dir)
41
- out, _err, ok = git(dir, "status", "--porcelain=v2", "--branch")
50
+ out, _err, ok = git(dir, "status", "--porcelain=v2", "--branch", "--untracked-files=all")
42
51
  return { branch: nil, files: [] } unless ok
43
52
 
44
53
  branch = nil
@@ -70,25 +79,265 @@ module Clacky
70
79
  # they diff against /dev/null via --no-index (rendered as pure
71
80
  # additions); the trailing `--` keeps a leading-dash filename from
72
81
  # being read as an option in that mode too.
73
- def diff(dir, file: nil)
82
+ # `context` overrides the default three lines of surrounding code; the
83
+ # changes panel passes a huge value to reveal the whole file behind a
84
+ # collapsed "N unmodified lines" gap.
85
+ def diff(dir, file: nil, context: nil, scope: "worktree", base: nil)
86
+ extra = context ? ["-U#{context.to_i.clamp(0, 1_000_000).to_s}"] : []
87
+ range = diff_range(dir, scope, base)
74
88
  if file && !file.empty?
75
89
  others, _e, _ok = git(dir, "ls-files", "--others", "--exclude-standard", "--", file)
76
90
  if others.strip.empty?
77
- out, _e, _ok = git(dir, "diff", "HEAD", "--", file)
91
+ out, _e, _ok = git(dir, "diff", *range, *extra, "--", file)
92
+ elsif scope.to_s == "worktree" || scope.to_s == "unstaged"
93
+ out, _e, _ok = git(dir, "diff", "--no-index", *extra, "--", "/dev/null", file)
78
94
  else
79
- out, _e, _ok = git(dir, "diff", "--no-index", "--", "/dev/null", file)
95
+ out = ""
80
96
  end
81
97
  out
82
98
  else
83
- git(dir, "diff", "HEAD")[0]
99
+ git(dir, "diff", *range, *extra)[0]
100
+ end
101
+ end
102
+
103
+ # Baseline args for `git diff` in the given scope. `worktree` keeps the
104
+ # historical behaviour (HEAD); `committed` reviews a single commit the
105
+ # user picked (or the whole unpushed range); `branch` compares the merge
106
+ # base of the chosen branch so unrelated commits on it do not leak in.
107
+ def diff_range(dir, scope, base)
108
+ case scope.to_s
109
+ when "unstaged" then []
110
+ when "staged" then ["--cached", "HEAD"]
111
+ when "committed"
112
+ base_ref = base.to_s.strip
113
+ if base_ref.empty?
114
+ upstream = default_base(dir)
115
+ ref?(dir, upstream) ? ["#{upstream}...HEAD"] : []
116
+ else
117
+ commit_range(dir, base_ref)
118
+ end
119
+ when "branch"
120
+ base_ref = base.to_s.strip
121
+ base_ref = default_base(dir) if base_ref.empty?
122
+ ref?(dir, base_ref) ? ["#{base_ref}...HEAD"] : []
123
+ else ["HEAD"]
124
+ end
125
+ end
126
+
127
+ # A commit picked in the "committed" menu is reviewed on its own: the
128
+ # panel answers "what did this commit change", not "what came after it".
129
+ # Root commits have no parent, so they diff against the empty tree.
130
+ EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
131
+
132
+ def commit_range(dir, sha)
133
+ return [] unless ref?(dir, sha)
134
+
135
+ parent = "#{sha}^"
136
+ ref?(dir, parent) ? ["#{parent}..#{sha}"] : [EMPTY_TREE, sha]
137
+ end
138
+
139
+ # Review scopes, mirroring the selector above the changes panel:
140
+ # worktree - everything not committed yet (baseline HEAD)
141
+ # unstaged - index vs working tree
142
+ # staged - HEAD vs index
143
+ # committed - the branch's commits on top of its base (upstream)
144
+ # branch - the same comparison against a branch the user picked
145
+ # lastTurn - what the previous agent turn touched (served from the
146
+ # Time Machine snapshots by `last_turn_review`, not git)
147
+ SCOPES = %w[worktree unstaged staged committed branch lastTurn].freeze
148
+
149
+ # One payload for the whole changes panel: status order, per-file unified
150
+ # diff, and per-file added/removed line counts. Tracked changes come from
151
+ # a single diff split on its `diff --git` headers so N files cost one
152
+ # subprocess; untracked files have no baseline and are diffed against
153
+ # /dev/null individually (they are usually few).
154
+ #
155
+ # `max_lines` caps each file's diff so a minified bundle cannot stall the
156
+ # browser; `truncated` tells the UI to say so instead of rendering half a
157
+ # hunk silently.
158
+ def review(dir, max_lines: 4000, max_total_lines: DEFAULT_MAX_TOTAL_LINES, scope: nil, base: nil)
159
+ return { repo: false } unless repo?(dir)
160
+
161
+ scope = SCOPES.include?(scope.to_s) ? scope.to_s : "worktree"
162
+ st = status(dir)
163
+ payload = { repo: true, branch: st[:branch], ahead: st[:ahead],
164
+ behind: st[:behind], scope: scope }
165
+
166
+ case scope
167
+ when "unstaged"
168
+ payload.merge!(unstaged_review(dir, st, max_lines: max_lines))
169
+ when "staged"
170
+ payload.merge!(range_review(dir, ["--cached", "HEAD"], max_lines: max_lines,
171
+ max_total_lines: max_total_lines))
172
+ when "committed"
173
+ base_ref = base.to_s.strip
174
+ if base_ref.empty?
175
+ upstream = default_base(dir)
176
+ if upstream.empty? || !ref?(dir, upstream)
177
+ payload.merge!(files: [], add: 0, del: 0, note: "noBase")
178
+ else
179
+ payload[:base] = upstream
180
+ payload.merge!(range_review(dir, ["#{upstream}...HEAD"], max_lines: max_lines,
181
+ max_total_lines: max_total_lines))
182
+ end
183
+ else
184
+ range = commit_range(dir, base_ref)
185
+ if range.empty?
186
+ payload.merge!(files: [], add: 0, del: 0, note: "noBase")
187
+ else
188
+ payload[:commit] = base_ref
189
+ payload.merge!(range_review(dir, range, max_lines: max_lines,
190
+ max_total_lines: max_total_lines))
191
+ end
192
+ end
193
+ when "branch"
194
+ base_ref = base.to_s.strip
195
+ base_ref = default_base(dir) if base_ref.empty?
196
+ if base_ref.empty? || !ref?(dir, base_ref)
197
+ payload.merge!(files: [], add: 0, del: 0, note: "noBase")
198
+ else
199
+ payload[:base] = base_ref
200
+ payload.merge!(range_review(dir, ["#{base_ref}...HEAD"], max_lines: max_lines,
201
+ max_total_lines: max_total_lines))
202
+ end
203
+ else
204
+ payload.merge!(worktree_review(dir, st, max_lines: max_lines,
205
+ max_total_lines: max_total_lines))
84
206
  end
85
207
  end
86
208
 
87
- # Recent commits: [{ hash:, short:, author:, date:, subject: }].
88
- def log(dir, limit: 50)
209
+ def worktree_review(dir, st, max_lines:, max_total_lines: DEFAULT_MAX_TOTAL_LINES)
210
+ chunks = split_diff(git(dir, "diff", "HEAD")[0])
211
+ entries_review(st[:files], max_lines: max_lines, max_total_lines: max_total_lines) do |f|
212
+ f[:untracked] ? diff(dir, file: f[:path]) : (chunks[f[:path]] || diff(dir, file: f[:path]))
213
+ end
214
+ end
215
+
216
+ def unstaged_review(dir, st, max_lines:, max_total_lines: DEFAULT_MAX_TOTAL_LINES)
217
+ chunks = split_diff(git(dir, "diff")[0])
218
+ subset = st[:files].select { |f| f[:untracked] || f[:y].to_s != "." }
219
+ entries_review(subset, max_lines: max_lines, max_total_lines: max_total_lines) do |f|
220
+ f[:untracked] ? diff(dir, file: f[:path]) : chunks[f[:path]].to_s
221
+ end
222
+ end
223
+
224
+ def range_review(dir, range_args, max_lines:, max_total_lines: DEFAULT_MAX_TOTAL_LINES)
225
+ chunks = split_diff(git(dir, "diff", *range_args)[0])
226
+ files = chunks.map do |path, text|
227
+ build_file(path, text, max_lines: max_lines,
228
+ x: diff_letter(text), y: ".")
229
+ end
230
+ totals(budget_files(files, max_total_lines))
231
+ end
232
+
233
+ def entries_review(entries, max_lines:, max_total_lines: DEFAULT_MAX_TOTAL_LINES)
234
+ files = entries.map do |f|
235
+ text = yield(f).to_s
236
+ build_file(f[:path], text, max_lines: max_lines,
237
+ x: f[:x], y: f[:y], untracked: f[:untracked])
238
+ end
239
+ totals(budget_files(files, max_total_lines))
240
+ end
241
+
242
+ # A branch comparison can span hundreds of files and hundreds of
243
+ # thousands of lines. Shipping every diff as JSON freezes the browser
244
+ # while it builds that much DOM, so files past the budget lose their
245
+ # `diff` payload and are flagged `lazy` — the UI fetches them one at a
246
+ # time when the user actually opens one. Counts stay intact so the tree
247
+ # still shows accurate +/- badges.
248
+ def budget_files(files, max_total_lines)
249
+ remaining = max_total_lines.to_i
250
+ files.each do |f|
251
+ if remaining <= 0
252
+ f[:lazy] = true
253
+ f[:diff] = ""
254
+ else
255
+ remaining -= f[:diff].lines.size
256
+ end
257
+ end
258
+ files
259
+ end
260
+
261
+ def build_file(path, text, max_lines:, x: "M", y: ".", untracked: false, binary: nil)
262
+ text, truncated = trim_diff(text.to_s, max_lines)
263
+ add, del = count_changes(text)
264
+ { path: path, x: x, y: y, untracked: untracked,
265
+ add: add, del: del, truncated: truncated,
266
+ binary: binary.nil? ? text.match?(/^Binary files .* differ$/) : binary,
267
+ diff: text }
268
+ end
269
+
270
+ def totals(files)
271
+ { files: files,
272
+ add: files.sum { |f| f[:add] },
273
+ del: files.sum { |f| f[:del] } }
274
+ end
275
+
276
+ # A file added or removed between the two sides of a diff has no content
277
+ # on one of them; the UI uses the letter for its A/D/M tag.
278
+ def diff_letter(text)
279
+ return "A" if text.match?(/^new file mode /)
280
+ return "D" if text.match?(/^deleted file mode /)
281
+ "M"
282
+ end
283
+
284
+ # Upstream of the current branch is the natural base for "committed":
285
+ # it is exactly the commits that have not been pushed yet. Falling back
286
+ # to origin/HEAD and then a local main/master covers fresh clones and
287
+ # branches without an upstream.
288
+ def default_base(dir)
289
+ out, _err, ok = git(dir, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}")
290
+ return out.strip if ok && !out.strip.empty?
291
+
292
+ out, _err, ok = git(dir, "symbolic-ref", "--short", "refs/remotes/origin/HEAD")
293
+ return out.strip if ok && !out.strip.empty?
294
+
295
+ %w[origin/main origin/master main master].find { |name| ref?(dir, name) }.to_s
296
+ end
297
+
298
+ def ref?(dir, name)
299
+ return false if name.to_s.empty? || name.start_with?("-")
300
+
301
+ _out, _err, ok = git(dir, "rev-parse", "--verify", "--quiet", "#{name}^{commit}")
302
+ ok
303
+ end
304
+
305
+ # Scope "lastTurn": what the previous agent turn changed. Git has no
306
+ # notion of a turn, so this comes from Time Machine snapshots — each task
307
+ # keeps a BEFORE/AFTER tree of the files it touched.
308
+ def last_turn_review(agent, max_lines: 4000, max_total_lines: DEFAULT_MAX_TOTAL_LINES)
309
+ payload = { repo: true, scope: "lastTurn", files: [], add: 0, del: 0, note: "noTurn" }
310
+ return payload unless agent.respond_to?(:get_task_history)
311
+
312
+ history = agent.get_task_history(limit: 20)
313
+ current = history.find { |task| task[:status] == :current }
314
+ task_id = current ? current[:parent_task_id].to_i : 0
315
+ return payload if task_id <= 0
316
+
317
+ files = agent.task_diff_files(task_id).map do |entry|
318
+ detail = agent.task_file_diff(task_id, entry[:path]) || {}
319
+ build_file(entry[:path], detail[:patch].to_s, max_lines: max_lines,
320
+ x: { "added" => "A", "deleted" => "D" }.fetch(entry[:status], "M"),
321
+ y: ".", binary: detail[:binary] ? true : nil)
322
+ end
323
+ totals(budget_files(files, max_total_lines)).merge(repo: true, scope: "lastTurn", task_id: task_id)
324
+ end
325
+
326
+ # Recent commits: [{ hash:, short:, author:, date:, subject: }]. With
327
+ # `unpushed: true` the log is limited to the commits the default base
328
+ # does not contain yet — the same range the "committed" scope diffs, so
329
+ # the menu never offers a commit that is already on the remote.
330
+ def log(dir, limit: 50, unpushed: false)
89
331
  limit = limit.to_i.clamp(1, 200)
90
332
  fmt = "%H%x1f%h%x1f%an%x1f%ad%x1f%s"
91
- out, _err, ok = git(dir, "log", "-n", limit.to_s, "--date=short", "--pretty=format:#{fmt}")
333
+ args = ["log", "-n", limit.to_s, "--date=short", "--pretty=format:#{fmt}"]
334
+ if unpushed
335
+ base = default_base(dir)
336
+ return [] unless ref?(dir, base)
337
+
338
+ args << "#{base}..HEAD"
339
+ end
340
+ out, _err, ok = git(dir, *args)
92
341
  return [] unless ok
93
342
 
94
343
  out.each_line.filter_map do |line|
@@ -98,18 +347,66 @@ module Clacky
98
347
  end
99
348
  end
100
349
 
101
- # [{ name:, current: bool }] from `git branch`.
350
+ # [{ name:, current: bool, remote: bool }] from `git branch --all`.
351
+ # Remote HEAD pointers (`origin/HEAD` → `origin/main`) are dropped: they
352
+ # are aliases, not branches the user can compare against.
102
353
  def branches(dir)
103
- out, _err, ok = git(dir, "branch", "--format=%(refname:short)%00%(HEAD)")
354
+ out, _err, ok = git(dir, "branch", "--all",
355
+ "--format=%(refname)%00%(refname:short)%00%(HEAD)")
104
356
  return [] unless ok
105
357
 
106
358
  out.each_line.filter_map do |line|
107
- name, head = line.chomp.split("\x00")
108
- next unless name && !name.empty?
109
- { name: name, current: head == "*" }
359
+ full, name, head = line.chomp.split("\x00")
360
+ next unless full && name && !name.empty?
361
+ next if full.end_with?("/HEAD")
362
+ { name: name, current: head == "*", remote: full.start_with?("refs/remotes/") }
110
363
  end
111
364
  end
112
365
 
366
+ # Current branch name, or nil when HEAD is detached / the dir is not a repo.
367
+ def branch_name(dir)
368
+ out, _err, ok = git(dir, "symbolic-ref", "--short", "-q", "HEAD")
369
+ ok ? out.strip : nil
370
+ end
371
+
372
+ # Whether `name` is a branch (or ref) git would accept. Refusing a leading
373
+ # dash keeps the value from being parsed as an option by the argv call
374
+ # below; the rest of the rules come from git itself so aliases such as
375
+ # `origin/pr-685` stay usable.
376
+ #
377
+ # Returns true/false - never raises.
378
+ def branch_ref?(dir, name)
379
+ ref = name.to_s.strip
380
+ return false if ref.empty? || ref.start_with?("-")
381
+
382
+ _out, _err, ok = git(dir, "check-ref-format", "--branch", ref)
383
+ ok
384
+ end
385
+
386
+ # Switch the work tree to `branch`, optionally creating it (from `from`,
387
+ # or from HEAD when omitted). Uncommitted changes are left to git: it
388
+ # either carries them across or refuses with a message the UI shows as-is.
389
+ def checkout(dir, branch:, create: false, from: nil)
390
+ name = branch.to_s.strip
391
+ return { ok: false, error: "branch is required" } if name.empty?
392
+ return { ok: false, error: "invalid branch name" } unless branch_ref?(dir, name)
393
+
394
+ args = ["checkout"]
395
+ if create
396
+ start = from.to_s.strip
397
+ return { ok: false, error: "invalid base ref" } unless start.empty? || branch_ref?(dir, start)
398
+ args.push("-b", name)
399
+ args.push(start) unless start.empty?
400
+ else
401
+ args.push(name)
402
+ end
403
+
404
+ _out, err, ok = git(dir, *args)
405
+ return { ok: true, branch: name } if ok
406
+
407
+ { ok: false, error: err.strip.empty? ? "git checkout failed" : err.strip }
408
+ end
409
+
113
410
  # Discard uncommitted changes to one file and return it to its HEAD
114
411
  # state (same baseline the diff API uses, so "what you saw is what you
115
412
  # lose"). Files that never existed in HEAD (staged-new or untracked)
@@ -147,28 +444,58 @@ module Clacky
147
444
  end
148
445
  end
149
446
 
150
- # Relative repo paths only: no absolute paths, no traversal segments.
151
- def invalid_path?(path)
152
- path.start_with?("/") || path.split("/").include?("..")
447
+ # Split a multi-file `git diff` into { path => chunk } keyed by the repo
448
+ # path, preferring the `+++ b/` side (the `--- a/` side is
449
+ # `/dev/null` for added files).
450
+ def split_diff(text)
451
+ chunks = {}
452
+ path = nil
453
+ buf = []
454
+ flush = lambda do
455
+ chunks[path] = buf.join if path && !buf.empty?
456
+ end
457
+ text.each_line do |line|
458
+ if line.start_with?("diff --git ")
459
+ flush.call
460
+ buf = [line]
461
+ path = nil
462
+ else
463
+ buf << line
464
+ next if path
465
+ if line.start_with?("--- a/")
466
+ path = line.sub("--- a/", "").chomp
467
+ elsif line.start_with?("+++ b/")
468
+ path = line.sub("+++ b/", "").chomp
469
+ end
470
+ end
471
+ end
472
+ flush.call
473
+ chunks
153
474
  end
154
475
 
155
- # Stage `files` (relative paths) and commit with `message`. Returns
156
- # { ok:, error?:, hash? }. Refuses empty message / empty file set. Uses
157
- # argv so paths/message cannot inject; no --no-verify, no amend.
158
- def commit(dir, message:, files:)
159
- msg = message.to_s.strip
160
- paths = Array(files).map(&:to_s).reject(&:empty?)
161
- return { ok: false, error: "commit message is required" } if msg.empty?
162
- return { ok: false, error: "no files selected" } if paths.empty?
163
-
164
- _out, add_err, add_ok = git(dir, "add", "--", *paths)
165
- return { ok: false, error: "git add failed: #{add_err.strip}" } unless add_ok
476
+ def count_changes(text)
477
+ add = 0
478
+ del = 0
479
+ text.each_line do |line|
480
+ next if line.start_with?("+++", "---")
481
+ if line.start_with?("+")
482
+ add += 1
483
+ elsif line.start_with?("-")
484
+ del += 1
485
+ end
486
+ end
487
+ [add, del]
488
+ end
166
489
 
167
- _out, c_err, c_ok = git(dir, "commit", "-m", msg, "--", *paths)
168
- return { ok: false, error: "git commit failed: #{c_err.strip}" } unless c_ok
490
+ def trim_diff(text, max_lines)
491
+ lines = text.lines
492
+ return [text, false] if lines.size <= max_lines
493
+ [lines.first(max_lines).join, true]
494
+ end
169
495
 
170
- head, _err, _ok = git(dir, "rev-parse", "--short", "HEAD")
171
- { ok: true, hash: head.strip }
496
+ # Relative repo paths only: no absolute paths, no traversal segments.
497
+ def invalid_path?(path)
498
+ path.start_with?("/") || path.split("/").include?("..")
172
499
  end
173
500
  end
174
501
  end