@yagni-app/code 1.0.0 → 1.0.1

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 (55) hide show
  1. package/README.md +42 -0
  2. package/dist/cli.js +231 -6
  3. package/dist/crashReport.d.ts +8 -0
  4. package/dist/crashReport.js +13 -1
  5. package/dist/doctor.d.ts +7 -0
  6. package/dist/doctor.js +33 -0
  7. package/dist/extension/askAdvisorTool.d.ts +7 -0
  8. package/dist/extension/askAdvisorTool.js +11 -3
  9. package/dist/extension/askYagniTool.js +2 -0
  10. package/dist/extension/branding.d.ts +15 -0
  11. package/dist/extension/branding.js +76 -0
  12. package/dist/extension/chipEditor.d.ts +22 -1
  13. package/dist/extension/chipEditor.js +58 -5
  14. package/dist/extension/condensedTools.d.ts +93 -0
  15. package/dist/extension/condensedTools.js +392 -0
  16. package/dist/extension/diffStat.d.ts +62 -0
  17. package/dist/extension/diffStat.js +158 -0
  18. package/dist/extension/footer.d.ts +2 -0
  19. package/dist/extension/footer.js +21 -8
  20. package/dist/extension/index.d.ts +6 -0
  21. package/dist/extension/index.js +70 -2
  22. package/dist/extension/permission/execPolicy.js +47 -0
  23. package/dist/extension/pipeline/invocation.d.ts +7 -0
  24. package/dist/extension/pipeline/invocation.js +7 -0
  25. package/dist/extension/pipeline/personas.js +4 -4
  26. package/dist/extension/pipeline/runner.d.ts +1 -0
  27. package/dist/extension/pipeline/runner.js +15 -3
  28. package/dist/extension/pipeline/sessionWorktree.d.ts +64 -0
  29. package/dist/extension/pipeline/sessionWorktree.js +225 -0
  30. package/dist/extension/scratchpad.d.ts +66 -0
  31. package/dist/extension/scratchpad.js +93 -0
  32. package/dist/extension/subagents.d.ts +10 -0
  33. package/dist/extension/subagents.js +18 -4
  34. package/dist/extension/todos.d.ts +1 -0
  35. package/dist/extension/todos.js +15 -0
  36. package/dist/extension/toolRuns.d.ts +92 -0
  37. package/dist/extension/toolRuns.js +201 -0
  38. package/dist/extension/webFetchTool.js +2 -0
  39. package/dist/extension/workingLine.d.ts +49 -0
  40. package/dist/extension/workingLine.js +116 -0
  41. package/dist/feedback.d.ts +77 -0
  42. package/dist/feedback.js +500 -0
  43. package/dist/goHeadless.d.ts +3 -0
  44. package/dist/goHeadless.js +13 -0
  45. package/dist/launch.d.ts +8 -0
  46. package/dist/launch.js +6 -0
  47. package/dist/otel.d.ts +150 -0
  48. package/dist/otel.js +291 -0
  49. package/dist/outputFormat.d.ts +83 -0
  50. package/dist/outputFormat.js +207 -0
  51. package/dist/paths.d.ts +10 -0
  52. package/dist/paths.js +13 -0
  53. package/dist/worktreeArgs.d.ts +43 -0
  54. package/dist/worktreeArgs.js +96 -0
  55. package/package.json +3 -2
