pi-odd-worktree 2.1.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +54 -319
  2. package/extensions/odd-worktree-tools.ts +4145 -2529
  3. package/lib/bash-activity.js +1164 -0
  4. package/lib/bash-design.js +684 -0
  5. package/lib/bash-destructive.js +559 -0
  6. package/lib/bash-frame.js +205 -0
  7. package/lib/card-content.js +23 -0
  8. package/lib/card-style.js +175 -0
  9. package/lib/checkout-facts.js +30 -70
  10. package/lib/codegraph-card-preview.js +628 -0
  11. package/lib/codegraph-card.js +515 -0
  12. package/lib/codegraph-compaction.js +76 -0
  13. package/lib/codegraph-daemon.js +246 -0
  14. package/lib/codegraph-edit-sync.js +182 -0
  15. package/lib/codegraph-guard-target.js +337 -0
  16. package/lib/codegraph-guard.js +211 -0
  17. package/lib/codegraph-index.js +1020 -0
  18. package/lib/codegraph-lock.js +607 -0
  19. package/lib/codegraph-mcp-config.js +134 -0
  20. package/lib/codegraph-mcp.js +123 -0
  21. package/lib/codegraph-paths.js +69 -0
  22. package/lib/codegraph-prompt/explore.md +11 -0
  23. package/lib/codegraph-prompt/fix.md +6 -0
  24. package/lib/codegraph-prompt/generic.md +8 -0
  25. package/lib/codegraph-prompt/judge.md +9 -0
  26. package/lib/codegraph-prompt/orchestrator.md +17 -0
  27. package/lib/codegraph-prompt/verify.md +10 -0
  28. package/lib/codegraph-prompt/worker.md +7 -0
  29. package/lib/codegraph-role.js +55 -0
  30. package/lib/codegraph-rules.js +146 -0
  31. package/lib/codegraph-session.js +303 -383
  32. package/lib/codegraph-warmup.js +139 -0
  33. package/lib/file-card-markdown.js +141 -0
  34. package/lib/file-card-resolver.js +245 -0
  35. package/lib/file-card.js +659 -0
  36. package/lib/files-index.js +387 -0
  37. package/lib/files-insert.js +81 -0
  38. package/lib/files-orders.js +326 -0
  39. package/lib/files-picker-view.js +1416 -0
  40. package/lib/files-preview.js +338 -0
  41. package/lib/files-scope-detail.js +171 -0
  42. package/lib/files-scope-view.js +507 -0
  43. package/lib/gh-issues.js +308 -14
  44. package/lib/issue-preview.js +26 -7
  45. package/lib/issues-bash-mutation.js +206 -0
  46. package/lib/issues-cache-store.js +261 -0
  47. package/lib/issues-section.js +710 -0
  48. package/lib/issues-view.js +649 -52
  49. package/lib/odd-prompt/odd-worktrees.md +21 -0
  50. package/lib/odd-worktrees-prompt.js +10 -28
  51. package/lib/related-issues-cache.js +210 -0
  52. package/lib/shell-card.js +825 -0
  53. package/lib/skill-odd-card.js +183 -0
  54. package/lib/tui-paint.js +4 -5
  55. package/lib/warp-create-panel.js +538 -250
  56. package/lib/warp-create-picker.js +56 -9
  57. package/lib/warp-delete-confirm.js +19 -28
  58. package/lib/warp-selector-view.js +160 -82
  59. package/lib/which-command.js +90 -0
  60. package/lib/worktree-card.js +267 -897
  61. package/lib/worktree-cards.js +383 -0
  62. package/lib/worktree-create.js +287 -0
  63. package/lib/worktree-git.js +3 -3
  64. package/lib/worktree-guard.js +548 -0
  65. package/lib/worktree-hooks.js +421 -712
  66. package/lib/worktree-list.js +120 -0
  67. package/lib/worktree-registry.js +162 -879
  68. package/lib/{worktree-close-herdr.js → worktree-remove.js} +9 -11
  69. package/lib/worktree-setup-runner.js +376 -0
  70. package/lib/worktree-setup.js +140 -0
  71. package/lib/worktree-warp-busy.js +462 -85
  72. package/lib/worktree-warp-sessions.js +1 -2
  73. package/package.json +2 -2
  74. package/tools/bash-activity.test.js +1419 -0
  75. package/tools/bash-design.test.js +1091 -0
  76. package/tools/bash-destructive.test.js +139 -0
  77. package/tools/card-content.test.js +44 -0
  78. package/tools/card-style.test.js +298 -0
  79. package/tools/codegraph-card-preview.test.js +254 -0
  80. package/tools/codegraph-card.test.js +1080 -0
  81. package/tools/codegraph-compaction.test.js +378 -0
  82. package/tools/codegraph-daemon.test.js +248 -0
  83. package/tools/codegraph-edit-sync.test.js +295 -0
  84. package/tools/codegraph-guard-target.test.js +174 -0
  85. package/tools/codegraph-guard.test.js +238 -0
  86. package/tools/codegraph-index.test.js +1948 -0
  87. package/tools/codegraph-lock.test.js +932 -0
  88. package/tools/codegraph-mcp-config.test.js +181 -0
  89. package/tools/codegraph-mcp.test.js +194 -0
  90. package/tools/codegraph-paths.test.js +44 -0
  91. package/tools/codegraph-role.test.js +30 -0
  92. package/tools/codegraph-rules.test.js +250 -0
  93. package/tools/codegraph-session.test.js +660 -391
  94. package/tools/codegraph-warmup.test.js +316 -0
  95. package/tools/commands.test.js +510 -31
  96. package/tools/file-card-markdown.test.js +188 -0
  97. package/tools/file-card.test.js +1289 -0
  98. package/tools/files-bridge.test.js +575 -0
  99. package/tools/files-command.test.js +610 -0
  100. package/tools/files-index.test.js +473 -0
  101. package/tools/files-insert.test.js +139 -0
  102. package/tools/files-orders.test.js +597 -0
  103. package/tools/files-picker-view.test.js +1871 -0
  104. package/tools/files-preview.test.js +452 -0
  105. package/tools/files-scope-detail.test.js +264 -0
  106. package/tools/files-scope-view.test.js +614 -0
  107. package/tools/fixtures/card-codegraph-outputs.js +110 -0
  108. package/tools/fixtures/codegraph-cli-stub.js +16 -0
  109. package/tools/fixtures/codegraph-init-process.js +28 -0
  110. package/tools/fixtures/codegraph-lock-worker.js +117 -0
  111. package/tools/fixtures/daemon-fake.js +98 -0
  112. package/tools/fixtures/daemon-mcp-server.js +39 -0
  113. package/tools/fixtures/daemon-warmup-worker.js +12 -0
  114. package/tools/fixtures/load-extension.js +136 -3
  115. package/tools/gh-issues-feedback.test.js +31 -7
  116. package/tools/gh-issues.test.js +391 -1
  117. package/tools/issue-preview.test.js +44 -7
  118. package/tools/issues-bash-mutation.test.js +101 -0
  119. package/tools/issues-cache-store.test.js +222 -0
  120. package/tools/issues-command.test.js +1512 -66
  121. package/tools/issues-open-guard.test.js +1096 -0
  122. package/tools/issues-section.test.js +4195 -0
  123. package/tools/issues-seed-query-regression.test.js +67 -0
  124. package/tools/issues-view.test.js +1489 -60
  125. package/tools/odd-worktrees-prompt.test.js +98 -65
  126. package/tools/package-surface.test.js +431 -36
  127. package/tools/related-issues-cache.test.js +324 -0
  128. package/tools/shell-card.test.js +834 -0
  129. package/tools/skill-odd-card.test.js +200 -0
  130. package/tools/t5-session-identity.test.js +44 -22
  131. package/tools/warp-busy-guard.test.js +2565 -309
  132. package/tools/warp-create-panel.test.js +499 -74
  133. package/tools/warp-create-picker.test.js +101 -5
  134. package/tools/warp-delete-confirm.test.js +49 -15
  135. package/tools/warp-empty-session.test.js +0 -1
  136. package/tools/warp-fallback-regression.test.js +533 -0
  137. package/tools/warp-selector-view.test.js +460 -196
  138. package/tools/which-command.test.js +126 -0
  139. package/tools/worktree-card.test.js +551 -0
  140. package/tools/worktree-cards.test.js +845 -0
  141. package/tools/worktree-changes.test.js +4 -5
  142. package/tools/worktree-create.test.js +489 -0
  143. package/tools/worktree-guard.test.js +823 -0
  144. package/tools/worktree-hooks.test.js +905 -0
  145. package/tools/worktree-list.test.js +170 -0
  146. package/tools/worktree-registry.test.js +89 -230
  147. package/tools/worktree-remove-async.test.js +318 -0
  148. package/tools/worktree-setup-runner.test.js +276 -0
  149. package/tools/worktree-setup.test.js +140 -0
  150. package/tools/worktree-tools.test.js +419 -199
  151. package/lib/codegraph-commands.js +0 -165
  152. package/lib/odd-prompt/odd-worktrees.with-codegraph.md +0 -19
  153. package/lib/odd-prompt/odd-worktrees.without-codegraph.md +0 -15
  154. package/lib/worktree-model-result.js +0 -291
  155. package/tools/codegraph-commands.test.js +0 -371
  156. package/tools/herdr-free-create.test.js +0 -161
  157. package/tools/worktree-close-herdr-async.test.js +0 -204
  158. package/tools/worktree-odd-migration.test.js +0 -224
  159. package/tools/worktree-registry-cache.test.js +0 -163
  160. package/tools/worktree-registry-odd.test.js +0 -231
