pi-odd-worktree 3.9.2 → 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 (39) 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/pr-preview.js +353 -0
  10. package/lib/prs-rail-store.js +317 -0
  11. package/lib/prs-view.js +2896 -0
  12. package/package.json +1 -1
  13. package/tools/files-bridge.test.js +2 -2
  14. package/tools/files-command.test.js +1 -1
  15. package/tools/fixtures/gh-pr-connection-page.json +84 -0
  16. package/tools/fixtures/gh-pr-metadata.json +29 -0
  17. package/tools/fixtures/gh-pr-rail.json +61 -0
  18. package/tools/fixtures/gh-pr-search-page.json +82 -0
  19. package/tools/fixtures/gh-pr-view.json +159 -0
  20. package/tools/gh-issues.test.js +4 -2
  21. package/tools/gh-prs.test.js +1828 -0
  22. package/tools/issue-preview.test.js +119 -0
  23. package/tools/issues-cache-store.test.js +2 -2
  24. package/tools/issues-command.test.js +10 -3
  25. package/tools/issues-open-guard.test.js +15 -0
  26. package/tools/issues-section.test.js +618 -9
  27. package/tools/issues-view.test.js +297 -0
  28. package/tools/package-surface.test.js +18 -4
  29. package/tools/pr-preview.test.js +281 -0
  30. package/tools/prs-command.test.js +1280 -0
  31. package/tools/prs-rail-store.test.js +343 -0
  32. package/tools/prs-t10-safety.test.js +326 -0
  33. package/tools/prs-t12-safety.test.js +348 -0
  34. package/tools/prs-t13-independent.test.js +378 -0
  35. package/tools/prs-t14-safety.test.js +340 -0
  36. package/tools/prs-t15-independent.test.js +259 -0
  37. package/tools/prs-t18-safety.test.js +217 -0
  38. package/tools/prs-t7-safety.test.js +127 -0
  39. package/tools/prs-view.test.js +1462 -0
