@wrongstack/tools 0.313.0 → 0.316.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 (182) hide show
  1. package/dist/_edit-match.d.ts +3 -2
  2. package/dist/_output-spool.d.ts +4 -3
  3. package/dist/_shell-pick.d.ts +2 -1
  4. package/dist/_spawn-stream.d.ts +2 -1
  5. package/dist/_syntax-check.d.ts +2 -1
  6. package/dist/audit.js +10 -4055
  7. package/dist/bash-kill-guard.d.ts +3 -6
  8. package/dist/bash.js +9 -2308
  9. package/dist/batch-tool-use.js +2 -187
  10. package/dist/browser/index.js +25 -1339
  11. package/dist/browser/network-guard-proxy.d.ts +2 -1
  12. package/dist/builtin.js +69 -33949
  13. package/dist/chunk-22B7GE5T.js +260 -0
  14. package/dist/chunk-2VSZC6QM.js +113 -0
  15. package/dist/chunk-3PVYQFRQ.js +472 -0
  16. package/dist/chunk-42BHI7TN.js +337 -0
  17. package/dist/chunk-4BHUSMNL.js +104 -0
  18. package/dist/chunk-4I4LWFOO.js +431 -0
  19. package/dist/chunk-4UESMQDP.js +122 -0
  20. package/dist/chunk-553IQUMO.js +478 -0
  21. package/dist/chunk-5H4GSJAI.js +223 -0
  22. package/dist/chunk-6RNIFLG4.js +305 -0
  23. package/dist/chunk-7EY5DCRO.js +434 -0
  24. package/dist/chunk-A6BRWIXN.js +317 -0
  25. package/dist/chunk-AHHDWNXC.js +200 -0
  26. package/dist/chunk-BSLVR56S.js +199 -0
  27. package/dist/chunk-BTSFTGIL.js +7 -0
  28. package/dist/chunk-D33S4RQG.js +222 -0
  29. package/dist/chunk-DA4KNE2H.js +4412 -0
  30. package/dist/chunk-DR7JOQTC.js +520 -0
  31. package/dist/chunk-EEOFQDT6.js +898 -0
  32. package/dist/chunk-EJWSCQ6D.js +137 -0
  33. package/dist/chunk-EMRGN4KM.js +170 -0
  34. package/dist/chunk-FQZOHLG3.js +89 -0
  35. package/dist/chunk-GOIZNNOA.js +221 -0
  36. package/dist/chunk-HFXSNKCV.js +196 -0
  37. package/dist/chunk-HYX2TZ7O.js +1272 -0
  38. package/dist/chunk-I64BS3VC.js +15 -0
  39. package/dist/chunk-IVWV2UM6.js +955 -0
  40. package/dist/chunk-IXMNTNW5.js +238 -0
  41. package/dist/chunk-IYK7XGDZ.js +892 -0
  42. package/dist/chunk-J5SKD6LN.js +235 -0
  43. package/dist/chunk-JNNVRHMV.js +2111 -0
  44. package/dist/chunk-JOHXDF3D.js +295 -0
  45. package/dist/chunk-JRJJX3L5.js +424 -0
  46. package/dist/chunk-K3WNSHUF.js +1371 -0
  47. package/dist/chunk-L25CVUVR.js +2830 -0
  48. package/dist/chunk-LIJQMYYX.js +59 -0
  49. package/dist/chunk-LWKUTMD5.js +197 -0
  50. package/dist/chunk-MQX2KXVW.js +54 -0
  51. package/dist/chunk-MZZN7VCD.js +359 -0
  52. package/dist/chunk-NBDZMMG2.js +169 -0
  53. package/dist/chunk-NKJW5GFO.js +366 -0
  54. package/dist/chunk-NKNOBUBU.js +522 -0
  55. package/dist/chunk-O4MBV4AX.js +134 -0
  56. package/dist/chunk-OUBDL3WH.js +3515 -0
  57. package/dist/chunk-PQKK5JH7.js +101 -0
  58. package/dist/chunk-PY2IOS7C.js +1000 -0
  59. package/dist/chunk-Q5JPPCZC.js +12 -0
  60. package/dist/chunk-QBV725YG.js +128 -0
  61. package/dist/chunk-QZQSPUBF.js +315 -0
  62. package/dist/chunk-RGISBZBD.js +231 -0
  63. package/dist/chunk-RJZQWEMS.js +84 -0
  64. package/dist/chunk-RXISBFR5.js +315 -0
  65. package/dist/chunk-S5CCLZL3.js +99 -0
  66. package/dist/chunk-SDLVH5RZ.js +178 -0
  67. package/dist/chunk-T2F4S7U4.js +1723 -0
  68. package/dist/chunk-TEBQ4VPZ.js +163 -0
  69. package/dist/chunk-U4D5S3VQ.js +21 -0
  70. package/dist/chunk-U4VAATKP.js +193 -0
  71. package/dist/chunk-UCYQTZ7F.js +113 -0
  72. package/dist/chunk-UKU2ZX4C.js +203 -0
  73. package/dist/chunk-UNSKG6DC.js +159 -0
  74. package/dist/chunk-V43EQ6VR.js +68 -0
  75. package/dist/chunk-VB3MJGCV.js +610 -0
  76. package/dist/chunk-VFKPWSOX.js +154 -0
  77. package/dist/chunk-VJNHFZ7J.js +190 -0
  78. package/dist/chunk-VXECAJJ7.js +1091 -0
  79. package/dist/chunk-WHIIIREL.js +223 -0
  80. package/dist/chunk-Z6DAKQ3U.js +1 -0
  81. package/dist/chunk-ZJQ4IGXK.js +474 -0
  82. package/dist/chunk-ZLTFLC25.js +385 -0
  83. package/dist/circuit-breaker.js +3 -191
  84. package/dist/codebase-index/ast-invariant-engine.d.ts +5 -4
  85. package/dist/codebase-index/binary-frame.d.ts +0 -2
  86. package/dist/codebase-index/bm25.d.ts +1 -1
  87. package/dist/codebase-index/circuit-breaker.d.ts +2 -1
  88. package/dist/codebase-index/codebase-ast-replace-tool.d.ts +3 -2
  89. package/dist/codebase-index/codebase-impact-analysis-tool.d.ts +4 -3
  90. package/dist/codebase-index/codebase-invariant-check-tool.d.ts +3 -2
  91. package/dist/codebase-index/codebase-repo-map-tool.d.ts +3 -2
  92. package/dist/codebase-index/codebase-skeleton-tool.d.ts +3 -2
  93. package/dist/codebase-index/codebase-targeted-test-tool.d.ts +3 -2
  94. package/dist/codebase-index/content-hash.d.ts +0 -2
  95. package/dist/codebase-index/import-extractor.d.ts +0 -13
  96. package/dist/codebase-index/index-service.d.ts +1 -1
  97. package/dist/codebase-index/index.js +84 -13688
  98. package/dist/codebase-index/languages.d.ts +2 -1
  99. package/dist/codebase-index/module-roots.d.ts +3 -2
  100. package/dist/codebase-index/parser-batch.d.ts +0 -5
  101. package/dist/codebase-index/parser-dispatch.d.ts +2 -1
  102. package/dist/codebase-index/parser-output.d.ts +4 -3
  103. package/dist/codebase-index/parser-worker-pool.d.ts +0 -2
  104. package/dist/codebase-index/parser-worker-script.d.ts +1 -16
  105. package/dist/codebase-index/parser-worker-script.js +8 -3995
  106. package/dist/codebase-index/project-server-client-state.d.ts +2 -2
  107. package/dist/codebase-index/project-server-endpoint.d.ts +0 -15
  108. package/dist/codebase-index/project-server.js +60 -8548
  109. package/dist/codebase-index/tree-sitter/visitor.d.ts +2 -1
  110. package/dist/codebase-index/tree-sitter-parser.d.ts +0 -2
  111. package/dist/codebase-index/ts-parser.d.ts +1 -1
  112. package/dist/codebase-index/vector-search.d.ts +2 -1
  113. package/dist/codebase-index/wal-maintenance.d.ts +3 -2
  114. package/dist/codebase-index/worker.js +20 -8416
  115. package/dist/codebase-index/writer-admin.d.ts +0 -1
  116. package/dist/codebase-index/writer-search.d.ts +0 -9
  117. package/dist/design.js +2 -299
  118. package/dist/diff.js +4 -256
  119. package/dist/document.js +4 -222
  120. package/dist/e2e.js +5 -476
  121. package/dist/edit.js +14 -10200
  122. package/dist/exec.js +16 -3131
  123. package/dist/fetch.js +8 -398
  124. package/dist/format.js +10 -3750
  125. package/dist/generic-parser-VUXDIAOZ.js +13 -0
  126. package/dist/git.js +4 -380
  127. package/dist/glob.js +6 -280
  128. package/dist/go-parser-JXYKJHRC.js +469 -0
  129. package/dist/grep.js +7 -604
  130. package/dist/index.js +318 -35387
  131. package/dist/install.js +10 -4091
  132. package/dist/json-parser-IBHZ4BZC.js +213 -0
  133. package/dist/json.js +4 -665
  134. package/dist/kanban-contract-actions.d.ts +1 -1
  135. package/dist/kanban-detail-actions.d.ts +2 -1
  136. package/dist/kanban-presence.d.ts +2 -1
  137. package/dist/kanban-serializer.d.ts +0 -8
  138. package/dist/kanban-split-task-handler.d.ts +2 -2
  139. package/dist/kanban-tool-types.d.ts +2 -1
  140. package/dist/kanban.js +3 -2096
  141. package/dist/languages/diagnostics.d.ts +2 -1
  142. package/dist/languages/index.js +23 -4664
  143. package/dist/languages/legacy-bridge.d.ts +3 -2
  144. package/dist/languages/types.d.ts +2 -1
  145. package/dist/legacy-bridge-7M6QLUQN.js +18 -0
  146. package/dist/lint.js +10 -3706
  147. package/dist/logs.js +4 -287
  148. package/dist/memory.js +6 -215
  149. package/dist/mode.js +3 -99
  150. package/dist/outdated.js +4 -5170
  151. package/dist/pack.js +65 -33897
  152. package/dist/parser-dispatch-QH4XPGG6.js +14 -0
  153. package/dist/patch.js +13 -9935
  154. package/dist/plan.js +5 -3286
  155. package/dist/process-registry.js +8 -651
  156. package/dist/ps-slash.js +12 -1439
  157. package/dist/pwsh.d.ts +0 -1
  158. package/dist/py-parser-IS4HKYMF.js +16 -0
  159. package/dist/read.js +13 -9816
  160. package/dist/replace.js +15 -10014
  161. package/dist/rs-parser-XHUUO2KZ.js +81 -0
  162. package/dist/scaffold.js +4 -253
  163. package/dist/search.js +5 -585
  164. package/dist/session-kanban-sync.d.ts +0 -6
  165. package/dist/session-kanban.js +30 -972
  166. package/dist/skill.js +2 -215
  167. package/dist/spawn-background.d.ts +1 -1
  168. package/dist/task.js +5 -3410
  169. package/dist/test.js +10 -3773
  170. package/dist/todo.js +4 -2891
  171. package/dist/tool-help.js +3 -123
  172. package/dist/tool-search.js +3 -79
  173. package/dist/tool-tier.js +68 -33984
  174. package/dist/tool-use.js +2 -93
  175. package/dist/tree-sitter-parser-AIERW3YI.js +15 -0
  176. package/dist/tree.js +4 -288
  177. package/dist/ts-parser-RCTYKSVI.js +232 -0
  178. package/dist/typecheck.js +10 -3753
  179. package/dist/win32.js +6 -60
  180. package/dist/write.js +14 -9882
  181. package/dist/yaml-parser-4SAXV3PL.js +157 -0
  182. package/package.json +5 -5