package/lib/gh-issues.js CHANGED
@@ -81,6 +81,7 @@
81
81
  const { execFile } = require('node:child_process');
82
82
  const crypto = require('node:crypto');
83
83
  const path = require('node:path');
84
+ const { whichCommand } = require('./which-command.js');
84
85
 
85
86
  const DEFAULT_TIMEOUT_MS = 30000;
86
87
  const GIT_TIMEOUT_MS = 5000;
@@ -158,6 +159,53 @@ function ghBinary(opts = {}) {
158
159
  return 'gh';
159
160
  }
160
161
 
162
+ // S13 (issues-startup-performance T11): a test seam for the CLI's presence,
163
+ // exactly like `setGhRunner` and `setGitRunner` — inject
164
+ // `fn(bin) -> foundPathOrNull`, or `null`/`undefined` to restore the local probe
165
+ // below.
166
+ let whichOverride = null;
167
+
168
+ function setGhWhich(fn) {
169
+ if (fn === null || fn === undefined) {
170
+ whichOverride = null;
171
+ return;
172
+ }
173
+ if (typeof fn !== 'function') throw new TypeError('setGhWhich requires a function or null');
174
+ whichOverride = fn;
175
+ }
176
+
177
+ // Whether the `gh` binary this client would run is reachable WITHOUT running it.
178
+ //
179
+ // S13 (T11): the caller — the session gate, `/issues`, the rail's read — needs
180
+ // that answer before it spends a child process finding out, and the answer is
181
+ // already on disk (`lib/which-command.js` walks PATH). No child process, no
182
+ // network, no cache, and `GH_BIN_PATH` is respected through `ghBinary`, so an
183
+ // install outside PATH that the caller named is still present.
184
+ //
185
+ // Two callers' facts outrank the probe: a `which` seam injected here answers for
186
+ // itself, and a caller that injected its own RUNNER (`setGhRunner`) owns the
187
+ // binary question — that runner never needs a `gh` on PATH, so its tests and the
188
+ // `GH_BIN_PATH`-less CI that drives them are not mistaken for a missing CLI.
189
+ // An internal failure never claims absence: only a definitive "nothing on PATH"
190
+ // answer is `false`, because a false answer turns every issues surface off.
191
+ function ghCliPresent(opts = {}) {
192
+ const options = opts && typeof opts === 'object' ? opts : {};
193
+ const bin = ghBinary(options);
194
+ if (whichOverride !== null) {
195
+ try {
196
+ return whichOverride(bin) !== null;
197
+ } catch {
198
+ return true;
199
+ }
200
+ }
201
+ if (runnerOverride !== null) return true;
202
+ try {
203
+ return whichCommand(bin, { env: options.env || process.env }) !== null;
204
+ } catch {
205
+ return true;
206
+ }
207
+ }
208
+
161
209
  // ---------------------------------------------------------------------------
