github-router 0.3.373 → 0.3.374
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.
- package/dist/ado-tools-BOW1k1KW.js +1 -0
- package/dist/{aic-ledger-Cp7Yk9-Q.js → aic-ledger-CeSXqTEE.js} +5 -7
- package/dist/{aic-ledger-Cp7Yk9-Q.js.map → aic-ledger-CeSXqTEE.js.map} +1 -1
- package/dist/{aic-statusline-settings-B5EMMSFC.js → aic-statusline-settings-BKveu679.js} +3 -4
- package/dist/{aic-statusline-settings-B5EMMSFC.js.map → aic-statusline-settings-BKveu679.js.map} +1 -1
- package/dist/{attribution-settings-DZ8fEfvP.js → attribution-settings-BLTnz2_A.js} +33 -53
- package/dist/{attribution-settings-DZ8fEfvP.js.map → attribution-settings-BLTnz2_A.js.map} +1 -1
- package/dist/{auth-B1egtvt4.js → auth-BZHpTtfF.js} +5 -6
- package/dist/{auth-B1egtvt4.js.map → auth-BZHpTtfF.js.map} +1 -1
- package/dist/{balanced-profile-contract-Dm_usmw7.js → balanced-profile-contract-B6pSoWjm.js} +2 -3
- package/dist/{balanced-profile-contract-Dm_usmw7.js.map → balanced-profile-contract-B6pSoWjm.js.map} +1 -1
- package/dist/{bluebird-client-ByCRusGQ.js → bluebird-client-BasIdv5J.js} +8 -12
- package/dist/{bluebird-client-ByCRusGQ.js.map → bluebird-client-BasIdv5J.js.map} +1 -1
- package/dist/{bluebird-client-CY6NBHQu.js → bluebird-client-BvoMTmEv.js} +1 -1
- package/dist/browser-bridge/index.js +84 -55
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-T_z84Pgc.js → check-usage-BlIWDuV2.js} +5 -6
- package/dist/{check-usage-T_z84Pgc.js.map → check-usage-BlIWDuV2.js.map} +1 -1
- package/dist/{claude-8ksmV0dC.js → claude-DSXrdz0v.js} +37 -43
- package/dist/{claude-8ksmV0dC.js.map → claude-DSXrdz0v.js.map} +1 -1
- package/dist/{claude-md-injection-BnzVv_aB.js → claude-md-injection-DU5KYXNc.js} +6 -7
- package/dist/{claude-md-injection-BnzVv_aB.js.map → claude-md-injection-DU5KYXNc.js.map} +1 -1
- package/dist/{client-CQMfroGV.js → client-Bjp3XAMK.js} +3 -5
- package/dist/{client-CQMfroGV.js.map → client-Bjp3XAMK.js.map} +1 -1
- package/dist/{codex-C89FoaaG.js → codex-DGMUk65v.js} +10 -11
- package/dist/{codex-C89FoaaG.js.map → codex-DGMUk65v.js.map} +1 -1
- package/dist/{copilot-discount-T-cfWmc4.js → copilot-discount-CHNQLYDJ.js} +3 -4
- package/dist/{copilot-discount-T-cfWmc4.js.map → copilot-discount-CHNQLYDJ.js.map} +1 -1
- package/dist/{debug-DL2JsRqY.js → debug-1HUHCWFl.js} +3 -4
- package/dist/{debug-DL2JsRqY.js.map → debug-1HUHCWFl.js.map} +1 -1
- package/dist/engine-BC4TF4pt.js +1 -0
- package/dist/{exec-Bf8g_bIR.js → exec-BC0MAnoA.js} +2 -3
- package/dist/{exec-Bf8g_bIR.js.map → exec-BC0MAnoA.js.map} +1 -1
- package/dist/{fast-profile-contract-JOnZBgFB.js → fast-profile-contract-BLnKg0Ay.js} +2 -3
- package/dist/{fast-profile-contract-JOnZBgFB.js.map → fast-profile-contract-BLnKg0Ay.js.map} +1 -1
- package/dist/{gate-discovery-Bc9FdRwg.js → gate-discovery-DiXu_olc.js} +8 -10
- package/dist/{gate-discovery-Bc9FdRwg.js.map → gate-discovery-DiXu_olc.js.map} +1 -1
- package/dist/{get-copilot-usage-BSXeQEx8.js → get-copilot-usage-CKg42gSH.js} +5 -6
- package/dist/{get-copilot-usage-BSXeQEx8.js.map → get-copilot-usage-CKg42gSH.js.map} +1 -1
- package/dist/{hook-mcp-client-DERIkeR7.js → hook-mcp-client-CYx10nlU.js} +2 -3
- package/dist/hook-mcp-client-CYx10nlU.js.map +1 -0
- package/dist/hooks.mjs +1766 -1548
- package/dist/hooks.sha256 +1 -1
- package/dist/{index-cmd-DOhwt92u.js → index-cmd-BPXhTfGQ.js} +8 -9
- package/dist/index-cmd-BPXhTfGQ.js.map +1 -0
- package/dist/{internal-aic-status-CY0QxSa7.js → internal-aic-status-FQB1DQzX.js} +6 -8
- package/dist/{internal-aic-status-CY0QxSa7.js.map → internal-aic-status-FQB1DQzX.js.map} +1 -1
- package/dist/{internal-artifact-open-NAGn9Mgt.js → internal-artifact-open-DbHjipxU.js} +5 -7
- package/dist/{internal-artifact-open-NAGn9Mgt.js.map → internal-artifact-open-DbHjipxU.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-De_DJOyZ.js → internal-fast-dispatch-guard-DMzqs-r8.js} +1 -1
- package/dist/{internal-fast-dispatch-guard-_n-A8hgo.js → internal-fast-dispatch-guard-PDdlkPU3.js} +6 -8
- package/dist/{internal-fast-dispatch-guard-_n-A8hgo.js.map → internal-fast-dispatch-guard-PDdlkPU3.js.map} +1 -1
- package/dist/{internal-first-mate-guard-GufCUMl3.js → internal-first-mate-guard-4Yro9xNM.js} +5 -7
- package/dist/{internal-first-mate-guard-GufCUMl3.js.map → internal-first-mate-guard-4Yro9xNM.js.map} +1 -1
- package/dist/{internal-first-mate-guard-C8GwLbaX.js → internal-first-mate-guard-BxPDUsV3.js} +1 -1
- package/dist/{internal-max-dispatch-guard-4rh6KSd8.js → internal-max-dispatch-guard-D3L00YXj.js} +5 -7
- package/dist/{internal-max-dispatch-guard-4rh6KSd8.js.map → internal-max-dispatch-guard-D3L00YXj.js.map} +1 -1
- package/dist/{internal-max-dispatch-guard-CKnzgJje.js → internal-max-dispatch-guard-fhBX_w49.js} +1 -1
- package/dist/{internal-plan-review-ChFx8wTX.js → internal-plan-review-BfHLeszV.js} +6 -7
- package/dist/{internal-plan-review-ChFx8wTX.js.map → internal-plan-review-BfHLeszV.js.map} +1 -1
- package/dist/{internal-prompt-submit-BW5g3MjD.js → internal-prompt-submit-BbnaMF2R.js} +7 -8
- package/dist/{internal-prompt-submit-BW5g3MjD.js.map → internal-prompt-submit-BbnaMF2R.js.map} +1 -1
- package/dist/{internal-prompt-submit-C4uDwr7G.js → internal-prompt-submit-DKzCckz-.js} +2 -2
- package/dist/{internal-rebrief-DvBS8myn.js → internal-rebrief-aEvxp7jw.js} +7 -9
- package/dist/{internal-rebrief-DvBS8myn.js.map → internal-rebrief-aEvxp7jw.js.map} +1 -1
- package/dist/{internal-session-bind-dsUOcKxU.js → internal-session-bind-pN1V11Mn.js} +3 -4
- package/dist/{internal-session-bind-dsUOcKxU.js.map → internal-session-bind-pN1V11Mn.js.map} +1 -1
- package/dist/{internal-stop-hook-nS91Jkda.js → internal-stop-hook-VQuOYpUC.js} +9 -10
- package/dist/{internal-stop-hook-nS91Jkda.js.map → internal-stop-hook-VQuOYpUC.js.map} +1 -1
- package/dist/{internal-stop-review-D_KEV_04.js → internal-stop-review-BWp-4XWW.js} +4 -5
- package/dist/{internal-stop-review-D_KEV_04.js.map → internal-stop-review-BWp-4XWW.js.map} +1 -1
- package/dist/{internal-worker-guard-DB6shBIn.js → internal-worker-guard-C9OZPgzu.js} +3 -4
- package/dist/{internal-worker-guard-DB6shBIn.js.map → internal-worker-guard-C9OZPgzu.js.map} +1 -1
- package/dist/{internal-workspace-header-DBg5Y7oN.js → internal-workspace-header-B4TXFBLU.js} +3 -4
- package/dist/{internal-workspace-header-DBg5Y7oN.js.map → internal-workspace-header-B4TXFBLU.js.map} +1 -1
- package/dist/lib/tree-sitter-pool/{lifecycle-Dx0SnP7Z.js → lifecycle-BPpOigPZ.js} +1 -2
- package/dist/lib/tree-sitter-pool/{lifecycle-C7W8D2lx.js → lifecycle-C3vsqXjS.js} +1 -3
- package/dist/lib/tree-sitter-pool/worker.js +29 -35
- package/dist/lifecycle-BENRuuX6.js +1 -0
- package/dist/{lifecycle-K9oVtGde.mjs → lifecycle-DBKu1T5r.mjs} +0 -1
- package/dist/{lifecycle-Gge2Dadd.js → lifecycle-Dh9y8OF1.js} +3 -4
- package/dist/{lifecycle-Gge2Dadd.js.map → lifecycle-Dh9y8OF1.js.map} +1 -1
- package/dist/lifecycle-Dli9vGI2.js +1 -0
- package/dist/{lifecycle-9nX09dBl.js → lifecycle-vjHAFCaY.js} +4 -6
- package/dist/{lifecycle-9nX09dBl.js.map → lifecycle-vjHAFCaY.js.map} +1 -1
- package/dist/main.js +26 -27
- package/dist/{max-profile-contract-CRj7N211.js → max-profile-contract-DLLTsSs2.js} +5 -8
- package/dist/{max-profile-contract-CRj7N211.js.map → max-profile-contract-DLLTsSs2.js.map} +1 -1
- package/dist/{mcp-workspace-header-Xw9B1W6T.js → mcp-workspace-header-C5-dOWNa.js} +3 -4
- package/dist/{mcp-workspace-header-Xw9B1W6T.js.map → mcp-workspace-header-C5-dOWNa.js.map} +1 -1
- package/dist/{models-Ca-HQTYi.js → models-B6nH1sS6.js} +4 -5
- package/dist/{models-Ca-HQTYi.js.map → models-B6nH1sS6.js.map} +1 -1
- package/dist/{orchestration-D3-2ulhX.js → orchestration-B93jxrWI.js} +4 -5
- package/dist/{orchestration-D3-2ulhX.js.map → orchestration-B93jxrWI.js.map} +1 -1
- package/dist/{package-root-B-osctCk.js → package-root-BXgdIM3q.js} +2 -3
- package/dist/{package-root-B-osctCk.js.map → package-root-BXgdIM3q.js.map} +1 -1
- package/dist/paths-Be9_ujQ3.js +1 -0
- package/dist/{paths-C5477RGC.js → paths-CVEO8jEH.js} +5 -7
- package/dist/{paths-C5477RGC.js.map → paths-CVEO8jEH.js.map} +1 -1
- package/dist/{peer-mcp-personas-BSxDj9sJ.js → peer-mcp-personas-Cv21q_YR.js} +244 -372
- package/dist/peer-mcp-personas-Cv21q_YR.js.map +1 -0
- package/dist/{pi-BglhJ6n_.js → pi-DI2QtaiZ.js} +26 -34
- package/dist/{pi-BglhJ6n_.js.map → pi-DI2QtaiZ.js.map} +1 -1
- package/dist/{pi-memory-bridge-DEU1SUDz.js → pi-memory-bridge-Dvj1T3e3.js} +2 -3
- package/dist/{pi-memory-bridge-DEU1SUDz.js.map → pi-memory-bridge-Dvj1T3e3.js.map} +1 -1
- package/dist/{plan-review-hook-C9K-em4D.js → plan-review-hook-MhjK92wq.js} +5 -6
- package/dist/{plan-review-hook-C9K-em4D.js.map → plan-review-hook-MhjK92wq.js.map} +1 -1
- package/dist/{provision-B0GNohdl.js → provision-CRmtV6ew.js} +10 -14
- package/dist/{provision-B0GNohdl.js.map → provision-CRmtV6ew.js.map} +1 -1
- package/dist/rolldown-runtime-D3PmRqjj.js +4 -0
- package/dist/{self-invocation-BtcGj-lY.js → self-invocation-DMUnXVGT.js} +5 -7
- package/dist/{self-invocation-BtcGj-lY.js.map → self-invocation-DMUnXVGT.js.map} +1 -1
- package/dist/{serve-BxZq9vNl.js → serve-DRASJ-ZO.js} +24 -30
- package/dist/{serve-BxZq9vNl.js.map → serve-DRASJ-ZO.js.map} +1 -1
- package/dist/{server-setup-BLdWCcby.js → server-setup-DldGizZR.js} +67 -117
- package/dist/{server-setup-BLdWCcby.js.map → server-setup-DldGizZR.js.map} +1 -1
- package/dist/{service-backend-BV2hHjuB.js → service-backend-Ce6b2XEe.js} +112 -130
- package/dist/service-backend-Ce6b2XEe.js.map +1 -0
- package/dist/{start-C3Zb8XMT.js → start-C0gngUPK.js} +6 -8
- package/dist/{start-C3Zb8XMT.js.map → start-C0gngUPK.js.map} +1 -1
- package/dist/{state-DzsaGHr9.js → state-CCGDJ43X.js} +2 -3
- package/dist/{state-DzsaGHr9.js.map → state-CCGDJ43X.js.map} +1 -1
- package/dist/{static-context-pack-CsOAC87F.js → static-context-pack-DwC69_VA.js} +14 -24
- package/dist/{static-context-pack-CsOAC87F.js.map → static-context-pack-DwC69_VA.js.map} +1 -1
- package/dist/{stop-gate-hook-DnLC09Lg.js → stop-gate-hook-CBVLD8iB.js} +9 -14
- package/dist/{stop-gate-hook-DnLC09Lg.js.map → stop-gate-hook-CBVLD8iB.js.map} +1 -1
- package/dist/{stop-gate-policy-Dx9c98_d.js → stop-gate-policy-BehNiNix.js} +4 -5
- package/dist/{stop-gate-policy-Dx9c98_d.js.map → stop-gate-policy-BehNiNix.js.map} +1 -1
- package/dist/{token-Dqjs5ixP.js → token-CPzYxU4Y.js} +16 -28
- package/dist/{token-Dqjs5ixP.js.map → token-CPzYxU4Y.js.map} +1 -1
- package/dist/{token-CVG0yI_j.js → token-DHEkiO4g.js} +3 -4
- package/dist/{token-CVG0yI_j.js.map → token-DHEkiO4g.js.map} +1 -1
- package/dist/{upstream-retry-i1k1Xai2.js → upstream-retry-VNR-bCuT.js} +2 -3
- package/dist/{upstream-retry-i1k1Xai2.js.map → upstream-retry-VNR-bCuT.js.map} +1 -1
- package/dist/{version-C8x2hQrZ.js → version-CTqwKr26.js} +3 -4
- package/dist/{version-C8x2hQrZ.js.map → version-CTqwKr26.js.map} +1 -1
- package/dist/{worker-dispatch-B1w2qfjX.js → worker-dispatch-C7RtNOXv.js} +3 -4
- package/dist/{worker-dispatch-B1w2qfjX.js.map → worker-dispatch-C7RtNOXv.js.map} +1 -1
- package/dist/{workiq-qnJR5_n2.js → workiq-CQauEAMc.js} +3 -4
- package/dist/{workiq-qnJR5_n2.js.map → workiq-CQauEAMc.js.map} +1 -1
- package/dist/{workiq-tools-C6LAF_vA.js → workiq-tools-7n2xXMrQ.js} +1 -1
- package/package.json +18 -15
- package/dist/ado-tools-WDyisN8w.js +0 -1
- package/dist/engine-C207cikp.js +0 -1
- package/dist/hook-mcp-client-DERIkeR7.js.map +0 -1
- package/dist/index-cmd-DOhwt92u.js.map +0 -1
- package/dist/lifecycle-C_CT13c9.js +0 -1
- package/dist/lifecycle-DibiH857.js +0 -1
- package/dist/paths-CEswtFj5.js +0 -1
- package/dist/peer-mcp-personas-BSxDj9sJ.js.map +0 -1
- package/dist/service-backend-BV2hHjuB.js.map +0 -1
|
@@ -4,7 +4,7 @@ import fs from "node:fs/promises";
|
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
5
|
import { execFileSync } from "node:child_process";
|
|
6
6
|
import process from "node:process";
|
|
7
|
-
|
|
7
|
+
// src/lib/worker-agent/lifecycle.ts
|
|
8
8
|
/**
|
|
9
9
|
* Lifecycle plumbing for worker worktrees: in-memory registry, signal
|
|
10
10
|
* handlers, ledger of repos touched, and the boot-time PID+instance
|
|
@@ -153,5 +153,4 @@ async function sweepStaleWorktreesAtBoot() {
|
|
|
153
153
|
}
|
|
154
154
|
}
|
|
155
155
|
}
|
|
156
|
-
//#endregion
|
|
157
156
|
export { sweepStaleWorktreesAtBoot };
|
|
@@ -2,9 +2,8 @@ import { t as PATHS } from "./worker.js";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import fs from "node:fs/promises";
|
|
4
4
|
import consola from "consola";
|
|
5
|
-
import "node:crypto";
|
|
6
5
|
import process from "node:process";
|
|
7
|
-
|
|
6
|
+
// src/lib/colbert/lifecycle.ts
|
|
8
7
|
/**
|
|
9
8
|
* True iff `pid` names a live process. `process.kill(pid, 0)` probes
|
|
10
9
|
* existence without signalling; `EPERM` means the process exists but is
|
|
@@ -161,5 +160,4 @@ async function exists(p) {
|
|
|
161
160
|
return false;
|
|
162
161
|
}
|
|
163
162
|
}
|
|
164
|
-
//#endregion
|
|
165
163
|
export { sweepStaleColbertMetaAtBoot };
|
|
@@ -2,24 +2,22 @@ import { createRequire } from "node:module";
|
|
|
2
2
|
import { readFileSync, statSync } from "node:fs";
|
|
3
3
|
import { parentPort } from "node:worker_threads";
|
|
4
4
|
import { Language, Parser } from "web-tree-sitter";
|
|
5
|
-
import path, * as path
|
|
6
|
-
import "node:fs/promises";
|
|
5
|
+
import path$1, * as path from "node:path";
|
|
7
6
|
import consola from "consola";
|
|
8
7
|
import { randomBytes } from "node:crypto";
|
|
9
8
|
import os from "node:os";
|
|
10
|
-
|
|
9
|
+
// \0rolldown/runtime.js
|
|
11
10
|
var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
|
|
12
|
-
|
|
13
|
-
//#region src/lib/paths.ts
|
|
11
|
+
// src/lib/paths.ts
|
|
14
12
|
function appDir() {
|
|
15
|
-
return path.join(os.homedir(), ".local", "share", "github-router");
|
|
13
|
+
return path$1.join(os.homedir(), ".local", "share", "github-router");
|
|
16
14
|
}
|
|
17
15
|
const PATHS = {
|
|
18
16
|
get APP_DIR() {
|
|
19
17
|
return appDir();
|
|
20
18
|
},
|
|
21
19
|
get GITHUB_TOKEN_PATH() {
|
|
22
|
-
return path.join(appDir(), "github_token");
|
|
20
|
+
return path$1.join(appDir(), "github_token");
|
|
23
21
|
},
|
|
24
22
|
/**
|
|
25
23
|
* Second, WRITE-capable GitHub token for the first-mate
|
|
@@ -29,7 +27,7 @@ const PATHS = {
|
|
|
29
27
|
* CLI OAuth client. Mode 0o600.
|
|
30
28
|
*/
|
|
31
29
|
get GITHUB_AGENT_TOKEN_PATH() {
|
|
32
|
-
return path.join(appDir(), "github_agent_token");
|
|
30
|
+
return path$1.join(appDir(), "github_agent_token");
|
|
33
31
|
},
|
|
34
32
|
/**
|
|
35
33
|
* Root of the durable first-mate fleet registry (`--agents`): the
|
|
@@ -40,10 +38,10 @@ const PATHS = {
|
|
|
40
38
|
* clears. Modeled on the worker-agent lifecycle ledger.
|
|
41
39
|
*/
|
|
42
40
|
get FIRST_MATE_DIR() {
|
|
43
|
-
return process.env.GH_ROUTER_FIRST_MATE_DIR ?? path.join(appDir(), "first-mate");
|
|
41
|
+
return process.env.GH_ROUTER_FIRST_MATE_DIR ?? path$1.join(appDir(), "first-mate");
|
|
44
42
|
},
|
|
45
43
|
get ERROR_LOG_PATH() {
|
|
46
|
-
return path.join(appDir(), "error.log");
|
|
44
|
+
return path$1.join(appDir(), "error.log");
|
|
47
45
|
},
|
|
48
46
|
/**
|
|
49
47
|
* Durable, router-owned directory for worker OVERFLOW artifacts. Two
|
|
@@ -61,7 +59,7 @@ const PATHS = {
|
|
|
61
59
|
* per-launch CLAUDE_CONFIG_DIR mirror and OUTSIDE the user's repo.
|
|
62
60
|
*/
|
|
63
61
|
get WORKER_DIFFS_DIR() {
|
|
64
|
-
return path.join(appDir(), "worker-diffs");
|
|
62
|
+
return path$1.join(appDir(), "worker-diffs");
|
|
65
63
|
},
|
|
66
64
|
/**
|
|
67
65
|
* Stable home for the relocated hook launcher (`hooks-<sha256>.mjs`).
|
|
@@ -76,7 +74,7 @@ const PATHS = {
|
|
|
76
74
|
* launcher the other is still using.
|
|
77
75
|
*/
|
|
78
76
|
get HOOK_LAUNCHER_DIR() {
|
|
79
|
-
return path.join(appDir(), "hooks");
|
|
77
|
+
return path$1.join(appDir(), "hooks");
|
|
80
78
|
},
|
|
81
79
|
/**
|
|
82
80
|
* Durable copy of the tree-sitter WASM runtime and the grammar subset used
|
|
@@ -85,7 +83,7 @@ const PATHS = {
|
|
|
85
83
|
* not silently disappear after the original install files are removed.
|
|
86
84
|
*/
|
|
87
85
|
get TREE_SITTER_ASSETS_DIR() {
|
|
88
|
-
return path.join(appDir(), "tree-sitter");
|
|
86
|
+
return path$1.join(appDir(), "tree-sitter");
|
|
89
87
|
},
|
|
90
88
|
/**
|
|
91
89
|
* Isolated CODEX_HOME for the spawned Codex CLI. Masks any cached
|
|
@@ -93,7 +91,7 @@ const PATHS = {
|
|
|
93
91
|
* override OPENAI_API_KEY) so the proxy's dummy key is authoritative.
|
|
94
92
|
*/
|
|
95
93
|
get CODEX_HOME() {
|
|
96
|
-
return path.join(appDir(), "codex-isolated");
|
|
94
|
+
return path$1.join(appDir(), "codex-isolated");
|
|
97
95
|
},
|
|
98
96
|
/**
|
|
99
97
|
* Router-owned install + data dir for CloudCLI (the `serve` browser control
|
|
@@ -102,7 +100,7 @@ const PATHS = {
|
|
|
102
100
|
* the persisted `.serve-secret.json` login. See docs/serve-control-plane.md.
|
|
103
101
|
*/
|
|
104
102
|
get CLOUDCLI_HOME() {
|
|
105
|
-
return path.join(appDir(), "cloudcli");
|
|
103
|
+
return path$1.join(appDir(), "cloudcli");
|
|
106
104
|
},
|
|
107
105
|
/**
|
|
108
106
|
* Runtime tempfiles for the per-launch peer-MCP wiring (the
|
|
@@ -112,7 +110,7 @@ const PATHS = {
|
|
|
112
110
|
* boot-time sweep of stale files (dead PIDs, >24h old).
|
|
113
111
|
*/
|
|
114
112
|
get CLAUDE_RUNTIME_DIR() {
|
|
115
|
-
return path.join(appDir(), "runtime");
|
|
113
|
+
return path$1.join(appDir(), "runtime");
|
|
116
114
|
},
|
|
117
115
|
/**
|
|
118
116
|
* Router-owned CLAUDE_CONFIG_DIR. The spawned Claude Code (and any
|
|
@@ -137,7 +135,7 @@ const PATHS = {
|
|
|
137
135
|
* reaps mirrors from crashed prior PIDs.
|
|
138
136
|
*/
|
|
139
137
|
get CLAUDE_CONFIG_DIR() {
|
|
140
|
-
return path.join(appDir(), "claude-config", claudeConfigDirSuffix());
|
|
138
|
+
return path$1.join(appDir(), "claude-config", claudeConfigDirSuffix());
|
|
141
139
|
},
|
|
142
140
|
/**
|
|
143
141
|
* Durable router-owned `bin/` for the LLM toolbelt — curated CLI
|
|
@@ -147,7 +145,7 @@ const PATHS = {
|
|
|
147
145
|
* is a cross-launch cache, like `last-update-check`.
|
|
148
146
|
*/
|
|
149
147
|
get TOOLBELT_BIN_DIR() {
|
|
150
|
-
return path.join(appDir(), "bin");
|
|
148
|
+
return path$1.join(appDir(), "bin");
|
|
151
149
|
},
|
|
152
150
|
/**
|
|
153
151
|
* Root of the github-router-managed ColBERT semantic-search sidecar
|
|
@@ -168,16 +166,16 @@ const PATHS = {
|
|
|
168
166
|
* .gh-router-meta/<hash>.json # router-owned sidecar metadata
|
|
169
167
|
*/
|
|
170
168
|
get COLBERT_DIR() {
|
|
171
|
-
return path.join(appDir(), "colbert");
|
|
169
|
+
return path$1.join(appDir(), "colbert");
|
|
172
170
|
},
|
|
173
171
|
get COLBERT_BIN_DIR() {
|
|
174
|
-
return path.join(appDir(), "colbert", "bin");
|
|
172
|
+
return path$1.join(appDir(), "colbert", "bin");
|
|
175
173
|
},
|
|
176
174
|
get COLBERT_MODELS_DIR() {
|
|
177
|
-
return path.join(appDir(), "colbert", "models");
|
|
175
|
+
return path$1.join(appDir(), "colbert", "models");
|
|
178
176
|
},
|
|
179
177
|
get COLBERT_ORT_DIR() {
|
|
180
|
-
return path.join(appDir(), "colbert", "onnxruntime");
|
|
178
|
+
return path$1.join(appDir(), "colbert", "onnxruntime");
|
|
181
179
|
},
|
|
182
180
|
/**
|
|
183
181
|
* Value passed to colgrep as `COLGREP_DATA_DIR`. colgrep keys the
|
|
@@ -187,10 +185,10 @@ const PATHS = {
|
|
|
187
185
|
* `<COLBERT_INDICES_DIR>/.gh-router-meta/<hash>.json`.
|
|
188
186
|
*/
|
|
189
187
|
get COLBERT_INDICES_DIR() {
|
|
190
|
-
return path.join(appDir(), "colbert", "indices");
|
|
188
|
+
return path$1.join(appDir(), "colbert", "indices");
|
|
191
189
|
},
|
|
192
190
|
get COLBERT_META_DIR() {
|
|
193
|
-
return path.join(appDir(), "colbert", "indices", ".gh-router-meta");
|
|
191
|
+
return path$1.join(appDir(), "colbert", "indices", ".gh-router-meta");
|
|
194
192
|
}
|
|
195
193
|
};
|
|
196
194
|
/**
|
|
@@ -238,8 +236,7 @@ const CLAUDE_HOME_POLICY = /* @__PURE__ */ new Map([
|
|
|
238
236
|
["backups", "SHARED"]
|
|
239
237
|
]);
|
|
240
238
|
Array.from(CLAUDE_HOME_POLICY.entries()).filter(([, kind]) => kind === "SHARED").map(([name]) => name);
|
|
241
|
-
|
|
242
|
-
//#region src/lib/tree-sitter-assets/files.ts
|
|
239
|
+
// src/lib/tree-sitter-assets/files.ts
|
|
243
240
|
/** WASM assets code search loads from tree-sitter-wasms. */
|
|
244
241
|
const TREE_SITTER_GRAMMAR_FILES = {
|
|
245
242
|
typescript: "tree-sitter-typescript.wasm",
|
|
@@ -254,8 +251,7 @@ const TREE_SITTER_GRAMMAR_FILES = {
|
|
|
254
251
|
csharp: "tree-sitter-c_sharp.wasm"
|
|
255
252
|
};
|
|
256
253
|
const TREE_SITTER_RUNTIME_FILE = "tree-sitter.wasm";
|
|
257
|
-
|
|
258
|
-
//#region src/lib/tree-sitter-assets/provision.ts
|
|
254
|
+
// src/lib/tree-sitter-assets/provision.ts
|
|
259
255
|
/**
|
|
260
256
|
* Whether the stable directory holds the COMPLETE asset set: the runtime plus
|
|
261
257
|
* every grammar.
|
|
@@ -271,7 +267,7 @@ function stableTreeSitterAssetsComplete() {
|
|
|
271
267
|
const dir = PATHS.TREE_SITTER_ASSETS_DIR;
|
|
272
268
|
return [TREE_SITTER_RUNTIME_FILE, ...Object.values(TREE_SITTER_GRAMMAR_FILES)].every((name) => {
|
|
273
269
|
try {
|
|
274
|
-
return statSync(path.join(dir, name)).isFile();
|
|
270
|
+
return statSync(path$1.join(dir, name)).isFile();
|
|
275
271
|
} catch {
|
|
276
272
|
return false;
|
|
277
273
|
}
|
|
@@ -456,7 +452,7 @@ function resolveGrammarRoot() {
|
|
|
456
452
|
if (stableTreeSitterAssetsComplete()) return PATHS.TREE_SITTER_ASSETS_DIR;
|
|
457
453
|
try {
|
|
458
454
|
const pkgPath = __require.resolve("tree-sitter-wasms/package.json");
|
|
459
|
-
return path
|
|
455
|
+
return path.join(path.dirname(pkgPath), "out");
|
|
460
456
|
} catch {
|
|
461
457
|
return null;
|
|
462
458
|
}
|
|
@@ -468,7 +464,7 @@ function resolveGrammarRoot() {
|
|
|
468
464
|
*/
|
|
469
465
|
function parserInitOptions() {
|
|
470
466
|
if (!stableTreeSitterAssetsComplete()) return void 0;
|
|
471
|
-
return { locateFile: () => path
|
|
467
|
+
return { locateFile: () => path.join(PATHS.TREE_SITTER_ASSETS_DIR, TREE_SITTER_RUNTIME_FILE) };
|
|
472
468
|
}
|
|
473
469
|
/**
|
|
474
470
|
* Pre-load all grammars at module-init time so the first search
|
|
@@ -492,7 +488,7 @@ function getGrammarBundle() {
|
|
|
492
488
|
return out;
|
|
493
489
|
}
|
|
494
490
|
for (const [key, filename] of Object.entries(GRAMMAR_FILES)) {
|
|
495
|
-
const wasmPath = path
|
|
491
|
+
const wasmPath = path.join(root, filename);
|
|
496
492
|
try {
|
|
497
493
|
const lang = await Language.load(wasmPath);
|
|
498
494
|
out.set(key, lang);
|
|
@@ -781,8 +777,7 @@ function confirmDefinitionSites(tree, source, language, hits, signal) {
|
|
|
781
777
|
}
|
|
782
778
|
return confirmed;
|
|
783
779
|
}
|
|
784
|
-
|
|
785
|
-
//#region src/lib/tree-sitter-pool/worker.ts
|
|
780
|
+
// src/lib/tree-sitter-pool/worker.ts
|
|
786
781
|
/**
|
|
787
782
|
* Tree-sitter parse worker (runs INSIDE a `worker_threads` thread).
|
|
788
783
|
*
|
|
@@ -908,5 +903,4 @@ port.on("message", (msg) => {
|
|
|
908
903
|
};
|
|
909
904
|
port.postMessage(ready);
|
|
910
905
|
})();
|
|
911
|
-
//#endregion
|
|
912
906
|
export { PATHS as t };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { o as sweepStaleWorktreesAtBoot } from "./lifecycle-Dh9y8OF1.js";
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { p as writeRuntimeFileSecure, t as PATHS } from "./paths-
|
|
1
|
+
import { p as writeRuntimeFileSecure, t as PATHS } from "./paths-CVEO8jEH.js";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { randomBytes, randomUUID } from "node:crypto";
|
|
4
4
|
import fs from "node:fs/promises";
|
|
5
5
|
import process from "node:process";
|
|
6
6
|
import { execFileSync } from "node:child_process";
|
|
7
|
-
|
|
7
|
+
// src/lib/worker-agent/lifecycle.ts
|
|
8
8
|
/**
|
|
9
9
|
* Lifecycle plumbing for worker worktrees: in-memory registry, signal
|
|
10
10
|
* handlers, ledger of repos touched, and the boot-time PID+instance
|
|
@@ -324,7 +324,6 @@ async function sweepStaleWorktreesAtBoot() {
|
|
|
324
324
|
}
|
|
325
325
|
}
|
|
326
326
|
}
|
|
327
|
-
//#endregion
|
|
328
327
|
export { sweepRegistry as a, registerExitHandlers as i, getInstanceUuid as n, sweepStaleWorktreesAtBoot as o, recordWorkerRepo as r, WorktreeRegistry as t };
|
|
329
328
|
|
|
330
|
-
//# sourceMappingURL=lifecycle-
|
|
329
|
+
//# sourceMappingURL=lifecycle-Dh9y8OF1.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lifecycle-Gge2Dadd.js","names":[],"sources":["../src/lib/worker-agent/lifecycle.ts"],"sourcesContent":["/**\n * Lifecycle plumbing for worker worktrees: in-memory registry, signal\n * handlers, ledger of repos touched, and the boot-time PID+instance\n * safety net.\n *\n * Plan: see `plans/we-have-added-a-dreamy-tide.md` (\"Worktree mode\" →\n * \"Cleanup paths\"). Three layers cooperate, none of them sufficient\n * alone:\n *\n * 1. Per-call cleanup (`engine.ts` finally block invoking\n * `WorktreeHandle.remove()`) — covers the happy path.\n *\n * 2. Session-end signal sweep (this file, registered via\n * `registerExitHandlers`) — covers Ctrl+C, service-manager stop,\n * and (in `github-router claude` mode) the spawned child's exit.\n * Synchronous `execFileSync` is intentional: exit handlers can't\n * reliably await async work.\n *\n * 3. Boot-time PID+instance sweep (`sweepStaleWorktreesAtBoot`) —\n * covers SIGKILL, OOM, container restart. Walks the ledger of\n * repos this proxy has touched and removes worktree dirs whose\n * `<pid>` is dead OR whose `<instance>` UUID doesn't match the\n * current proxy's UUID.\n *\n * Ledger writes are ATOMIC (temp + rename) per peer review — a\n * concurrent-RMW corruption would silently strand worktrees because\n * the boot sweep can't find their repo roots.\n */\n\nimport { execFileSync } from \"node:child_process\"\nimport { randomBytes, randomUUID } from \"node:crypto\"\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport { PATHS, writeRuntimeFileSecure } from \"../paths\"\n\n/**\n * Same regex worktree.ts uses for its per-call age sweep — kept in\n * sync intentionally. `<pid>-<uuid>-<8hex>` strictly.\n */\nconst WORKTREE_DIR_NAME_RE =\n /^(\\d+)-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})-([0-9a-f]{8})$/\n\n/**\n * Cap on the ledger: how many repos we remember across boots, and how\n * old an entry may be before it's pruned. Both are belt-and-suspenders\n * — the per-call age sweep is the primary guard against accumulation\n * inside any single repo.\n */\nconst LEDGER_MAX_ENTRIES = 100\nconst LEDGER_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000\n\nexport interface WorktreeRegistryEntry {\n repoRoot: string\n dir: string\n branch: string\n}\n\n/**\n * Set-like in-memory registry of worktrees this proxy created. Engine\n * passes it to `createWorktree` so per-call cleanup deletes the entry\n * on success; the signal handlers walk what's left at shutdown.\n *\n * Not a bare `Set` because we want to expose only the operations we\n * actually use, and we want a stable testable surface.\n */\nexport class WorktreeRegistry {\n private readonly entries = new Set<WorktreeRegistryEntry>()\n\n add(entry: WorktreeRegistryEntry): void {\n this.entries.add(entry)\n }\n delete(entry: WorktreeRegistryEntry): void {\n this.entries.delete(entry)\n }\n has(entry: WorktreeRegistryEntry): boolean {\n return this.entries.has(entry)\n }\n values(): IterableIterator<WorktreeRegistryEntry> {\n return this.entries.values()\n }\n get size(): number {\n return this.entries.size\n }\n clear(): void {\n this.entries.clear()\n }\n}\n\n// ---------------------------------------------------------------------\n// Per-launch instance UUID\n// ---------------------------------------------------------------------\n\nlet _instanceUuid: string | null = null\n\n/**\n * Stable UUID4 generated once per proxy process. Used in worktree\n * dir/branch names so the boot sweep can reliably distinguish \"this\n * proxy's still-live worktrees\" from \"stranded dirs from a prior\n * proxy that happens to have a recycled PID\" — Docker PID-1 across\n * container restarts is the classic case (peer-review HIGH finding).\n */\nexport function getInstanceUuid(): string {\n if (_instanceUuid === null) {\n _instanceUuid = randomUUID()\n }\n return _instanceUuid\n}\n\n/** Test-only: reset the cached UUID. */\nexport function __resetInstanceUuidForTests(): void {\n _instanceUuid = null\n}\n\n// ---------------------------------------------------------------------\n// Signal handlers + sweepRegistry\n// ---------------------------------------------------------------------\n\nlet _registered = false\nlet _activeRegistry: WorktreeRegistry | null = null\nlet _exitHandler: (() => void) | null = null\nlet _sigintHandler: (() => void) | null = null\nlet _sigtermHandler: (() => void) | null = null\n\n/**\n * Synchronous cleanup of every registry entry. Best-effort:\n * `execFileSync` failures are swallowed (the dir may have been\n * removed already, or git may not be on PATH any more in some\n * environments). After a successful removal we drop the entry from\n * the registry so a second call is a true no-op.\n *\n * Synchronous on purpose — exit handlers can't reliably await async\n * work; the process would die before the promise settled.\n */\nexport function sweepRegistry(): void {\n if (!_activeRegistry) return\n // Snapshot the values first so we can mutate the underlying set\n // during iteration without skipping entries.\n const snapshot = [..._activeRegistry.values()]\n for (const entry of snapshot) {\n try {\n // `-C entry.repoRoot` is load-bearing: without it git resolves\n // the worktree path relative to the proxy's cwd (which is the\n // user's launch dir, typically NOT inside the target repo), and\n // fails with `fatal: '<path>' is not a working tree`. The E2E\n // boot-sweep test (worker-agent-boot-sweep.test.ts) is what\n // caught the missing flag.\n execFileSync(\n \"git\",\n [\"-C\", entry.repoRoot, \"worktree\", \"remove\", \"--force\", entry.dir],\n { stdio: \"ignore\", timeout: 10_000, windowsHide: true },\n )\n } catch {\n // Already gone, EBUSY, or git not on PATH — best effort.\n }\n try {\n execFileSync(\"git\", [\"-C\", entry.repoRoot, \"branch\", \"-D\", entry.branch], {\n stdio: \"ignore\",\n timeout: 5_000,\n windowsHide: true,\n })\n } catch {\n // Same as above.\n }\n _activeRegistry.delete(entry)\n }\n}\n\n/**\n * Windows ConPTY / node-pty signal behavior:\n *\n * When a ConPTY host (VS Code terminal, Windows Terminal, node-pty) closes\n * the pseudo-console, the ConPTY layer sends CTRL_CLOSE_EVENT to the\n * process group. Node.js translates this into SIGINT (NOT SIGTERM). The\n * process has a ~5-second window before forced termination.\n *\n * Implication: the SIGTERM handler below may NEVER fire in node-pty\n * environments. This is by design — the three-layer cleanup architecture\n * ensures coverage:\n * 1. Per-call cleanup (engine.ts finally block) — happy path\n * 2. SIGINT handler (this file) — ConPTY close, Ctrl+C\n * 3. `exit` handler (this file) — unconditional, fires on any exit\n * 4. Boot-time PID+instance sweep (sweepStaleWorktreesAtBoot) — crash recovery\n *\n * Layers 1+2+3 cover ConPTY; layer 4 covers SIGKILL/OOM/container restart.\n */\n\n/**\n * Wire up SIGINT/SIGTERM/exit handlers that walk the registry and\n * remove every entry. Idempotent: subsequent calls swap the registry\n * pointer but do NOT register additional process listeners (otherwise\n * we'd leak listeners on every `runWorkerAgent`).\n *\n * Signal handlers re-raise the signal after sweeping. Naively running\n * the sweep on SIGINT/SIGTERM and returning would *suppress* the\n * signal: Node defaults to terminating the process on these, but only\n * if no user listener is attached. Once we attach a listener, the\n * default action is cancelled and the process keeps running — which\n * means Ctrl-C would clean worktrees but not actually exit, leaving\n * orphan processes in dev. The `process.kill(pid, sig)` re-raise\n * after removing our own listener restores the default behaviour\n * (the second delivery now hits an empty listener list, so Node\n * terminates with the conventional `128 + signum` exit code).\n */\nexport function registerExitHandlers(registry: WorktreeRegistry): void {\n _activeRegistry = registry\n if (_registered) return\n _registered = true\n _exitHandler = () => sweepRegistry()\n _sigintHandler = () => {\n sweepRegistry()\n if (_sigintHandler) process.off(\"SIGINT\", _sigintHandler)\n process.kill(process.pid, \"SIGINT\")\n }\n _sigtermHandler = () => {\n sweepRegistry()\n if (_sigtermHandler) process.off(\"SIGTERM\", _sigtermHandler)\n process.kill(process.pid, \"SIGTERM\")\n }\n process.on(\"SIGINT\", _sigintHandler)\n process.on(\"SIGTERM\", _sigtermHandler)\n // `exit` handlers can only run synchronous code — exactly what\n // sweepRegistry does. Async work here would never complete.\n process.on(\"exit\", _exitHandler)\n}\n\n/**\n * Test-only: unregister the handlers and reset module state. Tests\n * that want to verify `registerExitHandlers` semantics must clean up\n * after themselves or future tests in the same process inherit the\n * (now stale) registry pointer.\n */\nexport function __unregisterExitHandlersForTests(): void {\n if (_sigintHandler) {\n process.off(\"SIGINT\", _sigintHandler)\n _sigintHandler = null\n }\n if (_sigtermHandler) {\n process.off(\"SIGTERM\", _sigtermHandler)\n _sigtermHandler = null\n }\n if (_exitHandler) {\n process.off(\"exit\", _exitHandler)\n _exitHandler = null\n }\n _registered = false\n _activeRegistry = null\n}\n\n// ---------------------------------------------------------------------\n// Ledger: which repos has this proxy touched?\n// ---------------------------------------------------------------------\n\ninterface LedgerEntry {\n repoRoot: string\n lastSeenMs: number\n}\n\ninterface LedgerFile {\n entries: Array<LedgerEntry>\n}\n\nfunction ledgerPath(): string {\n return path.join(PATHS.APP_DIR, \"worker-repos.json\")\n}\n\nasync function readLedger(): Promise<LedgerFile> {\n let raw: string\n try {\n raw = await fs.readFile(ledgerPath(), \"utf8\")\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { entries: [] }\n }\n return { entries: [] }\n }\n try {\n const parsed = JSON.parse(raw) as Partial<LedgerFile>\n if (!parsed || !Array.isArray(parsed.entries)) return { entries: [] }\n const cleaned: Array<LedgerEntry> = []\n for (const e of parsed.entries) {\n if (\n e &&\n typeof e === \"object\" &&\n typeof (e as LedgerEntry).repoRoot === \"string\" &&\n typeof (e as LedgerEntry).lastSeenMs === \"number\"\n ) {\n cleaned.push({\n repoRoot: (e as LedgerEntry).repoRoot,\n lastSeenMs: (e as LedgerEntry).lastSeenMs,\n })\n }\n }\n return { entries: cleaned }\n } catch {\n // Corrupted JSON — start fresh rather than crashing the proxy.\n return { entries: [] }\n }\n}\n\n/**\n * Per-process serializer for ledger writes. Multiple concurrent\n * `recordWorkerRepo` calls (legitimate: several workers may start at\n * once) would otherwise race read-modify-write on the JSON file. Each\n * call chains onto the previous so the on-disk sequence is\n * deterministic from this process's perspective.\n *\n * Cross-process safety is provided by the atomic temp+rename below,\n * which makes the final state of the file always be a well-formed\n * full snapshot from ONE writer — never a partial write or\n * interleaved JSON.\n */\nlet _ledgerChain: Promise<void> = Promise.resolve()\n\n/**\n * Append `repoRoot` to the ledger (or update its `lastSeenMs`).\n * Atomic temp+rename per peer review.\n */\nexport function recordWorkerRepo(repoRoot: string): Promise<void> {\n const next = _ledgerChain.then(async () => {\n await fs.mkdir(PATHS.APP_DIR, { recursive: true })\n const current = await readLedger()\n // Dedup: drop any existing entry for this root before appending\n // the fresh one so the array doesn't grow unbounded with repeats.\n const filtered = current.entries.filter((e) => e.repoRoot !== repoRoot)\n filtered.push({ repoRoot, lastSeenMs: Date.now() })\n // Prune by age and cap entry count (newest wins).\n const now = Date.now()\n const pruned = filtered\n .filter((e) => now - e.lastSeenMs < LEDGER_MAX_AGE_MS)\n .slice(-LEDGER_MAX_ENTRIES)\n const ledger: LedgerFile = { entries: pruned }\n\n // Atomic temp+rename. The temp filename is unique per call\n // (PID + 8 random hex chars) so concurrent processes don't\n // collide on the temp name; the final `rename` is atomic on\n // POSIX and on Windows (both with same filesystem).\n const tmp = `${ledgerPath()}.tmp.${process.pid}.${randomBytes(4).toString(\n \"hex\",\n )}`\n try {\n await writeRuntimeFileSecure(tmp, JSON.stringify(ledger, null, 2))\n await fs.rename(tmp, ledgerPath())\n } catch (err) {\n // Clean up the temp file if rename failed midway.\n await fs.unlink(tmp).catch(() => {})\n throw err\n }\n })\n // Swallow chain-internal errors so one failed write doesn't poison\n // the chain for every subsequent caller. Each call still sees its\n // own rejection (we return `next`, not the catch-handler chain).\n _ledgerChain = next.catch(() => undefined)\n return next\n}\n\nfunction isPidAlive(pid: number): boolean {\n if (!Number.isInteger(pid) || pid <= 0) return false\n try {\n process.kill(pid, 0)\n return true\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n // EPERM = process exists but we can't signal it — still alive\n // for our purposes (we just need to know whether to clean up).\n if (code === \"EPERM\") return true\n return false\n }\n}\n\n/**\n * Boot-time sweep. For every repo we recorded in the ledger,\n * enumerate `<repoRoot>/.git/worker-worktrees/` (the conventional\n * location — for repos already inside a worktree, the actual\n * `git-common-dir` may differ, in which case we'll miss this batch\n * and the per-call age sweep will catch them within 7 days) and\n * remove dirs that aren't owned by THIS proxy.\n *\n * Ownership rule: dir is \"ours\" iff its embedded PID is alive AND\n * its embedded UUID equals `getInstanceUuid()`. Either condition\n * failing → remove.\n */\nexport async function sweepStaleWorktreesAtBoot(): Promise<void> {\n const ledger = await readLedger()\n if (ledger.entries.length === 0) return\n const currentUuid = getInstanceUuid()\n for (const entry of ledger.entries) {\n const parent = path.join(entry.repoRoot, \".git\", \"worker-worktrees\")\n let names: Array<string>\n try {\n names = await fs.readdir(parent)\n } catch {\n continue\n }\n for (const name of names) {\n const m = WORKTREE_DIR_NAME_RE.exec(name)\n if (!m) continue\n const pid = Number.parseInt(m[1], 10)\n const uuid = m[2]\n const isOurs = isPidAlive(pid) && uuid === currentUuid\n if (isOurs) continue\n\n const fullDir = path.join(parent, name)\n const branch = `worker/${pid}-${uuid}-${m[3]}`\n try {\n // `-C entry.repoRoot` is load-bearing here too — see the\n // matching comment in `sweepRegistry`. The boot sweep runs\n // BEFORE any worker tool has set cwd, so the proxy's cwd is\n // the user's launch dir, which is almost never inside the\n // target repo.\n execFileSync(\n \"git\",\n [\"-C\", entry.repoRoot, \"worktree\", \"remove\", \"--force\", fullDir],\n { stdio: \"ignore\", timeout: 10_000, windowsHide: true },\n )\n } catch {\n // ignore\n }\n try {\n execFileSync(\n \"git\",\n [\"-C\", entry.repoRoot, \"branch\", \"-D\", branch],\n { stdio: \"ignore\", timeout: 5_000, windowsHide: true },\n )\n } catch {\n // ignore\n }\n try {\n await fs.rm(fullDir, { recursive: true, force: true })\n } catch {\n // ignore — git may have removed it already\n }\n }\n }\n}\n\n/** Test-only: clear the ledger file (does NOT remove on-disk worktrees). */\nexport async function __clearLedgerForTests(): Promise<void> {\n await fs.unlink(ledgerPath()).catch(() => {})\n}\n\n/** Test-only: read the ledger as a plain array (no side effects). */\nexport async function __readLedgerForTests(): Promise<Array<LedgerEntry>> {\n return (await readLedger()).entries\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAM,uBACJ;AASF,MAAM,oBAAoB;;;;;;;;;AAgB1B,IAAa,mBAAb,MAA8B;CAC5B,0BAA2B,IAAI,IAA2B;CAE1D,IAAI,OAAoC;EACtC,KAAK,QAAQ,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AEf,IADe,WAAW,GAAG,KAAK,SAAS,aAC/B;GAEZ,MAAM,UAAU,KAAK,KAAK,QAAQ,IAAI;GACtC,MAAM,SAAS,UAAU,IAAI,GAAG,KAAK,GAAG,EAAE;GAC1C,IAAI;IAMF,aACE,OACA;KAAC;KAAM,MAAM;KAAU;KAAY;KAAU;KAAW;IAAO,GAC/D;KAAE,OAAO;KAAU,SAAS;KAAQ,aAAa;IAAK,CACxD;GACF,QAAQ,CAER;GACA,IAAI;IACF,aACE,OACA;KAAC;KAAM,MAAM;KAAU;KAAU;KAAM;IAAM,GAC7C;KAAE,OAAO;KAAU,SAAS;KAAO,aAAa;IAAK,CACvD;GACF,QAAQ,CAER;GACA,IAAI;IACF,MAAM,GAAG,GAAG,SAAS;KAAE,WAAW;KAAM,OAAO;IAAK,CAAC;GACvD,QAAQ,CAER;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"lifecycle-Dh9y8OF1.js","names":[],"sources":["../src/lib/worker-agent/lifecycle.ts"],"sourcesContent":["/**\n * Lifecycle plumbing for worker worktrees: in-memory registry, signal\n * handlers, ledger of repos touched, and the boot-time PID+instance\n * safety net.\n *\n * Plan: see `plans/we-have-added-a-dreamy-tide.md` (\"Worktree mode\" →\n * \"Cleanup paths\"). Three layers cooperate, none of them sufficient\n * alone:\n *\n * 1. Per-call cleanup (`engine.ts` finally block invoking\n * `WorktreeHandle.remove()`) — covers the happy path.\n *\n * 2. Session-end signal sweep (this file, registered via\n * `registerExitHandlers`) — covers Ctrl+C, service-manager stop,\n * and (in `github-router claude` mode) the spawned child's exit.\n * Synchronous `execFileSync` is intentional: exit handlers can't\n * reliably await async work.\n *\n * 3. Boot-time PID+instance sweep (`sweepStaleWorktreesAtBoot`) —\n * covers SIGKILL, OOM, container restart. Walks the ledger of\n * repos this proxy has touched and removes worktree dirs whose\n * `<pid>` is dead OR whose `<instance>` UUID doesn't match the\n * current proxy's UUID.\n *\n * Ledger writes are ATOMIC (temp + rename) per peer review — a\n * concurrent-RMW corruption would silently strand worktrees because\n * the boot sweep can't find their repo roots.\n */\n\nimport { execFileSync } from \"node:child_process\"\nimport { randomBytes, randomUUID } from \"node:crypto\"\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport { PATHS, writeRuntimeFileSecure } from \"../paths\"\n\n/**\n * Same regex worktree.ts uses for its per-call age sweep — kept in\n * sync intentionally. `<pid>-<uuid>-<8hex>` strictly.\n */\nconst WORKTREE_DIR_NAME_RE =\n /^(\\d+)-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})-([0-9a-f]{8})$/\n\n/**\n * Cap on the ledger: how many repos we remember across boots, and how\n * old an entry may be before it's pruned. Both are belt-and-suspenders\n * — the per-call age sweep is the primary guard against accumulation\n * inside any single repo.\n */\nconst LEDGER_MAX_ENTRIES = 100\nconst LEDGER_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000\n\nexport interface WorktreeRegistryEntry {\n repoRoot: string\n dir: string\n branch: string\n}\n\n/**\n * Set-like in-memory registry of worktrees this proxy created. Engine\n * passes it to `createWorktree` so per-call cleanup deletes the entry\n * on success; the signal handlers walk what's left at shutdown.\n *\n * Not a bare `Set` because we want to expose only the operations we\n * actually use, and we want a stable testable surface.\n */\nexport class WorktreeRegistry {\n private readonly entries = new Set<WorktreeRegistryEntry>()\n\n add(entry: WorktreeRegistryEntry): void {\n this.entries.add(entry)\n }\n delete(entry: WorktreeRegistryEntry): void {\n this.entries.delete(entry)\n }\n has(entry: WorktreeRegistryEntry): boolean {\n return this.entries.has(entry)\n }\n values(): IterableIterator<WorktreeRegistryEntry> {\n return this.entries.values()\n }\n get size(): number {\n return this.entries.size\n }\n clear(): void {\n this.entries.clear()\n }\n}\n\n// ---------------------------------------------------------------------\n// Per-launch instance UUID\n// ---------------------------------------------------------------------\n\nlet _instanceUuid: string | null = null\n\n/**\n * Stable UUID4 generated once per proxy process. Used in worktree\n * dir/branch names so the boot sweep can reliably distinguish \"this\n * proxy's still-live worktrees\" from \"stranded dirs from a prior\n * proxy that happens to have a recycled PID\" — Docker PID-1 across\n * container restarts is the classic case (peer-review HIGH finding).\n */\nexport function getInstanceUuid(): string {\n if (_instanceUuid === null) {\n _instanceUuid = randomUUID()\n }\n return _instanceUuid\n}\n\n/** Test-only: reset the cached UUID. */\nexport function __resetInstanceUuidForTests(): void {\n _instanceUuid = null\n}\n\n// ---------------------------------------------------------------------\n// Signal handlers + sweepRegistry\n// ---------------------------------------------------------------------\n\nlet _registered = false\nlet _activeRegistry: WorktreeRegistry | null = null\nlet _exitHandler: (() => void) | null = null\nlet _sigintHandler: (() => void) | null = null\nlet _sigtermHandler: (() => void) | null = null\n\n/**\n * Synchronous cleanup of every registry entry. Best-effort:\n * `execFileSync` failures are swallowed (the dir may have been\n * removed already, or git may not be on PATH any more in some\n * environments). After a successful removal we drop the entry from\n * the registry so a second call is a true no-op.\n *\n * Synchronous on purpose — exit handlers can't reliably await async\n * work; the process would die before the promise settled.\n */\nexport function sweepRegistry(): void {\n if (!_activeRegistry) return\n // Snapshot the values first so we can mutate the underlying set\n // during iteration without skipping entries.\n const snapshot = [..._activeRegistry.values()]\n for (const entry of snapshot) {\n try {\n // `-C entry.repoRoot` is load-bearing: without it git resolves\n // the worktree path relative to the proxy's cwd (which is the\n // user's launch dir, typically NOT inside the target repo), and\n // fails with `fatal: '<path>' is not a working tree`. The E2E\n // boot-sweep test (worker-agent-boot-sweep.test.ts) is what\n // caught the missing flag.\n execFileSync(\n \"git\",\n [\"-C\", entry.repoRoot, \"worktree\", \"remove\", \"--force\", entry.dir],\n { stdio: \"ignore\", timeout: 10_000, windowsHide: true },\n )\n } catch {\n // Already gone, EBUSY, or git not on PATH — best effort.\n }\n try {\n execFileSync(\"git\", [\"-C\", entry.repoRoot, \"branch\", \"-D\", entry.branch], {\n stdio: \"ignore\",\n timeout: 5_000,\n windowsHide: true,\n })\n } catch {\n // Same as above.\n }\n _activeRegistry.delete(entry)\n }\n}\n\n/**\n * Windows ConPTY / node-pty signal behavior:\n *\n * When a ConPTY host (VS Code terminal, Windows Terminal, node-pty) closes\n * the pseudo-console, the ConPTY layer sends CTRL_CLOSE_EVENT to the\n * process group. Node.js translates this into SIGINT (NOT SIGTERM). The\n * process has a ~5-second window before forced termination.\n *\n * Implication: the SIGTERM handler below may NEVER fire in node-pty\n * environments. This is by design — the three-layer cleanup architecture\n * ensures coverage:\n * 1. Per-call cleanup (engine.ts finally block) — happy path\n * 2. SIGINT handler (this file) — ConPTY close, Ctrl+C\n * 3. `exit` handler (this file) — unconditional, fires on any exit\n * 4. Boot-time PID+instance sweep (sweepStaleWorktreesAtBoot) — crash recovery\n *\n * Layers 1+2+3 cover ConPTY; layer 4 covers SIGKILL/OOM/container restart.\n */\n\n/**\n * Wire up SIGINT/SIGTERM/exit handlers that walk the registry and\n * remove every entry. Idempotent: subsequent calls swap the registry\n * pointer but do NOT register additional process listeners (otherwise\n * we'd leak listeners on every `runWorkerAgent`).\n *\n * Signal handlers re-raise the signal after sweeping. Naively running\n * the sweep on SIGINT/SIGTERM and returning would *suppress* the\n * signal: Node defaults to terminating the process on these, but only\n * if no user listener is attached. Once we attach a listener, the\n * default action is cancelled and the process keeps running — which\n * means Ctrl-C would clean worktrees but not actually exit, leaving\n * orphan processes in dev. The `process.kill(pid, sig)` re-raise\n * after removing our own listener restores the default behaviour\n * (the second delivery now hits an empty listener list, so Node\n * terminates with the conventional `128 + signum` exit code).\n */\nexport function registerExitHandlers(registry: WorktreeRegistry): void {\n _activeRegistry = registry\n if (_registered) return\n _registered = true\n _exitHandler = () => sweepRegistry()\n _sigintHandler = () => {\n sweepRegistry()\n if (_sigintHandler) process.off(\"SIGINT\", _sigintHandler)\n process.kill(process.pid, \"SIGINT\")\n }\n _sigtermHandler = () => {\n sweepRegistry()\n if (_sigtermHandler) process.off(\"SIGTERM\", _sigtermHandler)\n process.kill(process.pid, \"SIGTERM\")\n }\n process.on(\"SIGINT\", _sigintHandler)\n process.on(\"SIGTERM\", _sigtermHandler)\n // `exit` handlers can only run synchronous code — exactly what\n // sweepRegistry does. Async work here would never complete.\n process.on(\"exit\", _exitHandler)\n}\n\n/**\n * Test-only: unregister the handlers and reset module state. Tests\n * that want to verify `registerExitHandlers` semantics must clean up\n * after themselves or future tests in the same process inherit the\n * (now stale) registry pointer.\n */\nexport function __unregisterExitHandlersForTests(): void {\n if (_sigintHandler) {\n process.off(\"SIGINT\", _sigintHandler)\n _sigintHandler = null\n }\n if (_sigtermHandler) {\n process.off(\"SIGTERM\", _sigtermHandler)\n _sigtermHandler = null\n }\n if (_exitHandler) {\n process.off(\"exit\", _exitHandler)\n _exitHandler = null\n }\n _registered = false\n _activeRegistry = null\n}\n\n// ---------------------------------------------------------------------\n// Ledger: which repos has this proxy touched?\n// ---------------------------------------------------------------------\n\ninterface LedgerEntry {\n repoRoot: string\n lastSeenMs: number\n}\n\ninterface LedgerFile {\n entries: Array<LedgerEntry>\n}\n\nfunction ledgerPath(): string {\n return path.join(PATHS.APP_DIR, \"worker-repos.json\")\n}\n\nasync function readLedger(): Promise<LedgerFile> {\n let raw: string\n try {\n raw = await fs.readFile(ledgerPath(), \"utf8\")\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { entries: [] }\n }\n return { entries: [] }\n }\n try {\n const parsed = JSON.parse(raw) as Partial<LedgerFile>\n if (!parsed || !Array.isArray(parsed.entries)) return { entries: [] }\n const cleaned: Array<LedgerEntry> = []\n for (const e of parsed.entries) {\n if (\n e &&\n typeof e === \"object\" &&\n typeof (e as LedgerEntry).repoRoot === \"string\" &&\n typeof (e as LedgerEntry).lastSeenMs === \"number\"\n ) {\n cleaned.push({\n repoRoot: (e as LedgerEntry).repoRoot,\n lastSeenMs: (e as LedgerEntry).lastSeenMs,\n })\n }\n }\n return { entries: cleaned }\n } catch {\n // Corrupted JSON — start fresh rather than crashing the proxy.\n return { entries: [] }\n }\n}\n\n/**\n * Per-process serializer for ledger writes. Multiple concurrent\n * `recordWorkerRepo` calls (legitimate: several workers may start at\n * once) would otherwise race read-modify-write on the JSON file. Each\n * call chains onto the previous so the on-disk sequence is\n * deterministic from this process's perspective.\n *\n * Cross-process safety is provided by the atomic temp+rename below,\n * which makes the final state of the file always be a well-formed\n * full snapshot from ONE writer — never a partial write or\n * interleaved JSON.\n */\nlet _ledgerChain: Promise<void> = Promise.resolve()\n\n/**\n * Append `repoRoot` to the ledger (or update its `lastSeenMs`).\n * Atomic temp+rename per peer review.\n */\nexport function recordWorkerRepo(repoRoot: string): Promise<void> {\n const next = _ledgerChain.then(async () => {\n await fs.mkdir(PATHS.APP_DIR, { recursive: true })\n const current = await readLedger()\n // Dedup: drop any existing entry for this root before appending\n // the fresh one so the array doesn't grow unbounded with repeats.\n const filtered = current.entries.filter((e) => e.repoRoot !== repoRoot)\n filtered.push({ repoRoot, lastSeenMs: Date.now() })\n // Prune by age and cap entry count (newest wins).\n const now = Date.now()\n const pruned = filtered\n .filter((e) => now - e.lastSeenMs < LEDGER_MAX_AGE_MS)\n .slice(-LEDGER_MAX_ENTRIES)\n const ledger: LedgerFile = { entries: pruned }\n\n // Atomic temp+rename. The temp filename is unique per call\n // (PID + 8 random hex chars) so concurrent processes don't\n // collide on the temp name; the final `rename` is atomic on\n // POSIX and on Windows (both with same filesystem).\n const tmp = `${ledgerPath()}.tmp.${process.pid}.${randomBytes(4).toString(\n \"hex\",\n )}`\n try {\n await writeRuntimeFileSecure(tmp, JSON.stringify(ledger, null, 2))\n await fs.rename(tmp, ledgerPath())\n } catch (err) {\n // Clean up the temp file if rename failed midway.\n await fs.unlink(tmp).catch(() => {})\n throw err\n }\n })\n // Swallow chain-internal errors so one failed write doesn't poison\n // the chain for every subsequent caller. Each call still sees its\n // own rejection (we return `next`, not the catch-handler chain).\n _ledgerChain = next.catch(() => undefined)\n return next\n}\n\nfunction isPidAlive(pid: number): boolean {\n if (!Number.isInteger(pid) || pid <= 0) return false\n try {\n process.kill(pid, 0)\n return true\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n // EPERM = process exists but we can't signal it — still alive\n // for our purposes (we just need to know whether to clean up).\n if (code === \"EPERM\") return true\n return false\n }\n}\n\n/**\n * Boot-time sweep. For every repo we recorded in the ledger,\n * enumerate `<repoRoot>/.git/worker-worktrees/` (the conventional\n * location — for repos already inside a worktree, the actual\n * `git-common-dir` may differ, in which case we'll miss this batch\n * and the per-call age sweep will catch them within 7 days) and\n * remove dirs that aren't owned by THIS proxy.\n *\n * Ownership rule: dir is \"ours\" iff its embedded PID is alive AND\n * its embedded UUID equals `getInstanceUuid()`. Either condition\n * failing → remove.\n */\nexport async function sweepStaleWorktreesAtBoot(): Promise<void> {\n const ledger = await readLedger()\n if (ledger.entries.length === 0) return\n const currentUuid = getInstanceUuid()\n for (const entry of ledger.entries) {\n const parent = path.join(entry.repoRoot, \".git\", \"worker-worktrees\")\n let names: Array<string>\n try {\n names = await fs.readdir(parent)\n } catch {\n continue\n }\n for (const name of names) {\n const m = WORKTREE_DIR_NAME_RE.exec(name)\n if (!m) continue\n const pid = Number.parseInt(m[1], 10)\n const uuid = m[2]\n const isOurs = isPidAlive(pid) && uuid === currentUuid\n if (isOurs) continue\n\n const fullDir = path.join(parent, name)\n const branch = `worker/${pid}-${uuid}-${m[3]}`\n try {\n // `-C entry.repoRoot` is load-bearing here too — see the\n // matching comment in `sweepRegistry`. The boot sweep runs\n // BEFORE any worker tool has set cwd, so the proxy's cwd is\n // the user's launch dir, which is almost never inside the\n // target repo.\n execFileSync(\n \"git\",\n [\"-C\", entry.repoRoot, \"worktree\", \"remove\", \"--force\", fullDir],\n { stdio: \"ignore\", timeout: 10_000, windowsHide: true },\n )\n } catch {\n // ignore\n }\n try {\n execFileSync(\n \"git\",\n [\"-C\", entry.repoRoot, \"branch\", \"-D\", branch],\n { stdio: \"ignore\", timeout: 5_000, windowsHide: true },\n )\n } catch {\n // ignore\n }\n try {\n await fs.rm(fullDir, { recursive: true, force: true })\n } catch {\n // ignore — git may have removed it already\n }\n }\n }\n}\n\n/** Test-only: clear the ledger file (does NOT remove on-disk worktrees). */\nexport async function __clearLedgerForTests(): Promise<void> {\n await fs.unlink(ledgerPath()).catch(() => {})\n}\n\n/** Test-only: read the ledger as a plain array (no side effects). */\nexport async function __readLedgerForTests(): Promise<Array<LedgerEntry>> {\n return (await readLedger()).entries\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAM,uBACJ;AASF,MAAM,oBAAoB;;;;;;;;;AAgB1B,IAAa,mBAAb,MAA8B;CACX,0BAAU,IAAI,IAA2B;CAE1D,IAAI,OAAoC;EACtC,KAAK,QAAQ,IAAI,KAAK;CACxB;CACA,OAAO,OAAoC;EACzC,KAAK,QAAQ,OAAO,KAAK;CAC3B;CACA,IAAI,OAAuC;EACzC,OAAO,KAAK,QAAQ,IAAI,KAAK;CAC/B;CACA,SAAkD;EAChD,OAAO,KAAK,QAAQ,OAAO;CAC7B;CACA,IAAI,OAAe;EACjB,OAAO,KAAK,QAAQ;CACtB;CACA,QAAc;EACZ,KAAK,QAAQ,MAAM;CACrB;AACF;AAMA,IAAI,gBAA+B;;;;;;;;AASnC,SAAgB,kBAA0B;CACxC,IAAI,kBAAkB,MACpB,gBAAgB,WAAW;CAE7B,OAAO;AACT;AAWA,IAAI,cAAc;AAClB,IAAI,kBAA2C;AAC/C,IAAI,eAAoC;AACxC,IAAI,iBAAsC;AAC1C,IAAI,kBAAuC;;;;;;;;;;;AAY3C,SAAgB,gBAAsB;CACpC,IAAI,CAAC,iBAAiB;CAGtB,MAAM,WAAW,CAAC,GAAG,gBAAgB,OAAO,CAAC;CAC7C,KAAK,MAAM,SAAS,UAAU;EAC5B,IAAI;GAOF,aACE,OACA;IAAC;IAAM,MAAM;IAAU;IAAY;IAAU;IAAW,MAAM;GAAG,GACjE;IAAE,OAAO;IAAU,SAAS;IAAQ,aAAa;GAAK,CACxD;EACF,QAAQ,CAER;EAC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AC/D,MAAM,SAAS,MAAM,WAAW;CAChC,IAAI,OAAO,QAAQ,WAAW,GAAG;CACjC,MAAM,cAAc,gBAAgB;CACpC,KAAK,MAAM,SAAS,OAAO,SAAS;EAClC,MAAM,SAAS,KAAK,KAAK,MAAM,UAAU,QAAQ,kBAAkB;EACnE,IAAI;EACJ,IAAI;GACF,QAAQ,MAAM,GAAG,QAAQ,MAAM;EACjC,QAAQ;GACN;EACF;EACA,KAAK,MAAM,QAAQ,OAAO;GACxB,MAAM,IAAI,qBAAqB,KAAK,IAAI;GACxC,IAAI,CAAC,GAAG;GACR,MAAM,MAAM,OAAO,SAAS,EAAE,IAAI,EAAE;GACpC,MAAM,OAAO,EAAE;GAEf,IADe,WAAW,GAAG,KAAK,SAAS,aAC/B;GAEZ,MAAM,UAAU,KAAK,KAAK,QAAQ,IAAI;GACtC,MAAM,SAAS,UAAU,IAAI,GAAG,KAAK,GAAG,EAAE;GAC1C,IAAI;IAMF,aACE,OACA;KAAC;KAAM,MAAM;KAAU;KAAY;KAAU;KAAW;IAAO,GAC/D;KAAE,OAAO;KAAU,SAAS;KAAQ,aAAa;IAAK,CACxD;GACF,QAAQ,CAER;GACA,IAAI;IACF,aACE,OACA;KAAC;KAAM,MAAM;KAAU;KAAU;KAAM;IAAM,GAC7C;KAAE,OAAO;KAAU,SAAS;KAAO,aAAa;IAAK,CACvD;GACF,QAAQ,CAER;GACA,IAAI;IACF,MAAM,GAAG,GAAG,SAAS;KAAE,WAAW;KAAM,OAAO;IAAK,CAAC;GACvD,QAAQ,CAER;EACF;CACF;AACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { o as sweepStaleColbertMetaAtBoot } from "./lifecycle-vjHAFCaY.js";
|
|
@@ -1,12 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { i as killManagedTree } from "./exec-BC0MAnoA.js";
|
|
2
|
+
import { t as PATHS } from "./paths-CVEO8jEH.js";
|
|
3
3
|
import consola from "consola";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { randomUUID } from "node:crypto";
|
|
6
6
|
import fs from "node:fs/promises";
|
|
7
7
|
import process from "node:process";
|
|
8
|
-
|
|
9
|
-
//#region src/lib/colbert/lifecycle.ts
|
|
8
|
+
// src/lib/colbert/lifecycle.ts
|
|
10
9
|
let _instanceUuid = null;
|
|
11
10
|
/**
|
|
12
11
|
* Stable UUID4 generated once per proxy process. Written into the
|
|
@@ -229,7 +228,6 @@ async function exists(p) {
|
|
|
229
228
|
return false;
|
|
230
229
|
}
|
|
231
230
|
}
|
|
232
|
-
//#endregion
|
|
233
231
|
export { sweepLiveChildren as a, untrackChild as c, sweepColbertStore as i, isPidAlive as n, sweepStaleColbertMetaAtBoot as o, registerColbertExitHandlers as r, trackChild as s, getColbertInstanceUuid as t };
|
|
234
232
|
|
|
235
|
-
//# sourceMappingURL=lifecycle-
|
|
233
|
+
//# sourceMappingURL=lifecycle-vjHAFCaY.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lifecycle-9nX09dBl.js","names":[],"sources":["../src/lib/colbert/lifecycle.ts"],"sourcesContent":["/**\n * ColBERT sidecar lifecycle: in-memory PID ledger for the short-lived\n * `colgrep` children this proxy spawns, signal-handler tree-kill on\n * exit, and a boot-time metadata reclassification sweep.\n *\n * Because colgrep is CLI-per-invocation (no daemon), the lifecycle\n * problem is **process tracking + cancellation + boot/exit sweep**, NOT\n * keep-alive. Modeled on `worker-agent/lifecycle.ts` (PID ledger + boot\n * sweep + per-proxy-run instance UUID) and `exec.ts`'s tree-kill.\n *\n * Three cooperating layers (none sufficient alone):\n * 1. Per-call cleanup — the runner's `finally` force-kills the child\n * it spawned (handled in runner.ts).\n * 2. Session-end signal sweep (this file) — SIGINT/SIGTERM/exit kill\n * every still-tracked child of THIS run.\n * 3. Boot-time sweep (`sweepStaleColbertMetaAtBoot`) — reclassifies\n * `.gh-router-meta/*.json` entries whose `buildPid` is dead from\n * `building` → `failed`. It NEVER issues a kill to a PID from a\n * prior boot (a reused PID may belong to an unrelated process);\n * only the in-memory ledger (this run's spawns) is ever killed.\n */\n\nimport { spawn } from \"node:child_process\"\nimport { randomUUID } from \"node:crypto\"\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport consola from \"consola\"\n\nimport { killManagedTree } from \"../exec\"\nimport { PATHS } from \"../paths\"\n\n// ---------------------------------------------------------------------\n// Per-launch instance UUID (mirrors worker-agent/lifecycle.ts)\n// ---------------------------------------------------------------------\n\nlet _instanceUuid: string | null = null\n\n/**\n * Stable UUID4 generated once per proxy process. Written into the\n * sidecar metadata `ownerInstanceId` so the boot sweep can tell \"this\n * proxy's still-live build\" from \"a stranded `building` entry from a\n * prior proxy whose PID got recycled\" (Docker PID-1 across restarts).\n */\nexport function getColbertInstanceUuid(): string {\n if (_instanceUuid === null) _instanceUuid = randomUUID()\n return _instanceUuid\n}\n\n/** Test-only: reset the cached UUID. */\nexport function __resetColbertInstanceUuidForTests(): void {\n _instanceUuid = null\n}\n\n// ---------------------------------------------------------------------\n// In-memory PID ledger of THIS run's live colgrep children\n// ---------------------------------------------------------------------\n\ntype TrackedChild = ReturnType<typeof spawn>\n\nconst _liveChildren = new Set<TrackedChild>()\n\n/**\n * Register a freshly-spawned colgrep child so the exit sweep can reap\n * it. The runner also removes it on natural close via `untrackChild`.\n */\nexport function trackChild(child: TrackedChild): void {\n _liveChildren.add(child)\n child.once(\"close\", () => _liveChildren.delete(child))\n child.once(\"error\", () => _liveChildren.delete(child))\n}\n\n/** Remove a child from the ledger (e.g. after a clean per-call kill). */\nexport function untrackChild(child: TrackedChild): void {\n _liveChildren.delete(child)\n}\n\n/** Count of live tracked children (test/diagnostic). */\nexport function liveChildCount(): number {\n return _liveChildren.size\n}\n\n/**\n * Synchronous best-effort tree-kill of every tracked child. Called from\n * the signal/exit handlers. After killing, the set is cleared so a\n * second call is a no-op.\n */\nexport function sweepLiveChildren(): void {\n const isWin = process.platform === \"win32\"\n for (const child of _liveChildren) {\n try {\n killManagedTree(child, isWin)\n } catch {\n // already gone\n }\n }\n _liveChildren.clear()\n}\n\n// ---------------------------------------------------------------------\n// Signal handlers (mirror worker-agent/lifecycle.ts re-raise pattern)\n// ---------------------------------------------------------------------\n\nlet _registered = false\nlet _exitHandler: (() => void) | null = null\nlet _sigintHandler: (() => void) | null = null\nlet _sigtermHandler: (() => void) | null = null\n\n/**\n * Wire SIGINT/SIGTERM/exit handlers that tree-kill every tracked\n * colgrep child. Idempotent — subsequent calls are a no-op (we never\n * leak listeners). The signal handlers re-raise after sweeping so Node's\n * default terminate-on-signal behavior is restored (otherwise attaching\n * a listener cancels the default and Ctrl-C would clean but not exit).\n */\nexport function registerColbertExitHandlers(): void {\n if (_registered) return\n _registered = true\n _exitHandler = () => sweepLiveChildren()\n _sigintHandler = () => {\n sweepLiveChildren()\n if (_sigintHandler) process.off(\"SIGINT\", _sigintHandler)\n process.kill(process.pid, \"SIGINT\")\n }\n _sigtermHandler = () => {\n sweepLiveChildren()\n if (_sigtermHandler) process.off(\"SIGTERM\", _sigtermHandler)\n process.kill(process.pid, \"SIGTERM\")\n }\n process.on(\"SIGINT\", _sigintHandler)\n process.on(\"SIGTERM\", _sigtermHandler)\n process.on(\"exit\", _exitHandler)\n}\n\n/** Test-only: unregister handlers + reset module state. */\nexport function __unregisterColbertExitHandlersForTests(): void {\n if (_sigintHandler) {\n process.off(\"SIGINT\", _sigintHandler)\n _sigintHandler = null\n }\n if (_sigtermHandler) {\n process.off(\"SIGTERM\", _sigtermHandler)\n _sigtermHandler = null\n }\n if (_exitHandler) {\n process.off(\"exit\", _exitHandler)\n _exitHandler = null\n }\n _registered = false\n _liveChildren.clear()\n}\n\n// ---------------------------------------------------------------------\n// Boot-time metadata reclassification sweep\n// ---------------------------------------------------------------------\n\n/**\n * True iff `pid` names a live process. `process.kill(pid, 0)` probes\n * existence without signalling; `EPERM` means the process exists but is\n * owned by another user (still alive). Exported so the per-query freshness\n * verdict can mirror the boot sweep's liveness check.\n */\nexport function isPidAlive(pid: number): boolean {\n if (!Number.isInteger(pid) || pid <= 0) return false\n try {\n process.kill(pid, 0)\n return true\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"EPERM\") return true\n return false\n }\n}\n\n/**\n * Boot-time sweep. Walks `.gh-router-meta/*.json`; any entry stuck in\n * `status:\"building\"` whose `buildPid` is DEAD is a crashed-build\n * escapee → reset to `status:\"failed\"` so the next search re-kicks a\n * build instead of routing to a never-finishing one.\n *\n * It NEVER kills anything: a live PID matching a stale `buildPid` from a\n * prior boot may be a recycled PID belonging to an unrelated process, so\n * the boot sweep only RECLASSIFIES metadata. The in-memory ledger (this\n * run's spawns) is the only thing the SIGINT/SIGTERM handler ever kills.\n *\n * Best-effort; never throws (wrapped by the caller in `ensurePaths`).\n */\nexport async function sweepStaleColbertMetaAtBoot(): Promise<void> {\n const metaDir = PATHS.COLBERT_META_DIR\n let names: Array<string>\n try {\n names = await fs.readdir(metaDir)\n } catch {\n return // no meta dir yet — nothing to sweep\n }\n for (const name of names) {\n if (!name.endsWith(\".json\")) continue\n const file = path.join(metaDir, name)\n let meta: Record<string, unknown>\n try {\n meta = JSON.parse(await fs.readFile(file, \"utf8\")) as Record<string, unknown>\n } catch {\n continue // corrupt — leave it; index-store re-derives on next access\n }\n if (meta.status !== \"building\") continue\n const buildPid = typeof meta.buildPid === \"number\" ? meta.buildPid : 0\n if (buildPid > 0 && isPidAlive(buildPid)) {\n // A live PID — could be ours (this run re-kicked) or a recycled\n // unrelated PID. Either way: never kill from the boot sweep. Leave\n // the entry; the runner's own ownership check governs.\n continue\n }\n // Dead build PID → reclassify to failed (atomic temp+rename). Stamp the\n // crash class so the per-query self-heal treats it as transient (re-kick)\n // rather than operator-actionable.\n meta.status = \"failed\"\n meta.failureClass = \"crashed\"\n const tmp = `${file}.${process.pid}.tmp`\n try {\n await fs.writeFile(tmp, JSON.stringify(meta, null, 2))\n await fs.rename(tmp, file)\n } catch {\n await fs.rm(tmp, { force: true }).catch(() => {})\n }\n }\n await sweepColbertStore()\n}\n\n/** An orphan stub younger than this may be a build that just started. */\nconst ORPHAN_GRACE_MS = 60 * 60 * 1000\n\n/**\n * Reclaim disk in the colgrep store, ordered so it cannot destroy good data.\n *\n * This runs AFTER the identity fix in this same release, which matters: the\n * scanner that decides \"unreachable\" is the one that was wrong. Under the old\n * comparison a perfectly healthy index looked unreachable, and a sweep written\n * against that scanner would have deleted it. Everything below therefore\n * leans on evidence that does not depend on our path matching at all.\n *\n * Three rules, in increasing order of caution:\n *\n * 1. ORPHAN STUB — no `project.json` AND an empty-or-absent `index/` AND\n * older than the grace window. All three required. A dir with a\n * `project.json` is real data and is never touched by this rule; a dir\n * with shards is never touched even without one. Deleted outright,\n * because there is provably nothing in it.\n *\n * 2. DEAD META — a sidecar whose `workspace` no longer exists on disk. Pure\n * bookkeeping, never index data. (48 such entries had accumulated on the\n * machine where this was diagnosed; nothing ever reaped them.)\n *\n * 3. QUARANTINE, NEVER DIRECT DELETE, for anything holding real bytes. A\n * dir with a `project.json` is left alone entirely, however unreachable\n * it looks. Reclaiming those would mean deleting real index data on our\n * own inference about what colgrep would use — and this incident is the\n * proof that such inference can be wrong. If it is ever added it must\n * rename first and delete only after a retention window, so the whole\n * period stays reversible.\n *\n * Skips any dir with a live lock owner or an in-flight init, and logs a\n * one-line count so the accumulation is observable rather than silent.\n */\nexport async function sweepColbertStore(): Promise<void> {\n const indicesDir = PATHS.COLBERT_INDICES_DIR\n let names: Array<string>\n try {\n names = await fs.readdir(indicesDir)\n } catch {\n return\n }\n\n const now = Date.now()\n let orphans = 0\n let deadMeta = 0\n\n for (const name of names) {\n if (name === \".gh-router-meta\") continue\n // Quarantined husks are owned by the corrupt-repair path, which deletes\n // them out of band. Never race it.\n if (name.includes(\".corrupt-\")) continue\n const dir = path.join(indicesDir, name)\n try {\n const st = await fs.stat(dir)\n if (!st.isDirectory()) continue\n // A live build claims its dir with a `.lock`; another proxy may own it.\n if (await exists(path.join(dir, \".lock\"))) continue\n // Real index data — leave it. Reclaiming this needs quarantine-first\n // semantics, not a boot-time `rm`.\n if (await exists(path.join(dir, \"project.json\"))) continue\n // Anything with shards is real work in progress, even mid-build.\n let indexEntries: Array<string> = []\n try {\n indexEntries = await fs.readdir(path.join(dir, \"index\"))\n } catch {\n /* absent index/ is the orphan shape */\n }\n if (indexEntries.length > 0) continue\n if (now - st.mtimeMs < ORPHAN_GRACE_MS) continue\n await fs.rm(dir, { recursive: true, force: true })\n orphans++\n } catch {\n // Vanished mid-sweep or unreadable — skip.\n }\n }\n\n // Dead sidecars: the workspace they describe is gone.\n try {\n const metaDir = PATHS.COLBERT_META_DIR\n for (const f of await fs.readdir(metaDir)) {\n if (!f.endsWith(\".json\")) continue\n const file = path.join(metaDir, f)\n try {\n const meta = JSON.parse(await fs.readFile(file, \"utf8\")) as {\n workspace?: string\n status?: string\n }\n const ws = meta.workspace\n if (typeof ws !== \"string\" || ws.length === 0) continue\n // Never reap a live build's bookkeeping.\n if (meta.status === \"building\") continue\n // Nor an entry this very sweep just reclassified. The reclassification\n // pass above rewrites `building` + dead-PID to `failed` so the runner\n // can self-heal; deleting it in the same pass would erase that state\n // before anything could act on it. Only reap entries that have been\n // settled for a while.\n const stMeta = await fs.stat(file).catch(() => null)\n if (stMeta && now - stMeta.mtimeMs < ORPHAN_GRACE_MS) continue\n if (await exists(ws)) continue\n await fs.rm(file, { force: true })\n deadMeta++\n } catch {\n // Corrupt/unreadable — leave it; index-store re-derives on next access.\n }\n }\n } catch {\n // No meta dir yet.\n }\n\n if (orphans > 0 || deadMeta > 0) {\n consola.debug(\n `colbert: store sweep reclaimed ${orphans} orphan index dir(s), ${deadMeta} dead metadata entr(ies)`,\n )\n }\n}\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await fs.stat(p)\n return true\n } catch {\n return false\n }\n}\n"],"mappings":";;;;;;;;;AAqCA,IAAI,gBAA+B;;;;;;;AAQnC,SAAgB,yBAAiC;CAC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AAQ;EACN,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"lifecycle-vjHAFCaY.js","names":[],"sources":["../src/lib/colbert/lifecycle.ts"],"sourcesContent":["/**\n * ColBERT sidecar lifecycle: in-memory PID ledger for the short-lived\n * `colgrep` children this proxy spawns, signal-handler tree-kill on\n * exit, and a boot-time metadata reclassification sweep.\n *\n * Because colgrep is CLI-per-invocation (no daemon), the lifecycle\n * problem is **process tracking + cancellation + boot/exit sweep**, NOT\n * keep-alive. Modeled on `worker-agent/lifecycle.ts` (PID ledger + boot\n * sweep + per-proxy-run instance UUID) and `exec.ts`'s tree-kill.\n *\n * Three cooperating layers (none sufficient alone):\n * 1. Per-call cleanup — the runner's `finally` force-kills the child\n * it spawned (handled in runner.ts).\n * 2. Session-end signal sweep (this file) — SIGINT/SIGTERM/exit kill\n * every still-tracked child of THIS run.\n * 3. Boot-time sweep (`sweepStaleColbertMetaAtBoot`) — reclassifies\n * `.gh-router-meta/*.json` entries whose `buildPid` is dead from\n * `building` → `failed`. It NEVER issues a kill to a PID from a\n * prior boot (a reused PID may belong to an unrelated process);\n * only the in-memory ledger (this run's spawns) is ever killed.\n */\n\nimport { spawn } from \"node:child_process\"\nimport { randomUUID } from \"node:crypto\"\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\nimport process from \"node:process\"\n\nimport consola from \"consola\"\n\nimport { killManagedTree } from \"../exec\"\nimport { PATHS } from \"../paths\"\n\n// ---------------------------------------------------------------------\n// Per-launch instance UUID (mirrors worker-agent/lifecycle.ts)\n// ---------------------------------------------------------------------\n\nlet _instanceUuid: string | null = null\n\n/**\n * Stable UUID4 generated once per proxy process. Written into the\n * sidecar metadata `ownerInstanceId` so the boot sweep can tell \"this\n * proxy's still-live build\" from \"a stranded `building` entry from a\n * prior proxy whose PID got recycled\" (Docker PID-1 across restarts).\n */\nexport function getColbertInstanceUuid(): string {\n if (_instanceUuid === null) _instanceUuid = randomUUID()\n return _instanceUuid\n}\n\n/** Test-only: reset the cached UUID. */\nexport function __resetColbertInstanceUuidForTests(): void {\n _instanceUuid = null\n}\n\n// ---------------------------------------------------------------------\n// In-memory PID ledger of THIS run's live colgrep children\n// ---------------------------------------------------------------------\n\ntype TrackedChild = ReturnType<typeof spawn>\n\nconst _liveChildren = new Set<TrackedChild>()\n\n/**\n * Register a freshly-spawned colgrep child so the exit sweep can reap\n * it. The runner also removes it on natural close via `untrackChild`.\n */\nexport function trackChild(child: TrackedChild): void {\n _liveChildren.add(child)\n child.once(\"close\", () => _liveChildren.delete(child))\n child.once(\"error\", () => _liveChildren.delete(child))\n}\n\n/** Remove a child from the ledger (e.g. after a clean per-call kill). */\nexport function untrackChild(child: TrackedChild): void {\n _liveChildren.delete(child)\n}\n\n/** Count of live tracked children (test/diagnostic). */\nexport function liveChildCount(): number {\n return _liveChildren.size\n}\n\n/**\n * Synchronous best-effort tree-kill of every tracked child. Called from\n * the signal/exit handlers. After killing, the set is cleared so a\n * second call is a no-op.\n */\nexport function sweepLiveChildren(): void {\n const isWin = process.platform === \"win32\"\n for (const child of _liveChildren) {\n try {\n killManagedTree(child, isWin)\n } catch {\n // already gone\n }\n }\n _liveChildren.clear()\n}\n\n// ---------------------------------------------------------------------\n// Signal handlers (mirror worker-agent/lifecycle.ts re-raise pattern)\n// ---------------------------------------------------------------------\n\nlet _registered = false\nlet _exitHandler: (() => void) | null = null\nlet _sigintHandler: (() => void) | null = null\nlet _sigtermHandler: (() => void) | null = null\n\n/**\n * Wire SIGINT/SIGTERM/exit handlers that tree-kill every tracked\n * colgrep child. Idempotent — subsequent calls are a no-op (we never\n * leak listeners). The signal handlers re-raise after sweeping so Node's\n * default terminate-on-signal behavior is restored (otherwise attaching\n * a listener cancels the default and Ctrl-C would clean but not exit).\n */\nexport function registerColbertExitHandlers(): void {\n if (_registered) return\n _registered = true\n _exitHandler = () => sweepLiveChildren()\n _sigintHandler = () => {\n sweepLiveChildren()\n if (_sigintHandler) process.off(\"SIGINT\", _sigintHandler)\n process.kill(process.pid, \"SIGINT\")\n }\n _sigtermHandler = () => {\n sweepLiveChildren()\n if (_sigtermHandler) process.off(\"SIGTERM\", _sigtermHandler)\n process.kill(process.pid, \"SIGTERM\")\n }\n process.on(\"SIGINT\", _sigintHandler)\n process.on(\"SIGTERM\", _sigtermHandler)\n process.on(\"exit\", _exitHandler)\n}\n\n/** Test-only: unregister handlers + reset module state. */\nexport function __unregisterColbertExitHandlersForTests(): void {\n if (_sigintHandler) {\n process.off(\"SIGINT\", _sigintHandler)\n _sigintHandler = null\n }\n if (_sigtermHandler) {\n process.off(\"SIGTERM\", _sigtermHandler)\n _sigtermHandler = null\n }\n if (_exitHandler) {\n process.off(\"exit\", _exitHandler)\n _exitHandler = null\n }\n _registered = false\n _liveChildren.clear()\n}\n\n// ---------------------------------------------------------------------\n// Boot-time metadata reclassification sweep\n// ---------------------------------------------------------------------\n\n/**\n * True iff `pid` names a live process. `process.kill(pid, 0)` probes\n * existence without signalling; `EPERM` means the process exists but is\n * owned by another user (still alive). Exported so the per-query freshness\n * verdict can mirror the boot sweep's liveness check.\n */\nexport function isPidAlive(pid: number): boolean {\n if (!Number.isInteger(pid) || pid <= 0) return false\n try {\n process.kill(pid, 0)\n return true\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"EPERM\") return true\n return false\n }\n}\n\n/**\n * Boot-time sweep. Walks `.gh-router-meta/*.json`; any entry stuck in\n * `status:\"building\"` whose `buildPid` is DEAD is a crashed-build\n * escapee → reset to `status:\"failed\"` so the next search re-kicks a\n * build instead of routing to a never-finishing one.\n *\n * It NEVER kills anything: a live PID matching a stale `buildPid` from a\n * prior boot may be a recycled PID belonging to an unrelated process, so\n * the boot sweep only RECLASSIFIES metadata. The in-memory ledger (this\n * run's spawns) is the only thing the SIGINT/SIGTERM handler ever kills.\n *\n * Best-effort; never throws (wrapped by the caller in `ensurePaths`).\n */\nexport async function sweepStaleColbertMetaAtBoot(): Promise<void> {\n const metaDir = PATHS.COLBERT_META_DIR\n let names: Array<string>\n try {\n names = await fs.readdir(metaDir)\n } catch {\n return // no meta dir yet — nothing to sweep\n }\n for (const name of names) {\n if (!name.endsWith(\".json\")) continue\n const file = path.join(metaDir, name)\n let meta: Record<string, unknown>\n try {\n meta = JSON.parse(await fs.readFile(file, \"utf8\")) as Record<string, unknown>\n } catch {\n continue // corrupt — leave it; index-store re-derives on next access\n }\n if (meta.status !== \"building\") continue\n const buildPid = typeof meta.buildPid === \"number\" ? meta.buildPid : 0\n if (buildPid > 0 && isPidAlive(buildPid)) {\n // A live PID — could be ours (this run re-kicked) or a recycled\n // unrelated PID. Either way: never kill from the boot sweep. Leave\n // the entry; the runner's own ownership check governs.\n continue\n }\n // Dead build PID → reclassify to failed (atomic temp+rename). Stamp the\n // crash class so the per-query self-heal treats it as transient (re-kick)\n // rather than operator-actionable.\n meta.status = \"failed\"\n meta.failureClass = \"crashed\"\n const tmp = `${file}.${process.pid}.tmp`\n try {\n await fs.writeFile(tmp, JSON.stringify(meta, null, 2))\n await fs.rename(tmp, file)\n } catch {\n await fs.rm(tmp, { force: true }).catch(() => {})\n }\n }\n await sweepColbertStore()\n}\n\n/** An orphan stub younger than this may be a build that just started. */\nconst ORPHAN_GRACE_MS = 60 * 60 * 1000\n\n/**\n * Reclaim disk in the colgrep store, ordered so it cannot destroy good data.\n *\n * This runs AFTER the identity fix in this same release, which matters: the\n * scanner that decides \"unreachable\" is the one that was wrong. Under the old\n * comparison a perfectly healthy index looked unreachable, and a sweep written\n * against that scanner would have deleted it. Everything below therefore\n * leans on evidence that does not depend on our path matching at all.\n *\n * Three rules, in increasing order of caution:\n *\n * 1. ORPHAN STUB — no `project.json` AND an empty-or-absent `index/` AND\n * older than the grace window. All three required. A dir with a\n * `project.json` is real data and is never touched by this rule; a dir\n * with shards is never touched even without one. Deleted outright,\n * because there is provably nothing in it.\n *\n * 2. DEAD META — a sidecar whose `workspace` no longer exists on disk. Pure\n * bookkeeping, never index data. (48 such entries had accumulated on the\n * machine where this was diagnosed; nothing ever reaped them.)\n *\n * 3. QUARANTINE, NEVER DIRECT DELETE, for anything holding real bytes. A\n * dir with a `project.json` is left alone entirely, however unreachable\n * it looks. Reclaiming those would mean deleting real index data on our\n * own inference about what colgrep would use — and this incident is the\n * proof that such inference can be wrong. If it is ever added it must\n * rename first and delete only after a retention window, so the whole\n * period stays reversible.\n *\n * Skips any dir with a live lock owner or an in-flight init, and logs a\n * one-line count so the accumulation is observable rather than silent.\n */\nexport async function sweepColbertStore(): Promise<void> {\n const indicesDir = PATHS.COLBERT_INDICES_DIR\n let names: Array<string>\n try {\n names = await fs.readdir(indicesDir)\n } catch {\n return\n }\n\n const now = Date.now()\n let orphans = 0\n let deadMeta = 0\n\n for (const name of names) {\n if (name === \".gh-router-meta\") continue\n // Quarantined husks are owned by the corrupt-repair path, which deletes\n // them out of band. Never race it.\n if (name.includes(\".corrupt-\")) continue\n const dir = path.join(indicesDir, name)\n try {\n const st = await fs.stat(dir)\n if (!st.isDirectory()) continue\n // A live build claims its dir with a `.lock`; another proxy may own it.\n if (await exists(path.join(dir, \".lock\"))) continue\n // Real index data — leave it. Reclaiming this needs quarantine-first\n // semantics, not a boot-time `rm`.\n if (await exists(path.join(dir, \"project.json\"))) continue\n // Anything with shards is real work in progress, even mid-build.\n let indexEntries: Array<string> = []\n try {\n indexEntries = await fs.readdir(path.join(dir, \"index\"))\n } catch {\n /* absent index/ is the orphan shape */\n }\n if (indexEntries.length > 0) continue\n if (now - st.mtimeMs < ORPHAN_GRACE_MS) continue\n await fs.rm(dir, { recursive: true, force: true })\n orphans++\n } catch {\n // Vanished mid-sweep or unreadable — skip.\n }\n }\n\n // Dead sidecars: the workspace they describe is gone.\n try {\n const metaDir = PATHS.COLBERT_META_DIR\n for (const f of await fs.readdir(metaDir)) {\n if (!f.endsWith(\".json\")) continue\n const file = path.join(metaDir, f)\n try {\n const meta = JSON.parse(await fs.readFile(file, \"utf8\")) as {\n workspace?: string\n status?: string\n }\n const ws = meta.workspace\n if (typeof ws !== \"string\" || ws.length === 0) continue\n // Never reap a live build's bookkeeping.\n if (meta.status === \"building\") continue\n // Nor an entry this very sweep just reclassified. The reclassification\n // pass above rewrites `building` + dead-PID to `failed` so the runner\n // can self-heal; deleting it in the same pass would erase that state\n // before anything could act on it. Only reap entries that have been\n // settled for a while.\n const stMeta = await fs.stat(file).catch(() => null)\n if (stMeta && now - stMeta.mtimeMs < ORPHAN_GRACE_MS) continue\n if (await exists(ws)) continue\n await fs.rm(file, { force: true })\n deadMeta++\n } catch {\n // Corrupt/unreadable — leave it; index-store re-derives on next access.\n }\n }\n } catch {\n // No meta dir yet.\n }\n\n if (orphans > 0 || deadMeta > 0) {\n consola.debug(\n `colbert: store sweep reclaimed ${orphans} orphan index dir(s), ${deadMeta} dead metadata entr(ies)`,\n )\n }\n}\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await fs.stat(p)\n return true\n } catch {\n return false\n }\n}\n"],"mappings":";;;;;;;;AAqCA,IAAI,gBAA+B;;;;;;;AAQnC,SAAgB,yBAAiC;CAC/C,IAAI,kBAAkB,MAAM,gBAAgB,WAAW;CACvD,OAAO;AACT;AAaA,MAAM,gCAAgB,IAAI,IAAkB;;;;;AAM5C,SAAgB,WAAW,OAA2B;CACpD,cAAc,IAAI,KAAK;CACvB,MAAM,KAAK,eAAe,cAAc,OAAO,KAAK,CAAC;CACrD,MAAM,KAAK,eAAe,cAAc,OAAO,KAAK,CAAC;AACvD;;AAGA,SAAgB,aAAa,OAA2B;CACtD,cAAc,OAAO,KAAK;AAC5B;;;;;;AAYA,SAAgB,oBAA0B;CACxC,MAAM,QAAQ,QAAQ,aAAa;CACnC,KAAK,MAAM,SAAS,eAClB,IAAI;EACF,gBAAgB,OAAO,KAAK;CAC9B,QAAQ,CAER;CAEF,cAAc,MAAM;AACtB;AAMA,IAAI,cAAc;AAClB,IAAI,eAAoC;AACxC,IAAI,iBAAsC;AAC1C,IAAI,kBAAuC;;;;;;;;AAS3C,SAAgB,8BAAoC;CAClD,IAAI,aA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AAO,KAAK,KAAK,SAAS,CAAC;GACjC,IAAI;IACF,MAAM,OAAO,KAAK,MAAM,MAAM,GAAG,SAAS,MAAM,MAAM,CAAC;IAIvD,MAAM,KAAK,KAAK;IAChB,IAAI,OAAO,OAAO,YAAY,GAAG,WAAW,GAAG;IAE/C,IAAI,KAAK,WAAW,YAAY;IAMhC,MAAM,SAAS,MAAM,GAAG,KAAK,IAAI,CAAC,CAAC,YAAY,IAAI;IACnD,IAAI,UAAU,MAAM,OAAO,UAAU,iBAAiB;IACtD,IAAI,MAAM,OAAO,EAAE,GAAG;IACtB,MAAM,GAAG,GAAG,MAAM,EAAE,OAAO,KAAK,CAAC;IACjC;GACF,QAAQ,CAER;EACF;CACF,QAAQ,CAER;CAEA,IAAI,UAAU,KAAK,WAAW,GAC5B,QAAQ,MACN,kCAAkC,QAAQ,wBAAwB,SAAS,yBAC7E;AAEJ;AAEA,eAAe,OAAO,GAA6B;CACjD,IAAI;EACF,MAAM,GAAG,KAAK,CAAC;EACf,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF"}
|
package/dist/main.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { t as getPackageVersion } from "./version-
|
|
2
|
+
import { t as getPackageVersion } from "./version-CTqwKr26.js";
|
|
3
3
|
import { defineCommand, runMain, showUsage } from "citty";
|
|
4
4
|
import consola from "consola";
|
|
5
|
-
|
|
5
|
+
// src/main.ts
|
|
6
6
|
process.on("unhandledRejection", (error) => {
|
|
7
7
|
consola.error("Unhandled rejection:", error);
|
|
8
8
|
});
|
|
@@ -46,30 +46,30 @@ const main = defineCommand({
|
|
|
46
46
|
description: "A reverse proxy that exposes GitHub Copilot as OpenAI and Anthropic compatible API endpoints."
|
|
47
47
|
},
|
|
48
48
|
subCommands: {
|
|
49
|
-
auth: () => import("./auth-
|
|
50
|
-
start: () => import("./start-
|
|
51
|
-
claude: () => import("./claude-
|
|
52
|
-
codex: () => import("./codex-
|
|
53
|
-
pi: () => import("./pi-
|
|
54
|
-
workiq: () => import("./workiq-
|
|
55
|
-
serve: () => import("./serve-
|
|
56
|
-
models: () => import("./models-
|
|
57
|
-
"check-usage": () => import("./check-usage-
|
|
58
|
-
index: () => import("./index-cmd-
|
|
59
|
-
debug: () => import("./debug-
|
|
60
|
-
"internal-stop-hook": () => import("./internal-stop-hook-
|
|
61
|
-
"internal-prompt-submit": () => import("./internal-prompt-submit-
|
|
62
|
-
"internal-stop-review": () => import("./internal-stop-review-
|
|
63
|
-
"internal-plan-review": () => import("./internal-plan-review-
|
|
64
|
-
"internal-rebrief": () => import("./internal-rebrief-
|
|
65
|
-
"internal-session-bind": () => import("./internal-session-bind-
|
|
66
|
-
"internal-workspace-header": () => import("./internal-workspace-header-
|
|
67
|
-
"internal-artifact-open": () => import("./internal-artifact-open-
|
|
68
|
-
"internal-first-mate-guard": () => import("./internal-first-mate-guard-
|
|
69
|
-
"internal-worker-guard": () => import("./internal-worker-guard-
|
|
70
|
-
"internal-fast-dispatch-guard": () => import("./internal-fast-dispatch-guard-
|
|
71
|
-
"internal-max-dispatch-guard": () => import("./internal-max-dispatch-guard-
|
|
72
|
-
"internal-aic-status": () => import("./internal-aic-status-
|
|
49
|
+
auth: () => import("./auth-BZHpTtfF.js").then((m) => m.auth),
|
|
50
|
+
start: () => import("./start-C0gngUPK.js").then((m) => m.start),
|
|
51
|
+
claude: () => import("./claude-DSXrdz0v.js").then((m) => m.claude),
|
|
52
|
+
codex: () => import("./codex-DGMUk65v.js").then((m) => m.codex),
|
|
53
|
+
pi: () => import("./pi-DI2QtaiZ.js").then((m) => m.pi),
|
|
54
|
+
workiq: () => import("./workiq-CQauEAMc.js").then((m) => m.workiq),
|
|
55
|
+
serve: () => import("./serve-DRASJ-ZO.js").then((m) => m.serve),
|
|
56
|
+
models: () => import("./models-B6nH1sS6.js").then((m) => m.models),
|
|
57
|
+
"check-usage": () => import("./check-usage-BlIWDuV2.js").then((m) => m.checkUsage),
|
|
58
|
+
index: () => import("./index-cmd-BPXhTfGQ.js").then((m) => m.indexCmd),
|
|
59
|
+
debug: () => import("./debug-1HUHCWFl.js").then((m) => m.debug),
|
|
60
|
+
"internal-stop-hook": () => import("./internal-stop-hook-VQuOYpUC.js").then((m) => m.internalStopHook),
|
|
61
|
+
"internal-prompt-submit": () => import("./internal-prompt-submit-DKzCckz-.js").then((m) => m.internalPromptSubmit),
|
|
62
|
+
"internal-stop-review": () => import("./internal-stop-review-BWp-4XWW.js").then((m) => m.internalStopReview),
|
|
63
|
+
"internal-plan-review": () => import("./internal-plan-review-BfHLeszV.js").then((m) => m.internalPlanReview),
|
|
64
|
+
"internal-rebrief": () => import("./internal-rebrief-aEvxp7jw.js").then((m) => m.internalRebrief),
|
|
65
|
+
"internal-session-bind": () => import("./internal-session-bind-pN1V11Mn.js").then((m) => m.internalSessionBind),
|
|
66
|
+
"internal-workspace-header": () => import("./internal-workspace-header-B4TXFBLU.js").then((m) => m.internalWorkspaceHeader),
|
|
67
|
+
"internal-artifact-open": () => import("./internal-artifact-open-DbHjipxU.js").then((m) => m.internalArtifactOpen),
|
|
68
|
+
"internal-first-mate-guard": () => import("./internal-first-mate-guard-BxPDUsV3.js").then((m) => m.internalFirstMateGuard),
|
|
69
|
+
"internal-worker-guard": () => import("./internal-worker-guard-C9OZPgzu.js").then((m) => m.internalWorkerGuard),
|
|
70
|
+
"internal-fast-dispatch-guard": () => import("./internal-fast-dispatch-guard-DMzqs-r8.js").then((m) => m.internalFastDispatchGuard),
|
|
71
|
+
"internal-max-dispatch-guard": () => import("./internal-max-dispatch-guard-fhBX_w49.js").then((m) => m.internalMaxDispatchGuard),
|
|
72
|
+
"internal-aic-status": () => import("./internal-aic-status-FQB1DQzX.js").then((m) => m.internalAicStatus)
|
|
73
73
|
}
|
|
74
74
|
});
|
|
75
75
|
/**
|
|
@@ -115,7 +115,6 @@ if (argv.some((arg) => HELP_FLAGS.has(arg))) {
|
|
|
115
115
|
await showUsage(cmd, parent);
|
|
116
116
|
process.exitCode = 0;
|
|
117
117
|
} else await runMain(main);
|
|
118
|
-
//#endregion
|
|
119
118
|
export {};
|
|
120
119
|
|
|
121
120
|
//# sourceMappingURL=main.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as state } from "./state-
|
|
2
|
-
|
|
1
|
+
import { t as state } from "./state-CCGDJ43X.js";
|
|
2
|
+
// src/lib/model-suffix.ts
|
|
3
3
|
/** Strip every trailing `[1m]` marker, case-insensitively. */
|
|
4
4
|
function stripTrailingOneMSuffix(id) {
|
|
5
5
|
const match = id.match(/(?:\[1m\])+$/i);
|
|
@@ -17,8 +17,7 @@ function normalizeTrailingOneMSuffix(id) {
|
|
|
17
17
|
const { base, hadSuffix } = stripTrailingOneMSuffix(id);
|
|
18
18
|
return hadSuffix ? `${base}[1m]` : base;
|
|
19
19
|
}
|
|
20
|
-
|
|
21
|
-
//#region src/lib/fast-endpoint.ts
|
|
20
|
+
// src/lib/fast-endpoint.ts
|
|
22
21
|
const ENDPOINTS = {
|
|
23
22
|
chat: /* @__PURE__ */ new Set(["/chat/completions", "/v1/chat/completions"]),
|
|
24
23
|
responses: /* @__PURE__ */ new Set(["/responses", "/v1/responses"]),
|
|
@@ -58,8 +57,7 @@ function fastEndpointForCatalogId(modelId, catalog) {
|
|
|
58
57
|
const found = catalog?.find((model) => model.id === modelId);
|
|
59
58
|
return found ? fastEndpointForModel(found) : void 0;
|
|
60
59
|
}
|
|
61
|
-
|
|
62
|
-
//#region src/lib/max-profile-prompts.ts
|
|
60
|
+
// src/lib/max-profile-prompts.ts
|
|
63
61
|
const MAX_PARALLELISM_RULE = "When two or more delegated workstreams are independent and non-overlapping, issue them together; sequence them when one needs another's result or their side effects can conflict.";
|
|
64
62
|
const MAX_NATIVE_PROMPT_SPECS = {
|
|
65
63
|
Explore: {
|
|
@@ -350,7 +348,6 @@ function maxCodexReviewerModel() {
|
|
|
350
348
|
const model = catalogModel(MAX_PROFILE_MODELS.codex);
|
|
351
349
|
return model && hasToolCalls(model) && supportsEffort(model, "xhigh") && advertisesEndpoint(model, "responses") && hasUsableLimits(model) && (model.capabilities?.limits?.max_prompt_tokens ?? 0) >= 2e5 ? model.id : void 0;
|
|
352
350
|
}
|
|
353
|
-
//#endregion
|
|
354
351
|
export { normalizeTrailingOneMSuffix as A, MAX_PARALLELISM_RULE as C, maxPeerInstructions as D, maxPeerDescription as E, fastEndpointForCatalogId as O, MAX_COORDINATOR_PROMPT as S, maxNativePrompt as T, maxReviewerModel as _, MAX_PROFILE_NATIVE_AGENT_NAMES as a, MAX_ADVISOR_SYSTEM_PROMPT as b, formatMaxPrerequisiteFailure as c, maxAdvisorPinIsValid as d, maxCodexReviewerModel as f, maxProReplacementModel as g, maxOpusModel as h, MAX_PROFILE_MODELS as i, stripTrailingOneMSuffix as j, fastEndpointForModel as k, maxAdvisorEffortForModel as l, maxGrokModel as m, MAX_PROFILE_ALLOWED_LEAD_MODEL_IDS as n, MAX_PROFILE_NATIVE_EFFORTS as o, maxGeminiModel as p, MAX_PROFILE_LEAD_MODEL as r, MAX_PROFILE_NATIVE_MODELS as s, MAX_PROFILE_ADVISOR_INSTRUCTIONS as t, maxAdvisorModelFromPin as u, maxSonnetModel as v, maxNativeDescription as w, MAX_COORDINATOR_DESCRIPTION as x, validateMaxProfilePrerequisites as y };
|
|
355
352
|
|
|
356
|
-
//# sourceMappingURL=max-profile-contract-
|
|
353
|
+
//# sourceMappingURL=max-profile-contract-DLLTsSs2.js.map
|