package/dist/ps-slash.js CHANGED
@@ -1,1442 +1,15 @@
1
- // src/ps-slash.ts
2
- import * as os3 from "node:os";
3
-
4
- // src/process-registry-persistent.ts
5
- import * as fs from "node:fs/promises";
6
- import * as os2 from "node:os";
7
- import { wstackGlobalRoot } from "@wrongstack/core/utils";
8
- import * as path from "node:path";
9
-
10
- // src/process-registry.ts
11
- import { spawn } from "node:child_process";
12
- import * as os from "node:os";
13
-
14
- // src/circuit-breaker.ts
15
- var DEFAULT_MAX_CONSECUTIVE_FAILURES = 5;
16
- var DEFAULT_SLOW_CALL_THRESHOLD_MS = 18e4;
17
- var DEFAULT_MAX_SLOW_CALLS = 3;
18
- var DEFAULT_WINDOW_MS = 6e4;
19
- var DEFAULT_MAX_CALLS_PER_WINDOW = 30;
20
- var DEFAULT_COOLDOWN_MS = 3e4;
21
- var CircuitBreaker = class {
22
- maxConsecutiveFailures;
23
- slowCallThresholdMs;
24
- maxSlowCalls;
25
- windowMs;
26
- maxCallsPerWindow;
27
- cooldownMs;
28
- state = "closed";
29
- consecutiveFailures = 0;
30
- window = [];
31
- lastFailureAt = null;
32
- lastSlowAt = null;
33
- /** Timestamp when the breaker was opened (for cooldown calculation). */
34
- openedAt = null;
35
- /**
36
- * Master enable flag. When false the breaker is bypassed: `beforeCall`
37
- * always returns true and `afterCall` records nothing. The class itself
38
- * defaults to enabled (so the standalone unit tests exercise tripping); the
39
- * ProcessRegistry flips this off until the user opts in via `/settings`.
40
- */
41
- enabled = true;
42
- /**
43
- * Fired (best-effort) when the breaker transitions into the `open` state.
44
- * The registry uses this to arm its auto kill/reset countdown.
45
- */
46
- onTrip;
47
- /**
48
- * Fired (best-effort) when the breaker returns to `closed` after having been
49
- * open/half-open. The registry uses this to cancel a pending kill/reset.
50
- */
51
- onReset;
52
- constructor(config = {}) {
53
- this.maxConsecutiveFailures = config.maxConsecutiveFailures ?? DEFAULT_MAX_CONSECUTIVE_FAILURES;
54
- this.slowCallThresholdMs = config.slowCallThresholdMs ?? DEFAULT_SLOW_CALL_THRESHOLD_MS;
55
- this.maxSlowCalls = config.maxSlowCalls ?? DEFAULT_MAX_SLOW_CALLS;
56
- this.windowMs = config.windowMs ?? DEFAULT_WINDOW_MS;
57
- this.maxCallsPerWindow = config.maxCallsPerWindow ?? DEFAULT_MAX_CALLS_PER_WINDOW;
58
- this.cooldownMs = config.cooldownMs ?? DEFAULT_COOLDOWN_MS;
59
- }
60
- /** Toggle the master enable. Disabling resets to a clean `closed` state. */
61
- setEnabled(enabled) {
62
- if (this.enabled === enabled) return;
63
- this.enabled = enabled;
64
- if (!enabled) this._reset();
65
- }
66
- get isEnabled() {
67
- return this.enabled;
68
- }
69
- /**
70
- * Returns true if the circuit allows a new call to proceed.
71
- * When false, callers should abort the tool call and return a
72
- * circuit-breaker error instead of spawning a process.
73
- */
74
- get canProceed() {
75
- if (!this.enabled) return true;
76
- this._checkStateTransition();
77
- return this.state !== "open";
78
- }
79
- /**
80
- * Snapshot of the current breaker state for observability (`/kill`).
81
- */
82
- snapshot() {
83
- this._checkStateTransition();
84
- const now2 = Date.now();
85
- let cooldownRemaining = null;
86
- if (this.openedAt !== null && this.state === "open") {
87
- const elapsed = now2 - this.openedAt;
88
- cooldownRemaining = Math.max(0, this.cooldownMs - elapsed);
89
- }
90
- return {
91
- state: this.state,
92
- consecutiveFailures: this.consecutiveFailures,
93
- slowCallsInWindow: this.window.filter((c) => c.slow).length,
94
- callsInWindow: this.window.length,
95
- windowMs: this.windowMs,
96
- cooldownRemainingMs: cooldownRemaining,
97
- lastFailureAt: this.lastFailureAt,
98
- lastSlowAt: this.lastSlowAt
99
- };
100
- }
101
- /**
102
- * Call this BEFORE spawning a bash/exec process.
103
- * Returns true if the call is allowed; false if the breaker is open.
104
- * When false, callers MUST NOT spawn a process.
105
- *
106
- * @param bypass - If true, skip the circuit breaker check entirely.
107
- * Use for background/fire-and-forget processes that should
108
- * not affect breaker state.
109
- */
110
- beforeCall(bypass = false) {
111
- if (bypass || !this.enabled) return true;
112
- this._checkStateTransition();
113
- if (this.state === "open") return false;
114
- return true;
115
- }
116
- /**
117
- * Call this AFTER a bash/exec process finishes (success or failure).
118
- * `durationMs` is the wall-clock time the process ran.
119
- * `failed` is true when the process returned a non-zero exit code or
120
- * threw an exception before spawning.
121
- *
122
- * @param bypass - If true, do not update breaker state.
123
- * Use for background/fire-and-forget processes.
124
- */
125
- afterCall(durationMs, failed, bypass = false) {
126
- if (bypass || !this.enabled) return;
127
- const now2 = Date.now();
128
- if (this.state === "half-open") {
129
- if (failed) {
130
- this._trip();
131
- return;
132
- }
133
- this._reset();
134
- return;
135
- }
136
- this._pruneWindow(now2);
137
- const slow = durationMs >= this.slowCallThresholdMs;
138
- this.window.push({ at: now2, failed, slow });
139
- if (failed) {
140
- this.consecutiveFailures++;
141
- this.lastFailureAt = now2;
142
- if (this.consecutiveFailures >= this.maxConsecutiveFailures) {
143
- this._trip();
144
- }
145
- return;
146
- }
147
- this.consecutiveFailures = 0;
148
- if (slow) {
149
- this.lastSlowAt = now2;
150
- const slowCount = this.window.filter((c) => c.slow).length;
151
- if (slowCount >= this.maxSlowCalls) {
152
- this._trip();
153
- }
154
- }
155
- const callCount = this.window.length;
156
- if (callCount >= this.maxCallsPerWindow) {
157
- this._trip();
158
- }
159
- }
160
- /** Force the breaker open. Used by /kill force and Ctrl+C. */
161
- forceOpen() {
162
- this._trip();
163
- }
164
- /** Force a reset to closed. Used by tests and /kill reset. */
165
- forceReset() {
166
- this._reset();
167
- }
168
- _trip() {
169
- if (this.state === "open") return;
170
- this.state = "open";
171
- this.openedAt = Date.now();
172
- this.window = [];
173
- try {
174
- this.onTrip?.();
175
- } catch {
176
- }
177
- }
178
- _reset() {
179
- const wasRecovering = this.state !== "closed";
180
- this.state = "closed";
181
- this.consecutiveFailures = 0;
182
- this.window = [];
183
- this.openedAt = null;
184
- if (wasRecovering) {
185
- try {
186
- this.onReset?.();
187
- } catch {
188
- }
189
- }
190
- }
191
- /** Transition from open → half-open when cooldown elapses. */
192
- _checkStateTransition() {
193
- if (this.state !== "open" || this.openedAt === null) return;
194
- const elapsed = Date.now() - this.openedAt;
195
- if (elapsed >= this.cooldownMs) {
196
- this.state = "half-open";
197
- this.openedAt = null;
198
- }
199
- }
200
- _pruneWindow(now2) {
201
- const cutoff = now2 - this.windowMs;
202
- this.window = this.window.filter((c) => c.at >= cutoff);
203
- }
204
- };
205
-
206
- // src/process-registry.ts
207
- var DEFAULT_GRACE_MS = 2e3;
208
- var WIN32_TASKKILL_TIMEOUT_MS = 5e3;
209
- function killWin32Tree(pid, opts = {}) {
210
- try {
211
- const child = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
212
- stdio: "ignore",
213
- windowsHide: true
214
- });
215
- let settled = false;
216
- let timeout;
217
- const settle = () => {
218
- if (settled) return;
219
- settled = true;
220
- if (timeout) clearTimeout(timeout);
221
- try {
222
- opts.onSettled?.();
223
- } catch {
224
- }
225
- };
226
- child.on("error", settle);
227
- child.on("close", settle);
228
- timeout = setTimeout(
229
- () => {
230
- try {
231
- child.kill();
232
- } catch {
233
- }
234
- settle();
235
- },
236
- Math.max(1, opts.timeoutMs ?? WIN32_TASKKILL_TIMEOUT_MS)
237
- );
238
- timeout.unref?.();
239
- child.unref();
240
- return true;
241
- } catch {
242
- return false;
243
- }
244
- }
245
- var ProcessRegistryImpl = class {
246
- processes = /* @__PURE__ */ new Map();
247
- breaker;
248
- /**
249
- * Auto kill/reset config. When the breaker trips and `autoKillResetMs > 0`,
250
- * a countdown is armed; on expiry all tracked processes are killed and the
251
- * breaker is reset to closed (forced recovery). Zero means manual recovery
252
- * only (`/kill reset`).
253
- */
254
- autoKillResetMs = 0;
255
- autoKillTimer = null;
256
- autoKillArmedAt = null;
257
- breakerCountdownListeners = [];
258
- constructor(breakerConfig) {
259
- this.breaker = new CircuitBreaker(breakerConfig);
260
- this.breaker.onTrip = () => this._armAutoKillReset();
261
- this.breaker.onReset = () => this._cancelAutoKillReset();
262
- this.breaker.setEnabled(false);
263
- }
264
- register(info) {
265
- this.processes.set(info.pid, {
266
- ...info,
267
- killed: false,
268
- protected: info.protected ?? false,
269
- background: info.background ?? false
270
- });
271
- }
272
- _isSafeSignalPid(pid) {
273
- return Number.isInteger(pid) && pid > 1 && pid !== process.pid && pid !== process.ppid;
274
- }
275
- _canSignalProcessGroup(p) {
276
- return os.platform() !== "win32" && p.processGroupLeader === true && this._isSafeSignalPid(p.pid) && p.child !== null && typeof p.child.pid === "number" && p.child.pid === p.pid;
277
- }
278
- _killChildDirect(p, signal) {
279
- try {
280
- if (p.child) {
281
- p.child.kill(signal);
282
- return;
283
- }
284
- if (this._isSafeSignalPid(p.pid)) process.kill(p.pid, signal);
285
- } catch {
286
- }
287
- }
288
- _killPosix(p, signal) {
289
- if (this._canSignalProcessGroup(p)) {
290
- try {
291
- process.kill(-p.pid, signal);
292
- return;
293
- } catch {
294
- }
295
- }
296
- this._killChildDirect(p, signal);
297
- }
298
- /** Unregister a process by PID. Called on 'close' / 'exit' events. */
299
- unregister(pid) {
300
- this.processes.delete(pid);
301
- }
302
- /** Get a single process by PID. */
303
- get(pid) {
304
- this._pruneStale(pid);
305
- return this.processes.get(pid);
306
- }
307
- /** Get all tracked processes. */
308
- list() {
309
- this._pruneAllStale();
310
- return Array.from(this.processes.values());
311
- }
312
- /** Get processes filtered by name (e.g. 'bash', 'exec'). */
313
- byName(name) {
314
- return this.list().filter((p) => p.name === name);
315
- }
316
- /** Get processes filtered by session. */
317
- bySession(sessionId) {
318
- return this.list().filter((p) => p.sessionId === sessionId);
319
- }
320
- /** Count of active (non-killed) processes. */
321
- get activeCount() {
322
- let n = 0;
323
- for (const p of this.processes.values()) {
324
- if (!p.killed) n++;
325
- }
326
- return n;
327
- }
328
- /** Count of active jobs explicitly launched in background mode. */
329
- get activeBackgroundCount() {
330
- let n = 0;
331
- for (const p of this.processes.values()) {
332
- if (p.background && !p.killed) n++;
333
- }
334
- return n;
335
- }
336
- /**
337
- * Combined stats for observability — used by /ps and the TUI status bar.
338
- */
339
- stats() {
340
- this._pruneAllStale();
341
- return {
342
- activeCount: this.activeCount,
343
- backgroundCount: this.activeBackgroundCount,
344
- totalCount: this.processes.size,
345
- breaker: this.breaker.snapshot()
346
- };
347
- }
348
- /**
349
- * Returns true if the circuit allows a new bash/exec call to proceed.
350
- * When false, callers MUST NOT spawn a process.
351
- */
352
- get canProceed() {
353
- return this.breaker.canProceed;
354
- }
355
- /**
356
- * Called before spawning a process. Returns true if allowed; false if
357
- * the circuit breaker is open.
358
- *
359
- * @param bypass - If true, skip circuit breaker check (for background processes).
360
- */
361
- beforeCall(bypass = false) {
362
- return this.breaker.beforeCall(bypass);
363
- }
364
- /**
365
- * Called after a process finishes. `durationMs` is wall-clock time;
366
- * `failed` is true for non-zero exit codes.
367
- *
368
- * @param bypass - If true, do not update circuit breaker state (for background processes).
369
- */
370
- afterCall(durationMs, failed, bypass = false) {
371
- this.breaker.afterCall(durationMs, failed, bypass);
372
- }
373
- /** Force-open the circuit breaker (Ctrl+C, /kill force). */
374
- forceBreakerOpen() {
375
- this.breaker.forceOpen();
376
- }
377
- /** Force-reset the circuit breaker to closed (/kill reset). */
378
- forceBreakerReset() {
379
- this.breaker.forceReset();
380
- }
381
- /**
382
- * Configure circuit-breaker protection at runtime. Called from `/settings`
383
- * (instant, all modes) and on TUI mount (applies persisted config).
384
- *
385
- * - `enabled` toggles whether the breaker gates `bash`/`exec`.
386
- * - `autoKillResetMs` arms the auto kill/reset countdown when the breaker
387
- * trips (0 = manual recovery only).
388
- *
389
- * Re-applies cleanly on every call: cancels a pending countdown when the
390
- * timeout is cleared or protection disabled, and re-arms if the breaker is
391
- * currently open under the new settings.
392
- */
393
- setBreakerConfig(cfg) {
394
- if (cfg.enabled !== void 0) this.breaker.setEnabled(cfg.enabled);
395
- if (cfg.autoKillResetMs !== void 0) this.autoKillResetMs = Math.max(0, cfg.autoKillResetMs);
396
- if (this.autoKillResetMs <= 0) {
397
- this._cancelAutoKillReset();
398
- return;
399
- }
400
- if (this.breaker.isEnabled && this.breaker.snapshot().state === "open") {
401
- this._armAutoKillReset();
402
- }
403
- }
404
- /**
405
- * Live countdown to the next auto kill/reset, or null when nothing is armed.
406
- * The TUI polls this on a 1s tick while armed so the statusline decrements.
407
- */
408
- getBreakerCountdown() {
409
- if (this.autoKillArmedAt === null || this.autoKillResetMs <= 0) return null;
410
- const elapsed = Date.now() - this.autoKillArmedAt;
411
- return {
412
- remainingMs: Math.max(0, this.autoKillResetMs - elapsed),
413
- totalMs: this.autoKillResetMs
414
- };
415
- }
416
- /**
417
- * Subscribe to countdown arm/cancel events. Returns an unsubscribe function.
418
- * Use {@link getBreakerCountdown} for the live ticking value between events.
419
- */
420
- onBreakerCountdownChange(listener) {
421
- this.breakerCountdownListeners.push(listener);
422
- return () => {
423
- this.breakerCountdownListeners = this.breakerCountdownListeners.filter((l) => l !== listener);
424
- };
425
- }
426
- _emitBreakerCountdown() {
427
- const snap = this.getBreakerCountdown();
428
- for (const l of this.breakerCountdownListeners) {
429
- try {
430
- l(snap);
431
- } catch {
432
- }
433
- }
434
- }
435
- /**
436
- * Arm the auto kill/reset countdown. Idempotent: re-arming resets the window
437
- * (a fresh trip after a failed half-open probe restarts the clock). No-op
438
- * when protection is off or no timeout is configured.
439
- */
440
- _armAutoKillReset() {
441
- if (this.autoKillResetMs <= 0 || !this.breaker.isEnabled) return;
442
- this._clearAutoKillTimer();
443
- this.autoKillArmedAt = Date.now();
444
- this.autoKillTimer = setTimeout(() => {
445
- this.autoKillTimer = null;
446
- this.autoKillArmedAt = null;
447
- this.killAll({ force: false, preserveBackground: true });
448
- this.breaker.forceReset();
449
- this._emitBreakerCountdown();
450
- }, this.autoKillResetMs);
451
- this.autoKillTimer.unref?.();
452
- this._emitBreakerCountdown();
453
- }
454
- _cancelAutoKillReset() {
455
- const wasArmed = this.autoKillArmedAt !== null;
456
- this._clearAutoKillTimer();
457
- if (wasArmed) {
458
- this.autoKillArmedAt = null;
459
- this._emitBreakerCountdown();
460
- }
461
- }
462
- _clearAutoKillTimer() {
463
- if (this.autoKillTimer !== null) {
464
- clearTimeout(this.autoKillTimer);
465
- this.autoKillTimer = null;
466
- }
467
- }
468
- /** Kill a single process by PID.
469
- *
470
- * On POSIX: sends SIGTERM to the *process group* (-pid) so that
471
- * runaway grandchild processes (`sleep 9999 & disown`) are also killed.
472
- * After `graceMs` a SIGKILL is sent if the process hasn't exited.
473
- *
474
- * On Windows: `child.kill()` maps to TerminateProcess — process groups
475
- * are not meaningfully supported. A second `force=true` call sends
476
- * SIGKILL (which maps to TerminateProcess again — the distinction is
477
- * in the exit code, not the signal).
478
- *
479
- * Returns true if the process was found and kill was attempted.
480
- */
481
- kill(pid, opts = {}) {
482
- this._pruneStale(pid);
483
- const p = this.processes.get(pid);
484
- if (!p) return false;
485
- if (p.killed && opts.force !== true) return true;
486
- if (p.protected && opts.includeProtected !== true) return false;
487
- if (opts.preserveBackground && p.background) return false;
488
- const { force = false, graceMs = DEFAULT_GRACE_MS } = opts;
489
- const isWin = os.platform() === "win32";
490
- if (isWin) {
491
- const liveRealChild = p.child === null || p.child.exitCode === null && typeof p.child.pid === "number";
492
- const directFallback = () => {
493
- if (p.child && p.child.exitCode === null) {
494
- try {
495
- p.child.kill("SIGKILL");
496
- } catch {
497
- }
498
- }
499
- };
500
- if (liveRealChild && killWin32Tree(pid, {
501
- timeoutMs: Math.max(graceMs, WIN32_TASKKILL_TIMEOUT_MS),
502
- onSettled: directFallback
503
- })) {
504
- } else {
505
- this._killChildDirect(p, force ? "SIGKILL" : "SIGTERM");
506
- }
507
- p.killed = true;
508
- return true;
509
- }
510
- try {
511
- if (force) {
512
- this._killPosix(p, "SIGKILL");
513
- } else {
514
- this._killPosix(p, "SIGTERM");
515
- const timer = setTimeout(() => {
516
- if (this.processes.has(pid) && !p.child?.killed) {
517
- this._killPosix(p, "SIGKILL");
518
- }
519
- }, graceMs);
520
- timer.unref?.();
521
- }
522
- } catch {
523
- }
524
- p.killed = true;
525
- return true;
526
- }
527
- /**
528
- * Kill all tracked processes.
529
- * Returns the PIDs that were kill()ed.
530
- */
531
- killAll(opts = {}) {
532
- const pids = Array.from(this.processes.keys());
533
- const killed = [];
534
- const includeProtected = opts.includeProtected === true;
535
- for (const pid of pids) {
536
- const p = this.processes.get(pid);
537
- if (!p) continue;
538
- if (p.protected && !includeProtected) continue;
539
- if (opts.preserveBackground && p.background) continue;
540
- if (this.kill(pid, opts)) killed.push(pid);
541
- }
542
- return killed;
543
- }
544
- /**
545
- * Kill all processes for a specific session.
546
- * Returns the PIDs that were kill()ed.
547
- */
548
- killSession(sessionId, opts = {}) {
549
- const pids = this.bySession(sessionId).map((p) => p.pid);
550
- const killed = [];
551
- for (const pid of pids) {
552
- if (this.kill(pid, opts)) killed.push(pid);
553
- }
554
- return killed;
555
- }
556
- /**
557
- * Check whether a tracked process entry is stale — the child has exited
558
- * (exitCode !== null) AND it's been in the registry long enough that the
559
- * OS may have reused the PID for a new, unrelated process.
560
- *
561
- * P3 #24 (before-release.md): on POSIX, PIDs are reused after process
562
- * exit. If a tracked process exits but its 'close' event hasn't fired yet
563
- * (or was missed), the registry still holds the entry. A new process
564
- * gets the same PID, and PID-based lookups (get, kill, shouldBlockKill)
565
- * may incorrectly protect or target the wrong process.
566
- *
567
- * The 60s threshold is conservative — the OS typically waits much longer
568
- * before reusing a PID, but we want to clean up before that becomes a risk.
569
- */
570
- _isStaleEntry(entry) {
571
- if (entry.child === null) {
572
- if (Date.now() - entry.startedAt <= 6e4) return false;
573
- if (os.platform() === "win32") return false;
574
- try {
575
- process.kill(entry.pid, 0);
576
- return false;
577
- } catch (err) {
578
- return err.code !== "EPERM";
579
- }
580
- }
581
- return entry.child.exitCode !== null && Date.now() - entry.startedAt > 6e4;
582
- }
583
- /**
584
- * Remove a stale entry for a specific PID before any PID-based lookup.
585
- * This prevents PID reuse from causing the registry to act on a dead
586
- * process that has been replaced by a new one with the same PID.
587
- */
588
- _pruneStale(pid) {
589
- const entry = this.processes.get(pid);
590
- if (entry && this._isStaleEntry(entry)) {
591
- this.processes.delete(pid);
592
- }
593
- }
594
- /**
595
- * Remove every stale entry, not just one PID. `list()`/`stats()` — the
596
- * surfaces the TUI status bar and `/ps` poll — must prune too: a child
597
- * whose 'close' event never fires (e.g. Windows grandchildren holding stdio
598
- * open) would otherwise linger in the registry until someone looks up its
599
- * exact PID, and PID reuse meanwhile makes `get()`/`kill()` target the
600
- * wrong process. RAM-leak audit 2026-07-31, MEDIUM.
601
- */
602
- _pruneAllStale() {
603
- for (const [pid, entry] of this.processes) {
604
- if (this._isStaleEntry(entry)) this.processes.delete(pid);
605
- }
606
- }
607
- };
608
- var _registry;
609
- function getProcessRegistry() {
610
- if (!_registry) {
611
- _registry = new ProcessRegistryImpl();
612
- }
613
- return _registry;
614
- }
615
-
616
- // src/process-registry-persistent.ts
617
- var REGISTRY_FILE = "process-registry.json";
618
- function toErrorMessage(err) {
619
- return err instanceof Error ? err.message : String(err);
620
- }
621
- function emitStructuredLog(level, event, message, error) {
622
- const payload = {
623
- level,
624
- event,
625
- message,
626
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
627
- };
628
- if (error !== void 0) {
629
- payload.error = toErrorMessage(error);
630
- }
631
- console.log(JSON.stringify(payload));
632
- }
633
- var HEARTBEAT_INTERVAL_MS = 5e3;
634
- var STALE_THRESHOLD_MS = 3e4;
635
- var LOCK_STALE_MS = 3e4;
636
- var LOCKFILE = ".process-registry.lock";
637
- function generateInstanceId() {
638
- const hostname3 = os2.hostname();
639
- const pid = process.pid;
640
- const random = Math.random().toString(36).slice(2, 8);
641
- return `${hostname3}:${pid}:${random}`;
642
- }
643
- function isNodeError(err) {
644
- return typeof err === "object" && err !== null && "code" in err;
645
- }
646
- async function acquireLock(lockfilePath, timeoutMs = 5e3) {
647
- const start = Date.now();
648
- const pidStr = String(process.pid);
649
- const hostStr = os2.hostname();
650
- try {
651
- await fs.mkdir(path.dirname(lockfilePath), { recursive: true });
652
- } catch {
653
- }
654
- while (Date.now() - start < timeoutMs) {
655
- try {
656
- await fs.writeFile(lockfilePath, `${pidStr}:${hostStr}:${Date.now()}`, { flag: "wx" });
657
- return async () => {
658
- try {
659
- await fs.unlink(lockfilePath);
660
- } catch {
661
- }
662
- };
663
- } catch (err) {
664
- if (isNodeError(err) && err.code === "EEXIST") {
665
- try {
666
- const content = await fs.readFile(lockfilePath, "utf-8");
667
- const parts = content.split(":");
668
- const lockPid = parseInt(parts[0] ?? "0", 10);
669
- const lockTs = Number(parts[parts.length - 1]);
670
- const staleByAge = Number.isFinite(lockTs) && Date.now() - lockTs > LOCK_STALE_MS;
671
- let holderDead = false;
672
- if (process.platform !== "win32" && Number.isFinite(lockPid) && lockPid > 0) {
673
- try {
674
- process.kill(lockPid, 0);
675
- } catch {
676
- holderDead = true;
677
- }
678
- }
679
- if (holderDead || staleByAge) {
680
- await fs.unlink(lockfilePath).catch(() => {
681
- });
682
- continue;
683
- }
684
- } catch {
685
- await fs.unlink(lockfilePath).catch(() => {
686
- });
687
- continue;
688
- }
689
- await new Promise((r) => setTimeout(r, 100));
690
- continue;
691
- }
692
- throw err;
693
- }
694
- }
695
- throw new Error(`Failed to acquire lock after ${timeoutMs}ms`);
696
- }
697
- function freshRegistryData() {
698
- return {
699
- version: 1,
700
- instances: /* @__PURE__ */ new Map(),
701
- protectedPatterns: ["wrongstack", "node"],
702
- lastCleanup: Date.now()
703
- };
704
- }
705
- async function readRegistryFile(filePath) {
706
- let content;
707
- try {
708
- content = await fs.readFile(filePath, "utf-8");
709
- } catch (err) {
710
- if (isNodeError(err) && err.code === "ENOENT") return freshRegistryData();
711
- throw err;
712
- }
713
- try {
714
- const parsed = JSON.parse(content);
715
- if (!parsed || typeof parsed !== "object") return freshRegistryData();
716
- const base = freshRegistryData();
717
- return {
718
- version: 1,
719
- instances: Array.isArray(parsed.instances) ? new Map(parsed.instances) : base.instances,
720
- protectedPatterns: Array.isArray(parsed.protectedPatterns) ? parsed.protectedPatterns : base.protectedPatterns,
721
- lastCleanup: typeof parsed.lastCleanup === "number" ? parsed.lastCleanup : base.lastCleanup
722
- };
723
- } catch {
724
- return freshRegistryData();
725
- }
726
- }
727
- async function writeRegistryFile(filePath, data) {
728
- const tmpPath = `${filePath}.tmp.${process.pid}`;
729
- const content = JSON.stringify(
730
- data,
731
- (_k, v) => {
732
- if (v instanceof Map) {
733
- return Array.from(v.entries());
734
- }
735
- return v;
736
- },
737
- 2
738
- );
739
- await fs.writeFile(tmpPath, content, "utf-8");
740
- await fs.rename(tmpPath, filePath);
741
- }
742
- var PersistentProcessRegistry = class {
743
- instanceId;
744
- registryPath;
745
- lockPath;
746
- baseRegistry;
747
- heartbeatInterval = null;
748
- cleanupInterval = null;
749
- heartbeatRunning = false;
750
- cleanupRunning = false;
751
- isShuttingDown = false;
752
- onProcessExit = () => {
753
- this.runInBackground(
754
- this.syncToPersistent(),
755
- "process_registry.exit_sync_failed",
756
- "PersistentProcessRegistry: exit sync failed"
757
- );
758
- };
759
- constructor(baseRegistry) {
760
- this.instanceId = generateInstanceId();
761
- const globalRoot = wstackGlobalRoot();
762
- this.registryPath = path.join(globalRoot, REGISTRY_FILE);
763
- this.lockPath = path.join(globalRoot, LOCKFILE);
764
- this.baseRegistry = baseRegistry ?? getProcessRegistry();
765
- this.ensureDirectory().catch((err) => {
766
- emitStructuredLog(
767
- "warn",
768
- "process_registry.dir_create_failed",
769
- "PersistentProcessRegistry: failed to create .wrongstack directory",
770
- err
771
- );
772
- });
773
- }
774
- async ensureDirectory() {
775
- const dir = path.dirname(this.registryPath);
776
- try {
777
- await fs.mkdir(dir, { recursive: true });
778
- } catch (err) {
779
- if (!isNodeError(err) || err.code !== "EEXIST") throw err;
780
- }
781
- }
782
- runInBackground(operation, event, message) {
783
- void operation.catch((err) => {
784
- emitStructuredLog("warn", event, message, err);
785
- });
786
- }
787
- /**
788
- * Start the heartbeat and periodic cleanup tasks.
789
- */
790
- start() {
791
- if (this.heartbeatInterval) return;
792
- this.isShuttingDown = false;
793
- this.heartbeat();
794
- this.heartbeatInterval = setInterval(() => {
795
- this.heartbeat();
796
- }, HEARTBEAT_INTERVAL_MS);
797
- this.heartbeatInterval.unref?.();
798
- this.cleanupInterval = setInterval(() => {
799
- this.cleanup();
800
- }, STALE_THRESHOLD_MS);
801
- this.cleanupInterval.unref?.();
802
- this.registerMainProcess();
803
- process.on("exit", this.onProcessExit);
804
- }
805
- /**
806
- * Stop the heartbeat and clean up.
807
- */
808
- stop() {
809
- this.isShuttingDown = true;
810
- if (this.heartbeatInterval) {
811
- clearInterval(this.heartbeatInterval);
812
- this.heartbeatInterval = null;
813
- }
814
- if (this.cleanupInterval) {
815
- clearInterval(this.cleanupInterval);
816
- this.cleanupInterval = null;
817
- }
818
- process.off("exit", this.onProcessExit);
819
- this.runInBackground(
820
- this.syncToPersistent(),
821
- "process_registry.stop_sync_failed",
822
- "PersistentProcessRegistry: stop sync failed"
823
- );
824
- }
825
- /**
826
- * Register the main WrongStack process as protected.
827
- */
828
- registerMainProcess() {
829
- const mainPid = process.pid;
830
- this.runInBackground(
831
- this.updatePersistentEntry({
832
- pid: mainPid,
833
- name: "wrongstack-main",
834
- command: process.argv.slice(0, 3).join(" "),
835
- startedAt: Date.now(),
836
- lastHeartbeat: Date.now(),
837
- instanceId: this.instanceId,
838
- hostname: os2.hostname(),
839
- protected: true,
840
- spawnMode: "main",
841
- parentPid: process.ppid,
842
- platform: process.platform
843
- }),
844
- "process_registry.main_register_failed",
845
- "PersistentProcessRegistry: failed to register main process"
846
- );
847
- }
848
- /**
849
- * Register a spawned child process with the persistent registry.
850
- */
851
- registerChildProcess(pid, name, command, sessionId, spawnMode = "spawn") {
852
- const entry = {
853
- pid,
854
- name,
855
- command,
856
- startedAt: Date.now(),
857
- lastHeartbeat: Date.now(),
858
- instanceId: this.instanceId,
859
- hostname: os2.hostname(),
860
- protected: true,
861
- // All WrongStack child processes are protected by default
862
- spawnMode,
863
- parentPid: process.pid,
864
- platform: process.platform
865
- };
866
- if (sessionId) {
867
- entry.sessionId = sessionId;
868
- }
869
- this.runInBackground(
870
- this.updatePersistentEntry(entry),
871
- "process_registry.child_register_failed",
872
- "PersistentProcessRegistry: failed to register child process"
873
- );
874
- }
875
- /**
876
- * Update or add an entry in the persistent registry.
877
- */
878
- async updatePersistentEntry(entry) {
879
- const release = await acquireLock(this.lockPath);
880
- try {
881
- const data = await readRegistryFile(this.registryPath);
882
- data.instances.set(String(entry.pid), entry);
883
- this.baseRegistry.register({
884
- pid: entry.pid,
885
- name: entry.name,
886
- command: entry.command,
887
- startedAt: entry.startedAt,
888
- sessionId: entry.sessionId,
889
- protected: entry.protected,
890
- child: null
891
- });
892
- await writeRegistryFile(this.registryPath, data);
893
- } finally {
894
- await release();
895
- }
896
- }
897
- /**
898
- * Unregister a process from the persistent registry.
899
- */
900
- async unregister(pid) {
901
- const release = await acquireLock(this.lockPath);
902
- try {
903
- const data = await readRegistryFile(this.registryPath);
904
- data.instances.delete(String(pid));
905
- await writeRegistryFile(this.registryPath, data);
906
- } finally {
907
- await release();
908
- }
909
- }
910
- /**
911
- * Send heartbeat to mark all this instance's processes as alive.
912
- */
913
- heartbeat() {
914
- if (this.isShuttingDown || this.heartbeatRunning) return;
915
- this.heartbeatRunning = true;
916
- void this.syncToPersistent().catch((err) => {
917
- emitStructuredLog(
918
- "warn",
919
- "process_registry.heartbeat_failed",
920
- "PersistentProcessRegistry: heartbeat failed",
921
- err
922
- );
923
- }).finally(() => {
924
- this.heartbeatRunning = false;
925
- });
926
- }
927
- cleanup() {
928
- if (this.isShuttingDown || this.cleanupRunning) return;
929
- this.cleanupRunning = true;
930
- void this.cleanupStaleEntries().catch((err) => {
931
- emitStructuredLog(
932
- "warn",
933
- "process_registry.periodic_cleanup_failed",
934
- "PersistentProcessRegistry: periodic cleanup failed",
935
- err
936
- );
937
- }).finally(() => {
938
- this.cleanupRunning = false;
939
- });
940
- }
941
- /**
942
- * Sync this instance's processes to the persistent registry.
943
- */
944
- async syncToPersistent() {
945
- const release = await acquireLock(this.lockPath);
946
- try {
947
- const data = await readRegistryFile(this.registryPath);
948
- const now2 = Date.now();
949
- const updatedInstances = /* @__PURE__ */ new Map();
950
- for (const [_pidStr, entry] of data.instances) {
951
- if (entry.instanceId === this.instanceId) {
952
- entry.lastHeartbeat = now2;
953
- }
954
- if (entry.instanceId === this.instanceId || now2 - entry.lastHeartbeat < STALE_THRESHOLD_MS) {
955
- updatedInstances.set(_pidStr, entry);
956
- }
957
- }
958
- data.instances = updatedInstances;
959
- data.lastCleanup = now2;
960
- await writeRegistryFile(this.registryPath, data);
961
- } catch (err) {
962
- emitStructuredLog(
963
- "warn",
964
- "process_registry.sync_failed",
965
- "PersistentProcessRegistry: sync failed",
966
- err
967
- );
968
- } finally {
969
- await release();
970
- }
971
- }
972
- /**
973
- * Remove entries for processes that are no longer running.
974
- */
975
- async cleanupStaleEntries() {
976
- const release = await acquireLock(this.lockPath);
977
- try {
978
- const data = await readRegistryFile(this.registryPath);
979
- const now2 = Date.now();
980
- const stalePids = [];
981
- for (const [_pidStr, entry] of data.instances) {
982
- const age = now2 - entry.lastHeartbeat;
983
- if (age > STALE_THRESHOLD_MS) {
984
- try {
985
- if (process.platform !== "win32") {
986
- process.kill(entry.pid, 0);
987
- } else {
988
- emitStructuredLog(
989
- "debug",
990
- "process_registry.stale_pid_check",
991
- `PersistentProcessRegistry: checking stale pid ${entry.pid} (${age}ms old)`
992
- );
993
- }
994
- } catch {
995
- stalePids.push(_pidStr);
996
- }
997
- }
998
- }
999
- if (stalePids.length > 0) {
1000
- for (const pidStr of stalePids) {
1001
- data.instances.delete(pidStr);
1002
- }
1003
- await writeRegistryFile(this.registryPath, data);
1004
- }
1005
- } catch (err) {
1006
- emitStructuredLog(
1007
- "warn",
1008
- "process_registry.cleanup_failed",
1009
- "PersistentProcessRegistry: cleanup failed",
1010
- err
1011
- );
1012
- } finally {
1013
- await release();
1014
- }
1015
- }
1016
- /**
1017
- * Check if a PID belongs to a WrongStack process and should be protected.
1018
- */
1019
- async isProtectedPid(pid) {
1020
- const release = await acquireLock(this.lockPath);
1021
- try {
1022
- const data = await readRegistryFile(this.registryPath);
1023
- const entry = data.instances.get(String(pid));
1024
- if (!entry) return false;
1025
- if (Date.now() - entry.lastHeartbeat > STALE_THRESHOLD_MS) {
1026
- return false;
1027
- }
1028
- return entry.protected;
1029
- } finally {
1030
- await release();
1031
- }
1032
- }
1033
- /**
1034
- * Get all protected PIDs from all WrongStack instances.
1035
- */
1036
- async getAllProtectedPids() {
1037
- const release = await acquireLock(this.lockPath);
1038
- try {
1039
- const data = await readRegistryFile(this.registryPath);
1040
- const now2 = Date.now();
1041
- const protectedPids = [];
1042
- for (const [_pidStr, entry] of data.instances) {
1043
- if (entry.protected && now2 - entry.lastHeartbeat < STALE_THRESHOLD_MS) {
1044
- protectedPids.push(entry.pid);
1045
- }
1046
- }
1047
- return protectedPids;
1048
- } finally {
1049
- await release();
1050
- }
1051
- }
1052
- /**
1053
- * Get complete status of all tracked processes across all instances.
1054
- */
1055
- async getGlobalStatus() {
1056
- const release = await acquireLock(this.lockPath);
1057
- try {
1058
- const data = await readRegistryFile(this.registryPath);
1059
- const now2 = Date.now();
1060
- const instances = /* @__PURE__ */ new Map();
1061
- let protectedCount = 0;
1062
- let staleCount = 0;
1063
- for (const [_pidStr, entry] of data.instances) {
1064
- const instanceEntries = instances.get(entry.instanceId) ?? [];
1065
- instanceEntries.push(entry);
1066
- instances.set(entry.instanceId, instanceEntries);
1067
- if (entry.protected) protectedCount++;
1068
- if (now2 - entry.lastHeartbeat > STALE_THRESHOLD_MS) staleCount++;
1069
- }
1070
- return {
1071
- instances,
1072
- totalProcesses: data.instances.size,
1073
- protectedCount,
1074
- staleCount
1075
- };
1076
- } finally {
1077
- await release();
1078
- }
1079
- }
1080
- /**
1081
- * Get the instance ID for this process.
1082
- */
1083
- getInstanceId() {
1084
- return this.instanceId;
1085
- }
1086
- /**
1087
- * Check if a kill command should be blocked.
1088
- * Returns true if the kill should be blocked (target is a WrongStack process).
1089
- */
1090
- async shouldBlockKill(pid) {
1091
- const protectedPids = await this.getAllProtectedPids();
1092
- return protectedPids.includes(pid);
1093
- }
1094
- /**
1095
- * Add a pattern-based protection rule.
1096
- * Processes whose command matches any protected pattern are protected.
1097
- */
1098
- async addProtectedPattern(pattern) {
1099
- const release = await acquireLock(this.lockPath);
1100
- try {
1101
- const data = await readRegistryFile(this.registryPath);
1102
- if (!data.protectedPatterns.includes(pattern)) {
1103
- data.protectedPatterns.push(pattern);
1104
- await writeRegistryFile(this.registryPath, data);
1105
- }
1106
- } finally {
1107
- await release();
1108
- }
1109
- }
1110
- };
1111
- var _persistentRegistry;
1112
- function getPersistentProcessRegistry() {
1113
- if (!_persistentRegistry) {
1114
- _persistentRegistry = new PersistentProcessRegistry();
1115
- }
1116
- return _persistentRegistry;
1117
- }
1118
-
1119
- // src/ps-slash.ts
1120
- var IDLE_THRESHOLD_MS = 2 * 6e4;
1121
- var STALE_THRESHOLD_MS2 = 5 * 6e4;
1122
- function now() {
1123
- return Date.now();
1124
- }
1125
- function formatAge(ms) {
1126
- if (ms < 1e3) return "0s";
1127
- const seconds = Math.floor(ms / 1e3);
1128
- if (seconds < 60) return `${seconds}s`;
1129
- const minutes = Math.floor(seconds / 60);
1130
- if (minutes < 60) return `${minutes}m`;
1131
- const hours = Math.floor(minutes / 60);
1132
- if (hours < 24) return `${hours}h`;
1133
- const days = Math.floor(hours / 24);
1134
- return `${days}d`;
1135
- }
1136
- function formatUptime(ms) {
1137
- return formatAge(ms);
1138
- }
1139
- function matchGlob(pattern, value) {
1140
- const regexPattern = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
1141
- try {
1142
- const regex = new RegExp(`^${regexPattern}$`, "i");
1143
- return regex.test(value);
1144
- } catch {
1145
- return false;
1146
- }
1147
- }
1148
- async function listInstances(options = {}) {
1149
- const { includeStale = false, hostname: hostname3, status } = options;
1150
- const timestamp = now();
1151
- const registry = getPersistentProcessRegistry();
1152
- const globalStatus = await registry.getGlobalStatus();
1153
- const instances = [];
1154
- const instanceMap = globalStatus.instances;
1155
- for (const [instanceId, processes] of instanceMap) {
1156
- if (processes.length === 0) continue;
1157
- const mainProc = processes.find((p) => p.spawnMode === "main");
1158
- const firstProc = processes.at(0);
1159
- const mainPid = mainProc?.pid ?? firstProc?.pid ?? 0;
1160
- const hostname_ = firstProc?.hostname ?? os3.hostname();
1161
- const startedAt = Math.min(...processes.map((p) => p.startedAt));
1162
- const lastActivity = Math.max(...processes.map((p) => p.lastHeartbeat));
1163
- const age = timestamp - lastActivity;
1164
- let instanceStatus = "stale";
1165
- if (age < IDLE_THRESHOLD_MS) instanceStatus = "active";
1166
- else if (age < STALE_THRESHOLD_MS2) instanceStatus = "idle";
1167
- const sessionIds = /* @__PURE__ */ new Set();
1168
- for (const proc of processes) {
1169
- if (proc.sessionId) {
1170
- sessionIds.add(proc.sessionId);
1171
- }
1172
- }
1173
- if (!includeStale && instanceStatus === "stale") continue;
1174
- if (hostname3 && !matchGlob(hostname3, hostname_)) continue;
1175
- if (status && status !== "all" && instanceStatus !== status) continue;
1176
- instances.push({
1177
- instanceId,
1178
- hostname: hostname_,
1179
- mainPid,
1180
- startedAt,
1181
- lastActivity,
1182
- status: instanceStatus,
1183
- processCount: processes.length,
1184
- processes,
1185
- sessionIds
1186
- });
1187
- }
1188
- instances.sort((a, b) => b.lastActivity - a.lastActivity);
1189
- return instances;
1190
- }
1191
- async function getInstanceCount() {
1192
- const instances = await listInstances({ includeStale: true });
1193
- const byHostname = /* @__PURE__ */ new Map();
1194
- let active = 0;
1195
- let idle = 0;
1196
- let stale = 0;
1197
- for (const inst of instances) {
1198
- const current = byHostname.get(inst.hostname) ?? 0;
1199
- byHostname.set(inst.hostname, current + 1);
1200
- switch (inst.status) {
1201
- case "active":
1202
- active++;
1203
- break;
1204
- case "idle":
1205
- idle++;
1206
- break;
1207
- case "stale":
1208
- stale++;
1209
- break;
1210
- }
1211
- }
1212
- return {
1213
- total: instances.length,
1214
- active,
1215
- idle,
1216
- stale,
1217
- byHostname
1218
- };
1219
- }
1220
- async function getGlobalProcessStatus() {
1221
- const timestamp = now();
1222
- const registry = getPersistentProcessRegistry();
1223
- const globalStatus = await registry.getGlobalStatus();
1224
- const instances = await listInstances({ includeStale: true });
1225
- const localInstanceId = registry.getInstanceId();
1226
- const localInstance = instances.find((i) => i.instanceId === localInstanceId);
1227
- let localProtectedCount = 0;
1228
- if (localInstance) {
1229
- localProtectedCount = localInstance.processes.filter((p) => p.protected).length;
1230
- }
1231
- let activeInstanceCount = 0;
1232
- for (const inst of instances) {
1233
- if (inst.status === "active") activeInstanceCount++;
1234
- }
1235
- return {
1236
- localInstance: localInstance ? {
1237
- instanceId: localInstance.instanceId,
1238
- mainPid: localInstance.mainPid,
1239
- protectedCount: localProtectedCount,
1240
- platform: process.platform,
1241
- hostname: localInstance.hostname,
1242
- uptime: timestamp - localInstance.startedAt
1243
- } : {
1244
- instanceId: localInstanceId,
1245
- mainPid: process.pid,
1246
- protectedCount: 0,
1247
- platform: process.platform,
1248
- hostname: os3.hostname(),
1249
- uptime: 0
1250
- },
1251
- allInstances: instances.map((inst) => ({
1252
- instanceId: inst.instanceId,
1253
- hostname: inst.hostname,
1254
- mainPid: inst.mainPid,
1255
- processes: inst.processes,
1256
- startedAt: inst.startedAt,
1257
- lastActivity: inst.lastActivity
1258
- })),
1259
- summary: {
1260
- totalProcesses: globalStatus.totalProcesses,
1261
- protectedCount: globalStatus.protectedCount,
1262
- staleCount: globalStatus.staleCount,
1263
- instanceCount: instances.length,
1264
- activeInstanceCount
1265
- },
1266
- timestamp
1267
- };
1268
- }
1269
- async function formatGlobalStatus() {
1270
- const status = await getGlobalProcessStatus();
1271
- const lines = [];
1272
- lines.push("=== WrongStack Global Process Status ===");
1273
- lines.push(`Updated: ${new Date(status.timestamp).toISOString()}`);
1274
- lines.push("");
1275
- lines.push("Summary:");
1276
- lines.push(` Total processes: ${status.summary.totalProcesses}`);
1277
- lines.push(` Protected: ${status.summary.protectedCount}`);
1278
- lines.push(` Stale entries: ${status.summary.staleCount}`);
1279
- lines.push(
1280
- ` Instances: ${status.summary.instanceCount} (${status.summary.activeInstanceCount} active)`
1281
- );
1282
- lines.push("");
1283
- lines.push(`This instance (${status.localInstance.instanceId}):`);
1284
- lines.push(` Main PID: ${status.localInstance.mainPid}`);
1285
- lines.push(` Protected processes: ${status.localInstance.protectedCount}`);
1286
- lines.push(` Platform: ${status.localInstance.platform} (${status.localInstance.hostname})`);
1287
- lines.push(` Uptime: ${formatUptime(status.localInstance.uptime)}`);
1288
- lines.push("");
1289
- for (const instance of status.allInstances) {
1290
- if (instance.instanceId === status.localInstance.instanceId) continue;
1291
- const age = Math.round((status.timestamp - instance.lastActivity) / 1e3);
1292
- lines.push(`Instance ${instance.instanceId} (${instance.hostname}):`);
1293
- for (const proc of instance.processes) {
1294
- const procAge = formatAge(status.timestamp - proc.startedAt);
1295
- const heartbeatAge = formatAge(status.timestamp - proc.lastHeartbeat);
1296
- const protected_ = proc.protected ? "[P]" : " ";
1297
- lines.push(
1298
- ` ${protected_} ${String(proc.pid).padStart(6)} ${proc.name.padEnd(20)} started ${procAge.padStart(8)} heartbeat ${heartbeatAge.padStart(6)} ${proc.spawnMode}`
1299
- );
1300
- }
1301
- lines.push(` Last activity: ${age}s ago`);
1302
- lines.push("");
1303
- }
1304
- lines.push("Legend:");
1305
- lines.push(" [P] = Protected (cannot be killed via bash)");
1306
- lines.push(" main = Main WrongStack process");
1307
- lines.push(" spawn = Spawned child process");
1308
- lines.push(" fork = Forked process (e.g., worker threads)");
1309
- return lines.join("\n");
1310
- }
1311
- async function formatInstanceList(options = {}) {
1312
- const instances = await listInstances(options);
1313
- const count = await getInstanceCount();
1314
- const lines = [];
1315
- lines.push("=== WrongStack Instances ===");
1316
- lines.push(
1317
- `Total: ${count.total} instances (${count.active} active, ${count.idle} idle, ${count.stale} stale)`
1318
- );
1319
- lines.push("");
1320
- if (count.byHostname.size > 1) {
1321
- lines.push("By hostname:");
1322
- for (const [host, num] of count.byHostname) {
1323
- lines.push(` ${host}: ${num} instance${num !== 1 ? "s" : ""}`);
1324
- }
1325
- lines.push("");
1326
- }
1327
- if (instances.length === 0) {
1328
- lines.push("No instances found matching the filter.");
1329
- return lines.join("\n");
1330
- }
1331
- lines.push("INSTANCES:");
1332
- lines.push(
1333
- " " + [
1334
- "STATUS".padEnd(7),
1335
- "HOSTNAME".padEnd(16),
1336
- "MAIN PID".padEnd(9),
1337
- "PROCS".padEnd(6),
1338
- "SESSIONS".padEnd(8),
1339
- "UPTIME".padEnd(8),
1340
- "LAST ACTIVITY"
1341
- ].join(" ")
1342
- );
1343
- lines.push(" " + "-".repeat(80));
1344
- for (const inst of instances) {
1345
- const uptime = formatAge(Date.now() - inst.startedAt);
1346
- const lastAct = formatAge(Date.now() - inst.lastActivity);
1347
- const statusIcon = inst.status === "active" ? "[*]" : inst.status === "idle" ? "[-]" : "[ ]";
1348
- lines.push(
1349
- " " + [
1350
- `${statusIcon} ${inst.status}`.padEnd(7),
1351
- inst.hostname.padEnd(16),
1352
- String(inst.mainPid).padEnd(9),
1353
- String(inst.processCount).padEnd(6),
1354
- String(inst.sessionIds.size).padEnd(8),
1355
- uptime.padEnd(8),
1356
- `${lastAct} ago`
1357
- ].join(" ")
1358
- );
1359
- }
1360
- lines.push("");
1361
- lines.push("Use /ps full for detailed process listing per instance.");
1362
- return lines.join("\n");
1363
- }
1364
- async function formatInstanceSummary() {
1365
- const count = await getInstanceCount();
1366
- const instances = await listInstances({ includeStale: false });
1367
- if (instances.length === 0) {
1368
- return "No active WrongStack instances.";
1369
- }
1370
- const lines = [];
1371
- lines.push(`${count.total} instance${count.total !== 1 ? "s" : ""}`);
1372
- const byStatus = /* @__PURE__ */ new Map();
1373
- for (const inst of instances) {
1374
- byStatus.set(inst.status, (byStatus.get(inst.status) ?? 0) + 1);
1375
- }
1376
- const parts = [];
1377
- if (byStatus.get("active")) parts.push(`${byStatus.get("active")} active`);
1378
- if (byStatus.get("idle")) parts.push(`${byStatus.get("idle")} idle`);
1379
- if (byStatus.get("stale")) parts.push(`${byStatus.get("stale")} stale`);
1380
- lines.push(`(${parts.join(", ")})`);
1381
- const totalProcs = instances.reduce((sum, inst) => sum + inst.processCount, 0);
1382
- lines.push(`${totalProcs} total processes`);
1383
- return lines.join(" ");
1384
- }
1385
- function createGlobalPsSlashCommand() {
1386
- return {
1387
- name: "ps",
1388
- description: "List all WrongStack instances and their processes",
1389
- async handler(input) {
1390
- try {
1391
- const trimmed = input.trim();
1392
- const parts = trimmed.split(/\s+/);
1393
- const sub = parts[0]?.toLowerCase() ?? "";
1394
- if (sub === "list" || sub === "ls" || sub === "") {
1395
- const output = await formatInstanceList();
1396
- return { message: output };
1397
- }
1398
- if (sub === "summary" || sub === "sum") {
1399
- const output = await formatInstanceSummary();
1400
- return { message: output };
1401
- }
1402
- if (sub === "full" || sub === "detail") {
1403
- const output = await formatGlobalStatus();
1404
- return { message: output };
1405
- }
1406
- if (sub === "count" || sub === "num") {
1407
- const count = await getInstanceCount();
1408
- return {
1409
- message: `${count.total} instance${count.total !== 1 ? "s" : ""} (${count.active} active, ${count.idle} idle, ${count.stale} stale)`
1410
- };
1411
- }
1412
- if (sub === "hostname" || sub === "host") {
1413
- const pattern = parts.slice(1).join(" ");
1414
- if (!pattern) {
1415
- return { message: "Usage: /ps hostname <pattern> (e.g., /ps hostname workstation*)" };
1416
- }
1417
- const output = await formatInstanceList({ hostname: pattern });
1418
- return { message: output };
1419
- }
1420
- if (sub === "status" || sub === "state") {
1421
- const filterStatus = parts[1]?.toLowerCase();
1422
- if (!["active", "idle", "stale", "all"].includes(filterStatus ?? "")) {
1423
- return { message: "Usage: /ps status <active|idle|stale|all>" };
1424
- }
1425
- const output = await formatInstanceList({
1426
- status: filterStatus
1427
- });
1428
- return { message: output };
1429
- }
1430
- return {
1431
- message: "Usage: /ps [list|summary|count|full|hostname <pattern>|status <state>]"
1432
- };
1433
- } catch (err) {
1434
- const message = err instanceof Error ? err.message : String(err);
1435
- return { message: `Error getting process status: ${message}` };
1436
- }
1437
- }
1438
- };
1439
- }
1
+ import {
2
+ createGlobalPsSlashCommand,
3
+ formatGlobalStatus,
4
+ formatInstanceList,
5
+ formatInstanceSummary,
6
+ getGlobalProcessStatus,
7
+ getInstanceCount,
8
+ listInstances
9
+ } from "./chunk-42BHI7TN.js";
10
+ import "./chunk-NKNOBUBU.js";
11
+ import "./chunk-3PVYQFRQ.js";
12
+ import "./chunk-HFXSNKCV.js";
1440
13
  export {
1441
14
  createGlobalPsSlashCommand,
1442
15
  formatGlobalStatus,