162
210
  // Checkout scope: which repository this checkout belongs to.
163
211
  // ---------------------------------------------------------------------------
@@ -862,6 +910,91 @@ async function ghStatus(opts = {}) {
862
910
  return { ok: true, login, nameWithOwner: (scope.ok === true && scope.nameWithOwner) || reported };
863
911
  }
864
912
 
913
+ // The gate's answer — `gh api user` then `gh repo view`, plus the checkout's own
914
+ // git probes — is what `/issues` cannot open without, and it is pure network and
915
+ // disk latency. It is reused for a short while so one session start, a resume and a
916
+ // typed command share a single probe: minutes for a usable `gh`, seconds for a
917
+ // failure, so a package or login the human just fixed is noticed quickly.
918
+ const GATE_SUCCESS_TTL_MS = 5 * 60 * 1000;
919
+ const GATE_FAILURE_TTL_MS = 30 * 1000;
920
+ // A handful of checkouts: a few worktrees is the working set, and the oldest entry
921
+ // is what pays when the bound is exceeded.
922
+ const GATE_CACHE_MAX = 8;
923
+
924
+ let gateClockOverride = null;
925
+
926
+ // Test seam: inject `() => epochMillis` (or null to restore the real clock). The
927
+ // TTLs are wall-clock facts, so proving an expiry must move time without sleeping
928
+ // through it.
929
+ function setGateClock(fn) {
930
+ if (fn === null || fn === undefined) {
931
+ gateClockOverride = null;
932
+ return;
933
+ }
934
+ if (typeof fn !== 'function') throw new TypeError('setGateClock requires a function or null');
935
+ gateClockOverride = fn;
936
+ }
937
+
938
+ function gateNow() {
939
+ if (gateClockOverride === null) return Date.now();
940
+ try {
941
+ const value = gateClockOverride();
942
+ return Number.isFinite(value) ? value : Date.now();
943
+ } catch {
944
+ return Date.now();
945
+ }
946
+ }
947
+
948
+ // The checkout AND the host gh would target (GH_HOST), exactly like
949
+ // `checkoutRepoScope`: an answer resolved for one server is never reused for another.
950
+ function gateStatusKey(opts) {
951
+ let cwd = '';
952
+ try {
953
+ cwd = path.resolve(typeof opts.cwd === 'string' && opts.cwd.length > 0 ? opts.cwd : process.cwd());
954
+ } catch {
955
+ cwd = '';
956
+ }
957
+ return `${cwd}\n${ghHostOf(opts.env || process.env)}`;
958
+ }
959
+
960
+ const gateStatuses = new Map();
961
+
962
+ // Drop every cached gate answer. A session that ends takes its answers with it, so
963
+ // the next session starts from its own probe instead of its predecessor's.
964
+ function clearCachedGhStatus() {
965
+ gateStatuses.clear();
966
+ }
967
+
968
+ // `ghStatus` with one answer per checkout and TTL: a caller inside the window gets
969
+ // the previous answer, a caller DURING a probe awaits that same promise instead of
970
+ // spawning a second pair of children, and an expired entry is probed again. The
971
+ // shape is `ghStatus`'s, unchanged, so every decision made from it is the same one:
972
+ // only WHEN the probe runs changes.
973
+ async function cachedGhStatus(opts = {}) {
974
+ const options = opts && typeof opts === 'object' ? opts : {};
975
+ const key = gateStatusKey(options);
976
+ const entry = gateStatuses.get(key);
977
+ if (entry) {
978
+ if (entry.settled !== true) return entry.run;
979
+ const ttl = entry.result && entry.result.ok === true ? GATE_SUCCESS_TTL_MS : GATE_FAILURE_TTL_MS;
980
+ if (gateNow() - entry.at < ttl) return entry.result;
981
+ }
982
+ const next = { settled: false, result: null, at: gateNow(), run: null };
983
+ next.run = ghStatus(options)
984
+ .catch((err) => ({ ok: false, error: (err && err.message) || String(err) }))
985
+ .then((result) => {
986
+ next.settled = true;
987
+ next.result = result;
988
+ next.at = gateNow();
989
+ return result;
990
+ });
991
+ if (gateStatuses.size >= GATE_CACHE_MAX && !gateStatuses.has(key)) {
992
+ gateStatuses.delete(gateStatuses.keys().next().value);
993
+ }
994
+ gateStatuses.set(key, next);
995
+ return next.run;
996
+ }
997
+
865
998
  async function repoInfo(opts = {}) {
866
999
  const resolved = await repoNameWithOwner(opts);
867
1000
  if (!resolved.ok) return resolved;
@@ -995,11 +1128,24 @@ function graphqlIssueRow(node) {
995
1128
  const labelNodes = entry.labels && typeof entry.labels === 'object' && Array.isArray(entry.labels.nodes)
996
1129
  ? entry.labels.nodes
997
1130
  : [];
1131
+ // T10 (S9): the rail's row is the panel's first frame, so a request that asks
1132
+ // for `assignees { nodes { login } }` gets the plain login list the detail
1133
+ // read's `assignees` field also normalizes to.
1134
+ const assigneeNodes = entry.assignees && typeof entry.assignees === 'object'
1135
+ && Array.isArray(entry.assignees.nodes)
1136
+ ? entry.assignees.nodes
1137
+ : null;
998
1138
  const commentsTotal = entry.comments && typeof entry.comments === 'object'
999
1139
  && Number.isInteger(entry.comments.totalCount)
1000
1140
  ? entry.comments.totalCount
1001
1141
  : 0;
1002
- return { ...entry, labels: labelNodes, comments: [], commentsTotal };
1142
+ return {
1143
+ ...entry,
1144
+ labels: labelNodes,
1145
+ ...(assigneeNodes === null ? {} : { assignees: assigneeNodes }),
1146
+ comments: [],
1147
+ commentsTotal,
1148
+ };
1003
1149
  }
1004
1150
 
1005
1151
  // EVERY open issue of the repository, read through the GraphQL connection.
@@ -1369,7 +1515,7 @@ async function getIssueMetadata(number, opts = {}) {
1369
1515
  viewerPermission
1370
1516
  issue(number: $number) {
1371
1517
  assignees(first: 100) { nodes { login } pageInfo { hasNextPage } }
1372
- closedByPullRequestsReferences(first: 1, includeClosedPrs: true) { totalCount }
1518
+ closedByPullRequestsReferences(first: 100, includeClosedPrs: true) { nodes { number } pageInfo { hasNextPage } }
1373
1519
  }
1374
1520
  }
1375
1521
  }`;
@@ -1386,11 +1532,28 @@ async function getIssueMetadata(number, opts = {}) {
1386
1532
  permissions: repositoryEditPermissions(repository.viewerPermission),
1387
1533
  assignees: issue.assignees.nodes.map(asLogin).filter(Boolean),
1388
1534
  };
1389
- const count = issue.closedByPullRequestsReferences?.totalCount;
1390
- if (Number.isInteger(count) && count > 0) metadata.linkedPullRequestCount = count;
1391
- if (!Number.isInteger(count) || count < 0) metadata.metadataError = 'Linked PR metadata is unavailable';
1535
+ // S1/S4: the pane lists linked PRs by number, so the read carries the
1536
+ // reference numbers themselves (the first server page) instead of a count.
1537
+ // A page that is not a list of positive integers is a failed relation, and a
1538
+ // page the server says continues is marked truncated rather than passed off
1539
+ // as the whole list.
1540
+ const references = issue.closedByPullRequestsReferences;
1541
+ const referenceNodes = references?.nodes;
1542
+ const validReference = Array.isArray(referenceNodes)
1543
+ && referenceNodes.every((node) => Number.isInteger(node?.number) && node.number > 0);
1544
+ // S2: a relation that could not be read is NAMED, so the pane can say which
1545
+ // metadata is missing; `metadataError` stays reserved for a whole-read loss.
1546
+ const unavailable = [];
1547
+ if (validReference) {
1548
+ const numbers = [...new Set(referenceNodes.map((node) => node.number))].sort((a, b) => a - b);
1549
+ if (numbers.length > 0) metadata.linkedPullRequests = numbers;
1550
+ if (references.pageInfo?.hasNextPage === true) metadata.linkedPullRequestsTruncated = true;
1551
+ } else {
1552
+ unavailable.push('linked PRs');
1553
+ }
1392
1554
  // Project visibility/scopes are independent of issue triage permissions.
1393
- // A private or unsupported project relation must not disable known rights.
1555
+ // A private or unsupported project relation must not disable known rights,
1556
+ // and S3 keeps every confirmed fact when only this relation is lost.
1394
1557
  const relations = await feedbackGraphql(`query($owner: String!, $name: String!, $number: Int!) {
1395
1558
  repository(owner: $owner, name: $name) {
1396
1559
  issue(number: $number) {
@@ -1400,12 +1563,13 @@ async function getIssueMetadata(number, opts = {}) {
1400
1563
  }`, { owner: repo.owner, name: repo.name, number }, opts);
1401
1564
  const related = relations.ok ? relations.data.repository?.issue : null;
1402
1565
  if (!Array.isArray(related?.projectItems?.nodes) || related.projectItems.pageInfo?.hasNextPage) {
1403
- metadata.metadataError = relations.error || 'Project metadata is unavailable or incomplete';
1404
- return metadata;
1566
+ unavailable.push('projects');
1567
+ } else {
1568
+ const projects = related.projectItems.nodes.map((item) => item?.project)
1569
+ .filter((project) => typeof project?.title === 'string' && project.title);
1570
+ if (projects.length > 0) metadata.projects = projects.map(({ title, url }) => ({ title, url }));
1405
1571
  }
1406
- const projects = related.projectItems.nodes.map((item) => item?.project)
1407
- .filter((project) => typeof project?.title === 'string' && project.title);
1408
- if (projects.length > 0) metadata.projects = projects.map(({ title, url }) => ({ title, url }));
1572
+ if (unavailable.length > 0) metadata.unavailable = unavailable;
1409
1573
  return metadata;
1410
1574
  }
1411
1575
 
@@ -1455,10 +1619,16 @@ async function editAssignees(number, changes = {}, opts = {}) {
1455
1619
  || add.some((name) => remove.some((other) => name.toLowerCase() === other.toLowerCase()))) {
1456
1620
  return { ok: false, error: 'invalid assignee changes: supply distinct GitHub logins to add or remove' };
1457
1621
  }
1458
- if (add.length === 0 && remove.length === 0) return { ok: true, changed: false };
1622
+ if (add.length === 0 && remove.length === 0) return { ok: true, changed: false, self: false };
1459
1623
  const repo = await feedbackRepository(opts);
1460
1624
  if (!repo.ok) return repo;
1461
- const access = await feedbackGraphql('query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { viewerPermission } }', { owner: repo.owner, name: repo.name }, opts);
1625
+ // T17 (S21): the SAME permission read that authorizes the write names the
1626
+ // authenticated viewer (`viewer { login }` is a root field, so it costs no
1627
+ // second request). A delta that includes that login is the one write whose
1628
+ // effect the viewer's OWN `assigned` bucket shows, and the rail's merge is
1629
+ // built from that bucket too — so the answer says so itself instead of any
1630
+ // caller guessing from a display name, a local config or an optimistic guess.
1631
+ const access = await feedbackGraphql('query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { viewerPermission } viewer { login } }', { owner: repo.owner, name: repo.name }, opts);
1462
1632
  if (!access.ok) return access;
1463
1633
  if (!repositoryEditPermissions(access.data.repository?.viewerPermission).canEditAssignees) {
1464
1634
  return { ok: false, error: 'Repository permission does not allow changing issue assignees' };
@@ -1469,7 +1639,11 @@ async function editAssignees(number, changes = {}, opts = {}) {
1469
1639
  const result = await runGh(argv, { ...opts, freshScope: true });
1470
1640
  if (result.error) return { ok: false, error: result.error };
1471
1641
  if (result.status !== 0) return { ok: false, error: exitError(result, 'Cannot edit issue assignees') };
1472
- return { ok: true, changed: true };
1642
+ const viewer = access.data && access.data.viewer && typeof access.data.viewer.login === 'string'
1643
+ ? access.data.viewer.login.toLowerCase()
1644
+ : '';
1645
+ const self = viewer !== '' && [...new Set([...add, ...remove])].some((name) => name.toLowerCase() === viewer);
1646
+ return { ok: true, changed: true, self };
1473
1647
  }
1474
1648
 
1475
1649
  async function listLabels(opts = {}) {
@@ -1530,10 +1704,129 @@ async function setIssueState(number, state, opts = {}) {
1530
1704
  return { ok: true };
1531
1705
  }
1532
1706
 
1707
+ // S9 (issues-sidebar T14, superseding T9's marker read): the rail's ONE read.
1708
+ // A single `gh api graphql` request carries the three scoped views as aliased
1709
+ // searches over the same `repo:<owner>/<name> is:issue is:open` scope, each
1710
+ // sorted by `updatedAt` and bounded by the caller's `first`. The node selection
1711
+ // is the panel's own (`PAGE_ISSUE_FIELDS` + `graphqlIssueRow`), so a cached row
1712
+ // normalizes exactly like a panel row, and T9's pull-request cross-reference
1713
+ // sub-selection rides each node, so the marker costs no second call, no second
1714
+ // identity lookup and no second failure mode. `rateLimit { cost }` is not asked
1715
+ // for: it is a measured optimization fact, not something a row needs.
1716
+ const RELATED_ISSUE_QUALIFIERS = {
1717
+ mine: 'author:@me',
1718
+ assigned: 'assignee:@me',
1719
+ involved: 'involves:@me -author:@me',
1720
+ };
1721
+ // S3 (issues-sidebar-click T2): GraphQL answers `timelineItems` in
1722
+ // chronological order, so a `first: N` window is the OLDEST N cross-reference
1723
+ // events and its first pull request is the oldest one that references the
1724
+ // issue. The rail marks the issue with the number of the MOST RECENT pull
1725
+ // request, so the window is read from the end (`last: N`) — same ONE request for
1726
+ // the three views, same node selection. The window stays bounded and small: the
1727
+ // point is the newest events, and cross references from ISSUES rather than pull
1728
+ // requests must not crowd the pull requests out of it.
1729
+ const PR_REFERENCE_EVENT = 'CROSS_REFERENCED_EVENT';
1730
+ const PR_REFERENCE_WINDOW = 10;
1731
+
1732
+ function relatedIssuesQuery(owner, name, first) {
1733
+ const scope = `repo:${owner}/${name} is:issue is:open`;
1734
+ const aliases = Object.entries(RELATED_ISSUE_QUALIFIERS).map(([alias, qualifier]) => {
1735
+ const search = `${scope} ${qualifier} sort:updated-desc`;
1736
+ return ` ${alias}: search(query: ${JSON.stringify(search)}, type: ISSUE, first: ${first}) {
1737
+ issueCount
1738
+ nodes {
1739
+ ... on Issue {
1740
+ ${PAGE_ISSUE_FIELDS}
1741
+ assignees(first: 10) { nodes { login } }
1742
+ timelineItems(last: ${PR_REFERENCE_WINDOW}, itemTypes: [${PR_REFERENCE_EVENT}]) {
1743
+ nodes { ... on CrossReferencedEvent { source { __typename ... on PullRequest { number } } } }
1744
+ }
1745
+ }
1746
+ }
1747
+ }`;
1748
+ });
1749
+ return `query {\n${aliases.join('\n')}\n}`;
1750
+ }
1751
+
1752
+ // The marker is a decoration: a missing or malformed timeline is simply "no
1753
+ // pull request", never a failed read that costs the caller its rows.
1754
+ function pullRequestReferenced(node) {
1755
+ const connection = node && typeof node === 'object' ? node.timelineItems : null;
1756
+ if (!connection || typeof connection !== 'object' || !Array.isArray(connection.nodes)) return false;
1757
+ return connection.nodes.some(
1758
+ (item) => item && typeof item === 'object' && item.source && item.source.__typename === 'PullRequest',
1759
+ );
1760
+ }
1761
+
1762
+ // S8 (T9) + S3 (issues-sidebar-click T2): the marker a row wears is a pull
1763
+ // request's NUMBER, so the same timeline hands it over. The timeline window is
1764
+ // the NEWEST events (`last:`), so the newest pull request is the last event that
1765
+ // carries one: the scan runs from the end and the first pull-request source it
1766
+ // meets is the most recent. A cross reference from an issue, and a node the
1767
+ // answer malformed, are skipped — never read as a number and never a throw — and
1768
+ // a source whose number the answer did not carry is no number at all, so a `#0`
1769
+ // or a `#NaN` never reaches a row. No pull request at all is `null`.
1770
+ function pullRequestNumber(node) {
1771
+ const connection = node && typeof node === 'object' ? node.timelineItems : null;
1772
+ if (!connection || typeof connection !== 'object' || !Array.isArray(connection.nodes)) return null;
1773
+ for (let index = connection.nodes.length - 1; index >= 0; index -= 1) {
1774
+ const item = connection.nodes[index];
1775
+ const source = item && typeof item === 'object' ? item.source : null;
1776
+ if (!source || typeof source !== 'object' || source.__typename !== 'PullRequest') continue;
1777
+ const number = Number(source.number);
1778
+ if (Number.isInteger(number) && number > 0) return number;
1779
+ }
1780
+ return null;
1781
+ }
1782
+
1783
+ // `{ first }` is the per-bucket row budget (1..100) and is validated before any
1784
+ // child runs. The answer is `{ ok: true, buckets: { mine, assigned, involved } }`
1785
+ // with each bucket's exact `issueCount` and its normalized rows; a rejected
1786
+ // child, a non-zero exit, a GraphQL `errors` array, an unparseable body, a
1787
+ // missing alias or a non-array `nodes` is `{ ok: false, error }`.
1788
+ async function listRelatedIssues(params = {}, opts = {}) {
1789
+ const first = params && typeof params === 'object' ? params.first : undefined;
1790
+ if (!Number.isInteger(first) || first < 1 || first > 100) {
1791
+ return { ok: false, error: `invalid first ${JSON.stringify(first)}: want an integer 1..100` };
1792
+ }
1793
+ const repo = await feedbackRepository(opts);
1794
+ if (!repo.ok) return repo;
1795
+ const res = await feedbackGraphql(relatedIssuesQuery(repo.owner, repo.name, first), {}, opts);
1796
+ if (!res.ok) return res;
1797
+ const buckets = {};
1798
+ for (const alias of Object.keys(RELATED_ISSUE_QUALIFIERS)) {
1799
+ const connection = res.data ? res.data[alias] : null;
1800
+ if (!connection || typeof connection !== 'object' || Array.isArray(connection)
1801
+ || !Number.isInteger(connection.issueCount) || connection.issueCount < 0
1802
+ || !Array.isArray(connection.nodes)) {
1803
+ return { ok: false, error: 'gh api graphql returned an unexpected shape' };
1804
+ }
1805
+ const issues = [];
1806
+ for (const node of connection.nodes) {
1807
+ if (!node || typeof node !== 'object' || !Number.isInteger(node.number) || node.number <= 0) {
1808
+ return { ok: false, error: 'gh api graphql returned an issue without a number' };
1809
+ }
1810
+ issues.push({
1811
+ ...normalizeIssue(graphqlIssueRow(node)),
1812
+ hasPullRequest: pullRequestReferenced(node),
1813
+ pullRequestNumber: pullRequestNumber(node),
1814
+ });
1815
+ }
1816
+ buckets[alias] = { issueCount: connection.issueCount, issues };
1817
+ }
1818
+ return { ok: true, buckets };
1819
+ }
1820
+
1533
1821
  module.exports = {
1534
1822
  setGhRunner,
1535
1823
  setGitRunner,
1824
+ setGhWhich,
1825
+ setGateClock,
1826
+ clearCachedGhStatus,
1827
+ cachedGhStatus,
1536
1828
  ghBinary,
1829
+ ghCliPresent,
1537
1830
  checkoutRepoScope,
1538
1831
  reportedRepoName,
1539
1832
  normalizeScopeIdentity,
@@ -1552,4 +1845,5 @@ module.exports = {
1552
1845
  editLabels,
1553
1846
  commentIssue,
1554
1847
  setIssueState,
1848
+ listRelatedIssues,
1555
1849
  };
@@ -14,8 +14,9 @@
14
14
  // issueDetailLines(detail, comments, options) -> string[]
15
15
  // detail an issue as `gh` normalizes it (number, title, state, author,
16
16
  // labels, assignees, createdAt, updatedAt, commentsCount,
17
- // reactions{plusOne}, projects, linkedPullRequestCount,
18
- // metadataError, body). Every field is optional.
17
+ // reactions{plusOne}, projects, linkedPullRequests,
18
+ // linkedPullRequestsTruncated, unavailable, metadataError,
19
+ // body). Every field is optional.
19
20
  // comments an array of `{ author, body, createdAt }`; anything else is
20
21
  // treated as "no comments yet".
21
22
  // options { width, paint, emphasis, wrap, cache, note, pending, now }
@@ -36,8 +37,10 @@
36
37
  // never be served.
37
38
  //
38
39
  // Absent metadata is omitted rather than printed as "none" or "0": an empty
39
- // assignee/project list or a zero PR count does not add an optional row;
40
- // reaction/comment counters remain explicit facts, including measured zeros.
40
+ // assignee/project list or an empty linked-PR list does not add an optional
41
+ // row; reaction/comment counters remain explicit facts, including measured
42
+ // zeros. A relation that could not be read is omitted the same way, never
43
+ // announced, and S4 marks a capped linked-PR page as truncated.
41
44
  //
42
45
  // S13: the title is a TITLE, not a control. Its role comes from the shared
43
46
  // table in `lib/tui-paint.js` (`ROLES.title`) instead of a role name written
@@ -229,6 +232,12 @@ function issueDetailLines(detail, comments, options = {}) {
229
232
  if (settings.pending === true) {
230
233
  const pending = [];
231
234
  for (const line of lines) pending.push(...wrap(line));
235
+ // S9 (T10): a row already knows its author, so the framed identity is
236
+ // complete before the body is; the ages and counters still wait for the
237
+ // richer read (they are not invented from a row that never carried them).
238
+ if (typeof entry.author === 'string' && entry.author.length > 0) {
239
+ pending.push(...wrap(`by ${entry.author}`));
240
+ }
232
241
  pending.push(paint('muted', 'loading…'));
233
242
  return pending;
234
243
  }
@@ -248,9 +257,19 @@ function issueDetailLines(detail, comments, options = {}) {
248
257
  .map((project) => (project && project.title ? String(project.title) : ''))
249
258
  .filter(Boolean);
250
259
  if (projects.length > 0) lines.push(`projects: ${projects.join(', ')}`);
251
- const linkedPrs = Number(entry.linkedPullRequestCount);
252
- if (Number.isFinite(linkedPrs) && linkedPrs > 0) lines.push(`linked PRs: ${linkedPrs}`);
253
- if (entry.metadataError) lines.push(paint('muted', 'metadata unavailable'));
260
+ // S1: every linked PR is named by number, ascending, never counted; S4 keeps
261
+ // a capped page honest with a trailing ellipsis instead of passing for the
262
+ // whole list.
263
+ const linkedPrs = (Array.isArray(entry.linkedPullRequests) ? entry.linkedPullRequests : [])
264
+ .filter((number) => Number.isInteger(number) && number > 0);
265
+ if (linkedPrs.length > 0) {
266
+ const listed = linkedPrs.map((number) => `#${number}`).join(', ');
267
+ lines.push(`linked PRs: ${listed}${entry.linkedPullRequestsTruncated === true ? ', …' : ''}`);
268
+ }
269
+ // A relation that could not be read (`unavailable`) or a whole failed read
270
+ // (`metadataError`) paints NOTHING: the pane stays quiet, exactly as it does for a
271
+ // relation the issue simply does not have. The fields stay on the issue for the
272
+ // callers that gate on them (the permissions fail closed on `metadataError`).
254
273
 
255
274
  const out = [];
256
275
  lines.push('');
@@ -0,0 +1,206 @@
1
+ 'use strict';
2
+ // T9 (S10): does one `bash` command string mutate a GitHub issue or pull
3
+ // request?
4
+ //
5
+ // The rail re-reads on its own floor (S10/T8, 20 s), and the user's own words
6
+ // were "y que de tool solo revise tools bash, si uso algun comando git bash de
7
+ // creacion/update de alguna issue o pr, luego de terminar la tool ahi si podria
8
+ // forzar un refrezco porque sabemos que algo cambios". This module is that
9
+ // question and nothing else: a `bash` command in, a boolean out.
10
+ //
11
+ // TEXT ONLY, exactly like lib/worktree-guard.js: the command is split into
12
+ // segments on `&&`, `||`, `|`, `&`, `;` and newlines, each segment is tokenized
13
+ // with one simple quote pair per token (nothing else about the text is
14
+ // interpreted), and a segment counts only when its COMMAND position names the
15
+ // `gh` binary — an absolute path to it is the same binary, and a leading `env`
16
+ // or `VAR=value` prefix is skipped. A mutation MENTIONED in an argument or a
17
+ // commit message names no command, so it forces no read.
18
+ //
19
+ // The verbs are the issue and pull-request writes `gh` ships: for `gh issue`
20
+ // create/edit/close/reopen/comment/delete/transfer/develop/lock/unlock; for
21
+ // `gh pr` the same set plus merge/review/ready. `gh api` is a write when its
22
+ // method is POST/PATCH/PUT/DELETE (`-X POST`, `-XPOST`, `--method PATCH`,
23
+ // `--method=PUT`, …) or when it carries the field flags that make `gh` POST
24
+ // (`-f`, `--field`, `-F`, `--raw-field`, `--input`). Everything else — `gh issue
25
+ // list`, `gh pr view`, a bare `gh api` GET, `gh repo view`, plain `git` — is not
26
+ // a write.
27
+ //
28
+ // Nothing here spawns a child, reads a file, touches the clock or caches
29
+ // anything: it is one decision over a string that runs on the hot path of a
30
+ // `bash` result, and it never throws, because the caller's refresh is best
31
+ // effort and a throw there would ride into a host handler.
32
+
33
+ /** The `gh` subcommands whose write is a mutation of an issue. */
34
+ const ISSUE_MUTATIONS = new Set([
35
+ 'create',
36
+ 'edit',
37
+ 'close',
38
+ 'reopen',
39
+ 'comment',
40
+ 'delete',
41
+ 'transfer',
42
+ 'develop',
43
+ 'lock',
44
+ 'unlock',
45
+ ]);
46
+
47
+ /** The `gh` subcommands whose write is a mutation of a pull request. */
48
+ const PR_MUTATIONS = new Set([
49
+ 'create',
50
+ 'edit',
51
+ 'close',
52
+ 'reopen',
53
+ 'merge',
54
+ 'comment',
55
+ 'review',
56
+ 'ready',
57
+ 'lock',
58
+ 'unlock',
59
+ ]);
60
+
61
+ /** `gh api` methods that write. */
62
+ const WRITE_METHODS = new Set(['POST', 'PATCH', 'PUT', 'DELETE']);
63
+
64
+ /** `gh api` flags that make an unstated method POST. */
65
+ const FIELD_FLAGS = new Set(['-f', '--field', '-F', '--raw-field', '--input']);
66
+
67
+ /** The prefixes a shell uses in front of the command that really runs. */
68
+ const COMMAND_PREFIXES = new Set(['env', 'command', 'nohup', 'sudo', 'time']);
69
+
70
+ /** A `VAR=value` assignment in the command position. */
71
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
72
+
73
+ /**
74
+ * Split one command string into segments of tokens. Separators end a segment,
75
+ * one simple quote pair per token is stripped, and no escape is interpreted —
76
+ * the same reading lib/worktree-guard.js does, without its substitution walk:
77
+ * what a segment's command position names is the whole question here.
78
+ */
79
+ function scanSegments(command) {
80
+ const segments = [];
81
+ let tokens = [];
82
+ let token = null;
83
+ const flushToken = () => {
84
+ if (token !== null) {
85
+ tokens.push(token);
86
+ token = null;
87
+ }
88
+ };
89
+ const flushSegment = () => {
90
+ flushToken();
91
+ if (tokens.length > 0) segments.push(tokens);
92
+ tokens = [];
93
+ };
94
+ let i = 0;
95
+ while (i < command.length) {
96
+ const ch = command[i];
97
+ if (ch === "'" || ch === '"') {
98
+ const end = command.indexOf(ch, i + 1);
99
+ const inner = end < 0 ? command.slice(i + 1) : command.slice(i + 1, end);
100
+ token = (token === null ? '' : token) + inner;
101
+ i = end < 0 ? command.length : end + 1;
102
+ continue;
103
+ }
104
+ if (ch === ' ' || ch === '\t') {
105
+ flushToken();
106
+ i += 1;
107
+ continue;
108
+ }
109
+ if (ch === '\n' || ch === '\r' || ch === '&' || ch === '|' || ch === ';' || ch === '(' || ch === ')') {
110
+ // A subshell `( … )` starts a segment of its own, exactly like a separator.
111
+ flushSegment();
112
+ i += 1;
113
+ // `&&`, `||`, `|&`, `;;`: one separator, however it is spelled.
114
+ while (i < command.length && (command[i] === '&' || command[i] === '|' || command[i] === ';')) i += 1;
115
+ continue;
116
+ }
117
+ token = (token === null ? '' : token) + ch;
118
+ i += 1;
119
+ }
120
+ flushSegment();
121
+ return segments;
122
+ }
123
+
124
+ /** The index of the token that runs the command, past `env`/`VAR=value` prefixes. */
125
+ function commandIndex(tokens) {
126
+ let i = 0;
127
+ while (i < tokens.length) {
128
+ const token = tokens[i];
129
+ if (ASSIGNMENT.test(token)) {
130
+ i += 1;
131
+ continue;
132
+ }
133
+ if (COMMAND_PREFIXES.has(token)) {
134
+ i += 1;
135
+ // `env -u VAR gh …` / `sudo -E gh …`: the prefix's own options are skipped.
136
+ while (i < tokens.length && tokens[i].startsWith('-')) i += 1;
137
+ continue;
138
+ }
139
+ return i;
140
+ }
141
+ return -1;
142
+ }
143
+
144
+ /** Whether a command token names the `gh` binary, bare or by absolute path. */
145
+ function isGhToken(token) {
146
+ return token === 'gh' || token.endsWith('/gh');
147
+ }
148
+
149
+ /** The method `gh api` states on its command line, or null when it states none. */
150
+ function statedMethod(tokens, apiIndex) {
151
+ for (let i = apiIndex + 1; i < tokens.length; i += 1) {
152
+ const token = tokens[i];
153
+ if (token === '-X' || token === '--method') {
154
+ const value = tokens[i + 1];
155
+ if (typeof value === 'string' && value.length > 0) return value.toUpperCase();
156
+ continue;
157
+ }
158
+ if (token.startsWith('--method=')) return token.slice('--method='.length).toUpperCase();
159
+ if (token.startsWith('-X') && token.length > 2) return token.slice(2).toUpperCase();
160
+ }
161
+ return null;
162
+ }
163
+
164
+ /** Whether a `gh api` segment carries a field flag, which makes the call a POST. */
165
+ function carriesField(tokens, apiIndex) {
166
+ for (let i = apiIndex + 1; i < tokens.length; i += 1) {
167
+ const token = tokens[i];
168
+ if (FIELD_FLAGS.has(token)) return true;
169
+ // The `--field=key=value` spelling carries the flag and its value at once.
170
+ if (token.startsWith('--field=') || token.startsWith('--raw-field=') || token.startsWith('--input=')) return true;
171
+ }
172
+ return false;
173
+ }
174
+
175
+ /** Whether one segment's `gh` command mutates an issue or a pull request. */
176
+ function segmentMutates(tokens) {
177
+ const at = commandIndex(tokens);
178
+ if (at < 0 || !isGhToken(tokens[at])) return false;
179
+ const group = tokens[at + 1];
180
+ const verb = tokens[at + 2];
181
+ if (group === 'issue') return typeof verb === 'string' && ISSUE_MUTATIONS.has(verb);
182
+ if (group === 'pr') return typeof verb === 'string' && PR_MUTATIONS.has(verb);
183
+ if (group !== 'api') return false;
184
+ const method = statedMethod(tokens, at);
185
+ if (method !== null) return WRITE_METHODS.has(method);
186
+ return carriesField(tokens, at);
187
+ }
188
+
189
+ /**
190
+ * Whether one `bash` command mutates a GitHub issue or pull request. Answers
191
+ * `false` for anything that is not a command string, and never throws.
192
+ */
193
+ function bashMutatesIssuesOrPullRequests(command) {
194
+ try {
195
+ if (typeof command !== 'string' || command.length === 0) return false;
196
+ for (const tokens of scanSegments(command)) {
197
+ if (segmentMutates(tokens)) return true;
198
+ }
199
+ return false;
200
+ } catch {
201
+ // A command this scanner cannot read names nothing, so it forces no read.
202
+ return false;
203
+ }
204
+ }
205
+
206
+ module.exports = { bashMutatesIssuesOrPullRequests };