github-router 0.3.330 → 0.3.331

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/{attribution-settings-DepziZU8.js → attribution-settings-7dFpObGh.js} +4 -4
  2. package/dist/{attribution-settings-DepziZU8.js.map → attribution-settings-7dFpObGh.js.map} +1 -1
  3. package/dist/browser-ext/manifest.json +1 -1
  4. package/dist/{claude-Dw4V8o8l.js → claude-C3-yBGzw.js} +7 -7
  5. package/dist/{claude-Dw4V8o8l.js.map → claude-C3-yBGzw.js.map} +1 -1
  6. package/dist/{codex-CXOpv4WP.js → codex-C3hcVSOm.js} +5 -5
  7. package/dist/{codex-CXOpv4WP.js.map → codex-C3hcVSOm.js.map} +1 -1
  8. package/dist/engine-CPdWX70n.js +2 -0
  9. package/dist/{gate-discovery-BGqS7R2g.js → gate-discovery-BUhtwkyE.js} +2 -2
  10. package/dist/{gate-discovery-BGqS7R2g.js.map → gate-discovery-BUhtwkyE.js.map} +1 -1
  11. package/dist/index-cmd-k3oWl0n4.js +330 -0
  12. package/dist/index-cmd-k3oWl0n4.js.map +1 -0
  13. package/dist/{internal-stop-hook-CH9SKjZ9.js → internal-stop-hook-DBrlosd0.js} +2 -2
  14. package/dist/{internal-stop-hook-CH9SKjZ9.js.map → internal-stop-hook-DBrlosd0.js.map} +1 -1
  15. package/dist/main.js +6 -6
  16. package/dist/{peer-mcp-personas-CnYMTizo.js → peer-mcp-personas-Dztywua2.js} +2 -2
  17. package/dist/{peer-mcp-personas-CnYMTizo.js.map → peer-mcp-personas-Dztywua2.js.map} +1 -1
  18. package/dist/{provision-D5KOOw6n.js → provision-CjBt5wEK.js} +3 -3
  19. package/dist/{provision-D5KOOw6n.js.map → provision-CjBt5wEK.js.map} +1 -1
  20. package/dist/{serve-fJWhiivo.js → serve-C3LCkM-o.js} +6 -6
  21. package/dist/{serve-fJWhiivo.js.map → serve-C3LCkM-o.js.map} +1 -1
  22. package/dist/{server-setup-DHMPOXKT.js → server-setup-DrSUlFZ_.js} +4 -4
  23. package/dist/{server-setup-DHMPOXKT.js.map → server-setup-DrSUlFZ_.js.map} +1 -1
  24. package/dist/{service-backend-DYEPoszR.js → service-backend-ByT0gUc8.js} +405 -19
  25. package/dist/{service-backend-DYEPoszR.js.map → service-backend-ByT0gUc8.js.map} +1 -1
  26. package/dist/{start-Gs4jAwUR.js → start-CY1nnbB4.js} +4 -4
  27. package/dist/{start-Gs4jAwUR.js.map → start-CY1nnbB4.js.map} +1 -1
  28. package/package.json +1 -1
  29. package/dist/engine-CYba_zi7.js +0 -2
  30. package/dist/index-cmd-DUjQs9zw.js +0 -182
  31. package/dist/index-cmd-DUjQs9zw.js.map +0 -1
