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,1096 @@
1
+ 'use strict';
2
+ // T1 (issues-sidebar-click S1, S2): the rail click's single-flight guard and the
3
+ // numbered open's cached-scope identity pin, driven through the loaded extension
4
+ // with a fake host, a fake bridge and injected `gh`/`git` seams.
5
+ //
6
+ // Contract under test, through the public surface only:
7
+ // - while a rail click is being opened, every further rail click — the same row,
8
+ // another numbered row, the overflow row — is a no-op: exactly ONE
9
+ // `/issues …` message reaches the host, nothing is appended, notified or
10
+ // repainted, and the click callback returns normally (no throw, no refusal);
11
+ // - the effect comes back when the open is over: the panel mounted, an early
12
+ // return before it (the gh gate, a cwd outside a checkout, no interactive
13
+ // host, a failed identity proof), a throw, or the bounded safety interval —
14
+ // unref'd, about ten seconds — for a command the host never ran;
15
+ // - a typed `/issues` is never held back by a click in flight;
16
+ // - the guard belongs to one session generation: a click left over by a
17
+ // previous session never blocks the next one, and a shutdown releases it;
18
+ // - a numbered open (`/issues <n>`, the form the rail dispatches) pins the
19
+ // identity from the checkout's CACHED scope, so its first frame is seeded from
20
+ // the rail's cache for that identity, while a plain `/issues` keeps the FRESH
21
+ // proof; a cached pin that cannot be read falls back to the fresh one once;
22
+ // - the identity pin and the TUI helper load start together.
23
+ //
24
+ // Every child process is injected: `gh` through lib/gh-issues.js `setGhRunner`,
25
+ // the identity read's `git` through its `setGitRunner`, and the checkouts live
26
+ // under os.tmpdir() and are removed in `after()`. The bridge slot is
27
+ // process-wide, so it is always deleted again.
28
+
29
+ const { test, after, afterEach, beforeEach } = require('node:test');
30
+ const assert = require('node:assert/strict');
31
+ const fs = require('node:fs');
32
+ const os = require('node:os');
33
+ const path = require('node:path');
34
+ const { execFileSync } = require('node:child_process');
35
+
36
+ const { LIB_DIR, stubbedSource } = require('./fixtures/load-extension.js');
37
+ const { pathToFileURL } = require('node:url');
38
+
39
+ const BRIDGE_SLOT = Symbol.for('gentle-shell-bridge/api/v1');
40
+ // `waitFor` and the timer fixtures poll with the REAL timer, even while one test
41
+ // replaces the global one to fake the safety interval.
42
+ const realSetTimeout = setTimeout;
43
+
44
+ const stubTui = {
45
+ visibleWidth: (text) => [...String(text)].length,
46
+ truncateToWidth: (text, width) => {
47
+ const chars = [...String(text)];
48
+ return chars.length > width ? chars.slice(0, Math.max(0, width - 1)).join('') + '…' : String(text);
49
+ },
50
+ matchesKey: (key, name) => key === name,
51
+ isKeyRelease: (key) => key === 'release',
52
+ };
53
+
54
+ // The lib instance the extension load actually uses, so an injected runner
55
+ // reaches the code under test.
56
+ let ghIssues = null;
57
+ let restores = [];
58
+
59
+ const roots = [];
60
+ after(() => {
61
+ for (const dir of roots) {
62
+ try { fs.rmSync(dir, { recursive: true, force: true }); } catch {}
63
+ }
64
+ });
65
+
66
+ afterEach(() => {
67
+ delete globalThis[BRIDGE_SLOT];
68
+ if (ghIssues) {
69
+ ghIssues.setGhRunner(null);
70
+ ghIssues.setGitRunner(null);
71
+ }
72
+ for (const restore of restores) {
73
+ try { restore(); } catch {}
74
+ }
75
+ restores = [];
76
+ });
77
+
78
+ // S4 (issues-startup-performance T3): the issues read cache has a disk half, and
79
+ // this file DRAWS the rail, so every test gets an empty cache directory of its
80
+ // own — nothing here can read or write the real `$XDG_CACHE_HOME`/`~/.cache`
81
+ // document, and no test inherits a warm identity from another.
82
+ beforeEach(() => {
83
+ process.env.XDG_CACHE_HOME = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-issues-guard-cache-')));
84
+ });
85
+
86
+ function track(dir) {
87
+ roots.push(dir);
88
+ return dir;
89
+ }
90
+
91
+ // A fresh copy per load (the fixture's stubbed source is cached, the module is
92
+ // not), returning the module namespace so a test can reach the lib instance THIS
93
+ // load uses and the extension's test seams.
94
+ async function loadExtension(pi) {
95
+ const dir = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-issues-guard-ext-')));
96
+ const copy = path.join(dir, 'odd-worktree-tools.mjs');
97
+ fs.writeFileSync(copy, stubbedSource());
98
+ const commands = new Map();
99
+ const hooks = [];
100
+ const api = {
101
+ registerTool: () => {},
102
+ registerCommand: (name, definition) => { commands.set(name, definition); },
103
+ registerMessageRenderer: () => {},
104
+ registerEntryRenderer: () => {},
105
+ appendEntry: (customType, data) => { entries.push({ customType, data }); },
106
+ on: (event, handler) => { hooks.push([event, handler]); return () => {}; },
107
+ ...pi,
108
+ };
109
+ const entries = [];
110
+ process.env.GENTLE_WORKTREE_LIB_DIR = LIB_DIR;
111
+ const mod = await import(pathToFileURL(copy).href);
112
+ mod.default(api);
113
+ return { commands, hooks, api, mod, entries };
114
+ }
115
+
116
+ function git(cwd, args) {
117
+ return execFileSync('git', args, {
118
+ cwd,
119
+ encoding: 'utf8',
120
+ env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null' },
121
+ });
122
+ }
123
+
124
+ // A real checkout with TWO remotes (a fork), the case whose identity comes from
125
+ // the checkout's OWN git configuration: a CACHED scope read then reuses what the
126
+ // rail already proved, while a FRESH one reads git again. That is the difference
127
+ // the numbered open is tested against. `singleRemote` builds the other shape — one
128
+ // remote, so gh's own `repo view` is the whole identity — which is the shape whose
129
+ // cached-scope pin still paid that network call before the click carried its row's
130
+ // identity.
131
+ function makeCheckout({
132
+ singleRemote = false,
133
+ origin = 'git@github.com:myfork/project.git',
134
+ upstream = 'git@github.com:original/project.git',
135
+ } = {}) {
136
+ const dir = track(fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-issues-guard-'))));
137
+ git(dir, ['init']);
138
+ git(dir, ['config', 'user.email', 'test@example.com']);
139
+ git(dir, ['config', 'user.name', 'Test']);
140
+ git(dir, ['commit', '--allow-empty', '-m', 'init']);
141
+ git(dir, ['remote', 'add', 'origin', origin]);
142
+ if (!singleRemote) git(dir, ['remote', 'add', 'upstream', upstream]);
143
+ return dir;
144
+ }
145
+
146
+ // A SECOND checkout naming ANOTHER repository. An open that does not ride a rail
147
+ // row's identity pins THIS repository instead, so "did the click's hint survive?"
148
+ // is visible in the identity the reads are bound to, not only in how many children
149
+ // the open spawned.
150
+ function otherCheckout() {
151
+ return makeCheckout({
152
+ origin: 'git@github.com:other/project.git',
153
+ upstream: 'git@github.com:other/upstream.git',
154
+ });
155
+ }
156
+
157
+ // The remote URL each checkout of a test names: the harness checkout is
158
+ // `myfork/project` and `other` (when a test has one) is `other/project`.
159
+ function checkoutRemotes(other) {
160
+ const otherPath = other === undefined || other === null ? null : path.resolve(other);
161
+ return (cwd) => (otherPath !== null && path.resolve(String(cwd)) === otherPath
162
+ ? 'git@github.com:other/project.git'
163
+ : 'git@github.com:myfork/project.git');
164
+ }
165
+
166
+ function okJson(stdout) {
167
+ return { status: 0, stdout, stderr: '', error: null };
168
+ }
169
+
170
+ function issue(number, updatedAt = '2024-01-01T00:00:00Z') {
171
+ return { number, title: `Issue ${number}`, state: 'OPEN', updatedAt };
172
+ }
173
+
174
+ // Nine issues: seven painted rows and the overflow row, so a click on any row of
175
+ // the body and on the overflow row is available to the guard tests.
176
+ function nineIssues() {
177
+ return Array.from({ length: 9 }, (_, index) => {
178
+ const day = String(index + 1).padStart(2, '0');
179
+ return issue(100 + index, `2024-01-${day}T00:00:00Z`);
180
+ });
181
+ }
182
+
183
+ // The GraphQL node the rail's ONE combined read returns for a test row.
184
+ function graphqlNode(item) {
185
+ return {
186
+ number: item.number,
187
+ title: typeof item.title === 'string' ? item.title : '',
188
+ state: 'OPEN',
189
+ stateReason: '',
190
+ url: '',
191
+ createdAt: '',
192
+ updatedAt: typeof item.updatedAt === 'string' ? item.updatedAt : '',
193
+ author: { login: 'me' },
194
+ labels: { nodes: [] },
195
+ comments: { totalCount: 0 },
196
+ reactionGroups: [],
197
+ timelineItems: { nodes: [] },
198
+ };
199
+ }
200
+
201
+ function relatedAnswer({ mine = [], assigned = [], involved = [] } = {}) {
202
+ const bucket = (rows) => ({ issueCount: rows.length, nodes: rows.map(graphqlNode) });
203
+ return { data: { mine: bucket(mine), assigned: bucket(assigned), involved: bucket(involved) } };
204
+ }
205
+
206
+ // gh's answers for the rail's combined read and the gate. Each call records the
207
+ // scope it ran with: the identity reaches gh as `GH_REPO` in its environment, so
208
+ // `repo` is the repository the read was actually bound to.
209
+ function fakeGithub({ assigned = [], gate = true } = {}) {
210
+ const calls = [];
211
+ const runner = async (bin, argv, runOpts = {}) => {
212
+ const env = runOpts.env || {};
213
+ calls.push({
214
+ bin,
215
+ argv: argv.slice(),
216
+ cwd: runOpts.cwd,
217
+ repo: typeof env.GH_REPO === 'string' && env.GH_REPO.length > 0 ? env.GH_REPO : null,
218
+ });
219
+ if (argv[0] === 'api' && argv[1] === 'user') {
220
+ return gate ? okJson('{"login":"me"}') : { status: 1, stdout: '', stderr: 'not logged in', error: null };
221
+ }
222
+ if (argv[0] === 'repo' && argv[1] === 'view') {
223
+ return okJson(JSON.stringify({ nameWithOwner: 'myfork/project' }));
224
+ }
225
+ if (argv[0] === 'api' && argv[1] === 'graphql') {
226
+ return okJson(JSON.stringify(relatedAnswer({ assigned })));
227
+ }
228
+ return okJson('');
229
+ };
230
+ return { runner, calls };
231
+ }
232
+
233
+ function realGit(argv, cwd) {
234
+ try {
235
+ const stdout = execFileSync('git', argv, {
236
+ cwd,
237
+ encoding: 'utf8',
238
+ env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null' },
239
+ });
240
+ return { status: 0, stdout, stderr: '', error: null };
241
+ } catch (err) {
242
+ return {
243
+ status: typeof err.status === 'number' ? err.status : 1,
244
+ stdout: String(err.stdout || ''),
245
+ stderr: String(err.stderr || ''),
246
+ error: null,
247
+ };
248
+ }
249
+ }
250
+
251
+ // The identity read's own git seam, over the fixture's REAL git configuration but
252
+ // with the head remote's URL under the test's control: flipping `remoteUrl.value`
253
+ // models a checkout whose remote moved, and the CACHED scope keeps the identity it
254
+ // already proved (a fingerprint over the unchanged configuration still matches)
255
+ // while the FRESH one reads the new URL. `urlForCwd` answers per checkout, for the
256
+ // tests that run an open in a checkout naming another repository.
257
+ function identityGit({
258
+ remoteUrl = { value: 'git@github.com:myfork/project.git' },
259
+ failConfigReads = 0,
260
+ urlForCwd = null,
261
+ } = {}) {
262
+ const calls = [];
263
+ let configReads = 0;
264
+ return {
265
+ calls,
266
+ remoteUrl,
267
+ run: (argv, opts = {}) => {
268
+ calls.push(argv.slice());
269
+ if (argv[0] === 'config') {
270
+ configReads += 1;
271
+ if (configReads <= failConfigReads) return { status: 1, stdout: '', stderr: 'bad config', error: null };
272
+ return realGit(argv, opts.cwd);
273
+ }
274
+ if (argv[0] === 'remote' && argv[1] === 'get-url') {
275
+ const value = urlForCwd === null ? remoteUrl.value : urlForCwd(opts.cwd);
276
+ return { status: 0, stdout: `${value}\n`, stderr: '', error: null };
277
+ }
278
+ return realGit(argv, opts.cwd);
279
+ },
280
+ };
281
+ }
282
+
283
+ function installBridge() {
284
+ const registered = [];
285
+ const repaints = [];
286
+ globalThis[BRIDGE_SLOT] = {
287
+ schema: 'gentle-shell-bridge/api',
288
+ version: 1,
289
+ registerRows: () => {},
290
+ registerSection: (section) => { registered.push(section); return () => {}; },
291
+ createStore: () => ({}),
292
+ requestRepaint: () => { repaints.push(1); },
293
+ };
294
+ return { registered, repaints };
295
+ }
296
+
297
+ function sessionStartHandlers(hooks) {
298
+ return hooks.filter(([event]) => event === 'session_start').map(([, handler]) => handler);
299
+ }
300
+
301
+ async function fireSessionStart(hooks, ctx) {
302
+ for (const handler of sessionStartHandlers(hooks)) {
303
+ const out = handler({}, ctx);
304
+ if (out && typeof out.then === 'function') await out;
305
+ }
306
+ }
307
+
308
+ async function fireHook(hooks, event, ctx) {
309
+ for (const handler of hooks.filter(([name]) => name === event).map(([, fn]) => fn)) {
310
+ const out = handler({ toolResults: [] }, ctx);
311
+ if (out && typeof out.then === 'function') await out;
312
+ }
313
+ }
314
+
315
+ async function waitFor(predicate, message) {
316
+ const deadline = Date.now() + 8000;
317
+ while (Date.now() < deadline) {
318
+ if (predicate()) return;
319
+ await new Promise((resolve) => realSetTimeout(resolve, 10));
320
+ }
321
+ throw new Error(message);
322
+ }
323
+
324
+ // Let a deferred click and its promise chain settle before the next assertion.
325
+ async function settle(ms = 25) {
326
+ await new Promise((resolve) => realSetTimeout(resolve, ms));
327
+ }
328
+
329
+ // Only a drawn section reads, so the draw IS the trigger: poll it until its own
330
+ // TTL read has landed.
331
+ async function waitForRows(section, ctx) {
332
+ const deadline = Date.now() + 8000;
333
+ while (Date.now() < deadline) {
334
+ const rows = section.lines(ctx);
335
+ if (!(rows.length === 1 && rows[0].label === 'loading…')) return rows;
336
+ await new Promise((resolve) => realSetTimeout(resolve, 10));
337
+ }
338
+ throw new Error('the section never left loading');
339
+ }
340
+
341
+ // `draw: false` runs the session in a SECOND checkout: the startup `gh` probe
342
+ // warms nothing in the fixture checkout under test, so a numbered open there meets
343
+ // a COLD scope cache and has to prove the identity — the pattern the command tests
344
+ // use for the same reason.
345
+ async function harness({
346
+ assigned = nineIssues(),
347
+ draw = true,
348
+ gate = true,
349
+ singleRemote = false,
350
+ identityOptions = {},
351
+ } = {}) {
352
+ const checkout = makeCheckout({ singleRemote });
353
+ const { registered, repaints } = installBridge();
354
+ const sent = [];
355
+ const loaded = await loadExtension({
356
+ sendUserMessage: (text, opts) => { sent.push({ text, opts }); },
357
+ });
358
+ ghIssues = loaded.mod.libModule('gh-issues.js');
359
+ const gh = fakeGithub({ assigned, gate });
360
+ ghIssues.setGhRunner(gh.runner);
361
+ const identity = identityGit(identityOptions);
362
+ ghIssues.setGitRunner(identity.run);
363
+ loaded.mod.setIssuesTuiLoader(async () => stubTui);
364
+ const notices = [];
365
+ const sessionCwd = draw ? checkout : makeCheckout();
366
+ const ctx = { cwd: sessionCwd, ui: { notify: (text, level) => { notices.push({ text, level }); } } };
367
+ await fireSessionStart(loaded.hooks, ctx);
368
+ const section = registered[0];
369
+ const rows = draw && section ? await waitForRows(section, ctx) : [];
370
+ return { checkout, loaded, gh, identity, registered, section, rows, sent, notices, repaints, ctx };
371
+ }
372
+
373
+ // The host running the command a click dispatched. `custom` records the mount
374
+ // instead of drawing; `false` models a host with no overlay support at all.
375
+ function commandCtx(cwd, { custom = true, notices = [] } = {}) {
376
+ const customs = [];
377
+ const ctx = { cwd, ui: { notify: (text, level) => { notices.push({ text, level }); } } };
378
+ if (custom) {
379
+ ctx.ui.custom = async (factory, options) => {
380
+ customs.push({ factory, options });
381
+ return null;
382
+ };
383
+ }
384
+ return { ctx, customs, notices };
385
+ }
386
+
387
+ function numberOf(label) {
388
+ const match = /^#(\d+)/.exec(String(label));
389
+ assert.ok(match, `a row label starts with its issue number (saw ${label})`);
390
+ return Number(match[1]);
391
+ }
392
+
393
+ // Capture the options the command mounts the real view with: the module instance
394
+ // THIS extension load uses is patched, never a separate `require`.
395
+ function captureIssuesView(mod) {
396
+ const holder = { options: null };
397
+ const lib = mod.libModule('issues-view.js');
398
+ const original = lib.createIssuesView;
399
+ lib.createIssuesView = (options) => {
400
+ holder.options = options;
401
+ return { render: () => [], handleInput: () => {}, invalidate: () => {} };
402
+ };
403
+ restores.push(() => { lib.createIssuesView = original; });
404
+ return holder;
405
+ }
406
+
407
+ // A host's own terminal object, enough for the factory the command mounts.
408
+ function hostTui() {
409
+ return { stop: () => {}, start: () => {}, requestRender: () => {} };
410
+ }
411
+
412
+ // ---------------------------------------------------------------------------
413
+ // S1: one open at a time, and the effect is invisible to the click.
414
+ // ---------------------------------------------------------------------------
415
+
416
+ test('S1: two rapid clicks on one row send exactly one /issues message and announce nothing', async () => {
417
+ const h = await harness();
418
+ const row = h.rows[0];
419
+ const number = numberOf(row.label);
420
+ const paintedBefore = h.repaints.length;
421
+ const labelsBefore = h.rows.map((row) => row.label);
422
+
423
+ assert.doesNotThrow(() => row.onClick(), 'the click itself is never refused');
424
+ assert.doesNotThrow(() => row.onClick(), 'and a second one is not refused either');
425
+ await waitFor(() => h.sent.length > 0, 'the click never dispatched its command');
426
+ await settle();
427
+
428
+ assert.deepEqual(h.sent, [{ text: `/issues ${number}`, opts: { expandPromptTemplates: true } }],
429
+ 'one open at a time: the second click sent nothing');
430
+ assert.equal(h.loaded.entries.length, 0, 'nothing was appended for the swallowed click');
431
+ assert.deepEqual(h.notices, [], 'and nothing was notified');
432
+ assert.equal(h.repaints.length, paintedBefore, 'and the rail repainted nothing for it');
433
+ assert.deepEqual(h.section.lines(h.ctx).map((label) => label.label), labelsBefore,
434
+ 'and the rail paints exactly what it painted before the click');
435
+ });
436
+
437
+ test('S1: a click on another numbered row while one is opening is a no-op', async () => {
438
+ const h = await harness();
439
+ const first = numberOf(h.rows[0].label);
440
+ h.rows[0].onClick();
441
+ h.rows[2].onClick();
442
+ await waitFor(() => h.sent.length > 0, 'the first click never dispatched');
443
+ await settle();
444
+ assert.deepEqual(h.sent, [{ text: `/issues ${first}`, opts: { expandPromptTemplates: true } }],
445
+ 'a different row is swallowed exactly like the same one');
446
+ assert.equal(h.loaded.entries.length, 0);
447
+ assert.deepEqual(h.notices, []);
448
+ });
449
+
450
+ test('S1: the overflow row is guarded like a numbered row, in both orders', async () => {
451
+ const nine = await harness();
452
+ assert.equal(nine.rows.length, 8, 'seven issue rows plus the overflow row');
453
+ assert.equal(nine.rows[7].label, 'and 2 more issues');
454
+ nine.rows[7].onClick();
455
+ nine.rows[0].onClick();
456
+ await waitFor(() => nine.sent.length > 0, 'the overflow click never dispatched');
457
+ await settle();
458
+ assert.deepEqual(nine.sent, [{ text: '/issues', opts: { expandPromptTemplates: true } }],
459
+ 'the overflow row opened the panel and the numbered click behind it did nothing');
460
+
461
+ const numbered = await harness();
462
+ const number = numberOf(numbered.rows[0].label);
463
+ numbered.rows[0].onClick();
464
+ numbered.rows[7].onClick();
465
+ await waitFor(() => numbered.sent.length > 0, 'the numbered click never dispatched');
466
+ await settle();
467
+ assert.deepEqual(numbered.sent, [{ text: `/issues ${number}`, opts: { expandPromptTemplates: true } }],
468
+ 'and the overflow row is swallowed while a numbered open is in flight');
469
+ });
470
+
471
+ test('S1: the rail works again once the first panel mounted', async () => {
472
+ const h = await harness();
473
+ const first = numberOf(h.rows[0].label);
474
+ h.rows[0].onClick();
475
+ await waitFor(() => h.sent.length === 1, 'the first click never dispatched');
476
+
477
+ const { ctx, customs } = commandCtx(h.checkout);
478
+ await h.loaded.commands.get('issues').handler(String(first), ctx);
479
+ assert.equal(customs.length, 1, 'the panel mounted');
480
+
481
+ const second = numberOf(h.rows[1].label);
482
+ h.rows[1].onClick();
483
+ await waitFor(() => h.sent.length === 2, 'the click after a mounted panel was swallowed');
484
+ assert.deepEqual(h.sent[1], { text: `/issues ${second}`, opts: { expandPromptTemplates: true } });
485
+ });
486
+
487
+ test('S1: a gh gate that refuses releases the guard', async () => {
488
+ const h = await harness({ gate: false });
489
+ const number = numberOf(h.rows[0].label);
490
+ h.rows[0].onClick();
491
+ await waitFor(() => h.sent.length === 1, 'the click never dispatched');
492
+
493
+ const { ctx, customs } = commandCtx(h.checkout);
494
+ await h.loaded.commands.get('issues').handler(String(number), ctx);
495
+ assert.equal(customs.length, 0, 'the gate refusal opened nothing');
496
+
497
+ h.rows[0].onClick();
498
+ await waitFor(() => h.sent.length === 2, 'the refused command left the rail dead');
499
+ });
500
+
501
+ test('S1: a host with no overlay support releases the guard', async () => {
502
+ const h = await harness();
503
+ const number = numberOf(h.rows[0].label);
504
+ h.rows[0].onClick();
505
+ await waitFor(() => h.sent.length === 1, 'the click never dispatched');
506
+
507
+ const { ctx, customs } = commandCtx(h.checkout, { custom: false });
508
+ await h.loaded.commands.get('issues').handler(String(number), ctx);
509
+ assert.equal(customs.length, 0, 'no overlay exists to mount');
510
+
511
+ h.rows[0].onClick();
512
+ await waitFor(() => h.sent.length === 2, 'the ended open left the rail dead');
513
+ });
514
+
515
+ test('S1: a cwd outside a checkout releases the guard', async () => {
516
+ const h = await harness();
517
+ h.rows[0].onClick();
518
+ await waitFor(() => h.sent.length === 1, 'the click never dispatched');
519
+
520
+ const outside = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-issues-guard-plain-')));
521
+ const { ctx, customs, notices } = commandCtx(outside);
522
+ await h.loaded.commands.get('issues').handler('12', ctx);
523
+ assert.equal(customs.length, 0, 'nothing opens outside a checkout');
524
+ assert.equal(notices.length, 1, 'and the shared line is still said');
525
+
526
+ h.rows[0].onClick();
527
+ await waitFor(() => h.sent.length === 2, 'the early return left the rail dead');
528
+ });
529
+
530
+ test('S1: a failed identity proof still mounts and releases the guard', async () => {
531
+ const h = await harness();
532
+ h.rows[0].onClick();
533
+ await waitFor(() => h.sent.length === 1, 'the click never dispatched');
534
+
535
+ // The identity cannot be proven at all: the cached read and its one fresh
536
+ // fallback both fail, and the panel still opens (S5 reports the failure). The
537
+ // open names ANOTHER number than the click, because a click's own number now
538
+ // rides its row identity and pins it without a proof at all (S2 below) — the
539
+ // click still owns the guard that this failed open has to release.
540
+ ghIssues.setGitRunner(() => ({ status: 1, stdout: '', stderr: 'bad config', error: null }));
541
+ const holder = captureIssuesView(h.loaded.mod);
542
+ const { ctx, customs } = commandCtx(h.checkout);
543
+ ctx.ui.custom = async (factory) => { customs.push(1); factory(hostTui(), {}, {}, () => {}); return null; };
544
+ await h.loaded.commands.get('issues').handler('12', ctx);
545
+ assert.equal(customs.length, 1, 'the overlay mounted despite the failed proof');
546
+ assert.equal((await holder.options.loadIssuePage({ bucketId: 'assigned', limit: 5 })).ok, false,
547
+ 'and its reads report the unproven identity');
548
+
549
+ h.rows[0].onClick();
550
+ await waitFor(() => h.sent.length === 2, 'the failed proof left the rail dead');
551
+ });
552
+
553
+ test('S1: a throw before the overlay releases the guard', async () => {
554
+ const h = await harness();
555
+ h.rows[0].onClick();
556
+ await waitFor(() => h.sent.length === 1, 'the click never dispatched');
557
+
558
+ const { ctx } = commandCtx(h.checkout);
559
+ const hostile = { toString() { throw new Error('boom'); } };
560
+ await assert.rejects(h.loaded.commands.get('issues').handler(hostile, ctx), /boom/,
561
+ 'the command still fails as loudly as before');
562
+
563
+ h.rows[0].onClick();
564
+ await waitFor(() => h.sent.length === 2, 'the throw left the rail dead');
565
+ });
566
+
567
+ test('S1: the bounded safety interval releases the guard when the host never runs the command', async () => {
568
+ const h = await harness();
569
+ const row = h.rows[0];
570
+ const number = numberOf(row.label);
571
+ const timers = [];
572
+ const unrefd = [];
573
+ const saved = globalThis.setTimeout;
574
+ try {
575
+ globalThis.setTimeout = (fn, ms) => {
576
+ const timer = { fn, ms, ran: false, unref: () => { unrefd.push(timer); }, ref: () => {} };
577
+ timers.push(timer);
578
+ return timer;
579
+ };
580
+ row.onClick();
581
+ await drainDeferred(timers);
582
+ assert.deepEqual(h.sent, [{ text: `/issues ${number}`, opts: { expandPromptTemplates: true } }],
583
+ 'the first click still dispatches');
584
+
585
+ const armed = timers.filter((timer) => timer.ms > 0);
586
+ assert.equal(armed.length, 1, 'exactly one bounded safety timer was armed');
587
+ assert.ok(armed[0].ms >= 5000 && armed[0].ms <= 15000,
588
+ `the safety interval is about ten seconds (saw ${armed[0].ms}ms)`);
589
+ assert.deepEqual(unrefd, [armed[0]], 'and it is unref\'d, so it never holds the process open');
590
+
591
+ row.onClick();
592
+ await drainDeferred(timers);
593
+ assert.equal(h.sent.length, 1, 'while it is armed, a further click is still a no-op');
594
+
595
+ armed[0].fn();
596
+ row.onClick();
597
+ await drainDeferred(timers);
598
+ assert.deepEqual(h.sent[1], { text: `/issues ${number}`, opts: { expandPromptTemplates: true } },
599
+ 'the interval releases the guard even though no command ever ran');
600
+ } finally {
601
+ globalThis.setTimeout = saved;
602
+ }
603
+ });
604
+
605
+ // Run every zero-delay callback the fake scheduler holds — the rail defers a
606
+ // click onto one — and let the promises they settle flush.
607
+ async function drainDeferred(timers) {
608
+ for (let pass = 0; pass < 20; pass += 1) {
609
+ const due = timers.filter((timer) => timer.ms === 0 && timer.ran !== true);
610
+ if (due.length === 0) return;
611
+ for (const timer of due) {
612
+ timer.ran = true;
613
+ timer.fn();
614
+ }
615
+ await new Promise((resolve) => realSetTimeout(resolve, 0));
616
+ }
617
+ }
618
+
619
+ test('S1: a click from the previous session never blocks the next one', async () => {
620
+ const h = await harness();
621
+ h.rows[0].onClick();
622
+ await waitFor(() => h.sent.length === 1, 'the click never dispatched');
623
+ // The host never ran the click's command; the session ends and a new one starts.
624
+ await fireSessionStart(h.loaded.hooks, h.ctx);
625
+ const rows = await waitForRows(h.section, h.ctx);
626
+
627
+ const number = numberOf(rows[1].label);
628
+ rows[1].onClick();
629
+ await waitFor(() => h.sent.length === 2, "the next session's click was swallowed by the previous one");
630
+ assert.deepEqual(h.sent[1], { text: `/issues ${number}`, opts: { expandPromptTemplates: true } });
631
+ });
632
+
633
+ test('S1: a shutdown releases the guard', async () => {
634
+ const h = await harness();
635
+ h.rows[0].onClick();
636
+ await waitFor(() => h.sent.length === 1, 'the click never dispatched');
637
+ await fireHook(h.loaded.hooks, 'session_shutdown', h.ctx);
638
+
639
+ // T18 (S11): `session_shutdown` DISPOSES the section with the session, so the
640
+ // rows it retained are inert — a click from a dead session never reaches a live
641
+ // panel, and it never even asks the single-flight guard.
642
+ h.rows[1].onClick();
643
+ await settle(50);
644
+ assert.equal(h.sent.length, 1, 'a row retained across shutdown dispatched');
645
+
646
+ // The guard is still released: the next session binds its OWN section, and a
647
+ // click on one of its fresh rows dispatches exactly once.
648
+ await fireSessionStart(h.loaded.hooks, h.ctx);
649
+ const rows = await waitForRows(h.registered[h.registered.length - 1], h.ctx);
650
+ const number = numberOf(rows[1].label);
651
+ rows[1].onClick();
652
+ await waitFor(() => h.sent.length === 2, 'a shutdown left the next click dead');
653
+ assert.deepEqual(h.sent[1], { text: `/issues ${number}`, opts: { expandPromptTemplates: true } });
654
+ });
655
+
656
+ test('S1: a typed /issues is never swallowed by a click in flight', async () => {
657
+ const h = await harness();
658
+ h.rows[0].onClick();
659
+ await waitFor(() => h.sent.length === 1, 'the click never dispatched');
660
+
661
+ const { ctx, customs } = commandCtx(h.checkout);
662
+ await h.loaded.commands.get('issues').handler('', ctx);
663
+ assert.equal(customs.length, 1, 'the typed command opens its panel exactly as before');
664
+ });
665
+
666
+ // ---------------------------------------------------------------------------
667
+ // S2: the numbered open pins the cached scope, and starts both loads together.
668
+ // ---------------------------------------------------------------------------
669
+
670
+ // The pages the mount was handed, by bucket id.
671
+ function pageOf(options, id) {
672
+ const page = options.pages.find((entry) => entry.id === id);
673
+ assert.ok(page, `the mount is handed the ${id} page`);
674
+ return page;
675
+ }
676
+
677
+ test('S2: a numbered open pins the identity from the checkout\'s cached scope', async () => {
678
+ const h = await harness();
679
+ assert.ok(h.rows.slice(0, 7).some((row) => numberOf(row.label) === 104), 'the rail read the fixture rows');
680
+ // The checkout's remote "moves" after the rail proved its repository: a FRESH
681
+ // proof would name another repository, the CACHED one keeps the first.
682
+ h.identity.remoteUrl.value = 'git@github.com:myfork/renamed.git';
683
+ const identityCallsBefore = h.identity.calls.length;
684
+
685
+ const holder = captureIssuesView(h.loaded.mod);
686
+ const { ctx, customs } = commandCtx(h.checkout);
687
+ ctx.ui.custom = async (factory) => { customs.push(1); factory(hostTui(), {}, {}, () => {}); return null; };
688
+ await h.loaded.commands.get('issues').handler('104', ctx);
689
+ assert.equal(customs.length, 1, 'the panel mounted');
690
+
691
+ const options = holder.options;
692
+ assert.equal(options.initialIssue, 104);
693
+ assert.equal(options.initialBucket, 'assigned', 'the cache says which tab holds the number');
694
+ assert.deepEqual(pageOf(options, 'assigned').issues.map((row) => row.number).sort((a, b) => a - b),
695
+ [100, 101, 102, 103, 104, 105, 106, 107, 108],
696
+ 'the first frame is seeded from the rail cache for the identity the checkout already proved');
697
+ assert.equal(pageOf(options, 'assigned').total, 9, 'and reports the count that cache holds');
698
+ assert.deepEqual(pageOf(options, 'mine').issues, [],
699
+ 'a bucket the cache holds empty is seeded empty, exactly like the cache says');
700
+ assert.ok(h.identity.calls.length - identityCallsBefore <= 1,
701
+ 'the pin cost at most the cache validation, never a fresh proof');
702
+ assert.ok(!h.identity.calls.slice(identityCallsBefore).some((argv) => argv[0] === 'remote'),
703
+ 'the numbered open never re-read the checkout\'s remotes');
704
+ });
705
+
706
+ test('S2 (preserve): a plain /issues keeps its fresh identity proof', async () => {
707
+ const h = await harness();
708
+ h.identity.remoteUrl.value = 'git@github.com:myfork/renamed.git';
709
+ const identityCallsBefore = h.identity.calls.length;
710
+
711
+ const holder = captureIssuesView(h.loaded.mod);
712
+ const { ctx, customs } = commandCtx(h.checkout);
713
+ ctx.ui.custom = async (factory) => { customs.push(1); factory(hostTui(), {}, {}, () => {}); return null; };
714
+ await h.loaded.commands.get('issues').handler('', ctx);
715
+ assert.equal(customs.length, 1, 'the panel mounted');
716
+
717
+ const options = holder.options;
718
+ assert.equal('initialIssue' in options, false, 'a plain open is handed no initial issue');
719
+ assert.ok(h.identity.calls.slice(identityCallsBefore).some((argv) => argv[0] === 'remote'),
720
+ 'the plain open proved the checkout again');
721
+ for (const page of options.pages) {
722
+ assert.equal(page.issues, null,
723
+ `the fresh proof named the moved repository, which the cache does not hold (saw ${page.id})`);
724
+ }
725
+ });
726
+
727
+ test('S2: the identity pin and the TUI helper load start together', async () => {
728
+ const h = await harness({ draw: false });
729
+ let loaderStarted = false;
730
+ h.loaded.mod.setIssuesTuiLoader(async () => { loaderStarted = true; return stubTui; });
731
+
732
+ let releaseConfig = null;
733
+ const held = new Promise((resolve) => { releaseConfig = resolve; });
734
+ let configHeld = false;
735
+ const base = h.identity.run;
736
+ ghIssues.setGitRunner((argv, opts) => {
737
+ if (argv[0] === 'config' && configHeld !== true) {
738
+ configHeld = true;
739
+ return held.then(() => base(argv, opts));
740
+ }
741
+ return base(argv, opts);
742
+ });
743
+
744
+ const { ctx, customs } = commandCtx(h.checkout);
745
+ const pending = h.loaded.commands.get('issues').handler('12', ctx);
746
+ await waitFor(() => configHeld, 'the numbered open never started its identity pin');
747
+ assert.equal(loaderStarted, true, 'the TUI helper load starts WITH the pin, not after it settles');
748
+ releaseConfig();
749
+ await pending;
750
+ assert.equal(customs.length, 1, 'and the panel still mounts once the pin answers');
751
+ });
752
+
753
+ test('S2: a cached pin that cannot be read falls back to the fresh proof once', async () => {
754
+ const h = await harness({ draw: false });
755
+ // The FIRST identity read is the numbered open's cached one: it fails, and the
756
+ // fresh proof behind it answers.
757
+ const failing = identityGit({ failConfigReads: 1 });
758
+ ghIssues.setGitRunner(failing.run);
759
+
760
+ const holder = captureIssuesView(h.loaded.mod);
761
+ const { ctx, customs } = commandCtx(h.checkout);
762
+ ctx.ui.custom = async (factory) => { customs.push(1); factory(hostTui(), {}, {}, () => {}); return null; };
763
+ await h.loaded.commands.get('issues').handler('104', ctx);
764
+ assert.equal(customs.length, 1, 'the panel mounted');
765
+ assert.equal(holder.options.initialIssue, 104);
766
+
767
+ const configReads = failing.calls.filter((argv) => argv[0] === 'config').length;
768
+ const remoteReads = failing.calls.filter((argv) => argv[0] === 'remote' && argv[1] === 'get-url').length;
769
+ assert.equal(configReads, 2, 'the cached read failed once and the fresh fallback read once');
770
+ assert.equal(remoteReads, 1, 'the fallback proved the identity, once');
771
+ });
772
+
773
+ test('S2: both proofs failing keeps today\'s failure, and the panel still opens', async () => {
774
+ const h = await harness({ draw: false });
775
+ ghIssues.setGitRunner(() => ({ status: 1, stdout: '', stderr: 'bad config', error: null }));
776
+
777
+ const holder = captureIssuesView(h.loaded.mod);
778
+ const { ctx, customs } = commandCtx(h.checkout);
779
+ ctx.ui.custom = async (factory) => { customs.push(1); factory(hostTui(), {}, {}, () => {}); return null; };
780
+ await h.loaded.commands.get('issues').handler('12', ctx);
781
+ assert.equal(customs.length, 1, 'the panel still opens with an unproven identity');
782
+ const page = await holder.options.loadIssuePage({ bucketId: 'assigned', limit: 5 });
783
+ assert.equal(page.ok, false);
784
+ assert.match(page.error, /git configuration|cannot resolve this checkout's own repository|own repository/,
785
+ 'the read reports the unproven identity, exactly as before');
786
+ });
787
+
788
+ // ---------------------------------------------------------------------------
789
+ // S2, second half: the row's identity rides the click, so the numbered open
790
+ // pins THAT repository with no probe at all.
791
+ // ---------------------------------------------------------------------------
792
+
793
+ // The identity work a call did: the identity's own `git` seam (the cached-scope
794
+ // read and the fresh proof both go through it) plus gh's own repository
795
+ // resolution, which is the whole proof of a SINGLE-remote checkout. Everything
796
+ // else a mount runs is a read of issues, never the identity.
797
+ function identityChildren(h, before) {
798
+ return {
799
+ git: h.identity.calls.slice(before.git),
800
+ gh: h.gh.calls.slice(before.gh)
801
+ .filter((call) => call.bin === 'gh' && call.argv[0] === 'repo' && call.argv[1] === 'view'),
802
+ };
803
+ }
804
+
805
+ function rowFor(h, number) {
806
+ const row = h.rows.find((candidate) => numberOf(candidate.label) === number);
807
+ assert.ok(row, `the rail painted a row for #${number}`);
808
+ return row;
809
+ }
810
+
811
+ // The `git` children ONE open spawns through the extension's REAL runner: the
812
+ // command always resolves its checkout root (`oddCheckoutRootAsync` → two
813
+ // `rev-parse` probes) before anything else, and the identity read's injected seam
814
+ // (`h.identity`) never sees those. Counting them is what keeps "no identity probe"
815
+ // from quietly meaning "no probe we happened to instrument".
816
+ function countGitChildren(mod) {
817
+ const lib = mod.libModule('worktree-git.js');
818
+ const original = lib.runArgvAsync;
819
+ const calls = [];
820
+ lib.runArgvAsync = (bin, argv, opts) => {
821
+ calls.push({ bin, argv: Array.isArray(argv) ? argv.slice() : [], cwd: opts ? opts.cwd : undefined });
822
+ return original(bin, argv, opts);
823
+ };
824
+ restores.push(() => { lib.runArgvAsync = original; });
825
+ return calls;
826
+ }
827
+
828
+ // The repository every gh call after `marker` was bound to, newest last.
829
+ function ghScopesSince(h, marker) {
830
+ return h.gh.calls.slice(marker)
831
+ .filter((call) => call.argv[0] === 'api')
832
+ .map((call) => call.repo);
833
+ }
834
+
835
+ // Click a rail row and then run the command the host would run for it, with the
836
+ // view captured instead of drawn. `cwd` is the checkout the command runs in: the
837
+ // rail's own by default, or a SECOND checkout whose identity scope cache is cold
838
+ // — the only way to see a cached-scope pin cost anything at all.
839
+ async function clickOpen(h, { row, number, cwd } = {}) {
840
+ const target = row === undefined ? h.rows[0] : row;
841
+ const asked = number === undefined ? numberOf(target.label) : number;
842
+ const sentBefore = h.sent.length;
843
+ target.onClick();
844
+ await waitFor(() => h.sent.length > sentBefore, 'the click never dispatched its command');
845
+ assert.deepEqual(h.sent[h.sent.length - 1],
846
+ { text: `/issues ${asked}`, opts: { expandPromptTemplates: true } },
847
+ 'the click dispatched that row\'s number');
848
+ return await runOpen(h, { cwd: cwd === undefined ? h.checkout : cwd, args: String(asked) });
849
+ }
850
+
851
+ async function runOpen(h, { cwd, args }) {
852
+ const holder = captureIssuesView(h.loaded.mod);
853
+ const { ctx, customs, notices } = commandCtx(cwd);
854
+ ctx.ui.custom = async (factory) => { customs.push(1); factory(hostTui(), {}, {}, () => {}); return null; };
855
+ await h.loaded.commands.get('issues').handler(args, ctx);
856
+ assert.equal(customs.length, 1, 'the panel mounted');
857
+ return { holder, options: holder.options, notices, ctx };
858
+ }
859
+
860
+ test('S2: a click carrying an identity pins it with no identity probe and seeds from the rail cache', async () => {
861
+ // A SINGLE-remote checkout: there is no fork remote to read, so gh's own
862
+ // `repo view` IS the identity proof — the ~0.6 s call a cached-scope pin still
863
+ // paid before a click carried the identity of the row it came from.
864
+ const h = await harness({ singleRemote: true });
865
+ const row = rowFor(h, 104);
866
+ // The checkout's remote "moves" after the rail proved its repository. Nothing on
867
+ // this open path reads it again — and nothing needs to: the row's number belongs
868
+ // to the repository it was READ from, and every action still re-proves the
869
+ // checkout fresh (the drift test below refuses on exactly this).
870
+ h.identity.remoteUrl.value = 'git@github.com:myfork/renamed.git';
871
+ const before = { git: h.identity.calls.length, gh: h.gh.calls.length };
872
+ // The whole open's git children, including the checkout-root resolution the
873
+ // command always performs outside the identity read's injected seam.
874
+ const spawned = countGitChildren(h.loaded.mod);
875
+
876
+ const { options } = await clickOpen(h, { row });
877
+
878
+ assert.equal(options.initialIssue, 104, 'the panel opened on the clicked number');
879
+ assert.equal(options.initialBucket, 'assigned', 'the cache says which tab holds the number');
880
+ assert.deepEqual(pageOf(options, 'assigned').issues.map((entry) => entry.number).sort((a, b) => a - b),
881
+ [100, 101, 102, 103, 104, 105, 106, 107, 108],
882
+ 'the first frame is seeded from the rail cache for the identity the ROW was read from');
883
+ assert.equal(pageOf(options, 'assigned').total, 9, 'and reports the count that cache holds');
884
+ const children = identityChildren(h, before);
885
+ assert.deepEqual(children.git, [], 'the identity read ran no git child: no config read, no remote read');
886
+ assert.deepEqual(children.gh, [], 'and no gh repository probe either');
887
+ assert.deepEqual(spawned.map((call) => `${call.bin} ${call.argv.join(' ')}`),
888
+ ['git rev-parse --show-toplevel', 'git rev-parse --git-common-dir'],
889
+ 'the only git children of the whole open are the checkout-root resolution the command always runs');
890
+ });
891
+
892
+ test('S2: the row identity hint is one-shot — the open that takes it consumes it', async () => {
893
+ // The hint is cleared TWICE: by the open that takes it, and by the click's guard
894
+ // release at the mount. This isolates the take from the release: the first open is
895
+ // held on its TUI helper load, which happens after it took the hint and before it
896
+ // can release anything, so a second open started in that window finds the hint
897
+ // only if taking it did not consume it.
898
+ const h = await harness();
899
+ // A SECOND checkout of the same repository: its scope cache is cold, so an open
900
+ // that does NOT ride the hint has to read git to pin the identity.
901
+ const cold = makeCheckout();
902
+ let releaseFirst = null;
903
+ const held = new Promise((resolve) => { releaseFirst = resolve; });
904
+ let loads = 0;
905
+ let firstLoading = false;
906
+ h.loaded.mod.setIssuesTuiLoader(async () => {
907
+ loads += 1;
908
+ if (loads === 1) {
909
+ firstLoading = true;
910
+ await held;
911
+ }
912
+ return stubTui;
913
+ });
914
+
915
+ const sentBefore = h.sent.length;
916
+ rowFor(h, 104).onClick();
917
+ await waitFor(() => h.sent.length > sentBefore, 'the click never dispatched its command');
918
+ // The command the click dispatched: it takes the hint, then waits on the helper
919
+ // load before it can mount (and release).
920
+ const firstCtx = commandCtx(cold);
921
+ const first = h.loaded.commands.get('issues').handler('104', firstCtx.ctx);
922
+ try {
923
+ await waitFor(() => firstLoading, 'the first open never reached its TUI helper load');
924
+
925
+ const before = { git: h.identity.calls.length, gh: h.gh.calls.length };
926
+ const second = await runOpen(h, { cwd: cold, args: '104' });
927
+ assert.equal(second.options.initialIssue, 104, 'the second open is the same number');
928
+ assert.ok(identityChildren(h, before).git.length > 0,
929
+ 'the second open proved the identity again: taking the hint consumed it');
930
+ } finally {
931
+ releaseFirst();
932
+ await first;
933
+ }
934
+ assert.equal(firstCtx.customs.length, 1, 'the first open still mounted once its helper load answered');
935
+ });
936
+
937
+ test('S2: a hint for another number is ignored and that open takes the cached-scope pin', async () => {
938
+ const h = await harness();
939
+ const cold = makeCheckout();
940
+ const sentBefore = h.sent.length;
941
+ rowFor(h, 104).onClick();
942
+ await waitFor(() => h.sent.length > sentBefore, 'the click never dispatched its command');
943
+
944
+ const before = { git: h.identity.calls.length, gh: h.gh.calls.length };
945
+ const { options } = await runOpen(h, { cwd: cold, args: '105' });
946
+ assert.equal(options.initialIssue, 105, 'the open is the number that was asked for');
947
+ assert.ok(identityChildren(h, before).git.length > 0,
948
+ 'a hint for another number never pins anything: the open proved its own identity');
949
+ assert.deepEqual(pageOf(options, 'assigned').issues.map((entry) => entry.number).sort((a, b) => a - b),
950
+ [100, 101, 102, 103, 104, 105, 106, 107, 108],
951
+ 'and still seeds from the cache for the identity it proved');
952
+ });
953
+
954
+ test('S2: a click on a row retained from the previous session records no hint', async () => {
955
+ const other = otherCheckout();
956
+ const h = await harness({ identityOptions: { urlForCwd: checkoutRemotes(other) } });
957
+ const row = rowFor(h, 104);
958
+ // The session boundary moves the generation on and drops the section's snapshot,
959
+ // but the host still paints the row it kept. Its click dispatches `/<issues> N`
960
+ // exactly as before — the identity behind it, though, names the repository the
961
+ // session that READ it lived in.
962
+ await fireSessionStart(h.loaded.hooks, h.ctx);
963
+ const sentBefore = h.sent.length;
964
+ row.onClick();
965
+ await waitFor(() => h.sent.length > sentBefore, 'the retained row never dispatched its command');
966
+ assert.deepEqual(h.sent[h.sent.length - 1], { text: '/issues 104', opts: { expandPromptTemplates: true } },
967
+ 'a stale row still dispatches its own number, exactly as before');
968
+
969
+ // The open that follows takes the CACHED-scope pin of the checkout it runs in,
970
+ // which names ANOTHER repository than the row did: the pinned scope the detail
971
+ // read receives is that one.
972
+ const before = { git: h.identity.calls.length, gh: h.gh.calls.length };
973
+ const { options } = await runOpen(h, { cwd: other, args: '104' });
974
+ assert.equal(options.initialIssue, 104);
975
+ assert.ok(identityChildren(h, before).git.length > 0,
976
+ 'the open proved the identity: the stale row left no hint to pin');
977
+ const marker = h.gh.calls.length;
978
+ await options.loadIssuePage({ bucketId: 'assigned', limit: 5 });
979
+ const scopes = ghScopesSince(h, marker);
980
+ assert.ok(scopes.length > 0, 'the detail read reached gh');
981
+ assert.equal(scopes[scopes.length - 1], 'github.com/other/project',
982
+ 'the read is bound to the cached-scope identity, never the retained row\'s repository');
983
+ });
984
+
985
+ test('S2: an action in a panel opened from a click still refuses when the checkout drifted', async () => {
986
+ const other = otherCheckout();
987
+ const h = await harness({ identityOptions: { urlForCwd: checkoutRemotes(other) } });
988
+ // The click pins the repository its ROW was read from; the command it dispatched
989
+ // runs in ANOTHER checkout, which names another repository — the drift every
990
+ // action must refuse. An open that ignored the hint would pin that other
991
+ // repository instead, see no drift at all and send the write.
992
+ const { options } = await clickOpen(h, { row: rowFor(h, 104), cwd: other });
993
+ const before = { git: h.identity.calls.length, gh: h.gh.calls.length };
994
+
995
+ const refused = await options.actions.setState(104, 'closed');
996
+ assert.equal(refused.ok, false, 'the write is refused on the drift');
997
+ assert.match(refused.error, /changed since this issue list loaded/,
998
+ 'the refusal is the scope-drift line, naming the repository it found');
999
+ assert.ok(identityChildren(h, before).git.length > 0, 'the action re-proved the checkout fresh');
1000
+ const mutations = h.gh.calls.slice(before.gh)
1001
+ .filter((call) => call.argv[0] === 'issue' && ['edit', 'comment', 'close', 'reopen'].includes(call.argv[1]));
1002
+ assert.deepEqual(mutations, [], 'no mutating gh command ran after the drift');
1003
+ });
1004
+
1005
+ // ---------------------------------------------------------------------------
1006
+ // S2, correction: a hint is only as good as the identity and the generation
1007
+ // behind it.
1008
+ // ---------------------------------------------------------------------------
1009
+
1010
+ // The dispatch a click performs, with the identity under test: the extension's own
1011
+ // seam, so a test can hand it a value no rail row would produce today. The
1012
+ // generation is the CURRENT one (a click whose row was read by this session), which
1013
+ // is what makes "did this click leave a hint?" a real question.
1014
+ function click(h, number, identity) {
1015
+ const sentBefore = h.sent.length;
1016
+ const outcome = h.loaded.mod.dispatchIssuesPanel(
1017
+ h.loaded.api, number, identity, 'assigned', h.loaded.mod.issuesSidebarGeneration(),
1018
+ );
1019
+ assert.deepEqual(outcome, { ok: true }, 'the click answers at once');
1020
+ assert.equal(h.sent.length, sentBefore + 1, 'and dispatches its command');
1021
+ assert.deepEqual(h.sent[h.sent.length - 1], { text: `/issues ${number}`, opts: { expandPromptTemplates: true } },
1022
+ 'the number alone reaches the panel');
1023
+ }
1024
+
1025
+ test('S2 (correction): a click with a malformed or blank identity records no hint', async () => {
1026
+ const other = otherCheckout();
1027
+ const h = await harness({ identityOptions: { urlForCwd: checkoutRemotes(other) } });
1028
+ for (const identity of [' ', 'myfork', 'a/b/c/d']) {
1029
+ click(h, 104, identity);
1030
+ // The open this click dispatched reads as every numbered open does: it pins the
1031
+ // checkout's cached scope, so its reads are bound to that repository. A raw
1032
+ // identity pinned instead makes every read fail before any gh child runs.
1033
+ const { options } = await runOpen(h, { cwd: other, args: '104' });
1034
+ const marker = h.gh.calls.length;
1035
+ const page = await options.loadIssuePage({ bucketId: 'assigned', limit: 5 });
1036
+ const scopes = ghScopesSince(h, marker);
1037
+ assert.ok(scopes.length > 0,
1038
+ `${JSON.stringify(identity)}: the read reached gh instead of failing on a pinned nonsense identity`);
1039
+ assert.equal(scopes[scopes.length - 1], 'github.com/other/project',
1040
+ `${JSON.stringify(identity)}: the read is bound to the cached-scope identity`);
1041
+ assert.doesNotMatch(String(page.error || ''), /pinned repository/,
1042
+ `${JSON.stringify(identity)}: no read carries a malformed pin`);
1043
+ }
1044
+ });
1045
+
1046
+ test('S2 (correction): a click identity is recorded normalized, so a bare owner/name keys the rail cache', async () => {
1047
+ const savedHost = process.env.GH_HOST;
1048
+ const savedRepo = process.env.GH_REPO;
1049
+ delete process.env.GH_HOST;
1050
+ delete process.env.GH_REPO;
1051
+ try {
1052
+ const h = await harness();
1053
+ // `myfork/project` is a legal identity gh accepts; the hint is recorded as the
1054
+ // same host-qualified `<host>/<owner>/<repo>` the rail cache is keyed by, so the
1055
+ // open it dispatches seeds its first frame from that entry.
1056
+ click(h, 104, 'myfork/project');
1057
+ const { options } = await runOpen(h, { cwd: h.checkout, args: '104' });
1058
+ assert.equal(options.initialIssue, 104);
1059
+ assert.deepEqual(pageOf(options, 'assigned').issues.map((entry) => entry.number).sort((a, b) => a - b),
1060
+ [100, 101, 102, 103, 104, 105, 106, 107, 108],
1061
+ 'the pin is github.com/myfork/project, the key the rail cache holds');
1062
+ } finally {
1063
+ if (savedHost === undefined) delete process.env.GH_HOST;
1064
+ else process.env.GH_HOST = savedHost;
1065
+ if (savedRepo === undefined) delete process.env.GH_REPO;
1066
+ else process.env.GH_REPO = savedRepo;
1067
+ }
1068
+ });
1069
+
1070
+ test('S2 (correction): the browser opener normalizes the identity it hands to -R', async () => {
1071
+ const dir = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-issues-guard-open-')));
1072
+ const loaded = await loadExtension({});
1073
+ // gh is stubbed, never spawned: the fixed argv is what this test reads.
1074
+ const git = loaded.mod.libModule('worktree-git.js');
1075
+ const original = git.runArgvAsync;
1076
+ const spawned = [];
1077
+ git.runArgvAsync = async (bin, argv) => {
1078
+ spawned.push({ bin, argv: argv.slice() });
1079
+ return { status: 0, stdout: '', stderr: '', error: null };
1080
+ };
1081
+ restores.push(() => { git.runArgvAsync = original; });
1082
+ const opened = await loaded.mod.issuesOpenInBrowser(hostTui(), dir, 76, ' GitHub.com/MyFork/Project ');
1083
+ assert.equal(opened.ok, true, 'the opener ran');
1084
+ assert.deepEqual(spawned.map((call) => call.argv),
1085
+ [['issue', 'view', '76', '--web', '-R', 'github.com/MyFork/Project']],
1086
+ 'the identity reaches -R normalized: host canonical, owner/name as given, no stray whitespace');
1087
+ assert.equal(spawned[0].bin, 'gh', 'through the fixed-argv runner, never a shell');
1088
+
1089
+ for (const identity of [' ', 'myfork', '']) {
1090
+ const refused = await loaded.mod.issuesOpenInBrowser(hostTui(), dir, 76, identity);
1091
+ assert.equal(refused.ok, false, `${JSON.stringify(identity)} is not an identity`);
1092
+ assert.equal(refused.error, 'the issue list has not loaded a repository yet',
1093
+ 'and it keeps its existing no-identity refusal');
1094
+ }
1095
+ assert.equal(spawned.length, 1, 'no gh child runs for an identity that is not one');
1096
+ });