pi-odd-worktree 2.1.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +54 -319
  2. package/extensions/odd-worktree-tools.ts +4182 -2539
  3. package/lib/bash-activity.js +1166 -0
  4. package/lib/bash-design.js +684 -0
  5. package/lib/bash-destructive.js +559 -0
  6. package/lib/bash-frame.js +205 -0
  7. package/lib/card-content.js +23 -0
  8. package/lib/card-style.js +175 -0
  9. package/lib/checkout-facts.js +30 -70
  10. package/lib/codegraph-card-preview.js +628 -0
  11. package/lib/codegraph-card.js +515 -0
  12. package/lib/codegraph-compaction.js +76 -0
  13. package/lib/codegraph-daemon.js +246 -0
  14. package/lib/codegraph-edit-sync.js +182 -0
  15. package/lib/codegraph-guard-target.js +337 -0
  16. package/lib/codegraph-guard.js +211 -0
  17. package/lib/codegraph-index.js +1020 -0
  18. package/lib/codegraph-lock.js +607 -0
  19. package/lib/codegraph-mcp-config.js +134 -0
  20. package/lib/codegraph-mcp.js +123 -0
  21. package/lib/codegraph-paths.js +69 -0
  22. package/lib/codegraph-prompt/explore.md +11 -0
  23. package/lib/codegraph-prompt/fix.md +6 -0
  24. package/lib/codegraph-prompt/generic.md +8 -0
  25. package/lib/codegraph-prompt/judge.md +9 -0
  26. package/lib/codegraph-prompt/orchestrator.md +17 -0
  27. package/lib/codegraph-prompt/verify.md +10 -0
  28. package/lib/codegraph-prompt/worker.md +7 -0
  29. package/lib/codegraph-role.js +55 -0
  30. package/lib/codegraph-rules.js +146 -0
  31. package/lib/codegraph-session.js +303 -383
  32. package/lib/codegraph-warmup.js +139 -0
  33. package/lib/file-card-markdown.js +141 -0
  34. package/lib/file-card-resolver.js +245 -0
  35. package/lib/file-card.js +659 -0
  36. package/lib/files-index.js +387 -0
  37. package/lib/files-insert.js +81 -0
  38. package/lib/files-orders.js +326 -0
  39. package/lib/files-picker-view.js +1421 -0
  40. package/lib/files-preview.js +338 -0
  41. package/lib/files-scope-detail.js +171 -0
  42. package/lib/files-scope-view.js +507 -0
  43. package/lib/gh-issues.js +323 -15
  44. package/lib/issue-preview.js +26 -7
  45. package/lib/issues-bash-mutation.js +206 -0
  46. package/lib/issues-cache-store.js +261 -0
  47. package/lib/issues-section.js +710 -0
  48. package/lib/issues-view.js +649 -52
  49. package/lib/odd-prompt/odd-worktrees.md +21 -0
  50. package/lib/odd-worktrees-prompt.js +10 -28
  51. package/lib/related-issues-cache.js +210 -0
  52. package/lib/shell-card.js +825 -0
  53. package/lib/skill-odd-card.js +183 -0
  54. package/lib/tui-paint.js +4 -5
  55. package/lib/warp-create-panel.js +538 -250
  56. package/lib/warp-create-picker.js +56 -9
  57. package/lib/warp-delete-confirm.js +19 -28
  58. package/lib/warp-selector-view.js +160 -82
  59. package/lib/which-command.js +90 -0
  60. package/lib/worktree-card.js +267 -897
  61. package/lib/worktree-cards.js +383 -0
  62. package/lib/worktree-create.js +287 -0
  63. package/lib/worktree-git.js +3 -3
  64. package/lib/worktree-guard.js +548 -0
  65. package/lib/worktree-hooks.js +421 -712
  66. package/lib/worktree-list.js +120 -0
  67. package/lib/worktree-registry.js +162 -879
  68. package/lib/{worktree-close-herdr.js → worktree-remove.js} +9 -11
  69. package/lib/worktree-setup-runner.js +376 -0
  70. package/lib/worktree-setup.js +140 -0
  71. package/lib/worktree-warp-busy.js +462 -85
  72. package/lib/worktree-warp-sessions.js +1 -2
  73. package/package.json +2 -2
  74. package/tools/bash-activity.test.js +1420 -0
  75. package/tools/bash-design.test.js +1093 -0
  76. package/tools/bash-destructive.test.js +139 -0
  77. package/tools/card-content.test.js +44 -0
  78. package/tools/card-style.test.js +298 -0
  79. package/tools/codegraph-card-preview.test.js +254 -0
  80. package/tools/codegraph-card.test.js +1080 -0
  81. package/tools/codegraph-compaction.test.js +378 -0
  82. package/tools/codegraph-daemon.test.js +248 -0
  83. package/tools/codegraph-edit-sync.test.js +295 -0
  84. package/tools/codegraph-guard-target.test.js +174 -0
  85. package/tools/codegraph-guard.test.js +238 -0
  86. package/tools/codegraph-index.test.js +1948 -0
  87. package/tools/codegraph-lock.test.js +932 -0
  88. package/tools/codegraph-mcp-config.test.js +181 -0
  89. package/tools/codegraph-mcp.test.js +194 -0
  90. package/tools/codegraph-paths.test.js +44 -0
  91. package/tools/codegraph-role.test.js +30 -0
  92. package/tools/codegraph-rules.test.js +250 -0
  93. package/tools/codegraph-session.test.js +660 -391
  94. package/tools/codegraph-warmup.test.js +316 -0
  95. package/tools/commands.test.js +510 -31
  96. package/tools/file-card-markdown.test.js +188 -0
  97. package/tools/file-card.test.js +1289 -0
  98. package/tools/files-bridge.test.js +575 -0
  99. package/tools/files-command.test.js +613 -0
  100. package/tools/files-index.test.js +473 -0
  101. package/tools/files-insert.test.js +139 -0
  102. package/tools/files-orders.test.js +597 -0
  103. package/tools/files-picker-view.test.js +1889 -0
  104. package/tools/files-preview.test.js +452 -0
  105. package/tools/files-scope-detail.test.js +264 -0
  106. package/tools/files-scope-view.test.js +614 -0
  107. package/tools/fixtures/card-codegraph-outputs.js +110 -0
  108. package/tools/fixtures/codegraph-cli-stub.js +16 -0
  109. package/tools/fixtures/codegraph-init-process.js +28 -0
  110. package/tools/fixtures/codegraph-lock-worker.js +117 -0
  111. package/tools/fixtures/daemon-fake.js +98 -0
  112. package/tools/fixtures/daemon-mcp-server.js +39 -0
  113. package/tools/fixtures/daemon-warmup-worker.js +12 -0
  114. package/tools/fixtures/load-extension.js +136 -3
  115. package/tools/gh-issues-feedback.test.js +31 -7
  116. package/tools/gh-issues.test.js +417 -1
  117. package/tools/issue-preview.test.js +44 -7
  118. package/tools/issues-bash-mutation.test.js +101 -0
  119. package/tools/issues-cache-store.test.js +222 -0
  120. package/tools/issues-command.test.js +1517 -67
  121. package/tools/issues-open-guard.test.js +1096 -0
  122. package/tools/issues-section.test.js +4235 -0
  123. package/tools/issues-seed-query-regression.test.js +67 -0
  124. package/tools/issues-view.test.js +1489 -60
  125. package/tools/odd-worktrees-prompt.test.js +98 -65
  126. package/tools/package-surface.test.js +431 -36
  127. package/tools/related-issues-cache.test.js +324 -0
  128. package/tools/shell-card.test.js +834 -0
  129. package/tools/skill-odd-card.test.js +200 -0
  130. package/tools/t5-session-identity.test.js +44 -22
  131. package/tools/warp-busy-guard.test.js +2565 -309
  132. package/tools/warp-create-panel.test.js +499 -74
  133. package/tools/warp-create-picker.test.js +101 -5
  134. package/tools/warp-delete-confirm.test.js +49 -15
  135. package/tools/warp-empty-session.test.js +0 -1
  136. package/tools/warp-fallback-regression.test.js +533 -0
  137. package/tools/warp-selector-view.test.js +460 -196
  138. package/tools/which-command.test.js +126 -0
  139. package/tools/worktree-card.test.js +551 -0
  140. package/tools/worktree-cards.test.js +845 -0
  141. package/tools/worktree-changes.test.js +4 -5
  142. package/tools/worktree-create.test.js +489 -0
  143. package/tools/worktree-guard.test.js +823 -0
  144. package/tools/worktree-hooks.test.js +905 -0
  145. package/tools/worktree-list.test.js +170 -0
  146. package/tools/worktree-registry.test.js +89 -230
  147. package/tools/worktree-remove-async.test.js +318 -0
  148. package/tools/worktree-setup-runner.test.js +276 -0
  149. package/tools/worktree-setup.test.js +140 -0
  150. package/tools/worktree-tools.test.js +419 -199
  151. package/lib/codegraph-commands.js +0 -165
  152. package/lib/odd-prompt/odd-worktrees.with-codegraph.md +0 -19
  153. package/lib/odd-prompt/odd-worktrees.without-codegraph.md +0 -15
  154. package/lib/worktree-model-result.js +0 -291
  155. package/tools/codegraph-commands.test.js +0 -371
  156. package/tools/herdr-free-create.test.js +0 -161
  157. package/tools/worktree-close-herdr-async.test.js +0 -204
  158. package/tools/worktree-odd-migration.test.js +0 -224
  159. package/tools/worktree-registry-cache.test.js +0 -163
  160. package/tools/worktree-registry-odd.test.js +0 -231
