pi-odd-worktree 2.1.0 → 3.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 (160) hide show
  1. package/README.md +54 -319
  2. package/extensions/odd-worktree-tools.ts +4182 -2539
  3. package/lib/bash-activity.js +1166 -0
  4. package/lib/bash-design.js +684 -0
  5. package/lib/bash-destructive.js +559 -0
  6. package/lib/bash-frame.js +205 -0
  7. package/lib/card-content.js +23 -0
  8. package/lib/card-style.js +175 -0
  9. package/lib/checkout-facts.js +30 -70
  10. package/lib/codegraph-card-preview.js +628 -0
  11. package/lib/codegraph-card.js +515 -0
  12. package/lib/codegraph-compaction.js +76 -0
  13. package/lib/codegraph-daemon.js +246 -0
  14. package/lib/codegraph-edit-sync.js +182 -0
  15. package/lib/codegraph-guard-target.js +337 -0
  16. package/lib/codegraph-guard.js +211 -0
  17. package/lib/codegraph-index.js +1020 -0
  18. package/lib/codegraph-lock.js +607 -0
  19. package/lib/codegraph-mcp-config.js +134 -0
  20. package/lib/codegraph-mcp.js +123 -0
  21. package/lib/codegraph-paths.js +69 -0
  22. package/lib/codegraph-prompt/explore.md +11 -0
  23. package/lib/codegraph-prompt/fix.md +6 -0
  24. package/lib/codegraph-prompt/generic.md +8 -0
  25. package/lib/codegraph-prompt/judge.md +9 -0
  26. package/lib/codegraph-prompt/orchestrator.md +17 -0
  27. package/lib/codegraph-prompt/verify.md +10 -0
  28. package/lib/codegraph-prompt/worker.md +7 -0
  29. package/lib/codegraph-role.js +55 -0
  30. package/lib/codegraph-rules.js +146 -0
  31. package/lib/codegraph-session.js +303 -383
  32. package/lib/codegraph-warmup.js +139 -0
  33. package/lib/file-card-markdown.js +141 -0
  34. package/lib/file-card-resolver.js +245 -0
  35. package/lib/file-card.js +659 -0
  36. package/lib/files-index.js +387 -0
  37. package/lib/files-insert.js +81 -0
  38. package/lib/files-orders.js +326 -0
  39. package/lib/files-picker-view.js +1421 -0
  40. package/lib/files-preview.js +338 -0
  41. package/lib/files-scope-detail.js +171 -0
  42. package/lib/files-scope-view.js +507 -0
  43. package/lib/gh-issues.js +323 -15
  44. package/lib/issue-preview.js +26 -7
  45. package/lib/issues-bash-mutation.js +206 -0
  46. package/lib/issues-cache-store.js +261 -0
  47. package/lib/issues-section.js +710 -0
  48. package/lib/issues-view.js +649 -52
  49. package/lib/odd-prompt/odd-worktrees.md +21 -0
  50. package/lib/odd-worktrees-prompt.js +10 -28
  51. package/lib/related-issues-cache.js +210 -0
  52. package/lib/shell-card.js +825 -0
  53. package/lib/skill-odd-card.js +183 -0
  54. package/lib/tui-paint.js +4 -5
  55. package/lib/warp-create-panel.js +538 -250
  56. package/lib/warp-create-picker.js +56 -9
  57. package/lib/warp-delete-confirm.js +19 -28
  58. package/lib/warp-selector-view.js +160 -82
  59. package/lib/which-command.js +90 -0
  60. package/lib/worktree-card.js +267 -897
  61. package/lib/worktree-cards.js +383 -0
  62. package/lib/worktree-create.js +287 -0
  63. package/lib/worktree-git.js +3 -3
  64. package/lib/worktree-guard.js +548 -0
  65. package/lib/worktree-hooks.js +421 -712
  66. package/lib/worktree-list.js +120 -0
  67. package/lib/worktree-registry.js +162 -879
  68. package/lib/{worktree-close-herdr.js → worktree-remove.js} +9 -11
  69. package/lib/worktree-setup-runner.js +376 -0
  70. package/lib/worktree-setup.js +140 -0
  71. package/lib/worktree-warp-busy.js +462 -85
  72. package/lib/worktree-warp-sessions.js +1 -2
  73. package/package.json +2 -2
  74. package/tools/bash-activity.test.js +1420 -0
  75. package/tools/bash-design.test.js +1093 -0
  76. package/tools/bash-destructive.test.js +139 -0
  77. package/tools/card-content.test.js +44 -0
  78. package/tools/card-style.test.js +298 -0
  79. package/tools/codegraph-card-preview.test.js +254 -0
  80. package/tools/codegraph-card.test.js +1080 -0
  81. package/tools/codegraph-compaction.test.js +378 -0
  82. package/tools/codegraph-daemon.test.js +248 -0
  83. package/tools/codegraph-edit-sync.test.js +295 -0
  84. package/tools/codegraph-guard-target.test.js +174 -0
  85. package/tools/codegraph-guard.test.js +238 -0
  86. package/tools/codegraph-index.test.js +1948 -0
  87. package/tools/codegraph-lock.test.js +932 -0
  88. package/tools/codegraph-mcp-config.test.js +181 -0
  89. package/tools/codegraph-mcp.test.js +194 -0
  90. package/tools/codegraph-paths.test.js +44 -0
  91. package/tools/codegraph-role.test.js +30 -0
  92. package/tools/codegraph-rules.test.js +250 -0
  93. package/tools/codegraph-session.test.js +660 -391
  94. package/tools/codegraph-warmup.test.js +316 -0
  95. package/tools/commands.test.js +510 -31
  96. package/tools/file-card-markdown.test.js +188 -0
  97. package/tools/file-card.test.js +1289 -0
  98. package/tools/files-bridge.test.js +575 -0
  99. package/tools/files-command.test.js +613 -0
  100. package/tools/files-index.test.js +473 -0
  101. package/tools/files-insert.test.js +139 -0
  102. package/tools/files-orders.test.js +597 -0
  103. package/tools/files-picker-view.test.js +1889 -0
  104. package/tools/files-preview.test.js +452 -0
  105. package/tools/files-scope-detail.test.js +264 -0
  106. package/tools/files-scope-view.test.js +614 -0
  107. package/tools/fixtures/card-codegraph-outputs.js +110 -0
  108. package/tools/fixtures/codegraph-cli-stub.js +16 -0
  109. package/tools/fixtures/codegraph-init-process.js +28 -0
  110. package/tools/fixtures/codegraph-lock-worker.js +117 -0
  111. package/tools/fixtures/daemon-fake.js +98 -0
  112. package/tools/fixtures/daemon-mcp-server.js +39 -0
  113. package/tools/fixtures/daemon-warmup-worker.js +12 -0
  114. package/tools/fixtures/load-extension.js +136 -3
  115. package/tools/gh-issues-feedback.test.js +31 -7
  116. package/tools/gh-issues.test.js +417 -1
  117. package/tools/issue-preview.test.js +44 -7
  118. package/tools/issues-bash-mutation.test.js +101 -0
  119. package/tools/issues-cache-store.test.js +222 -0
  120. package/tools/issues-command.test.js +1517 -67
  121. package/tools/issues-open-guard.test.js +1096 -0
  122. package/tools/issues-section.test.js +4235 -0
  123. package/tools/issues-seed-query-regression.test.js +67 -0
  124. package/tools/issues-view.test.js +1489 -60
  125. package/tools/odd-worktrees-prompt.test.js +98 -65
  126. package/tools/package-surface.test.js +431 -36
  127. package/tools/related-issues-cache.test.js +324 -0
  128. package/tools/shell-card.test.js +834 -0
  129. package/tools/skill-odd-card.test.js +200 -0
  130. package/tools/t5-session-identity.test.js +44 -22
  131. package/tools/warp-busy-guard.test.js +2565 -309
  132. package/tools/warp-create-panel.test.js +499 -74
  133. package/tools/warp-create-picker.test.js +101 -5
  134. package/tools/warp-delete-confirm.test.js +49 -15
  135. package/tools/warp-empty-session.test.js +0 -1
  136. package/tools/warp-fallback-regression.test.js +533 -0
  137. package/tools/warp-selector-view.test.js +460 -196
  138. package/tools/which-command.test.js +126 -0
  139. package/tools/worktree-card.test.js +551 -0
  140. package/tools/worktree-cards.test.js +845 -0
  141. package/tools/worktree-changes.test.js +4 -5
  142. package/tools/worktree-create.test.js +489 -0
  143. package/tools/worktree-guard.test.js +823 -0
  144. package/tools/worktree-hooks.test.js +905 -0
  145. package/tools/worktree-list.test.js +170 -0
  146. package/tools/worktree-registry.test.js +89 -230
  147. package/tools/worktree-remove-async.test.js +318 -0
  148. package/tools/worktree-setup-runner.test.js +276 -0
  149. package/tools/worktree-setup.test.js +140 -0
  150. package/tools/worktree-tools.test.js +419 -199
  151. package/lib/codegraph-commands.js +0 -165
  152. package/lib/odd-prompt/odd-worktrees.with-codegraph.md +0 -19
  153. package/lib/odd-prompt/odd-worktrees.without-codegraph.md +0 -15
  154. package/lib/worktree-model-result.js +0 -291
  155. package/tools/codegraph-commands.test.js +0 -371
  156. package/tools/herdr-free-create.test.js +0 -161
  157. package/tools/worktree-close-herdr-async.test.js +0 -204
  158. package/tools/worktree-odd-migration.test.js +0 -224
  159. package/tools/worktree-registry-cache.test.js +0 -163
  160. package/tools/worktree-registry-odd.test.js +0 -231
