pi-odd-worktree 3.9.1 → 3.10.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 (41) hide show
  1. package/README.md +63 -40
  2. package/extensions/odd-worktree-tools.ts +859 -12
  3. package/lib/gh-issues.js +65 -10
  4. package/lib/gh-prs.js +2011 -0
  5. package/lib/issue-preview.js +70 -4
  6. package/lib/issues-cache-store.js +4 -1
  7. package/lib/issues-section.js +346 -23
  8. package/lib/issues-view.js +116 -5
  9. package/lib/modules.js +5 -0
  10. package/lib/pr-preview.js +353 -0
  11. package/lib/prs-rail-store.js +317 -0
  12. package/lib/prs-view.js +2896 -0
  13. package/package.json +1 -1
  14. package/tools/files-bridge.test.js +2 -2
  15. package/tools/files-command.test.js +1 -1
  16. package/tools/fixtures/gh-pr-connection-page.json +84 -0
  17. package/tools/fixtures/gh-pr-metadata.json +29 -0
  18. package/tools/fixtures/gh-pr-rail.json +61 -0
  19. package/tools/fixtures/gh-pr-search-page.json +82 -0
  20. package/tools/fixtures/gh-pr-view.json +159 -0
  21. package/tools/gh-issues.test.js +4 -2
  22. package/tools/gh-prs.test.js +1828 -0
  23. package/tools/issue-preview.test.js +119 -0
  24. package/tools/issues-cache-store.test.js +2 -2
  25. package/tools/issues-command.test.js +10 -3
  26. package/tools/issues-open-guard.test.js +15 -0
  27. package/tools/issues-section.test.js +618 -9
  28. package/tools/issues-view.test.js +297 -0
  29. package/tools/modules-wiring.test.js +5 -0
  30. package/tools/package-surface.test.js +18 -4
  31. package/tools/pr-preview.test.js +281 -0
  32. package/tools/prs-command.test.js +1280 -0
  33. package/tools/prs-rail-store.test.js +343 -0
  34. package/tools/prs-t10-safety.test.js +326 -0
  35. package/tools/prs-t12-safety.test.js +348 -0
  36. package/tools/prs-t13-independent.test.js +378 -0
  37. package/tools/prs-t14-safety.test.js +340 -0
  38. package/tools/prs-t15-independent.test.js +259 -0
  39. package/tools/prs-t18-safety.test.js +217 -0
  40. package/tools/prs-t7-safety.test.js +127 -0
  41. package/tools/prs-view.test.js +1462 -0