@@ -0,0 +1,710 @@
1
+ 'use strict';
2
+ // The checkout's issues as a gentle-shell rail section (odd/tasks/
3
+ // issues-sidebar.md, T1: S1, S3, S4, S5; S7/T8 of rail-cards-fixes merged the
4
+ // authored `mine` bucket into the assigned one).
5
+ //
6
+ // Pure and injectable: a reader (`load`), two openers (`open`, `openAll`), a
7
+ // clock, a scheduler and a repaint callback all arrive as options, so nothing
8
+ // here imports another lib module, runs a child process or reads the clock on
9
+ // its own. The bridge calls `lines(ctx)`/`meta(ctx)` once per frame and both
10
+ // must return synchronously: they read ONE in-process snapshot and only ever
11
+ // SCHEDULE the refresh, so a frame never waits on `gh`.
12
+ //
13
+ // ONE source (`load` answers `{ ok, identity, issues, truncated }`): ONE merged
14
+ // list of the checkout repository's OPEN issues the viewer authored and the ones
15
+ // they are assigned, deduplicated by issue number by the caller that owns the
16
+ // read. A row is its label and its one pull-request number mark (S8/T9, drawn as
17
+ // `\ue726 #69` by S7/T5), never a relation; the header reports the merged count
18
+ // alone (`8 issues`, `8 issues · stale`), because the rail never separates `mine`
19
+ // from `assigned`. The heading reads `GITHUB` (S12/T10).
20
+ //
21
+ // `load` may also answer `{ ok: false, error, errorTone: 'dim' }` for a state
22
+ // that is not an error at all — a cwd outside a repository — so that one line is
23
+ // gray instead of red (S12/T11). A toned state is SETTLED (S3/T2 of
24
+ // issues-startup-performance): there is nothing to check outside a repository, so
25
+ // no later frame and no activity read retries it — only a session boundary
26
+ // supersedes it, exactly like the snapshot it replaced.
27
+ //
28
+ // Rows are ordered by `updatedAt` descending and the body paints at most SEVEN
29
+ // of them; when the read produced more, ONE eighth row in the `dim` tone reads
30
+ // `and N more issues`, `N` being the issues beyond the seven and written `N+`
31
+ // when the read reached its fetch bound (so the real total is larger). That
32
+ // keeps the body at the host's eight-row maximum, which is why the bridge's own
33
+ // inert `… +N more` elision never appears. The overflow row opens the `/issues`
34
+ // panel through the `openAll` seam.
35
+ //
36
+ // A row's `onClick` defers its opener onto the scheduler: it never runs on the
37
+ // paint path, it runs once per click, and a throw, a rejected promise or a
38
+ // resolved `{ ok: false, error }` is recorded in the snapshot's `error` instead
39
+ // of escaping into the host. The identity the row was BUILT from travels with
40
+ // it (`open(number, identity, bucket, generation)`), so a row the host retains
41
+ // across a checkout change still opens the repository it was read from instead of
42
+ // whatever snapshot is current when the human clicks — and the generation its read
43
+ // was taken under travels too, so a click the host retained across a session
44
+ // boundary cannot claim the repository of a session that has ended. Every state is
45
+ // a row — `loading…`, `no open issues`, ONE error row — and neither `lines()` nor
46
+ // `meta()` ever throws. Only `lines()` ever schedules a READ: a collapsed section
47
+ // draws solely its heading through `meta()`, so it reads nothing. What both
48
+ // drawing calls do own is the floor timer below (S10/T8), which a collapsed but
49
+ // drawn section keeps alive exactly like a drawn body — the heading is a frame the
50
+ // host painted, so the rail is on screen.
51
+ //
52
+ // A session that starts in ANOTHER checkout supersedes this one through
53
+ // `invalidate()`: the snapshot is dropped (the rail shows the loading row, never
54
+ // the previous repository's rows) and the latest-wins token moves on, so an
55
+ // answer the previous checkout's read delivers afterwards is discarded instead
56
+ // of applied. That drop is synchronous by design — the caller performs it the
57
+ // moment the session boundary fires.
58
+ //
59
+ // `refreshIfStale(maxAgeMs)` is the seam the caller's own activity uses: a frame
60
+ // only exists when the host has a reason to produce one, so the TTL on a drawn
61
+ // frame never fires on a session that is only being used. The caller asks for a
62
+ // read on the session's own activity behind a floor — but ONLY while the section
63
+ // is actually on screen: `lines()` and `meta()` are the drawing calls and each
64
+ // stamps WHEN it was last drawn, `drawnWithin(maxAgeMs)` answers whether a draw
65
+ // happened inside that window, and `invalidate()`/`dispose()` clear it. A hidden
66
+ // section therefore starts nothing at all: no child process, no network, no
67
+ // timer. The module reads no clock but the one it was injected with.
68
+ //
69
+ // S10 (T8, L9): the activity floor alone never refreshes an IDLE session, and the
70
+ // user's own words were "deberia ser algo que compruebe cada cierto tiempo nomas,
71
+ // como cada 10seg o 20seg". So a caller that names a `refreshFloorMs` gets the
72
+ // other half: while the section is DRAWN the module keeps ONE self-scheduled,
73
+ // unref'd timer at that floor, which fires one read, arms the next floor, and
74
+ // stops by itself once the section leaves the drawn window. It is armed by a
75
+ // draw, so a section nobody draws keeps no timer (S11) — and it is cleared by
76
+ // `invalidate()` and `dispose()`, which is what a session boundary performs.
77
+ //
78
+ // `forceRefresh(minIntervalMs)` is the second seam:
79
+ // ONE read the caller knows is worth starting right now (a `bash` command that
80
+ // mutated an issue or a pull request, S10/T9), bypassing the frame TTL and the
81
+ // activity floor but never the anti-storm cap the caller names.
82
+ //
83
+ // The module never leaves a timer or a state write behind after `dispose()`:
84
+ // whatever the read lands with is dropped silently.
85
+
86
+ const DEFAULT_TTL_MS = 60000;
87
+ // S11: how long a section counts as DRAWN after its last frame when the module
88
+ // owns the time check itself. It is the caller's window unless it names one.
89
+ const DEFAULT_TIMER_DRAWN_WINDOW_MS = 120000;
90
+ // The host's body holds eight rows and the eighth is the overflow row, so a
91
+ // larger `maxRows` would push the bridge's own inert elision into play: the
92
+ // retained rows are capped one below the body.
93
+ const BODY_MAX_ROWS = 8;
94
+ const DEFAULT_MAX_ROWS = BODY_MAX_ROWS - 1;
95
+ const LOADING_ROW = { label: 'loading…', tone: 'dim' };
96
+ const EMPTY_ROW = { label: 'no open issues', tone: 'dim' };
97
+ // S8 (T9): the ONE mark a row can carry is the pull request's NUMBER, and S7
98
+ // (T5) puts the nerd-font pull-request glyph in front of it: `\ue726 #69`, the
99
+ // glyph, ONE space, `#` and the number. `meta` is the bridge's right-hand,
100
+ // right-aligned segment and it paints it in its own idle `muted` role
101
+ // (`gentle-shell-bridge/src/section-panel.ts`, `IDLE_META_ROLE = 'muted'`), which
102
+ // IS the gray the user asked for — so the mark is gray while the row's `tone`
103
+ // stays the plain `text` and nothing paints the whole row gray to gray one
104
+ // segment. The number is the LAST associated pull request (the read hands it
105
+ // over already decided); no number, no mark. There is still exactly ONE click
106
+ // target on the line — the issue — because the bridge's `SectionRow` carries a
107
+ // single `onClick`, so a second target (the pull request in a browser) has no
108
+ // contract today. This is noted where the mark is built.
109
+ const PR_MARK_GLYPH = '\ue726';
110
+ const READ_FAILED = 'cannot read issues';
111
+ // T12 (S4, L11) moved the row click's destination into the extension: the row
112
+ // dispatches `/issues <number>` and the panel proves its own repository, so the
113
+ // fallback line a failed click is recorded with no longer names a browser.
114
+ const OPEN_FAILED = 'cannot open the issue';
115
+ const OPEN_ALL_FAILED = 'cannot open the issues panel';
116
+
117
+ function textOf(value, fallback) {
118
+ if (value && typeof value.message === 'string' && value.message.length > 0) return value.message;
119
+ if (typeof value === 'string' && value.length > 0) return value;
120
+ return fallback;
121
+ }
122
+
123
+ function updatedAtValue(item) {
124
+ const raw = item && typeof item === 'object' ? item.updatedAt : null;
125
+ const parsed = typeof raw === 'string' ? Date.parse(raw) : Number.NaN;
126
+ return Number.isFinite(parsed) ? parsed : Number.NEGATIVE_INFINITY;
127
+ }
128
+
129
+ function issueRows(issues, limit) {
130
+ // Descending by the ISO `updatedAt`; a missing date sorts last, so the order
131
+ // is deterministic across frames. S7 (T8): the read hands over one MERGED list
132
+ // (mine + assigned, deduplicated by number), so the order here is the merged
133
+ // order and the cap is the same seven.
134
+ return issues
135
+ .slice()
136
+ .sort((left, right) => updatedAtValue(right) - updatedAtValue(left))
137
+ .slice(0, limit)
138
+ .map((item) => {
139
+ const title = typeof item.title === 'string' ? item.title : '';
140
+ // `number` and `bucket` stay on the snapshot row so the deferred click
141
+ // binds the issue AND the bucket it came from. The painted row below
142
+ // exposes only its label, tone, click and — when its issue has a linked
143
+ // pull request — that pull request's number as `meta`. A row without one
144
+ // carries NO `meta` key at all, so nothing pends on `undefined` meaning the
145
+ // same thing as absent.
146
+ //
147
+ // S8 (T9): the whole line keeps ONE click target, the issue itself. The
148
+ // `#<number>` mark shares the row's single `onClick` because a
149
+ // `SectionRow` has exactly one, so a click on the number opens the issue
150
+ // too; the bridge has no per-segment handler to open the pull request
151
+ // instead.
152
+ const row = {
153
+ label: `#${item.number} ${title}`,
154
+ tone: 'text',
155
+ onClick: null,
156
+ number: item.number,
157
+ bucket: item.bucket,
158
+ };
159
+ if (Number.isInteger(item.pullRequestNumber) && item.pullRequestNumber > 0) {
160
+ row.meta = `${PR_MARK_GLYPH} #${item.pullRequestNumber}`;
161
+ }
162
+ return row;
163
+ });
164
+ }
165
+
166
+ function overflowRow(hidden, truncated) {
167
+ const suffix = truncated === true ? '+' : '';
168
+ return { label: `and ${hidden}${suffix} more issues`, tone: 'dim', onClick: null };
169
+ }
170
+
171
+ function createIssuesSection(options = {}) {
172
+ const opts = options && typeof options === 'object' ? options : {};
173
+ const load = typeof opts.load === 'function' ? opts.load : null;
174
+ const open = typeof opts.open === 'function' ? opts.open : null;
175
+ const openAll = typeof opts.openAll === 'function' ? opts.openAll : null;
176
+ const now = typeof opts.now === 'function' ? opts.now : Date.now;
177
+ const schedule = typeof opts.schedule === 'function' ? opts.schedule : (fn) => setTimeout(fn, 0);
178
+ // S10 (T8): the two timer seams, injected exactly like `schedule` so a test
179
+ // drives the floor without waiting for it. No floor named, no timer: a caller
180
+ // that only wants the frame TTL gets the module it always had.
181
+ const setTimer = typeof opts.setTimer === 'function' ? opts.setTimer : (fn, ms) => setTimeout(fn, ms);
182
+ const cancelTimer = typeof opts.clearTimer === 'function' ? opts.clearTimer : (timer) => clearTimeout(timer);
183
+ const refreshFloorMs = Number.isFinite(opts.refreshFloorMs) && opts.refreshFloorMs > 0
184
+ ? opts.refreshFloorMs
185
+ : null;
186
+ const timerDrawnWindowMs = Number.isFinite(opts.timerDrawnWindowMs) && opts.timerDrawnWindowMs >= 0
187
+ ? opts.timerDrawnWindowMs
188
+ : DEFAULT_TIMER_DRAWN_WINDOW_MS;
189
+ const ttlMs = Number.isFinite(opts.ttlMs) && opts.ttlMs >= 0 ? opts.ttlMs : DEFAULT_TTL_MS;
190
+ const requestedRows = Number.isFinite(opts.maxRows) && opts.maxRows > 0
191
+ ? Math.floor(opts.maxRows)
192
+ : DEFAULT_MAX_ROWS;
193
+ const maxRows = Math.min(requestedRows, DEFAULT_MAX_ROWS);
194
+ const sectionId = typeof opts.sectionId === 'string' && opts.sectionId.length > 0 ? opts.sectionId : 'odd-worktree.issues';
195
+ const title = typeof opts.title === 'string' && opts.title.length > 0 ? opts.title : 'GITHUB';
196
+ const rowLabel = typeof opts.rowLabel === 'string' && opts.rowLabel.length > 0 ? opts.rowLabel : 'issues';
197
+ const onRefreshed = typeof opts.onRefreshed === 'function' ? opts.onRefreshed : null;
198
+
199
+ let snapshot = null;
200
+ // A refresh that is scheduled but has not started, and the one that runs.
201
+ // Both are module state so two stale frames schedule ONE refresh and a frame
202
+ // drawn while it runs schedules nothing. `runToken` is the latest-wins
203
+ // boundary: an explicit refresh never coalesces onto an older in-flight run,
204
+ // and a result from a run that is no longer the latest is dropped.
205
+ let scheduled = false;
206
+ let running = null;
207
+ let runToken = 0;
208
+ let disposed = false;
209
+ // T15 (S3, defects 1 and 2): two facts the stale checks need besides the
210
+ // snapshot. `lastAttemptAt` is when the last read SETTLED, success or failure,
211
+ // so a failing `gh` starts the floor/TTL instead of being retried at the same
212
+ // instant; `generation` is the token a DEFERRED refresh captured when it was
213
+ // queued, so a callback that outlives `invalidate()`/`dispose()`/its checkout
214
+ // starts no read at all. `snapshot.at` still means the last SUCCESSFUL read
215
+ // (S5 keeps the stale header at that time) — the attempt time is separate.
216
+ let lastAttemptAt = null;
217
+ let generation = 0;
218
+ // S3 amended (T13, L11): WHEN the section was last DRAWN. A hidden section
219
+ // costs nothing, so the caller asks (`drawnWithin`) before an activity read and
220
+ // reads only when the host actually painted the section recently. `lines()` and
221
+ // `meta()` are the drawing calls, and a superseded (`invalidate()`) or disposed
222
+ // section is showing nothing, so both clear it.
223
+ let lastDrawnAt = null;
224
+ // S10 (T8): the ONE self-scheduled floor timer, and the token that makes a
225
+ // callback the host already queued inert once the timer was cleared.
226
+ let timer = null;
227
+ let timerToken = 0;
228
+ // S10 (T9): when the last FORCED read started, so the caller's anti-storm cap
229
+ // measures from it. Null until one runs.
230
+ let lastForcedAt = null;
231
+
232
+ // The time the staleness checks measure from: the last SETTLED attempt when
233
+ // there is one, otherwise the last snapshot. Measuring the TTL from a failed
234
+ // attempt is what keeps a frame after a failure from retrying immediately.
235
+ function lastAttempt() {
236
+ if (lastAttemptAt !== null) return lastAttemptAt;
237
+ return snapshot === null ? null : snapshot.at;
238
+ }
239
+
240
+ // S3 (T2 of issues-startup-performance): a failure the caller TONED — the one
241
+ // dim line a cwd outside a git repository draws — is a STATE, not a failure to
242
+ // retry. There is nothing to check outside a repository, so the activity floor,
243
+ // the frame TTL and every later frame schedule nothing at all: the line stays
244
+ // until a session boundary supersedes it (`invalidate()`/`dispose()`). An
245
+ // explicit `refresh()` is still the caller's own decision.
246
+ function stateSettled() {
247
+ return snapshot !== null
248
+ && snapshot.status === 'error'
249
+ && (snapshot.tone === 'dim' || snapshot.tone === 'muted');
250
+ }
251
+
252
+ function isStale() {
253
+ if (snapshot === null) return true;
254
+ if (stateSettled()) return false;
255
+ const age = now() - lastAttempt();
256
+ return !Number.isFinite(age) || age >= ttlMs;
257
+ }
258
+
259
+ function ensureFresh() {
260
+ if (disposed || scheduled || running !== null) return;
261
+ if (!isStale()) return;
262
+ const queuedGeneration = generation;
263
+ scheduled = true;
264
+ try {
265
+ schedule(() => {
266
+ // T15 (defect 2): a callback that outlived the section it was queued
267
+ // for — an `invalidate()`, a `dispose()` or a newer checkout — does
268
+ // nothing. It leaves `scheduled` to whichever callback still owns it.
269
+ if (disposed || queuedGeneration !== generation) return undefined;
270
+ scheduled = false;
271
+ // A run that started while this one was queued already covers the
272
+ // staleness: the TTL path starts nothing besides its own run.
273
+ if (running !== null) return undefined;
274
+ return refresh();
275
+ });
276
+ } catch {
277
+ scheduled = false;
278
+ }
279
+ }
280
+
281
+ // S10 (T8): drop the floor timer. The token moves on FIRST, so a callback the
282
+ // host already queued cannot read through a timer this section no longer owns.
283
+ function clearFloorTimer() {
284
+ timerToken += 1;
285
+ if (timer === null) return;
286
+ const handle = timer;
287
+ timer = null;
288
+ try {
289
+ cancelTimer(handle);
290
+ } catch {
291
+ // A timer the host will not cancel still finds the token moved on.
292
+ }
293
+ }
294
+
295
+ // S10 (T8, L9): arm the ONE floor timer. It is armed by a DRAW and never by a
296
+ // second timer of its own while one is running, so a burst of frames can never
297
+ // stack two reads; the fire turns into the next floor's arm.
298
+ function armFloorTimer() {
299
+ if (disposed || refreshFloorMs === null || timer !== null) return;
300
+ // S11/S3 (T2): a state the caller toned — a cwd outside a repository — has
301
+ // nothing to check, so it keeps no timer either.
302
+ if (stateSettled()) return;
303
+ const token = (timerToken += 1);
304
+ let handle = null;
305
+ try {
306
+ handle = setTimer(() => {
307
+ // A timer that was cleared (or superseded) while the host held its
308
+ // callback: the token is what makes it inert.
309
+ if (token !== timerToken) return;
310
+ timer = null;
311
+ if (disposed) return;
312
+ if (stateSettled()) return;
313
+ // S11: the moment the section is no longer drawn, the timer stops by
314
+ // itself — no read, and no next floor.
315
+ if (!drawnWithin(timerDrawnWindowMs)) return;
316
+ // One read per floor: a read already in flight owns this instant.
317
+ refreshIfStale(refreshFloorMs);
318
+ armFloorTimer();
319
+ }, refreshFloorMs);
320
+ } catch {
321
+ timer = null;
322
+ return;
323
+ }
324
+ timer = handle;
325
+ // Unref'd: the floor is never a reason for the process to stay alive.
326
+ if (handle && typeof handle.unref === 'function') {
327
+ try {
328
+ handle.unref();
329
+ } catch {
330
+ // A handle without a working unref still bounds the wait.
331
+ }
332
+ }
333
+ }
334
+
335
+ function replace(next) {
336
+ snapshot = next;
337
+ if (onRefreshed !== null) {
338
+ try {
339
+ onRefreshed();
340
+ } catch {
341
+ // A repaint failure never breaks the frame that reads the snapshot.
342
+ }
343
+ }
344
+ }
345
+
346
+ function apply(result) {
347
+ const at = now();
348
+ // T15 (defect 1): every settled attempt — success or failure — starts the
349
+ // floor and the frame TTL. `snapshot.at` is left alone by the failure branch
350
+ // below, which is what keeps it the last SUCCESSFUL read.
351
+ lastAttemptAt = at;
352
+ if (result && result.ok === true) {
353
+ // S8 (T9): the per-issue mark facts are normalized here, once, so every
354
+ // entry the snapshot exposes reports them in one shape — an absent or
355
+ // ambiguous answer is `hasPullRequest: false` and `pullRequestNumber:
356
+ // null`, never `undefined`, and the row renders no mark.
357
+ // S7 (T8): the bucket the row came from is carried through the same way,
358
+ // so the click can ask it of the opener.
359
+ const rawIssues = Array.isArray(result.issues) ? result.issues : [];
360
+ const issues = rawIssues.map((item) => {
361
+ const entry = item && typeof item === 'object' ? item : {};
362
+ const number = Number(entry.pullRequestNumber);
363
+ return {
364
+ ...entry,
365
+ hasPullRequest: entry.hasPullRequest === true,
366
+ pullRequestNumber: Number.isInteger(number) && number > 0 ? number : null,
367
+ };
368
+ });
369
+ // S4: the identity is captured HERE, together with the rows it labels, so
370
+ // the click never reads the current snapshot. A row retained on screen
371
+ // across a checkout change keeps the repository its number was read from.
372
+ const identity = result.identity === undefined ? null : result.identity;
373
+ const truncated = result.truncated === true;
374
+ // S2 (issues-sidebar-click T1, correction): the generation the caller's read
375
+ // was taken under rides the row into the `open` seam, opaquely. The section
376
+ // never reads it and keeps no second clock: it is how the opener tells a row
377
+ // read by the session that is still running from one the host retained across
378
+ // a session boundary. A read that carries none hands `null`.
379
+ const readGeneration = result.generation === undefined ? null : result.generation;
380
+ const rows = issueRows(issues, maxRows);
381
+ for (const row of rows) {
382
+ row.onClick = deferSeam(
383
+ () => (open === null ? undefined : open(row.number, identity, row.bucket, readGeneration)),
384
+ OPEN_FAILED,
385
+ );
386
+ }
387
+ if (issues.length > maxRows) {
388
+ const row = overflowRow(issues.length - maxRows, truncated);
389
+ row.onClick = deferSeam(() => (openAll === null ? undefined : openAll()), OPEN_ALL_FAILED);
390
+ rows.push(row);
391
+ }
392
+ replace({
393
+ status: 'ready',
394
+ at,
395
+ identity,
396
+ issues,
397
+ error: null,
398
+ rows,
399
+ truncated,
400
+ });
401
+ return;
402
+ }
403
+ const error = textOf(result && result.error, READ_FAILED);
404
+ // S5 amended (T10): once a list is on screen, a failed refresh is a
405
+ // transient stall, not an empty repository — a `gh` killed by its 30 s bound
406
+ // must never cost the human seven good rows. The rows stay exactly as they
407
+ // were (same rows, same order, same markers), `error` records the reason for
408
+ // a caller, and `status` becomes the fourth value `stale`. `at` keeps the
409
+ // time of the last SUCCESSFUL read, so the TTL still sees an aged snapshot
410
+ // and keeps retrying. Only a failure with nothing to show is an error row.
411
+ if (snapshot !== null && (snapshot.status === 'ready' || snapshot.status === 'stale')) {
412
+ replace({ ...snapshot, status: 'stale', error });
413
+ return;
414
+ }
415
+ // S12 (T11): the caller may say a failure is not an error at all — a cwd
416
+ // outside a repository is one short gray line, not the red the read failures
417
+ // wear. Only the two secondary roles it asks for are honored; every other
418
+ // failure keeps the `error` tone.
419
+ const tone = result && (result.errorTone === 'dim' || result.errorTone === 'muted')
420
+ ? result.errorTone
421
+ : 'error';
422
+ replace({
423
+ status: 'error',
424
+ at,
425
+ identity: null,
426
+ issues: [],
427
+ error,
428
+ tone,
429
+ rows: [],
430
+ truncated: false,
431
+ });
432
+ // S13 (T11) / S3 (T2): a TONED failure is a STATE, not a failure to retry — a
433
+ // cwd outside a repository, or a missing `gh` CLI — so it owns no timer either.
434
+ // The draw that preceded it armed the floor, and that one is dropped HERE
435
+ // instead of surviving to its next fire only to find the state settled.
436
+ if (tone === 'dim' || tone === 'muted') clearFloorTimer();
437
+ }
438
+
439
+ function recordOpenError(err, fallback) {
440
+ if (disposed) return;
441
+ const error = textOf(err, fallback);
442
+ if (snapshot === null) {
443
+ replace({
444
+ status: 'error',
445
+ at: now(),
446
+ identity: null,
447
+ issues: [],
448
+ error,
449
+ rows: [],
450
+ truncated: false,
451
+ });
452
+ return;
453
+ }
454
+ // One field changes: a click failure never turns a ready list into an
455
+ // error row, it is only recorded for the next reader.
456
+ snapshot = { ...snapshot, error };
457
+ }
458
+
459
+ // A resolved `{ ok: false, error }` is how the extension's openers report a
460
+ // failure (they catch and resolve, never reject), so it takes the same path a
461
+ // throw does. A resolved `{ ok: true }` or a plain `undefined` records
462
+ // nothing, and a ready list stays a ready list.
463
+ function applyOpenOutcome(outcome, fallback) {
464
+ if (disposed) return undefined;
465
+ if (outcome && typeof outcome === 'object' && outcome.ok === false) {
466
+ recordOpenError(outcome.error, fallback);
467
+ }
468
+ return undefined;
469
+ }
470
+
471
+ // One click is one deferred run of one injected seam, and the run's outcome is
472
+ // classified here: never a throw on the paint path, never an unhandled
473
+ // rejection, and a failure lands in the snapshot instead of the host.
474
+ function deferSeam(invoke, fallback) {
475
+ return () => {
476
+ if (disposed) return undefined;
477
+ try {
478
+ schedule(() => {
479
+ if (disposed) return undefined;
480
+ let outcome;
481
+ try {
482
+ outcome = invoke();
483
+ } catch (err) {
484
+ recordOpenError(err, fallback);
485
+ return undefined;
486
+ }
487
+ if (outcome && typeof outcome.then === 'function') {
488
+ return Promise.resolve(outcome).then(
489
+ (value) => applyOpenOutcome(value, fallback),
490
+ (err) => recordOpenError(err, fallback),
491
+ );
492
+ }
493
+ return applyOpenOutcome(outcome, fallback);
494
+ });
495
+ } catch {
496
+ // A scheduler that refuses the work leaves the list as it was.
497
+ }
498
+ return undefined;
499
+ };
500
+ }
501
+
502
+ // An explicit refresh always starts its own read: coalescing it onto a run the
503
+ // previous checkout started would land that checkout's rows. The latest run
504
+ // wins, so an older run that settles later is dropped instead of overwriting
505
+ // it. The TTL path guards itself in `ensureFresh` and never reaches this while
506
+ // a run is in flight.
507
+ function refresh() {
508
+ if (disposed) return Promise.resolve(snapshot);
509
+ const token = (runToken += 1);
510
+ let pending;
511
+ try {
512
+ pending = load === null ? Promise.resolve({ ok: false, error: READ_FAILED }) : Promise.resolve(load());
513
+ } catch (err) {
514
+ pending = Promise.reject(err);
515
+ }
516
+ const run = pending.then(
517
+ (result) => {
518
+ if (disposed || token !== runToken) return snapshot;
519
+ apply(result);
520
+ return snapshot;
521
+ },
522
+ (err) => {
523
+ if (disposed || token !== runToken) return snapshot;
524
+ apply({ ok: false, error: textOf(err, READ_FAILED) });
525
+ return snapshot;
526
+ },
527
+ );
528
+ running = run;
529
+ const settle = () => {
530
+ if (running === run) running = null;
531
+ };
532
+ run.then(settle, settle);
533
+ return run;
534
+ }
535
+
536
+ // S6: the supersede the session boundary performs when the checkout changes.
537
+ // Dropping the snapshot is what makes the rail fall back to the loading row;
538
+ // bumping the token is what makes an in-flight answer from the previous
539
+ // checkout land nowhere. It starts no read, reports no repaint and never
540
+ // throws, and after `dispose()` it does nothing at all. S10 (T8,T9): the
541
+ // session boundary also clears the floor timer and the forced-read cap, so
542
+ // nothing timed outlives the session that armed it.
543
+ function invalidate() {
544
+ if (disposed) return;
545
+ snapshot = null;
546
+ runToken += 1;
547
+ scheduled = false;
548
+ lastDrawnAt = null;
549
+ clearFloorTimer();
550
+ lastForcedAt = null;
551
+ // T15 (defects 1 and 2): the previous checkout's attempt no longer sets the
552
+ // floor, and a refresh already queued for it is now stale.
553
+ lastAttemptAt = null;
554
+ generation += 1;
555
+ }
556
+
557
+ // S3 (activity floor): the caller's session events ask for a read at most once
558
+ // per floor. It goes through `refresh()`, so the latest-wins token is the same
559
+ // one an explicit refresh uses, and it starts ONE read when the snapshot is
560
+ // absent or at least `maxAgeMs` old. A fresher snapshot, a read already in
561
+ // flight and a disposed module start nothing. It answers whether a read
562
+ // started, and it never throws or rejects.
563
+ function refreshIfStale(maxAgeMs) {
564
+ if (disposed) return false;
565
+ if (running !== null) return false;
566
+ // S3 (T2): nothing to check outside a repository, so the activity seam starts
567
+ // nothing either — however long the session lives there.
568
+ if (stateSettled()) return false;
569
+ if (snapshot !== null) {
570
+ // T15 (defect 1): a failed attempt starts the activity floor too.
571
+ const age = now() - lastAttempt();
572
+ if (Number.isFinite(age) && age < maxAgeMs) return false;
573
+ }
574
+ try {
575
+ const pending = refresh();
576
+ if (pending && typeof pending.catch === 'function') pending.catch(() => {});
577
+ return true;
578
+ } catch {
579
+ return false;
580
+ }
581
+ }
582
+
583
+ // S10 (T9): the caller's ONE forced read. It bypasses the frame TTL and the
584
+ // activity floor — the caller knows something changed — but never the anti-storm
585
+ // cap it names, and never a read already in flight. It answers whether a read
586
+ // started, and it never throws.
587
+ function forceRefresh(minIntervalMs) {
588
+ if (disposed) return false;
589
+ if (running !== null) return false;
590
+ // S3 (T2): nothing to check outside a repository, so nothing is forced there.
591
+ if (stateSettled()) return false;
592
+ let at = null;
593
+ try {
594
+ at = now();
595
+ } catch {
596
+ at = null;
597
+ }
598
+ if (lastForcedAt !== null && Number.isFinite(at)) {
599
+ const age = at - lastForcedAt;
600
+ if (!Number.isFinite(age) || age < minIntervalMs) return false;
601
+ }
602
+ try {
603
+ const pending = refresh();
604
+ if (pending && typeof pending.catch === 'function') pending.catch(() => {});
605
+ lastForcedAt = Number.isFinite(at) ? at : null;
606
+ return true;
607
+ } catch {
608
+ return false;
609
+ }
610
+ }
611
+
612
+ function lines(_ctx) {
613
+ try {
614
+ // S3 amended (T13): a drawn body is the host painting the section, and that
615
+ // is what the caller's activity trigger is gated on.
616
+ noteDrawn();
617
+ ensureFresh();
618
+ if (snapshot === null) return [{ ...LOADING_ROW }];
619
+ if (snapshot.status === 'error') return [{ label: snapshot.error, tone: snapshot.tone || 'error' }];
620
+ if (snapshot.rows.length === 0) return [{ ...EMPTY_ROW }];
621
+ // A copy per frame: the host may keep the array it was handed, and the
622
+ // snapshot stays the one source the TTL and the clicks read. A row's
623
+ // marker travels with it, so a stale list keeps the markers it had.
624
+ return snapshot.rows.map((row) => (row.meta === undefined
625
+ ? { label: row.label, tone: row.tone, onClick: row.onClick }
626
+ : { label: row.label, tone: row.tone, meta: row.meta, onClick: row.onClick }));
627
+ } catch {
628
+ return [{ ...LOADING_ROW }];
629
+ }
630
+ }
631
+
632
+ function meta(_ctx) {
633
+ try {
634
+ // S3 amended (T13): a collapsed header is still a drawn section — the host
635
+ // painted it — so it stamps the drawn frame like the body does.
636
+ noteDrawn();
637
+ // The heading only reads the snapshot. A collapsed section is drawn with
638
+ // this call alone, so scheduling a refresh here would make it cost the
639
+ // network it is supposed to cost nothing. S7 (T8): the count is the MERGED
640
+ // list's length, before any display cap, and S12 (T10) names its unit:
641
+ // `7 issues`, and `7 issues · stale` while the list is stalled. The rail
642
+ // never separates mine from assigned, so it never names either. A stale
643
+ // list still has a count — the one the last successful read produced — and
644
+ // it says so instead of hiding the failure. No snapshot is no count.
645
+ if (snapshot === null) return undefined;
646
+ if (snapshot.status === 'stale') return `${snapshot.issues.length} issues · stale`;
647
+ if (snapshot.status !== 'ready') return undefined;
648
+ return `${snapshot.issues.length} issues`;
649
+ } catch {
650
+ return undefined;
651
+ }
652
+ }
653
+
654
+ function snapshotOf() {
655
+ return snapshot;
656
+ }
657
+
658
+ // S3 amended (T13, L11): a drawing call stamps the frame. A clock that throws
659
+ // or answers nonsense costs the drawn window, never the frame itself.
660
+ function noteDrawn() {
661
+ try {
662
+ const at = now();
663
+ if (Number.isFinite(at)) lastDrawnAt = at;
664
+ } catch {
665
+ // The frame is drawn; only its stamp is lost.
666
+ }
667
+ // S10 (T8): the drawn frame is also what owns the floor timer — a section the
668
+ // host stops painting keeps it no longer than the drawn window.
669
+ armFloorTimer();
670
+ }
671
+
672
+ // S3 amended (T13, L11): true only while a successful draw happened at or
673
+ // after `now() - maxAgeMs`. An undrawn, superseded or disposed section answers
674
+ // false, and that answer is what keeps a hidden section free: the caller reads
675
+ // only on `true`. It starts no work and never throws.
676
+ function drawnWithin(maxAgeMs) {
677
+ if (disposed || lastDrawnAt === null) return false;
678
+ let at;
679
+ try {
680
+ at = now();
681
+ } catch {
682
+ return false;
683
+ }
684
+ const age = at - lastDrawnAt;
685
+ return Number.isFinite(age) && age <= maxAgeMs;
686
+ }
687
+
688
+ function dispose() {
689
+ disposed = true;
690
+ scheduled = false;
691
+ lastDrawnAt = null;
692
+ clearFloorTimer();
693
+ lastForcedAt = null;
694
+ // T15 (defect 2): a refresh already queued for this section is stale.
695
+ generation += 1;
696
+ }
697
+
698
+ const section = {
699
+ id: sectionId,
700
+ title,
701
+ rowLabel,
702
+ defaultVisible: true,
703
+ meta,
704
+ lines,
705
+ };
706
+
707
+ return { section, refresh, refreshIfStale, forceRefresh, invalidate, drawnWithin, snapshot: snapshotOf, dispose };
708
+ }
709
+
710
+ module.exports = { createIssuesSection };