@@ -0,0 +1,383 @@
1
+ 'use strict';
2
+ // S5 / T5b: the call and result cards of the two worktree tools, drawn on the
3
+ // substrate of `lib/shell-card.js`.
4
+ //
5
+ // One factory builds both renderers, because both cards are the same card in two
6
+ // states: the call owns the heading (the tool's own name and its subject), the
7
+ // result owns the body (the tool's own text) and the closing rule, and the two
8
+ // halves meet as one rounded frame through the substrate's shared row mark. What
9
+ // each tool says is decided here; how a row is painted, wrapped and clipped is the
10
+ // substrate's (T5a), which is also where the tone roles come from.
11
+ //
12
+ // S5: the look is not decided here either. Every card is composed as its parts
13
+ // (`head`, `body`, `bottom`) and handed to the substrate's `floatRows`, which
14
+ // reads the style the shell chose ONCE per render and draws the whole card in it —
15
+ // the rounded neon frame, or the float rail over the tone background. Content,
16
+ // order, truncation, the collapsed preview and the elapsed time are the same text
17
+ // in both styles; only the chrome differs.
18
+ //
19
+ // The module is a pure function of its inputs plus that one read:
20
+ // * text measurement is injected as `metrics` — the substrate's required seam —
21
+ // so this package needs no node_modules and no host TUI package;
22
+ // * colour is the injected `theme.fg(role, text)` (and its optional `bg`); no
23
+ // escape sequence is written down here, and no role outside the substrate's
24
+ // palette is asked for;
25
+ // * the clock is not read: the elapsed time on the closing rule is the host's
26
+ // own `durationMs`, rendered by the substrate;
27
+ // * nothing is read from the filesystem or the process HERE. The style is the
28
+ // substrate's own input (lib/card-style.js: the shell's live slot, else the
29
+ // user's document, else float), so a style change reaches the next render
30
+ // without this module knowing about it.
31
+ //
32
+ // Both tool results are plain `{text, details}` views (lib/worktree-create.js
33
+ // `worktreeCreateView`, lib/worktree-list.js `worktreeListView`) inside the host's
34
+ // result shape `{content: [{type: 'text', text}], details, isError?}`, and the
35
+ // body is exactly that text: no card ever reformats what the tool said.
36
+ //
37
+ // A refusal is the tool's error text — one sentence and, for a create, the second
38
+ // line that says what to do instead — and it is treated like any other body:
39
+ // expanded it is wrapped, never clipped, and a width too narrow for the sentence
40
+ // still shows all of it on more rows; collapsed it shows the first three rows of
41
+ // that same body, and the last one ends in `…`, so the reason is never silently
42
+ // eaten and the reader always knows there is more. Both halves are pinned by
43
+ // tools/worktree-cards.test.js.
44
+ //
45
+ // The CONTENT LEVEL does not withhold these cards' rows (S2): a collapsed result
46
+ // always shows its bounded three-row preview, in both content levels, because those
47
+ // rows ARE the information the card exists to show — the created path, its branch
48
+ // and its odd, or the list's own first three rows. A failure still says why, and an
49
+ // expanded card still shows everything.
50
+ //
51
+ // The collapsed preview is the FIRST three rows of the expanded card, never a
52
+ // reordered selection: the two views never disagree about what comes first.
53
+ //
54
+ // The TONE is the `/warp` card's own: the documented `warning` role, which is the
55
+ // git-orange slot the moved checkout wears. A running call and a finished one are
56
+ // the same `warning` tone (the substring `running…` is what says which), and only a
57
+ // failure is `error`.
58
+
59
+ const {
60
+ CARD_TONE,
61
+ cardAwaitingResult,
62
+ cardBodyRows,
63
+ cardBottom,
64
+ cardElapsed,
65
+ cardInnerWidth,
66
+ cardMouseEvent,
67
+ cardRunningLine,
68
+ cardTopLine,
69
+ cardTopRows,
70
+ floatRows,
71
+ markCardResult,
72
+ } = require('./shell-card.js');
73
+
74
+ // The two tools this module draws, named as the host names them.
75
+ const WORKTREE_CARD_TOOLS = ['worktree_create', 'worktree_list'];
76
+
77
+ // The heading of each tool: the tool's own name, so the transcript never invents a
78
+ // second vocabulary for the same call. Both tools carry this package's git mark,
79
+ // one identity for every worktree card.
80
+ const TITLES = {
81
+ worktree_create: 'worktree create',
82
+ worktree_list: 'worktree list',
83
+ };
84
+ const GLYPH = '⎇';
85
+
86
+ // The host keybinding the expand affordance is bound to, and the two verbs the
87
+ // heading offers for it.
88
+ const EXPAND_KEYBINDING = 'app.tools.expand';
89
+ const EXPAND_TEXT = { collapsed: 'to expand', expanded: 'to collapse' };
90
+
91
+ // S5: the collapsed body budget. Expanded draws every row.
92
+ const PREVIEW_ROWS = 3;;
93
+ // The literal the substrate clips with, reused as the "there is more" mark.
94
+ const ELLIPSIS = '…';
95
+
96
+ const METRICS_FUNCTIONS = ['visibleWidth', 'truncateToWidth', 'wrapTextWithAnsi'];
97
+
98
+ const asObject = (value) => (value !== null && typeof value === 'object' ? value : {});
99
+ const asFunction = (value) => (typeof value === 'function' ? value : undefined);
100
+
101
+ function assertMetrics(value) {
102
+ if (value === null || typeof value !== 'object') {
103
+ throw new TypeError('createWorktreeCards requires an injected metrics object ({visibleWidth, truncateToWidth, wrapTextWithAnsi})');
104
+ }
105
+ for (const name of METRICS_FUNCTIONS) {
106
+ if (typeof value[name] !== 'function') {
107
+ throw new TypeError(`createWorktreeCards requires metrics.${name} to be a function`);
108
+ }
109
+ }
110
+ }
111
+
112
+ /**
113
+ * The text of a tool result: the host's `content` parts, or the `{text}` shape a
114
+ * refusal forwarded from another tool carries. Nothing is reformatted, trimmed or
115
+ * reordered — the card body IS what the tool said.
116
+ */
117
+ function resultText(result) {
118
+ const value = asObject(result);
119
+ if (typeof value.text === 'string') return value.text;
120
+ const parts = Array.isArray(value.content) ? value.content : [];
121
+ return parts
122
+ .map((part) => (typeof asObject(part).text === 'string' ? asObject(part).text : ''))
123
+ .filter((text) => text.length > 0)
124
+ .join('\n');
125
+ }
126
+
127
+ /** The detail the heading carries: the branch a create works on, `all` for a full list. */
128
+ function callDetail(toolName, args) {
129
+ const value = asObject(args);
130
+ if (toolName === 'worktree_create') {
131
+ return typeof value.branch === 'string' && value.branch.length > 0 ? value.branch : undefined;
132
+ }
133
+ return value.all === true ? 'all' : undefined;
134
+ }
135
+
136
+ /** Whether the host asked for the expanded card. Both slots carry the flag. */
137
+ function isExpanded(options, context) {
138
+ return asObject(options).expanded === true || asObject(context).expanded === true;
139
+ }
140
+
141
+ // ---- one card's own expansion choice ----
142
+ //
143
+ // `ctrl+o` is the HOST's expansion flag (`app.tools.expand`): it flips the flag for
144
+ // every expandable child at once, and each render context carries its value as
145
+ // `expanded`. A click must move ONE card, so a card keeps the value it chose for
146
+ // itself (`chosen`) beside a snapshot of the host flag it was made against
147
+ // (`seed`), both under this symbol in the row's own state — the `rendererState`
148
+ // the host hands every render of that one execution as `context.state`, and never
149
+ // another call's. A render resolves `chosen ?? context.expanded`; when the host
150
+ // flag no longer matches the snapshot the host moved it (ctrl+o, or the host's own
151
+ // `setExpanded`), so the choice is dropped and the card follows the host again.
152
+ // That keeps ctrl+o global and authoritative over an earlier click.
153
+ const EXPANSION_MARK = Symbol.for('gentle-pi.card-expansion');
154
+
155
+ function expansionChoice(state) {
156
+ if (state === null || typeof state !== 'object') return null;
157
+ let choice = state[EXPANSION_MARK];
158
+ if (choice === null || typeof choice !== 'object') {
159
+ choice = { seed: undefined, chosen: undefined };
160
+ state[EXPANSION_MARK] = choice;
161
+ }
162
+ return choice;
163
+ }
164
+
165
+ /** Whether THIS card is expanded: its own click choice, else the host's flag. */
166
+ function rowExpanded(state, hostExpanded) {
167
+ const choice = expansionChoice(state);
168
+ if (choice === null) return hostExpanded;
169
+ if (choice.seed !== hostExpanded) {
170
+ choice.seed = hostExpanded;
171
+ choice.chosen = undefined;
172
+ }
173
+ return choice.chosen === undefined ? hostExpanded : choice.chosen;
174
+ }
175
+
176
+ /** Flip this card's own choice, from the value it is showing now. Never throws. */
177
+ function flipRowExpanded(context) {
178
+ const ctx = asObject(context);
179
+ const hostExpanded = ctx.expanded === true;
180
+ const choice = expansionChoice(ctx.state);
181
+ if (choice === null) return;
182
+ const shown = choice.seed === hostExpanded && choice.chosen !== undefined ? choice.chosen : hostExpanded;
183
+ choice.seed = hostExpanded;
184
+ choice.chosen = !shown;
185
+ }
186
+
187
+ /** Whether the host asked for the expanded card, this card's own click choice winning over the flag. */
188
+ function rowIsExpanded(options, context) {
189
+ const ctx = asObject(context);
190
+ return rowExpanded(ctx.state, isExpanded(options, context));
191
+ }
192
+
193
+ /**
194
+ * The right-aligned dim hint the heading offers: the host's own keybinding text for
195
+ * expanding (or collapsing) the card. No keybinding seam means no hint, and a
196
+ * running row offers none at all.
197
+ */
198
+ function expandHint(context, expanded) {
199
+ const keyHint = asFunction(asObject(context).keyHint);
200
+ if (!keyHint) return undefined;
201
+ const text = keyHint(EXPAND_KEYBINDING, expanded ? EXPAND_TEXT.expanded : EXPAND_TEXT.collapsed);
202
+ return typeof text === 'string' && text.length > 0 ? text : undefined;
203
+ }
204
+
205
+ /** A row the host asked for, whatever it was: the floor the substrate itself uses. */
206
+ function rowWidth(width) {
207
+ return Math.max(0, Math.floor(Number.isFinite(width) ? width : 0));
208
+ }
209
+
210
+ /**
211
+ * The body's lines, in the tool's own order. A collapsed preview is the first
212
+ * `PREVIEW_ROWS` of them, exactly as the expanded card starts: the two views never
213
+ * disagree about what comes first.
214
+ */
215
+ function bodyLines(text) {
216
+ return text.split('\n');
217
+ }
218
+
219
+ /**
220
+ * The body rows of a result: the text wrapped to the inner width, capped by the
221
+ * preview budget unless expanded, and with `…` on the last preview row when the
222
+ * budget hides the rest. Painting, padding and clipping are the substrate's, so a
223
+ * row is always exactly as wide as the card it belongs to.
224
+ *
225
+ * `width` is the width the component draws at — the full width in the neon style,
226
+ * two columns narrower in float, where the substrate's margins live — so the body
227
+ * wraps to the columns the chrome actually leaves in either style.
228
+ *
229
+ * The three-row preview is drawn in BOTH content levels (S2): these rows are the
230
+ * card's information, so `minimal` no longer withholds them. A failure still says
231
+ * why, and an expanded card shows every row.
232
+ *
233
+ * Every row that survives the cap is a complete wrapped row — wrapping never cuts a
234
+ * word — so a growing body only ever appends after the preview it already showed.
235
+ *
236
+ * The rows handed to the substrate are PLAIN text: the body is the card's own text,
237
+ * so it is painted in the substrate's body role (`BODY_ROLE`: the theme's `text`)
238
+ * by `cardLine` AFTER it has been wrapped, clipped and padded. The tool's words
239
+ * stay the transcript's readable text while the chrome carries the state, and no
240
+ * painted row is measured a second time.
241
+ */
242
+ function resultBodyRows(text, tone, theme, width, state, metrics) {
243
+ if (text.length === 0 || width <= 0) return [];
244
+ const inner = cardInnerWidth(width);
245
+ const wrapped = bodyLines(text)
246
+ .flatMap((line) => (line === '' ? [''] : metrics.wrapTextWithAnsi(line, inner)));
247
+ const limit = state.expanded ? wrapped.length : Math.min(PREVIEW_ROWS, wrapped.length);
248
+ const shown = wrapped.slice(0, limit);
249
+ if (limit < wrapped.length && shown.length > 0) {
250
+ // The mark replaces the last column of a full row instead of widening it, so the
251
+ // row stays inside the card and no second wrap can push it onto another one.
252
+ const last = shown[shown.length - 1];
253
+ shown[shown.length - 1] = metrics.visibleWidth(last) >= inner
254
+ ? `${metrics.truncateToWidth(last, Math.max(0, inner - 1), '')}${ELLIPSIS}`
255
+ : `${last}${ELLIPSIS}`;
256
+ }
257
+ // The shown rows stay plain: the substrate wraps, clips and pads them and paints
258
+ // each one in the body role as its last step. A blank line keeps its blank row.
259
+ return cardBodyRows(shown, tone, theme, width, { expanded: true }, metrics);
260
+ }
261
+
262
+ /** One tool's card renderers, bound to the injected text seam. */
263
+ function toolRenderer(toolName, metrics) {
264
+ const title = TITLES[toolName];
265
+
266
+ /** The call: the heading, the running row while pending, and its frame while it awaits the result. */
267
+ function renderCall(args, theme, context) {
268
+ const ctx = asObject(context);
269
+ const pending = ctx.isPartial !== false;
270
+ const failed = ctx.isError === true;
271
+ // The warp card's tone, which a finished call keeps: only a failure is `error`.
272
+ const tone = failed ? CARD_TONE.ERROR : CARD_TONE.WARNING;
273
+ const expanded = rowIsExpanded(undefined, ctx);
274
+ const hint = pending || failed ? undefined : expandHint(ctx, expanded);
275
+ const card = { title, subtitle: callDetail(toolName, args), body: [], tone, glyph: GLYPH };
276
+
277
+ return component((width) => floatRows(tone, theme, width, (inner) => {
278
+ const head = expanded
279
+ ? cardTopRows(card, theme, inner, hint, metrics)
280
+ : [cardTopLine(card, theme, inner, hint, undefined, metrics)];
281
+ const body = pending && !failed ? [cardRunningLine(tone, theme, inner, metrics)] : [];
282
+ // The result that follows owns the closing rule; a call still waiting for it
283
+ // closes its own frame, so a running row never floats outside one.
284
+ const bottom = cardAwaitingResult(ctx) ? cardBottom(tone, theme, inner, undefined, metrics) : undefined;
285
+ return { head, body, bottom };
286
+ }), ctx);
287
+ }
288
+
289
+ /** The result: the tool's text as the body, then the closing rule with the elapsed time. */
290
+ function renderResult(result, options, theme, context) {
291
+ const opts = asObject(options);
292
+ const ctx = asObject(context);
293
+ const partial = opts.isPartial === true;
294
+ const failed = asObject(result).isError === true || opts.isError === true || ctx.isError === true;
295
+ // The same tone the call above wears, and the one the warp card has always had.
296
+ const tone = failed ? CARD_TONE.ERROR : CARD_TONE.WARNING;
297
+ const expanded = rowIsExpanded(opts, ctx);
298
+ const text = resultText(result);
299
+ // One frame: from here on the call above is a heading and this card closes it.
300
+ markCardResult(ctx.state);
301
+
302
+ return component((width) => floatRows(tone, theme, width, (inner) => {
303
+ const body = resultBodyRows(text, tone, theme, inner, { expanded }, metrics);
304
+ // A streamed result is not finished: the closing rule (and the time on it)
305
+ // belongs to the final one, which the host renders when the call settles.
306
+ const bottom = partial ? undefined : cardBottom(tone, theme, inner, cardElapsed(ctx.durationMs), metrics);
307
+ // The call above owns the heading, so the float style still sets this body
308
+ // off from it with its separator row.
309
+ return { body, bottom, afterHeading: true };
310
+ }), ctx);
311
+ }
312
+
313
+ return { renderCall, renderResult };
314
+ }
315
+
316
+ /**
317
+ * The host component around one card: `render(width)` returns the lines for that
318
+ * width and nothing else is remembered, so a card is a pure function of its
319
+ * inputs and a re-render never drifts.
320
+ *
321
+ * Every cell the card drew is a click target, and a click moves THIS card alone:
322
+ * the choice is stored in the render context's own `state` (see
323
+ * `EXPANSION_MARK`), never in the host's session-wide flag, so a sibling card
324
+ * keeps whatever it shows. The click then repaints through
325
+ * `context.invalidate()`, which the host scopes to this one execution; a context
326
+ * without that seam still gets the click, and the next render the host does
327
+ * applies the choice (the guard is what keeps a host double from throwing).
328
+ */
329
+ function component(build, context) {
330
+ let rows = [];
331
+ const card = {
332
+ render(width) {
333
+ rows = build(rowWidth(width));
334
+ return rows;
335
+ },
336
+ invalidate() {
337
+ // Nothing is cached: there is no measurement to invalidate.
338
+ },
339
+ // The press is claimed so the host retargets the click to this card; the
340
+ // click flips this card's choice and repaints this card only.
341
+ handleMouse: (event) => cardMouseEvent(event, rows, () => {
342
+ flipRowExpanded(context);
343
+ const invalidate = asObject(context).invalidate;
344
+ if (typeof invalidate === 'function') invalidate();
345
+ }),
346
+ };
347
+ return card;
348
+ }
349
+
350
+ /**
351
+ * One factory for both tools: `createWorktreeCards({ metrics })` returns
352
+ * `renderer(toolName)` → `{renderCall(args, theme, context),
353
+ * renderResult(result, options, theme, context)}`, the two hooks the host spreads
354
+ * over the tool definitions. An unknown tool name is a programming error, not a
355
+ * card: the removed tools must not silently borrow one of these.
356
+ *
357
+ * The text seam is required. The content level is no longer an input: S2 keeps the
358
+ * three info rows in both levels, so there is no reader to inject.
359
+ */
360
+ function createWorktreeCards(dependencies) {
361
+ const { metrics } = asObject(dependencies);
362
+ assertMetrics(metrics);
363
+ const renderers = new Map();
364
+ return {
365
+ renderer(toolName) {
366
+ if (!WORKTREE_CARD_TOOLS.includes(toolName)) {
367
+ throw new Error(`unknown worktree tool: ${typeof toolName === 'string' ? toolName : typeof toolName}`);
368
+ }
369
+ let renderer = renderers.get(toolName);
370
+ if (renderer === undefined) {
371
+ renderer = toolRenderer(toolName, metrics);
372
+ renderers.set(toolName, renderer);
373
+ }
374
+ return renderer;
375
+ },
376
+ };
377
+ }
378
+
379
+ module.exports = {
380
+ ELLIPSIS,
381
+ WORKTREE_CARD_TOOLS,
382
+ createWorktreeCards,
383
+ };
@@ -0,0 +1,287 @@
1
+ 'use strict';
2
+ // The core of `worktree_create`.
3
+ //
4
+ // Git owns the mechanics — the base ref, the branch, the administrative directory and
5
+ // the checkout — and this module owns the decisions that must be right before anything
6
+ // lands on disk: where the worktree goes, which branch it takes and which ref it starts
7
+ // from, each refused with the exact sentence the agent reads. Every Git call passes an
8
+ // argument array, so no value is ever interpolated into a shell.
9
+ //
10
+ // The preparation hooks live in `worktree-hooks.js` (T5): they run once the worktree
11
+ // exists, and the create prints their dedicated `copy_changes` line (S18). Nothing is
12
+ // stored about them (S1): the checkout's directory is the only record, so a hook
13
+ // outcome is reported once, in the create's answer, and never persisted.
14
+ //
15
+ // `copy_changes` arrives as a further hook and the setup chain (T7) starts after it,
16
+ // so nothing here is written around them.
17
+
18
+ const { basename, dirname, isAbsolute, join } = require('node:path');
19
+ const { parseWorktreePorcelain } = require('./worktree-registry.js');
20
+ const { worktreeCopyChangesLine } = require('./worktree-hooks.js');
21
+
22
+ /** S27: the sentence a session outside a Git worktree gets, shared with the tool and its tests. */
23
+ const WORKTREE_NOT_A_REPOSITORY = 'not inside a Git worktree, so there is no repository to create a worktree from';
24
+
25
+ /** S5: what a single path segment may say, printed under every refusal. */
26
+ const WORKTREE_SEGMENT_HINT = 'odd must be a single path segment (letters, digits, dash, underscore, dot)';
27
+
28
+ const BASE_RESOLUTION_FAILURE = 'could not resolve a base branch: tried main, origin/HEAD, init.defaultBranch';
29
+ const SHORT_SHA_LENGTH = 7;
30
+ const CONTROL_CHARACTER = /[\u0000-\u001f\u007f]/;
31
+
32
+ // ---- S1 and S5: the name and the destination ----
33
+
34
+ /** S5: one segment, so no value can escape the directory it names. */
35
+ function isWorktreeSegment(value) {
36
+ return typeof value === 'string'
37
+ && value.length > 0
38
+ // A segment of nothing but whitespace is not a name, and the store refuses it
39
+ // too (S4: the ODD field is optional, its type is not), so it is refused here
40
+ // instead of creating a worktree whose record can never be written.
41
+ && value.trim().length > 0
42
+ && !CONTROL_CHARACTER.test(value)
43
+ && !value.includes('/')
44
+ && !value.includes('\\')
45
+ && !value.includes('..')
46
+ && !isAbsolute(value);
47
+ }
48
+
49
+ /** S5/S7: the one sentence an unusable or absent `odd` prints, shared with the panel. */
50
+ function oddRefusal(value) {
51
+ if (isWorktreeSegment(value)) return undefined;
52
+ return { code: 'invalid-odd', message: `invalid odd name: ${JSON.stringify(value)}\n${WORKTREE_SEGMENT_HINT}` };
53
+ }
54
+
55
+ /**
56
+ * S7: `<repo-parent>/<repo-name>-worktrees/<odd>`, derived from the canonical main root.
57
+ * The directory IS the ODD, so the branch never names a checkout and two worktrees for
58
+ * one ODD cannot coexist.
59
+ */
60
+ function worktreeDestinationPath(mainRoot, odd) {
61
+ return join(dirname(mainRoot), `${basename(mainRoot)}-worktrees`, odd);
62
+ }
63
+
64
+ // ---- S2 and S3: what Git answers ----
65
+
66
+ async function readGitText(git, cwd, args) {
67
+ const result = await git(cwd, args);
68
+ if (!result || result.code !== 0) return undefined;
69
+ const text = result.stdout.trim();
70
+ return text.length > 0 ? text : undefined;
71
+ }
72
+
73
+ /**
74
+ * S2 in order: a local `main`, then the default branch `origin/HEAD` names, then
75
+ * `init.defaultBranch`. A candidate whose ref does not resolve cannot supply the commit
76
+ * the worktree starts from, so it is passed over.
77
+ */
78
+ async function resolveWorktreeBase(git, cwd) {
79
+ const candidates = [{ branch: 'main', startRef: 'refs/heads/main' }];
80
+ const originHead = await readGitText(git, cwd, ['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD']);
81
+ const remoteBranch = originHead?.replace(/^origin\//, '');
82
+ if (remoteBranch) candidates.push({ branch: remoteBranch, startRef: `refs/remotes/origin/${remoteBranch}` });
83
+ const configured = await readGitText(git, cwd, ['config', '--get', 'init.defaultBranch']);
84
+ if (configured) candidates.push({ branch: configured, startRef: `refs/heads/${configured}` });
85
+ for (const candidate of candidates) {
86
+ const sha = await readGitText(git, cwd, ['rev-parse', '--verify', '--quiet', candidate.startRef]);
87
+ if (sha) return { branch: candidate.branch, startRef: candidate.startRef, sha };
88
+ }
89
+ return undefined;
90
+ }
91
+
92
+ /**
93
+ * An explicit `base`: the branch a new branch starts from instead of the default one,
94
+ * for a flow that integrates somewhere else (a `dev` branch in git flow) or a piece of
95
+ * work that resumes from another branch. A local branch is preferred, as it is for the
96
+ * default; `origin/<base>` answers for one that only exists there.
97
+ */
98
+ function baseRefusal(value) {
99
+ if (typeof value === 'string' && value.trim().length > 0 && !CONTROL_CHARACTER.test(value) && !value.startsWith('-')) {
100
+ return undefined;
101
+ }
102
+ return { code: 'invalid-base', message: `invalid base: ${JSON.stringify(value)}\nbase must be the name of an existing branch` };
103
+ }
104
+
105
+ async function resolveExplicitBase(git, cwd, name) {
106
+ for (const startRef of [`refs/heads/${name}`, `refs/remotes/origin/${name}`]) {
107
+ const sha = await readGitText(git, cwd, ['rev-parse', '--verify', '--quiet', startRef]);
108
+ if (sha) return { branch: name, startRef, sha };
109
+ }
110
+ return undefined;
111
+ }
112
+
113
+ /** S3: the worktree path Git reports for a branch, when one already holds it. */
114
+ async function findBranchHolder(git, cwd, branch) {
115
+ const listing = await git(cwd, ['worktree', 'list', '--porcelain']);
116
+ if (!listing || listing.code !== 0) return undefined;
117
+ return parseWorktreePorcelain(listing.stdout).find((entry) => entry.branch === branch)?.path;
118
+ }
119
+
120
+ // ---- Planning ----
121
+
122
+ /**
123
+ * Validates the request against the clone and returns either the plan to run or the
124
+ * exact refusal. Input validation comes first and touches neither Git nor the
125
+ * filesystem (S5); after that every question is read-only, so a refusal leaves the
126
+ * clone exactly as it was found.
127
+ */
128
+ async function planWorktreeCreate(request, repository, seams) {
129
+ // S7: the ODD names the directory, so it is REQUIRED — an absent one is refused
130
+ // with the same sentence an unusable one gets, before Git or the filesystem.
131
+ const refused = oddRefusal(request.odd);
132
+ if (refused) return { ok: false, error: refused };
133
+
134
+ // An explicit `base` replaces the default resolution and is checked like the ODD: its
135
+ // shape first, before Git runs; omitting it (or passing undefined) changes nothing.
136
+ const explicitBase = request.base !== undefined;
137
+ if (explicitBase) {
138
+ const invalid = baseRefusal(request.base);
139
+ if (invalid) return { ok: false, error: invalid };
140
+ }
141
+ const base = explicitBase
142
+ ? await resolveExplicitBase(seams.git, repository.mainRoot, request.base)
143
+ : await resolveWorktreeBase(seams.git, repository.mainRoot);
144
+ if (!base && explicitBase) {
145
+ return {
146
+ ok: false,
147
+ error: {
148
+ code: 'base-not-found',
149
+ message: `could not resolve base branch ${request.base}: tried ${request.base}, origin/${request.base}`,
150
+ },
151
+ };
152
+ }
153
+ if (!base) return { ok: false, error: { code: 'no-base-branch', message: BASE_RESOLUTION_FAILURE } };
154
+ if (request.branch === base.branch) {
155
+ return {
156
+ ok: false,
157
+ error: {
158
+ code: 'base-branch-is-target',
159
+ message: `branch ${request.branch} is the base branch; pick the branch this worktree should work on`,
160
+ },
161
+ };
162
+ }
163
+
164
+ const path = worktreeDestinationPath(repository.mainRoot, request.odd);
165
+ if (seams.exists(path)) {
166
+ return {
167
+ ok: false,
168
+ error: { code: 'path-exists', message: `worktree path already exists: ${path}\nRemove it or pass a different odd.` },
169
+ };
170
+ }
171
+
172
+ const holder = await findBranchHolder(seams.git, repository.mainRoot, request.branch);
173
+ if (holder !== undefined) {
174
+ return {
175
+ ok: false,
176
+ error: {
177
+ code: 'branch-in-use',
178
+ message: `branch ${request.branch} is already checked out in ${holder}\nUse a different branch, or work in that worktree.`,
179
+ },
180
+ };
181
+ }
182
+
183
+ const branchRef = `refs/heads/${request.branch}`;
184
+ const existing = (await readGitText(seams.git, repository.mainRoot, ['rev-parse', '--verify', '--quiet', branchRef])) !== undefined;
185
+ // A base only decides where a NEW branch starts. An existing branch is checked out as
186
+ // it is, so a base beside it would be silently ignored: refuse it instead.
187
+ if (existing && explicitBase) {
188
+ return {
189
+ ok: false,
190
+ error: {
191
+ code: 'base-on-existing-branch',
192
+ message: `branch ${request.branch} already exists, so it is checked out as it is; base only applies when the branch is created`,
193
+ },
194
+ };
195
+ }
196
+ // A plain branch name is what makes `worktree add` check the branch out; a fully
197
+ // qualified ref would detach the new worktree's HEAD.
198
+ const args = existing
199
+ ? ['worktree', 'add', path, request.branch]
200
+ : ['worktree', 'add', '-b', request.branch, path, base.startRef];
201
+ return {
202
+ ok: true,
203
+ plan: {
204
+ mainRoot: repository.mainRoot,
205
+ path,
206
+ odd: request.odd,
207
+ branch: request.branch,
208
+ branchState: existing ? 'existing' : 'created',
209
+ base: base.branch,
210
+ startRef: base.startRef,
211
+ baseSha: base.sha,
212
+ shortSha: base.sha.slice(0, SHORT_SHA_LENGTH),
213
+ copyChanges: request.copy_changes === true,
214
+ args,
215
+ },
216
+ };
217
+ }
218
+
219
+ // ---- Executing the plan ----
220
+
221
+ /**
222
+ * Runs the planned create. `git worktree add` is the whole effect: nothing is recorded
223
+ * afterwards, because the destination directory IS the record (S3). A Git failure is
224
+ * the caller's sentence and leaves the clone as it was.
225
+ */
226
+ async function executeWorktreeCreatePlan(input) {
227
+ const added = await input.git(input.plan.mainRoot, input.plan.args);
228
+ if (!added || added.code !== 0) {
229
+ return {
230
+ ok: false,
231
+ error: {
232
+ code: 'git-failed',
233
+ message: `could not create the worktree at ${input.plan.path}: git worktree add exited ${added === undefined ? 'without a result' : added.code}`,
234
+ },
235
+ };
236
+ }
237
+ return { ok: true, result: {} };
238
+ }
239
+
240
+ // ---- S16: the agent-facing output ----
241
+
242
+ /**
243
+ * S16: the fixed lines of a successful create, in order, with no padding and no ANSI.
244
+ *
245
+ * S1: the hooks part and the setup part are gone — at call time this answer knows
246
+ * neither which hooks were skipped nor how the background chain went, so printing
247
+ * either would state a guess. The dedicated `copy_changes` line stays: it reports the
248
+ * copy this very call performed.
249
+ */
250
+ function worktreeCreateView(result) {
251
+ const { plan } = result;
252
+ const lines = [
253
+ `worktree created: ${plan.path}`,
254
+ `branch: ${plan.branch} (${plan.branchState})`,
255
+ // The ODD is the directory's name, so the create names it once, here.
256
+ `odd: ${plan.odd}`,
257
+ `base: ${plan.base}@${plan.shortSha}`,
258
+ result.registered ? 'worktree register in session' : 'worktree register failed',
259
+ ];
260
+ // S18: its own line, only when the parameter was passed.
261
+ const copyChanges = result.hooks?.find((hook) => hook.name === 'copy_changes')?.copyChanges;
262
+ const copyChangesLine = result.hooks === undefined ? undefined : worktreeCopyChangesLine(result.hooks);
263
+ if (copyChangesLine !== undefined) lines.push(copyChangesLine);
264
+ const details = {
265
+ path: plan.path,
266
+ // The name IS the directory's basename, which is the ODD.
267
+ name: basename(plan.path),
268
+ branch: plan.branch,
269
+ branchState: plan.branchState,
270
+ base: plan.base,
271
+ baseSha: plan.baseSha,
272
+ odd: plan.odd,
273
+ registered: result.registered,
274
+ };
275
+ if (copyChanges !== undefined) details.copyChanges = { copied: copyChanges.copied, failed: [...copyChanges.failed] };
276
+ return { text: lines.join('\n'), details };
277
+ }
278
+
279
+ module.exports = {
280
+ WORKTREE_NOT_A_REPOSITORY,
281
+ WORKTREE_SEGMENT_HINT,
282
+ isWorktreeSegment,
283
+ worktreeDestinationPath,
284
+ planWorktreeCreate,
285
+ executeWorktreeCreatePlan,
286
+ worktreeCreateView,
287
+ };
@@ -337,9 +337,9 @@ function resetCommonDirCache() {
337
337
  commonDirCache.clear();
338
338
  }
339
339
 
340
- // Flatten a branch name into a single path component, exactly like the
341
- // AGENTS.md rule: lowercase, runs of non-alphanumerics collapse to one
342
- // `-`, leading/trailing dashes trimmed, `worktree` when nothing survives.
340
+ // Flatten a branch name into a single path component: lowercase, runs of
341
+ // non-alphanumerics collapse to one `-`, leading/trailing dashes trimmed,
342
+ // `worktree` when nothing survives.
343
343
  function slugifyBranch(branch) {
344
344
  const slug = String(branch).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
345
345
  return slug === '' ? 'worktree' : slug;