@@ -0,0 +1,340 @@
1
+ 'use strict';
2
+ // T14 (prs-panel S2): the defects the T13 verdict left open, exercised through
3
+ // the public client and panel seams — never a real `gh`, never a real write.
4
+ // D21 (fence refusal) and the D23/D24 scope rules live in the client; D22
5
+ // (reserved confirmation row) and D25/D26 (newest detail answer wins, every
6
+ // editor save gated) live in the panel.
7
+ const test = require('node:test');
8
+ const assert = require('node:assert/strict');
9
+ const { createPrsClient, setGhRunner } = require('../lib/gh-prs');
10
+ const { createPrsView } = require('../lib/prs-view');
11
+
12
+ const tick = () => new Promise(setImmediate);
13
+ function deferred() {
14
+ let resolve;
15
+ const promise = new Promise((r) => { resolve = r; });
16
+ return { promise, resolve };
17
+ }
18
+ const ok = (doc) => ({ status: 0, stdout: JSON.stringify(doc) });
19
+ const ENTERPRISE = 'github.company.example/amber/widget';
20
+ const GITHUB = 'github.com/amber/widget';
21
+
22
+ // A recorder over the client's child seam. Reads answer the shapes the client
23
+ // parses; every write is collected instead of run.
24
+ function recorder(t, fixture = {}) {
25
+ const calls = [];
26
+ const writes = [];
27
+ const run = async (_bin, argv, opts = {}) => {
28
+ const env = opts.env || {};
29
+ const call = { argv: argv.slice(), repo: env.GH_REPO, host: env.GH_HOST };
30
+ calls.push(call);
31
+ switch (argv.slice(0, 2).join(' ')) {
32
+ case 'repo view': {
33
+ const repo = env.GH_REPO || GITHUB;
34
+ return ok({ nameWithOwner: repo.split('/').slice(-2).join('/') });
35
+ }
36
+ case 'api graphql':
37
+ return ok({
38
+ data: {
39
+ search: {
40
+ issueCount: 0,
41
+ pageInfo: { hasNextPage: false, endCursor: null },
42
+ edges: [],
43
+ },
44
+ repository: {
45
+ viewerPermission: fixture.role || 'WRITE',
46
+ mergeCommitAllowed: true,
47
+ pullRequest: {
48
+ state: 'OPEN',
49
+ isDraft: false,
50
+ closingIssuesReferences: { nodes: [] },
51
+ },
52
+ },
53
+ viewer: { login: 'pat' },
54
+ },
55
+ });
56
+ case 'pr view':
57
+ return ok({
58
+ number: 64,
59
+ title: 'Ticket',
60
+ state: 'OPEN',
61
+ body: fixture.body ?? 'Summary\n',
62
+ });
63
+ default:
64
+ writes.push(call);
65
+ return ok({});
66
+ }
67
+ };
68
+ setGhRunner(run);
69
+ t.after(() => setGhRunner(null));
70
+ return { client: createPrsClient(), calls, writes };
71
+ }
72
+
73
+ function graphqlRead(calls) {
74
+ return calls.find((call) => call.argv[0] === 'api' && call.argv[1] === 'graphql');
75
+ }
76
+
77
+ // ---------------------------------------------------------------------------
78
+ // D21/D27 (S2): a body whose fence runs do not pair up refuses the edit
79
+ // outright — add and remove alike — and writes nothing. The body's loose fence
80
+ // total is odd: the only run is the one the rule refuses to guess at.
81
+ // ---------------------------------------------------------------------------
82
+ test('D21: an odd fence total this reader cannot resolve refuses the body edit', async (t) => {
83
+ const body = '```js `x`\nCloses #915\n';
84
+ const { client, writes } = recorder(t, { body });
85
+
86
+ const removed = await client.editLinkedIssues(64, { remove: [915] }, { scope: GITHUB });
87
+ assert.deepEqual(removed, {
88
+ ok: false,
89
+ error: 'the pull request body ends inside an unclosed code fence or comment',
90
+ });
91
+ const added = await client.editLinkedIssues(64, { add: [916] }, { scope: GITHUB });
92
+ assert.equal(added.ok, false);
93
+ assert.equal(added.error, 'the pull request body ends inside an unclosed code fence or comment');
94
+ assert.deepEqual(writes, [], 'nothing is written for a body this reader cannot read');
95
+ });
96
+
97
+ // ---------------------------------------------------------------------------
98
+ // D23 (S2): `gh api`/GraphQL never take their host from GH_REPO, so every
99
+ // gated read and write names the scope's API host, and a github.com scope adds
100
+ // nothing at all.
101
+ // ---------------------------------------------------------------------------
102
+ const GATED_WRITES = [
103
+ ['close', (client, options) => client.closePullRequest(64, options)],
104
+ ['merge', (client, options) => client.mergePullRequest(64, { method: 'merge', subject: 's', body: '' }, options)],
105
+ ['labels', (client, options) => client.editLabels(64, { add: ['support'] }, options)],
106
+ ['assignees', (client, options) => client.editAssignees(64, { add: ['pat'] }, options)],
107
+ ['linked', (client, options) => client.editLinkedIssues(64, { add: [915] }, options)],
108
+ ['create label', (client, options) => client.createLabel({ name: 'support' }, options)],
109
+ ];
110
+
111
+ for (const [name, write] of GATED_WRITES) {
112
+ test(`D23: ${name} carries the enterprise API host and GH_HOST on every child`, async (t) => {
113
+ const { client, calls, writes } = recorder(t, { body: 'Summary\n' });
114
+
115
+ const result = await write(client, { env: { GH_REPO: ENTERPRISE } });
116
+
117
+ assert.equal(result.ok, true, result.error);
118
+ const lookup = graphqlRead(calls);
119
+ assert.ok(lookup, 'the gated role read ran');
120
+ assert.equal(lookup.argv[3], `query=${lookup.argv[3].slice('query='.length)}`,
121
+ 'the query stays in its own argv slot');
122
+ const at = lookup.argv.indexOf('--hostname');
123
+ assert.equal(at >= 0 ? lookup.argv[at + 1] : null, 'github.company.example',
124
+ 'the GraphQL lookup names the enterprise API host');
125
+ assert.equal(lookup.host, 'github.company.example', 'and the child carries GH_HOST');
126
+ assert.equal(writes.length, 1);
127
+ assert.equal(writes[0].host, 'github.company.example', 'the write child carries GH_HOST too');
128
+ assert.equal(writes[0].repo, ENTERPRISE, 'and the pinned enterprise repository');
129
+ });
130
+ }
131
+
132
+ test('D28: a github.com scope names github.com explicitly on every child', async (t) => {
133
+ // D28 replaced the "a github.com scope adds nothing" rule: gh's own default
134
+ // may itself be an Enterprise server, so the host is always named, github.com
135
+ // included, and it can never drift in either direction.
136
+ const { client, calls, writes } = recorder(t, { body: 'Summary\n' });
137
+
138
+ assert.equal((await client.closePullRequest(64, { scope: GITHUB })).ok, true);
139
+
140
+ const lookup = graphqlRead(calls);
141
+ assert.equal(lookup.argv[lookup.argv.indexOf('--hostname') + 1], 'github.com');
142
+ assert.equal(lookup.host, 'github.com');
143
+ assert.equal(writes[0].host, 'github.com');
144
+ assert.equal(writes[0].repo, GITHUB);
145
+ });
146
+
147
+ test('D23: an enterprise page read names the host on its GraphQL child', async (t) => {
148
+ const { client, calls } = recorder(t);
149
+
150
+ const page = await client.getPullRequestPage({ bucket: 'mine' }, { env: { GH_REPO: ENTERPRISE } });
151
+
152
+ assert.equal(page.ok, true, page.error);
153
+ const lookup = graphqlRead(calls);
154
+ const at = lookup.argv.indexOf('--hostname');
155
+ assert.equal(at >= 0 ? lookup.argv[at + 1] : null, 'github.company.example');
156
+ assert.equal(lookup.host, 'github.company.example');
157
+ });
158
+
159
+ // ---------------------------------------------------------------------------
160
+ // D24 (S2): with no pin and no checkout, the ambient repository is resolved
161
+ // ONCE and pinned for the role read and the write alike.
162
+ // ---------------------------------------------------------------------------
163
+ test('D24: an ambient default that moves mid-write cannot redirect the close', async (t) => {
164
+ let ambient = GITHUB;
165
+ const calls = [];
166
+ const writes = [];
167
+ setGhRunner(async (_bin, argv, opts = {}) => {
168
+ const env = opts.env || {};
169
+ const call = { argv: argv.slice(), repo: env.GH_REPO || ambient };
170
+ calls.push(call);
171
+ if (argv.slice(0, 2).join(' ') === 'repo view') {
172
+ return ok({ nameWithOwner: call.repo.split('/').slice(-2).join('/') });
173
+ }
174
+ if (argv.slice(0, 2).join(' ') === 'api graphql') {
175
+ ambient = 'github.com/copper/widget';
176
+ return ok({ data: { repository: { viewerPermission: 'WRITE', pullRequest: { state: 'OPEN' } } } });
177
+ }
178
+ writes.push(call);
179
+ return ok({});
180
+ });
181
+ t.after(() => setGhRunner(null));
182
+
183
+ const result = await createPrsClient().closePullRequest(64);
184
+
185
+ assert.equal(result.ok, true, result.error);
186
+ assert.equal(graphqlRead(calls).repo, GITHUB);
187
+ assert.equal(writes.length, 1);
188
+ assert.equal(writes[0].repo, GITHUB, 'the write runs in the repository the role read proved');
189
+ });
190
+
191
+ // ---------------------------------------------------------------------------
192
+ // The panel seams: a small harness with a held reload, so a detail read can be
193
+ // ordered by hand.
194
+ // ---------------------------------------------------------------------------
195
+ const METHODS = { merge: true };
196
+ const ALL_CAPS = {
197
+ canClosePullRequests: true,
198
+ canMerge: true,
199
+ canEditLabels: true,
200
+ canCreateLabels: true,
201
+ canEditAssignees: true,
202
+ canEditLinkedIssues: true,
203
+ };
204
+ const row = (number, state = 'open') => ({ number, title: `Ticket-${number}`, author: 'someone-else', state });
205
+ const detail = (number, props = {}) => ({
206
+ ok: true,
207
+ pullRequest: {
208
+ ...row(number),
209
+ body: 'Summary',
210
+ isDraft: false,
211
+ mergeMethods: METHODS,
212
+ mergeDefaults: { merge: { subject: 'Subject', body: 'Details' } },
213
+ linkedIssues: [915],
214
+ ...props,
215
+ },
216
+ permissions: props.permissions || ALL_CAPS,
217
+ });
218
+ const page = (rows) => ({ ok: true, rows, hasMore: false, totalCount: rows.length });
219
+ const keys = (view, ...inputs) => inputs.forEach((input) => view.handleInput(input));
220
+ const display = (view, width = 130) => view.render(width).join('\n');
221
+
222
+ async function panel(options = {}) {
223
+ const held = deferred();
224
+ const writes = [];
225
+ const others = Array.from({ length: 30 }, (_, index) => row(100 + index));
226
+ let opens = 0;
227
+ let read = (number) => detail(number);
228
+ const actions = Object.fromEntries(
229
+ ['close', 'merge', 'commentPullRequest', 'editLinkedIssues', 'editLabels', 'editAssignees']
230
+ .map((name) => [name, (...args) => { writes.push([name, ...args]); return { ok: true }; }]),
231
+ );
232
+ const view = createPrsView({
233
+ rowsAvailable: () => (typeof options.rowsAvailable === 'function'
234
+ ? options.rowsAvailable()
235
+ : (options.rowsAvailable ?? 19)),
236
+ loadPullRequestPage: ({ bucketId }) => (bucketId === 'mine' && (opens += 1) === 2
237
+ ? held.promise
238
+ : page([row(64), ...others])),
239
+ loadPullRequest: (number, opts) => read(number, opts),
240
+ labels: [{ name: 'support' }],
241
+ loadAssignees: () => ({ ok: true, users: [{ login: 'pat' }] }),
242
+ actions,
243
+ });
244
+ await tick();
245
+ return { view, held, writes, others, readFrom: (fn) => { read = fn; } };
246
+ }
247
+
248
+ // ---------------------------------------------------------------------------
249
+ // D22 (S2): the captured target's own line is reserved a pane row in a short
250
+ // frame, and a frame too short to hold it refuses to confirm.
251
+ // ---------------------------------------------------------------------------
252
+ test('D22: a short frame still paints Confirm merge #N, and the merge proceeds', async () => {
253
+ const { view, held, writes, others } = await panel({ rowsAvailable: () => 10 });
254
+ keys(view, 'r', 'm');
255
+ held.resolve(page(others));
256
+ await tick();
257
+
258
+ const rendered = display(view);
259
+ assert.match(rendered, /Confirm merge #64/);
260
+ keys(view, 'ctrl+s');
261
+ await tick();
262
+ assert.deepEqual(writes.map((call) => call.slice(0, 2)), [['merge', 64]]);
263
+ });
264
+
265
+ test('D22: a frame too short to hold the confirmation refuses to confirm', async () => {
266
+ const { view, writes } = await panel({ rowsAvailable: () => 6 });
267
+
268
+ keys(view, 'm', 'ctrl+s');
269
+ await tick();
270
+ assert.deepEqual(writes, [], 'a merge in a frame that cannot name its target writes nothing');
271
+ assert.match(display(view), /the terminal is too short to confirm this pull request/);
272
+
273
+ // The step stays open so the reader can enlarge the terminal and retry.
274
+ assert.equal(view.state.mode, 'merge');
275
+ keys(view, 'escape', 'x', 'enter');
276
+ await tick();
277
+ assert.deepEqual(writes, [], 'the same rule holds for the close confirmation');
278
+ assert.match(display(view), /the terminal is too short to confirm this pull request/);
279
+
280
+ keys(view, 'escape', 'c', 'h', 'i', 'ctrl+s');
281
+ await tick();
282
+ assert.deepEqual(writes, [], 'and for the composer, which also names its target');
283
+ assert.match(display(view), /the terminal is too short to confirm this pull request/);
284
+ });
285
+
286
+ // ---------------------------------------------------------------------------
287
+ // D25 (S2): the NEWEST detail read for a number decides, in both directions.
288
+ // ---------------------------------------------------------------------------
289
+ test('D25: a stale negative read never blocks a newer positive answer', async () => {
290
+ const { view, held, writes, others, readFrom } = await panel();
291
+ const stale = deferred();
292
+ const newer = deferred();
293
+ let reads = 0;
294
+ keys(view, 'r', 'x');
295
+ readFrom((number) => (number !== 64 ? detail(number) : (++reads === 1 ? stale.promise : newer.promise)));
296
+ keys(view, 'enter');
297
+ held.resolve(page([row(64), ...others]));
298
+ await tick();
299
+ newer.resolve(detail(64));
300
+ await tick();
301
+ stale.resolve({ ok: false, error: 'gone' });
302
+ await tick();
303
+
304
+ assert.deepEqual(writes.map((call) => call.slice(0, 2)), [['close', 64]],
305
+ 'the newest positive answer authorizes the close');
306
+ });
307
+
308
+ // ---------------------------------------------------------------------------
309
+ // D26 (S2): every editor save is gated on a fresh read, label creation
310
+ // included, whatever a reorder did to the list.
311
+ // ---------------------------------------------------------------------------
312
+ test('D26: a new-label save after a reorder re-reads the creation capability', async () => {
313
+ const { view, held, writes, others, readFrom } = await panel();
314
+ keys(view, 'r', 'l', 'n', 'N', 'e', 'w', 'enter');
315
+ readFrom((number) => (number === 64
316
+ ? detail(64, { permissions: { ...ALL_CAPS, canCreateLabels: false } })
317
+ : detail(number)));
318
+ held.resolve(page([...others, row(64)]));
319
+ await tick();
320
+ keys(view, 'ctrl+s');
321
+ await tick();
322
+
323
+ assert.deepEqual(writes, []);
324
+ assert.match(display(view), /new labels cannot be created: this repository permission is missing/);
325
+ });
326
+
327
+ test('D26: an assignee save on a pull request merged meanwhile writes nothing', async () => {
328
+ const { view, held, writes, others, readFrom } = await panel();
329
+ keys(view, 'r', 'a');
330
+ await tick();
331
+ keys(view, 'space');
332
+ readFrom((number) => (number === 64 ? detail(64, { state: 'merged' }) : detail(number)));
333
+ held.resolve(page(others));
334
+ await tick();
335
+ keys(view, 'ctrl+s');
336
+ await tick();
337
+
338
+ assert.deepEqual(writes, []);
339
+ assert.match(display(view), /pull request #64 is not open; its assignees cannot be edited/);
340
+ });
@@ -0,0 +1,259 @@
1
+ 'use strict';
2
+ const assert = require('node:assert/strict');
3
+ const test = require('node:test');
4
+ const {createPrsClient} = require('../lib/gh-prs');
5
+ const issuesClient = require('../lib/gh-issues');
6
+ const {createPrsView} = require('../lib/prs-view');
7
+ const {createIssuesView} = require('../lib/issues-view');
8
+ const {createIssuesSection} = require('../lib/issues-section');
9
+ const tick = () => new Promise(setImmediate);
10
+ const hold = () => { let resolve; return {promise: new Promise(r => { resolve = r; }), release: value => resolve(value)}; };
11
+ const ok = data => ({status: 0, stdout: JSON.stringify(data)});
12
+ const N = 381, I = 259;
13
+ const publicScope = 'github.com/pine/ledger', enterprise = 'github.company.example';
14
+ const entScope = `${enterprise}/pine/ledger`;
15
+ const caps = {canClosePullRequests:true, canMerge:true, canEditLinkedIssues:true, canEditLabels:true, canEditAssignees:true, canCreateLabels:true};
16
+ const row = (number=N, state='open') => ({number,state,title:`Ledger-${number}`,author:'someone-else'});
17
+ const detail = (number=N, changes={}) => ({ok:true,pullRequest:{...row(number),isDraft:false,permissions:caps,linkedIssues:[I],mergeMethods:{squash:true,rebase:true},mergeDefaults:{squash:{subject:'Ledger title',body:'Ledger body'}},...changes}});
18
+ const page = rows => ({ok:true,rows,hasMore:false,totalCount:rows.length});
19
+ const keys = (v,...inputs) => inputs.forEach(input=>v.handleInput(input));
20
+ const frame = (v,w=148) => v.render(w).join('\n');
21
+ function client(t, f={}) {
22
+ const c=createPrsClient(f.delegates?{issues:issuesClient}:{});
23
+ const calls=[],writes=[];
24
+ c.setGhRunner((_bin,argv,opts)=>{
25
+ const env=opts.env||{};
26
+ const repo=env.GH_REPO||f.ambient?.()||publicScope;
27
+ const apiHost=argv.includes('--hostname')?argv[argv.indexOf('--hostname')+1]:(env.GH_HOST||f.defaultApiHost||'github.com');
28
+ const call={argv,repo,apiHost,env};calls.push(call);
29
+ switch(argv.slice(0,2).join(' ')) {
30
+ case 'repo view': return ok({nameWithOwner:repo.split('/').slice(-2).join('/'),url:`https://${repo}`});
31
+ case 'pr view': return f.prView?.(call)||ok({...row(N,'OPEN'),isDraft:false,body:f.body??'Preamble\n'});
32
+ case 'label list': return ok([]);
33
+ case 'api graphql': {
34
+ assert.match(argv[3],/^query=query\b/);
35
+ f.afterRead?.(call);
36
+ return ok({data:{viewer:{login:'lee'},repository:{viewerPermission:f.permission?.(call)||'WRITE',mergeCommitAllowed:true,squashMergeAllowed:true,...(argv[3].includes('pullRequest(number:') ? {pullRequest:{isDraft:false,state:f.state?.(call)||'OPEN',closingIssuesReferences:{nodes:[{number:I}]}}} : {}),assignableUsers:{nodes:[],pageInfo:{hasNextPage:false}}},search:{edges:[],pageInfo:{hasNextPage:false},issueCount:0},mine:{nodes:[],issueCount:0},review:{nodes:[],issueCount:0}}});
37
+ }
38
+ default: writes.push(call); return ok({});
39
+ }
40
+ });
41
+ t.after(()=>c.setGhRunner(null));
42
+ return {c,calls,writes};
43
+ }
44
+ const publicOpts={scope:publicScope,env:{}};
45
+ const mer=(c,o)=>c.mergePullRequest(N,{method:'squash',subject:'Exact subject',body:''},o);
46
+ const writesByKind={
47
+ close:(c,o)=>c.closePullRequest(N,o), merge:mer,
48
+ linked:(c,o)=>c.editLinkedIssues(N,{add:[I]},o),
49
+ labels:(c,o)=>c.editLabels(N,{add:['triage']},o),
50
+ assignees:(c,o)=>c.editAssignees(N,{add:['lee']},o),
51
+ create:(c,o)=>c.createLabel({name:'triage'},o),
52
+ };
53
+ // D27 replaced the fence parser: only a line this panel wrote — carrying its
54
+ // marker — is ever removed, so the real declaration below carries one while the
55
+ // code example does not. Both bodies pair their fence runs, so the edit is read.
56
+ for(const [title,original] of [
57
+ ['tilde CRLF',`Intro\r\n ~~~text\r\nCloses #${I}\r\n ~~~\r\n`],
58
+ ['indent and nested list',`Intro\n\n- List\n - Nested\n ~~~text\n Closes #${I}\n ~~~\n`],
59
+ ]) test(`D21 paired ${title}: preserve every byte except the real declaration`,async t=>{
60
+ const eol=original.includes('\r\n')?'\r\n':'\n';
61
+ const {c,writes}=client(t,{body:`${original}${eol}Closes #${I} <!-- odd-worktree:linked -->${eol}Tail${eol}`});
62
+ await c.editLinkedIssues(N,{remove:[I]},publicOpts);
63
+ assert.deepEqual(writes.map(x=>x.argv),[['pr','edit',String(N),'--body',`${original}${eol}Tail${eol}`]]);
64
+ });
65
+ test('D21 odd unclosed fence: never append a link inside it',async t=>{
66
+ const {c,writes}=client(t,{body:`Intro\n\n ~~~text\nCloses #${I}\n`});
67
+ const r=await c.editLinkedIssues(N,{add:[I+1]},publicOpts);
68
+ assert.deepEqual(writes,[]); assert.equal(r.ok,false);
69
+ // D27's single refusal sentence: an unpaired fence run or an unbalanced
70
+ // comment means the body cannot be read, so nothing is added.
71
+ assert.equal(r.error,'the pull request body ends inside an unclosed code fence or comment');
72
+ });
73
+ test('D21/S2 body data: info string inside a backtick fence is not a closing fence',async t=>{
74
+ const body='```text\n```not-a-closer\n'+`Closes #${I}\n`+'```\n\nUnrelated prose.\n';
75
+ const {c,writes}=client(t,{body});
76
+ await c.editLinkedIssues(N,{remove:[I]},publicOpts);
77
+ assert.deepEqual(writes.map(w=>w.argv),[]);
78
+ });
79
+ test('D21/S2 body data: HTML comment retains its closing-keyword example',async t=>{
80
+ const body=`<!--\nTemplate example:\nCloses #${I}\n-->\n\nUnrelated prose.\n`;
81
+ const {c,writes}=client(t,{body});
82
+ await c.editLinkedIssues(N,{remove:[I]},publicOpts);
83
+ assert.deepEqual(writes.map(w=>w.argv),[]);
84
+ });
85
+ test('S2 body data: concurrent author edit is not overwritten by the link command',async t=>{
86
+ let body='Original text\n';
87
+ const {c,writes}=client(t,{prView:()=>{
88
+ const read=body;
89
+ body='Original text\nAuthor added this while the read completed.\n';
90
+ return ok({body:read});
91
+ }});
92
+ await c.editLinkedIssues(N,{add:[I]},publicOpts);
93
+ if(writes.length) assert.ok(writes[0].argv[4].includes('Author added this'),JSON.stringify(writes[0].argv));
94
+ });
95
+ for(const [name,run] of Object.entries(writesByKind)) test(`D23 enterprise GH_REPO/GH_HOST and pin: ${name}`,async t=>{
96
+ const {c,calls,writes}=client(t,{delegates:true});
97
+ assert.equal((await run(c,{env:{GH_REPO:entScope,GH_HOST:enterprise}})).ok,true);
98
+ assert.equal(writes.length,1);
99
+ for(const call of calls){
100
+ assert.equal(call.repo,entScope);
101
+ assert.equal(call.env.GH_HOST,enterprise);
102
+ if(call.argv[0]==='api') assert.equal(call.argv[call.argv.indexOf('--hostname')+1],enterprise);
103
+ }
104
+ if(name==='merge') assert.deepEqual(writes[0].argv,['pr','merge',String(N),'--squash','--subject','Exact subject','--body','']);
105
+ });
106
+ test('D23 enterprise read surface: page, metadata, assignable users, labels and rail',async t=>{
107
+ const {c,calls,writes}=client(t,{delegates:true});
108
+ const opts={scope:entScope,env:{GH_REPO:entScope,GH_HOST:enterprise}};
109
+ for(const result of await Promise.all([c.getPullRequestPage({bucket:'review'},opts),c.getPullRequest(N,{includeMetadata:true},opts),c.listAssignableUsers(opts),c.listLabels(opts),c.listRailPullRequests({},opts)])) assert.equal(result.ok,true);
110
+ assert.deepEqual(writes,[]);
111
+ for(const call of calls) {
112
+ assert.equal(call.env.GH_HOST,enterprise);
113
+ if(call.argv[0]==='api') assert.equal(call.apiHost,enterprise,call.argv[3]);
114
+ }
115
+ });
116
+ test('D23/S2 explicit github.com pin cannot use Enterprise permission to authorize close',async t=>{
117
+ const {c,calls,writes}=client(t,{defaultApiHost:enterprise,permission:({apiHost})=>apiHost===enterprise?'WRITE':'READ'});
118
+ await c.closePullRequest(N,publicOpts);
119
+ assert.deepEqual(writes.map(w=>[w.repo,w.argv]),[],JSON.stringify(calls.map(w=>[w.repo,w.apiHost,w.argv.slice(0,2)])));
120
+ });
121
+ test('D24 ambient repository changes after role read: close stays on original repository',async t=>{
122
+ let ambient=publicScope;
123
+ const {c,calls,writes}=client(t,{ambient:()=>ambient,afterRead:()=>{ambient='github.com/oak/ledger';}});
124
+ assert.equal((await c.closePullRequest(N,{env:{}})).ok,true);
125
+ assert.deepEqual(calls.map(call=>call.repo),[publicScope,publicScope,publicScope]);
126
+ assert.deepEqual(writes.map(w=>w.argv),[['pr','close',String(N)]]);
127
+ });
128
+ test('D24/S2 ambient enterprise resolution pins the resolved repository host as well as its slug',async t=>{
129
+ let ambient=entScope;
130
+ const {c,writes}=client(t,{ambient:()=>ambient,defaultApiHost:enterprise,afterRead:()=>{ambient=`${enterprise}/oak/ledger`;}});
131
+ await c.closePullRequest(N,{env:{}});
132
+ assert.ok(writes.every(w=>w.repo===entScope),JSON.stringify(writes.map(w=>[w.repo,w.argv])));
133
+ });
134
+ const tasks={
135
+ close:{edit:['x'],save:'enter',seam:'close',anchor:`Confirm close #${N}`},
136
+ merge:{edit:['m'],save:'ctrl+s',seam:'merge',anchor:`Confirm merge #${N}`},
137
+ comment:{edit:['c','z'],save:'ctrl+s',seam:'commentPullRequest',anchor:`Comment on #${N}`},
138
+ linked:{edit:['i','space'],save:'ctrl+s',seam:'editLinkedIssues'},
139
+ labels:{edit:['l','space'],save:'ctrl+s',seam:'editLabels'},
140
+ assignees:{edit:['a','space'],save:'ctrl+s',seam:'editAssignees'},
141
+ create:{edit:['l','n','z','e','d','enter'],save:'ctrl+s',seam:'editLabels'},
142
+ };
143
+ async function panel(extra={}) {
144
+ const reload=hold(),writes=[],reads=[];
145
+ const others=Array.from({length:20},(_,i)=>row(N+i+1));
146
+ let mine=0,source=number=>detail(number),height=12;
147
+ const actions=Object.fromEntries(Object.values(tasks).map(task=>[task.seam,(...a)=>{writes.push([task.seam,...a]); return {ok:true};}]));
148
+ const v=createPrsView({rowsAvailable:()=>height,loadPullRequestPage:({bucketId})=>bucketId==='mine'&&++mine===2?reload.promise:page([row(),...others]),loadPullRequest:(n,opt)=>{reads.push([n,opt]);return source(n,opt);},loadAssignees:()=>({ok:true,users:[{login:'lee'}]}),labels:[{name:'triage'}],actions,...extra});
149
+ await tick();
150
+ return {v,writes,reads,reload,others,load:fn=>{source=fn;},resize:rows=>{height=rows;}};
151
+ }
152
+ for(const name of ['close','merge','comment']) test(`D22 short frame, removed target: ${name} names captured #${N}`,async()=>{
153
+ const {v,writes,reload,others}=await panel(); const task=tasks[name];
154
+ keys(v,'r',...task.edit);
155
+ reload.release(page(others)); await tick();
156
+ assert.equal(v.render(148).length,12);
157
+ assert.ok(frame(v).includes(task.anchor),frame(v));
158
+ keys(v,task.save);await tick();
159
+ assert.deepEqual(writes.map(w=>w.slice(0,2)),[[task.seam,N]]);
160
+ if(name==='merge') assert.deepEqual(writes[0][2],{method:'squash',subject:'Ledger title',body:'Ledger body'});
161
+ });
162
+ // MINOR advisory (T15 verdict): at 24 columns the target line clips, the captured PR is still the one dispatched.
163
+ test.todo('D22 merge: shrink width after opening; no blind confirmation',async()=>{
164
+ const {v,writes}=await panel();keys(v,'m');
165
+ assert.match(frame(v),/Confirm merge/);
166
+ const narrow=frame(v,24);assert.doesNotMatch(narrow,/Confirm merge/);
167
+ keys(v,'ctrl+s');await tick();
168
+ assert.deepEqual(writes,[],`${narrow}\n${JSON.stringify(writes)}`);
169
+ });
170
+ for(const name of ['close','merge','linked','labels','assignees','create']) test(`D25/D26 newest negative detail wins a pending save: ${name}`,async()=>{
171
+ const {v,writes,reads,reload,load,others}=await panel();
172
+ const older=hold(),newer=hold();let read=0;
173
+ const task=tasks[name];keys(v,'r',...task.edit);await tick();
174
+ load(n=>n!==N?detail(n):++read===1?older.promise:newer.promise);
175
+ const start=reads.length;keys(v,task.save);await tick();
176
+ reload.release(page([row(),...others.reverse()]));await tick();
177
+ assert.deepEqual(reads.slice(start).filter(([n])=>n===N),[[N,{refresh:true}],[N,{refresh:true}]]);
178
+ newer.release(detail(N,name==='create'?{permissions:{...caps,canCreateLabels:false}}:name==='assignees'?{state:'closed'}:{permissions:{}}));await tick();
179
+ older.release(detail());await tick();
180
+ assert.deepEqual(writes,[]);
181
+ });
182
+ test('S2 merge method revoked while editor open: no merge seam',async()=>{
183
+ const {v,writes,load}=await panel();keys(v,'m');
184
+ load(n=>detail(n,{mergeMethods:{rebase:true}}));
185
+ keys(v,'ctrl+s');await tick();
186
+ assert.deepEqual(writes,[]);
187
+ });
188
+ for(const kind of ['labels','assignees']) test(`S2 fresh client access must not emit ${kind} edit for closed PR`,async t=>{
189
+ const {c,writes}=client(t,{state:()=> 'CLOSED'});
190
+ await writesByKind[kind](c,publicOpts);
191
+ assert.deepEqual(writes.map(w=>w.argv),[]);
192
+ });
193
+ test('S2 real client detail: newer GraphQL CLOSED must refuse the label seam despite older pr view OPEN',async t=>{
194
+ let state='OPEN';
195
+ const {c,writes:children}=client(t,{state:()=>state});
196
+ const {v,writes}=await panel({loadPullRequest:n=>c.getPullRequest(n,{includeMetadata:true},publicOpts)});
197
+ await tick();keys(v,'l','space');state='CLOSED';keys(v,'ctrl+s');await tick();
198
+ assert.deepEqual(children,[]);assert.deepEqual(writes,[]);
199
+ });
200
+ test('S7 enter inserts exactly once and only from list mode in both views',()=>{
201
+ const calls=[];const actions={insert:text=>calls.push(text)};
202
+ const issue={number:I,title:'Ledger issue',state:'open'};
203
+ const pr=createPrsView({pages:[{label:'mine',rows:[row()]}],loadPullRequest:()=>detail(),actions});
204
+ const iv=createIssuesView({issues:[issue],loadIssue:()=>({ok:true,issue}),actions});
205
+ for(const v of [pr,iv]) { frame(v); keys(v,'/','enter'); assert.equal(calls.length,0); }
206
+ keys(pr,'c','enter');keys(iv,'c','enter');assert.equal(calls.length,0);
207
+ for(const v of [pr,iv])keys(v,'escape','y','enter');
208
+ assert.deepEqual(calls,[`PR #${N}`,`ISSUE #${I}`]);
209
+ });
210
+ test('S5/S2 rail must not close a same-number PR in a different repo from the linked source',async t=>{
211
+ const target='github.com/oak/payroll';
212
+ const parse={mine:{issueCount:1,nodes:[{number:I,title:'Issue linked to another repository',state:'OPEN',url:`https://${publicScope}/issues/${I}`,timelineItems:{nodes:[{source:{__typename:'PullRequest',number:N,repository:{nameWithOwner:'oak/payroll'},url:`https://${target}/pull/${N}`}}]}}]},assigned:{issueCount:0,nodes:[]},involved:{issueCount:0,nodes:[]}};
213
+ issuesClient.setGhRunner((_bin,argv)=>{
214
+ assert.deepEqual(argv.slice(0,2),['api','graphql']);assert.match(argv[3],/^query=query\b/);return ok({data:parse});
215
+ });
216
+ t.after(()=>issuesClient.setGhRunner(null));
217
+ const loaded=await issuesClient.listRelatedIssues({first:5},publicOpts); assert.equal(loaded.ok,true,JSON.stringify(loaded));
218
+ const writes=[],routes=[];let opened;
219
+ const rail=createIssuesSection({schedule:fn=>fn(),load:()=>({ok:true,identity:publicScope,issues:loaded.buckets.mine.issues}),open:(number,hint)=>{
220
+ routes.push([number,hint]);
221
+ if(!hint?.pullRequest)return;
222
+ // Extension dispatches `/prs <number>` in the current checkout; a hint
223
+ // without repository identity therefore opens this repo's lookalike PR.
224
+ const openedScope=hint.scope||publicScope;
225
+ opened=createPrsView({loadPullRequestPage:()=>page([row(hint.pullRequest)]),initialPullRequest:hint.pullRequest,loadPullRequest:n=>detail(n),actions:{close:(n)=>{writes.push([openedScope,n]);return {ok:true};}}});
226
+ }});
227
+ t.after(()=>rail.dispose());
228
+ await rail.refresh(); await rail.section.lines()[0].onClick();
229
+ if(opened){await tick();frame(opened);keys(opened,'x','enter');await tick();}
230
+ assert.ok(routes.length,JSON.stringify(rail.section.lines()));
231
+ assert.ok(writes.every(([scope,num])=>scope===target&&num===N),JSON.stringify(writes));
232
+ });
233
+ test('S6/S2 cross-repository clickable PR must not close the current repository lookalike',async t=>{
234
+ const linkedScope='github.com/oak/payroll';
235
+ const issueRow={number:I,title:'Issue with cross-repository closer',state:'OPEN',url:`https://${publicScope}/issues/${I}`};
236
+ issuesClient.setGhRunner((_bin,argv)=>{
237
+ if(argv.slice(0,2).join(' ')==='issue view') return ok(issueRow);
238
+ assert.deepEqual(argv.slice(0,2),['api','graphql']); assert.match(argv[3],/^query=query\b/);
239
+ const ref={number:N,repository:{nameWithOwner:'oak/payroll'},url:`https://${linkedScope}/pull/${N}`};
240
+ return ok({data:{repository:{viewerPermission:'WRITE',issue:{assignees:{nodes:[],pageInfo:{hasNextPage:false}},closedByPullRequestsReferences:{nodes:[ref],pageInfo:{hasNextPage:false}},projectItems:{nodes:[],pageInfo:{hasNextPage:false}}}}}});
241
+ });
242
+ t.after(()=>issuesClient.setGhRunner(null));
243
+ const loaded=await issuesClient.getIssue(I,{...publicOpts,includeMetadata:true});
244
+ assert.equal(loaded.ok,true);
245
+ const writes=[];let opened;
246
+ const v=createIssuesView({issues:[loaded.issue],loadIssue:()=>loaded,actions:{openLinked:link=>{
247
+ assert.equal(link.kind,'pullRequest');assert.equal(link.number,N);
248
+ const repo=link.scope||publicScope;
249
+ opened=createPrsView({initialPullRequest:N,loadPullRequestPage:()=>page([row()]),loadPullRequest:n=>detail(n),actions:{close:n=>{writes.push([repo,n]);return {ok:true};}}});
250
+ }}});
251
+ const lines=v.render(148);
252
+ const y=lines.findIndex(line=>line.includes('linked PRs:'));
253
+ if(y<0) return; // A safe implementation can withhold an unpinnable target.
254
+ const x=lines[y].indexOf(`#${N}`,lines[y].indexOf('linked PRs:'));
255
+ assert.ok(x>=0);
256
+ v.handleMouse({type:'click',button:'left',x,y,width:148,height:lines.length});
257
+ if(opened){await tick();frame(opened);keys(opened,'x','enter');await tick();}
258
+ assert.ok(writes.every(([scope,n])=>scope===linkedScope&&n===N),JSON.stringify(writes));
259
+ });