@@ -0,0 +1,392 @@
1
+ /**
2
+ * Condensed, Claude Code-style rendering for pi's seven built-in tools.
3
+ *
4
+ * pi resolves renderers per slot (`toolDefinition.renderCall ?? builtIn.renderCall`),
5
+ * so re-registering a built-in by name with the SAME factory-made definition
6
+ * spread underneath swaps ONLY the presentation: name, description, parameters,
7
+ * prompt metadata, and execution semantics stay byte-identical with the
8
+ * built-in (execution delegates to the same `create*ToolDefinition` the session
9
+ * would have built, including the settings-driven bash shellPath/commandPrefix
10
+ * and read image auto-resize). pi 0.84.1 registers such overrides silently —
11
+ * there is no built-in-override startup warning in this version (verified
12
+ * against dist; the extensions.md claim is stale).
13
+ *
14
+ * Rendering contract per row (renderShell "self", so no tinted Box):
15
+ * - renderCall paints the TITLE slot: a live "● Tool(arg)" line while running,
16
+ * a "● Tool(arg)" line for visible rows, the run summary line for the tail
17
+ * of a completed quiet run, or nothing (a zero-line component removes the
18
+ * row entirely, including its spacer).
19
+ * - renderResult paints the BODY slot: condensed write/edit previews, bash
20
+ * error/partial output tails, or nothing. Expanded (ctrl+o) shows full
21
+ * output for every row.
22
+ *
23
+ * String assembly is pure over {@link RenderTheme} (subagentRender.ts's
24
+ * pattern) so tests run against plain text. Renderer exceptions are swallowed
25
+ * by pi (degrading to the built-in fallback), so everything stays total.
26
+ */
27
+ import * as os from "node:os";
28
+ import * as path from "node:path";
29
+ import { createBashToolDefinition, createEditToolDefinition, createFindToolDefinition, createGrepToolDefinition, createLsToolDefinition, createReadToolDefinition, createWriteToolDefinition, getAgentDir, getLanguageFromPath, highlightCode, renderDiff, SettingsManager, } from "@earendil-works/pi-coding-agent";
30
+ import { Container, Text } from "@earendil-works/pi-tui";
31
+ import { isQuiet, kindForTool, ToolRunTracker } from "./toolRuns.js";
32
+ /** Lines of write content shown collapsed (mirrors Claude Code's preview). */
33
+ export const WRITE_PREVIEW_LINES = 8;
34
+ /** Visual lines of a diff shown collapsed. */
35
+ export const DIFF_PREVIEW_LINES = 12;
36
+ /** Output tail lines shown under a failed shell command. */
37
+ export const ERROR_TAIL_LINES = 5;
38
+ /** Output tail lines shown under a still-running shell command. */
39
+ export const PARTIAL_TAIL_LINES = 3;
40
+ /** Hard cap on expanded body lines so a huge output cannot stall a repaint. */
41
+ const EXPANDED_MAX_LINES = 1000;
42
+ /** Title arg preview width. */
43
+ const ARG_PREVIEW_MAX = 96;
44
+ const BUILTIN_NAMES = ["read", "bash", "edit", "write", "grep", "find", "ls"];
45
+ const TITLE_BY_NAME = {
46
+ read: "Read",
47
+ bash: "Bash",
48
+ edit: "Edit",
49
+ write: "Write",
50
+ grep: "Grep",
51
+ find: "Find",
52
+ ls: "List",
53
+ };
54
+ /** Collapse whitespace and clip to `max`, appending an ellipsis when cut. */
55
+ function clip(text, max) {
56
+ const collapsed = text.replace(/\s+/g, " ").trim();
57
+ if (collapsed.length <= max)
58
+ return collapsed;
59
+ return `${collapsed.slice(0, max - 1)}…`;
60
+ }
61
+ /** Forward slashes for comparison and display, on every platform. */
62
+ function slashed(p) {
63
+ return p.replace(/\\/g, "/");
64
+ }
65
+ /** Home-collapse, and prefer cwd-relative for paths inside the project. */
66
+ export function displayPath(rawPath, cwd) {
67
+ if (!rawPath)
68
+ return rawPath;
69
+ let display = slashed(rawPath);
70
+ if (cwd) {
71
+ // Resolve BOTH sides so a POSIX-style cwd and Windows' drive-letter
72
+ // absolute paths compare in the same space.
73
+ const absolute = slashed(path.resolve(cwd, rawPath));
74
+ const base = slashed(path.resolve(cwd)).replace(/\/+$/, "");
75
+ if (absolute.startsWith(`${base}/`))
76
+ return absolute.slice(base.length + 1);
77
+ display = absolute;
78
+ }
79
+ const home = slashed(os.homedir());
80
+ return display.startsWith(home) ? `~${display.slice(home.length)}` : display;
81
+ }
82
+ /** Whether a tool-call path targets the session scratchpad. */
83
+ export function isScratchpadPath(rawPath, scratchpadDir, cwd) {
84
+ if (typeof rawPath !== "string" || !rawPath || !scratchpadDir)
85
+ return false;
86
+ const absolute = slashed(path.resolve(cwd ?? process.cwd(), rawPath));
87
+ const base = slashed(path.resolve(scratchpadDir)).replace(/\/+$/, "");
88
+ return absolute === base || absolute.startsWith(`${base}/`);
89
+ }
90
+ /** The one argument worth showing in a title: path, command, or pattern. */
91
+ export function primaryArg(name, args, cwd) {
92
+ const a = args ?? {};
93
+ const str = (v) => (typeof v === "string" ? v : "");
94
+ switch (name) {
95
+ case "bash":
96
+ return clip(str(a.command) || "…", ARG_PREVIEW_MAX);
97
+ case "grep": {
98
+ const pattern = str(a.pattern) || "…";
99
+ const where = str(a.path);
100
+ return clip(where ? `${pattern} in ${displayPath(where, cwd)}` : pattern, ARG_PREVIEW_MAX);
101
+ }
102
+ case "find":
103
+ return clip(str(a.pattern) || "…", ARG_PREVIEW_MAX);
104
+ case "ls":
105
+ return clip(displayPath(str(a.path) || ".", cwd), ARG_PREVIEW_MAX);
106
+ default: {
107
+ const p = str(a.path);
108
+ let display = p ? displayPath(p, cwd) : "…";
109
+ if (name === "read" && (a.offset !== undefined || a.limit !== undefined)) {
110
+ const start = typeof a.offset === "number" ? a.offset : 1;
111
+ const end = typeof a.limit === "number" ? start + a.limit - 1 : undefined;
112
+ display += `:${start}${end !== undefined ? `-${end}` : ""}`;
113
+ }
114
+ return clip(display, ARG_PREVIEW_MAX);
115
+ }
116
+ }
117
+ }
118
+ function statusDot(status, theme) {
119
+ if (status === "error")
120
+ return theme.fg("error", "●");
121
+ if (status === "running")
122
+ return theme.fg("accent", "●");
123
+ return theme.fg("success", "●");
124
+ }
125
+ /** `● Tool(arg)` — the visible-row (and live-row) title line. */
126
+ export function formatRowTitle(name, args, status, theme, cwd) {
127
+ const title = theme.bold(theme.fg("toolTitle", TITLE_BY_NAME[name]));
128
+ return `${statusDot(status, theme)} ${title}(${theme.fg("accent", primaryArg(name, args, cwd))})`;
129
+ }
130
+ /** Extract "Command exited with code N" from a bash error body, if present. */
131
+ export function splitBashError(outputText) {
132
+ const match = outputText.match(/\n*(Command exited with code \d+)\s*$/);
133
+ if (!match)
134
+ return { output: outputText.trimEnd(), exitLine: undefined };
135
+ return { output: outputText.slice(0, match.index).trimEnd(), exitLine: match[1] };
136
+ }
137
+ function indent(lines, pad) {
138
+ return lines.map((line) => pad + line);
139
+ }
140
+ /** `⎿ exit line` + a dim tail of output under a failed shell command. */
141
+ export function formatBashErrorBody(outputText, theme) {
142
+ const { output, exitLine } = splitBashError(outputText);
143
+ const lines = [];
144
+ lines.push(` ${theme.fg("muted", "⎿")} ${theme.fg("error", exitLine ?? "Command failed")}`);
145
+ const tail = output.split("\n").filter((l) => l.length > 0).slice(-ERROR_TAIL_LINES);
146
+ lines.push(...indent(tail.map((l) => theme.fg("toolOutput", l)), " "));
147
+ return lines;
148
+ }
149
+ /** A dim tail of live output under a still-running shell command. */
150
+ export function formatBashPartialBody(outputText, theme) {
151
+ const tail = outputText.split("\n").filter((l) => l.length > 0).slice(-PARTIAL_TAIL_LINES);
152
+ return indent(tail.map((l) => theme.fg("dim", l)), " ");
153
+ }
154
+ /** Count added lines in a unified patch (edit summaries surface "+N"). */
155
+ export function countPatchAdditions(patch) {
156
+ if (!patch)
157
+ return 0;
158
+ let added = 0;
159
+ for (const line of patch.split("\n")) {
160
+ if (line.startsWith("+") && !line.startsWith("+++"))
161
+ added += 1;
162
+ }
163
+ return added;
164
+ }
165
+ function countPatchRemovals(patch) {
166
+ if (!patch)
167
+ return 0;
168
+ let removed = 0;
169
+ for (const line of patch.split("\n")) {
170
+ if (line.startsWith("-") && !line.startsWith("---"))
171
+ removed += 1;
172
+ }
173
+ return removed;
174
+ }
175
+ const EXPAND_HINT = "(ctrl+o to expand)";
176
+ /**
177
+ * `⎿ Wrote N lines to path` + a numbered, syntax-highlighted preview.
178
+ * `highlight` is injectable so tests stay independent of pi's theme state.
179
+ */
180
+ export function formatWriteBody(rawPath, content, expanded, theme, cwd, highlight = highlightForPath) {
181
+ const allLines = content.replace(/\n$/, "").split("\n");
182
+ const total = allLines.length;
183
+ const shownCount = expanded ? Math.min(total, EXPANDED_MAX_LINES) : Math.min(total, WRITE_PREVIEW_LINES);
184
+ const head = ` ${theme.fg("muted", "⎿")} Wrote ${total} ${total === 1 ? "line" : "lines"} to ${theme.fg("accent", displayPath(rawPath, cwd))}`;
185
+ const shown = allLines.slice(0, shownCount);
186
+ const painted = highlight(shown.join("\n"), rawPath);
187
+ const numberWidth = String(shownCount).length;
188
+ const body = painted
189
+ .slice(0, shownCount)
190
+ .map((line, i) => ` ${theme.fg("dim", String(i + 1).padStart(numberWidth))} ${line}`);
191
+ const lines = [head, ...body];
192
+ if (total > shownCount) {
193
+ lines.push(` ${theme.fg("muted", `… +${total - shownCount} lines ${EXPAND_HINT}`)}`);
194
+ }
195
+ return lines;
196
+ }
197
+ /** Default highlighter: pi's theme-backed syntax highlighting, failing to plain lines. */
198
+ function highlightForPath(code, filePath) {
199
+ try {
200
+ return highlightCode(code, getLanguageFromPath(filePath));
201
+ }
202
+ catch {
203
+ return code.split("\n");
204
+ }
205
+ }
206
+ /**
207
+ * `⎿ Updated path (+A -R)` + a colored diff preview.
208
+ * `paintDiff` is injectable for the same reason as `highlight` above.
209
+ */
210
+ export function formatEditBody(rawPath, details, expanded, theme, cwd, paintDiff = defaultPaintDiff) {
211
+ const added = countPatchAdditions(details?.patch);
212
+ const removed = countPatchRemovals(details?.patch);
213
+ const counts = added || removed
214
+ ? ` (${[added ? theme.fg("success", `+${added}`) : "", removed ? theme.fg("error", `-${removed}`) : ""]
215
+ .filter(Boolean)
216
+ .join(" ")})`
217
+ : "";
218
+ const head = ` ${theme.fg("muted", "⎿")} Updated ${theme.fg("accent", displayPath(rawPath, cwd))}${counts}`;
219
+ const diffText = details?.diff;
220
+ if (!diffText)
221
+ return [head];
222
+ const diffLines = paintDiff(diffText).split("\n");
223
+ const cap = expanded ? EXPANDED_MAX_LINES : DIFF_PREVIEW_LINES;
224
+ const lines = [head, ...indent(diffLines.slice(0, cap), " ")];
225
+ if (diffLines.length > cap) {
226
+ lines.push(` ${theme.fg("muted", `… +${diffLines.length - cap} lines ${EXPAND_HINT}`)}`);
227
+ }
228
+ return lines;
229
+ }
230
+ function defaultPaintDiff(diffText) {
231
+ try {
232
+ return renderDiff(diffText);
233
+ }
234
+ catch {
235
+ return diffText;
236
+ }
237
+ }
238
+ /** Expanded body: the raw output, dimmed and capped. */
239
+ export function formatExpandedOutput(outputText, theme) {
240
+ const lines = outputText.replace(/\n$/, "").split("\n");
241
+ const shown = lines.slice(0, EXPANDED_MAX_LINES).map((l) => theme.fg("toolOutput", l));
242
+ if (lines.length > EXPANDED_MAX_LINES) {
243
+ shown.push(theme.fg("muted", `… +${lines.length - EXPANDED_MAX_LINES} lines`));
244
+ }
245
+ return shown;
246
+ }
247
+ function textOf(result) {
248
+ return (result?.content ?? [])
249
+ .filter((c) => c.type === "text" && typeof c.text === "string")
250
+ .map((c) => c.text)
251
+ .join("\n");
252
+ }
253
+ function hasImages(result) {
254
+ return (result?.content ?? []).some((c) => c.type === "image");
255
+ }
256
+ function empty() {
257
+ return new Container();
258
+ }
259
+ function textComponent(lines) {
260
+ return lines.length === 0 ? empty() : new Text(lines.join("\n"), 0, 0);
261
+ }
262
+ function defaultLoadSettings(cwd) {
263
+ return SettingsManager.create(cwd, getAgentDir());
264
+ }
265
+ /**
266
+ * Re-register the seven built-ins with condensed renderers. Returns the
267
+ * tracker so callers (and tests) can feed message boundaries into it.
268
+ */
269
+ export function registerCondensedTools(pi, deps = {}) {
270
+ const tracker = new ToolRunTracker();
271
+ const registrationCwd = deps.cwd ?? process.cwd();
272
+ // Assistant/user prose breaks a run; toolResult messages must not (they are
273
+ // interleaved between the very rows a run aggregates).
274
+ pi.on("message_start", (event) => {
275
+ const role = event.message?.role;
276
+ if (role === "assistant" || role === "user")
277
+ tracker.markBreak();
278
+ });
279
+ let toolOptions;
280
+ try {
281
+ const settings = (deps.loadSettings ?? defaultLoadSettings)(registrationCwd);
282
+ toolOptions = {
283
+ bash: { shellPath: settings.getShellPath(), commandPrefix: settings.getShellCommandPrefix() },
284
+ read: { autoResizeImages: settings.getImageAutoResize() },
285
+ };
286
+ }
287
+ catch {
288
+ toolOptions = { bash: {}, read: {} };
289
+ }
290
+ const buildDefinitions = (cwd) => ({
291
+ read: createReadToolDefinition(cwd, toolOptions.read),
292
+ bash: createBashToolDefinition(cwd, toolOptions.bash),
293
+ edit: createEditToolDefinition(cwd),
294
+ write: createWriteToolDefinition(cwd),
295
+ grep: createGrepToolDefinition(cwd),
296
+ find: createFindToolDefinition(cwd),
297
+ ls: createLsToolDefinition(cwd),
298
+ });
299
+ const definitionsByCwd = new Map();
300
+ const definitionsFor = (cwd) => {
301
+ let defs = definitionsByCwd.get(cwd);
302
+ if (!defs) {
303
+ defs = buildDefinitions(cwd);
304
+ definitionsByCwd.set(cwd, defs);
305
+ }
306
+ return defs;
307
+ };
308
+ definitionsByCwd.set(registrationCwd, buildDefinitions(registrationCwd));
309
+ for (const name of BUILTIN_NAMES) {
310
+ const base = definitionsFor(registrationCwd)[name];
311
+ const kind = kindForTool(name);
312
+ const upsertFromCall = (context) => {
313
+ const args = context.args;
314
+ return tracker.upsert(context.toolCallId, {
315
+ kind,
316
+ scratchpad: isScratchpadPath(args?.path, deps.scratchpadDir, context.cwd),
317
+ error: context.isError,
318
+ final: !context.isPartial,
319
+ invalidate: context.invalidate,
320
+ });
321
+ };
322
+ pi.registerTool({
323
+ ...base,
324
+ renderShell: "self",
325
+ execute(toolCallId, params, signal, onUpdate, ctx) {
326
+ const cwd = ctx?.cwd ?? registrationCwd;
327
+ return definitionsFor(cwd)[name].execute(toolCallId, params, signal, onUpdate, ctx);
328
+ },
329
+ renderCall(args, theme, context) {
330
+ const slice = context;
331
+ const row = upsertFromCall(slice);
332
+ const status = slice.isError ? "error" : slice.isPartial ? "running" : "ok";
333
+ const argsRecord = args;
334
+ if (slice.expanded || !isQuiet(row)) {
335
+ return new Text(formatRowTitle(name, argsRecord, status, theme, slice.cwd), 0, 0);
336
+ }
337
+ if (!row.final) {
338
+ return new Text(formatRowTitle(name, argsRecord, "running", theme, slice.cwd), 0, 0);
339
+ }
340
+ const summary = tracker.summaryFor(row.id);
341
+ return summary ? new Text(theme.fg("muted", summary), 0, 0) : empty();
342
+ },
343
+ renderResult(result, options, theme, context) {
344
+ const slice = context;
345
+ const args = (slice.args ?? {});
346
+ const row = tracker.upsert(slice.toolCallId, {
347
+ kind,
348
+ final: !options.isPartial,
349
+ error: slice.isError,
350
+ images: hasImages(result),
351
+ added: name === "write" && typeof args.content === "string"
352
+ ? args.content.replace(/\n$/, "").split("\n").length
353
+ : name === "edit"
354
+ ? countPatchAdditions(result.details?.patch)
355
+ : 0,
356
+ });
357
+ if (options.expanded) {
358
+ if (name === "write" && typeof args.path === "string" && typeof args.content === "string" && !slice.isError) {
359
+ return textComponent(formatWriteBody(args.path, args.content, true, theme, slice.cwd));
360
+ }
361
+ if (name === "edit" && typeof args.path === "string" && !slice.isError && result.details) {
362
+ return textComponent(formatEditBody(args.path, result.details, true, theme, slice.cwd));
363
+ }
364
+ const output = textOf(result);
365
+ return output ? textComponent(formatExpandedOutput(output, theme)) : empty();
366
+ }
367
+ if (name === "bash" && options.isPartial) {
368
+ return textComponent(formatBashPartialBody(textOf(result), theme));
369
+ }
370
+ if (isQuiet(row))
371
+ return empty();
372
+ if (slice.isError) {
373
+ if (name === "bash")
374
+ return textComponent(formatBashErrorBody(textOf(result), theme));
375
+ const message = textOf(result).split("\n").filter(Boolean).slice(-ERROR_TAIL_LINES);
376
+ return textComponent(message.map((l, i) => (i === 0 ? ` ${theme.fg("muted", "⎿")} ${theme.fg("error", l)}` : ` ${theme.fg("toolOutput", l)}`)));
377
+ }
378
+ if (name === "write" && typeof args.path === "string" && typeof args.content === "string") {
379
+ return textComponent(formatWriteBody(args.path, args.content, false, theme, slice.cwd));
380
+ }
381
+ if (name === "edit" && typeof args.path === "string") {
382
+ return textComponent(formatEditBody(args.path, result.details, false, theme, slice.cwd));
383
+ }
384
+ // Visible for another reason (e.g. an image read): title already
385
+ // painted by renderCall; images render themselves below the row.
386
+ return empty();
387
+ },
388
+ });
389
+ }
390
+ return tracker;
391
+ }
392
+ //# sourceMappingURL=condensedTools.js.map
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Committed branch diff stat for the footer's git badge.
3
+ *
4
+ * Counting follows Codex (`tui/src/branch_summary.rs`), not Kimi: it sums the
5
+ * line delta between `HEAD` and the merge base with the repository's *default*
6
+ * branch, so the badge answers "what does this branch contain" — the same
7
+ * number a GitHub PR UI would show. Uncommitted working-tree edits are
8
+ * intentionally ignored (Codex: "the status-line item summarizes the checked-
9
+ * out branch, not the current dirty worktree").
10
+ *
11
+ * Display follows Kimi: `[+N -M]` appended to the branch, dim grey.
12
+ *
13
+ * Refresh reuses Kimi's synchronous TTL model: re-read at most every 15s,
14
+ * demanded on each footer render. The only divergence from Codex is that their
15
+ * probe is `async`; ours is `spawnSync` because the footer render path is
16
+ * synchronous.
17
+ */
18
+ /** Committed branch delta relative to the default branch. */
19
+ export interface BranchDiffStat {
20
+ readonly added: number;
21
+ readonly deleted: number;
22
+ }
23
+ /** Diff-stat source with a workDir, callable on demand. */
24
+ export interface DiffStatCache {
25
+ /** Current stat, or `null` when workDir isn't a git repo. */
26
+ get(): BranchDiffStat | null;
27
+ }
28
+ /**
29
+ * Injectable git runner seam (tests stub it; production shells out to `git`).
30
+ * Returns stdout, or `null` on any failure.
31
+ */
32
+ export type GitRunner = (args: string[], cwd: string) => string | null;
33
+ /** True when `cwd` is inside a git work tree. Never throws. */
34
+ export declare function detectGitRepo(run: GitRunner, cwd: string): boolean;
35
+ /** Codex's `parseDiffNumstatCount`-equivalent: `-` (binary) → 0; non-numeric → 0. */
36
+ export declare function parseNumstatCount(value: string | undefined): number;
37
+ /**
38
+ * Resolve the default branch name, preferring remote-tracking refs over local
39
+ * branches so a stale local `main` doesn't inflate the diff (Codex's ordering).
40
+ * Falls back to common local names when no remote advertises a default.
41
+ * Returns null when nothing resolves.
42
+ */
43
+ export declare function resolveDefaultBranch(run: GitRunner, cwd: string): string | null;
44
+ /**
45
+ * Sum the committed line delta between `HEAD` and the merge base with the
46
+ * default branch: `git diff --numstat <merge-base>..HEAD`. Returns null when
47
+ * the default branch or merge base can't be resolved (hide the badge).
48
+ */
49
+ export declare function readDiffStat(run: GitRunner, cwd: string): BranchDiffStat | null;
50
+ /**
51
+ * Kimi-style display: `+N -M`, or null when the branch is even with its base
52
+ * (a fresh/unchanged branch shows no badge). Both-zero still renders nothing,
53
+ * matching "our style" (Kimi hides a clean tree; Codex would say "No changes").
54
+ */
55
+ export declare function formatDiffStat(diff: BranchDiffStat | null): string | null;
56
+ /**
57
+ * Time-bucketed cache: `get()` re-reads git only when the last read was more
58
+ * than 15s ago, null off-repo. All git failures → null (badge hidden), never
59
+ * throws.
60
+ */
61
+ export declare function createDiffStatCache(workDir: string, run?: GitRunner): DiffStatCache;
62
+ //# sourceMappingURL=diffStat.d.ts.map
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Committed branch diff stat for the footer's git badge.
3
+ *
4
+ * Counting follows Codex (`tui/src/branch_summary.rs`), not Kimi: it sums the
5
+ * line delta between `HEAD` and the merge base with the repository's *default*
6
+ * branch, so the badge answers "what does this branch contain" — the same
7
+ * number a GitHub PR UI would show. Uncommitted working-tree edits are
8
+ * intentionally ignored (Codex: "the status-line item summarizes the checked-
9
+ * out branch, not the current dirty worktree").
10
+ *
11
+ * Display follows Kimi: `[+N -M]` appended to the branch, dim grey.
12
+ *
13
+ * Refresh reuses Kimi's synchronous TTL model: re-read at most every 15s,
14
+ * demanded on each footer render. The only divergence from Codex is that their
15
+ * probe is `async`; ours is `spawnSync` because the footer render path is
16
+ * synchronous.
17
+ */
18
+ import { spawnSync } from "node:child_process";
19
+ /** Status refresh interval — same value Kimi uses (STATUS_TTL_MS). */
20
+ const STATUS_TTL_MS = 15_000;
21
+ /** git spawn timeout — same value Kimi uses (SPAWN_TIMEOUT_MS). */
22
+ const SPAWN_TIMEOUT_MS = 500;
23
+ const SPAWN_MAX_BUFFER = 4 * 1024 * 1024;
24
+ /** Production runner: `spawnSync` with a short timeout, all errors → null. */
25
+ function runGit(args, cwd) {
26
+ try {
27
+ const r = spawnSync("git", ["--no-optional-locks", ...args], {
28
+ cwd,
29
+ encoding: "utf8",
30
+ timeout: SPAWN_TIMEOUT_MS,
31
+ maxBuffer: SPAWN_MAX_BUFFER,
32
+ stdio: ["ignore", "pipe", "ignore"],
33
+ });
34
+ if (r.error || r.status !== 0)
35
+ return null;
36
+ return r.stdout;
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ }
42
+ /** True when `cwd` is inside a git work tree. Never throws. */
43
+ export function detectGitRepo(run, cwd) {
44
+ const out = run(["rev-parse", "--is-inside-work-tree"], cwd);
45
+ return out !== null && out.trim() === "true";
46
+ }
47
+ /** Codex's `parseDiffNumstatCount`-equivalent: `-` (binary) → 0; non-numeric → 0. */
48
+ export function parseNumstatCount(value) {
49
+ if (value === undefined || value === "-")
50
+ return 0;
51
+ const n = Number.parseInt(value, 10);
52
+ return Number.isFinite(n) && n > 0 ? n : 0;
53
+ }
54
+ /** List remotes, `origin` first (mirrors Codex's `get_git_remotes`). */
55
+ function gitRemotes(run, cwd) {
56
+ const out = run(["remote"], cwd);
57
+ if (out === null)
58
+ return [];
59
+ const remotes = out.split("\n").map((l) => l.trim()).filter(Boolean);
60
+ const originIdx = remotes.indexOf("origin");
61
+ if (originIdx > 0) {
62
+ remotes.splice(originIdx, 1);
63
+ remotes.unshift("origin");
64
+ }
65
+ return remotes;
66
+ }
67
+ /**
68
+ * Resolve the default branch name, preferring remote-tracking refs over local
69
+ * branches so a stale local `main` doesn't inflate the diff (Codex's ordering).
70
+ * Falls back to common local names when no remote advertises a default.
71
+ * Returns null when nothing resolves.
72
+ */
73
+ export function resolveDefaultBranch(run, cwd) {
74
+ // Tier 1: remote default via `refs/remotes/<remote>/HEAD` symbolic ref.
75
+ for (const remote of gitRemotes(run, cwd)) {
76
+ const out = run(["symbolic-ref", "--quiet", `refs/remotes/${remote}/HEAD`], cwd);
77
+ if (out === null)
78
+ continue;
79
+ const ref = out.trim();
80
+ if (!ref)
81
+ continue;
82
+ // `refs/remotes/origin/main` → `main`.
83
+ const name = ref.replace(/^refs\/remotes\/[^/]+\//, "");
84
+ if (name && name !== "HEAD")
85
+ return name;
86
+ }
87
+ // Tier 2: local main/master/trunk/develop.
88
+ for (const candidate of ["main", "master", "trunk", "develop"]) {
89
+ const out = run(["rev-parse", "--verify", "--quiet", candidate], cwd);
90
+ if (out !== null && out.trim())
91
+ return candidate;
92
+ }
93
+ return null;
94
+ }
95
+ /**
96
+ * Sum the committed line delta between `HEAD` and the merge base with the
97
+ * default branch: `git diff --numstat <merge-base>..HEAD`. Returns null when
98
+ * the default branch or merge base can't be resolved (hide the badge).
99
+ */
100
+ export function readDiffStat(run, cwd) {
101
+ const defaultBranch = resolveDefaultBranch(run, cwd);
102
+ if (defaultBranch === null)
103
+ return null;
104
+ const mergeBase = run(["merge-base", "HEAD", defaultBranch], cwd);
105
+ if (mergeBase === null || !mergeBase.trim())
106
+ return null;
107
+ const out = run(["diff", "--numstat", `${mergeBase.trim()}..HEAD`, "--"], cwd);
108
+ if (out === null)
109
+ return null;
110
+ let added = 0;
111
+ let deleted = 0;
112
+ for (const line of out.split("\n")) {
113
+ if (!line)
114
+ continue;
115
+ const [addedText, deletedText] = line.split("\t");
116
+ added += parseNumstatCount(addedText);
117
+ deleted += parseNumstatCount(deletedText);
118
+ }
119
+ return { added, deleted };
120
+ }
121
+ /**
122
+ * Kimi-style display: `+N -M`, or null when the branch is even with its base
123
+ * (a fresh/unchanged branch shows no badge). Both-zero still renders nothing,
124
+ * matching "our style" (Kimi hides a clean tree; Codex would say "No changes").
125
+ */
126
+ export function formatDiffStat(diff) {
127
+ if (diff === null)
128
+ return null;
129
+ const parts = [];
130
+ if (diff.added > 0)
131
+ parts.push(`+${String(diff.added)}`);
132
+ if (diff.deleted > 0)
133
+ parts.push(`-${String(diff.deleted)}`);
134
+ return parts.length > 0 ? parts.join(" ") : null;
135
+ }
136
+ /**
137
+ * Time-bucketed cache: `get()` re-reads git only when the last read was more
138
+ * than 15s ago, null off-repo. All git failures → null (badge hidden), never
139
+ * throws.
140
+ */
141
+ export function createDiffStatCache(workDir, run = runGit) {
142
+ const isRepo = detectGitRepo(run, workDir);
143
+ let cached = null;
144
+ let fetchedAt = 0;
145
+ return {
146
+ get() {
147
+ if (!isRepo)
148
+ return null;
149
+ const now = Date.now();
150
+ if (cached === null || now - fetchedAt >= STATUS_TTL_MS) {
151
+ cached = readDiffStat(run, workDir);
152
+ fetchedAt = now;
153
+ }
154
+ return cached;
155
+ },
156
+ };
157
+ }
158
+ //# sourceMappingURL=diffStat.js.map
@@ -96,6 +96,8 @@ export declare function renderFooterLines(input: {
96
96
  model: string;
97
97
  /** Current permission mode; shown on line 2 to the left of the model as "<mode> mode". */
98
98
  mode?: PermissionMode | null;
99
+ /** Formatted `+N -M` / `±`, or null when clean — appended to the branch as `[ … ]`. */
100
+ diff?: string | null;
99
101
  usage: UsageTotals;
100
102
  contextPercent: number | null;
101
103
  statuses: string[];