pi-odd-worktree 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +54 -311
  2. package/extensions/odd-worktree-tools.ts +4149 -2447
  3. package/lib/bash-activity.js +1164 -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 +1416 -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 +308 -14
  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 -711
  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 +1419 -0
  75. package/tools/bash-design.test.js +1091 -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 +610 -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 +1871 -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 +391 -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 +1512 -66
  121. package/tools/issues-open-guard.test.js +1096 -0
  122. package/tools/issues-section.test.js +4195 -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 +2569 -308
  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 +477 -93
  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
@@ -29,17 +29,21 @@
29
29
  // instance the extension loads via GENTLE_WORKTREE_LIB_DIR), so no live `gh`
30
30
  // runs and no real GitHub mutation is possible.
31
31
 
32
- const { test, describe, after, afterEach } = require('node:test');
32
+ const { test, describe, after, afterEach, beforeEach } = require('node:test');
33
33
  const assert = require('node:assert/strict');
34
34
  const fs = require('node:fs');
35
35
  const os = require('node:os');
36
36
  const path = require('node:path');
37
37
  const { execFileSync } = require('node:child_process');
38
38
  const { pathToFileURL } = require('node:url');
39
- const { LIB_DIR, stubbedSource } = require('./fixtures/load-extension.js');
39
+ const { LIB_DIR, stubbedSource, installDefaultBridge, withGhPath } = require('./fixtures/load-extension.js');
40
40
 
41
- const ghIssues = require('../lib/gh-issues.js');
42
- const worktreeGit = require('../lib/worktree-git.js');
41
+ // The client and git seam the extension itself loaded. One extension load compiles
42
+ // its own lib modules, so a fake must reach THAT instance — the extension's
43
+ // `libModule` seam — instead of a separate `require` of the same path. Each load
44
+ // below rebinds these, so a case always patches the instance its handler uses.
45
+ let ghIssues = require('../lib/gh-issues.js');
46
+ let worktreeGit = require('../lib/worktree-git.js');
43
47
 
44
48
  const roots = [];
