github-router 0.3.329 → 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.
- package/dist/{attribution-settings-B7ShuykF.js → attribution-settings-7dFpObGh.js} +138 -93
- package/dist/attribution-settings-7dFpObGh.js.map +1 -0
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{claude-mRxETPzg.js → claude-C3-yBGzw.js} +14 -11
- package/dist/{claude-mRxETPzg.js.map → claude-C3-yBGzw.js.map} +1 -1
- package/dist/{codex-DFw8NKp1.js → codex-C3hcVSOm.js} +5 -5
- package/dist/{codex-DFw8NKp1.js.map → codex-C3hcVSOm.js.map} +1 -1
- package/dist/engine-CPdWX70n.js +2 -0
- package/dist/{gate-discovery-Dkmfcujh.js → gate-discovery-BUhtwkyE.js} +2 -2
- package/dist/{gate-discovery-Dkmfcujh.js.map → gate-discovery-BUhtwkyE.js.map} +1 -1
- package/dist/{hook-mcp-client-DBvm9608.js → hook-mcp-client-DbFtxo6_.js} +6 -5
- package/dist/hook-mcp-client-DbFtxo6_.js.map +1 -0
- package/dist/hooks.mjs +46 -15
- package/dist/hooks.sha256 +1 -1
- package/dist/index-cmd-k3oWl0n4.js +330 -0
- package/dist/index-cmd-k3oWl0n4.js.map +1 -0
- package/dist/{internal-plan-review-DM-Zycyn.js → internal-plan-review-O2dwnQv3.js} +3 -3
- package/dist/{internal-plan-review-DM-Zycyn.js.map → internal-plan-review-O2dwnQv3.js.map} +1 -1
- package/dist/{internal-prompt-submit-6AKy89nq.js → internal-prompt-submit-CD0UFkT-.js} +11 -8
- package/dist/internal-prompt-submit-CD0UFkT-.js.map +1 -0
- package/dist/{internal-stop-hook-D0m7aRJ4.js → internal-stop-hook-DBrlosd0.js} +3 -3
- package/dist/{internal-stop-hook-D0m7aRJ4.js.map → internal-stop-hook-DBrlosd0.js.map} +1 -1
- package/dist/{internal-stop-review-CPk66wwo.js → internal-stop-review-a3rpzzhd.js} +9 -9
- package/dist/internal-stop-review-a3rpzzhd.js.map +1 -0
- package/dist/main.js +9 -9
- package/dist/{peer-mcp-personas-C5WQdw7V.js → peer-mcp-personas-Dztywua2.js} +147 -64
- package/dist/{peer-mcp-personas-C5WQdw7V.js.map → peer-mcp-personas-Dztywua2.js.map} +1 -1
- package/dist/{plan-review-hook-ChuywYy_.js → plan-review-hook-CfZBvsHd.js} +2 -2
- package/dist/{plan-review-hook-ChuywYy_.js.map → plan-review-hook-CfZBvsHd.js.map} +1 -1
- package/dist/{prompt-submit-hook-C0ZospPT.js → prompt-submit-hook-CRH6m7Vz.js} +33 -12
- package/dist/prompt-submit-hook-CRH6m7Vz.js.map +1 -0
- package/dist/{provision-B96yW3ax.js → provision-CjBt5wEK.js} +3 -3
- package/dist/{provision-B96yW3ax.js.map → provision-CjBt5wEK.js.map} +1 -1
- package/dist/{serve-BOqxpa24.js → serve-C3LCkM-o.js} +11 -9
- package/dist/serve-C3LCkM-o.js.map +1 -0
- package/dist/{server-setup-DCp30g9w.js → server-setup-DrSUlFZ_.js} +4 -4
- package/dist/{server-setup-DCp30g9w.js.map → server-setup-DrSUlFZ_.js.map} +1 -1
- package/dist/{service-backend-DYEPoszR.js → service-backend-ByT0gUc8.js} +405 -19
- package/dist/{service-backend-DYEPoszR.js.map → service-backend-ByT0gUc8.js.map} +1 -1
- package/dist/{start-CQduw8RP.js → start-CY1nnbB4.js} +4 -4
- package/dist/{start-CQduw8RP.js.map → start-CY1nnbB4.js.map} +1 -1
- package/package.json +1 -1
- package/dist/attribution-settings-B7ShuykF.js.map +0 -1
- package/dist/engine-Y2BmXHF9.js +0 -2
- package/dist/hook-mcp-client-DBvm9608.js.map +0 -1
- package/dist/index-cmd-DUjQs9zw.js +0 -182
- package/dist/index-cmd-DUjQs9zw.js.map +0 -1
- package/dist/internal-prompt-submit-6AKy89nq.js.map +0 -1
- package/dist/internal-stop-review-CPk66wwo.js.map +0 -1
- package/dist/prompt-submit-hook-C0ZospPT.js.map +0 -1
- package/dist/serve-BOqxpa24.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,MAA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AAE;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"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { n as explicitPackageRoot, t as PACKAGE_ROOT_FLAG } from "./package-root-B-osctCk.js";
|
|
2
2
|
import { n as fileFindingsStore, u as stopReviewStateDir } from "./stop-gate-policy-D6jIeOXB.js";
|
|
3
|
-
import { r as hookMcpRuntimeFromEnv } from "./hook-mcp-client-
|
|
4
|
-
import { a as runPlanReview, n as decidePlanReviewHook, r as filePlanReviewDebounce } from "./plan-review-hook-
|
|
3
|
+
import { r as hookMcpRuntimeFromEnv } from "./hook-mcp-client-DbFtxo6_.js";
|
|
4
|
+
import { a as runPlanReview, n as decidePlanReviewHook, r as filePlanReviewDebounce } from "./plan-review-hook-CfZBvsHd.js";
|
|
5
5
|
import { defineCommand } from "citty";
|
|
6
6
|
import { mkdirSync, promises, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
7
7
|
import path from "node:path";
|
|
@@ -118,4 +118,4 @@ const internalPlanReview = defineCommand({
|
|
|
118
118
|
//#endregion
|
|
119
119
|
export { internalPlanReview };
|
|
120
120
|
|
|
121
|
-
//# sourceMappingURL=internal-plan-review-
|
|
121
|
+
//# sourceMappingURL=internal-plan-review-O2dwnQv3.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal-plan-review-
|
|
1
|
+
{"version":3,"file":"internal-plan-review-O2dwnQv3.js","names":["fs"],"sources":["../src/internal-plan-review.ts"],"sourcesContent":["/**\n * The internal `internal-plan-review` subcommand: a PostToolUse(ExitPlanMode)\n * hook that spawns a bounded advisory critic review when the main agent finalizes\n * a substantive plan.\n *\n * It never blocks ExitPlanMode: the hook process exits 0 quickly after deciding\n * whether to spawn a detached reviewer. The detached child calls a cross-lab plan\n * critic and writes material findings to the SAME per-session findings store used\n * by the Stop review, so the next UserPromptSubmit surfaces them with the existing\n * non-authoritative findings path.\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 { promises as fs } from \"node:fs\"\nimport path from \"node:path\"\n\nimport { PACKAGE_ROOT_FLAG, explicitPackageRoot } from \"./lib/package-root\"\n\nimport { hookMcpRuntimeFromEnv } from \"./lib/orchestration/hook-mcp-client\"\nimport {\n decidePlanReviewHook,\n filePlanReviewDebounce,\n runPlanReview,\n type PlanReviewSpawnContext,\n} from \"./lib/orchestration/plan-review-hook\"\nimport { fileFindingsStore, stopReviewStateDir } from \"./lib/orchestration/stop-gate-policy\"\n\nfunction readStdin(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\nasync function readDetachedPayload(): Promise<PlanReviewSpawnContext | undefined> {\n const payloadPath = (process.env.GH_ROUTER_PLAN_REVIEW_PAYLOAD ?? \"\").trim()\n if (payloadPath.length === 0) return undefined\n try {\n const raw = await fs.readFile(payloadPath, \"utf8\")\n await fs.unlink(payloadPath).catch(() => {})\n const parsed: unknown = JSON.parse(raw)\n if (!parsed || typeof parsed !== \"object\") return undefined\n const p = parsed as Partial<PlanReviewSpawnContext>\n if (!p.sessionId || !p.cwd || !p.plan || !p.planHash) return undefined\n return { sessionId: p.sessionId, cwd: p.cwd, plan: p.plan, planHash: p.planHash }\n } catch {\n await fs.unlink(payloadPath).catch(() => {})\n return undefined\n }\n}\n\nfunction spawnDetachedPlanReview(ctx: PlanReviewSpawnContext): void {\n let payloadPath: string | undefined\n try {\n const dir = stopReviewStateDir()\n mkdirSync(dir, { recursive: true })\n payloadPath = path.join(dir, `plan-review-${process.pid}-${randomBytes(4).toString(\"hex\")}.json`)\n writeFileSync(payloadPath, JSON.stringify(ctx), { mode: 0o600 })\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-plan-review\"], {\n detached: true,\n windowsHide: true,\n stdio: \"ignore\",\n env: { ...process.env, GH_ROUTER_PLAN_REVIEW_PAYLOAD: payloadPath },\n })\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 if (payloadPath) {\n try {\n unlinkSync(payloadPath)\n } catch {\n /* best-effort */\n }\n }\n }\n}\n\nexport const internalPlanReview = defineCommand({\n meta: {\n name: \"internal-plan-review\",\n description:\n \"Internal: advisory ExitPlanMode plan reviewer. Spawns a bounded detached critic review \"\n + \"for substantive plans and writes findings for the next prompt. Always exit 0.\",\n },\n async run() {\n try {\n const runtime = hookMcpRuntimeFromEnv()\n if (!runtime) return\n\n const detached = await readDetachedPayload()\n if (detached) {\n await runPlanReview({\n runtime,\n sessionId: detached.sessionId,\n cwd: detached.cwd,\n plan: detached.plan,\n findingsStore: fileFindingsStore(stopReviewStateDir()),\n })\n return\n }\n\n const decision = await decidePlanReviewHook({\n stdin: readStdin(),\n runtimeAvailable: true,\n debounce: filePlanReviewDebounce(stopReviewStateDir()),\n fallbackCwd: process.cwd(),\n })\n if (decision.kind === \"spawn\") spawnDetachedPlanReview(decision)\n } catch {\n /* side-effect only: never block ExitPlanMode */\n }\n process.exitC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BAAoB;EACjC,MAAM,kBAAkB,OAAO,CAAC,mBAAmB,IAAI,IAAI,CAAC;EAC5D,MAAM,QAAQ,MAAM,QAAQ,UAAU;GAAC,GAAG;GAAY,GAAG;GAAiB;EAAsB,GAAG;GACjG,UAAU;GACV,aAAa;GACb,OAAO;GACP,KAAK;IAAE,GAAG,QAAQ;IAAK,+BAA+B;GAAY;EACpE,CAAC;EACD,MAAM,SAAS;EACf,MAAM,GAAG,eAAe;GACtB,IAAI,QACF,IAAI;IACF,WAAW,MAAM;GACnB,QAAQ,CAER;EAEJ,CAAC;EACD,MAAM,MAAM;CACd,QAAQ;EACN,IAAI,aACF,IAAI;GACF,WAAW,WAAW;EACxB,QAAQ,CAER;CAEJ;AACF;AAEA,MAAa,qBAAqB,cAAc;CAC9C,MAAM;EACJ,MAAM;EACN,aACE;CAEJ;CACA,MAAM,MAAM;EACV,IAAI;GACF,MAAM,UAAU,sBAAsB;GACtC,IAAI,CAAC,SAAS;GAEd,MAAM,WAAW,MAAM,oBAAoB;GAC3C,IAAI,UAAU;IACZ,MAAM,cAAc;KAClB;KACA,WAAW,SAAS;KACpB,KAAK,SAAS;KACd,MAAM,SAAS;KACf,eAAe,kBAAkB,mBAAmB,CAAC;IACvD,CAAC;IACD;GACF;GAEA,MAAM,WAAW,MAAM,qBAAqB;IAC1C,OAAO,UAAU;IACjB,kBAAkB;IAClB,UAAU,uBAAuB,mBAAmB,CAAC;IACrD,aAAa,QAAQ,IAAI;GAC3B,CAAC;GACD,IAAI,SAAS,SAAS,SAAS,wBAAwB,QAAQ;EACjE,QAAQ,CAER;EACA,QAAQ,WAAW;CACrB;AACF,CAAC"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { i as parseBoolEnv } from "./exec-COUT4QsS.js";
|
|
2
2
|
import { o as fileBlockBudget } from "./stop-gate-hook-BACb8dlj.js";
|
|
3
3
|
import { n as fileFindingsStore, r as fileLastPromptStore, u as stopReviewStateDir } from "./stop-gate-policy-D6jIeOXB.js";
|
|
4
|
-
import { n as callMcpTool, r as hookMcpRuntimeFromEnv, t as callInference } from "./hook-mcp-client-
|
|
5
|
-
import { n as decidePromptSubmit, r as decidePromptSubmitV2 } from "./prompt-submit-hook-
|
|
4
|
+
import { n as callMcpTool, r as hookMcpRuntimeFromEnv, t as callInference } from "./hook-mcp-client-DbFtxo6_.js";
|
|
5
|
+
import { n as decidePromptSubmit, r as decidePromptSubmitV2 } from "./prompt-submit-hook-CRH6m7Vz.js";
|
|
6
6
|
import { defineCommand } from "citty";
|
|
7
7
|
import { readFileSync } from "node:fs";
|
|
8
8
|
import path from "node:path";
|
|
@@ -16,9 +16,10 @@ import { tmpdir } from "node:os";
|
|
|
16
16
|
* 1. resets the Stop-gate's per-session block budget (making `maxBlocks`
|
|
17
17
|
* per-prompt);
|
|
18
18
|
* 2. stashes the prompt + surfaces the prior turn's advisory review findings;
|
|
19
|
-
*
|
|
20
|
-
* note (one gpt-5.6-
|
|
21
|
-
* search
|
|
19
|
+
* 3. for a non-trivial prompt, injects a GROUNDED, user-derived scope/goal
|
|
20
|
+
* note (one gpt-5.6-luna call at high effort over the prompt + grounding
|
|
21
|
+
* code search — semantic-first when --search is on, lexical-only
|
|
22
|
+
* otherwise) — or, when the proxy URL/nonce isn't wired or anything errors,
|
|
22
23
|
* falls open to the v1 regex goal.
|
|
23
24
|
*
|
|
24
25
|
* ALWAYS exits 0 (never blocks the prompt): the steer is additive context, and a
|
|
@@ -66,6 +67,7 @@ const internalPromptSubmit = defineCommand({
|
|
|
66
67
|
try {
|
|
67
68
|
const stdin = readStdin();
|
|
68
69
|
const steerEnabled = parseBoolEnv(process.env.GH_ROUTER_DISABLE_PROMPT_STEER) !== true;
|
|
70
|
+
const searchEnabled = process.env.GH_ROUTER_SEARCH_ENABLED !== void 0 ? process.env.GH_ROUTER_SEARCH_ENABLED === "1" : process.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === "1";
|
|
69
71
|
const runtime = hookMcpRuntimeFromEnv();
|
|
70
72
|
let decision;
|
|
71
73
|
if (runtime) {
|
|
@@ -73,6 +75,7 @@ const internalPromptSubmit = defineCommand({
|
|
|
73
75
|
decision = await decidePromptSubmitV2({
|
|
74
76
|
stdin,
|
|
75
77
|
steerEnabled,
|
|
78
|
+
searchEnabled,
|
|
76
79
|
io: {
|
|
77
80
|
searchCode: async (query, mode, signal) => {
|
|
78
81
|
const r = await callMcpTool({
|
|
@@ -93,10 +96,10 @@ const internalPromptSubmit = defineCommand({
|
|
|
93
96
|
},
|
|
94
97
|
infer: (system, user, signal) => callInference({
|
|
95
98
|
serverUrl: runtime.serverUrl,
|
|
96
|
-
model: "gpt-5.6-
|
|
99
|
+
model: "gpt-5.6-luna",
|
|
97
100
|
instructions: system,
|
|
98
101
|
input: user,
|
|
99
|
-
effort: "
|
|
102
|
+
effort: "high",
|
|
100
103
|
timeoutMs: INFER_TIMEOUT_MS,
|
|
101
104
|
signal
|
|
102
105
|
}),
|
|
@@ -118,4 +121,4 @@ const internalPromptSubmit = defineCommand({
|
|
|
118
121
|
//#endregion
|
|
119
122
|
export { internalPromptSubmit };
|
|
120
123
|
|
|
121
|
-
//# sourceMappingURL=internal-prompt-submit-
|
|
124
|
+
//# sourceMappingURL=internal-prompt-submit-CD0UFkT-.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"internal-prompt-submit-CD0UFkT-.js","names":[],"sources":["../src/internal-prompt-submit.ts"],"sourcesContent":["/**\n * The internal `internal-prompt-submit` subcommand: the executable a spawned\n * Claude Code session's `UserPromptSubmit` hook invokes (registered into the\n * mirrored settings.json by the launcher). It serves the front-end of the\n * floor-raising surface on one event:\n * 1. resets the Stop-gate's per-session block budget (making `maxBlocks`\n * per-prompt);\n * 2. stashes the prompt + surfaces the prior turn's advisory review findings;\n * 3. for a non-trivial prompt, injects a GROUNDED, user-derived scope/goal\n * note (one gpt-5.6-luna call at high effort over the prompt + grounding\n * code search — semantic-first when --search is on, lexical-only\n * otherwise) — or, when the proxy URL/nonce isn't wired or anything errors,\n * falls open to the v1 regex goal.\n *\n * ALWAYS exits 0 (never blocks the prompt): the steer is additive context, and a\n * UserPromptSubmit hook that exit-2'd would refuse the user's prompt. The pure\n * v1 path (`decidePromptSubmit`) is the fail-open fallback; V2\n * (`decidePromptSubmitV2`) layers the grounded enrichment on top via injected IO.\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { readFileSync } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport path from \"node:path\"\n\nimport { parseBoolEnv } from \"./lib/exec\"\nimport { callInference, callMcpTool, hookMcpRuntimeFromEnv } from \"./lib/orchestration/hook-mcp-client\"\nimport { fileBlockBudget } from \"./lib/orchestration/stop-gate-hook\"\nimport {\n decidePromptSubmit,\n decidePromptSubmitV2,\n type PromptSubmitDecision,\n} from \"./lib/orchestration/prompt-submit-hook\"\nimport {\n fileFindingsStore,\n fileLastPromptStore,\n stopReviewStateDir,\n} from \"./lib/orchestration/stop-gate-policy\"\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/** Parse the session cwd from the payload — the workspace the grounding search\n * runs in. Falls back to the process cwd. */\nfunction workspaceFromStdin(stdin: string): string {\n try {\n const p: unknown = JSON.parse(stdin)\n if (p && typeof p === \"object\") {\n const cwd = (p as { cwd?: unknown }).cwd\n if (typeof cwd === \"string\" && cwd.length > 0) return cwd\n }\n } catch {\n /* fall through */\n }\n return process.cwd()\n}\n\n/** Per-call timeout for the grounding search (short — it must not stall the prompt). */\nconst SEARCH_TIMEOUT_MS = 8_000\n/** Per-call timeout for the single scope/goal inference. */\nconst INFER_TIMEOUT_MS = 18_000\n\nexport const internalPromptSubmit = defineCommand({\n meta: {\n name: \"internal-prompt-submit\",\n description:\n \"Internal: the UserPromptSubmit hook. Resets the Stop-gate per-prompt block \"\n + \"budget, surfaces prior-turn review findings, and injects a grounded advisory goal \"\n + \"for non-trivial prompts. Always exit 0.\",\n },\n async run() {\n try {\n const stdin = readStdin()\n const steerEnabled = parseBoolEnv(process.env.GH_ROUTER_DISABLE_PROMPT_STEER) !== true\n // Search capability for tip/enrichment text. The launcher exports\n // GH_ROUTER_SEARCH_ENABLED (\"1\"/\"0\") from its resolved\n // `state.searchEnabled` before spawning the session, so this\n // short-lived hook process inherits the launch's capability even when\n // the opt-in came from the `--search` CLI flag (which otherwise would\n // not survive the process boundary). Falls back to the raw opt-in env\n // for standalone invocations.\n const searchEnabled = process.env.GH_ROUTER_SEARCH_ENABLED !== undefined\n ? process.env.GH_ROUTER_SEARCH_ENABLED === \"1\"\n : process.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === \"1\"\n const runtime = hookMcpRuntimeFromEnv()\n\n let decision: PromptSubmitDecision\n if (runtime) {\n const workspace = workspaceFromStdin(stdin)\n decision = await decidePromptSubmitV2({\n stdin,\n steerEnabled,\n searchEnabled,\n io: {\n searchCode: async (query, mode, signal) => {\n const r = await callMcpTool({\n runtime,\n group: \"search\",\n tool: \"code\",\n args: { query, workspace, mode, limit: 10, summary: false },\n timeoutMs: SEARCH_TIMEOUT_MS,\n signal,\n })\n return r.isError ? \"\" : r.text\n },\n infer: (system, user, signal) =>\n callInference({\n serverUrl: runtime.serverUrl,\n model: \"gpt-5.6-luna\",\n instructions: system,\n input: user,\n effort: \"high\",\n timeoutMs: INFER_TIMEOUT_MS,\n signal,\n }),\n readFindings: (sid) => fileFindingsStore(stopReviewStateDir()).read(sid),\n clearFindings: (sid) => fileFindingsStore(stopReviewStateDir()).clear(sid),\n storePrompt: (sid, prompt) => fileLastPromptStore(stopReviewStateDir()).write(sid, prompt),\n },\n })\n } else {\n // Proxy URL/nonce not wired -> the LLM layer is off; use the pure v1 path.\n decision = decidePromptSubmit({ stdin, steerEnabled })\n }\n\n if (decision.resetSession) {\n // Same budget store the Stop hook uses, so a new prompt clears its count.\n await fileBlockBudget(path.join(tmpdir(), \"gh-router-stopgate\"))\n .reset(decision.resetSession)\n .catch(() => {})\n }\n if (decision.inject.length > 0) {\n await new Promise<void>((resolve) => process.stdout.write(`${decision.inject}\\n`, () => resolve()))\n }\n } catch {\n /* never let the front-end hook disrupt a prompt */\n }\n // Natural exit (exit code 0): a hard process.exit() races libuv stdio teardown\n // on Windows. No handles are kept alive once the (aborted) enrichment settles,\n // so returning lets the process exit cleanly with code 0.\n process.exitCode = 0\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,SAAS,YAAoB;CAC3B,IAAI;EACF,IAAI,QAAQ,MAAM,OAAO,OAAO;EAChC,OAAO,aAAa,GAAG,MAAM;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;;AAIA,SAAS,mBAAmB,OAAuB;CACjD,IAAI;EACF,MAAM,IAAa,KAAK,MAAM,KAAK;EACnC,IAAI,KAAK,OAAO,MAAM,UAAU;GAC9B,MAAM,MAAO,EAAwB;GACrC,IAAI,OAAO,QAAQ,YAAY,IAAI,SAAS,GAAG,OAAO;EACxD;CACF,QAAQ,CAER;CACA,OAAO,QAAQ,IAAI;AACrB;;AAGA,MAAM,oBAAoB;;AAE1B,MAAM,mBAAmB;AAEzB,MAAa,uBAAuB,cAAc;CAChD,MAAM;EACJ,MAAM;EACN,aACE;CAGJ;CACA,MAAM,MAAM;EACV,IAAI;GACF,MAAM,QAAQ,UAAU;GACxB,MAAM,eAAe,aAAa,QAAQ,IAAI,8BAA8B,MAAM;GAQlF,MAAM,gBAAgB,QAAQ,IAAI,6BAA6B,KAAA,IAC3D,QAAQ,IAAI,6BAA6B,MACzC,QAAQ,IAAI,qCAAqC;GACrD,MAAM,UAAU,sBAAsB;GAEtC,IAAI;GACJ,IAAI,SAAS;IACX,MAAM,YAAY,mBAAmB,KAAK;IAC1C,WAAW,MAAM,qBAAqB;KACpC;KACA;KACA;KACA,IAAI;MACF,YAAY,OAAO,OAAO,MAAM,WAAW;OACzC,MAAM,IAAI,MAAM,YAAY;QAC1B;QACA,OAAO;QACP,MAAM;QACN,MAAM;SAAE;SAAO;SAAW;SAAM,OAAO;SAAI,SAAS;QAAM;QAC1D,WAAW;QACX;OACF,CAAC;OACD,OAAO,EAAE,UAAU,KAAK,EAAE;MAC5B;MACA,QAAQ,QAAQ,MAAM,WACpB,cAAc;OACZ,WAAW,QAAQ;OACnB,OAAO;OACP,cAAc;OACd,OAAO;OACP,QAAQ;OACR,WAAW;OACX;MACF,CAAC;MACH,eAAe,QAAQ,kBAAkB,mBAAmB,CAAC,CAAC,CAAC,KAAK,GAAG;MACvE,gBAAgB,QAAQ,kBAAkB,mBAAmB,CAAC,CAAC,CAAC,MAAM,GAAG;MACzE,cAAc,KAAK,WAAW,oBAAoB,mBAAmB,CAAC,CAAC,CAAC,MAAM,KAAK,MAAM;KAC3F;IACF,CAAC;GACH,OAEE,WAAW,mBAAmB;IAAE;IAAO;GAAa,CAAC;GAGvD,IAAI,SAAS,cAEX,MAAM,gBAAgB,KAAK,KAAK,OAAO,GAAG,oBAAoB,CAAC,CAAC,CAC7D,MAAM,SAAS,YAAY,CAAC,CAC5B,YAAY,CAAC,CAAC;GAEnB,IAAI,SAAS,OAAO,SAAS,GAC3B,MAAM,IAAI,SAAe,YAAY,QAAQ,OAAO,MAAM,GAAG,SAAS,OAAO,WAAW,QAAQ,CAAC,CAAC;EAEtG,QAAQ,CAER;EAIA,QAAQ,WAAW;CACrB;AACF,CAAC"}
|
|
@@ -3,8 +3,8 @@ import { a as parseIntEnv, i as parseBoolEnv, s as runCommandCapture } from "./e
|
|
|
3
3
|
import { a as decideStopHook, c as launchBaselineKey, d as stopGateId, f as stopReviewEnabled, o as fileBlockBudget } from "./stop-gate-hook-BACb8dlj.js";
|
|
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
|
-
import { r as hookMcpRuntimeFromEnv } from "./hook-mcp-client-
|
|
7
|
-
import { a as checksForDescriptor, n as readDiscoveredGate, o as descriptorHash, s as parseGateDescriptor } from "./gate-discovery-
|
|
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-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-
|
|
260
|
+
//# sourceMappingURL=internal-stop-hook-DBrlosd0.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal-stop-hook-D0m7aRJ4.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;;;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M,MAAM,OAAO,IAAI,eAAe,WAAW,IAAI,aAAa;IAClE,IAAI,KACF,aAAc,MAAM,oBAAoB,mBAAmB,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,YAAY,IAAI,KAAM;GAElG;EACF,QAAQ,CAER;EAGF,IAAI;EACJ,IAAI;GACF,MAAM,aAAa,YAAY,QAAQ,IAAI,8BAA8B;GACzE,MAAM,OAAO,YAAY;GACzB,WAAW,MAAM,eAAe;IAC9B;IACA,QAAQ,WAAW;IACnB,MAAM;IACN,aAAa;IACb,aAAa,QAAQ,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"}
|
|
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,GAA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