@@ -0,0 +1,1280 @@
1
+ 'use strict';
2
+ // T5 (S1, S4-S7): the `/prs` wiring in extensions/odd-worktree-tools.ts, driven
3
+ // through the registered command, the one rail section and the injected `gh`
4
+ // runner.
5
+ //
6
+ // Contract under test, through the public surface only (registration, the
7
+ // notified text, the overlay options, the argv reaching `gh`, the bytes on the
8
+ // chat input, the message the host receives):
9
+ // - `/prs` is registered behind the SAME `gh` gate as `/issues`: absent `gh`
10
+ // registers neither, and an unauthenticated `gh` refuses the open with the
11
+ // `prs:` sentence and mounts nothing;
12
+ // - a plain `/prs` mounts the full-screen overlay on the three scoped searches
13
+ // (`author:@me`, `review-requested:@me`, `involves:@me`) with `all` lazy and
14
+ // read from the repository connection;
15
+ // - every read, the detail (with the authoritative metadata) and the `o` opener
16
+ // bind the identity the panel pinned: `gh pr view <n> --web -R <pinned>`;
17
+ // - `enter` in BOTH panels inserts `ISSUE #63` / `PR #87` into the chat input
18
+ // through `ctx.ui.pasteToEditor` and closes the panel, sending nothing;
19
+ // - a click on one linked number closes the panel it was clicked in and opens
20
+ // the other one through the single-flight dispatch path (`/issues N` /
21
+ // `/prs N`), so no panel stacks on another;
22
+ // - the one GITHUB section reads the pull requests too, paints `N issues · M pr`,
23
+ // routes a row whose issue links a PR to the PR panel with `review` winning
24
+ // over `mine`, keeps the old `/issues N` call for every other row, persists its
25
+ // count through lib/prs-rail-store.js from the async loader alone, and a
26
+ // mutation made in the panel invalidates that count;
27
+ // - the session start preload is DISPATCHED and never awaited, and only for a
28
+ // section the host was actually drawing.
29
+ //
30
+ // Every child is injected and every temp tree lives under os.tmpdir().
31
+
32
+ const { test, describe, after, afterEach, beforeEach } = require('node:test');
33
+ const assert = require('node:assert/strict');
34
+ const fs = require('node:fs');
35
+ const os = require('node:os');
36
+ const path = require('node:path');
37
+ const { execFileSync } = require('node:child_process');
38
+ const { pathToFileURL } = require('node:url');
39
+
40
+ const { LIB_DIR, stubbedSource, withGhPath } = require('./fixtures/load-extension.js');
41
+
42
+ const BRIDGE_SLOT = Symbol.for('gentle-shell-bridge/api/v1');
43
+ const realSetTimeout = setTimeout;
44
+
45
+ const stubTui = {
46
+ visibleWidth: (text) => [...String(text)].length,
47
+ truncateToWidth: (text, width) => {
48
+ const chars = [...String(text)];
49
+ return chars.length > width ? chars.slice(0, Math.max(0, width - 1)).join('') + '…' : String(text);
50
+ },
51
+ matchesKey: (key, name) => key === name,
52
+ isKeyRelease: (key) => key === 'release',
53
+ };
54
+
55
+ let ghIssues = null;
56
+ let restores = [];
57
+ const roots = [];
58
+
59
+ after(() => {
60
+ for (const dir of roots) {
61
+ try { fs.rmSync(dir, { recursive: true, force: true }); } catch {}
62
+ }
63
+ });
64
+
65
+ function track(dir) {
66
+ roots.push(dir);
67
+ return dir;
68
+ }
69
+
70
+ afterEach(() => {
71
+ delete globalThis[BRIDGE_SLOT];
72
+ if (ghIssues) {
73
+ ghIssues.setGhRunner(null);
74
+ ghIssues.setGitRunner(null);
75
+ if (typeof ghIssues.clearCachedGhStatus === 'function') ghIssues.clearCachedGhStatus();
76
+ }
77
+ for (const restore of restores) {
78
+ try { restore(); } catch {}
79
+ }
80
+ restores = [];
81
+ });
82
+
83
+ beforeEach(() => {
84
+ process.env.XDG_CACHE_HOME = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-prs-cache-')));
85
+ });
86
+
87
+ function git(cwd, args) {
88
+ return execFileSync('git', args, {
89
+ cwd,
90
+ encoding: 'utf8',
91
+ env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null' },
92
+ });
93
+ }
94
+
95
+ // A checkout with TWO remotes: its identity comes from its own git configuration,
96
+ // so the pin is observable without a `gh repo view` call.
97
+ function makeCheckout() {
98
+ const dir = track(fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-prs-'))));
99
+ git(dir, ['init']);
100
+ git(dir, ['config', 'user.email', 'test@example.com']);
101
+ git(dir, ['config', 'user.name', 'Test']);
102
+ git(dir, ['commit', '--allow-empty', '-m', 'init']);
103
+ git(dir, ['remote', 'add', 'origin', 'git@github.com:myfork/project.git']);
104
+ git(dir, ['remote', 'add', 'upstream', 'git@github.com:original/project.git']);
105
+ return dir;
106
+ }
107
+
108
+ async function loadExtension(pi, options = {}) {
109
+ return withGhPath(options && options.gh === false ? 'absent' : 'present', async () => {
110
+ const dir = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-prs-ext-')));
111
+ const copy = path.join(dir, 'odd-worktree-tools.mjs');
112
+ fs.writeFileSync(copy, stubbedSource());
113
+ const commands = new Map();
114
+ const hooks = [];
115
+ const api = {
116
+ registerTool: () => {},
117
+ registerCommand: (name, definition) => { commands.set(name, definition); },
118
+ registerMessageRenderer: () => {},
119
+ registerEntryRenderer: () => {},
120
+ appendEntry: () => {},
121
+ on: (event, handler) => { hooks.push([event, handler]); return () => {}; },
122
+ ...pi,
123
+ };
124
+ process.env.GENTLE_WORKTREE_LIB_DIR = LIB_DIR;
125
+ const mod = await import(pathToFileURL(copy).href);
126
+ mod.default(api);
127
+ return { commands, hooks, api, mod };
128
+ });
129
+ }
130
+
131
+ // `onRepaint` observes the bridge's own repaint request: S4 (D9) needs to see
132
+ // that a settled rail read ASKS for the frame the new count is painted by.
133
+ function installBridge(onRepaint = null) {
134
+ const registered = [];
135
+ globalThis[BRIDGE_SLOT] = {
136
+ schema: 'gentle-shell-bridge/api',
137
+ version: 1,
138
+ registerRows: () => {},
139
+ registerSection: (section) => { registered.push(section); return () => {}; },
140
+ registerToolDesign: () => () => {},
141
+ createStore: () => ({ get: () => undefined, set: () => {}, delete: () => {} }),
142
+ requestRepaint: () => {
143
+ if (typeof onRepaint === 'function') onRepaint();
144
+ },
145
+ };
146
+ return { registered };
147
+ }
148
+
149
+ function sessionStartHandlers(hooks) {
150
+ return hooks.filter(([event]) => event === 'session_start').map(([, handler]) => handler);
151
+ }
152
+
153
+ async function fireSessionStart(hooks, ctx) {
154
+ for (const handler of sessionStartHandlers(hooks)) {
155
+ const out = handler({}, ctx);
156
+ if (out && typeof out.then === 'function') await out;
157
+ }
158
+ }
159
+
160
+ function fireSessionStartSync(hooks, ctx) {
161
+ const returned = [];
162
+ for (const handler of sessionStartHandlers(hooks)) returned.push(handler({}, ctx));
163
+ return returned;
164
+ }
165
+
166
+ async function fireHook(hooks, event, payload, ctx) {
167
+ for (const handler of hooks.filter(([name]) => name === event).map(([, fn]) => fn)) {
168
+ const out = handler(payload, ctx);
169
+ if (out && typeof out.then === 'function') await out;
170
+ }
171
+ }
172
+
173
+ function ok(stdout) {
174
+ return { status: 0, stdout, stderr: '', error: null };
175
+ }
176
+
177
+ function failed(stderr = 'boom') {
178
+ return { status: 1, stdout: '', stderr, error: null };
179
+ }
180
+
181
+ function gqlField(argv, name, flag = '-F') {
182
+ for (let index = 0; index < argv.length - 1; index += 1) {
183
+ if (argv[index] === flag && argv[index + 1].startsWith(`${name}=`)) {
184
+ return argv[index + 1].slice(name.length + 1);
185
+ }
186
+ }
187
+ return null;
188
+ }
189
+
190
+ function gqlQuery(argv) {
191
+ return gqlField(argv, 'query', '-f') || '';
192
+ }
193
+
194
+ function prNode(row) {
195
+ return {
196
+ number: row.number,
197
+ title: row.title || `Pull ${row.number}`,
198
+ state: 'OPEN',
199
+ isDraft: false,
200
+ url: `https://github.com/myfork/project/pull/${row.number}`,
201
+ createdAt: '2024-01-01T00:00:00Z',
202
+ updatedAt: '2024-01-02T00:00:00Z',
203
+ author: { login: 'me' },
204
+ labels: { nodes: [] },
205
+ assignees: { nodes: [] },
206
+ comments: { totalCount: 0 },
207
+ reactionGroups: [],
208
+ reviewDecision: '',
209
+ };
210
+ }
211
+
212
+ function issueNode(row) {
213
+ return {
214
+ number: row.number,
215
+ title: row.title || `Issue ${row.number}`,
216
+ state: 'OPEN',
217
+ stateReason: '',
218
+ url: `https://github.com/myfork/project/issues/${row.number}`,
219
+ createdAt: '2024-01-01T00:00:00Z',
220
+ updatedAt: '2024-01-02T00:00:00Z',
221
+ author: { login: 'me' },
222
+ labels: { nodes: [] },
223
+ comments: { totalCount: 0 },
224
+ reactionGroups: [],
225
+ timelineItems: {
226
+ nodes: row.pullRequest
227
+ ? [{ source: { __typename: 'PullRequest', number: row.pullRequest } }]
228
+ : [],
229
+ },
230
+ };
231
+ }
232
+
233
+ function searchPage(argv, rows, nodeOf) {
234
+ const first = Number(gqlField(argv, 'first')) || rows.length;
235
+ const after = gqlField(argv, 'cursor');
236
+ const start = after === null ? 0 : Number(String(after).replace('row-', '')) + 1;
237
+ const page = rows.slice(start, start + first);
238
+ const hasNextPage = start + page.length < rows.length;
239
+ return JSON.stringify({
240
+ data: {
241
+ search: {
242
+ issueCount: rows.length,
243
+ pageInfo: { hasNextPage, endCursor: hasNextPage ? `row-${start + page.length - 1}` : null },
244
+ edges: page.map((row, at) => ({ cursor: `row-${start + at}`, node: nodeOf(row) })),
245
+ },
246
+ },
247
+ });
248
+ }
249
+
250
+ function connectionPage(argv, rows) {
251
+ const first = Number(gqlField(argv, 'first')) || rows.length;
252
+ const after = gqlField(argv, 'cursor');
253
+ const start = after === null ? 0 : Number(String(after).replace('conn-', '')) + 1;
254
+ const page = rows.slice(start, start + first);
255
+ const hasNextPage = start + page.length < rows.length;
256
+ return JSON.stringify({
257
+ data: {
258
+ repository: {
259
+ pullRequests: {
260
+ totalCount: rows.length,
261
+ pageInfo: { hasNextPage, endCursor: hasNextPage ? `conn-${start + page.length - 1}` : null },
262
+ edges: page.map((row, at) => ({ cursor: `conn-${start + at}`, node: prNode(row) })),
263
+ },
264
+ },
265
+ },
266
+ });
267
+ }
268
+
269
+ // `total` is the bucket's EXACT `issueCount`, which the window of `rows` may
270
+ // under-represent (D8): the header must count the difference too.
271
+ function railBucket(rows, total = rows.length) {
272
+ return {
273
+ issueCount: total,
274
+ nodes: rows.map((row) => ({
275
+ number: row.number,
276
+ closingIssuesReferences: {
277
+ nodes: (row.linkedIssues || []).map((number) => ({ number })),
278
+ pageInfo: { hasNextPage: false },
279
+ },
280
+ })),
281
+ };
282
+ }
283
+
284
+ function issueRailBucket(rows) {
285
+ return { issueCount: rows.length, nodes: rows.map(issueNode) };
286
+ }
287
+
288
+ function prDetail(number, overrides = {}) {
289
+ return {
290
+ number,
291
+ title: `Pull ${number}`,
292
+ state: 'OPEN',
293
+ isDraft: false,
294
+ author: { login: 'me' },
295
+ assignees: [],
296
+ labels: [{ name: 'bug', color: 'ff0000', description: '' }],
297
+ createdAt: '2024-01-01T00:00:00Z',
298
+ updatedAt: '2024-01-02T00:00:00Z',
299
+ comments: [],
300
+ reactionGroups: [],
301
+ url: `https://github.com/myfork/project/pull/${number}`,
302
+ body: 'Body text',
303
+ baseRefName: 'main',
304
+ headRefName: 'feature',
305
+ headRepositoryOwner: { login: 'myfork' },
306
+ additions: 12,
307
+ deletions: 3,
308
+ changedFiles: 2,
309
+ commits: [{ committedDate: '2024-01-02T00:00:00Z' }],
310
+ reviewDecision: 'REVIEW_REQUIRED',
311
+ reviewRequests: [{ requestedReviewer: { login: 'reviewer' } }],
312
+ latestReviews: [],
313
+ statusCheckRollup: [],
314
+ mergeable: 'MERGEABLE',
315
+ mergeStateStatus: 'CLEAN',
316
+ closingIssuesReferences: { nodes: [{ number: 63 }], pageInfo: { hasNextPage: false } },
317
+ ...overrides,
318
+ };
319
+ }
320
+
321
+ // The `gh` double: answers by argv shape, records every call together with the
322
+ // `GH_REPO` it was bound to, and can fail the rail read on demand.
323
+ function makeGithub(options = {}) {
324
+ const calls = [];
325
+ const state = {
326
+ gate: options.gate !== false,
327
+ role: options.role || 'WRITE',
328
+ railFail: options.railFail === true,
329
+ railReads: 0,
330
+ railGate: null,
331
+ railTotals: { mine: null, review: null },
332
+ };
333
+ const prRows = options.prRows || [{ number: 69 }, { number: 70 }];
334
+ const issueRows = options.issueRows || [{ number: 1, title: 'One' }, { number: 2, title: 'Two' }];
335
+ const railMine = options.railMine || [{ number: 69, linkedIssues: [1] }];
336
+ const railReview = options.railReview || [{ number: 70, linkedIssues: [2] }, { number: 69, linkedIssues: [1] }];
337
+ state.railTotals.mine = Number.isInteger(options.railMineTotal) ? options.railMineTotal : railMine.length;
338
+ state.railTotals.review = Number.isInteger(options.railReviewTotal) ? options.railReviewTotal : railReview.length;
339
+ const runner = async (bin, argv, runOpts = {}) => {
340
+ const env = runOpts.env || {};
341
+ calls.push({
342
+ bin,
343
+ argv: argv.slice(),
344
+ cwd: runOpts.cwd,
345
+ repo: typeof env.GH_REPO === 'string' && env.GH_REPO.length > 0 ? env.GH_REPO : null,
346
+ });
347
+ if (argv[0] === 'api' && argv[1] === 'user') {
348
+ return state.gate ? ok('{"login":"me"}') : failed('not logged in');
349
+ }
350
+ if (argv[0] === 'repo' && argv[1] === 'view') {
351
+ return ok(JSON.stringify({ nameWithOwner: 'myfork/project' }));
352
+ }
353
+ if (argv[0] === 'api' && argv[1] === 'graphql') {
354
+ const query = gqlQuery(argv);
355
+ if (query.includes('assignableUsers')) {
356
+ return ok(JSON.stringify({ data: { repository: { assignableUsers: {
357
+ nodes: [{ login: 'me', name: 'Me' }],
358
+ pageInfo: { hasNextPage: false, endCursor: null },
359
+ } } } }));
360
+ }
361
+ if (query.includes('viewer { login }')) {
362
+ return ok(JSON.stringify({ data: {
363
+ repository: { viewerPermission: state.role },
364
+ viewer: { login: 'me' },
365
+ } }));
366
+ }
367
+ if (query.includes('viewerPermission') && query.includes('closingIssuesReferences')) {
368
+ return ok(JSON.stringify({ data: { repository: {
369
+ viewerPermission: state.role,
370
+ mergeCommitAllowed: true,
371
+ squashMergeAllowed: true,
372
+ rebaseMergeAllowed: false,
373
+ pullRequest: {
374
+ isDraft: false,
375
+ state: 'OPEN',
376
+ closingIssuesReferences: { nodes: [{ number: 63 }], pageInfo: { hasNextPage: false } },
377
+ },
378
+ } } }));
379
+ }
380
+ if (query.includes('is:pr') && query.includes('mine: search')) {
381
+ state.railReads += 1;
382
+ if (state.railGate !== null) await state.railGate;
383
+ if (state.railFail) return failed('rate limited');
384
+ return ok(JSON.stringify({ data: {
385
+ mine: railBucket(railMine, state.railTotals.mine),
386
+ review: railBucket(railReview, state.railTotals.review),
387
+ } }));
388
+ }
389
+ if (query.includes('is:issue') && query.includes('mine: search')) {
390
+ return ok(JSON.stringify({ data: {
391
+ mine: issueRailBucket(issueRows),
392
+ assigned: issueRailBucket([]),
393
+ involved: issueRailBucket([]),
394
+ } }));
395
+ }
396
+ if (query.includes('pullRequests(states: OPEN')) {
397
+ return ok(connectionPage(argv, prRows));
398
+ }
399
+ const search = gqlField(argv, 'search');
400
+ if (search !== null) {
401
+ if (search.includes('is:pr')) return ok(searchPage(argv, prRows, prNode));
402
+ return ok(searchPage(argv, issueRows, issueNode));
403
+ }
404
+ if (query.includes('projectItems')) {
405
+ return ok(JSON.stringify({ data: { repository: { issue: {
406
+ projectItems: { nodes: [], pageInfo: { hasNextPage: false } },
407
+ } } } }));
408
+ }
409
+ if (query.includes('viewerPermission')) {
410
+ return ok(JSON.stringify({ data: { repository: {
411
+ viewerPermission: state.role,
412
+ // S2/D20: a write's role read answers the pull request state too.
413
+ pullRequest: { state: 'OPEN' },
414
+ issue: { assignees: { nodes: [], pageInfo: { hasNextPage: false } } },
415
+ } } }));
416
+ }
417
+ return ok(JSON.stringify({ data: {} }));
418
+ }
419
+ if (argv[0] === 'pr' && argv[1] === 'view' && argv.includes('--json')) {
420
+ if (argv.includes('--web')) return ok('');
421
+ if (argv[3] === 'body') return ok(JSON.stringify({ body: 'Body text' }));
422
+ return ok(JSON.stringify(prDetail(Number(argv[2]))));
423
+ }
424
+ if (argv[0] === 'issue' && argv[1] === 'view' && argv.includes('--json')) {
425
+ return ok(JSON.stringify({
426
+ number: Number(argv[2]),
427
+ title: `Issue ${argv[2]}`,
428
+ state: 'OPEN',
429
+ url: 'https://github.com/myfork/project/issues/1',
430
+ createdAt: '2024-01-01T00:00:00Z',
431
+ updatedAt: '2024-01-02T00:00:00Z',
432
+ author: { login: 'me' },
433
+ labels: [],
434
+ assignees: [],
435
+ comments: [],
436
+ body: 'Body',
437
+ }));
438
+ }
439
+ if (argv[0] === 'label' && argv[1] === 'list') {
440
+ return ok(JSON.stringify([{ name: 'bug', color: 'ff0000', description: '' }]));
441
+ }
442
+ if (argv[0] === 'label' && argv[1] === 'create') return ok('{}');
443
+ if (argv[0] === 'pr' && (argv[1] === 'comment' || argv[1] === 'close' || argv[1] === 'merge' || argv[1] === 'edit')) {
444
+ return ok('');
445
+ }
446
+ return ok('');
447
+ };
448
+ return { runner, calls, state };
449
+ }
450
+
451
+ function identityGit() {
452
+ return (argv, opts = {}) => {
453
+ try {
454
+ const stdout = execFileSync('git', argv, {
455
+ cwd: opts.cwd,
456
+ encoding: 'utf8',
457
+ env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null' },
458
+ });
459
+ return { status: 0, stdout, stderr: '', error: null };
460
+ } catch (err) {
461
+ return {
462
+ status: typeof err.status === 'number' ? err.status : 1,
463
+ stdout: String(err.stdout || ''),
464
+ stderr: String(err.stderr || ''),
465
+ error: null,
466
+ };
467
+ }
468
+ };
469
+ }
470
+
471
+ async function boot(options = {}) {
472
+ const sent = [];
473
+ const loaded = await loadExtension({
474
+ sendUserMessage: (text, sendOpts) => { sent.push({ text, opts: sendOpts }); },
475
+ }, options);
476
+ ghIssues = loaded.mod.libModule('gh-issues.js');
477
+ const gh = makeGithub(options);
478
+ ghIssues.setGhRunner(gh.runner);
479
+ ghIssues.setGitRunner(identityGit());
480
+ // `lib/gh-prs.js` keeps its own runner seam: the issue client is injected for
481
+ // its identity and scope helpers, and `runGh` is not one of the seams it
482
+ // exports, so the pull-request client's own `setGhRunner` is the lever.
483
+ const ghPrs = loaded.mod.libModule('gh-prs.js');
484
+ ghPrs.setGhRunner(gh.runner);
485
+ restores.push(() => { ghPrs.setGhRunner(null); });
486
+ loaded.mod.setIssuesTuiLoader(async () => stubTui);
487
+ // A test's extension must not outlive it: a rail read still in flight when the
488
+ // test ends would otherwise persist its answer under the NEXT test's cache home
489
+ // (the store reads `XDG_CACHE_HOME` when it writes), and that stale document
490
+ // would be hydrated into the next test's header. `session_shutdown` is the
491
+ // production path that drops a late answer by its generation.
492
+ restores.push(() => {
493
+ for (const [name, handler] of loaded.hooks) {
494
+ if (name !== 'session_shutdown') continue;
495
+ try { handler({}, { cwd: process.cwd(), ui: { notify() {} } }); } catch {}
496
+ }
497
+ });
498
+ return { loaded, sent, gh, ghPrs };
499
+ }
500
+
501
+ function sessionCtx(cwd, notes = []) {
502
+ return { cwd, ui: { notify: (text, level) => { notes.push({ text, level }); } } };
503
+ }
504
+
505
+ function captureView(mod, file, factoryName) {
506
+ const holder = { options: null, component: null };
507
+ const lib = mod.libModule(file);
508
+ const original = lib[factoryName];
509
+ lib[factoryName] = (options) => {
510
+ holder.options = options;
511
+ holder.component = {
512
+ render: () => [],
513
+ handleInput: () => {},
514
+ handleMouse: () => undefined,
515
+ invalidate: () => {},
516
+ };
517
+ return holder.component;
518
+ };
519
+ restores.push(() => { lib[factoryName] = original; });
520
+ return holder;
521
+ }
522
+
523
+ const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
524
+
525
+ async function waitFor(predicate, timeoutMs = 8000) {
526
+ const deadline = Date.now() + timeoutMs;
527
+ for (;;) {
528
+ if (predicate()) return;
529
+ if (Date.now() >= deadline) throw new Error('condition never became true');
530
+ await new Promise((resolve) => realSetTimeout(resolve, 10));
531
+ }
532
+ }
533
+
534
+ function makeCtx(cwd) {
535
+ const notes = [];
536
+ const ctx = { cwd, ui: { notify: (text, level) => { notes.push({ text, level }); } } };
537
+ return { ctx, notes };
538
+ }
539
+
540
+ // Mount the command the way the host would, capturing the overlay options, the
541
+ // view options (through the capture seam) and the `done` the view was handed.
542
+ async function mountCommand(loaded, name, args, ctx, { capture = null } = {}) {
543
+ const host = {
544
+ terminal: { rows: 24 },
545
+ stop: () => {},
546
+ start: () => {},
547
+ requestRender: () => {},
548
+ visibleWidth: stubTui.visibleWidth,
549
+ truncateToWidth: stubTui.truncateToWidth,
550
+ };
551
+ const mount = { overlay: null, options: null, component: null, doneCount: 0, doneResult: 'pending' };
552
+ ctx.ui.custom = async (factory, options) => {
553
+ mount.overlay = options;
554
+ mount.component = factory(host, {}, {}, (result) => {
555
+ mount.doneCount += 1;
556
+ mount.doneResult = result;
557
+ });
558
+ mount.options = capture === null ? mount.options : capture.options;
559
+ return null;
560
+ };
561
+ const def = loaded.commands.get(name);
562
+ assert.ok(def, `expected the /${name} command to be registered`);
563
+ await def.handler(args, ctx);
564
+ await tick();
565
+ mount.options = capture === null ? null : capture.options;
566
+ return mount;
567
+ }
568
+
569
+ // The gate warms in a scratch checkout (no repository), so the command's own open
570
+ // proves the fixture checkout's identity from cold, exactly like production.
571
+ async function warmGate(loaded) {
572
+ const scratch = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-prs-gate-')));
573
+ await fireSessionStart(loaded.hooks, sessionCtx(scratch));
574
+ return scratch;
575
+ }
576
+
577
+ async function drawSection(section, ctx) {
578
+ const deadline = Date.now() + 8000;
579
+ for (;;) {
580
+ const rows = section.lines(ctx);
581
+ const meta = section.meta(ctx);
582
+ if (rows.length > 0 && !(rows.length === 1 && rows[0].label === 'loading…')) return { rows, meta };
583
+ if (Date.now() >= deadline) throw new Error('the section never left loading');
584
+ await new Promise((resolve) => realSetTimeout(resolve, 10));
585
+ }
586
+ }
587
+
588
+ // ---------------------------------------------------------------------------
589
+ // Registration and the shared `gh` gate
590
+ // ---------------------------------------------------------------------------
591
+
592
+ describe('/prs registration and gate (S1)', () => {
593
+ test('without the gh CLI neither /issues nor /prs is registered', async () => {
594
+ installBridge();
595
+ const loaded = await loadExtension({}, { gh: false });
596
+ assert.equal(loaded.commands.has('issues'), false, 'the issues reader is withheld');
597
+ assert.equal(loaded.commands.has('prs'), false, 'the pull-request reader is withheld');
598
+ });
599
+
600
+ test('with the CLI present both commands exist (PRESERVE)', async () => {
601
+ installBridge();
602
+ const loaded = await loadExtension({}, { gh: true });
603
+ assert.equal(loaded.commands.has('issues'), true);
604
+ assert.equal(loaded.commands.has('prs'), true);
605
+ assert.match(loaded.commands.get('prs').description, /pull request/i);
606
+ });
607
+
608
+ test('an unauthenticated gh refuses /prs with the prs sentence and mounts nothing', async () => {
609
+ installBridge();
610
+ const b = await boot({ gate: false });
611
+ await warmGate(b.loaded);
612
+ const root = makeCheckout();
613
+ const { ctx, notes } = makeCtx(root);
614
+ const mount = await mountCommand(b.loaded, 'prs', '', ctx);
615
+ assert.equal(mount.overlay, null, 'no overlay is mounted');
616
+ assert.ok(
617
+ notes.some((note) => note.level === 'error' && /^prs: .*— \/prs cannot open until then$/.test(note.text)),
618
+ `the refusal names the prs command (saw ${JSON.stringify(notes)})`,
619
+ );
620
+ });
621
+ });
622
+
623
+ // ---------------------------------------------------------------------------
624
+ // S1: the overlay and the reads it makes
625
+ // ---------------------------------------------------------------------------
626
+
627
+ describe('/prs overlay and reads (S1, S3)', () => {
628
+ test('opens full screen on the three scoped buckets, leaving all lazy', async () => {
629
+ installBridge();
630
+ const b = await boot();
631
+ await warmGate(b.loaded);
632
+ const root = makeCheckout();
633
+ const capture = captureView(b.loaded.mod, 'prs-view.js', 'createPrsView');
634
+ const { ctx } = makeCtx(root);
635
+ const mount = await mountCommand(b.loaded, 'prs', '', ctx, { capture });
636
+
637
+ assert.deepEqual(mount.overlay, {
638
+ overlay: true,
639
+ overlayOptions: { anchor: 'center', width: '100%', maxHeight: '100%', margin: 0 },
640
+ });
641
+ const opts = capture.options;
642
+ assert.deepEqual(opts.pages.map((page) => page.id), ['mine', 'review', 'involved', 'all']);
643
+ assert.deepEqual(opts.pages.map((page) => page.label), ['My Pull Request', 'Needs My Review', 'Involved', 'All']);
644
+ assert.equal(opts.pages.find((page) => page.id === 'all').lazy, true, 'all stays out of the prefetch');
645
+
646
+ const page = await opts.loadPullRequestPage({ bucketId: 'review', cursor: null, limit: 2, query: '' });
647
+ assert.equal(page.ok, true);
648
+ assert.equal(page.rows.length, 2);
649
+ const search = gqlField(b.gh.calls[b.gh.calls.length - 1].argv, 'search');
650
+ assert.ok(search.includes('is:pr'), 'the read is the pull-request search');
651
+ assert.ok(search.includes('review-requested:@me'), 'the bucket qualifier reaches gh');
652
+ assert.equal(b.gh.calls[b.gh.calls.length - 1].repo, 'github.com/myfork/project', 'the pinned identity binds the page');
653
+ });
654
+
655
+ test('the lazy all bucket reads the repository connection', async () => {
656
+ installBridge();
657
+ const b = await boot();
658
+ await warmGate(b.loaded);
659
+ const root = makeCheckout();
660
+ const capture = captureView(b.loaded.mod, 'prs-view.js', 'createPrsView');
661
+ const { ctx } = makeCtx(root);
662
+ await mountCommand(b.loaded, 'prs', '', ctx, { capture });
663
+ const page = await capture.options.loadPullRequestPage({ bucketId: 'all', cursor: null, limit: 2, query: '' });
664
+ assert.equal(page.ok, true);
665
+ const call = b.gh.calls.find((entry) => gqlQuery(entry.argv).includes('pullRequests(states: OPEN'));
666
+ assert.ok(call, 'the connection page was read');
667
+ assert.equal(call.repo, 'github.com/myfork/project');
668
+ });
669
+
670
+ test('the detail asks for the authoritative metadata under the pinned identity', async () => {
671
+ installBridge();
672
+ const b = await boot();
673
+ await warmGate(b.loaded);
674
+ const root = makeCheckout();
675
+ const capture = captureView(b.loaded.mod, 'prs-view.js', 'createPrsView');
676
+ const { ctx } = makeCtx(root);
677
+ await mountCommand(b.loaded, 'prs', '', ctx, { capture });
678
+ const detail = await capture.options.loadPullRequest(69);
679
+ assert.equal(detail.ok, true);
680
+ assert.equal(detail.pullRequest.permissions.canMerge, true, 'a WRITE viewer with an allowed method can merge');
681
+ assert.equal(detail.pullRequest.mergeMethods.merge, true);
682
+ assert.deepEqual(detail.pullRequest.linkedIssues, [63]);
683
+ const view = b.gh.calls.find((entry) => entry.argv[0] === 'pr' && entry.argv[1] === 'view' && entry.argv.includes('--json'));
684
+ assert.deepEqual(view.argv.slice(0, 3), ['pr', 'view', '69']);
685
+ assert.ok(view.argv.some((part) => part.includes('closingIssuesReferences')), 'the linked issues ride the detail read');
686
+ assert.equal(view.repo, 'github.com/myfork/project');
687
+ });
688
+
689
+ test('the o opener runs gh pr view <n> --web -R <pinned>', async () => {
690
+ installBridge();
691
+ const b = await boot();
692
+ await warmGate(b.loaded);
693
+ const root = makeCheckout();
694
+ const worktreeGit = b.loaded.mod.libModule('worktree-git.js');
695
+ const original = worktreeGit.runArgvAsync;
696
+ const argvSeen = [];
697
+ // Only the opener's own child is faked: every other git call of the command
698
+ // (the checkout resolution and the identity proof) stays real, so the test
699
+ // observes the opener instead of breaking the pin it rides on.
700
+ worktreeGit.runArgvAsync = async (bin, argv, opts) => {
701
+ if (argv[0] !== 'pr') return original.call(worktreeGit, bin, argv, opts);
702
+ argvSeen.push({ bin, argv: argv.slice() });
703
+ return { status: 0, stdout: '', stderr: '', error: null };
704
+ };
705
+ restores.push(() => { worktreeGit.runArgvAsync = original; });
706
+ const capture = captureView(b.loaded.mod, 'prs-view.js', 'createPrsView');
707
+ const { ctx } = makeCtx(root);
708
+ await mountCommand(b.loaded, 'prs', '', ctx, { capture });
709
+ const result = await capture.options.actions.openBrowser(69);
710
+ assert.equal(result.ok, true);
711
+ const open = argvSeen.find((entry) => entry.argv[0] === 'pr');
712
+ assert.ok(open, 'the opener ran gh pr view');
713
+ assert.deepEqual(open.argv, ['pr', 'view', '69', '--web', '-R', 'github.com/myfork/project']);
714
+ });
715
+ });
716
+
717
+ // ---------------------------------------------------------------------------
718
+ // S7: `enter` inserts, in BOTH panels
719
+ // ---------------------------------------------------------------------------
720
+
721
+ describe('S7: enter inserts the item into the chat input', () => {
722
+ test('the PR panel inserts "PR #N" and closes, sending nothing', async () => {
723
+ installBridge();
724
+ const b = await boot();
725
+ await warmGate(b.loaded);
726
+ const root = makeCheckout();
727
+ const { ctx } = makeCtx(root);
728
+ const pasted = [];
729
+ ctx.ui.pasteToEditor = (text) => { pasted.push(text); };
730
+ const mount = await mountCommand(b.loaded, 'prs', '', ctx);
731
+ // The host hands mouse events to the component it mounted, so both panels must
732
+ // expose the seam the linked-number click rides.
733
+ assert.equal(typeof mount.component.handleMouse, 'function', 'the PR panel receives mouse events');
734
+ mount.component.render(100);
735
+ await tick();
736
+ mount.component.render(100);
737
+ mount.component.handleInput('enter');
738
+ assert.deepEqual(pasted, ['PR #69']);
739
+ assert.equal(mount.doneCount, 1, 'the panel closes behind the insertion');
740
+ assert.deepEqual(b.sent, [], 'nothing is sent to the agent');
741
+ });
742
+
743
+ test('the issues panel inserts "ISSUE #N" and closes, sending nothing', async () => {
744
+ installBridge();
745
+ const b = await boot();
746
+ await warmGate(b.loaded);
747
+ const root = makeCheckout();
748
+ const { ctx } = makeCtx(root);
749
+ const pasted = [];
750
+ ctx.ui.pasteToEditor = (text) => { pasted.push(text); };
751
+ const mount = await mountCommand(b.loaded, 'issues', '', ctx);
752
+ assert.equal(typeof mount.component.handleMouse, 'function', 'the issues panel receives mouse events');
753
+ mount.component.render(100);
754
+ await tick();
755
+ mount.component.render(100);
756
+ mount.component.handleInput('enter');
757
+ assert.deepEqual(pasted, ['ISSUE #1']);
758
+ assert.equal(mount.doneCount, 1, 'the panel closes behind the insertion');
759
+ assert.deepEqual(b.sent, []);
760
+ });
761
+
762
+ test('a host with no paste seam gets one honest line and the panel still closes', async () => {
763
+ installBridge();
764
+ const b = await boot();
765
+ await warmGate(b.loaded);
766
+ const root = makeCheckout();
767
+ const { ctx, notes } = makeCtx(root);
768
+ const mount = await mountCommand(b.loaded, 'prs', '', ctx);
769
+ mount.component.render(100);
770
+ await tick();
771
+ mount.component.render(100);
772
+ mount.component.handleInput('enter');
773
+ assert.ok(
774
+ notes.some((note) => note.level === 'warning' && note.text === 'prs: the editor did not accept the insertion: PR #69'),
775
+ `the fallback names the exact text (saw ${JSON.stringify(notes)})`,
776
+ );
777
+ assert.equal(mount.doneCount, 1);
778
+ });
779
+ });
780
+
781
+ // ---------------------------------------------------------------------------
782
+ // S6: cross-links close the current panel and open the other one
783
+ // ---------------------------------------------------------------------------
784
+
785
+ describe('S6: linked numbers open the other panel without stacking', () => {
786
+ test('a linked issue in the PR panel closes it and dispatches /issues N', async () => {
787
+ installBridge();
788
+ const b = await boot();
789
+ await warmGate(b.loaded);
790
+ const root = makeCheckout();
791
+ const capture = captureView(b.loaded.mod, 'prs-view.js', 'createPrsView');
792
+ const { ctx } = makeCtx(root);
793
+ const mount = await mountCommand(b.loaded, 'prs', '', ctx, { capture });
794
+ const order = [];
795
+ capture.options.actions.openLinked({ kind: 'issue', number: 63 });
796
+ if (mount.doneCount === 1) order.push('closed');
797
+ if (b.sent.length > 0) order.push('dispatched');
798
+ assert.deepEqual(order, ['closed', 'dispatched'], 'the current panel is closed BEFORE the other opens');
799
+ assert.deepEqual(b.sent.map((entry) => entry.text), ['/issues 63']);
800
+ assert.deepEqual(b.sent[0].opts, { expandPromptTemplates: true });
801
+ });
802
+
803
+ test('a linked PR in the issues panel closes it and dispatches /prs N', async () => {
804
+ installBridge();
805
+ const b = await boot();
806
+ await warmGate(b.loaded);
807
+ const root = makeCheckout();
808
+ const capture = captureView(b.loaded.mod, 'issues-view.js', 'createIssuesView');
809
+ const { ctx } = makeCtx(root);
810
+ const mount = await mountCommand(b.loaded, 'issues', '', ctx, { capture });
811
+ const order = [];
812
+ capture.options.actions.openLinked({ kind: 'pullRequest', number: 70 });
813
+ if (mount.doneCount === 1) order.push('closed');
814
+ if (b.sent.length > 0) order.push('dispatched');
815
+ assert.deepEqual(order, ['closed', 'dispatched']);
816
+ assert.deepEqual(b.sent.map((entry) => entry.text), ['/prs 70']);
817
+ });
818
+
819
+ test('a linked click while that other panel is already opening changes nothing', async () => {
820
+ installBridge();
821
+ const b = await boot();
822
+ await warmGate(b.loaded);
823
+ const root = makeCheckout();
824
+ const capture = captureView(b.loaded.mod, 'prs-view.js', 'createPrsView');
825
+ const { ctx } = makeCtx(root);
826
+ const mount = await mountCommand(b.loaded, 'prs', '', ctx, { capture });
827
+ // The rail's own click holds the /issues guard: this click must leave the
828
+ // panel exactly as it is instead of closing onto a dispatch that is dropped.
829
+ const section = installBridge().registered;
830
+ capture.options.actions.openLinked({ kind: 'issue', number: 63 });
831
+ assert.equal(mount.doneCount, 1);
832
+ assert.deepEqual(b.sent.map((entry) => entry.text), ['/issues 63']);
833
+ assert.equal(Array.isArray(section), true);
834
+ });
835
+ });
836
+
837
+ // ---------------------------------------------------------------------------
838
+ // S4/S5: the rail's pull-request count, routing and persistence
839
+ // ---------------------------------------------------------------------------
840
+
841
+ describe('S4/S5: the one section counts and routes pull requests', () => {
842
+ test('the header paints N issues · M pr from the one section', async () => {
843
+ installBridge();
844
+ const b = await boot({
845
+ issueRows: [{ number: 1, title: 'One', pullRequest: 69 }, { number: 2, title: 'Two' }],
846
+ });
847
+ const { registered } = installBridge();
848
+ const root = makeCheckout();
849
+ await warmGate(b.loaded);
850
+ const ctx = sessionCtx(root);
851
+ await fireSessionStart(b.loaded.hooks, ctx);
852
+ const section = registered[0];
853
+ assert.ok(section, 'one section is registered');
854
+ await drawSection(section, ctx);
855
+ // The count is the second read; the header grows its `· N pr` segment when
856
+ // that answer lands, so the assertion waits for it instead of the first frame.
857
+ await waitFor(() => section.meta(ctx) === '2 issues · 2 pr');
858
+ assert.equal(section.meta(ctx), '2 issues · 2 pr', 'the distinct union of mine and review counts once');
859
+ assert.equal(registered.length, 1, 'the count is not a second section');
860
+ });
861
+
862
+ test('a row whose issue links a PR opens the PR panel with the review bucket hint', async () => {
863
+ installBridge();
864
+ const b = await boot({
865
+ issueRows: [{ number: 1, title: 'One', pullRequest: 69 }],
866
+ });
867
+ const { registered } = installBridge();
868
+ const root = makeCheckout();
869
+ await warmGate(b.loaded);
870
+ const ctx = sessionCtx(root);
871
+ await fireSessionStart(b.loaded.hooks, ctx);
872
+ const section = registered[0];
873
+ const { rows } = await drawSection(section, ctx);
874
+ // The bucket hint is decided against the rail's own read, so the click runs
875
+ // after that second answer landed.
876
+ await waitFor(() => String(section.meta(ctx)).includes(' pr'));
877
+ const row = rows.find((entry) => entry.label.startsWith('#1 '));
878
+ assert.ok(row, 'the issue row is painted');
879
+ assert.match(String(row.meta), /#69/, 'the linked pull request is the row mark');
880
+ row.onClick();
881
+ await waitFor(() => b.sent.length > 0);
882
+ assert.deepEqual(b.sent.map((entry) => entry.text), ['/prs 69']);
883
+
884
+ // The command the host runs next consumes the bucket hint: 69 is in both
885
+ // buckets and `review` wins, so the panel opens on that list.
886
+ const capture = captureView(b.loaded.mod, 'prs-view.js', 'createPrsView');
887
+ const mount = await mountCommand(b.loaded, 'prs', '69', ctx, { capture });
888
+ assert.equal(capture.options.initialPullRequest, 69);
889
+ assert.equal(capture.options.initialBucket, 'review');
890
+ assert.ok(mount.overlay, 'the panel opens');
891
+ });
892
+
893
+ test('a row without a linked PR keeps the /issues call (PRESERVE)', async () => {
894
+ installBridge();
895
+ const b = await boot({ issueRows: [{ number: 1, title: 'One' }] });
896
+ const { registered } = installBridge();
897
+ const root = makeCheckout();
898
+ await warmGate(b.loaded);
899
+ const ctx = sessionCtx(root);
900
+ await fireSessionStart(b.loaded.hooks, ctx);
901
+ const section = registered[0];
902
+ const { rows } = await drawSection(section, ctx);
903
+ rows.find((entry) => entry.label.startsWith('#1 ')).onClick();
904
+ await waitFor(() => b.sent.length > 0);
905
+ assert.deepEqual(b.sent.map((entry) => entry.text), ['/issues 1']);
906
+ });
907
+
908
+ test('the loader persists the rail read and paints it back when the live read fails', async () => {
909
+ installBridge();
910
+ const b = await boot();
911
+ const { registered } = installBridge();
912
+ const root = makeCheckout();
913
+ await warmGate(b.loaded);
914
+ const ctx = sessionCtx(root);
915
+ await fireSessionStart(b.loaded.hooks, ctx);
916
+ const section = registered[0];
917
+ await drawSection(section, ctx);
918
+ await waitFor(() => section.meta(ctx) === '2 issues · 2 pr');
919
+ assert.match(String(section.meta(ctx)), /^2 issues · 2 pr$/);
920
+
921
+ const docPath = path.join(process.env.XDG_CACHE_HOME, 'odd-worktree', 'prs-rail.json');
922
+ await waitFor(() => fs.existsSync(docPath));
923
+ const doc = JSON.parse(fs.readFileSync(docPath, 'utf8'));
924
+ assert.equal(doc.version, 2, 'the document carries the bucket totals beside the rows (T10b)');
925
+ const entry = doc.identities.find((candidate) => candidate.identity === 'github.com/myfork/project');
926
+ assert.ok(entry, 'the read is stored under the identity it was read from');
927
+ assert.deepEqual(entry.mine.map((row) => row.number), [69]);
928
+ assert.deepEqual(entry.review.map((row) => row.number), [70, 69]);
929
+
930
+ // A live read that fails falls back to the stored one instead of blanking.
931
+ b.gh.state.railFail = true;
932
+ await fireHook(b.loaded.hooks, 'tool_result', {
933
+ tool: 'bash',
934
+ args: { command: 'gh pr merge 1 --merge' },
935
+ toolResults: [],
936
+ }, ctx);
937
+ await new Promise((resolve) => realSetTimeout(resolve, 50));
938
+ section.lines(ctx);
939
+ assert.equal(section.meta(ctx), '2 issues · 2 pr', 'the stored count is painted, never a blank header');
940
+ const left = fs.readdirSync(path.join(process.env.XDG_CACHE_HOME, 'odd-worktree'));
941
+ assert.equal(left.some((entry) => entry.includes('.tmp')), false, `no temp file is left behind (saw ${left.join(', ')})`);
942
+ });
943
+
944
+ test('a mutation made in the panel invalidates the count and re-reads the rail', async () => {
945
+ installBridge();
946
+ const b = await boot();
947
+ const { registered } = installBridge();
948
+ const root = makeCheckout();
949
+ await warmGate(b.loaded);
950
+ const ctx = sessionCtx(root);
951
+ await fireSessionStart(b.loaded.hooks, ctx);
952
+ const section = registered[0];
953
+ await drawSection(section, ctx);
954
+ const readsBefore = b.gh.state.railReads;
955
+
956
+ const capture = captureView(b.loaded.mod, 'prs-view.js', 'createPrsView');
957
+ await mountCommand(b.loaded, 'prs', '', ctx, { capture });
958
+ const merged = await capture.options.actions.mergePullRequest(69, { method: 'merge', subject: 'Merge it', body: 'Body' });
959
+ assert.equal(merged.ok, true);
960
+ const mergeCall = b.gh.calls.find((entry) => entry.argv[0] === 'pr' && entry.argv[1] === 'merge');
961
+ assert.deepEqual(mergeCall.argv, ['pr', 'merge', '69', '--merge', '--subject', 'Merge it', '--body', 'Body']);
962
+ await waitFor(() => b.gh.state.railReads > readsBefore);
963
+ assert.ok(b.gh.state.railReads > readsBefore, 'the rail read again after the write');
964
+ });
965
+ });
966
+
967
+ // ---------------------------------------------------------------------------
968
+ // S5: the session-start preload
969
+ // ---------------------------------------------------------------------------
970
+
971
+ describe('S5: the session-start preload is dispatched, never awaited', () => {
972
+ // The section is created only once the bridge exists, so the spy below can wrap
973
+ // its `refreshIfStale` before the extension builds it: the surface is registered
974
+ // by the first `session_start`, after the bridge is published late.
975
+ function spySectionFactory(mod) {
976
+ const holder = { calls: 0 };
977
+ const lib = mod.libModule('issues-section.js');
978
+ const original = lib.createIssuesSection;
979
+ lib.createIssuesSection = (options) => {
980
+ const handle = original(options);
981
+ const real = handle.refreshIfStale;
982
+ handle.refreshIfStale = (...args) => {
983
+ holder.calls += 1;
984
+ return real.apply(handle, args);
985
+ };
986
+ return handle;
987
+ };
988
+ restores.push(() => { lib.createIssuesSection = original; });
989
+ return holder;
990
+ }
991
+
992
+ async function gatedBoot() {
993
+ const b = await boot();
994
+ const { registered } = installBridge();
995
+ const spy = spySectionFactory(b.loaded.mod);
996
+ // The first start publishes the surface (the bridge arrived after the load);
997
+ // the section exists from here on.
998
+ await fireSessionStart(b.loaded.hooks, sessionCtx(track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-prs-gate-')))));
999
+ const root = makeCheckout();
1000
+ const ctx = sessionCtx(root);
1001
+ await fireSessionStart(b.loaded.hooks, ctx);
1002
+ return { b, registered, spy, ctx };
1003
+ }
1004
+
1005
+ test('a section the host was drawing asks for a read, dispatched and never awaited', async () => {
1006
+ const { b, registered, spy, ctx } = await gatedBoot();
1007
+ assert.equal(spy.calls, 0, 'the not-yet-drawn section earned no preload');
1008
+ await drawSection(registered[0], ctx);
1009
+ await waitFor(() => String(registered[0].meta(ctx)).includes(' pr'));
1010
+
1011
+ const returned = fireSessionStartSync(b.loaded.hooks, ctx);
1012
+ for (const value of returned) {
1013
+ if (value && typeof value.then === 'function') {
1014
+ throw new Error('a session_start handler must not return a promise');
1015
+ }
1016
+ }
1017
+ assert.equal(spy.calls, 0, 'the preload is a microtask, not work on the handler path');
1018
+ await new Promise((resolve) => realSetTimeout(resolve, 20));
1019
+ assert.equal(spy.calls, 1, 'the dispatched preload asked the drawn section for a read');
1020
+ await b.loaded.mod.awaitPendingStartupTasks();
1021
+ });
1022
+
1023
+ test('a hidden section starts no read at session start', async () => {
1024
+ const { b, spy, ctx } = await gatedBoot();
1025
+ await fireSessionStart(b.loaded.hooks, ctx);
1026
+ await new Promise((resolve) => realSetTimeout(resolve, 20));
1027
+ await b.loaded.mod.awaitPendingStartupTasks();
1028
+ assert.equal(spy.calls, 0, 'a section nobody drew costs no read');
1029
+ });
1030
+ });
1031
+
1032
+ // ---------------------------------------------------------------------------
1033
+ // T8b (S4, S2): the defects T7 found in the rail and in `/prs`'s own refusals.
1034
+ //
1035
+ // D8 — the rail's read carries an EXACT `issueCount` per bucket and at most a
1036
+ // window of rows, so the header counts the unfetched remainder of each total as
1037
+ // well as the distinct numbers it fetched: `issueCount=51` with 50 nodes and an
1038
+ // empty review is `2 issues · 51 pr`, never `50 pr`.
1039
+ //
1040
+ // D9 — the persisted `prs-rail.json` count is painted at a COLD START, from the
1041
+ // async loader, while the live read is still in flight; the live answer then
1042
+ // replaces it. The stored entry never settles the read (the live one is asked
1043
+ // anyway) and a mutation that invalidated the identity is never painted back.
1044
+ //
1045
+ // D10 — the remote-moved refusal of a `/prs` action names `/prs`.
1046
+ // ---------------------------------------------------------------------------
1047
+
1048
+ describe('T8b: the exact count, the cold-start paint and the /prs refusal', () => {
1049
+ test('S4 (D8): the header counts each bucket\'s total, not only the rows it carried', async () => {
1050
+ installBridge();
1051
+ const first = Array.from({ length: 50 }, (_, index) => ({ number: index + 1, linkedIssues: [] }));
1052
+ const b = await boot({ railMine: first, railMineTotal: 51, railReview: [] });
1053
+ const { registered } = installBridge();
1054
+ const root = makeCheckout();
1055
+ await warmGate(b.loaded);
1056
+ const ctx = sessionCtx(root);
1057
+ await fireSessionStart(b.loaded.hooks, ctx);
1058
+ const section = registered[0];
1059
+ await drawSection(section, ctx);
1060
+ await waitFor(() => section.meta(ctx) === '2 issues · 51 pr');
1061
+ assert.equal(section.meta(ctx), '2 issues · 51 pr',
1062
+ 'the one node the window cut is counted, not dropped');
1063
+ });
1064
+
1065
+ test('S4/S5 (D9): a cold start paints the stored count at once, and the live read still replaces it', async () => {
1066
+ installBridge();
1067
+ // The entry a previous process left behind: ONE pull request, stored under the
1068
+ // identity this checkout proves.
1069
+ const docPath = path.join(process.env.XDG_CACHE_HOME, 'odd-worktree', 'prs-rail.json');
1070
+ fs.mkdirSync(path.dirname(docPath), { recursive: true });
1071
+ fs.writeFileSync(docPath, JSON.stringify({
1072
+ version: 2,
1073
+ identities: [{
1074
+ identity: 'github.com/myfork/project',
1075
+ mine: [{ number: 69, linkedIssues: [1] }],
1076
+ review: [],
1077
+ counts: { mine: 1, review: 0 },
1078
+ syncedAt: Date.now(),
1079
+ }],
1080
+ }));
1081
+ const b = await boot({ railMine: [{ number: 71 }], railReview: [{ number: 72 }] });
1082
+ const { registered } = installBridge();
1083
+ const root = makeCheckout();
1084
+ await warmGate(b.loaded);
1085
+ const ctx = sessionCtx(root);
1086
+ // The live read is HELD, so anything on the header before it is released was
1087
+ // painted by the stored entry alone.
1088
+ let release = null;
1089
+ b.gh.state.railGate = new Promise((resolve) => { release = resolve; });
1090
+ await fireSessionStart(b.loaded.hooks, ctx);
1091
+ const section = registered[0];
1092
+ await drawSection(section, ctx);
1093
+
1094
+ await waitFor(() => String(section.meta(ctx)).includes(' pr'));
1095
+ assert.equal(section.meta(ctx), '2 issues · 1 pr', 'the stored count is painted while the live read is held');
1096
+ // The live read was asked anyway: the stored entry is a paint, never the read's
1097
+ // own answer (invariant 25 keeps the TTL the live read's).
1098
+ await waitFor(() => b.gh.state.railReads >= 1);
1099
+ assert.equal(section.meta(ctx), '2 issues · 1 pr', 'and the live read is in flight, not skipped');
1100
+
1101
+ b.gh.state.railGate = null;
1102
+ release();
1103
+ await waitFor(() => section.meta(ctx) === '2 issues · 2 pr');
1104
+ assert.equal(section.meta(ctx), '2 issues · 2 pr', 'the live answer replaces the stored one'); });
1105
+
1106
+ test('S4/S5 (D9): a mutation\'s invalidation is never painted back from the store', async () => {
1107
+ installBridge();
1108
+ const docPath = path.join(process.env.XDG_CACHE_HOME, 'odd-worktree', 'prs-rail.json');
1109
+ fs.mkdirSync(path.dirname(docPath), { recursive: true });
1110
+ fs.writeFileSync(docPath, JSON.stringify({
1111
+ version: 2,
1112
+ identities: [{
1113
+ identity: 'github.com/myfork/project',
1114
+ mine: [{ number: 69, linkedIssues: [1] }],
1115
+ review: [],
1116
+ counts: { mine: 1, review: 0 },
1117
+ syncedAt: Date.now(),
1118
+ }],
1119
+ }));
1120
+ const b = await boot({ railMine: [{ number: 71 }], railReview: [{ number: 72 }] });
1121
+ const { registered } = installBridge();
1122
+ const root = makeCheckout();
1123
+ await warmGate(b.loaded);
1124
+ const ctx = sessionCtx(root);
1125
+ await fireSessionStart(b.loaded.hooks, ctx);
1126
+ const section = registered[0];
1127
+ await drawSection(section, ctx);
1128
+ await waitFor(() => section.meta(ctx) === '2 issues · 2 pr');
1129
+
1130
+ // A write made in the panel drops the identity, so nothing may hydrate it back.
1131
+ const capture = captureView(b.loaded.mod, 'prs-view.js', 'createPrsView');
1132
+ await mountCommand(b.loaded, 'prs', '', ctx, { capture });
1133
+ const merged = await capture.options.actions.mergePullRequest(69, { method: 'merge', subject: 's', body: 'b' });
1134
+ assert.equal(merged.ok, true);
1135
+ const held = new Promise(() => {});
1136
+ b.gh.state.railGate = held;
1137
+ await fireHook(b.loaded.hooks, 'tool_result', {
1138
+ tool: 'bash',
1139
+ args: { command: 'gh pr merge 69 --merge' },
1140
+ toolResults: [],
1141
+ }, ctx);
1142
+ await new Promise((resolve) => realSetTimeout(resolve, 50));
1143
+ section.lines(ctx);
1144
+ assert.notEqual(section.meta(ctx), '2 issues · 1 pr',
1145
+ 'the invalidated entry is never painted back while the live read is held');
1146
+ });
1147
+
1148
+ test('S2 (D10): the remote-moved refusal of a /prs action names /prs', async () => {
1149
+ installBridge();
1150
+ const b = await boot();
1151
+ installBridge();
1152
+ const root = makeCheckout();
1153
+ await warmGate(b.loaded);
1154
+ const ctx = sessionCtx(root);
1155
+ await fireSessionStart(b.loaded.hooks, ctx);
1156
+ const capture = captureView(b.loaded.mod, 'prs-view.js', 'createPrsView');
1157
+ await mountCommand(b.loaded, 'prs', '', ctx, { capture });
1158
+ assert.ok(capture.options, 'the panel opened');
1159
+
1160
+ // The checkout moves to another repository under the open panel: every write
1161
+ // must refuse and say which panel to reopen.
1162
+ git(root, ['remote', 'set-url', 'origin', 'git@github.com:otherfork/project.git']);
1163
+ const before = b.gh.calls.length;
1164
+ const refused = await capture.options.actions.closePullRequest(69);
1165
+ assert.equal(refused.ok, false, 'the close is refused on the drift');
1166
+ assert.match(refused.error, /changed since this pull request list loaded/,
1167
+ 'the refusal names the list that loaded');
1168
+ assert.match(refused.error, /reopen \/prs$/,
1169
+ 'and the panel to reopen is /prs, never /issues');
1170
+ const mutations = b.gh.calls.slice(before)
1171
+ .filter((call) => call.argv[0] === 'pr' && ['close', 'merge', 'edit', 'comment'].includes(call.argv[1]));
1172
+ assert.deepEqual(mutations, [], 'no mutating gh command ran after the drift');
1173
+ });
1174
+ });
1175
+
1176
+ // ---------------------------------------------------------------------------
1177
+ // T10b (S4): D9 and D15, at the wiring level.
1178
+ //
1179
+ // D9 — the rail's pull-request read is a SECOND state of the one section, so its
1180
+ // settlement must ask the bridge to repaint exactly like the issues read does;
1181
+ // without it the header keeps the old `pr` count until an unrelated frame.
1182
+ //
1183
+ // D15 — the store keeps each bucket's TOTAL beside its rows, so a restart paints
1184
+ // the number the live read painted: 50 returned rows with a total of 52 is
1185
+ // `52 pr` on both sides of the restart, never `50 pr`.
1186
+ // ---------------------------------------------------------------------------
1187
+
1188
+ describe('T10b: the rail read repaints the header and its totals survive a restart', () => {
1189
+ const fiftyRows = () => Array.from({ length: 50 }, (_, index) => ({ number: index + 1, linkedIssues: [] }));
1190
+
1191
+ test('S4 (D9): the settled rail read asks the bridge to repaint the header it changed', async () => {
1192
+ installBridge();
1193
+ const b = await boot({ railMine: [{ number: 69 }], railReview: [{ number: 70 }] });
1194
+ let repaints = 0;
1195
+ const { registered } = installBridge(() => { repaints += 1; });
1196
+ const root = makeCheckout();
1197
+ await warmGate(b.loaded);
1198
+ const ctx = sessionCtx(root);
1199
+ // The rail read is HELD, so the header exists without a `pr` segment and the
1200
+ // repaint count measured below is the one the settlement is responsible for.
1201
+ let release = null;
1202
+ b.gh.state.railGate = new Promise((resolve) => { release = resolve; });
1203
+ await fireSessionStart(b.loaded.hooks, ctx);
1204
+ const section = registered[0];
1205
+ await drawSection(section, ctx);
1206
+ await waitFor(() => b.gh.state.railReads >= 1);
1207
+ await new Promise((resolve) => realSetTimeout(resolve, 60));
1208
+ const settled = repaints;
1209
+ assert.equal(section.meta(ctx), '2 issues', 'a read still in flight paints no `pr` count yet');
1210
+
1211
+ b.gh.state.railGate = null;
1212
+ release();
1213
+ await waitFor(() => section.meta(ctx) === '2 issues · 2 pr');
1214
+ assert.ok(repaints > settled,
1215
+ 'the settled rail read asked the bridge for the frame the new count is painted by');
1216
+ });
1217
+
1218
+ test('S4 (D15): the loader writes each bucket total beside its rows', async () => {
1219
+ installBridge();
1220
+ const rows = fiftyRows();
1221
+ const b = await boot({ railMine: rows, railMineTotal: 52, railReview: [] });
1222
+ const { registered } = installBridge();
1223
+ const root = makeCheckout();
1224
+ await warmGate(b.loaded);
1225
+ const ctx = sessionCtx(root);
1226
+ await fireSessionStart(b.loaded.hooks, ctx);
1227
+ const section = registered[0];
1228
+ await drawSection(section, ctx);
1229
+ await waitFor(() => section.meta(ctx) === '2 issues · 52 pr');
1230
+ assert.equal(section.meta(ctx), '2 issues · 52 pr', 'the live read counts the two rows its window cut');
1231
+
1232
+ const docPath = path.join(process.env.XDG_CACHE_HOME, 'odd-worktree', 'prs-rail.json');
1233
+ await waitFor(() => fs.existsSync(docPath));
1234
+ const doc = JSON.parse(fs.readFileSync(docPath, 'utf8'));
1235
+ const entry = doc.identities.find((candidate) => candidate.identity === 'github.com/myfork/project');
1236
+ assert.ok(entry, 'the read is stored under the identity it was read from');
1237
+ assert.deepEqual(entry.counts, { mine: 52, review: 0 },
1238
+ 'the totals that produced the live count sleep beside the rows');
1239
+ assert.equal(doc.version, 2, 'and the document that carries them is the version this module writes');
1240
+ });
1241
+
1242
+ test('S4 (D15): a cold start paints the stored total, so 50 rows with a total of 52 is 52 pr', async () => {
1243
+ installBridge();
1244
+ // The entry a previous process left behind: 50 rows and the total they came
1245
+ // with, under the identity this checkout proves.
1246
+ const rows = fiftyRows();
1247
+ const docPath = path.join(process.env.XDG_CACHE_HOME, 'odd-worktree', 'prs-rail.json');
1248
+ fs.mkdirSync(path.dirname(docPath), { recursive: true });
1249
+ fs.writeFileSync(docPath, JSON.stringify({
1250
+ version: 2,
1251
+ identities: [{
1252
+ identity: 'github.com/myfork/project',
1253
+ mine: rows,
1254
+ review: [],
1255
+ counts: { mine: 52, review: 0 },
1256
+ syncedAt: Date.now(),
1257
+ }],
1258
+ }));
1259
+ const b = await boot({ railMine: rows, railMineTotal: 52, railReview: [] });
1260
+ const { registered } = installBridge();
1261
+ const root = makeCheckout();
1262
+ await warmGate(b.loaded);
1263
+ const ctx = sessionCtx(root);
1264
+ let release = null;
1265
+ b.gh.state.railGate = new Promise((resolve) => { release = resolve; });
1266
+ await fireSessionStart(b.loaded.hooks, ctx);
1267
+ const section = registered[0];
1268
+ await drawSection(section, ctx);
1269
+
1270
+ await waitFor(() => section.meta(ctx) === '2 issues · 52 pr', 3000);
1271
+ assert.equal(section.meta(ctx), '2 issues · 52 pr',
1272
+ 'the cold start paints the number the live read painted, not the rows the window carried');
1273
+
1274
+ b.gh.state.railGate = null;
1275
+ release();
1276
+ await waitFor(() => b.gh.state.railReads >= 1);
1277
+ await new Promise((resolve) => realSetTimeout(resolve, 60));
1278
+ assert.equal(section.meta(ctx), '2 issues · 52 pr', 'and the live answer paints the same number');
1279
+ });
1280
+ });