45
49
  after(() => {
@@ -78,6 +82,22 @@ after(() => {
78
82
 
79
83
  afterEach(() => {
80
84
  ghIssues.setGhRunner(null);
85
+ ghIssues.setGhWhich(null);
86
+ // S5 (T8): the gate's clock seam and its cache are process state too; every
87
+ // test loads its own extension instance, and a leftover fake clock must not
88
+ // reach the next one.
89
+ if (typeof ghIssues.setGateClock === 'function') ghIssues.setGateClock(null);
90
+ if (typeof ghIssues.clearCachedGhStatus === 'function') ghIssues.clearCachedGhStatus();
91
+ // S8 (T4): the rail's published bridge is process-wide, so no test may leave
92
+ // one behind for the next.
93
+ delete globalThis[Symbol.for('gentle-shell-bridge/api/v1')];
94
+ });
95
+
96
+ // S4 (T3): the read cache has a disk half now, so every test gets its own cache
97
+ // directory — no test inherits a warm identity from another, and nothing here can
98
+ // touch the real `$XDG_CACHE_HOME`/home.
99
+ beforeEach(() => {
100
+ process.env.XDG_CACHE_HOME = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-issues-cache-')));
81
101
  });
82
102
 
83
103
  const FIXTURES = path.join(__dirname, 'fixtures');
@@ -87,40 +107,75 @@ function fixture(name) {
87
107
 
88
108
  // A fresh copy per load: module-level gate state belongs to one runtime load,
89
109
  // exactly like the host's rebuilt command registry.
90
- async function loadExtension() {
91
- const dir = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-issues-ext-')));
92
- const copy = path.join(dir, 'odd-worktree-tools.mjs');
93
- fs.writeFileSync(copy, stubbedSource());
94
- const commands = new Map();
95
- const hooks = [];
96
- const api = {
97
- registerTool: () => {},
98
- registerCommand: (name, definition) => { commands.set(name, definition); },
99
- registerMessageRenderer: () => {},
100
- on: (event, handler) => { hooks.push([event, handler]); return () => {}; },
101
- };
102
- process.env.GENTLE_WORKTREE_LIB_DIR = LIB_DIR;
103
- // The worktree plan's own Herdr calls stay isolated from a live workspace.
104
- process.env.HERDR_BIN_PATH = path.join(dir, 'no-such-herdr-binary');
105
- const mod = await import(pathToFileURL(copy).href);
106
- const factory = mod.default;
107
- factory(api);
108
- return { commands, hooks, api, mod, factory };
110
+ //
111
+ // S13 (T11): the issues surfaces are registered only when the local presence probe
112
+ // finds `gh`, and that probe reads PATH (the extension compiles its own
113
+ // `lib/gh-issues.js`, so a seam set here would not reach it). The load therefore
114
+ // runs with a PATH that answers the way the case asked — present unless it passes
115
+ // `{ gh: false }` — so the machine the suite runs on decides nothing.
116
+ async function loadExtension(options = {}) {
117
+ // S18 (T14): the extension registers nothing without gentle-shell-bridge, so
118
+ // this file's own host publishes the shared fixture's bridge before the load.
119
+ installDefaultBridge();
120
+ return withGhPath(options && options.gh === false ? 'absent' : 'present', async () => {
121
+ const dir = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-issues-ext-')));
122
+ const copy = path.join(dir, 'odd-worktree-tools.mjs');
123
+ fs.writeFileSync(copy, stubbedSource());
124
+ const commands = new Map();
125
+ const hooks = [];
126
+ const api = {
127
+ registerTool: () => {},
128
+ registerCommand: (name, definition) => { commands.set(name, definition); },
129
+ registerMessageRenderer: () => {},
130
+ on: (event, handler) => { hooks.push([event, handler]); return () => {}; },
131
+ };
132
+ process.env.GENTLE_WORKTREE_LIB_DIR = LIB_DIR;
133
+ const mod = await import(pathToFileURL(copy).href);
134
+ const factory = mod.default;
135
+ factory(api);
136
+ ghIssues = mod.libModule('gh-issues.js');
137
+ worktreeGit = mod.libModule('worktree-git.js');
138
+ modsFor.set(hooks, mod);
139
+ return { commands, hooks, api, mod, factory };
140
+ });
109
141
  }
110
142
 
111
143
  function sessionStartHandlers(hooks) {
112
144
  return hooks.filter(([event]) => event === 'session_start').map(([, handler]) => handler);
113
145
  }
114
146
 
147
+ // The module one load produced, keyed by the hooks it registered: the startup work
148
+ // `session_start` DISPATCHES (never awaits, T1) is reachable only through it.
149
+ const modsFor = new Map();
150
+
115
151
  async function fireSessionStart(hooks, ctx) {
116
152
  for (const handler of sessionStartHandlers(hooks)) {
117
153
  const out = handler({}, ctx);
118
154
  if (out && typeof out.then === 'function') await out;
119
155
  }
156
+ // S1/S2 (T1): the `gh` gate is no longer on the AWAITED path — it is dispatched
157
+ // as tracked startup work — so a test that asserts on the gate's own answer
158
+ // waits for that work here, the way the host's shutdown barrier does, instead of
159
+ // racing it. The one test that proves the awaited path is free of it fires the
160
+ // handlers itself and never reaches this helper.
161
+ const mod = modsFor.get(hooks);
162
+ if (mod && typeof mod.awaitPendingStartupTasks === 'function') {
163
+ await mod.awaitPendingStartupTasks();
164
+ }
120
165
  }
121
166
 
167
+ // This file is about the `gh` gate and the panel. The missing-bridge hint is another surface
168
+ // (tools/issues-section.test.js owns it) and it fires ONCE per process, so which test here saw it
169
+ // first would depend on execution order: a test that counts notifications passed only because an
170
+ // earlier one had already consumed the hint. The fixtures leave it out, so every count below means
171
+ // the same thing alone or in the full run.
172
+ const BRIDGE_HINT = /gentle-shell-bridge/;
173
+ const recordNote = (notes) => (message, level) => {
174
+ if (!BRIDGE_HINT.test(String(message))) notes.push([message, level]);
175
+ };
176
+
122
177
  function gateCtx(cwd, notes) {
123
- return { cwd, ui: { notify: (message, level) => notes.push([message, level]) } };
178
+ return { cwd, ui: { notify: recordNote(notes) } };
124
179
  }
125
180
 
126
181
  const stubTui = {
@@ -155,7 +210,7 @@ function makeCtx({ cwd, customImpl } = {}) {
155
210
  const ctx = {
156
211
  cwd,
157
212
  ui: {
158
- notify: (message, level) => notes.push([message, level]),
213
+ notify: recordNote(notes),
159
214
  select: async (title, options) => { selects.push([title, options]); return undefined; },
160
215
  },
161
216
  };
@@ -189,16 +244,26 @@ async function waitFor(predicate, timeoutMs = 2000) {
189
244
  const clean = (value) => String(value).replace(/\x1b\[[0-9;]*m/g, '');
190
245
 
191
246
  // Captures the options the extension mounts the real view with, leaving every
192
- // client call real and injectable.
247
+ // client call real and injectable. The patched module is the extension's OWN view
248
+ // instance (`attach`), taken from the load that will mount it.
193
249
  function captureIssuesView() {
194
- const lib = require('../lib/issues-view.js');
195
- const original = lib.createIssuesView;
196
250
  const holder = { options: null };
197
- lib.createIssuesView = (options) => {
198
- holder.options = options;
199
- return { render: () => [], handleInput: () => {}, invalidate: () => {} };
251
+ let lib;
252
+ let original;
253
+ return {
254
+ holder,
255
+ attach(mod) {
256
+ lib = mod.libModule('issues-view.js');
257
+ original = lib.createIssuesView;
258
+ lib.createIssuesView = (options) => {
259
+ holder.options = options;
260
+ return { render: () => [], handleInput: () => {}, invalidate: () => {} };
261
+ };
262
+ },
263
+ restore() {
264
+ if (lib) lib.createIssuesView = original;
265
+ },
200
266
  };
201
- return { holder, restore: () => { lib.createIssuesView = original; } };
202
267
  }
203
268
 
204
269
  // One issue node in the shape both GraphQL page queries ask for.
@@ -316,7 +381,7 @@ function makeIssuesRunner({ failComment = false, role = 'WRITE', connectionRows
316
381
  viewerPermission: role,
317
382
  issue: {
318
383
  assignees: { nodes: [{ login: 'jonasotoaguilar' }], pageInfo: { hasNextPage: false } },
319
- closedByPullRequestsReferences: { totalCount: 2 },
384
+ closedByPullRequestsReferences: { nodes: [{ number: 69 }, { number: 77 }], pageInfo: { hasNextPage: false } },
320
385
  },
321
386
  } } }));
322
387
  }
@@ -353,8 +418,11 @@ function registryFile(root) {
353
418
  // Gate the extension through session_start with a scratch cwd (so the
354
419
  // unrelated worktree discovery never touches the fixture repo), then run the
355
420
  // command handler against the fixture checkout.
356
- async function openIssues(root, { runner, rows = 24 } = {}) {
421
+ async function openIssues(root, { runner, rows = 24, prepare, args = '' } = {}) {
357
422
  const loaded = await loadExtension();
423
+ // `prepare` receives the load that is about to run the command, so a test's fake
424
+ // lands on the instance the command actually mounts.
425
+ if (typeof prepare === 'function') prepare(loaded.mod);
358
426
  ghIssues.setGhRunner(runner || makeIssuesRunner().runner);
359
427
  const scratch = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-issues-gate-')));
360
428
  await fireSessionStart(loaded.hooks, gateCtx(scratch, []));
@@ -367,7 +435,7 @@ async function openIssues(root, { runner, rows = 24 } = {}) {
367
435
  cwd: root,
368
436
  customImpl: async (captured) => { factory = captured; return null; },
369
437
  });
370
- await def.handler('', ctx);
438
+ await def.handler(args, ctx);
371
439
  assert.ok(factory, 'the overlay opens');
372
440
  const { component, done } = openComponent(factory, host);
373
441
  await tick();
@@ -383,6 +451,7 @@ async function capturedIssuesOptions(root, options = {}) {
383
451
  const capture = captureIssuesView();
384
452
  try {
385
453
  const loaded = await loadExtension();
454
+ capture.attach(loaded.mod);
386
455
  ghIssues.setGhRunner(injected.runner);
387
456
  const scratch = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-issues-gate-')));
388
457
  await fireSessionStart(loaded.hooks, gateCtx(scratch, []));
@@ -393,7 +462,7 @@ async function capturedIssuesOptions(root, options = {}) {
393
462
  factory(host.tui, {}, {}, () => {});
394
463
  return null;
395
464
  };
396
- await loaded.commands.get('issues').handler('', ctx);
465
+ await loaded.commands.get('issues').handler(options.args || '', ctx);
397
466
  await tick();
398
467
  assert.ok(capture.holder.options, 'the command mounts the view');
399
468
  return {
@@ -428,6 +497,12 @@ describe('/issues gate (S3)', () => {
428
497
 
429
498
  test('a missing gh notifies the fix once at startup and again on invocation, opening nothing', async () => {
430
499
  const { commands, hooks, mod } = await loadExtension();
500
+ // T11 (S13): the CLI's PRESENCE is pinned here, because this test is about the
501
+ // other failure — a `gh` that is installed and whose own child cannot be
502
+ // spawned (an ENOENT from the runner). The local presence check would
503
+ // otherwise answer first on a machine that has no `gh` at all, which is a
504
+ // different state with its own line.
505
+ ghIssues.setGhWhich(() => '/usr/local/bin/gh');
431
506
  ghIssues.setGhRunner(async (bin) => ({
432
507
  status: null, stdout: '', stderr: '', error: `spawn ${bin} ENOENT: gh CLI is not available`,
433
508
  }));
@@ -435,6 +510,9 @@ describe('/issues gate (S3)', () => {
435
510
  const notes = [];
436
511
  await fireSessionStart(hooks, gateCtx(root, notes));
437
512
  await fireSessionStart(hooks, gateCtx(root, notes));
513
+ // S5 (T8): the gate is decided in the background now, so the session start
514
+ // returns before the verdict lands. The notice still arrives, and still once.
515
+ assert.ok(await waitFor(() => notes.length === 1), 'the startup notification never arrived');
438
516
  assert.ok(commands.has('issues'), 'the command stays discoverable');
439
517
  assert.equal(notes.length, 1, 'exactly one startup notification per session');
440
518
  assert.match(notes[0][0], /gh CLI is not available/, 'the note names what is missing');
@@ -465,8 +543,359 @@ describe('/issues gate (S3)', () => {
465
543
  });
466
544
  });
467
545
 
546
+ // ---------------------------------------------------------------------------
547
+ // S13 (T11, corrected): without the `gh` CLI the two issues surfaces are NOT
548
+ // REGISTERED — `/issues` never loads and the `GITHUB` rail section is never added
549
+ // to the rail — so there is no line, notice or refusal for them: nothing appears,
550
+ // because nothing was registered. The decision is a LOCAL presence answer (a PATH
551
+ // walk, no child process, no `gh` invocation to find out whether `gh` exists), and
552
+ // every other surface this package contributes keeps working. A `gh` that is
553
+ // present but unauthenticated is NOT this state and keeps the login fix it always
554
+ // had.
555
+ // ---------------------------------------------------------------------------
556
+ describe('a missing gh CLI registers no issues surface (S13, T11)', () => {
557
+ test('without the CLI neither the command nor the rail section exists', async () => {
558
+ const { commands } = await loadExtension({ gh: false });
559
+
560
+ assert.equal(commands.has('issues'), false, '/issues never loads without the CLI');
561
+ // Everything else is still there: a missing `gh` is not a plugin-wide switch.
562
+ assert.ok(commands.has('warp'), '/warp still registers');
563
+ assert.ok(commands.has('odd'), '/odd still registers');
564
+ assert.ok(commands.has('files'), '/files still registers');
565
+ });
566
+
567
+ test('the decision costs no child process, at load or at session start', async () => {
568
+ const { hooks, mod } = await loadExtension({ gh: false });
569
+ const { runner, calls } = makeIssuesRunner();
570
+ ghIssues.setGhRunner(runner);
571
+
572
+ const root = makeRepo({ tag: 'cli-missing-gate' });
573
+ const notes = [];
574
+ await fireSessionStart(hooks, gateCtx(root, notes));
575
+
576
+ assert.deepEqual(calls, [], 'a missing CLI is answered locally: no gh child is ever spawned');
577
+ assert.deepEqual(notes, [], 'and nothing is said: there is no surface to say it on');
578
+ assert.equal(typeof mod, 'object');
579
+ });
580
+
581
+ test('with the CLI present the command is registered (PRESERVE)', async () => {
582
+ const { commands } = await loadExtension();
583
+ assert.ok(commands.has('issues'), '/issues loads when the CLI is on PATH');
584
+ assert.equal(typeof commands.get('issues').handler, 'function');
585
+ });
586
+
587
+ test('an unauthenticated gh that IS present keeps the login fix (PRESERVE)', async () => {
588
+ const { commands, mod } = await loadExtension();
589
+ ghIssues.setGhWhich(() => '/usr/local/bin/gh');
590
+ ghIssues.setGhRunner(async () => ({
591
+ status: 1, stdout: '', stderr: 'Failed to log in: authentication required', error: null,
592
+ }));
593
+ mod.setIssuesTuiLoader(async () => stubTui);
594
+
595
+ const { ctx, customs, notes } = makeCtx({
596
+ cwd: makeRepo({ tag: 'cli-present-unauth' }),
597
+ customImpl: async () => null,
598
+ });
599
+ await commands.get('issues').handler('', ctx);
600
+
601
+ assert.equal(customs.length, 0, 'no overlay while unauthenticated');
602
+ assert.equal(notes.length, 1);
603
+ assert.match(notes[0][0], /gh auth login/, 'the presence check never intercepts an authentication failure');
604
+ assert.equal(notes[0][1], 'error');
605
+ assert.equal(/not installed/.test(notes[0][0]), false, 'a present gh is never reported as missing');
606
+ });
607
+ });
608
+
609
+ // S1/S2 (T1, T2 of the startup theory): `session_start` must resolve without
610
+ // waiting on any child process or network call. The `gh` gate used to be AWAITED
611
+ // there — `gh api user` (≈485 ms) then `gh repo view` (≈550 ms), serially, on
612
+ // every session start AND every session switch — and `/issues` probes `gh` on
613
+ // demand anyway, so nothing is lost by dispatching it as startup work instead.
614
+ // Outside a repository there is nothing to check at all, so the gate resolves the
615
+ // checkout first and spawns nothing (T2/S3).
616
+ describe('session startup takes no gh call (S1, S2)', () => {
617
+ test('the awaited session_start resolves while the injected gh runner is still pending', async () => {
618
+ const { hooks } = await loadExtension();
619
+ const calls = [];
620
+ let release = null;
621
+ ghIssues.setGhRunner((bin, argv) => {
622
+ calls.push({ bin, argv: argv.slice() });
623
+ return new Promise((resolve) => {
624
+ release = () => resolve({ status: 0, stdout: '{"login":"me"}', stderr: '', error: null });
625
+ });
626
+ });
627
+ const root = makeRepo({ tag: 'startup-nonblocking' });
628
+ // The handlers are fired HERE, not through `fireSessionStart`: that helper
629
+ // waits for the dispatched startup work, and this is precisely the work the
630
+ // awaited path must not wait for.
631
+ const fired = sessionStartHandlers(hooks).map((handler) => Promise.resolve(handler({}, gateCtx(root, []))));
632
+ const settled = await Promise.race([
633
+ Promise.all(fired).then(() => 'resolved'),
634
+ new Promise((resolve) => { setTimeout(() => resolve('blocked'), 500); }),
635
+ ]);
636
+ assert.equal(settled, 'resolved',
637
+ 'the awaited session_start path never waits on a child process or a network call');
638
+
639
+ // Dispatched, not dropped: the probe is still startup work, so the session's
640
+ // own gate answer still arrives in the background.
641
+ assert.equal(await waitFor(() => calls.length > 0), true,
642
+ 'the gh gate still probes, off the awaited path');
643
+ if (typeof release === 'function') release();
644
+ });
645
+
646
+ test('a session outside a repository makes no gh call at startup, and stays silent', async () => {
647
+ const { hooks } = await loadExtension();
648
+ const { runner, calls } = makeIssuesRunner();
649
+ ghIssues.setGhRunner(runner);
650
+ const outside = fs.realpathSync(track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-issues-startup-plain-'))));
651
+ const notes = [];
652
+ await fireSessionStart(hooks, gateCtx(outside, notes));
653
+ assert.deepEqual(calls, [], 'outside a repository there is nothing to check, so no gh child runs');
654
+ assert.deepEqual(notes, [], 'and nothing is said: a non-repository cwd is not an error');
655
+ });
656
+ });
657
+
658
+ // S5 (T8): the gate is network work (`gh api user` then `gh repo view`, plus the
659
+ // checkout's own git probes) and the host awaits every `session_start` handler it
660
+ // is handed, so awaiting it there put the first prompt behind the whole probe on
661
+ // every open, resume and switch. What the gate DECIDES is unchanged; only WHEN it
662
+ // runs. These cases drive the registered handlers only.
663
+ describe('S5 (T8): the issues gate never delays session_start', () => {
664
+ const ghOk = (stdout) => ({ status: 0, stdout, stderr: '', error: null });
665
+ const USER_OK = ghOk(JSON.stringify({ login: 'me' }));
666
+ const USER_FAIL = { status: 1, stdout: '', stderr: 'Failed to log in: authentication required', error: null };
667
+
668
+ // A fake `gh` that answers the gate's two commands, records the checkout of
669
+ // every `gh api user` it was asked for, and lets the test decide when that one
670
+ // call answers.
671
+ function gateRunner({ user = () => Promise.resolve(USER_OK) } = {}) {
672
+ const gateCalls = [];
673
+ const runner = (_bin, argv, opts = {}) => {
674
+ if (argv[0] === 'api' && argv[1] === 'user') {
675
+ gateCalls.push(opts.cwd);
676
+ return user(opts.cwd);
677
+ }
678
+ if (argv[0] === 'repo' && argv[1] === 'view') {
679
+ return Promise.resolve(ghOk(JSON.stringify({ nameWithOwner: 'myfork/project' })));
680
+ }
681
+ return Promise.resolve(ghOk(''));
682
+ };
683
+ return { runner, gateCalls };
684
+ }
685
+
686
+ // The gate resolves the CHECKOUT before it asks gh anything (S3/T2), so a
687
+ // session's cwd has to be a real checkout for a probe to run at all: a bare
688
+ // temporary directory is the non-repository state, which by design spawns
689
+ // nothing. What these cases measure — dispatch, the TTL, the shared probe, the
690
+ // generation — is unchanged; only the preconditions of the directory moved.
691
+ function scratchCheckout(tag) {
692
+ return makeRepo({ tag: `gate-${tag}` });
693
+ }
694
+
695
+ function sessionShutdownHandlers(hooks) {
696
+ return hooks.filter(([event]) => event === 'session_shutdown').map(([, handler]) => handler);
697
+ }
698
+
699
+ async function fireSessionShutdown(hooks, ctx) {
700
+ for (const handler of sessionShutdownHandlers(hooks)) {
701
+ const out = handler({}, ctx);
702
+ if (out && typeof out.then === 'function') await out;
703
+ }
704
+ }
705
+
706
+ // Fire the host's session_start handlers and give them a bounded window to
707
+ // resolve, so a handler that waits for `gh` fails an assertion below instead of
708
+ // hanging the suite.
709
+ async function fireSessionStartPromptly(hooks, ctx) {
710
+ const pending = sessionStartHandlers(hooks).map((handler) => Promise.resolve(handler({}, ctx)));
711
+ const outcome = await Promise.race([
712
+ Promise.all(pending).then(() => 'returned'),
713
+ new Promise((resolve) => setTimeout(() => resolve('waiting'), 100)),
714
+ ]);
715
+ return { outcome, pending };
716
+ }
717
+
718
+ // A window in which a NEW probe would have reached the injected `gh` (the client
719
+ // reads the checkout's local git configuration first). Nothing arriving inside it
720
+ // is the evidence that a cached answer was reused.
721
+ const settleWindow = (ms = 100) => new Promise((resolve) => setTimeout(resolve, ms));
722
+
723
+ test('session_start returns while the gate is still pending, and the probe still runs', async () => {
724
+ const { hooks } = await loadExtension();
725
+ const held = [];
726
+ ghIssues.setGhRunner(gateRunner({ user: () => new Promise((resolve) => { held.push(resolve); }) }).runner);
727
+ const notes = [];
728
+ const { outcome } = await fireSessionStartPromptly(hooks, gateCtx(scratchCheckout('pending'), notes));
729
+ assert.equal(outcome, 'returned', 'session_start never waits for the network gate');
730
+ assert.ok(await waitFor(() => held.length === 1), 'the probe never ran in the background');
731
+ assert.deepEqual(notes, [], 'and decides nothing before it answers');
732
+ held[0](USER_OK);
733
+ await tick();
734
+ assert.deepEqual(notes, [], 'a usable gh still says nothing, exactly as before');
735
+ });
736
+
737
+ test('a verdict that lands late still notifies the same sentence and still refuses /issues', async () => {
738
+ const { hooks, commands, mod } = await loadExtension();
739
+ const held = [];
740
+ ghIssues.setGhRunner(gateRunner({ user: () => new Promise((resolve) => { held.push(resolve); }) }).runner);
741
+ const root = scratchCheckout('deferred');
742
+ const notes = [];
743
+ const { outcome } = await fireSessionStartPromptly(hooks, gateCtx(root, notes));
744
+ assert.equal(outcome, 'returned', 'the session start does not wait for the verdict');
745
+ assert.deepEqual(notes, [], 'the startup note waits for the verdict');
746
+ assert.ok(await waitFor(() => held.length === 1), 'the probe never ran in the background');
747
+
748
+ held[0]({ status: null, stdout: '', stderr: '', error: 'spawn gh ENOENT: gh CLI is not available' });
749
+ assert.ok(await waitFor(() => notes.length === 1), 'the deferred verdict never notified');
750
+ assert.match(notes[0][0], /gh CLI is not available/, 'the note names what is missing');
751
+ assert.match(notes[0][0], /gh auth login/, 'the note names the command that fixes it');
752
+ assert.match(notes[0][0], /cannot open/, 'the note names the real consequence');
753
+ assert.equal(notes[0][1], 'info');
754
+
755
+ mod.setIssuesTuiLoader(async () => stubTui);
756
+ const { ctx, customs, notes: invokeNotes } = makeCtx({ cwd: root, customImpl: async () => null });
757
+ await commands.get('issues').handler('', ctx);
758
+ assert.equal(customs.length, 0, 'invocation without gh opens nothing');
759
+ assert.equal(invokeNotes.length, 1, 'invocation reports its own, fuller error');
760
+ assert.match(invokeNotes[0][0], /gh auth login/);
761
+ assert.equal(invokeNotes[0][1], 'error');
762
+ });
763
+
764
+ test('concurrent probes share one call and a settled answer is reused inside the TTL', async () => {
765
+ const { hooks } = await loadExtension();
766
+ const held = [];
767
+ const gate = gateRunner({ user: () => new Promise((resolve) => { held.push(resolve); }) });
768
+ ghIssues.setGhRunner(gate.runner);
769
+ const root = scratchCheckout('share');
770
+ const other = scratchCheckout('share-other');
771
+
772
+ // Two session starts for ONE checkout while the first probe is in flight.
773
+ await fireSessionStartPromptly(hooks, gateCtx(root, []));
774
+ await fireSessionStartPromptly(hooks, gateCtx(root, []));
775
+ assert.ok(await waitFor(() => gate.gateCalls.length === 1), 'the gate never probed');
776
+ assert.equal(gate.gateCalls.length, 1, 'concurrent probes for one checkout share one gh call');
777
+ held[0](USER_OK);
778
+ await tick();
779
+
780
+ // A settled success is reused for the rest of its TTL.
781
+ await fireSessionStartPromptly(hooks, gateCtx(root, []));
782
+ await settleWindow();
783
+ assert.equal(gate.gateCalls.length, 1, 'a later session reuses the answer it already paid for');
784
+
785
+ // Another checkout pays for its own.
786
+ await fireSessionStartPromptly(hooks, gateCtx(other, []));
787
+ assert.ok(await waitFor(() => gate.gateCalls.length === 2), 'a different checkout never probed');
788
+ assert.deepEqual(gate.gateCalls, [root, other], 'and the cache is keyed by the checkout');
789
+ held[1](USER_OK);
790
+ await tick();
791
+ });
792
+
793
+ test('a success is reused for minutes, a failure only for seconds', async () => {
794
+ const { hooks } = await loadExtension();
795
+ const clock = { at: 1_000_000 };
796
+ ghIssues.setGateClock(() => clock.at);
797
+
798
+ const okRoot = scratchCheckout('ttl-ok');
799
+ const okGate = gateRunner();
800
+ ghIssues.setGhRunner(okGate.runner);
801
+ await fireSessionStart(hooks, gateCtx(okRoot, []));
802
+ await waitFor(() => okGate.gateCalls.length === 1);
803
+ clock.at += 60_000;
804
+ await fireSessionStart(hooks, gateCtx(okRoot, []));
805
+ await settleWindow();
806
+ assert.equal(okGate.gateCalls.length, 1, 'a success inside its TTL is reused, not re-probed');
807
+ clock.at += 5 * 60_000;
808
+ await fireSessionStart(hooks, gateCtx(okRoot, []));
809
+ await waitFor(() => okGate.gateCalls.length === 2);
810
+ assert.equal(okGate.gateCalls.length, 2, 'past the success TTL the gate probes again');
811
+
812
+ const failRoot = scratchCheckout('ttl-fail');
813
+ const failGate = gateRunner({ user: () => Promise.resolve(USER_FAIL) });
814
+ ghIssues.setGhRunner(failGate.runner);
815
+ await fireSessionStart(hooks, gateCtx(failRoot, []));
816
+ await waitFor(() => failGate.gateCalls.length === 1);
817
+ clock.at += 10_000;
818
+ await fireSessionStart(hooks, gateCtx(failRoot, []));
819
+ await settleWindow();
820
+ assert.equal(failGate.gateCalls.length, 1, 'a failure inside its short TTL is reused');
821
+ clock.at += 30_000;
822
+ await fireSessionStart(hooks, gateCtx(failRoot, []));
823
+ await waitFor(() => failGate.gateCalls.length === 2);
824
+ assert.equal(failGate.gateCalls.length, 2, 'past the short TTL the failure is probed again');
825
+ });
826
+
827
+ test('a verdict from a superseded checkout never applies to the session that replaced it', async () => {
828
+ const { hooks } = await loadExtension();
829
+ const held = new Map();
830
+ ghIssues.setGhRunner(gateRunner({
831
+ user: (cwd) => new Promise((resolve) => { held.set(cwd, resolve); }),
832
+ }).runner);
833
+ const checkoutA = scratchCheckout('supersede-a');
834
+ const checkoutB = scratchCheckout('supersede-b');
835
+ const notesA = [];
836
+ const notesB = [];
837
+
838
+ await fireSessionStartPromptly(hooks, gateCtx(checkoutA, notesA));
839
+ await waitFor(() => held.has(checkoutA));
840
+ await fireSessionStartPromptly(hooks, gateCtx(checkoutB, notesB));
841
+ await waitFor(() => held.has(checkoutB));
842
+
843
+ // The previous checkout's verdict lands now, after its session was superseded.
844
+ held.get(checkoutA)(USER_FAIL);
845
+ await tick();
846
+ await tick();
847
+ assert.deepEqual(notesA, [], 'a superseded verdict never notifies the session it belonged to');
848
+
849
+ held.get(checkoutB)(USER_OK);
850
+ await tick();
851
+ assert.deepEqual(notesB, [], 'the live session keeps its own verdict');
852
+ assert.equal(held.size, 2, 'no extra probe ran');
853
+ });
854
+
855
+ test('session_shutdown drops the gate cache, so the next session probes afresh', async () => {
856
+ const { hooks } = await loadExtension();
857
+ const clock = { at: 2_000_000 };
858
+ ghIssues.setGateClock(() => clock.at);
859
+ const gate = gateRunner();
860
+ ghIssues.setGhRunner(gate.runner);
861
+ const root = scratchCheckout('shutdown');
862
+ const ctx = gateCtx(root, []);
863
+
864
+ await fireSessionStart(hooks, ctx);
865
+ await waitFor(() => gate.gateCalls.length === 1);
866
+ clock.at += 1_000;
867
+ await fireSessionStart(hooks, ctx);
868
+ await settleWindow();
869
+ assert.equal(gate.gateCalls.length, 1, 'inside the TTL the same checkout is reused');
870
+
871
+ await fireSessionShutdown(hooks, ctx);
872
+ await fireSessionStart(hooks, ctx);
873
+ await waitFor(() => gate.gateCalls.length === 2);
874
+ assert.equal(gate.gateCalls.length, 2, 'a new session never inherits the probe its predecessor paid for');
875
+ });
876
+
877
+ test('the cache holds a handful of checkouts, never every one ever seen', async () => {
878
+ const { hooks } = await loadExtension();
879
+ const gate = gateRunner();
880
+ ghIssues.setGhRunner(gate.runner);
881
+ const scopes = Array.from({ length: 10 }, (_, index) => scratchCheckout(`bound-${index}`));
882
+ for (const scope of scopes) await fireSessionStart(hooks, gateCtx(scope, []));
883
+ await waitFor(() => gate.gateCalls.length === scopes.length);
884
+ assert.equal(gate.gateCalls.length, scopes.length, 'every checkout probed once');
885
+
886
+ await fireSessionStart(hooks, gateCtx(scopes.at(-1), []));
887
+ await settleWindow();
888
+ assert.equal(gate.gateCalls.length, scopes.length, 'the newest checkout is still cached');
889
+
890
+ await fireSessionStart(hooks, gateCtx(scopes[0], []));
891
+ await waitFor(() => gate.gateCalls.length === scopes.length + 1);
892
+ assert.equal(gate.gateCalls.length, scopes.length + 1,
893
+ 'the oldest checkout was evicted instead of the cache growing without bound');
894
+ });
895
+ });
896
+
468
897
  describe('/issues overlay and arguments', () => {
469
- test('opens full screen fed by the scoped searches and the All connection', async () => {
898
+ test('opens full screen fed by the three scoped searches, and leaves All until it is asked for', async () => {
470
899
  const root = makeRepo({ tag: 'issues-open' });
471
900
  const { runner, calls } = makeIssuesRunner();
472
901
  const { component, customs, notes } = await openIssues(root, { runner });
@@ -485,17 +914,112 @@ describe('/issues overlay and arguments', () => {
485
914
  'assignee:@me sort:updated-desc',
486
915
  'involves:@me -author:@me sort:updated-desc',
487
916
  ], 'every scoped tab is read once with its own exact query');
488
- assert.equal(connectionReads(calls).length, 1, 'the All tab is read once through the issue connection');
917
+ assert.equal(connectionReads(calls).length, 0,
918
+ 'opening the panel reads no connection page: All is read when it is entered (S2)');
489
919
  const body = clean(component.render(110).join('\n'));
490
920
  assert.match(body, /My issues/);
491
921
  assert.match(body, /Assigned/);
492
922
  assert.match(body, /Involved/);
923
+ assert.doesNotMatch(clean(component.render(110)[2]), /\bAll\b/, 'All is no longer a tab (S1)');
493
924
  assert.match(body, /76/, 'the listed issue number');
494
925
  assert.match(body, /chore: update/, 'the listed issue title');
495
926
  assert.match(body, /◈ Issues/, 'the header names the surface');
496
927
  assert.ok(!body.includes(path.basename(root)), 'the header never repeats the checkout name');
497
928
  });
498
929
 
930
+ test('All is read the first time the shortcut enters it, and re-entering reuses it (S1/S2)', async () => {
931
+ const root = makeRepo({ tag: 'issues-all-lazy' });
932
+ const { runner, calls } = makeIssuesRunner();
933
+ const { component } = await openIssues(root, { runner });
934
+ await tick();
935
+ assert.equal(connectionReads(calls).length, 0, 'the mount reads no connection page');
936
+ assert.equal(searchQueries(calls).length, 3, 'and exactly the three scoped searches');
937
+ component.handleInput('g');
938
+ await tick();
939
+ const reads = connectionReads(calls);
940
+ assert.equal(reads.length, 1, 'entering All issues one connection read');
941
+ const bar = clean(component.render(110)[2]);
942
+ assert.match(bar, /▸ All \(\d+\)/, `the bar reads only the All view: ${bar}`);
943
+ for (const label of ['My issues', 'Assigned', 'Involved']) {
944
+ assert.ok(!bar.includes(label), `the scoped tabs leave the bar in the All view: ${bar}`);
945
+ }
946
+ // The full legend only fits a wide frame; the label is what is under test.
947
+ assert.match(clean(component.render(200).at(-2)), /g related issues/,
948
+ 'inside All the hint says the key goes back (D1)');
949
+ component.handleInput('g');
950
+ await tick();
951
+ assert.match(clean(component.render(200).at(-2)), /g all issues/,
952
+ 'outside All the hint names what the key opens (D1)');
953
+ assert.equal(connectionReads(calls).length, 1, 'leaving All reads nothing');
954
+ component.handleInput('g');
955
+ await tick();
956
+ assert.equal(connectionReads(calls).length, 1, 're-entering All reuses the page it read (S2)');
957
+ });
958
+
959
+ test('a typed filter is read by the three scoped tabs, and the All view searches instead of connecting (S3/S4/S5)', async () => {
960
+ const root = makeRepo({ tag: 'issues-filter' });
961
+ const { runner, calls } = makeIssuesRunner();
962
+ const { component } = await openIssues(root, { runner });
963
+ await tick();
964
+ const mount = searchQueries(calls).length;
965
+ assert.equal(mount, 3, 'the mount read the three scoped buckets');
966
+ component.handleInput('t');
967
+ for (const ch of 'label:bug') component.handleInput(ch);
968
+ await waitFor(() => searchQueries(calls).length >= mount + 3);
969
+ await tick();
970
+ assert.deepEqual(searchQueries(calls).slice(mount), [
971
+ 'author:@me sort:updated-desc label:bug',
972
+ 'assignee:@me sort:updated-desc label:bug',
973
+ 'involves:@me -author:@me sort:updated-desc label:bug',
974
+ ], 'the settled filter re-reads all three scoped buckets, each with its own scope');
975
+ component.handleInput('enter');
976
+ await tick();
977
+ // Entering All while the filter is on is a SEARCH read: the connection takes
978
+ // no text, and the search count is capped, so the view never claims it exact.
979
+ const before = searchQueries(calls).length;
980
+ component.handleInput('g');
981
+ await waitFor(() => searchQueries(calls).length > before);
982
+ await tick();
983
+ assert.deepEqual(searchQueries(calls).slice(before), ['sort:updated-desc label:bug'],
984
+ 'a filtered All goes through the search path, with the filter');
985
+ assert.equal(connectionReads(calls).length, 0, 'and never reads the unfiltered connection');
986
+ await waitFor(() => /▸ All \(\d+\+\)/.test(clean(component.render(110)[2])));
987
+ assert.match(clean(component.render(110)[2]), /▸ All \(\d+\+\)/,
988
+ 'a filtered All marks its count inexact instead of claiming an exact total');
989
+ assert.match(clean(component.render(110)[3]), /via search/, 'the frame names the read on screen');
990
+ });
991
+
992
+ // S5: the route trims a whitespace-only query into "no filter" and takes the
993
+ // repository CONNECTION, so the note the view paints has to name that same
994
+ // read — the route and the note decide from one fact.
995
+ test('a whitespace-only filter takes the connection read, and the note names it (S5)', async () => {
996
+ const root = makeRepo({ tag: 'issues-blank-filter' });
997
+ const { runner, calls } = makeIssuesRunner();
998
+ const { component } = await openIssues(root, { runner });
999
+ await tick();
1000
+ const mount = searchQueries(calls).length;
1001
+ assert.equal(mount, 3, 'the mount read the three scoped buckets');
1002
+ component.handleInput('g');
1003
+ await waitFor(() => connectionReads(calls).length === 1);
1004
+ await tick();
1005
+ component.handleInput('t');
1006
+ component.handleInput(' ');
1007
+ await waitFor(() => connectionReads(calls).length === 2);
1008
+ await tick();
1009
+ assert.deepEqual(searchQueries(calls).slice(mount), [
1010
+ 'author:@me sort:updated-desc',
1011
+ 'assignee:@me sort:updated-desc',
1012
+ 'involves:@me -author:@me sort:updated-desc',
1013
+ ], 'the scoped tabs re-read their own searches with no stray text appended');
1014
+ assert.equal(connectionReads(calls).length, 2,
1015
+ 'the All view reads the repository connection again, never a search');
1016
+ const note = clean(component.render(110)[3]);
1017
+ assert.match(note, /via connection \(exact total\)/, `the note names the read on screen: ${note}`);
1018
+ const bar = clean(component.render(110)[2]);
1019
+ assert.match(bar, /▸ All \(\d+\)/, `and the exact connection total wears no mark: ${bar}`);
1020
+ assert.ok(!/\(\d+\+\)/.test(bar), `no inexact total is claimed for an exact read: ${bar}`);
1021
+ });
1022
+
499
1023
  test('an argument notifies and opens nothing', async () => {
500
1024
  const root = makeRepo({ tag: 'issues-args' });
501
1025
  const { commands, mod, hooks } = await loadExtension();
@@ -510,9 +1034,10 @@ describe('/issues overlay and arguments', () => {
510
1034
  assert.deepEqual(notes[0], ['Unknown option "extra". Use /issues.', 'error']);
511
1035
  });
512
1036
 
513
- test('outside a Git checkout notifies the shared line at info and opens nothing', async () => {
1037
+ test('outside a Git checkout notifies the shared line at info and spawns no gh', async () => {
514
1038
  const { commands, mod, hooks } = await loadExtension();
515
- ghIssues.setGhRunner(makeIssuesRunner().runner);
1039
+ const { runner, calls } = makeIssuesRunner();
1040
+ ghIssues.setGhRunner(runner);
516
1041
  const scratch = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-issues-gate-')));
517
1042
  await fireSessionStart(hooks, gateCtx(scratch, []));
518
1043
  mod.setIssuesTuiLoader(async () => stubTui);
@@ -522,22 +1047,23 @@ describe('/issues overlay and arguments', () => {
522
1047
  assert.equal(customs.length, 0, 'no overlay outside a checkout');
523
1048
  assert.equal(selects.length, 0, 'no fallback selector outside a checkout');
524
1049
  assert.deepEqual(notes, [[`not a git repository: ${outside}; run 'git init' first`, 'info']]);
1050
+ assert.deepEqual(calls, [],
1051
+ 'the refusal is the checkout’s own answer: it never asks gh, which could only report its own error');
525
1052
  });
526
1053
  });
527
1054
 
528
1055
  describe('/issues is read-only about the worktree association', () => {
1056
+ // S3/S4: the association's document is gone. The property this case proves is the
1057
+ // one that survives it — /issues is handed no association option and every read and
1058
+ // keypress writes nothing at all.
529
1059
  test('the mounted view is handed no association option and reading writes nothing', async () => {
530
1060
  const root = makeRepo({ tag: 'issues-readonly' });
531
1061
  const file = registryFile(root);
532
- fs.writeFileSync(file, `${JSON.stringify({
533
- version: 1,
534
- worktrees: [{ branch: git(root, ['branch', '--show-current']).trim(), path: root, thread: 't', issues: [76], odd: null }],
535
- }, null, 2)}\n`);
536
- const before = fs.readFileSync(file, 'utf8');
1062
+ assert.equal(fs.existsSync(file), false, 'the fixture starts with no worktree document');
537
1063
  const { runner } = makeIssuesRunner();
538
1064
  const capture = captureIssuesView();
539
1065
  try {
540
- await openIssues(root, { runner });
1066
+ await openIssues(root, { runner, prepare: (mod) => capture.attach(mod) });
541
1067
  const options = capture.holder.options;
542
1068
  for (const key of ['assigned', 'assignedOdd', 'saveAssignment', 'assignmentEnabled']) {
543
1069
  assert.equal(key in options, false, `the view is handed no ${key}: ${JSON.stringify(Object.keys(options))}`);
@@ -545,15 +1071,14 @@ describe('/issues is read-only about the worktree association', () => {
545
1071
  } finally {
546
1072
  capture.restore();
547
1073
  }
548
- assert.equal(fs.readFileSync(file, 'utf8'), before, 'reading writes nothing');
1074
+ assert.equal(fs.existsSync(file), false, 'reading writes no worktree document');
549
1075
 
550
1076
  const { component } = await openIssues(root, { runner });
551
- assert.match(clean(component.render(110).join('\n')), /76/, 'the stored issue still lists');
552
1077
  component.handleInput('down');
553
1078
  component.handleInput('space');
554
1079
  component.handleInput('ctrl+s');
555
1080
  await tick();
556
- assert.equal(fs.readFileSync(file, 'utf8'), before, 'the removed association keys write nothing');
1081
+ assert.equal(fs.existsSync(file), false, 'the removed association keys write nothing');
557
1082
  });
558
1083
  });
559
1084
 
@@ -688,7 +1213,7 @@ describe('/issues actions (S3,S4)', () => {
688
1213
  const primed = searchQueries(calls);
689
1214
  assert.equal(primed.length, 3, 'the mount read every scoped bucket once');
690
1215
  const connections = connectionReads(calls).length;
691
- assert.equal(connections, 1, 'and the All bucket once, through the connection');
1216
+ assert.equal(connections, 0, 'and no page of the All connection (S2)');
692
1217
 
693
1218
  const before = clean(component.render(110).join('\n'));
694
1219
  component.handleInput('f');
@@ -724,23 +1249,16 @@ describe('/issues actions (S3,S4)', () => {
724
1249
  describe('/issues page seam (S5,D1)', () => {
725
1250
  async function mountCapturing(root, rows = 24) {
726
1251
  const base = makeIssuesRunner();
727
- const lib = require('../lib/issues-view.js');
728
- const realCreate = lib.createIssuesView;
729
- const realPage = ghIssues.getIssuePage;
1252
+ // The extension's OWN view and client, taken after the load: one load compiles
1253
+ // its own lib modules, so the fakes go on the instance the command mounts.
1254
+ let lib;
1255
+ let realCreate;
1256
+ let realPage;
730
1257
  const order = [];
731
1258
  const pages = [];
732
1259
  const holder = { options: null };
733
- ghIssues.getIssuePage = (params, opts) => {
734
- order.push('page');
735
- pages.push({ params, opts });
736
- return realPage(params, opts);
737
- };
738
- lib.createIssuesView = (options) => {
739
- holder.options = options;
740
- order.push('view');
741
- return realCreate(options);
742
- };
743
1260
  const restore = () => {
1261
+ if (!lib) return;
744
1262
  lib.createIssuesView = realCreate;
745
1263
  ghIssues.getIssuePage = realPage;
746
1264
  };
@@ -748,6 +1266,19 @@ describe('/issues page seam (S5,D1)', () => {
748
1266
  let loaded = null;
749
1267
  try {
750
1268
  loaded = await loadExtension();
1269
+ lib = loaded.mod.libModule('issues-view.js');
1270
+ realCreate = lib.createIssuesView;
1271
+ realPage = ghIssues.getIssuePage;
1272
+ ghIssues.getIssuePage = (params, opts) => {
1273
+ order.push('page');
1274
+ pages.push({ params, opts });
1275
+ return realPage(params, opts);
1276
+ };
1277
+ lib.createIssuesView = (options) => {
1278
+ holder.options = options;
1279
+ order.push('view');
1280
+ return realCreate(options);
1281
+ };
751
1282
  ghIssues.setGhRunner(base.runner);
752
1283
  const scratch = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-issues-gate-')));
753
1284
  await fireSessionStart(loaded.hooks, gateCtx(scratch, []));
@@ -781,6 +1312,8 @@ describe('/issues page seam (S5,D1)', () => {
781
1312
  ['involved', 'Involved', null],
782
1313
  ['all', 'All', null],
783
1314
  ], 'bucket metadata only: no accumulated rows are handed to the view');
1315
+ assert.deepEqual(options.pages.filter((page) => page.lazy === true).map((page) => page.id), ['all'],
1316
+ 'the All bucket is marked lazy so the mount-time prefetch skips it (S2)');
784
1317
  assert.equal(options.loadPages, undefined, 'no eager/lazy-list loader is passed beside the fresh seam');
785
1318
  assert.equal(typeof options.loadIssuePage, 'function');
786
1319
  const first = run.pages[0];
@@ -1077,7 +1610,7 @@ describe('/issues repository identity (S5)', () => {
1077
1610
  const run = await capturedIssuesOptions(root, { runner: gh.runner, calls: gh.calls });
1078
1611
  const gitCalls = [];
1079
1612
  const original = worktreeGit.runArgvAsync;
1080
- worktreeGit.runArgvAsync = async (bin, argv) => {
1613
+ worktreeGit.runArgvAsync = async (_bin, argv) => {
1081
1614
  gitCalls.push({ argv: argv.slice() });
1082
1615
  return { status: 0, stdout: '', stderr: '', error: null };
1083
1616
  };
@@ -1093,7 +1626,15 @@ describe('/issues repository identity (S5)', () => {
1093
1626
  assert.equal(opened.ok, false, 'the opener refuses instead of opening another repository');
1094
1627
  assert.match(opened.error, /is a local path, not a GitHub repository/);
1095
1628
  assert.deepEqual(gitCalls, [], 'the browser opener never ran');
1096
- assert.ok(gh.calls.every((call) => call.cwd !== root), 'no gh command ran in this checkout');
1629
+ // S1/S3 (T1, T2): the session gate is dispatched startup work now and no
1630
+ // longer warms a session-wide `ok` from a scratch cwd, so THIS command's own
1631
+ // on-demand health probe (`gh api user`, `gh repo view`) runs here. That probe
1632
+ // asks gh whether it is usable; it reads nothing of this repository. No READ
1633
+ // and no opener reaches gh from a checkout it cannot name.
1634
+ const reads = gh.calls.filter((call) => call.argv[0] === 'issue'
1635
+ || call.argv[0] === 'label'
1636
+ || (call.argv[0] === 'api' && call.argv[1] === 'graphql'));
1637
+ assert.deepEqual(reads, [], 'no repository read left this checkout');
1097
1638
  } finally {
1098
1639
  worktreeGit.runArgvAsync = original;
1099
1640
  run.restore();
@@ -1106,7 +1647,7 @@ describe('/issues repository identity (S5)', () => {
1106
1647
  const run = await capturedIssuesOptions(root, { runner: gh.runner, calls: gh.calls });
1107
1648
  const gitCalls = [];
1108
1649
  const original = worktreeGit.runArgvAsync;
1109
- worktreeGit.runArgvAsync = async (bin, argv) => {
1650
+ worktreeGit.runArgvAsync = async (_bin, argv) => {
1110
1651
  gitCalls.push({ argv: argv.slice() });
1111
1652
  return { status: 0, stdout: '', stderr: '', error: null };
1112
1653
  };
@@ -1215,3 +1756,908 @@ describe('/issues registration survives a reused module', () => {
1215
1756
  assert.ok(reloaded.has('issues'), 'a rebuilt registry on the same API must also regain the command');
1216
1757
  });
1217
1758
  });
1759
+
1760
+ // S7 (issues-all-toggle): `/issues <number>` opens the same panel on `Assigned`
1761
+ // with that issue selected and its detail shown, exactly as if the reader had
1762
+ // moved to Assigned and arrowed down to it. Anything that is not a bare
1763
+ // positive integer (optionally `#`-prefixed) keeps the command's original
1764
+ // refusal. S8 (the sidebar's cache) is another task and is not exercised here.
1765
+ describe('/issues <number> opens the panel on one issue (S7)', () => {
1766
+ const assignedSearches = (calls) => searchQueries(calls).filter((query) => query.startsWith('assignee:@me'));
1767
+
1768
+ function syntheticRow(number, title = `assigned issue ${number}`) {
1769
+ return {
1770
+ number,
1771
+ title,
1772
+ state: 'OPEN',
1773
+ createdAt: '2026-02-01T00:00:00Z',
1774
+ updatedAt: '2026-02-01T00:00:00Z',
1775
+ url: `https://example.test/issues/${number}`,
1776
+ };
1777
+ }
1778
+
1779
+ // A runner that answers the scoped SEARCH reads from per-bucket row lists,
1780
+ // and everything else from the shared fixture runner, so the mounted view's
1781
+ // own cursor paging is exercised through the real client seam.
1782
+ function pagedSearchRunner(rowsByBucket) {
1783
+ const base = makeIssuesRunner();
1784
+ const calls = [];
1785
+ const runner = async (bin, argv, opts) => {
1786
+ calls.push({ bin, argv: argv.slice(), cwd: opts ? opts.cwd : undefined });
1787
+ if (argv[0] === 'api' && argv[1] === 'graphql') {
1788
+ const query = graphqlField(argv, 'query', '-f') || '';
1789
+ if (query.includes('type: ISSUE')) {
1790
+ const search = graphqlField(argv, 'search') || '';
1791
+ const rows = search.includes('assignee:@me') ? rowsByBucket.assigned
1792
+ : search.includes('involves:@me') ? rowsByBucket.involved
1793
+ : rowsByBucket.mine;
1794
+ return { status: 0, stdout: graphqlSearchPage(argv, rows || []), stderr: '', error: null };
1795
+ }
1796
+ }
1797
+ return base.runner(bin, argv, opts);
1798
+ };
1799
+ return { runner, calls };
1800
+ }
1801
+
1802
+ test('a bare number opens on Assigned with that row selected and its detail shown', async () => {
1803
+ const root = makeRepo({ tag: 'issues-one-number' });
1804
+ const { runner, calls } = makeIssuesRunner();
1805
+ const { component } = await openIssues(root, { runner, args: '76' });
1806
+ await tick();
1807
+ const frame = clean(component.render(200).join('\n'));
1808
+ assert.match(frame, /▸ Assigned/, 'the panel opens on the Assigned tab');
1809
+ assert.match(frame, /▸ chore: update/, 'the matching row is the selected one');
1810
+ assert.ok(calls.some((call) => call.argv[0] === 'issue' && call.argv[1] === 'view'
1811
+ && call.argv.includes('76') && call.argv.includes('--json')),
1812
+ 'the requested issue detail was read through gh');
1813
+ assert.equal(searchQueries(calls).length, 3, 'opening still reads exactly the three scoped buckets');
1814
+ assert.equal(connectionReads(calls).length, 0, 'and never the All connection (S2)');
1815
+ });
1816
+
1817
+ test('the #-prefixed form opens the same panel on the same issue', async () => {
1818
+ const root = makeRepo({ tag: 'issues-one-hash' });
1819
+ const { runner } = makeIssuesRunner();
1820
+ const { component } = await openIssues(root, { runner, args: '#76' });
1821
+ await tick();
1822
+ const frame = clean(component.render(200).join('\n'));
1823
+ assert.match(frame, /▸ Assigned/);
1824
+ assert.match(frame, /▸ chore: update/);
1825
+ });
1826
+
1827
+ test('anything else keeps the exact old refusal and opens nothing', async () => {
1828
+ const root = makeRepo({ tag: 'issues-one-refused' });
1829
+ const { commands, mod, hooks } = await loadExtension();
1830
+ ghIssues.setGhRunner(makeIssuesRunner().runner);
1831
+ const scratch = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-issues-gate-')));
1832
+ await fireSessionStart(hooks, gateCtx(scratch, []));
1833
+ mod.setIssuesTuiLoader(async () => stubTui);
1834
+ for (const arg of ['0', '-3', '12abc', 'all', '5 6', '#', '#0']) {
1835
+ const { ctx, customs, notes } = makeCtx({ cwd: root, customImpl: async () => null });
1836
+ await commands.get('issues').handler(arg, ctx);
1837
+ assert.equal(customs.length, 0, `${arg}: no overlay is opened`);
1838
+ assert.deepEqual(notes, [[`Unknown option "${arg}". Use /issues.`, 'error']], `${arg}: the old refusal is unchanged`);
1839
+ }
1840
+ });
1841
+
1842
+ test('a number that is not in Assigned says so and keeps the first row', async () => {
1843
+ const root = makeRepo({ tag: 'issues-one-missing' });
1844
+ const { runner } = makeIssuesRunner();
1845
+ const { component } = await openIssues(root, { runner, args: '51' });
1846
+ assert.ok(await waitFor(() => clean(component.render(200).join('\n')).includes('#51 is not in Assigned')));
1847
+ const frame = clean(component.render(200).join('\n'));
1848
+ assert.match(frame, /#51 is not in Assigned/, 'the note row names the miss');
1849
+ assert.match(frame, /▸ chore: update/, 'the first row is still the selection');
1850
+ });
1851
+
1852
+ test('a number on a later Assigned page is found by paging and selected', async () => {
1853
+ const root = makeRepo({ tag: 'issues-one-page2' });
1854
+ const rows = Array.from({ length: 18 }, (_, at) => syntheticRow(at + 1));
1855
+ const { runner, calls } = pagedSearchRunner({ mine: [], assigned: [...rows, syntheticRow(51)], involved: [] });
1856
+ const { component } = await openIssues(root, { runner, args: '51' });
1857
+ await tick();
1858
+ const frame = clean(component.render(200).join('\n'));
1859
+ assert.match(frame, /▸ assigned issue 51/, 'the second-page match is selected');
1860
+ assert.equal(assignedSearches(calls).length, 2, 'exactly one more page was read to find it');
1861
+ });
1862
+
1863
+ test('paging for a missing number stops at five Assigned pages', async () => {
1864
+ const root = makeRepo({ tag: 'issues-one-bound' });
1865
+ const rows = Array.from({ length: 200 }, (_, at) => syntheticRow(at + 1));
1866
+ const { runner, calls } = pagedSearchRunner({ mine: [], assigned: rows, involved: [] });
1867
+ const { component } = await openIssues(root, { runner, args: '999' });
1868
+ assert.ok(await waitFor(() => assignedSearches(calls).length >= 5));
1869
+ await tick();
1870
+ assert.equal(assignedSearches(calls).length, 5, 'the bound is five Assigned pages in total');
1871
+ const frame = clean(component.render(200).join('\n'));
1872
+ assert.match(frame, /#999 is not in Assigned/, 'the panel discloses the miss');
1873
+ assert.match(frame, /▸ assigned issue 1/, 'the first row stays selected');
1874
+ });
1875
+
1876
+ test('plain /issues still opens on My issues and is handed no initial issue', async () => {
1877
+ const root = makeRepo({ tag: 'issues-one-plain' });
1878
+ const run = await capturedIssuesOptions(root);
1879
+ try {
1880
+ assert.equal('initialBucket' in run.options, false, 'a plain open passes no initial bucket');
1881
+ assert.equal('initialIssue' in run.options, false, 'and no initial issue');
1882
+ } finally {
1883
+ run.restore();
1884
+ }
1885
+ const { runner } = makeIssuesRunner();
1886
+ const { component } = await openIssues(root, { runner });
1887
+ const frame = clean(component.render(200).join('\n'));
1888
+ assert.match(frame, /▸ My issues/, 'a plain open still starts on My issues');
1889
+ assert.ok(!frame.includes('is not in'), 'and paints no initial-issue note');
1890
+ });
1891
+ });
1892
+
1893
+ // ---------------------------------------------------------------------------
1894
+ // S8 (the panel ODD's T4; the sidebar ODD's S9 consumer half): the rail's
1895
+ // process cache is what makes the first frame instant. The cache is filled by
1896
+ // the section's ONE combined read — through the published bridge — and the
1897
+ // panel READS it, keyed by the identity the panel itself just proved.
1898
+ //
1899
+ // The contract under test, through the public surface only:
1900
+ // - with an entry for the proved identity, the three scoped pages are seeded
1901
+ // from it, so the first frame paints rows instead of `loading…`;
1902
+ // - the seeded open STILL reads: the visible bucket's page read is issued at
1903
+ // mount and its answer replaces the seeded rows, and every other seeded tab
1904
+ // is read the first time it is activated — nothing is seeded forever;
1905
+ // - with NO entry the panel behaves exactly as before (the same notes, the same
1906
+ // three scoped reads and the same first frame);
1907
+ // - a bucket the cache reported TRUNCATED never renders an exact total (`N+`);
1908
+ // - the panel never writes the cache: a second open paints the same seeded rows.
1909
+ // ---------------------------------------------------------------------------
1910
+
1911
+ describe('/issues opens from the rail cache (S8/T4)', () => {
1912
+ const BRIDGE_SLOT = Symbol.for('gentle-shell-bridge/api/v1');
1913
+ // The identity both halves prove for the fixture checkout: one remote would
1914
+ // have no scope identity, and `makeRepo` has none at all, so gh's own answer
1915
+ // (`tools/fixtures/gh-repo-view.json`) is normalized host-qualified.
1916
+ const IDENTITY = 'github.com/jonasotoaguilar/herdr-gentle-shell';
1917
+
1918
+ function installBridge() {
1919
+ const registered = [];
1920
+ globalThis[BRIDGE_SLOT] = {
1921
+ schema: 'gentle-shell-bridge/api',
1922
+ version: 1,
1923
+ registerRows: () => {},
1924
+ registerSection: (section) => { registered.push(section); return () => {}; },
1925
+ createStore: () => ({}),
1926
+ requestRepaint: () => {},
1927
+ };
1928
+ return registered;
1929
+ }
1930
+
1931
+ // One issue node in the shape the rail's combined read asks for.
1932
+ function relatedNode(row) {
1933
+ const stamp = row.updatedAt || '2026-02-01T00:00:00Z';
1934
+ return {
1935
+ number: row.number,
1936
+ title: row.title,
1937
+ state: 'OPEN',
1938
+ stateReason: '',
1939
+ url: `https://example.test/issues/${row.number}`,
1940
+ createdAt: stamp,
1941
+ updatedAt: stamp,
1942
+ author: { login: 'me' },
1943
+ labels: { nodes: [] },
1944
+ // T10 (S9): the assignees the panel's first frame can show without
1945
+ // waiting for the detail read.
1946
+ assignees: { nodes: Array.isArray(row.assignees) ? row.assignees.map((login) => ({ login })) : [] },
1947
+ comments: { totalCount: 0 },
1948
+ reactionGroups: [],
1949
+ timelineItems: { nodes: [] },
1950
+ };
1951
+ }
1952
+
1953
+ // The rail's ONE combined answer: three aliased buckets, each with its exact
1954
+ // `issueCount`. `counts` overrides a count, which is how a bucket past the
1955
+ // cache's cap becomes `truncated`.
1956
+ function relatedAnswer({ mine = [], assigned = [], involved = [], counts = {} } = {}) {
1957
+ const bucket = (key, rows) => ({
1958
+ issueCount: Number.isInteger(counts[key]) ? counts[key] : rows.length,
1959
+ nodes: rows.map(relatedNode),
1960
+ });
1961
+ return {
1962
+ data: {
1963
+ mine: bucket('mine', mine),
1964
+ assigned: bucket('assigned', assigned),
1965
+ involved: bucket('involved', involved),
1966
+ },
1967
+ };
1968
+ }
1969
+
1970
+ function issueRow(number, title) {
1971
+ return {
1972
+ number,
1973
+ title,
1974
+ state: 'OPEN',
1975
+ createdAt: '2026-02-01T00:00:00Z',
1976
+ updatedAt: '2026-02-01T00:00:00Z',
1977
+ url: `https://example.test/issues/${number}`,
1978
+ };
1979
+ }
1980
+
1981
+ // The detail `gh issue view` answers with when a test holds it and then
1982
+ // releases it: one row's whole issue, with a body.
1983
+ function defaultIssueDetail(row) {
1984
+ return {
1985
+ number: row.number,
1986
+ title: row.title,
1987
+ state: 'OPEN',
1988
+ body: `body of issue ${row.number}`,
1989
+ author: { login: 'me' },
1990
+ labels: [],
1991
+ assignees: [],
1992
+ createdAt: '2026-02-01T00:00:00Z',
1993
+ updatedAt: '2026-02-01T00:00:00Z',
1994
+ url: `https://example.test/issues/${row.number}`,
1995
+ };
1996
+ }
1997
+
1998
+ // A runner over the shared fixture runner: the rail's combined read answers
1999
+ // from `related`, and the panel's page reads can be HELD so the seeded first
2000
+ // frame is observable before any answer lands.
2001
+ function cacheRunner({ related, holdPages = false, holdDetail = false, fixtureIssue = defaultIssueDetail }) {
2002
+ const base = makeIssuesRunner();
2003
+ const calls = [];
2004
+ const held = [];
2005
+ const heldDetails = [];
2006
+ const runner = async (bin, argv, opts) => {
2007
+ calls.push({ bin, argv: argv.slice(), env: { ...((opts && opts.env) || {}) }, cwd: opts ? opts.cwd : undefined });
2008
+ if (holdDetail && argv[0] === 'issue' && argv[1] === 'view') {
2009
+ const entry = { argv: argv.slice(), release: null };
2010
+ entry.answer = new Promise((resolve) => {
2011
+ entry.release = (row) => resolve({
2012
+ status: 0, stdout: JSON.stringify(fixtureIssue(row)), stderr: '', error: null,
2013
+ });
2014
+ });
2015
+ heldDetails.push(entry);
2016
+ return entry.answer;
2017
+ }
2018
+ if (argv[0] === 'api' && argv[1] === 'graphql') {
2019
+ const query = graphqlField(argv, 'query', '-f') || '';
2020
+ if (query.includes('mine: search(')) {
2021
+ return { status: 0, stdout: JSON.stringify(related), stderr: '', error: null };
2022
+ }
2023
+ if (holdPages && query.includes('type: ISSUE')) {
2024
+ const entry = { argv: argv.slice(), release: null };
2025
+ entry.answer = new Promise((resolve) => {
2026
+ entry.release = (rows) => resolve({
2027
+ status: 0, stdout: graphqlSearchPage(argv, rows), stderr: '', error: null,
2028
+ });
2029
+ });
2030
+ held.push(entry);
2031
+ return entry.answer;
2032
+ }
2033
+ }
2034
+ return base.runner(bin, argv, opts);
2035
+ };
2036
+ return { runner, calls, held, heldDetails };
2037
+ }
2038
+
2039
+ // Mount `/issues` over an already-loaded extension. The component is the real
2040
+ // view, against the real (injected) client.
2041
+ async function mountIssues(loaded, root, { args = '' } = {}) {
2042
+ loaded.mod.setIssuesTuiLoader(async () => stubTui);
2043
+ let factory = null;
2044
+ const { ctx, notes } = makeCtx({ cwd: root });
2045
+ ctx.ui.custom = async (captured) => { factory = captured; return null; };
2046
+ await loaded.commands.get('issues').handler(args, ctx);
2047
+ assert.ok(factory, 'the overlay opens');
2048
+ const { component } = openComponent(factory, makeHostTui(24));
2049
+ return { component, notes };
2050
+ }
2051
+
2052
+ // The rail fills the cache exactly as it does in a live session: the bridge is
2053
+ // published BEFORE the extension loads (that is when the section is
2054
+ // registered), `session_start` binds the checkout, and ONE drawn frame starts
2055
+ // the section's read.
2056
+ async function warmRail(root, related, options = {}) {
2057
+ const registered = installBridge();
2058
+ const loaded = await loadExtension();
2059
+ const gh = cacheRunner({
2060
+ related,
2061
+ holdPages: true,
2062
+ holdDetail: options.holdDetail === true,
2063
+ fixtureIssue: options.fixtureIssue || defaultIssueDetail,
2064
+ });
2065
+ ghIssues.setGhRunner(gh.runner);
2066
+ await fireSessionStart(loaded.hooks, gateCtx(root, []));
2067
+ assert.equal(registered.length, 1, 'the rail section is registered through the bridge');
2068
+ const section = registered[0];
2069
+ const ctx = { cwd: root, ui: { notify: () => {} } };
2070
+ const deadline = Date.now() + 4000;
2071
+ while (Date.now() < deadline) {
2072
+ const rows = section.lines(ctx);
2073
+ if (!(rows.length === 1 && rows[0].label === 'loading…')) break;
2074
+ await new Promise((resolve) => setTimeout(resolve, 10));
2075
+ }
2076
+ const labels = section.lines(ctx).map((row) => row.label);
2077
+ assert.ok(labels.length > 0 && labels[0] !== 'loading…',
2078
+ `the rail never filled the cache (saw ${JSON.stringify(labels)})`);
2079
+ return { loaded, gh, section, labels };
2080
+ }
2081
+
2082
+ test('a warmed cache paints the cached rows on the first frame and still reads', async () => {
2083
+ const root = makeRepo({ tag: 'issues-cache-warm' });
2084
+ const related = relatedAnswer({
2085
+ mine: [{ number: 12, title: 'Newer twelve', updatedAt: '2026-02-02T00:00:00Z' },
2086
+ { number: 11, title: 'Older eleven', updatedAt: '2026-02-01T00:00:00Z' }],
2087
+ assigned: [{ number: 21, title: 'Assigned twenty-one', updatedAt: '2026-02-03T00:00:00Z' }],
2088
+ involved: [{ number: 31, title: 'Involved thirty-one', updatedAt: '2026-02-04T00:00:00Z' }],
2089
+ });
2090
+ const warmed = await warmRail(root, related);
2091
+ const { loaded, gh } = warmed;
2092
+ assert.deepEqual(warmed.labels,
2093
+ ['#21 Assigned twenty-one', '#12 Newer twelve', '#11 Older eleven'],
2094
+ 'the rail draws the merged mine+assigned list it caches (S7/T8)');
2095
+ const railRead = gh.calls.filter((call) => call.argv[0] === 'api' && call.argv[1] === 'graphql')[0];
2096
+ assert.equal(railRead.env.GH_REPO, IDENTITY,
2097
+ 'the cache entry is keyed by the identity the rail proved for this checkout');
2098
+
2099
+ const { component } = await mountIssues(loaded, root);
2100
+ const first = clean(component.render(200).join('\n'));
2101
+ // The list row is the title alone (the number lives in the preview beside
2102
+ // it), and the seeded frames are what is on screen before any page read
2103
+ // answers — which is exactly what the cache is for.
2104
+ assert.match(first, /Newer twelve/, 'the cached row is painted before any page read answers');
2105
+ assert.match(first, /Older eleven/);
2106
+ assert.match(first, /▸ My issues \(2\)/, 'and the seeded bucket reports the rows it holds');
2107
+ assert.match(first, /Assigned \(1\)/);
2108
+ assert.match(first, /Involved \(1\)/);
2109
+
2110
+ // The seeded open STILL reads: the visible bucket (My issues) asks for its
2111
+ // own page at mount, so the seeded rows are replaced by a real answer.
2112
+ await waitFor(() => gh.held.length === 1, 'opening never started the visible bucket\'s own read');
2113
+ assert.deepEqual(searchQueries(gh.held), ['author:@me sort:updated-desc'],
2114
+ 'the held read is the visible bucket\'s scoped search');
2115
+
2116
+ gh.held[0].release([issueRow(40, 'Fresh forty')]);
2117
+ await waitFor(() => clean(component.render(200).join('\n')).includes('Fresh forty'));
2118
+ const afterAnswer = clean(component.render(200).join('\n'));
2119
+ assert.ok(!afterAnswer.includes('Newer twelve'),
2120
+ 'the real answer replaced the seeded row instead of sitting beside it');
2121
+
2122
+ // A seeded tab that mount did not read is read on its FIRST activation: the
2123
+ // seed is never the tab's only data.
2124
+ component.handleInput('tab');
2125
+ await waitFor(() => gh.held.length === 2, 'the activated seeded tab never read its own page');
2126
+ assert.deepEqual(searchQueries([gh.held[1]]), ['assignee:@me sort:updated-desc'],
2127
+ 'the Assigned tab reads its own bucket the first time it is entered');
2128
+
2129
+ // The panel never writes the cache: a second open still paints the SAME
2130
+ // seeded rows, not the answer the first open read — and it backs them with
2131
+ // its own read again.
2132
+ const second = await mountIssues(loaded, root);
2133
+ const secondFrame = clean(second.component.render(200).join('\n'));
2134
+ assert.match(secondFrame, /Newer twelve/, 'the cache still holds the rail\'s rows');
2135
+ await waitFor(() => gh.held.length === 3, 'the second open never read its own page');
2136
+ assert.deepEqual(searchQueries([gh.held[2]]), ['author:@me sort:updated-desc'],
2137
+ 'the second open reads the visible bucket again');
2138
+ });
2139
+
2140
+ // S7 (T8): an issue that is BOTH authored and assigned is one merged row, and
2141
+ // the assigned bucket wins the collision — so clicking it opens on Assigned,
2142
+ // exactly as the user asked ("assigned tiene prioridad").
2143
+ test('a number in both mine and assigned opens on Assigned', async () => {
2144
+ const root = makeRepo({ tag: 'issues-seed-both' });
2145
+ const related = relatedAnswer({
2146
+ mine: [{ number: 13, title: 'Both thirteen', updatedAt: '2026-02-03T00:00:00Z' }],
2147
+ assigned: [{ number: 13, title: 'Both thirteen', updatedAt: '2026-02-03T00:00:00Z' }],
2148
+ });
2149
+ const { loaded } = await warmRail(root, related);
2150
+ const { component } = await mountIssues(loaded, root, { args: '13' });
2151
+ const frame = clean(component.render(240).join('\n'));
2152
+ const bar = frame.split('\n').find((line) => line.includes('Assigned')) ?? '';
2153
+ assert.match(bar, /▸ Assigned/, 'the assigned bucket wins the collision');
2154
+ assert.ok(!frame.includes('is not in'), 'and the number is found, not reported missing');
2155
+ });
2156
+
2157
+ // S9 (T10) part 2: the rail's cached row is the panel's seed, so the FIRST
2158
+ // frame of a numbered open already carries the issue's identity — number,
2159
+ // title, labels, assignees, author — while the body is still on its way. The
2160
+ // defect was the opposite: a bare `loading…` pane for facts the rail knew.
2161
+ test('a numbered open paints the seeded facts on its first frame, with the body behind them', async () => {
2162
+ const root = makeRepo({ tag: 'issues-seed-detail' });
2163
+ const related = relatedAnswer({
2164
+ assigned: [{
2165
+ number: 22,
2166
+ title: 'Assigned twenty-two',
2167
+ updatedAt: '2026-02-02T00:00:00Z',
2168
+ assignees: ['ana'],
2169
+ }],
2170
+ });
2171
+ const { loaded, gh } = await warmRail(root, related, { holdDetail: true });
2172
+ const { component } = await mountIssues(loaded, root, { args: '22' });
2173
+ await waitFor(() => gh.heldDetails.length === 1, 'the detail read never started');
2174
+
2175
+ const first = clean(component.render(240).join('\n'));
2176
+ assert.match(first, /#22 Assigned twenty-two/, 'the number and title are on screen at once');
2177
+ assert.match(first, /\[open\]/, 'and the state the row already carried');
2178
+ assert.match(first, /assignees: ana/, 'so are the assignees the rail cached');
2179
+ assert.match(first, /\(no labels\)/, 'and the labels line, honest about a row that carried none');
2180
+ assert.match(first, /by me/, 'and the author');
2181
+ // S9: the frame opens ON the issue. The body marker still names the read,
2182
+ // but only under those facts — never a bare `loading…` pane.
2183
+ assert.match(first, /loading…/, 'the body read still names itself under the facts');
2184
+ assert.match(first, /#22 Assigned twenty-two[\s\S]*loading…/,
2185
+ 'the facts come first and the read is named below them — never a bare loading pane');
2186
+ assert.ok(!first.includes('body of issue 22'),
2187
+ 'the body is not invented from a row that never carried it');
2188
+
2189
+ // The body follows behind the facts, in the same pane.
2190
+ gh.heldDetails[0].release({ number: 22, title: 'Assigned twenty-two' });
2191
+ assert.ok(await waitFor(() => clean(component.render(240).join('\n')).includes('body of issue 22')),
2192
+ 'the detail read replaced the pending frame');
2193
+ });
2194
+
2195
+ // S9 (T10) part 3: the command picks the bucket from the cache — `assigned`
2196
+ // when the number is there, `mine` when it is only there. A number that is
2197
+ // only authored therefore opens on My issues, selected and loaded.
2198
+ test('a number that is only in mine opens on My issues', async () => {
2199
+ const root = makeRepo({ tag: 'issues-seed-mine' });
2200
+ const related = relatedAnswer({
2201
+ mine: [{ number: 61, title: 'Mine sixty-one', updatedAt: '2026-02-03T00:00:00Z' }],
2202
+ assigned: [{ number: 21, title: 'Assigned twenty-one', updatedAt: '2026-02-02T00:00:00Z' }],
2203
+ });
2204
+ const { loaded, gh } = await warmRail(root, related);
2205
+ assert.deepEqual(gh.held.length, 0, 'the rail read answers no page');
2206
+
2207
+ const { component } = await mountIssues(loaded, root, { args: '61' });
2208
+ const frame = clean(component.render(240).join('\n'));
2209
+ const bar = frame.split('\n').find((line) => line.includes('My issues')) ?? '';
2210
+ assert.match(bar, /▸ My issues/, 'the reader lands on My issues, which holds the number');
2211
+ assert.match(frame, /Mine sixty-one/, 'and its row is on screen');
2212
+ assert.ok(!frame.includes('is not in'), 'no miss is reported for a number the rail had');
2213
+ assert.ok(await waitFor(() => gh.held.length >= 1), 'the visible bucket still reads its own page');
2214
+ assert.deepEqual(searchQueries([gh.held[0]]), ['author:@me sort:updated-desc'],
2215
+ 'and the page it reads is My issues, the bucket the cache chose');
2216
+ });
2217
+
2218
+ test('with no cache the panel opens exactly as before', async () => {
2219
+ const root = makeRepo({ tag: 'issues-cache-empty' });
2220
+ const base = makeIssuesRunner();
2221
+ const calls = [];
2222
+ const held = [];
2223
+ // No bridge at all: no rail, no draw, so no entry for this identity.
2224
+ const loaded = await loadExtension();
2225
+ ghIssues.setGhRunner(async (bin, argv, opts) => {
2226
+ calls.push({ bin, argv: argv.slice(), cwd: opts ? opts.cwd : undefined });
2227
+ if (argv[0] === 'api' && argv[1] === 'graphql') {
2228
+ const query = graphqlField(argv, 'query', '-f') || '';
2229
+ if (query.includes('type: ISSUE')) {
2230
+ const entry = { argv: argv.slice(), release: null };
2231
+ entry.answer = new Promise((resolve) => {
2232
+ entry.release = (rows) => resolve({
2233
+ status: 0, stdout: graphqlSearchPage(argv, rows), stderr: '', error: null,
2234
+ });
2235
+ });
2236
+ held.push(entry);
2237
+ return entry.answer;
2238
+ }
2239
+ }
2240
+ return base.runner(bin, argv, opts);
2241
+ });
2242
+ const scratch = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-issues-gate-')));
2243
+ await fireSessionStart(loaded.hooks, gateCtx(scratch, []));
2244
+
2245
+ const { component, notes } = await mountIssues(loaded, root);
2246
+ await waitFor(() => held.length === 3, 'the open never read the three scoped buckets');
2247
+ assert.deepEqual(notes, [], 'an empty cache produces no note');
2248
+ assert.deepEqual(searchQueries(calls), [
2249
+ 'author:@me sort:updated-desc',
2250
+ 'assignee:@me sort:updated-desc',
2251
+ 'involves:@me -author:@me sort:updated-desc',
2252
+ ], 'the open reads the three scoped buckets exactly as before');
2253
+ assert.equal(connectionReads(calls).length, 0, 'and never the All connection');
2254
+ // `render(100)` produces the full-screen frame the host paints. Runs of box
2255
+ // drawing and padding are collapsed so the assertion states the frame's
2256
+ // CONTENT — the box, the search row, the loading line and the footer, with
2257
+ // today's blank body rows. A seeded frame would carry rows here instead.
2258
+ const frame = clean(component.render(100).join('\n'));
2259
+ const shape = frame.split('\n').map((line) => line
2260
+ .trimEnd()
2261
+ .replace(/─{2,}/g, '─…')
2262
+ .replace(/ {2,}/g, ' '));
2263
+ assert.deepEqual(shape, [
2264
+ '╭─ ◈ Issues ─…╮',
2265
+ '│ › Search │',
2266
+ '│ loading issues… │',
2267
+ ...new Array(19).fill('│ │'),
2268
+ // S11: no issue is under the cursor on the first frame, so the five
2269
+ // tokens that act on one are absent; every other hint stays.
2270
+ '│ ↑↓ move · ctrl+j/k scroll · ←→ bucket · t search · g all issues · esc close │',
2271
+ '╰─…╯',
2272
+ ], 'the first frame is today\'s loading frame, byte for byte');
2273
+ });
2274
+
2275
+ test('a truncated cached bucket never claims an exact total', async () => {
2276
+ const root = makeRepo({ tag: 'issues-cache-truncated' });
2277
+ const assigned = Array.from({ length: 105 }, (_, at) => ({
2278
+ number: 100 + at,
2279
+ title: `assigned ${100 + at}`,
2280
+ updatedAt: '2026-02-01T00:00:00Z',
2281
+ }));
2282
+ const related = relatedAnswer({
2283
+ mine: [{ number: 12, title: 'Mine twelve', updatedAt: '2026-02-02T00:00:00Z' }],
2284
+ assigned,
2285
+ counts: { assigned: 105 },
2286
+ });
2287
+ const { loaded } = await warmRail(root, related);
2288
+
2289
+ const { component } = await mountIssues(loaded, root);
2290
+ const first = clean(component.render(240).join('\n'));
2291
+ assert.match(first, /Assigned \(100\+\)/, 'a bucket the cache truncated is painted as inexact');
2292
+ assert.ok(!/Assigned \(100\)/.test(first), 'and never with an exact total it does not have');
2293
+ assert.ok(!/Assigned \(105\)/.test(first), 'nor with a count no surface read');
2294
+ });
2295
+
2296
+ // T17 (E17b): the rail refuses to trust an entry whose cached rows no longer
2297
+ // match the `issueCount` the response reported (its next sync is a full
2298
+ // re-read), so a total derived from those rows is exactly the number the rail
2299
+ // itself refuses to claim. The panel must paint it inexact too.
2300
+ // E18 (S4, verify round 5 blocker b): a seeded page is rows on screen before its
2301
+ // own read answers, and the verifier's exact scenario is `/issues 22` over a
2302
+ // seeded `Assigned` of `[21, 22]` with that page still in flight: the initial
2303
+ // selection landed on 21, and `c` then `ctrl+s` posted a comment on 21 while the
2304
+ // human asked for 22. A mutation on an issue nobody chose is the one thing the
2305
+ // identity work exists to prevent.
2306
+ //
2307
+ // The property: with `Assigned` seeded and `/issues <n>` where `n` is the second
2308
+ // seeded row, no mutation of any kind — comment, labels, assignees, close — can
2309
+ // reach any row other than `n`.
2310
+ test('a seeded Assigned page never lends a mutation to another issue (E18)', async () => {
2311
+ const root = makeRepo({ tag: 'issues-seed-mutation' });
2312
+ const related = relatedAnswer({
2313
+ assigned: [
2314
+ { number: 21, title: 'Assigned twenty-one', updatedAt: '2026-02-03T00:00:00Z' },
2315
+ { number: 22, title: 'Assigned twenty-two', updatedAt: '2026-02-02T00:00:00Z' },
2316
+ ],
2317
+ });
2318
+ const warmed = await warmRail(root, related);
2319
+ const { loaded, gh } = warmed;
2320
+ const { component } = await mountIssues(loaded, root, { args: '22' });
2321
+ const frame = () => clean(component.render(240).join('\n'));
2322
+ const writes = () => gh.calls.filter((call) => call.argv[0] === 'issue'
2323
+ && ['comment', 'edit', 'close'].includes(call.argv[1]));
2324
+
2325
+ assert.ok(await waitFor(() => gh.held.length >= 1), 'the numbered open issued its own Assigned read');
2326
+ assert.deepEqual(searchQueries([gh.held[0]]), ['assignee:@me sort:updated-desc'],
2327
+ 'the held read is the bucket the panel was opened on');
2328
+
2329
+ // The verifier's exact scenario: `c`, then `ctrl+s`, in that window.
2330
+ component.handleInput('c');
2331
+ for (const ch of 'looks right') component.handleInput(ch);
2332
+ component.handleInput('ctrl+s');
2333
+ assert.ok(await waitFor(() => writes().length > 0), 'the comment reached gh');
2334
+ assert.deepEqual(writes().map((call) => call.argv.slice(0, 3)), [['issue', 'comment', '22']],
2335
+ 'the comment names the issue the human asked for, never the seeded #21');
2336
+
2337
+ // The page's own answer lands. The correct issue is still the only one any
2338
+ // mutation can reach.
2339
+ gh.held[0].release([
2340
+ issueRow(21, 'Assigned twenty-one'),
2341
+ issueRow(22, 'Assigned twenty-two'),
2342
+ ]);
2343
+ assert.ok(await waitFor(() => frame().includes('l labels')),
2344
+ 'the answer is on screen and the detail confirmed the role');
2345
+
2346
+ component.handleInput('l');
2347
+ await tick();
2348
+ component.handleInput('down');
2349
+ component.handleInput('space');
2350
+ component.handleInput('ctrl+s');
2351
+ assert.ok(await waitFor(() => writes().some((call) => call.argv[1] === 'edit'
2352
+ && call.argv.includes('--add-label'))), 'the label save reached gh');
2353
+ assert.ok(await waitFor(() => component.state.mode === 'list'), 'the label save closed the editor');
2354
+ // A successful write re-reads the detail, and the editor keys are only
2355
+ // offered once that answer confirms the repository role again.
2356
+ const roleBack = await waitFor(() => frame().includes('l labels'));
2357
+ if (!roleBack) console.log('DEBUG2>>>\n' + frame().split('\n').filter((line) => !line.trim().startsWith('│') || line.includes('Assigned twenty') || line.includes('·')).join('\n') + '\n<<<DEBUG2');
2358
+ assert.ok(roleBack, 'the refreshed detail confirms the role');
2359
+
2360
+ component.handleInput('a');
2361
+ // S10: the editor's title is its name alone; its keys are the footer row.
2362
+ assert.ok(await waitFor(() => frame().includes('Assignees') && frame().includes('space toggle')),
2363
+ 'the assignee editor opened');
2364
+ assert.ok(await waitFor(() => !frame().includes('loading assignees')), 'the assignable users answered');
2365
+ component.handleInput('space');
2366
+ component.handleInput('ctrl+s');
2367
+ const assigneeWrite = (call) => call.argv[1] === 'edit'
2368
+ && (call.argv.includes('--add-assignee') || call.argv.includes('--remove-assignee'));
2369
+ assert.ok(await waitFor(() => writes().some(assigneeWrite)), 'the assignee save reached gh');
2370
+ assert.ok(await waitFor(() => component.state.mode === 'list'), 'the assignee save closed the editor');
2371
+ assert.ok(await waitFor(() => frame().includes('x close')), 'the refreshed detail confirms the role again');
2372
+
2373
+ component.handleInput('x');
2374
+ component.handleInput('enter');
2375
+ assert.ok(await waitFor(() => writes().some((call) => call.argv[1] === 'close')), 'the close reached gh');
2376
+
2377
+ assert.deepEqual(writes().map((call) => call.argv[2]), ['22', '22', '22', '22'],
2378
+ 'every mutation this panel ran named #22, the issue the human asked for');
2379
+ assert.equal(writes().some((call) => call.argv[2] === '21'), false,
2380
+ 'and not one of them ever named the seeded #21');
2381
+ });
2382
+
2383
+ test('an inconsistent cached entry never claims an exact total', async () => {
2384
+ const root = makeRepo({ tag: 'issues-cache-inconsistent' });
2385
+ // ONE read whose assigned `issueCount` (2) outruns the nodes it returned
2386
+ // (1): the count invariant breaks on the very first apply, which is exactly
2387
+ // the state a departed issue leaves behind between two rail reads.
2388
+ const related = relatedAnswer({
2389
+ mine: [{ number: 12, title: 'Mine twelve', updatedAt: '2026-02-02T00:00:00Z' }],
2390
+ assigned: [{ number: 21, title: 'Assigned twenty-one', updatedAt: '2026-02-03T00:00:00Z' }],
2391
+ counts: { assigned: 2 },
2392
+ });
2393
+ const { loaded } = await warmRail(root, related);
2394
+
2395
+ const { component } = await mountIssues(loaded, root);
2396
+ const first = clean(component.render(240).join('\n'));
2397
+ assert.match(first, /Assigned \(1\+\)/, 'an entry the rail calls inconsistent is seeded inexact');
2398
+ assert.ok(!/Assigned \(1\)(?!\+)/.test(first), 'and never with the exact total it cannot prove');
2399
+ });
2400
+ });
2401
+
2402
+ // ---------------------------------------------------------------------------
2403
+ // S21 (T17), the human's own words: «me la asigne a mi o me quite la
2404
+ // asignacion … no se refresca altiro los tabs … actualmente eso demora o no
2405
+ // refrezca de hecho hasta que lo cierro y abro panel». This drives the REAL
2406
+ // panel over the injected `gh` client, and the REAL rail section over the
2407
+ // published bridge, so every assertion below is a read or a write that reached
2408
+ // `gh`:
2409
+ // - a save that changed the VIEWER's own assignment drops the rail's cached
2410
+ // entry for this repository, so the rail's next read is the FULL one (a delta
2411
+ // merges by issue number and can never express a removal) and it starts now,
2412
+ // not on the 20 s floor;
2413
+ // - the panel reads the `assigned` bucket again and its count and rows follow;
2414
+ // - a write that did not land invalidates nothing: no rail read, no page read,
2415
+ // the pre-write rows and count stay, and the draft stays open with the error.
2416
+ // ---------------------------------------------------------------------------
2417
+ describe('/issues reflects a self-assignment on the panel and the rail (S21/T17)', () => {
2418
+ const BRIDGE_SLOT = Symbol.for('gentle-shell-bridge/api/v1');
2419
+ const VIEWER = 'jonasotoaguilar';
2420
+
2421
+ // The one repository state both surfaces read. `assignees` is what makes an
2422
+ // issue `assigned` to the viewer; `mine` is authorship, which an assignment
2423
+ // never changes.
2424
+ function repoState() {
2425
+ return {
2426
+ issues: new Map([
2427
+ [12, { number: 12, title: 'Mine twelve', mine: true, assignees: [], updatedAt: '2026-02-02T00:00:00Z' }],
2428
+ [21, { number: 21, title: 'Assigned twenty-one', mine: false, assignees: [VIEWER], updatedAt: '2026-02-03T00:00:00Z' }],
2429
+ ]),
2430
+ };
2431
+ }
2432
+
2433
+ const authored = (state) => [...state.issues.values()].filter((row) => row.mine);
2434
+ const assignedToViewer = (state) => [...state.issues.values()].filter((row) => row.assignees.includes(VIEWER));
2435
+
2436
+ function searchRow(row) {
2437
+ return {
2438
+ number: row.number,
2439
+ title: row.title,
2440
+ state: 'OPEN',
2441
+ url: `https://example.test/issues/${row.number}`,
2442
+ createdAt: row.updatedAt,
2443
+ updatedAt: row.updatedAt,
2444
+ author: { login: row.mine ? VIEWER : 'octocat' },
2445
+ };
2446
+ }
2447
+
2448
+ function relatedNode(row) {
2449
+ return {
2450
+ ...searchRow(row),
2451
+ labels: { nodes: [] },
2452
+ assignees: { nodes: row.assignees.map((login) => ({ login })) },
2453
+ comments: { totalCount: 0 },
2454
+ reactionGroups: [],
2455
+ timelineItems: { nodes: [] },
2456
+ };
2457
+ }
2458
+
2459
+ function relatedAnswer(state) {
2460
+ const bucket = (rows) => ({ issueCount: rows.length, nodes: rows.map(relatedNode) });
2461
+ return { data: { mine: bucket(authored(state)), assigned: bucket(assignedToViewer(state)), involved: bucket([]) } };
2462
+ }
2463
+
2464
+ function assignmentRunner(state, failure) {
2465
+ const calls = [];
2466
+ const ok = (stdout) => ({ status: 0, stdout, stderr: '', error: null });
2467
+ const runner = async (bin, argv, opts) => {
2468
+ calls.push({ bin, argv: argv.slice(), cwd: opts ? opts.cwd : undefined });
2469
+ if (argv[0] === 'api' && argv[1] === 'graphql') {
2470
+ const query = graphqlField(argv, 'query', '-f') || '';
2471
+ const search = graphqlField(argv, 'search');
2472
+ if (query.includes('mine: search(')) return ok(JSON.stringify(relatedAnswer(state)));
2473
+ if (search !== null) {
2474
+ if (search.includes('assignee:@me')) return ok(graphqlSearchPage(argv, assignedToViewer(state).map(searchRow)));
2475
+ if (search.includes('involves:@me')) return ok(graphqlSearchPage(argv, []));
2476
+ return ok(graphqlSearchPage(argv, authored(state).map(searchRow)));
2477
+ }
2478
+ if (query.includes('assignableUsers')) {
2479
+ return ok(JSON.stringify({ data: { repository: { assignableUsers: {
2480
+ nodes: [{ login: VIEWER, name: 'Jonathan Soto' }, { login: 'octocat', name: 'Octo Cat' }],
2481
+ pageInfo: { hasNextPage: false, endCursor: null },
2482
+ } } } }));
2483
+ }
2484
+ // The assignee mutation's own permission read: it names the viewer too,
2485
+ // which is what makes the save's answer able to say "this one was mine".
2486
+ if (query.includes('viewer {')) {
2487
+ return ok(JSON.stringify({ data: { repository: { viewerPermission: 'WRITE' }, viewer: { login: VIEWER } } }));
2488
+ }
2489
+ if (query.includes('projectItems')) {
2490
+ return ok(JSON.stringify({ data: { repository: { issue: { projectItems: { nodes: [], pageInfo: { hasNextPage: false } } } } } }));
2491
+ }
2492
+ if (query.includes('viewerPermission')) {
2493
+ const number = Number(graphqlField(argv, 'number', '-F'));
2494
+ const row = state.issues.get(number);
2495
+ return ok(JSON.stringify({ data: { repository: {
2496
+ viewerPermission: 'WRITE',
2497
+ issue: {
2498
+ assignees: { nodes: (row ? row.assignees : []).map((login) => ({ login })), pageInfo: { hasNextPage: false } },
2499
+ closedByPullRequestsReferences: { nodes: [], pageInfo: { hasNextPage: false } },
2500
+ },
2501
+ } } }));
2502
+ }
2503
+ return ok(JSON.stringify({ data: {} }));
2504
+ }
2505
+ if (argv[0] === 'api') return ok(fixture('gh-api-user.json'));
2506
+ if (argv[0] === 'repo') return ok(fixture('gh-repo-view.json'));
2507
+ if (argv[0] === 'issue' && argv[1] === 'view' && argv.includes('--json')) {
2508
+ const number = Number(argv[2]);
2509
+ const row = state.issues.get(number);
2510
+ return ok(JSON.stringify({
2511
+ number,
2512
+ title: row.title,
2513
+ state: 'OPEN',
2514
+ body: `body of issue ${number}`,
2515
+ author: { login: row.mine ? VIEWER : 'octocat' },
2516
+ labels: [],
2517
+ createdAt: row.updatedAt,
2518
+ updatedAt: row.updatedAt,
2519
+ url: `https://example.test/issues/${number}`,
2520
+ comments: [],
2521
+ }));
2522
+ }
2523
+ if (argv[0] === 'issue' && argv[1] === 'edit') {
2524
+ if (failure && failure.on === true) return { status: 1, stdout: '', stderr: 'Forbidden', error: null };
2525
+ const row = state.issues.get(Number(argv[2]));
2526
+ for (let index = 3; index < argv.length; index += 1) {
2527
+ const flag = argv[index];
2528
+ const login = argv[index + 1];
2529
+ if (flag === '--add-assignee' && row) row.assignees = [...new Set([...row.assignees, login])];
2530
+ if (flag === '--remove-assignee' && row) row.assignees = row.assignees.filter((name) => name !== login);
2531
+ }
2532
+ return ok('');
2533
+ }
2534
+ if (argv[0] === 'label' && argv[1] === 'list') return ok(fixture('gh-label-list.json'));
2535
+ return ok('');
2536
+ };
2537
+ return { runner, calls };
2538
+ }
2539
+
2540
+ // The rail fills its cache exactly as a live session does: the bridge is
2541
+ // published BEFORE the extension loads, `session_start` binds the checkout,
2542
+ // and ONE drawn frame starts the read.
2543
+ async function warmRail(root, state, options = {}) {
2544
+ const registered = [];
2545
+ globalThis[BRIDGE_SLOT] = {
2546
+ schema: 'gentle-shell-bridge/api',
2547
+ version: 1,
2548
+ registerRows: () => {},
2549
+ registerSection: (section) => { registered.push(section); return () => {}; },
2550
+ createStore: () => ({}),
2551
+ requestRepaint: () => {},
2552
+ };
2553
+ const loaded = await loadExtension();
2554
+ const gh = assignmentRunner(state, options.failure);
2555
+ ghIssues.setGhRunner(gh.runner);
2556
+ await fireSessionStart(loaded.hooks, gateCtx(root, []));
2557
+ assert.equal(registered.length, 1, 'the rail section is registered through the bridge');
2558
+ const section = registered[0];
2559
+ const ctx = { cwd: root, ui: { notify: () => {} } };
2560
+ const deadline = Date.now() + 4000;
2561
+ while (Date.now() < deadline) {
2562
+ const rows = section.lines(ctx);
2563
+ if (!(rows.length === 1 && rows[0].label === 'loading…')) break;
2564
+ await new Promise((resolve) => setTimeout(resolve, 10));
2565
+ }
2566
+ return { loaded, gh, section, ctx };
2567
+ }
2568
+
2569
+ async function mountPanel(loaded, root) {
2570
+ loaded.mod.setIssuesTuiLoader(async () => stubTui);
2571
+ let factory = null;
2572
+ const { ctx } = makeCtx({ cwd: root });
2573
+ ctx.ui.custom = async (captured) => { factory = captured; return null; };
2574
+ await loaded.commands.get('issues').handler('', ctx);
2575
+ assert.ok(factory, 'the overlay opens');
2576
+ const host = makeHostTui(24);
2577
+ const { component } = openComponent(factory, host.tui);
2578
+ return { component, host };
2579
+ }
2580
+
2581
+ const isRailRead = (call) => call.argv[0] === 'api' && call.argv[1] === 'graphql'
2582
+ && (graphqlField(call.argv, 'query', '-f') || '').includes('mine: search(');
2583
+ const railReads = (gh) => gh.calls.filter(isRailRead);
2584
+ const railQuery = (call) => graphqlField(call.argv, 'query', '-f');
2585
+ const assigneeWrites = (gh) => gh.calls.filter((call) => call.argv[0] === 'issue'
2586
+ && call.argv[1] === 'edit'
2587
+ && (call.argv.includes('--add-assignee') || call.argv.includes('--remove-assignee')));
2588
+ const frameOf = (component) => clean(component.render(240).join('\n'));
2589
+
2590
+ test('unassigning yourself repaints the tab, refetches the full rail entry and counts one less', async () => {
2591
+ const root = makeRepo({ tag: 'issues-self-assign' });
2592
+ const state = repoState();
2593
+ const { loaded, gh, section, ctx } = await warmRail(root, state);
2594
+ assert.equal(section.meta(ctx), '2 issues', 'the rail starts with both rows');
2595
+
2596
+ const { component } = await mountPanel(loaded, root);
2597
+ // `Assigned` is where the viewer's own row lives; the tab reads it on entry.
2598
+ component.handleInput('tab');
2599
+ assert.ok(await waitFor(() => frameOf(component).includes('Assigned twenty-one')),
2600
+ 'the Assigned tab paints the viewer\'s row before the write');
2601
+
2602
+ // The editor key requires the repository role the DETAIL confirms, so the
2603
+ // press waits for that answer exactly like the panel's other editor tests.
2604
+ assert.ok(await waitFor(() => frameOf(component).includes('a assign')), 'the detail confirmed the role');
2605
+ component.handleInput('a');
2606
+ assert.ok(await waitFor(() => frameOf(component).includes('Assignees') && frameOf(component).includes('space toggle')),
2607
+ 'the assignee editor opened');
2608
+ assert.ok(await waitFor(() => !frameOf(component).includes('loading assignees')),
2609
+ 'the assignable users answered');
2610
+ component.handleInput('space');
2611
+ component.handleInput('ctrl+s');
2612
+ assert.ok(await waitFor(() => assigneeWrites(gh).length === 1), 'the assignee save reached gh');
2613
+ assert.deepEqual(assigneeWrites(gh)[0].argv,
2614
+ ['issue', 'edit', '21', '--remove-assignee', VIEWER],
2615
+ 'the write names the viewer exactly as the editor toggled it');
2616
+
2617
+ // The panel: the Assigned bucket was read again and its count follows.
2618
+ assert.ok(await waitFor(() => frameOf(component).includes('Assigned (0)')),
2619
+ 'the Assigned tab count follows the removal without reopening the panel');
2620
+ assert.ok(!frameOf(component).includes('Assigned twenty-one'), 'and the row is gone');
2621
+ const assignedReads = gh.calls
2622
+ .filter((call) => call.argv[0] === 'api' && call.argv[1] === 'graphql')
2623
+ .map((call) => graphqlField(call.argv, 'search'))
2624
+ .filter((value) => value !== null && value.includes('assignee:@me'));
2625
+ assert.ok(assignedReads.length >= 2, 'the write invalidated the Assigned page, so it was read again');
2626
+
2627
+ // The rail: one read started by the write itself, and it is the FULL one —
2628
+ // a delta could only merge by issue number and could never drop the row.
2629
+ assert.ok(await waitFor(() => railReads(gh).length >= 2), 'the write started a rail read of its own');
2630
+ assert.match(railQuery(railReads(gh)[1]), /first: 100/,
2631
+ 'the dropped entry makes the next rail read the full size, so a removal can land');
2632
+ assert.ok(await waitFor(() => section.meta(ctx) === '1 issues'), 'the rail count follows the removal');
2633
+ assert.deepEqual(section.lines(ctx).map((row) => row.label), ['#12 Mine twelve'],
2634
+ 'and the merged rows are the ones the full read answered');
2635
+ });
2636
+
2637
+ test('a rejected assignee save repaints nothing and keeps the row and the count', async () => {
2638
+ const root = makeRepo({ tag: 'issues-self-assign-fail' });
2639
+ const state = repoState();
2640
+ // GitHub refuses the write: the answer is the only source of truth here, so
2641
+ // a rejection that reached the surface must leave every row and count alone.
2642
+ const failure = { on: false };
2643
+ const { loaded, gh, section, ctx } = await warmRail(root, state, { failure });
2644
+ const { component } = await mountPanel(loaded, root);
2645
+ component.handleInput('tab');
2646
+ assert.ok(await waitFor(() => frameOf(component).includes('Assigned twenty-one')), 'the row is on screen');
2647
+ assert.ok(await waitFor(() => frameOf(component).includes('a assign')), 'the detail confirmed the role');
2648
+ component.handleInput('a');
2649
+ assert.ok(await waitFor(() => !frameOf(component).includes('loading assignees')), 'the users answered');
2650
+ component.handleInput('space');
2651
+ const before = railReads(gh).length;
2652
+ failure.on = true;
2653
+ component.handleInput('ctrl+s');
2654
+ assert.ok(await waitFor(() => /Forbidden/.test(frameOf(component))), 'the rejection is visible');
2655
+ await tick();
2656
+ await tick();
2657
+ assert.equal(component.state.mode, 'assignees', 'the editor keeps the draft');
2658
+ assert.equal(railReads(gh).length, before, 'a failed write invalidates nothing, so no rail read starts');
2659
+ assert.equal(section.meta(ctx), '2 issues', 'the rail keeps the pre-write count');
2660
+ assert.match(frameOf(component), /Assigned \(1\)/, 'and the panel keeps the pre-write count');
2661
+ assert.ok(frameOf(component).includes('Assigned twenty-one'), 'the row never left');
2662
+ });
2663
+ });