@@ -0,0 +1,330 @@
1
+ import { C as provisionColbert, a as semanticBackend, b as validateIndexIntegrity, c as serviceFreshness, g as freshnessVerdict, h as completedIndexOnDisk, i as selectServerVariant, k as validateWorkspace, l as stopServiceServer, m as colbertProjectDir, n as populateWorkspace, p as waitForInit, s as serviceBackendProvisionable, t as ensureServerForeground, u as kickBackgroundInit, v as indexDirSignature, w as provisionNextPlaidServer, y as readColbertMeta } from "./service-backend-ByT0gUc8.js";
2
+ import { t as PATHS } from "./paths-P5ajjpzU.js";
3
+ import { i as parseBoolEnv } from "./exec-COUT4QsS.js";
4
+ import { r as registerColbertExitHandlers } from "./lifecycle-D8vQXfeC.js";
5
+ import { defineCommand } from "citty";
6
+ import consola from "consola";
7
+ import * as os$1 from "node:os";
8
+ import process from "node:process";
9
+ //#region src/index-cmd.ts
10
+ /**
11
+ * `github-router index` — build the semantic code-search index in the
12
+ * foreground, without starting the proxy (`start`/`claude`/`codex`).
13
+ *
14
+ * Phase 4a: drives the CURRENT colbert backend (foreground `init` with
15
+ * progress). Phase 5: `auto` (default) prefers the persistent service
16
+ * backend — foreground all-core encode with CUDA when a GPU is visible —
17
+ * with TRUE DELTA indexing (only changed files are re-embedded); falls
18
+ * back to colbert when the service is not actionable. `--backend` forces
19
+ * `service` or `colbert`. The explicit invocation IS the opt-in — `--search` is not
20
+ * required — but `GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1` still hard-disables
21
+ * (building an index that can never be served is pointless).
22
+ *
23
+ * Exit codes: 0 = fresh or successfully built; 1 = provision/build
24
+ * failure; 2 = usage error (bad workspace, hard-disabled).
25
+ */
26
+ const POLL_MS = 1e4;
27
+ function cpuCount() {
28
+ try {
29
+ const n = os$1.cpus().length;
30
+ return Number.isSafeInteger(n) && n > 0 ? n : 4;
31
+ } catch {
32
+ return 4;
33
+ }
34
+ }
35
+ async function collectStatus(workspace) {
36
+ const { verdict, head, dirty } = await freshnessVerdict(workspace);
37
+ const status = {
38
+ workspace,
39
+ verdict,
40
+ indexOnDisk: await completedIndexOnDisk(workspace)
41
+ };
42
+ const projectDir = await colbertProjectDir(workspace);
43
+ if (projectDir) {
44
+ const integrity = validateIndexIntegrity(`${projectDir}/index`);
45
+ if (integrity.verdict === "coherent") {
46
+ status.shards = integrity.shardCount;
47
+ status.embeddings = integrity.embeddingCount;
48
+ } else status.integrity = integrity.verdict;
49
+ }
50
+ const meta = await readColbertMeta(workspace);
51
+ if (meta?.lastIndexedAt) status.lastIndexedAt = meta.lastIndexedAt;
52
+ if (head !== void 0) status.head = head.slice(0, 12);
53
+ if (dirty !== void 0) status.dirty = dirty;
54
+ return status;
55
+ }
56
+ function printStatus(s) {
57
+ consola.info(`workspace: ${s.workspace}`);
58
+ consola.info(`verdict: ${s.verdict}`);
59
+ consola.info(`index: ${s.indexOnDisk ? "present" : "absent"}`);
60
+ if (s.shards !== void 0) consola.info(`shards: ${s.shards} (${s.embeddings ?? 0} embeddings)`);
61
+ if (s.integrity && s.integrity !== "not-built") consola.info(`integrity: ${s.integrity}`);
62
+ if (s.head !== void 0) consola.info(`head: ${s.head}${s.dirty ? " (dirty)" : ""}`);
63
+ if (s.lastIndexedAt) consola.info(`indexed: ${s.lastIndexedAt}`);
64
+ }
65
+ async function collectServiceStatus(workspace) {
66
+ const { verdict, meta, head, dirty } = await serviceFreshness(workspace);
67
+ const status = {
68
+ workspace,
69
+ backend: "service",
70
+ verdict
71
+ };
72
+ if (meta?.indexedAt) status.indexedAt = meta.indexedAt;
73
+ if (meta?.docCount !== void 0) status.docCount = meta.docCount;
74
+ if (head !== void 0) status.head = head.slice(0, 12);
75
+ if (dirty !== void 0) status.dirty = dirty;
76
+ return status;
77
+ }
78
+ function printServiceStatus(s) {
79
+ consola.info(`workspace: ${s.workspace}`);
80
+ consola.info(`backend: ${s.backend}`);
81
+ consola.info(`verdict: ${s.verdict}`);
82
+ if (s.docCount !== void 0) consola.info(`documents: ${s.docCount}`);
83
+ if (s.head !== void 0) consola.info(`head: ${s.head}${s.dirty ? " (dirty)" : ""}`);
84
+ if (s.indexedAt) consola.info(`indexed: ${s.indexedAt}`);
85
+ }
86
+ function resolveIndexBackend(requested) {
87
+ const raw = typeof requested === "string" && requested.length > 0 ? requested.toLowerCase() : "auto";
88
+ if (raw !== "auto" && raw !== "service" && raw !== "colgrep") return { error: `index: --backend must be auto, service, or colgrep (got ${String(requested)})` };
89
+ if (raw === "service" || raw === "auto" && semanticBackend() === "service") return {
90
+ backend: "service",
91
+ explicit: true
92
+ };
93
+ if (raw === "colgrep") return {
94
+ backend: "colgrep",
95
+ explicit: false
96
+ };
97
+ return serviceBackendProvisionable() ? {
98
+ backend: "service",
99
+ explicit: false
100
+ } : {
101
+ backend: "colgrep",
102
+ explicit: false
103
+ };
104
+ }
105
+ function sleep(ms) {
106
+ return new Promise((resolve) => {
107
+ setTimeout(resolve, ms).unref?.();
108
+ });
109
+ }
110
+ const indexCmd = defineCommand({
111
+ meta: {
112
+ name: "index",
113
+ description: "Build the semantic code-search index for a workspace in the foreground (no proxy needed)"
114
+ },
115
+ args: {
116
+ workspace: {
117
+ alias: "w",
118
+ type: "string",
119
+ description: "Absolute path to the repo to index (default: cwd)"
120
+ },
121
+ status: {
122
+ type: "boolean",
123
+ default: false,
124
+ description: "Print index status and exit (no build)"
125
+ },
126
+ timeout: {
127
+ type: "string",
128
+ description: "Max minutes to wait for the build (0 = none, default 0)"
129
+ },
130
+ backend: {
131
+ type: "string",
132
+ description: "Index backend: auto (service with CUDA/CPU autodetect, colgrep fallback), service, or colgrep (default auto)"
133
+ },
134
+ full: {
135
+ type: "boolean",
136
+ default: false,
137
+ description: "Force a full rebuild, ignoring content hashes (service backend)"
138
+ },
139
+ dryRun: {
140
+ type: "boolean",
141
+ default: false,
142
+ description: "Classify changed files without building (service backend)"
143
+ }
144
+ },
145
+ async run({ args }) {
146
+ const rawWorkspace = typeof args.workspace === "string" && args.workspace.length > 0 ? args.workspace : process.cwd();
147
+ const ws = validateWorkspace(rawWorkspace);
148
+ if (!ws.ok || !ws.canonical) {
149
+ consola.error(`index: ${ws.error ?? "workspace validation failed"}`);
150
+ process.exitCode = 2;
151
+ return;
152
+ }
153
+ const workspace = ws.canonical;
154
+ if (parseBoolEnv(process.env.GH_ROUTER_DISABLE_SEMANTIC_SEARCH) === true) {
155
+ consola.error("index: semantic search is hard-disabled (GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1); nothing to build");
156
+ process.exitCode = 2;
157
+ return;
158
+ }
159
+ const backendSelection = resolveIndexBackend(args.backend);
160
+ if ("error" in backendSelection) {
161
+ consola.error(backendSelection.error);
162
+ process.exitCode = 2;
163
+ return;
164
+ }
165
+ const { backend, explicit: backendExplicit } = backendSelection;
166
+ if (args.status === true) {
167
+ if (backend === "service") printServiceStatus(await collectServiceStatus(workspace));
168
+ else printStatus(await collectStatus(workspace));
169
+ return;
170
+ }
171
+ const timeoutMin = args.timeout === void 0 ? 0 : Number(args.timeout);
172
+ if (args.timeout !== void 0 && !(Number.isFinite(timeoutMin) && timeoutMin >= 0)) {
173
+ consola.error("index: --timeout must be a non-negative number of minutes");
174
+ process.exitCode = 2;
175
+ return;
176
+ }
177
+ const deadlineMs = timeoutMin > 0 ? Date.now() + timeoutMin * 6e4 : Number.POSITIVE_INFINITY;
178
+ if (process.env.GH_ROUTER_COLBERT_PARALLEL === void 0) {
179
+ process.env.GH_ROUTER_COLBERT_PARALLEL = String(cpuCount());
180
+ consola.debug(`index: parallelism defaulted to ${cpuCount()} sessions (override with GH_ROUTER_COLBERT_PARALLEL)`);
181
+ }
182
+ registerColbertExitHandlers();
183
+ consola.info(`Provisioning semantic-search artifacts into ${PATHS.COLBERT_INDICES_DIR}…`);
184
+ try {
185
+ const result = await provisionColbert();
186
+ if (result.status !== "ready") {
187
+ consola.error(`index: provision ${result.status}${result.reason ? ` (${result.reason})` : ""}`);
188
+ process.exitCode = 1;
189
+ return;
190
+ }
191
+ } catch (err) {
192
+ consola.error("index: provision threw:", err);
193
+ process.exitCode = 1;
194
+ return;
195
+ }
196
+ if (backend === "service") {
197
+ let variant;
198
+ try {
199
+ variant = await selectServerVariant();
200
+ const server = await provisionNextPlaidServer(variant);
201
+ if (server.path) consola.info(`index: service backend ready (${variant}: ${server.path})`);
202
+ else if (backendExplicit) {
203
+ consola.error(`index: service binary unavailable (${server.reason ?? "unknown"}) — retry with --backend=colgrep`);
204
+ process.exitCode = 1;
205
+ return;
206
+ } else {
207
+ consola.warn(`index: service binary unavailable (${server.reason ?? "unknown"}) — falling back to colgrep`);
208
+ if (args.full === true || args.dryRun === true) consola.warn("index: --full/--dry-run apply to the service backend only; ignored for colgrep");
209
+ await runColbertIndex(workspace, deadlineMs, timeoutMin);
210
+ return;
211
+ }
212
+ } catch (err) {
213
+ if (backendExplicit) {
214
+ consola.error("index: service provision threw:", err);
215
+ process.exitCode = 1;
216
+ return;
217
+ }
218
+ consola.warn("index: service provision skipped:", err);
219
+ await runColbertIndex(workspace, deadlineMs, timeoutMin);
220
+ return;
221
+ }
222
+ if (variant === void 0) {
223
+ consola.error("index: no service variant resolved");
224
+ process.exitCode = 1;
225
+ return;
226
+ }
227
+ await runServiceIndex(workspace, {
228
+ full: args.full === true,
229
+ dryRun: args.dryRun === true,
230
+ deadlineMs,
231
+ timeoutMin,
232
+ variant
233
+ });
234
+ return;
235
+ }
236
+ await runColbertIndex(workspace, deadlineMs, timeoutMin);
237
+ }
238
+ });
239
+ async function runServiceIndex(workspace, opts) {
240
+ const startMs = Date.now();
241
+ const signal = Number.isFinite(opts.deadlineMs) && opts.deadlineMs !== Number.POSITIVE_INFINITY ? AbortSignal.timeout(Math.max(1, opts.deadlineMs - Date.now())) : void 0;
242
+ if (opts.dryRun) {
243
+ const plan = await populateWorkspace(workspace, { dryRun: true }).catch((err) => {
244
+ consola.error("index: dry-run failed:", err);
245
+ process.exitCode = 1;
246
+ return null;
247
+ });
248
+ if (!plan) return;
249
+ consola.info(`dry-run: ${plan.scanned} files scanned → ${plan.updatedFiles} to index, ${plan.removedFiles} to remove, ${plan.unchanged} unchanged`);
250
+ return;
251
+ }
252
+ const first = await serviceFreshness(workspace);
253
+ if (first.verdict === "fresh" && !opts.full) {
254
+ consola.success("index is already fresh — nothing to build");
255
+ printServiceStatus(await collectServiceStatus(workspace));
256
+ return;
257
+ }
258
+ consola.info(`Building service index for ${workspace} (freshness: ${first.verdict}, variant: ${opts.variant})…`);
259
+ if (!await ensureServerForeground()) {
260
+ consola.error("index: service server failed to start — retry with --backend=colgrep");
261
+ process.exitCode = 1;
262
+ return;
263
+ }
264
+ let lastLogMs = 0;
265
+ try {
266
+ const result = await populateWorkspace(workspace, {
267
+ full: opts.full,
268
+ foreground: true,
269
+ ...signal ? { signal } : {},
270
+ onProgress: (p) => {
271
+ const now = Date.now();
272
+ if (p.phase !== "done" && now - lastLogMs < POLL_MS) return;
273
+ lastLogMs = now;
274
+ if (p.phase === "done") return;
275
+ consola.info(`… ${p.phase}: ${p.scanned}/${p.total} files` + (p.phase === "encode" || p.phase === "extract" ? ` (${p.updatedFiles} changed, ${p.units} units)` : ""));
276
+ }
277
+ });
278
+ const elapsedS = Math.round((Date.now() - startMs) / 1e3);
279
+ if (result.status === "unchanged") consola.success(`index ready in ${elapsedS}s (no changes)`);
280
+ else consola.success(`index ready in ${elapsedS}s (delta: ${result.unchanged} unchanged, ${result.updatedFiles} updated, ${result.removedFiles} removed, ${result.units} units)`);
281
+ printServiceStatus(await collectServiceStatus(workspace));
282
+ } catch (err) {
283
+ if (signal?.aborted || Date.now() > opts.deadlineMs) consola.error(`index: timed out after ${opts.timeoutMin}min — retry or raise --timeout`);
284
+ else consola.error("index: service build failed:", err);
285
+ process.exitCode = 1;
286
+ } finally {
287
+ await stopServiceServer();
288
+ }
289
+ }
290
+ async function runColbertIndex(workspace, deadlineMs, timeoutMin) {
291
+ const first = await freshnessVerdict(workspace);
292
+ if (first.verdict === "fresh") {
293
+ consola.success("index is already fresh — nothing to build");
294
+ printStatus(await collectStatus(workspace));
295
+ return;
296
+ }
297
+ if (first.verdict === "failed") consola.warn("index: last build failed; starting one bounded rebuild attempt");
298
+ consola.info(`Building semantic index for ${workspace} (freshness: ${first.verdict})…`);
299
+ kickBackgroundInit(workspace);
300
+ const startMs = Date.now();
301
+ for (;;) {
302
+ if (Date.now() > deadlineMs) {
303
+ consola.error(`index: timed out after ${timeoutMin}min — the background build continues; retry or raise --timeout`);
304
+ process.exitCode = 1;
305
+ return;
306
+ }
307
+ await waitForInit(workspace).catch(() => {});
308
+ const v = await freshnessVerdict(workspace);
309
+ const elapsedS = Math.round((Date.now() - startMs) / 1e3);
310
+ if (v.verdict === "fresh") {
311
+ consola.success(`index ready in ${elapsedS}s`);
312
+ printStatus(await collectStatus(workspace));
313
+ return;
314
+ }
315
+ if (v.verdict === "failed" || v.verdict === "crashed" || v.verdict === "corrupt") {
316
+ consola.error(`index: build ended ${v.verdict} — lexical code search still works; see the proxy error log for the failure class`);
317
+ process.exitCode = 1;
318
+ return;
319
+ }
320
+ const sig = indexDirSignature(workspace);
321
+ const progress = sig.kind === "observed" ? ` [${sig.signature}]` : " [starting…]";
322
+ consola.info(`… ${elapsedS}s elapsed (freshness: ${v.verdict})${progress}`);
323
+ await sleep(POLL_MS);
324
+ kickBackgroundInit(workspace);
325
+ }
326
+ }
327
+ //#endregion
328
+ export { indexCmd };
329
+
330
+ //# sourceMappingURL=index-cmd-k3oWl0n4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-cmd-k3oWl0n4.js","names":["os"],"sources":["../src/index-cmd.ts"],"sourcesContent":["/**\n * `github-router index` — build the semantic code-search index in the\n * foreground, without starting the proxy (`start`/`claude`/`codex`).\n *\n * Phase 4a: drives the CURRENT colbert backend (foreground `init` with\n * progress). Phase 5: `auto` (default) prefers the persistent service\n * backend — foreground all-core encode with CUDA when a GPU is visible —\n * with TRUE DELTA indexing (only changed files are re-embedded); falls\n * back to colbert when the service is not actionable. `--backend` forces\n * `service` or `colbert`. The explicit invocation IS the opt-in — `--search` is not\n * required — but `GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1` still hard-disables\n * (building an index that can never be served is pointless).\n *\n * Exit codes: 0 = fresh or successfully built; 1 = provision/build\n * failure; 2 = usage error (bad workspace, hard-disabled).\n */\n\nimport { defineCommand } from \"citty\";\nimport consola from \"consola\";\nimport * as os from \"node:os\";\nimport process from \"node:process\";\n\nimport { validateWorkspace } from \"~/lib/code-search\";\nimport {\n colbertProjectDir,\n completedIndexOnDisk,\n freshnessVerdict,\n indexDirSignature,\n readColbertMeta,\n validateIndexIntegrity,\n} from \"~/lib/colbert/index-store\";\nimport { registerColbertExitHandlers } from \"~/lib/colbert/lifecycle\";\nimport { provisionColbert, provisionNextPlaidServer } from \"~/lib/colbert/provision\";\nimport { kickBackgroundInit, waitForInit } from \"~/lib/colbert/runner\";\nimport {\n ensureServerForeground,\n populateWorkspace,\n selectServerVariant,\n semanticBackend,\n serviceBackendProvisionable,\n serviceFreshness,\n stopServiceServer,\n} from \"~/lib/colbert/service-backend\";\nimport { PATHS } from \"~/lib/paths\";\nimport { parseBoolEnv } from \"~/lib/exec\";\n\nconst POLL_MS = 10_000;\n\nfunction cpuCount(): number {\n try {\n const n = os.cpus().length;\n return Number.isSafeInteger(n) && n > 0 ? n : 4;\n } catch {\n return 4;\n }\n}\n\ninterface IndexStatus {\n workspace: string;\n verdict: string;\n indexOnDisk: boolean;\n shards?: number;\n embeddings?: number;\n integrity?: string;\n head?: string;\n dirty?: boolean;\n lastIndexedAt?: string;\n}\n\nasync function collectStatus(workspace: string): Promise<IndexStatus> {\n const { verdict, head, dirty } = await freshnessVerdict(workspace);\n const onDisk = await completedIndexOnDisk(workspace);\n const status: IndexStatus = {\n workspace,\n verdict,\n indexOnDisk: onDisk,\n };\n const projectDir = await colbertProjectDir(workspace);\n if (projectDir) {\n const integrity = validateIndexIntegrity(`${projectDir}/index`);\n if (integrity.verdict === \"coherent\") {\n status.shards = integrity.shardCount;\n status.embeddings = integrity.embeddingCount;\n } else {\n status.integrity = integrity.verdict;\n }\n }\n const meta = await readColbertMeta(workspace);\n if (meta?.lastIndexedAt) status.lastIndexedAt = meta.lastIndexedAt;\n if (head !== undefined) status.head = head.slice(0, 12);\n if (dirty !== undefined) status.dirty = dirty;\n return status;\n}\n\nfunction printStatus(s: IndexStatus): void {\n consola.info(`workspace: ${s.workspace}`);\n consola.info(`verdict: ${s.verdict}`);\n consola.info(`index: ${s.indexOnDisk ? \"present\" : \"absent\"}`);\n if (s.shards !== undefined) {\n consola.info(`shards: ${s.shards} (${s.embeddings ?? 0} embeddings)`);\n }\n if (s.integrity && s.integrity !== \"not-built\") {\n consola.info(`integrity: ${s.integrity}`);\n }\n if (s.head !== undefined)\n consola.info(`head: ${s.head}${s.dirty ? \" (dirty)\" : \"\"}`);\n if (s.lastIndexedAt) consola.info(`indexed: ${s.lastIndexedAt}`);\n}\n\ninterface IndexServiceStatus {\n workspace: string;\n backend: string;\n verdict: string;\n indexedAt?: string;\n docCount?: number;\n head?: string;\n dirty?: boolean;\n}\n\nasync function collectServiceStatus(workspace: string): Promise<IndexServiceStatus> {\n const { verdict, meta, head, dirty } = await serviceFreshness(workspace);\n const status: IndexServiceStatus = {\n workspace,\n backend: \"service\",\n verdict,\n };\n if (meta?.indexedAt) status.indexedAt = meta.indexedAt;\n if (meta?.docCount !== undefined) status.docCount = meta.docCount;\n if (head !== undefined) status.head = head.slice(0, 12);\n if (dirty !== undefined) status.dirty = dirty;\n return status;\n}\n\nfunction printServiceStatus(s: IndexServiceStatus): void {\n consola.info(`workspace: ${s.workspace}`);\n consola.info(`backend: ${s.backend}`);\n consola.info(`verdict: ${s.verdict}`);\n if (s.docCount !== undefined) consola.info(`documents: ${s.docCount}`);\n if (s.head !== undefined)\n consola.info(`head: ${s.head}${s.dirty ? \" (dirty)\" : \"\"}`);\n if (s.indexedAt) consola.info(`indexed: ${s.indexedAt}`);\n}\n\ntype IndexBackend = \"service\" | \"colgrep\";\n\nfunction resolveIndexBackend(requested: unknown): { backend: IndexBackend; explicit: boolean } | { error: string } {\n const raw = typeof requested === \"string\" && requested.length > 0 ? requested.toLowerCase() : \"auto\";\n if (raw !== \"auto\" && raw !== \"service\" && raw !== \"colgrep\") {\n return { error: `index: --backend must be auto, service, or colgrep (got ${String(requested)})` };\n }\n // Explicit opt-in (flag or env) always means service.\n if (raw === \"service\" || (raw === \"auto\" && semanticBackend() === \"service\")) {\n return { backend: \"service\", explicit: true };\n }\n if (raw === \"colgrep\") return { backend: \"colgrep\", explicit: false };\n // Auto: service when provisionable (binary on disk or promoted\n // download + model present), else the colgrep fallback.\n return serviceBackendProvisionable()\n ? { backend: \"service\", explicit: false }\n : { backend: \"colgrep\", explicit: false };\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const t = setTimeout(resolve, ms);\n t.unref?.();\n });\n}\n\nexport const indexCmd = defineCommand({\n meta: {\n name: \"index\",\n description:\n \"Build the semantic code-search index for a workspace in the foreground (no proxy needed)\",\n },\n args: {\n workspace: {\n alias: \"w\",\n type: \"string\",\n description: \"Absolute path to the repo to index (default: cwd)\",\n },\n status: {\n type: \"boolean\",\n default: false,\n description: \"Print index status and exit (no build)\",\n },\n timeout: {\n type: \"string\",\n description: \"Max minutes to wait for the build (0 = none, default 0)\",\n },\n backend: {\n type: \"string\",\n description: \"Index backend: auto (service with CUDA/CPU autodetect, colgrep fallback), service, or colgrep (default auto)\",\n },\n full: {\n type: \"boolean\",\n default: false,\n description: \"Force a full rebuild, ignoring content hashes (service backend)\",\n },\n dryRun: {\n type: \"boolean\",\n default: false,\n description: \"Classify changed files without building (service backend)\",\n },\n },\n async run({ args }) {\n const rawWorkspace =\n typeof args.workspace === \"string\" && args.workspace.length > 0\n ? args.workspace\n : process.cwd();\n const ws = validateWorkspace(rawWorkspace);\n if (!ws.ok || !ws.canonical) {\n consola.error(`index: ${ws.error ?? \"workspace validation failed\"}`);\n process.exitCode = 2;\n return;\n }\n const workspace = ws.canonical;\n\n if (parseBoolEnv(process.env.GH_ROUTER_DISABLE_SEMANTIC_SEARCH) === true) {\n consola.error(\n \"index: semantic search is hard-disabled (GH_ROUTER_DISABLE_SEMANTIC_SEARCH=1); nothing to build\",\n );\n process.exitCode = 2;\n return;\n }\n\n const backendSelection = resolveIndexBackend(args.backend);\n if (\"error\" in backendSelection) {\n consola.error(backendSelection.error);\n process.exitCode = 2;\n return;\n }\n const { backend, explicit: backendExplicit } = backendSelection;\n\n if (args.status === true) {\n if (backend === \"service\") {\n printServiceStatus(await collectServiceStatus(workspace));\n } else {\n printStatus(await collectStatus(workspace));\n }\n return;\n }\n\n const timeoutMin = args.timeout === undefined ? 0 : Number(args.timeout);\n if (\n args.timeout !== undefined &&\n !(Number.isFinite(timeoutMin) && timeoutMin >= 0)\n ) {\n consola.error(\n \"index: --timeout must be a non-negative number of minutes\",\n );\n process.exitCode = 2;\n return;\n }\n const deadlineMs =\n timeoutMin > 0\n ? Date.now() + timeoutMin * 60_000\n : Number.POSITIVE_INFINITY;\n\n // Foreground dedicated build: use all cores unless the operator capped\n // explicitly. Background auto-indexing stays at 25% (the colbert\n // default); an explicit `index` invocation expects speed.\n if (process.env.GH_ROUTER_COLBERT_PARALLEL === undefined) {\n process.env.GH_ROUTER_COLBERT_PARALLEL = String(cpuCount());\n consola.debug(\n `index: parallelism defaulted to ${cpuCount()} sessions (override with GH_ROUTER_COLBERT_PARALLEL)`,\n );\n }\n\n registerColbertExitHandlers();\n\n consola.info(\n `Provisioning semantic-search artifacts into ${PATHS.COLBERT_INDICES_DIR}…`,\n );\n try {\n const result = await provisionColbert();\n if (result.status !== \"ready\") {\n consola.error(\n `index: provision ${result.status}${result.reason ? ` (${result.reason})` : \"\"}`,\n );\n process.exitCode = 1;\n return;\n }\n } catch (err) {\n consola.error(\"index: provision threw:\", err);\n process.exitCode = 1;\n return;\n }\n\n // Auto resolves the backend AFTER provisioning (the model dir must\n // exist before provisionability can report actionable). An\n // explicit service request that cannot provision the server binary\n // fails closed; auto silently falls back to colgrep.\n if (backend === \"service\") {\n let variant: Awaited<ReturnType<typeof selectServerVariant>> | undefined;\n try {\n variant = await selectServerVariant();\n const server = await provisionNextPlaidServer(variant);\n if (server.path) {\n consola.info(`index: service backend ready (${variant}: ${server.path})`);\n } else if (backendExplicit) {\n consola.error(\n `index: service binary unavailable (${server.reason ?? \"unknown\"}) — retry with --backend=colgrep`,\n );\n process.exitCode = 1;\n return;\n } else {\n consola.warn(\n `index: service binary unavailable (${server.reason ?? \"unknown\"}) — falling back to colgrep`,\n );\n if (args.full === true || args.dryRun === true) {\n consola.warn(\n \"index: --full/--dry-run apply to the service backend only; ignored for colgrep\",\n );\n }\n\n await runColbertIndex(workspace, deadlineMs, timeoutMin);\n return;\n }\n } catch (err) {\n if (backendExplicit) {\n consola.error(\"index: service provision threw:\", err);\n process.exitCode = 1;\n return;\n }\n consola.warn(\"index: service provision skipped:\", err);\n await runColbertIndex(workspace, deadlineMs, timeoutMin);\n return;\n }\n // Foreground service build (all-core encode; CUDA when detected).\n if (variant === undefined) {\n consola.error(\"index: no service variant resolved\");\n process.exitCode = 1;\n return;\n }\n await runServiceIndex(workspace, {\n full: args.full === true,\n dryRun: args.dryRun === true,\n deadlineMs,\n timeoutMin,\n variant,\n });\n return;\n }\n\n await runColbertIndex(workspace, deadlineMs, timeoutMin);\n },\n});\n\nasync function runServiceIndex(\n workspace: string,\n opts: {\n full: boolean;\n dryRun: boolean;\n deadlineMs: number;\n timeoutMin: number;\n variant: string;\n },\n): Promise<void> {\n const startMs = Date.now();\n const signal =\n Number.isFinite(opts.deadlineMs) && opts.deadlineMs !== Number.POSITIVE_INFINITY\n ? AbortSignal.timeout(Math.max(1, opts.deadlineMs - Date.now()))\n : undefined;\n\n if (opts.dryRun) {\n const plan = await populateWorkspace(workspace, { dryRun: true }).catch((err) => {\n consola.error(\"index: dry-run failed:\", err);\n process.exitCode = 1;\n return null;\n });\n if (!plan) return;\n consola.info(\n `dry-run: ${plan.scanned} files scanned → ${plan.updatedFiles} to index, ${plan.removedFiles} to remove, ${plan.unchanged} unchanged`,\n );\n return;\n }\n\n const first = await serviceFreshness(workspace);\n if (first.verdict === \"fresh\" && !opts.full) {\n consola.success(\"index is already fresh — nothing to build\");\n printServiceStatus(await collectServiceStatus(workspace));\n return;\n }\n\n consola.info(\n `Building service index for ${workspace} (freshness: ${first.verdict}, variant: ${opts.variant})…`,\n );\n const server = await ensureServerForeground();\n if (!server) {\n consola.error(\n \"index: service server failed to start — retry with --backend=colgrep\",\n );\n process.exitCode = 1;\n return;\n }\n let lastLogMs = 0;\n try { const result = await populateWorkspace(workspace, {\n full: opts.full,\n foreground: true,\n ...(signal ? { signal } : {}),\n onProgress: (p) => {\n const now = Date.now();\n if (p.phase !== \"done\" && now - lastLogMs < POLL_MS) return;\n lastLogMs = now;\n if (p.phase === \"done\") return;\n consola.info(\n `… ${p.phase}: ${p.scanned}/${p.total} files` +\n (p.phase === \"encode\" || p.phase === \"extract\"\n ? ` (${p.updatedFiles} changed, ${p.units} units)`\n : \"\"),\n );\n },\n });\n const elapsedS = Math.round((Date.now() - startMs) / 1000);\n if (result.status === \"unchanged\") {\n consola.success(`index ready in ${elapsedS}s (no changes)`);\n } else {\n consola.success(\n `index ready in ${elapsedS}s (delta: ${result.unchanged} unchanged, ${result.updatedFiles} updated, ${result.removedFiles} removed, ${result.units} units)`,\n );\n }\n printServiceStatus(await collectServiceStatus(workspace));\n } catch (err) {\n if (signal?.aborted || Date.now() > opts.deadlineMs) {\n consola.error(\n `index: timed out after ${opts.timeoutMin}min — retry or raise --timeout`,\n );\n } else {\n consola.error(\"index: service build failed:\", err);\n }\n process.exitCode = 1;\n } finally {\n // The persistent server holds the event loop open — stop it or this\n // foreground command never exits (and orphans a server per run).\n await stopServiceServer();\n }\n}\n\nasync function runColbertIndex(\n workspace: string,\n deadlineMs: number,\n timeoutMin: number,\n): Promise<void> {\n const first = await freshnessVerdict(workspace);\n if (first.verdict === \"fresh\") {\n consola.success(\"index is already fresh — nothing to build\");\n printStatus(await collectStatus(workspace));\n return;\n }\n if (first.verdict === \"failed\") {\n consola.warn(\n \"index: last build failed; starting one bounded rebuild attempt\",\n );\n }\n\n consola.info(\n `Building semantic index for ${workspace} (freshness: ${first.verdict})…`,\n );\n kickBackgroundInit(workspace);\n const startMs = Date.now();\n\n for (;;) {\n if (Date.now() > deadlineMs) {\n consola.error(\n `index: timed out after ${timeoutMin}min — the background build continues; retry or raise --timeout`,\n );\n process.exitCode = 1;\n return;\n }\n // Wait for this process's tracked build; resolves immediately when\n // another proxy owns it, in which case the sleep below paces polling.\n await waitForInit(workspace).catch(() => {});\n const v = await freshnessVerdict(workspace);\n const elapsedS = Math.round((Date.now() - startMs) / 1000);\n if (v.verdict === \"fresh\") {\n consola.success(`index ready in ${elapsedS}s`);\n printStatus(await collectStatus(workspace));\n return;\n }\n if (\n v.verdict === \"failed\" ||\n v.verdict === \"crashed\" ||\n v.verdict === \"corrupt\"\n ) {\n consola.error(\n `index: build ended ${v.verdict} — lexical code search still works; see the proxy error log for the failure class`,\n );\n process.exitCode = 1;\n return;\n }\n // building | stale | absent: report progress, keep waiting. colgrep\n // is silent on pipes during encode, so disk growth is the signal.\n const sig = indexDirSignature(workspace);\n const progress =\n sig.kind === \"observed\" ? ` [${sig.signature}]` : \" [starting…]\";\n consola.info(\n `… ${elapsedS}s elapsed (freshness: ${v.verdict})${progress}`,\n );\n await sleep(POLL_MS);\n // Re-kick if nothing owns the build (crash between kick and track).\n kickBackgroundInit(workspace);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,UAAU;AAEhB,SAAS,WAAmB;CAC1B,IAAI;EACF,MAAM,IAAIA,KAAG,KAAK,CAAC,CAAC;EACpB,OAAO,OAAO,cAAc,CAAC,KAAK,IAAI,IAAI,IAAI;CAChD,QAAQ;EACN,OAAO;CACT;AACF;AAcA,eAAe,cAAc,WAAyC;CACpE,MAAM,EAAE,SAAS,MAAM,UAAU,MAAM,iBAAiB,SAAS;CAEjE,MAAM,SAAsB;EAC1B;EACA;EACA,aAAa,MAJM,qBAAqB,SAAS;CAKnD;CACA,MAAM,aAAa,MAAM,kBAAkB,SAAS;CACpD,IAAI,YAAY;EACd,MAAM,YAAY,uBAAuB,GAAG,WAAW,OAAO;EAC9D,IAAI,UAAU,YAAY,YAAY;GACpC,OAAO,SAAS,UAAU;GAC1B,OAAO,aAAa,UAAU;EAChC,OACE,OAAO,YAAY,UAAU;CAEjC;CACA,MAAM,OAAO,MAAM,gBAAgB,SAAS;CAC5C,IAAI,MAAM,eAAe,OAAO,gBAAgB,KAAK;CACrD,IAAI,SAAS,KAAA,GAAW,OAAO,OAAO,KAAK,MAAM,GAAG,EAAE;CACtD,IAAI,UAAU,KAAA,GAAW,OAAO,QAAQ;CACxC,OAAO;AACT;AAEA,SAAS,YAAY,GAAsB;CACzC,QAAQ,KAAK,cAAc,EAAE,WAAW;CACxC,QAAQ,KAAK,cAAc,EAAE,SAAS;CACtC,QAAQ,KAAK,cAAc,EAAE,cAAc,YAAY,UAAU;CACjE,IAAI,EAAE,WAAW,KAAA,GACf,QAAQ,KAAK,cAAc,EAAE,OAAO,IAAI,EAAE,cAAc,EAAE,aAAa;CAEzE,IAAI,EAAE,aAAa,EAAE,cAAc,aACjC,QAAQ,KAAK,cAAc,EAAE,W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;CACF;CACA,IAAI,MAAM,YAAY,UACpB,QAAQ,KACN,gEACF;CAGF,QAAQ,KACN,+BAA+B,UAAU,eAAe,MAAM,QAAQ,GACxE;CACA,mBAAmB,SAAS;CAC5B,MAAM,UAAU,KAAK,IAAI;CAEzB,SAAS;EACP,IAAI,KAAK,IAAI,IAAI,YAAY;GAC3B,QAAQ,MACN,0BAA0B,WAAW,+DACvC;GACA,QAAQ,WAAW;GACnB;EACF;EAGA,MAAM,YAAY,SAAS,CAAC,CAAC,YAAY,CAAC,CAAC;EAC3C,MAAM,IAAI,MAAM,iBAAiB,SAAS;EAC1C,MAAM,WAAW,KAAK,OAAO,KAAK,IAAI,IAAI,WAAW,GAAI;EACzD,IAAI,EAAE,YAAY,SAAS;GACzB,QAAQ,QAAQ,kBAAkB,SAAS,EAAE;GAC7C,YAAY,MAAM,cAAc,SAAS,CAAC;GAC1C;EACF;EACA,IACE,EAAE,YAAY,YACd,EAAE,YAAY,aACd,EAAE,YAAY,WACd;GACA,QAAQ,MACN,sBAAsB,EAAE,QAAQ,kFAClC;GACA,QAAQ,WAAW;GACnB;EACF;EAGA,MAAM,MAAM,kBAAkB,SAAS;EACvC,MAAM,WACJ,IAAI,SAAS,aAAa,KAAK,IAAI,UAAU,KAAK;EACpD,QAAQ,KACN,KAAK,SAAS,wBAAwB,EAAE,QAAQ,GAAG,UACrD;EACA,MAAM,MAAM,OAAO;EAEnB,mBAAmB,SAAS;CAC9B;AACF"}
@@ -4,7 +4,7 @@ import { a as decideStopHook, c as launchBaselineKey, d as stopGateId, f as stop
4
4
  import { t as liveExec } from "./orchestration-Dn5v8c0a.js";
5
5
  import { c as repoRoot, i as fileReviewDebounce, l as stopGateEnabledForRepo, r as fileLastPromptStore, t as fileBaselineStore, u as stopReviewStateDir } from "./stop-gate-policy-D6jIeOXB.js";
6
6
  import { r as hookMcpRuntimeFromEnv } from "./hook-mcp-client-DbFtxo6_.js";
7
- import { a as checksForDescriptor, n as readDiscoveredGate, o as descriptorHash, s as parseGateDescriptor } from "./gate-discovery-BGqS7R2g.js";
7
+ import { a as checksForDescriptor, n as readDiscoveredGate, o as descriptorHash, s as parseGateDescriptor } from "./gate-discovery-BUhtwkyE.js";
8
8
  import { defineCommand } from "citty";
9
9
  import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
10
10
  import path from "node:path";
@@ -257,4 +257,4 @@ const internalStopHook = defineCommand({
257
257
  //#endregion
258
258
  export { internalStopHook };
259
259
 
260
- //# sourceMappingURL=internal-stop-hook-CH9SKjZ9.js.map
260
+ //# sourceMappingURL=internal-stop-hook-DBrlosd0.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"internal-stop-hook-CH9SKjZ9.js","names":[],"sources":["../src/internal-stop-hook.ts"],"sourcesContent":["/**\n * The internal `internal-stop-hook` subcommand: the executable a spawned Claude\n * Code session's Stop hook invokes (registered into the mirrored settings.json by\n * the launcher when `GH_ROUTER_ENABLE_STOP_GATE` is set). It reads Claude Code's\n * hook payload from stdin, runs the SEALED structural gate over the session's\n * working-tree diff, and maps the result to the hook exit contract: exit 2 (with\n * the reason on stderr) blocks the stop so the model fixes the failure; exit 0\n * allows it. The `stop_hook_active` loop guard (in `decideStopHook`) guarantees\n * it can never wedge the session.\n *\n * All decision logic lives in `decideStopHook` (pure, unit-tested); this wrapper\n * only does stdin read + the live `git diff` capture + the exit. The live firing\n * is verified by the gated E2E (it needs a real spawned session).\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { spawn } from \"node:child_process\"\nimport { randomBytes } from \"node:crypto\"\nimport { mkdirSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport path from \"node:path\"\n\nimport { parseBoolEnv, runCommandCapture } from \"./lib/exec\"\nimport { PACKAGE_ROOT_FLAG, explicitPackageRoot } from \"./lib/package-root\"\nimport { liveExec } from \"./lib/orchestration\"\nimport { readDiscoveredGate } from \"./lib/orchestration/gate-discovery\"\nimport { checksForDescriptor, descriptorHash, parseGateDescriptor, type GateDescriptor } from \"./lib/orchestration/harness-parse\"\nimport { hookMcpRuntimeFromEnv } from \"./lib/orchestration/hook-mcp-client\"\nimport {\n decideStopHook,\n fileBlockBudget,\n launchBaselineKey,\n stopGateId,\n stopReviewEnabled,\n type StopReviewContext,\n} from \"./lib/orchestration/stop-gate-hook\"\nimport {\n fileBaselineStore,\n fileLastPromptStore,\n fileReviewDebounce,\n repoRoot,\n stopGateEnabledForRepo,\n stopReviewStateDir,\n} from \"./lib/orchestration/stop-gate-policy\"\nimport { parseIntEnv } from \"./lib/exec\"\n\n/**\n * Read the hook payload from stdin SYNCHRONOUSLY (`readFileSync(0)`). An async\n * stdin read leaves an in-flight libuv FS request that, on Windows, races the\n * process teardown and trips a `uv_async_send` assertion; a synchronous read has\n * no such handle. Hooks always receive piped/redirected stdin, so this never\n * blocks (guarded against an interactive TTY, and any error -> \"\").\n */\nfunction readStdin(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\n/** Max diff bytes scanned for gate-weakening: a hard cap so a huge generated diff\n * (e.g. a lockfile) can never OOM or stall the hook. */\nconst MAX_DIFF_BYTES = 2 * 1024 * 1024\n\n/** Build a tiny synthetic diff for untracked paths so the weakening scan sees\n * their contents too. No index mutation (`git add -N`) is needed. */\nasync function captureUntrackedDiff(cwd: string, paths: string[]): Promise<string> {\n const chunks: string[] = []\n let bytes = 0\n for (const untrackedPath of paths) {\n const result = await runCommandCapture(\n [\"git\", \"diff\", \"--no-index\", \"--\", \"/dev/null\", untrackedPath],\n { cwd, timeoutMs: 5_000, maxStdoutBytes: MAX_DIFF_BYTES },\n )\n // `git diff --no-index` returns 1 when differences exist; anything else is an\n // actual failure. A truncated untracked diff is unknown, never \"no diff\".\n if (result.code !== 1 || result.truncated) throw new Error(`git diff for untracked file failed with exit ${result.code}`)\n bytes += Buffer.byteLength(result.stdout, \"utf8\")\n if (bytes > MAX_DIFF_BYTES) throw new Error(\"git working-tree capture exceeded its size limit\")\n chunks.push(result.stdout)\n }\n return chunks.join(\"\")\n}\n\n/** Capture every working-tree change WITHOUT mutating the user's index (no\n * `git add -N`). `git diff HEAD` covers staged + unstaged tracked changes;\n * `git ls-files --others` catches untracked files and each is diffed against an\n * empty file so gate-weakening in new tests is visible. Git failures/truncation\n * reject, so the decision layer runs the full checks instead of mistaking an\n * unknown tree for a no-diff turn. */\nexport async function captureStopGateDiff(cwd: string): Promise<string> {\n const [diffResult, untrackedResult] = await Promise.all([\n runCommandCapture([\"git\", \"diff\", \"HEAD\"], { cwd, timeoutMs: 5_000, maxStdoutBytes: MAX_DIFF_BYTES }),\n runCommandCapture([\"git\", \"ls-files\", \"--others\", \"--exclude-standard\", \"-z\"], {\n cwd,\n timeoutMs: 5_000,\n maxStdoutBytes: MAX_DIFF_BYTES,\n }),\n ])\n if (diffResult.code !== 0) throw new Error(`git diff failed with exit ${diffResult.code}`)\n if (untrackedResult.code !== 0) throw new Error(`git ls-files failed with exit ${untrackedResult.code}`)\n if (diffResult.truncated || untrackedResult.truncated) throw new Error(\"git working-tree capture exceeded its size limit\")\n\n const untrackedPaths = untrackedResult.stdout.split(\"\\0\").filter(Boolean)\n if (untrackedPaths.length === 0) return diffResult.stdout\n const untrackedDiff = await captureUntrackedDiff(cwd, untrackedPaths)\n if (Buffer.byteLength(diffResult.stdout, \"utf8\") + Buffer.byteLength(untrackedDiff, \"utf8\") > MAX_DIFF_BYTES) {\n throw new Error(\"git working-tree capture exceeded its size limit\")\n }\n return diffResult.stdout + untrackedDiff\n}\n\n/** Flush a message to stderr before exiting (process.exit can drop an unflushed\n * write; the model reads this stderr on a block). */\nasync function writeStderr(msg: string): Promise<void> {\n await new Promise<void>((resolve) => {\n process.stderr.write(msg, () => resolve())\n })\n}\n\n/**\n * Fire-and-forget spawn of the detached background reviewer. The payload (which\n * includes the up-to-2-MiB diff) is written to a temp file SYNCHRONOUSLY before\n * the spawn — a pipe to the child's stdin would race the parent's `process.exit`\n * and could deliver a truncated diff. The child reads the file (path passed via\n * `GH_ROUTER_STOP_REVIEW_PAYLOAD`), unlinks it, and inherits the proxy URL/nonce\n * env. Everything is swallowed: the advisory layer never affects the stop.\n */\nfunction spawnStopReview(ctx: StopReviewContext, extras: { prompt: string; transcriptPath: string }): void {\n let payloadPath: string | undefined\n try {\n const dir = stopReviewStateDir()\n mkdirSync(dir, { recursive: true })\n payloadPath = path.join(dir, `payload-${process.pid}-${randomBytes(4).toString(\"hex\")}.json`)\n writeFileSync(\n payloadPath,\n JSON.stringify({\n session_id: ctx.sessionId,\n cwd: ctx.cwd,\n diff: ctx.diff,\n prompt: extras.prompt,\n transcript_path: extras.transcriptPath,\n }),\n { mode: 0o600 },\n )\n // Invoke the same binary's `internal-stop-review` subcommand. Preserve the\n // package root when this hook itself runs from the relocated launcher.\n const scriptArgs = process.argv[1] && process.argv[1] !== process.execPath ? [process.argv[1]] : []\n const root = explicitPackageRoot()\n const packageRootArgs = root ? [PACKAGE_ROOT_FLAG, root] : []\n const child = spawn(process.execPath, [...scriptArgs, ...packageRootArgs, \"internal-stop-review\"], {\n detached: true,\n windowsHide: true,\n stdio: \"ignore\",\n env: { ...process.env, GH_ROUTER_STOP_REVIEW_PAYLOAD: payloadPath },\n })\n // A spawn failure (EAGAIN / EACCES / fork limit) is delivered ASYNCHRONOUSLY\n // via the child's 'error' event, AFTER this synchronous try block exits. With\n // no listener Node escalates it to an uncaughtException — which main.ts turns\n // into process.exit(1), corrupting the Stop hook's exit code. Swallow it here\n // (and drop the now-orphaned payload the child never read) so the advisory\n // spawn truly never affects the stop.\n const orphan = payloadPath\n child.on(\"error\", () => {\n if (orphan) {\n try {\n unlinkSync(orphan)\n } catch {\n /* best-effort */\n }\n }\n })\n child.unref()\n } catch {\n // Advisory spawn is best-effort; never disrupt the stop. If we wrote the\n // payload file but the spawn failed, drop it so it doesn't orphan (the\n // child — which would normally unlink it — never started).\n if (payloadPath) {\n try {\n unlinkSync(payloadPath)\n } catch {\n /* best-effort */\n }\n }\n }\n}\n\n/** The checks for a resolved descriptor: sealed descriptors resolve their sealed\n * command set; parsed/discovered carry their own. */\ntype ResolveChecks = NonNullable<Parameters<typeof decideStopHook>[0][\"resolveChecks\"]>\n\n/**\n * Build the dynamic `resolveChecks` for the live Stop hook, per the env the\n * launcher set:\n * - GH_ROUTER_STOP_GATE_PARSED → re-derive the deterministic parser at the\n * stop-time tree (stateless, no cache);\n * - GH_ROUTER_STOP_GATE_DISCOVERED → read the cached evidence-pinned record.\n * Both pin the checks to the descriptor's `workdir` (the repo root) and compute\n * the launch-stable baseline key so the launch-captured (pre-mutation) baseline\n * is read. Any miss → null → the hook fails OPEN.\n */\nfunction buildResolveChecks(mode: \"parsed\" | \"discovered\"): ResolveChecks {\n const includeTests = parseBoolEnv(process.env.GH_ROUTER_STOP_GATE_RUN_TESTS) === true\n return async (cwd: string) => {\n const root = await repoRoot(cwd).catch(() => cwd)\n let descriptor: GateDescriptor | null = null\n if (mode === \"parsed\") {\n descriptor = await parseGateDescriptor(root, { includeTests }).catch(() => null)\n } else {\n const rec = await readDiscoveredGate(root).catch(() => null)\n if (rec) {\n descriptor = {\n kind: \"discovered\",\n checks: rec.checks,\n ecosystem: rec.ecosystem,\n workdir: root,\n evidence: rec.evidence,\n }\n }\n }\n if (!descriptor) return null\n const checks = checksForDescriptor(descriptor)\n if (checks.length === 0) return null\n const descriptorKey = descriptorHash(descriptor)\n const workdir = descriptor.workdir || root\n const token = process.env.GH_ROUTER_STOP_GATE_BASELINE_TOKEN || undefined\n return { checks, workdir, descriptorKey, baselineKey: launchBaselineKey(workdir, descriptorKey, token) }\n }\n}\n\n/** Which dynamic gate mode the launcher armed (sealed → undefined). */\nfunction dynamicMode(): \"parsed\" | \"discovered\" | undefined {\n if (parseBoolEnv(process.env.GH_ROUTER_STOP_GATE_PARSED) === true) return \"parsed\"\n if (parseBoolEnv(process.env.GH_ROUTER_STOP_GATE_DISCOVERED) === true) return \"discovered\"\n return undefined\n}\n\nexport const internalStopHook = defineCommand({\n meta: {\n name: \"internal-stop-hook\",\n description:\n \"Internal: the structural-gate Stop hook. Reads the Claude Code hook payload on stdin, \"\n + \"runs the sealed gate, exits 2 (blocks the stop) on a red gate or gate-weakening diff.\",\n },\n async run() {\n const stdin = readStdin()\n // The advisory review (hook V2) is wired only when it's enabled AND the\n // launcher injected the proxy URL/nonce. It is side-effect-only: the\n // deterministic gate below is unchanged and remains the only blocker.\n const reviewEnabled = stopReviewEnabled() && hookMcpRuntimeFromEnv() !== undefined\n let transcriptPath = \"\"\n let userPrompt = \"\"\n if (reviewEnabled) {\n // Parse the payload once for the transcript pointer + the session id used\n // to look up the user's last prompt (the Stop payload carries no prompt;\n // the UserPromptSubmit hook stashed it). Best-effort — a parse miss just\n // means the reviewer judges against the diff alone.\n try {\n const p: unknown = JSON.parse(stdin)\n if (p && typeof p === \"object\") {\n const obj = p as { transcript_path?: unknown; session_id?: unknown }\n transcriptPath = typeof obj.transcript_path === \"string\" ? obj.transcript_path : \"\"\n const sid = typeof obj.session_id === \"string\" ? obj.session_id : \"\"\n if (sid) {\n userPrompt = (await fileLastPromptStore(stopReviewStateDir()).read(sid).catch(() => null)) ?? \"\"\n }\n }\n } catch {\n /* tolerate a non-JSON stdin */\n }\n }\n\n let decision: { exitCode: 0 | 2; stderr?: string }\n try {\n const timeoutEnv = parseIntEnv(process.env.GH_ROUTER_STOP_GATE_TIMEOUT_MS)\n const mode = dynamicMode()\n decision = await decideStopHook({\n stdin,\n gateId: stopGateId(),\n exec: liveExec,\n captureDiff: captureStopGateDiff,\n fallbackCwd: process.cwd(),\n budget: fileBlockBudget(path.join(tmpdir(), \"gh-router-stopgate\")),\n baseline: fileBaselineStore(path.join(tmpdir(), \"gh-router-stopgate-baseline\")),\n isEnabledForRepo: (cwd) => stopGateEnabledForRepo(cwd),\n resolveChecks: mode ? buildResolveChecks(mode) : undefined,\n // parseIntEnv already rejects non-positive / non-integer / truncating\n // values, so undefined here means \"use the built-in default\".\n timeoutMs: timeoutEnv,\n reviewDebounce: reviewEnabled ? fileReviewDebounce(stopReviewStateDir()) : undefined,\n spawnReview: reviewEnabled\n ? (ctx) => spawnStopReview(ctx, { prompt: userPrompt, transcriptPath })\n : undefined,\n })\n } catch {\n // Fail OPEN on ANY unexpected error: a Stop hook must never wedge the\n // session, so an internal crash allows the stop (exit 0) rather than\n // surfacing a non-blocking error or a hang.\n process.exitCode = 0\n return\n }\n // Write any stderr the decision carries — both the exit-2 block reason AND\n // the LOUD exit-0 stand-down (max-block budget reached). A clean green stop\n // carries no stderr, so this stays silent on the common path.\n if (decision.stderr) {\n await writeStderr(`${decision.stderr}\\n`)\n }\n // Natural exit: set the code and return. A hard process.exit() races libuv's\n // stdio teardown on Windows (uv_async_send assertion) on the fast-return\n // paths. The detached review child is unref'd and the gate's children are\n // reaped, so no handle keeps the loop alive — the process exits with this\n // code. The exit-2 block contract is preserved (stderr is flushed above).\n process.exitCode = decision.exitCode\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,SAAS,YAAoB;CAC3B,IAAI;EACF,IAAI,QAAQ,MAAM,OAAO,OAAO;EAChC,OAAO,aAAa,GAAG,MAAM;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;;AAIA,MAAM,iBAAiB;;;AAIvB,eAAe,qBAAqB,KAAa,OAAkC;CACjF,MAAM,SAAmB,CAAC;CAC1B,IAAI,QAAQ;CACZ,KAAK,MAAM,iBAAiB,OAAO;EACjC,MAAM,SAAS,MAAM,kBACnB;GAAC;GAAO;GAAQ;GAAc;GAAM;GAAa;EAAa,GAC9D;GAAE;GAAK,WAAW;GAAO,gBAAgB;EAAe,CAC1D;EAGA,IAAI,OAAO,SAAS,KAAK,OAAO,WAAW,MAAM,IAAI,MAAM,gDAAgD,OAAO,MAAM;EACxH,SAAS,OAAO,WAAW,OAAO,QAAQ,MAAM;EAChD,IAAI,QAAQ,gBAAgB,MAAM,IAAI,MAAM,kDAAk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CAAC;IACjE,UAAU,kBAAkB,KAAK,KAAK,OAAO,GAAG,6BAA6B,CAAC;IAC9E,mBAAmB,QAAQ,uBAAuB,GAAG;IACrD,eAAe,OAAO,mBAAmB,IAAI,IAAI,KAAA;IAGjD,WAAW;IACX,gBAAgB,gBAAgB,mBAAmB,mBAAmB,CAAC,IAAI,KAAA;IAC3E,aAAa,iBACR,QAAQ,gBAAgB,KAAK;KAAE,QAAQ;KAAY;IAAe,CAAC,IACpE,KAAA;GACN,CAAC;EACH,QAAQ;GAIN,QAAQ,WAAW;GACnB;EACF;EAIA,IAAI,SAAS,QACX,MAAM,YAAY,GAAG,SAAS,OAAO,GAAG;EAO1C,QAAQ,WAAW,SAAS;CAC9B;AACF,CAAC"}
1
+ {"version":3,"file":"internal-stop-hook-DBrlosd0.js","names":[],"sources":["../src/internal-stop-hook.ts"],"sourcesContent":["/**\n * The internal `internal-stop-hook` subcommand: the executable a spawned Claude\n * Code session's Stop hook invokes (registered into the mirrored settings.json by\n * the launcher when `GH_ROUTER_ENABLE_STOP_GATE` is set). It reads Claude Code's\n * hook payload from stdin, runs the SEALED structural gate over the session's\n * working-tree diff, and maps the result to the hook exit contract: exit 2 (with\n * the reason on stderr) blocks the stop so the model fixes the failure; exit 0\n * allows it. The `stop_hook_active` loop guard (in `decideStopHook`) guarantees\n * it can never wedge the session.\n *\n * All decision logic lives in `decideStopHook` (pure, unit-tested); this wrapper\n * only does stdin read + the live `git diff` capture + the exit. The live firing\n * is verified by the gated E2E (it needs a real spawned session).\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { spawn } from \"node:child_process\"\nimport { randomBytes } from \"node:crypto\"\nimport { mkdirSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport path from \"node:path\"\n\nimport { parseBoolEnv, runCommandCapture } from \"./lib/exec\"\nimport { PACKAGE_ROOT_FLAG, explicitPackageRoot } from \"./lib/package-root\"\nimport { liveExec } from \"./lib/orchestration\"\nimport { readDiscoveredGate } from \"./lib/orchestration/gate-discovery\"\nimport { checksForDescriptor, descriptorHash, parseGateDescriptor, type GateDescriptor } from \"./lib/orchestration/harness-parse\"\nimport { hookMcpRuntimeFromEnv } from \"./lib/orchestration/hook-mcp-client\"\nimport {\n decideStopHook,\n fileBlockBudget,\n launchBaselineKey,\n stopGateId,\n stopReviewEnabled,\n type StopReviewContext,\n} from \"./lib/orchestration/stop-gate-hook\"\nimport {\n fileBaselineStore,\n fileLastPromptStore,\n fileReviewDebounce,\n repoRoot,\n stopGateEnabledForRepo,\n stopReviewStateDir,\n} from \"./lib/orchestration/stop-gate-policy\"\nimport { parseIntEnv } from \"./lib/exec\"\n\n/**\n * Read the hook payload from stdin SYNCHRONOUSLY (`readFileSync(0)`). An async\n * stdin read leaves an in-flight libuv FS request that, on Windows, races the\n * process teardown and trips a `uv_async_send` assertion; a synchronous read has\n * no such handle. Hooks always receive piped/redirected stdin, so this never\n * blocks (guarded against an interactive TTY, and any error -> \"\").\n */\nfunction readStdin(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\n/** Max diff bytes scanned for gate-weakening: a hard cap so a huge generated diff\n * (e.g. a lockfile) can never OOM or stall the hook. */\nconst MAX_DIFF_BYTES = 2 * 1024 * 1024\n\n/** Build a tiny synthetic diff for untracked paths so the weakening scan sees\n * their contents too. No index mutation (`git add -N`) is needed. */\nasync function captureUntrackedDiff(cwd: string, paths: string[]): Promise<string> {\n const chunks: string[] = []\n let bytes = 0\n for (const untrackedPath of paths) {\n const result = await runCommandCapture(\n [\"git\", \"diff\", \"--no-index\", \"--\", \"/dev/null\", untrackedPath],\n { cwd, timeoutMs: 5_000, maxStdoutBytes: MAX_DIFF_BYTES },\n )\n // `git diff --no-index` returns 1 when differences exist; anything else is an\n // actual failure. A truncated untracked diff is unknown, never \"no diff\".\n if (result.code !== 1 || result.truncated) throw new Error(`git diff for untracked file failed with exit ${result.code}`)\n bytes += Buffer.byteLength(result.stdout, \"utf8\")\n if (bytes > MAX_DIFF_BYTES) throw new Error(\"git working-tree capture exceeded its size limit\")\n chunks.push(result.stdout)\n }\n return chunks.join(\"\")\n}\n\n/** Capture every working-tree change WITHOUT mutating the user's index (no\n * `git add -N`). `git diff HEAD` covers staged + unstaged tracked changes;\n * `git ls-files --others` catches untracked files and each is diffed against an\n * empty file so gate-weakening in new tests is visible. Git failures/truncation\n * reject, so the decision layer runs the full checks instead of mistaking an\n * unknown tree for a no-diff turn. */\nexport async function captureStopGateDiff(cwd: string): Promise<string> {\n const [diffResult, untrackedResult] = await Promise.all([\n runCommandCapture([\"git\", \"diff\", \"HEAD\"], { cwd, timeoutMs: 5_000, maxStdoutBytes: MAX_DIFF_BYTES }),\n runCommandCapture([\"git\", \"ls-files\", \"--others\", \"--exclude-standard\", \"-z\"], {\n cwd,\n timeoutMs: 5_000,\n maxStdoutBytes: MAX_DIFF_BYTES,\n }),\n ])\n if (diffResult.code !== 0) throw new Error(`git diff failed with exit ${diffResult.code}`)\n if (untrackedResult.code !== 0) throw new Error(`git ls-files failed with exit ${untrackedResult.code}`)\n if (diffResult.truncated || untrackedResult.truncated) throw new Error(\"git working-tree capture exceeded its size limit\")\n\n const untrackedPaths = untrackedResult.stdout.split(\"\\0\").filter(Boolean)\n if (untrackedPaths.length === 0) return diffResult.stdout\n const untrackedDiff = await captureUntrackedDiff(cwd, untrackedPaths)\n if (Buffer.byteLength(diffResult.stdout, \"utf8\") + Buffer.byteLength(untrackedDiff, \"utf8\") > MAX_DIFF_BYTES) {\n throw new Error(\"git working-tree capture exceeded its size limit\")\n }\n return diffResult.stdout + untrackedDiff\n}\n\n/** Flush a message to stderr before exiting (process.exit can drop an unflushed\n * write; the model reads this stderr on a block). */\nasync function writeStderr(msg: string): Promise<void> {\n await new Promise<void>((resolve) => {\n process.stderr.write(msg, () => resolve())\n })\n}\n\n/**\n * Fire-and-forget spawn of the detached background reviewer. The payload (which\n * includes the up-to-2-MiB diff) is written to a temp file SYNCHRONOUSLY before\n * the spawn — a pipe to the child's stdin would race the parent's `process.exit`\n * and could deliver a truncated diff. The child reads the file (path passed via\n * `GH_ROUTER_STOP_REVIEW_PAYLOAD`), unlinks it, and inherits the proxy URL/nonce\n * env. Everything is swallowed: the advisory layer never affects the stop.\n */\nfunction spawnStopReview(ctx: StopReviewContext, extras: { prompt: string; transcriptPath: string }): void {\n let payloadPath: string | undefined\n try {\n const dir = stopReviewStateDir()\n mkdirSync(dir, { recursive: true })\n payloadPath = path.join(dir, `payload-${process.pid}-${randomBytes(4).toString(\"hex\")}.json`)\n writeFileSync(\n payloadPath,\n JSON.stringify({\n session_id: ctx.sessionId,\n cwd: ctx.cwd,\n diff: ctx.diff,\n prompt: extras.prompt,\n transcript_path: extras.transcriptPath,\n }),\n { mode: 0o600 },\n )\n // Invoke the same binary's `internal-stop-review` subcommand. Preserve the\n // package root when this hook itself runs from the relocated launcher.\n const scriptArgs = process.argv[1] && process.argv[1] !== process.execPath ? [process.argv[1]] : []\n const root = explicitPackageRoot()\n const packageRootArgs = root ? [PACKAGE_ROOT_FLAG, root] : []\n const child = spawn(process.execPath, [...scriptArgs, ...packageRootArgs, \"internal-stop-review\"], {\n detached: true,\n windowsHide: true,\n stdio: \"ignore\",\n env: { ...process.env, GH_ROUTER_STOP_REVIEW_PAYLOAD: payloadPath },\n })\n // A spawn failure (EAGAIN / EACCES / fork limit) is delivered ASYNCHRONOUSLY\n // via the child's 'error' event, AFTER this synchronous try block exits. With\n // no listener Node escalates it to an uncaughtException — which main.ts turns\n // into process.exit(1), corrupting the Stop hook's exit code. Swallow it here\n // (and drop the now-orphaned payload the child never read) so the advisory\n // spawn truly never affects the stop.\n const orphan = payloadPath\n child.on(\"error\", () => {\n if (orphan) {\n try {\n unlinkSync(orphan)\n } catch {\n /* best-effort */\n }\n }\n })\n child.unref()\n } catch {\n // Advisory spawn is best-effort; never disrupt the stop. If we wrote the\n // payload file but the spawn failed, drop it so it doesn't orphan (the\n // child — which would normally unlink it — never started).\n if (payloadPath) {\n try {\n unlinkSync(payloadPath)\n } catch {\n /* best-effort */\n }\n }\n }\n}\n\n/** The checks for a resolved descriptor: sealed descriptors resolve their sealed\n * command set; parsed/discovered carry their own. */\ntype ResolveChecks = NonNullable<Parameters<typeof decideStopHook>[0][\"resolveChecks\"]>\n\n/**\n * Build the dynamic `resolveChecks` for the live Stop hook, per the env the\n * launcher set:\n * - GH_ROUTER_STOP_GATE_PARSED → re-derive the deterministic parser at the\n * stop-time tree (stateless, no cache);\n * - GH_ROUTER_STOP_GATE_DISCOVERED → read the cached evidence-pinned record.\n * Both pin the checks to the descriptor's `workdir` (the repo root) and compute\n * the launch-stable baseline key so the launch-captured (pre-mutation) baseline\n * is read. Any miss → null → the hook fails OPEN.\n */\nfunction buildResolveChecks(mode: \"parsed\" | \"discovered\"): ResolveChecks {\n const includeTests = parseBoolEnv(process.env.GH_ROUTER_STOP_GATE_RUN_TESTS) === true\n return async (cwd: string) => {\n const root = await repoRoot(cwd).catch(() => cwd)\n let descriptor: GateDescriptor | null = null\n if (mode === \"parsed\") {\n descriptor = await parseGateDescriptor(root, { includeTests }).catch(() => null)\n } else {\n const rec = await readDiscoveredGate(root).catch(() => null)\n if (rec) {\n descriptor = {\n kind: \"discovered\",\n checks: rec.checks,\n ecosystem: rec.ecosystem,\n workdir: root,\n evidence: rec.evidence,\n }\n }\n }\n if (!descriptor) return null\n const checks = checksForDescriptor(descriptor)\n if (checks.length === 0) return null\n const descriptorKey = descriptorHash(descriptor)\n const workdir = descriptor.workdir || root\n const token = process.env.GH_ROUTER_STOP_GATE_BASELINE_TOKEN || undefined\n return { checks, workdir, descriptorKey, baselineKey: launchBaselineKey(workdir, descriptorKey, token) }\n }\n}\n\n/** Which dynamic gate mode the launcher armed (sealed → undefined). */\nfunction dynamicMode(): \"parsed\" | \"discovered\" | undefined {\n if (parseBoolEnv(process.env.GH_ROUTER_STOP_GATE_PARSED) === true) return \"parsed\"\n if (parseBoolEnv(process.env.GH_ROUTER_STOP_GATE_DISCOVERED) === true) return \"discovered\"\n return undefined\n}\n\nexport const internalStopHook = defineCommand({\n meta: {\n name: \"internal-stop-hook\",\n description:\n \"Internal: the structural-gate Stop hook. Reads the Claude Code hook payload on stdin, \"\n + \"runs the sealed gate, exits 2 (blocks the stop) on a red gate or gate-weakening diff.\",\n },\n async run() {\n const stdin = readStdin()\n // The advisory review (hook V2) is wired only when it's enabled AND the\n // launcher injected the proxy URL/nonce. It is side-effect-only: the\n // deterministic gate below is unchanged and remains the only blocker.\n const reviewEnabled = stopReviewEnabled() && hookMcpRuntimeFromEnv() !== undefined\n let transcriptPath = \"\"\n let userPrompt = \"\"\n if (reviewEnabled) {\n // Parse the payload once for the transcript pointer + the session id used\n // to look up the user's last prompt (the Stop payload carries no prompt;\n // the UserPromptSubmit hook stashed it). Best-effort — a parse miss just\n // means the reviewer judges against the diff alone.\n try {\n const p: unknown = JSON.parse(stdin)\n if (p && typeof p === \"object\") {\n const obj = p as { transcript_path?: unknown; session_id?: unknown }\n transcriptPath = typeof obj.transcript_path === \"string\" ? obj.transcript_path : \"\"\n const sid = typeof obj.session_id === \"string\" ? obj.session_id : \"\"\n if (sid) {\n userPrompt = (await fileLastPromptStore(stopReviewStateDir()).read(sid).catch(() => null)) ?? \"\"\n }\n }\n } catch {\n /* tolerate a non-JSON stdin */\n }\n }\n\n let decision: { exitCode: 0 | 2; stderr?: string }\n try {\n const timeoutEnv = parseIntEnv(process.env.GH_ROUTER_STOP_GATE_TIMEOUT_MS)\n const mode = dynamicMode()\n decision = await decideStopHook({\n stdin,\n gateId: stopGateId(),\n exec: liveExec,\n captureDiff: captureStopGateDiff,\n fallbackCwd: process.cwd(),\n budget: fileBlockBudget(path.join(tmpdir(), \"gh-router-stopgate\")),\n baseline: fileBaselineStore(path.join(tmpdir(), \"gh-router-stopgate-baseline\")),\n isEnabledForRepo: (cwd) => stopGateEnabledForRepo(cwd),\n resolveChecks: mode ? buildResolveChecks(mode) : undefined,\n // parseIntEnv already rejects non-positive / non-integer / truncating\n // values, so undefined here means \"use the built-in default\".\n timeoutMs: timeoutEnv,\n reviewDebounce: reviewEnabled ? fileReviewDebounce(stopReviewStateDir()) : undefined,\n spawnReview: reviewEnabled\n ? (ctx) => spawnStopReview(ctx, { prompt: userPrompt, transcriptPath })\n : undefined,\n })\n } catch {\n // Fail OPEN on ANY unexpected error: a Stop hook must never wedge the\n // session, so an internal crash allows the stop (exit 0) rather than\n // surfacing a non-blocking error or a hang.\n process.exitCode = 0\n return\n }\n // Write any stderr the decision carries — both the exit-2 block reason AND\n // the LOUD exit-0 stand-down (max-block budget reached). A clean green stop\n // carries no stderr, so this stays silent on the common path.\n if (decision.stderr) {\n await writeStderr(`${decision.stderr}\\n`)\n }\n // Natural exit: set the code and return. A hard process.exit() races libuv's\n // stdio teardown on Windows (uv_async_send assertion) on the fast-return\n // paths. The detached review child is unref'd and the gate's children are\n // reaped, so no handle keeps the loop alive — the process exits with this\n // code. The exit-2 block contract is preserved (stderr is flushed above).\n process.exitCode = decision.exitCode\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,SAAS,YAAoB;CAC3B,IAAI;EACF,IAAI,QAAQ,MAAM,OAAO,OAAO;EAChC,OAAO,aAAa,GAAG,MAAM;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;;AAIA,MAAM,iBAAiB;;;AAIvB,eAAe,qBAAqB,KAAa,OAAkC;CACjF,MAAM,SAAmB,CAAC;CAC1B,IAAI,QAAQ;CACZ,KAAK,MAAM,iBAAiB,OAAO;EACjC,MAAM,SAAS,MAAM,kBACnB;GAAC;GAAO;GAAQ;GAAc;GAAM;GAAa;EAAa,GAC9D;GAAE;GAAK,WAAW;GAAO,gBAAgB;EAAe,CAC1D;EAGA,IAAI,OAAO,SAAS,KAAK,OAAO,WAAW,MAAM,IAAI,MAAM,gDAAgD,OAAO,MAAM;EACxH,SAAS,OAAO,WAAW,OAAO,QAA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,IAAI;IACzB,QAAQ,gBAAgB,KAAK,KAAK,OAAO,GAAG,oBAAoB,CAAC;IACjE,UAAU,kBAAkB,KAAK,KAAK,OAAO,GAAG,6BAA6B,CAAC;IAC9E,mBAAmB,QAAQ,uBAAuB,GAAG;IACrD,eAAe,OAAO,mBAAmB,IAAI,IAAI,KAAA;IAGjD,WAAW;IACX,gBAAgB,gBAAgB,mBAAmB,mBAAmB,CAAC,IAAI,KAAA;IAC3E,aAAa,iBACR,QAAQ,gBAAgB,KAAK;KAAE,QAAQ;KAAY;IAAe,CAAC,IACpE,KAAA;GACN,CAAC;EACH,QAAQ;GAIN,QAAQ,WAAW;GACnB;EACF;EAIA,IAAI,SAAS,QACX,MAAM,YAAY,GAAG,SAAS,OAAO,GAAG;EAO1C,QAAQ,WAAW,SAAS;CAC9B;AACF,CAAC"}
package/dist/main.js CHANGED
@@ -47,15 +47,15 @@ const main = defineCommand({
47
47
  },
48
48
  subCommands: {
49
49
  auth: () => import("./auth-xgFZGZbf.js").then((m) => m.auth),
50
- start: () => import("./start-Gs4jAwUR.js").then((m) => m.start),
51
- claude: () => import("./claude-Dw4V8o8l.js").then((m) => m.claude),
52
- codex: () => import("./codex-CXOpv4WP.js").then((m) => m.codex),
53
- serve: () => import("./serve-fJWhiivo.js").then((m) => m.serve),
50
+ start: () => import("./start-CY1nnbB4.js").then((m) => m.start),
51
+ claude: () => import("./claude-C3-yBGzw.js").then((m) => m.claude),
52
+ codex: () => import("./codex-C3hcVSOm.js").then((m) => m.codex),
53
+ serve: () => import("./serve-C3LCkM-o.js").then((m) => m.serve),
54
54
  models: () => import("./models-BjCRO0AC.js").then((m) => m.models),
55
55
  "check-usage": () => import("./check-usage-vUDk6oV7.js").then((m) => m.checkUsage),
56
- index: () => import("./index-cmd-DUjQs9zw.js").then((m) => m.indexCmd),
56
+ index: () => import("./index-cmd-k3oWl0n4.js").then((m) => m.indexCmd),
57
57
  debug: () => import("./debug-a737qcCC.js").then((m) => m.debug),
58
- "internal-stop-hook": () => import("./internal-stop-hook-CH9SKjZ9.js").then((m) => m.internalStopHook),
58
+ "internal-stop-hook": () => import("./internal-stop-hook-DBrlosd0.js").then((m) => m.internalStopHook),
59
59
  "internal-prompt-submit": () => import("./internal-prompt-submit-CD0UFkT-.js").then((m) => m.internalPromptSubmit),
60
60
  "internal-stop-review": () => import("./internal-stop-review-a3rpzzhd.js").then((m) => m.internalStopReview),
61
61
  "internal-plan-review": () => import("./internal-plan-review-O2dwnQv3.js").then((m) => m.internalPlanReview),
@@ -1,4 +1,4 @@
1
- import { C as searchCode, D as recommendedRgThreads, E as isSensitivePath, S as resolveRipgrep, T as confineToWorkspaceResult, _ as colbertSmokeOk, a as kickBackgroundInit, f as gitState, g as colbertArtifactsPresent, i as serviceBackendEnabled, k as outlineFile, m as readColbertMeta, o as runSemanticSearch, s as startupKickAllowed, t as runServiceSearch, v as provisionColbert } from "./service-backend-DYEPoszR.js";
1
+ import { A as confineToWorkspaceResult, C as provisionColbert, D as resolveRipgrep, M as recommendedRgThreads, O as searchCode, P as outlineFile, S as colbertSmokeOk, _ as gitState, d as runSemanticSearch, f as startupKickAllowed, j as isSensitivePath, o as serviceBackendEnabled, r as runServiceSearch, u as kickBackgroundInit, x as colbertArtifactsPresent, y as readColbertMeta } from "./service-backend-ByT0gUc8.js";
2
2
  import { n as explicitPackageRoot } from "./package-root-B-osctCk.js";
3
3
  import { t as getPackageVersion } from "./version-C8x2hQrZ.js";
4
4
  import { t as PATHS } from "./paths-P5ajjpzU.js";
@@ -33032,4 +33032,4 @@ function enumerateInjectedMcpToolNames(groupKeys, opts = {}) {
33032
33032
  //#endregion
33033
33033
  export { EFFORT_ORDER as $, MAX_RESPONSE_BODY_BYTES as $t, TOOLBELT_TOOLS$1 as A, withOneMSuffix as An, implementerFastModel as At, resolveAdvisorEffort as B, CHEAPEST_PROFILE_NATIVE_EFFORTS as Bn, countTokens as Bt, runWorkerAgent as C, pickClaudeDefault as Cn, fastOracleModel as Ct, toolbeltEnabled as D, classifyMessagesRoute as Dn, fleetToolsEnabled as Dt, buildToolbeltAwareness as E, upstreamMaxConnections as En, fastScoutModel as Et, ADVISOR_TOOL_INSTRUCTIONS as F, BALANCED_PROFILE_NATIVE_MODELS as Fn, scoutModel as Ft, repairKnownThinkingHistory as G, CHEAP_PROFILE_NATIVE_AGENT_NAMES as Gn, findLaunchBySecret as Gt, resolveCheapestAdvisorModel as H, CHEAPEST_PROFILE_SUBAGENT_CONTEXT_TOKENS as Hn, getTextTokenCount as Ht, FAST_ADVISOR_TOOL_INSTRUCTIONS as I, BALANCED_PROFILE_SUBAGENT_CONTEXT_TOKENS as In, scribeModel as It, buildOpenAIErrorEvent as J, CHEAP_PROFILE_SUBAGENT_CONTEXT_TOKENS as Jn, assembleResponsesPayload as Jt, repairRejectedThinkingHistory as K, CHEAP_PROFILE_NATIVE_EFFORTS as Kn, registerLaunch as Kt, buildAdvisorStream as L, CHEAPEST_PROFILE_ADVISOR_CLIENT_MODEL as Ln, standInToolEnabled as Lt, satisfiesMinVersion as M, BALANCED_PROFILE_MODELS as Mn, resolveGeminiReviewModel as Mt, searchWeb as N, BALANCED_PROFILE_NATIVE_AGENT_NAMES as Nn, reviewerFastModel as Nt, toolbeltSkipSet as O, catalogAdvertises1M as On, geminiAvailable as Ot, ADVISOR_INTERNAL_TOOL_NAME as P, BALANCED_PROFILE_NATIVE_EFFORTS as Pn, reviewerModel as Pt, relayAnthropicStream as Q, createChatCompletions as Qt, injectAdvisorTool as R, CHEAPEST_PROFILE_MODELS as Rn, workerToolsEnabled as Rt, resolveWorkerRunOpts as S, isBudgetClaudeLead as Sn, fastGeneralPurposeModel as St, availableToolCommands as T, upstreamAllowH2 as Tn, fastReviewerModel as Tt, formatThinkingRepairDecline as U, CHEAP_PROFILE_ADVISOR_CLIENT_MODEL as Un, getTokenCount as Ut, resolveAdvisorModel as V, CHEAPEST_PROFILE_NATIVE_MODELS as Vn, createMessages as Vt, rememberThinkingHistoryRepair as W, CHEAP_PROFILE_MODELS as Wn, getTokenizerFromModel as Wt, logStreamError as X, resolveMcpToolTimeoutMs as Xt, isControllerClosedError as Y, warnOnTokenPriceDrift as Yt, readIteratorWithTimeout as Z, createResponses as Zt, REVIEW_DEFAULT_MODEL as _, DEFAULT_CODEX_MODEL_FALLBACKS as _n, cheapestAdvisorModel as _t, buildAgentPrompt as a, colbertDegradedWarning as an, agentToolsEnabled as at, resolveDefaultModel as b, UPSTREAM_INACTIVITY_TIMEOUT_MS as bn, fastAdvisorModel as bt, enumerateInjectedMcpToolNames as c, CONDENSED_OPERATING_SEQUENCE as cn, balancedOracleModel as ct, BROWSE_DEFAULT_MODEL as d, collapsePathKeys as dn, browseAgentEnabled as dt, readResponseBodyCapped as en, UNKNOWN_EFFORT_ANCHOR as et, DEFAULT_MODEL_CHAIN as f, toolbeltPathOverride as fn, browserCompoundToolsEnabled as ft, PLAN_DEFAULT_MODEL as g, DEFAULT_CODEX_MODEL as gn, cheapReviewerModel as gt, IMPLEMENT_DEFAULT_MODEL as h, DEFAULT_CLAUDE_MODEL_FALLBACKS as hn, cheapOracleModel as ht, assertMcpToolSurfaceConsistent as i, hasSupportedBrowserInstalled as in, handleMcpPost as it, assetFor as j, withOneMSuffixForLead as jn, nativeSubagentModel as jt, vscodeRipgrepPath as k, oneMContextDisabled as kn, generalPurposeFastModel as kt, maxPersonasFor as l, DEFINITION_OF_GREATNESS as ln, balancedReviewerModel as lt, EXPLORE_DEFAULT_THINKING as m, BUDGET_SMALL_FAST_SLUG as mn, cheapAdvisorModel as mt, MCP_GROUPS as n, normalizeOpenAIUsage as nn, clampEffort as nt, buildPeerAwarenessSnippet as o, provisionAndIndexColbert as on, artifactToolsEnabled as ot, EXPLORE_DEFAULT_MODEL as p, BUDGET_SMALL_FAST_CATALOG_ID as pn, browserToolsEnabled as pt, buildAnthropicErrorEvent as q, CHEAP_PROFILE_NATIVE_MODELS as qn, unregisterLaunch as qt, agentNamesForToolAllowlist as r, provisionBrowserAssets as rn, handleMcpDelete as rt, buildPeerAwarenessSummary as s, semanticSearchOptedIn as sn, balancedAdvisorModel as st, GROUP_META as t, parseJsonOrDiagnose as tn, bucketEffort as tt, personasFor as u, shouldUseInsecureTls as un, brainstormModel as ut, TEST_DEFAULT_MODEL as v, DEFAULT_PORT as vn, cheapestOracleModel as vt, buildEnv as w, resolveLeadSlugArg as wn, fastPlanModel as wt, resolveModeDefaults as x, generateRandomPort as xn, fastAstraModel as xt, appendPlanReminder as y, UPSTREAM_FETCH_TIMEOUT_MS as yn, cheapestReviewerModel as yt, isAdvisorRequested as z, CHEAPEST_PROFILE_NATIVE_AGENT_NAMES as zn, shimDefaultsToXhigh as zt };
33034
33034
 
33035
- //# sourceMappingURL=peer-mcp-personas-CnYMTizo.js.map
33035
+ //# sourceMappingURL=peer-mcp-personas-Dztywua2.js.map