github-router 0.3.347 → 0.3.349

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 (63) hide show
  1. package/dist/{aic-statusline-settings-YoDG20pq.js → aic-statusline-settings-DCFywz3N.js} +2 -2
  2. package/dist/aic-statusline-settings-DCFywz3N.js.map +1 -0
  3. package/dist/{attribution-settings-50S3mk4N.js → attribution-settings-BgYkynRc.js} +30 -18
  4. package/dist/attribution-settings-BgYkynRc.js.map +1 -0
  5. package/dist/browser-ext/manifest.json +1 -1
  6. package/dist/{claude-D0rojAcX.js → claude-Chtd07VA.js} +32 -16
  7. package/dist/claude-Chtd07VA.js.map +1 -0
  8. package/dist/{codex-kcdKpoOe.js → codex-DayPQ8t5.js} +4 -4
  9. package/dist/{codex-kcdKpoOe.js.map → codex-DayPQ8t5.js.map} +1 -1
  10. package/dist/engine-T81FYVwK.js +2 -0
  11. package/dist/{gate-discovery-CzZ5Oc3H.js → gate-discovery-CBOPoK9-.js} +4 -4
  12. package/dist/{gate-discovery-CzZ5Oc3H.js.map → gate-discovery-CBOPoK9-.js.map} +1 -1
  13. package/dist/hooks.mjs +684 -14
  14. package/dist/hooks.sha256 +1 -1
  15. package/dist/{internal-aic-status-CCvU7zhC.js → internal-aic-status-lM0YNDaH.js} +52 -11
  16. package/dist/internal-aic-status-lM0YNDaH.js.map +1 -0
  17. package/dist/{internal-artifact-open-lta2UPnE.js → internal-artifact-open-CXJbMXpq.js} +2 -2
  18. package/dist/{internal-artifact-open-lta2UPnE.js.map → internal-artifact-open-CXJbMXpq.js.map} +1 -1
  19. package/dist/{internal-plan-review-B4f0dpss.js → internal-plan-review-F-WbltsT.js} +3 -3
  20. package/dist/{internal-plan-review-B4f0dpss.js.map → internal-plan-review-F-WbltsT.js.map} +1 -1
  21. package/dist/internal-prompt-submit-DRCJ5kWC.js +559 -0
  22. package/dist/internal-prompt-submit-DRCJ5kWC.js.map +1 -0
  23. package/dist/{internal-session-bind-IpZ5hJzR.js → internal-session-bind-LrYEo-kg.js} +2 -2
  24. package/dist/{internal-session-bind-IpZ5hJzR.js.map → internal-session-bind-LrYEo-kg.js.map} +1 -1
  25. package/dist/{internal-stop-hook-BdVV3NyD.js → internal-stop-hook-CIe2kVss.js} +5 -5
  26. package/dist/{internal-stop-hook-BdVV3NyD.js.map → internal-stop-hook-CIe2kVss.js.map} +1 -1
  27. package/dist/{internal-stop-review-C7bOxX1q.js → internal-stop-review-nL003JIj.js} +2 -2
  28. package/dist/{internal-stop-review-C7bOxX1q.js.map → internal-stop-review-nL003JIj.js.map} +1 -1
  29. package/dist/main.js +12 -12
  30. package/dist/{orchestration-Ccmfslh4.js → orchestration-DjuJRhXn.js} +2 -2
  31. package/dist/{orchestration-Ccmfslh4.js.map → orchestration-DjuJRhXn.js.map} +1 -1
  32. package/dist/{peer-mcp-personas-DlmmbpD6.js → peer-mcp-personas-agpBeTgS.js} +258 -52
  33. package/dist/peer-mcp-personas-agpBeTgS.js.map +1 -0
  34. package/dist/{pi-07uTIAcP.js → pi-BLDBFXg3.js} +5 -5
  35. package/dist/{pi-07uTIAcP.js.map → pi-BLDBFXg3.js.map} +1 -1
  36. package/dist/{plan-review-hook-BTvxvCCo.js → plan-review-hook-DMqPHBBN.js} +2 -2
  37. package/dist/{plan-review-hook-BTvxvCCo.js.map → plan-review-hook-DMqPHBBN.js.map} +1 -1
  38. package/dist/prompt-submit-hook-CBGlhEpU.js +411 -0
  39. package/dist/prompt-submit-hook-CBGlhEpU.js.map +1 -0
  40. package/dist/{provision-D_rmmqTq.js → provision-BKdrO1Sv.js} +2 -2
  41. package/dist/{provision-D_rmmqTq.js.map → provision-BKdrO1Sv.js.map} +1 -1
  42. package/dist/{serve-DbrYa6zo.js → serve-p_58sDJK.js} +8 -8
  43. package/dist/{serve-DbrYa6zo.js.map → serve-p_58sDJK.js.map} +1 -1
  44. package/dist/{server-setup-CKhj8I0W.js → server-setup-PAHohZ-u.js} +86 -33
  45. package/dist/server-setup-PAHohZ-u.js.map +1 -0
  46. package/dist/{start-BXVrchgI.js → start-CTHcqkQL.js} +3 -3
  47. package/dist/{start-BXVrchgI.js.map → start-CTHcqkQL.js.map} +1 -1
  48. package/dist/{stop-gate-hook-DZVfKoSh.js → stop-gate-hook-DRcYQAtf.js} +2 -2
  49. package/dist/{stop-gate-hook-DZVfKoSh.js.map → stop-gate-hook-DRcYQAtf.js.map} +1 -1
  50. package/dist/{stop-gate-policy-Gd_cNT9-.js → stop-gate-policy-CbLklfV2.js} +21 -2
  51. package/dist/{stop-gate-policy-Gd_cNT9-.js.map → stop-gate-policy-CbLklfV2.js.map} +1 -1
  52. package/package.json +1 -1
  53. package/dist/aic-statusline-settings-YoDG20pq.js.map +0 -1
  54. package/dist/attribution-settings-50S3mk4N.js.map +0 -1
  55. package/dist/claude-D0rojAcX.js.map +0 -1
  56. package/dist/engine-BWxxbsSu.js +0 -2
  57. package/dist/internal-aic-status-CCvU7zhC.js.map +0 -1
  58. package/dist/internal-prompt-submit-DGxv_Vgl.js +0 -127
  59. package/dist/internal-prompt-submit-DGxv_Vgl.js.map +0 -1
  60. package/dist/peer-mcp-personas-DlmmbpD6.js.map +0 -1
  61. package/dist/prompt-submit-hook-BeLUDy_m.js +0 -173
  62. package/dist/prompt-submit-hook-BeLUDy_m.js.map +0 -1
  63. package/dist/server-setup-CKhj8I0W.js.map +0 -1
@@ -0,0 +1,559 @@
1
+ import { i as parseBoolEnv } from "./exec-MCU1H-KZ.js";
2
+ import { o as fileBlockBudget } from "./stop-gate-hook-DRcYQAtf.js";
3
+ import { a as fileRewriteFlagStore, d as stopReviewStateDir, n as fileFindingsStore, r as fileLastPromptStore } from "./stop-gate-policy-CbLklfV2.js";
4
+ import { n as callMcpTool, r as hookMcpRuntimeFromEnv, t as callInference } from "./hook-mcp-client-BRL_y-bz.js";
5
+ import { a as CHEAPEST_REWRITE_GUIDANCE_CAP, c as isCheapestRewriteDisabledEnv, i as CHEAPEST_REWRITE_EFFORT, n as decidePromptSubmit, o as CHEAPEST_REWRITE_MODEL, r as decidePromptSubmitV2, s as CHEAPEST_REWRITE_STRUCTURE_CAP } from "./prompt-submit-hook-CBGlhEpU.js";
6
+ import { defineCommand } from "citty";
7
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
8
+ import path from "node:path";
9
+ import { tmpdir } from "node:os";
10
+ //#region src/internal-prompt-submit.ts
11
+ /**
12
+ * The internal `internal-prompt-submit` subcommand: the executable a spawned
13
+ * Claude Code session's `UserPromptSubmit` hook invokes (registered into the
14
+ * mirrored settings.json by the launcher). It serves the front-end of the
15
+ * floor-raising surface on one event:
16
+ * 1. resets the Stop-gate's per-session block budget (making `maxBlocks`
17
+ * per-prompt);
18
+ * 2. stashes the prompt + surfaces the prior turn's advisory review findings;
19
+ * 3. for a non-trivial prompt, injects a GROUNDED, user-derived scope/goal
20
+ * note (one gpt-6-luna call at high effort over the prompt + grounding
21
+ * code search — local ColBERT when --search is on, Bluebird when
22
+ * --bluebird is on, lexical-only otherwise) — or, when the proxy URL/nonce
23
+ * isn't wired or anything errors,
24
+ * falls open to the v1 regex goal.
25
+ * 4. on a cheapest-profile launch only, tries FIRST a Sol (gpt-5.6-sol,
26
+ * medium) rewrite of the prompt into a short structured EXECUTION BRIEF over
27
+ * the prompt + AGENTS.md/CLAUDE.md + repo structure + ecosystem's verify
28
+ * command + grounding search
29
+ * (adaptive 3 turns, up to 5 on Sol's deep-grounding flag) — additive,
30
+ * never replacing the user prompt — and falls back to (3) on any miss.
31
+ * One-shot per session (first non-trivial prompt only, marked on
32
+ * attempt even if Sol fails open). Opt out with
33
+ * GH_ROUTER_DISABLE_CHEAPEST_REWRITE=1.
34
+ *
35
+ * ALWAYS exits 0 (never blocks the prompt): the steer is additive context, and a
36
+ * UserPromptSubmit hook that exit-2'd would refuse the user's prompt. The pure
37
+ * v1 path (`decidePromptSubmit`) is the fail-open fallback; V2
38
+ * (`decidePromptSubmitV2`) layers the grounded enrichment on top via injected IO.
39
+ */
40
+ /**
41
+ * Read the hook payload from stdin SYNCHRONOUSLY (`readFileSync(0)`). An async
42
+ * stdin read leaves an in-flight libuv FS request that, on Windows, races the
43
+ * process teardown and trips a `uv_async_send` assertion; a synchronous read has
44
+ * no such handle. Hooks always receive piped/redirected stdin, so this never
45
+ * blocks (guarded against an interactive TTY, and any error -> "").
46
+ */
47
+ function readStdin() {
48
+ try {
49
+ if (process.stdin.isTTY) return "";
50
+ return readFileSync(0, "utf8");
51
+ } catch {
52
+ return "";
53
+ }
54
+ }
55
+ /** Parse the session cwd from the payload — the workspace the grounding search
56
+ * runs in. Falls back to the process cwd. */
57
+ function workspaceFromStdin(stdin) {
58
+ try {
59
+ const p = JSON.parse(stdin);
60
+ if (p && typeof p === "object") {
61
+ const cwd = p.cwd;
62
+ if (typeof cwd === "string" && cwd.length > 0) return cwd;
63
+ }
64
+ } catch {}
65
+ return process.cwd();
66
+ }
67
+ /** Per-call timeout for the grounding search (short — it must not stall the prompt). */
68
+ const SEARCH_TIMEOUT_MS = 8e3;
69
+ /** Per-call timeout for a single Sol/Luna inference. */
70
+ const INFER_TIMEOUT_MS = 25e3;
71
+ /**
72
+ * Overall budget for the cheapest Sol rewrite (search + Sol, 3 turns default
73
+ * with one adaptive extension to 5). The hook is registered with a 90s host
74
+ * timeout. A rewrite timeout is TERMINAL — the orchestrator falls open to the
75
+ * cheap regex goal and does NOT then run the Luna scope path — so the worst
76
+ * case is one rewrite (≤30s) OR one Luna scope (≤22s), never both.
77
+ */
78
+ const REWRITE_TIMEOUT_MS = 3e4;
79
+ /** Read a text file best-effort, capped; missing/unreadable -> "". */
80
+ function readCappedFile(absPath, cap) {
81
+ try {
82
+ return readFileSync(absPath, "utf8").slice(0, cap);
83
+ } catch {
84
+ return "";
85
+ }
86
+ }
87
+ /**
88
+ * Markers that identify the top of a project when there is no `.git` above
89
+ * (a plain directory, a tarball, a scratch tree). Ordered only for readability —
90
+ * the walk is first-hit-wins.
91
+ */
92
+ const PROJECT_ROOT_MARKERS = [
93
+ "package.json",
94
+ "go.mod",
95
+ "Cargo.toml",
96
+ "pyproject.toml",
97
+ "setup.py",
98
+ "mix.exs",
99
+ "Gemfile",
100
+ "deno.json",
101
+ "deno.jsonc",
102
+ "global.json",
103
+ "Makefile",
104
+ "makefile",
105
+ "GNUmakefile"
106
+ ];
107
+ /**
108
+ * Resolve the project root for `startDir`: the nearest ancestor (inclusive)
109
+ * holding a `.git` entry — a file in worktrees/submodules, else a directory.
110
+ *
111
+ * A `.git` anywhere in the walk WINS over a nearer project marker, because
112
+ * inside a repository the root's guidance is the one that applies: a workspace
113
+ * package with its own `package.json` must not become the root, or the
114
+ * repo-root `AGENTS.md` would never be read. With no `.git` above (non-repo
115
+ * working tree), the nearest project marker is the best available root, so
116
+ * non-git projects still get hierarchical guidance.
117
+ *
118
+ * Sync `existsSync` only, deliberately: this runs inside the rewrite's 30s
119
+ * budget on every non-trivial prompt, and the async `repoRoot()` helper in
120
+ * `stop-gate-policy` spawns `git rev-parse` — too expensive for a value a
121
+ * directory probe answers. Falls back to `startDir`, and the walk is bounded
122
+ * so a deep or symlinked path can't spin.
123
+ */
124
+ function resolveProjectRoot(startDir) {
125
+ const start = path.resolve(startDir);
126
+ const MAX_ROOT_LEVELS = 8;
127
+ let current = start;
128
+ let nearestMarker;
129
+ for (let i = 0; i < MAX_ROOT_LEVELS; i++) {
130
+ if (existsSync(path.join(current, ".git"))) return current;
131
+ if (!nearestMarker && PROJECT_ROOT_MARKERS.some((m) => existsSync(path.join(current, m)))) nearestMarker = current;
132
+ const parent = path.dirname(current);
133
+ if (parent === current) break;
134
+ current = parent;
135
+ }
136
+ return nearestMarker ?? start;
137
+ }
138
+ /**
139
+ * Read the nearest AGENTS.md / CLAUDE.md guidance for `startDir`, walking up
140
+ * toward (and including) `root`. Frontier guidance treats AGENTS.md as
141
+ * hierarchical: the closest file to the work wins — so the chain is built and
142
+ * joined CLOSEST-FIRST. That ordering is load-bearing, not cosmetic: the caller
143
+ * truncates the joined text with `slice(0, CAP)`, which keeps the head, so
144
+ * closest-first is what makes the nearest file survive the budget. (Root-first
145
+ * ordering plus a head-truncating slice silently starves the nearest guidance.)
146
+ *
147
+ * The walk is bounded to `MAX_LEVELS` directories from the start dir and always
148
+ * includes the root, so a deep subdirectory still sees repo-root conventions
149
+ * without paying to read every level. AGENTS.md and CLAUDE.md are collected
150
+ * independently; the caller uses CLAUDE.md only when no AGENTS.md was found at
151
+ * any level. Returns empty strings when none exist.
152
+ */
153
+ function readHierarchicalGuidance(startDir, root) {
154
+ const start = path.resolve(startDir);
155
+ const rootAbs = path.resolve(root);
156
+ const dirs = [];
157
+ let current = start;
158
+ const MAX_LEVELS = 3;
159
+ for (let i = 0; i < MAX_LEVELS; i++) {
160
+ dirs.push(current);
161
+ if (current === rootAbs) break;
162
+ const parent = path.dirname(current);
163
+ if (parent === current) break;
164
+ current = parent;
165
+ }
166
+ if (!dirs.includes(rootAbs)) dirs.push(rootAbs);
167
+ const agentsParts = [];
168
+ const claudeParts = [];
169
+ for (const dir of dirs) {
170
+ const agents = readCappedFile(path.join(dir, "AGENTS.md"), CHEAPEST_REWRITE_GUIDANCE_CAP);
171
+ if (agents.length > 0) agentsParts.push(agents);
172
+ const claude = readCappedFile(path.join(dir, "CLAUDE.md"), CHEAPEST_REWRITE_GUIDANCE_CAP);
173
+ if (claude.length > 0) claudeParts.push(claude);
174
+ }
175
+ return {
176
+ agentsMd: agentsParts.join("\n").slice(0, CHEAPEST_REWRITE_GUIDANCE_CAP),
177
+ claudeMd: claudeParts.join("\n").slice(0, CHEAPEST_REWRITE_GUIDANCE_CAP)
178
+ };
179
+ }
180
+ /** `packageManager` is versioned (`"pnpm@9.1.0"`) — take the leading name. */
181
+ function runnerFromPackageManager(value) {
182
+ if (typeof value !== "string") return void 0;
183
+ const name = value.trim().split("@")[0]?.trim() ?? "";
184
+ return name === "npm" || name === "pnpm" || name === "yarn" || name === "bun" ? name : void 0;
185
+ }
186
+ /** Lockfile → runner, searching `dirs` in order (nearest first). */
187
+ function runnerFromLockfiles(dirs) {
188
+ const table = [
189
+ ["bun.lock", "bun"],
190
+ ["bun.lockb", "bun"],
191
+ ["pnpm-lock.yaml", "pnpm"],
192
+ ["yarn.lock", "yarn"],
193
+ ["package-lock.json", "npm"]
194
+ ];
195
+ for (const dir of dirs) for (const [lockfile, runner] of table) if (existsSync(path.join(dir, lockfile))) return runner;
196
+ }
197
+ /** Lockfile-less repos still name their runner in the script bodies. */
198
+ function runnerFromScriptBodies(scripts) {
199
+ for (const body of Object.values(scripts)) {
200
+ if (typeof body !== "string") continue;
201
+ const head = body.trimStart();
202
+ if (head.startsWith("bun ")) return "bun";
203
+ if (head.startsWith("pnpm ")) return "pnpm";
204
+ if (head.startsWith("yarn ")) return "yarn";
205
+ if (head.startsWith("npm ")) return "npm";
206
+ }
207
+ }
208
+ /** Resolve the package runner for `dir`'s project. */
209
+ function resolvePackageRunner(dir, root, pkg) {
210
+ return runnerFromPackageManager(pkg.packageManager) ?? runnerFromLockfiles([dir, root]) ?? runnerFromScriptBodies(pkg.scripts ?? {}) ?? "npm";
211
+ }
212
+ /**
213
+ * `<runner> run <name>` for EVERY script name, including `test`.
214
+ *
215
+ * The obvious shorthand (`npm test`) is NOT safe: `bun test` invokes Bun's
216
+ * built-in test runner and ignores the `test` script entirely, so a repo whose
217
+ * `test` script is `bun run build && bun scripts/run-tests.ts` would be told to
218
+ * skip its own build and orchestrator. `run` is accepted by npm, pnpm, yarn
219
+ * (1 and berry) and bun alike.
220
+ */
221
+ function scriptCommand(runner, name) {
222
+ return `${runner} run ${name}`;
223
+ }
224
+ /** Pick test/build/lint scripts, in preference order. */
225
+ function pickVerifyScripts(scripts) {
226
+ return [
227
+ "test",
228
+ "test:unit",
229
+ "build",
230
+ "typecheck",
231
+ "lint"
232
+ ].filter((name) => {
233
+ const body = scripts[name];
234
+ return typeof body === "string" && body.trim().length > 0;
235
+ });
236
+ }
237
+ /** Directories never worth descending when looking for project files. */
238
+ const SCAN_SKIP_DIRS = /* @__PURE__ */ new Set([
239
+ ".git",
240
+ "node_modules",
241
+ "dist",
242
+ "build",
243
+ "out",
244
+ "target",
245
+ "bin",
246
+ "obj",
247
+ "vendor",
248
+ "venv",
249
+ ".venv",
250
+ "__pycache__",
251
+ "coverage",
252
+ ".next",
253
+ ".turbo"
254
+ ]);
255
+ /**
256
+ * Bounded search for a project file (`*.sln`, `*.csproj`) at `dir` and up to
257
+ * `maxDepth` levels below it. Entries are capped per directory so a huge tree
258
+ * can't stall the hook, and heavy/known-noise directories are skipped.
259
+ */
260
+ function findProjectFile(dir, matches, maxDepth = 2) {
261
+ if (maxDepth < 0) return void 0;
262
+ let entries;
263
+ try {
264
+ entries = readdirSync(dir, { withFileTypes: true }).slice(0, 200);
265
+ } catch {
266
+ return;
267
+ }
268
+ for (const entry of entries) if (matches(entry.name)) return entry.name;
269
+ if (maxDepth === 0) return void 0;
270
+ for (const entry of entries) {
271
+ if (!entry.isDirectory() || SCAN_SKIP_DIRS.has(entry.name)) continue;
272
+ const hit = findProjectFile(path.join(dir, entry.name), matches, maxDepth - 1);
273
+ if (hit) return hit;
274
+ }
275
+ }
276
+ const NO_VERIFICATION = {
277
+ ecosystem: "",
278
+ verifyCommand: ""
279
+ };
280
+ /** Tier 0c: .NET. `dotnet test` restores + builds, but a solution-wide build
281
+ * is still the gate, and `dotnet format` is only proposed when the repo
282
+ * actually carries an .editorconfig to check against. */
283
+ function dotnetVerification(root, cwd) {
284
+ for (const dir of root === cwd ? [cwd] : [root, cwd]) {
285
+ const project = findProjectFile(dir, (name) => /\.(sln|csproj)$/i.test(name));
286
+ if (!project) continue;
287
+ const commands = ["dotnet build", "dotnet test"];
288
+ if (existsSync(path.join(dir, ".editorconfig"))) commands.push("dotnet format --verify-no-changes");
289
+ return {
290
+ ecosystem: `dotnet (${project})`,
291
+ verifyCommand: `VERIFY COMMAND: ${commands.join(" ; ")}`
292
+ };
293
+ }
294
+ }
295
+ /** Parse `name:` target lines out of a Makefile (skipping `%` pattern rules). */
296
+ function makeTargets(dir) {
297
+ const body = readCappedFile([
298
+ "Makefile",
299
+ "makefile",
300
+ "GNUmakefile"
301
+ ].map((name) => path.join(dir, name)).find((abs) => existsSync(abs)) ?? path.join(dir, "Makefile"), 8192);
302
+ const targets = /* @__PURE__ */ new Set();
303
+ for (const line of body.split("\n")) {
304
+ const match = /^([A-Za-z0-9][A-Za-z0-9_.-]*)\s*:(?!=)/.exec(line);
305
+ if (match?.[1] && !match[1].includes("%")) targets.add(match[1]);
306
+ }
307
+ return targets;
308
+ }
309
+ /** Tier 1 ladder. First marker hit wins; each entry returns "" for a repo it
310
+ * recognizes but can't derive a command for (which lets the next probe try). */
311
+ function markerVerification(cwd, root) {
312
+ for (const dir of root === cwd ? [cwd] : [cwd, root]) {
313
+ if (existsSync(path.join(dir, "go.mod"))) return {
314
+ ecosystem: "go (go.mod)",
315
+ verifyCommand: "VERIFY COMMAND: go build ./... ; go test ./... ; go vet ./..."
316
+ };
317
+ if (existsSync(path.join(dir, "Cargo.toml"))) return {
318
+ ecosystem: "rust (Cargo.toml)",
319
+ verifyCommand: "VERIFY COMMAND: cargo build ; cargo test"
320
+ };
321
+ if (existsSync(path.join(dir, "mix.exs"))) return {
322
+ ecosystem: "elixir (mix.exs)",
323
+ verifyCommand: "VERIFY COMMAND: mix test"
324
+ };
325
+ if (existsSync(path.join(dir, "Gemfile"))) return {
326
+ ecosystem: "ruby (Gemfile)",
327
+ verifyCommand: findProjectFile(dir, (name) => name === "spec", 0) !== void 0 ? "VERIFY COMMAND: bundle exec rspec" : "VERIFY COMMAND: bundle exec rake test"
328
+ };
329
+ const denoConfig = ["deno.json", "deno.jsonc"].map((name) => path.join(dir, name)).find((abs) => existsSync(abs));
330
+ if (denoConfig) {
331
+ const tasks = readCappedFile(denoConfig, 32768);
332
+ if (/"test"\s*:/.test(tasks) || /'test'\s*:/.test(tasks)) return {
333
+ ecosystem: "deno (deno.json)",
334
+ verifyCommand: "VERIFY COMMAND: deno task test"
335
+ };
336
+ }
337
+ const pyproject = path.join(dir, "pyproject.toml");
338
+ const pyprojectBody = readCappedFile(pyproject, 32768);
339
+ const setupCfg = readCappedFile(path.join(dir, "setup.cfg"), 32768);
340
+ if (["tests", "test"].some((name) => findProjectFile(dir, (entry) => entry === name, 0) !== void 0) || existsSync(path.join(dir, "pytest.ini")) || existsSync(path.join(dir, "tox.ini")) || /\[tool\.pytest/.test(pyprojectBody) || /\[tool:pytest\]/.test(setupCfg)) {
341
+ const commands = [existsSync(path.join(dir, "uv.lock")) ? "uv run pytest" : existsSync(path.join(dir, "poetry.lock")) ? "poetry run pytest" : existsSync(path.join(dir, "Pipfile")) ? "pipenv run pytest" : "pytest"];
342
+ if (existsSync(path.join(dir, "mypy.ini")) || /\[tool\.mypy/.test(pyprojectBody)) commands.push("mypy .");
343
+ if (existsSync(path.join(dir, "ruff.toml")) || /\[tool\.ruff/.test(pyprojectBody)) commands.push("ruff check .");
344
+ return {
345
+ ecosystem: `python (${path.basename(pyproject)})`,
346
+ verifyCommand: `VERIFY COMMAND: ${commands.join(" ; ")}`
347
+ };
348
+ }
349
+ if (existsSync(path.join(dir, "Makefile")) || existsSync(path.join(dir, "makefile")) || existsSync(path.join(dir, "GNUmakefile"))) {
350
+ const targets = makeTargets(dir);
351
+ const picked = [
352
+ "test",
353
+ "tests",
354
+ "check",
355
+ "ci",
356
+ "verify",
357
+ "build",
358
+ "lint"
359
+ ].filter((name) => targets.has(name)).slice(0, 2);
360
+ if (picked.length > 0) return {
361
+ ecosystem: "make (Makefile)",
362
+ verifyCommand: `VERIFY COMMAND: ${picked.map((t) => `make ${t}`).join(" ; ")}`
363
+ };
364
+ }
365
+ }
366
+ return NO_VERIFICATION;
367
+ }
368
+ /** Full detection: JS/TS first, then .NET, then the marker ladder. */
369
+ function detectVerification(cwd, root) {
370
+ const cwdPkg = readPackageJson(cwd);
371
+ if (cwdPkg) {
372
+ const picks = pickVerifyScripts(cwdPkg.scripts ?? {});
373
+ if (picks.length > 0) {
374
+ const runner = resolvePackageRunner(cwd, root, cwdPkg);
375
+ return {
376
+ ecosystem: `node (${runner})`,
377
+ verifyCommand: `VERIFY COMMAND: ${picks.map((n) => scriptCommand(runner, n)).join(" ; ")}`
378
+ };
379
+ }
380
+ }
381
+ const ancestor = findAncestorScriptRoot(cwd, root);
382
+ if (ancestor) {
383
+ const { dir, pkg } = ancestor;
384
+ const runner = resolvePackageRunner(dir, root, pkg);
385
+ return {
386
+ ecosystem: `node (${runner}, workspace root)`,
387
+ verifyCommand: `VERIFY COMMAND (run from ${dir}): ` + pickVerifyScripts(pkg.scripts ?? {}).map((n) => scriptCommand(runner, n)).join(" ; ")
388
+ };
389
+ }
390
+ return dotnetVerification(root, cwd) ?? markerVerification(cwd, root);
391
+ }
392
+ /**
393
+ * Nearest strict ancestor of `cwd` whose package.json declares at least one
394
+ * recognized verify script — the monorepo case, where the workspace manifest is
395
+ * the real gate. Never ascends above `root` (so a stray `~/package.json` can't
396
+ * be picked up for a session already at the project root), and bounded so a
397
+ * deep sub-package can't pay for a long ascent.
398
+ */
399
+ function findAncestorScriptRoot(cwd, root) {
400
+ const start = path.resolve(cwd);
401
+ const rootAbs = path.resolve(root);
402
+ if (rootAbs === start) return void 0;
403
+ const MAX_ASCENT = 4;
404
+ let current = path.dirname(start);
405
+ for (let i = 0; i <= MAX_ASCENT; i++) {
406
+ const pkg = readPackageJson(current);
407
+ if (pkg && pickVerifyScripts(pkg.scripts ?? {}).length > 0) return {
408
+ dir: current,
409
+ pkg
410
+ };
411
+ if (current === rootAbs) break;
412
+ const parent = path.dirname(current);
413
+ if (parent === current) break;
414
+ current = parent;
415
+ }
416
+ }
417
+ function readPackageJson(dir) {
418
+ const raw = readCappedFile(path.join(dir, "package.json"), 65536);
419
+ if (raw.length === 0) return void 0;
420
+ try {
421
+ const parsed = JSON.parse(raw);
422
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
423
+ } catch {}
424
+ }
425
+ /**
426
+ * Static repo context for the cheapest rewrite: hierarchical AGENTS.md
427
+ * (preferred) / CLAUDE.md (fallback) + top-level structure + a detected
428
+ * ecosystem + its VERIFY COMMAND line. All synchronous (tiny reads) and
429
+ * capped; missing files yield "".
430
+ */
431
+ function buildStaticPack(workspace) {
432
+ const root = resolveProjectRoot(workspace);
433
+ const guidance = readHierarchicalGuidance(workspace, root);
434
+ const agentsMd = guidance.agentsMd;
435
+ const claudeMd = agentsMd.length > 0 ? "" : guidance.claudeMd;
436
+ let listing;
437
+ try {
438
+ listing = readdirSync(workspace, { withFileTypes: true }).slice(0, 60).map((e) => e.isDirectory() ? `${e.name}/` : e.name).join(", ");
439
+ } catch {
440
+ listing = "";
441
+ }
442
+ let pkgSnippet;
443
+ const pkg = readPackageJson(workspace);
444
+ if (pkg) pkgSnippet = `scripts: [${pkg.scripts ? Object.keys(pkg.scripts).slice(0, 20).join(", ") : ""}] deps: [${Object.keys(pkg.dependencies ?? {}).slice(0, 20).join(", ")}]`;
445
+ else pkgSnippet = "";
446
+ const { ecosystem, verifyCommand: detected } = detectVerification(workspace, root);
447
+ return {
448
+ agentsMd,
449
+ claudeMd,
450
+ repoStructure: [
451
+ `top-level: ${listing}`,
452
+ ecosystem ? `ecosystem: ${ecosystem}` : "",
453
+ pkgSnippet
454
+ ].filter((s) => s.trim().length > 0 && s !== "top-level: ").join("\n").slice(0, CHEAPEST_REWRITE_STRUCTURE_CAP),
455
+ verifyCommand: detected.slice(0, 512)
456
+ };
457
+ }
458
+ const internalPromptSubmit = defineCommand({
459
+ meta: {
460
+ name: "internal-prompt-submit",
461
+ description: "Internal: the UserPromptSubmit hook. Resets the Stop-gate per-prompt block budget, surfaces prior-turn review findings, and injects a grounded advisory goal for non-trivial prompts. Always exit 0."
462
+ },
463
+ async run() {
464
+ try {
465
+ const stdin = readStdin();
466
+ const steerEnabled = parseBoolEnv(process.env.GH_ROUTER_DISABLE_PROMPT_STEER) !== true;
467
+ 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";
468
+ const bluebirdEnabled = process.env.GH_ROUTER_BLUEBIRD_ENABLED === "1";
469
+ const runtime = hookMcpRuntimeFromEnv();
470
+ let decision;
471
+ if (runtime) {
472
+ const workspace = workspaceFromStdin(stdin);
473
+ const profile = (process.env.GH_ROUTER_PROFILE ?? "").trim().toLowerCase();
474
+ const rewriteDisabled = isCheapestRewriteDisabledEnv();
475
+ decision = await decidePromptSubmitV2({
476
+ stdin,
477
+ steerEnabled,
478
+ searchEnabled,
479
+ bluebirdEnabled,
480
+ profile,
481
+ rewriteDisabled,
482
+ rewrite: {
483
+ searchCode: async (query, mode, signal) => {
484
+ const r = await callMcpTool({
485
+ runtime,
486
+ group: "search",
487
+ tool: "code",
488
+ args: {
489
+ query,
490
+ workspace,
491
+ mode,
492
+ limit: 10,
493
+ summary: false
494
+ },
495
+ timeoutMs: SEARCH_TIMEOUT_MS,
496
+ signal
497
+ });
498
+ return r.isError ? "" : r.text;
499
+ },
500
+ inferSol: (system, user, signal) => callInference({
501
+ serverUrl: runtime.serverUrl,
502
+ model: CHEAPEST_REWRITE_MODEL,
503
+ instructions: system,
504
+ input: user,
505
+ effort: CHEAPEST_REWRITE_EFFORT,
506
+ timeoutMs: INFER_TIMEOUT_MS,
507
+ signal
508
+ }),
509
+ staticPack: async () => buildStaticPack(workspace),
510
+ hasRewriteRun: (sid) => fileRewriteFlagStore(stopReviewStateDir()).hasRun(sid),
511
+ markRewriteRun: (sid) => fileRewriteFlagStore(stopReviewStateDir()).markRun(sid),
512
+ timeoutMs: REWRITE_TIMEOUT_MS
513
+ },
514
+ io: {
515
+ searchCode: async (query, mode, signal) => {
516
+ const r = await callMcpTool({
517
+ runtime,
518
+ group: "search",
519
+ tool: "code",
520
+ args: {
521
+ query,
522
+ workspace,
523
+ mode,
524
+ limit: 10,
525
+ summary: false
526
+ },
527
+ timeoutMs: SEARCH_TIMEOUT_MS,
528
+ signal
529
+ });
530
+ return r.isError ? "" : r.text;
531
+ },
532
+ infer: (system, user, signal) => callInference({
533
+ serverUrl: runtime.serverUrl,
534
+ model: "gpt-6-luna",
535
+ instructions: system,
536
+ input: user,
537
+ effort: "high",
538
+ timeoutMs: INFER_TIMEOUT_MS,
539
+ signal
540
+ }),
541
+ readFindings: (sid) => fileFindingsStore(stopReviewStateDir()).read(sid),
542
+ clearFindings: (sid) => fileFindingsStore(stopReviewStateDir()).clear(sid),
543
+ storePrompt: (sid, prompt) => fileLastPromptStore(stopReviewStateDir()).write(sid, prompt)
544
+ }
545
+ });
546
+ } else decision = decidePromptSubmit({
547
+ stdin,
548
+ steerEnabled
549
+ });
550
+ if (decision.resetSession) await fileBlockBudget(path.join(tmpdir(), "gh-router-stopgate")).reset(decision.resetSession).catch(() => {});
551
+ if (decision.inject.length > 0) await new Promise((resolve) => process.stdout.write(`${decision.inject}\n`, () => resolve()));
552
+ } catch {}
553
+ process.exitCode = 0;
554
+ }
555
+ });
556
+ //#endregion
557
+ export { internalPromptSubmit };
558
+
559
+ //# sourceMappingURL=internal-prompt-submit-DRCJ5kWC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"internal-prompt-submit-DRCJ5kWC.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-6-luna call at high effort over the prompt + grounding\n * code search — local ColBERT when --search is on, Bluebird when\n * --bluebird is on, lexical-only otherwise) — or, when the proxy URL/nonce\n * isn't wired or anything errors,\n * falls open to the v1 regex goal.\n * 4. on a cheapest-profile launch only, tries FIRST a Sol (gpt-5.6-sol,\n * medium) rewrite of the prompt into a short structured EXECUTION BRIEF over\n * the prompt + AGENTS.md/CLAUDE.md + repo structure + ecosystem's verify\n * command + grounding search\n * (adaptive 3 turns, up to 5 on Sol's deep-grounding flag) — additive,\n * never replacing the user prompt — and falls back to (3) on any miss.\n * One-shot per session (first non-trivial prompt only, marked on\n * attempt even if Sol fails open). Opt out with\n * GH_ROUTER_DISABLE_CHEAPEST_REWRITE=1.\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 { existsSync, readdirSync, readFileSync } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport path from \"node:path\"\n\nimport {\n CHEAPEST_REWRITE_EFFORT,\n CHEAPEST_REWRITE_GUIDANCE_CAP,\n CHEAPEST_REWRITE_MODEL,\n CHEAPEST_REWRITE_STRUCTURE_CAP,\n CHEAPEST_REWRITE_TEST_CMD_CAP,\n isCheapestRewriteDisabledEnv,\n} from \"./lib/cheapest-prompt-rewrite\"\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 fileRewriteFlagStore,\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 a single Sol/Luna inference. */\nconst INFER_TIMEOUT_MS = 25_000\n/**\n * Overall budget for the cheapest Sol rewrite (search + Sol, 3 turns default\n * with one adaptive extension to 5). The hook is registered with a 90s host\n * timeout. A rewrite timeout is TERMINAL — the orchestrator falls open to the\n * cheap regex goal and does NOT then run the Luna scope path — so the worst\n * case is one rewrite (≤30s) OR one Luna scope (≤22s), never both.\n */\nconst REWRITE_TIMEOUT_MS = 30_000\n\n/** Read a text file best-effort, capped; missing/unreadable -> \"\". */\nfunction readCappedFile(absPath: string, cap: number): string {\n try {\n return readFileSync(absPath, \"utf8\").slice(0, cap)\n } catch {\n return \"\"\n }\n}\n\n/** The subset of package.json this module reads. */\ninterface PackageJsonShape {\n scripts?: Record<string, string>\n packageManager?: string\n dependencies?: Record<string, string>\n}\n\n/**\n * Markers that identify the top of a project when there is no `.git` above\n * (a plain directory, a tarball, a scratch tree). Ordered only for readability —\n * the walk is first-hit-wins.\n */\nconst PROJECT_ROOT_MARKERS = [\n \"package.json\", \"go.mod\", \"Cargo.toml\", \"pyproject.toml\", \"setup.py\",\n \"mix.exs\", \"Gemfile\", \"deno.json\", \"deno.jsonc\", \"global.json\",\n \"Makefile\", \"makefile\", \"GNUmakefile\",\n]\n\n/**\n * Resolve the project root for `startDir`: the nearest ancestor (inclusive)\n * holding a `.git` entry — a file in worktrees/submodules, else a directory.\n *\n * A `.git` anywhere in the walk WINS over a nearer project marker, because\n * inside a repository the root's guidance is the one that applies: a workspace\n * package with its own `package.json` must not become the root, or the\n * repo-root `AGENTS.md` would never be read. With no `.git` above (non-repo\n * working tree), the nearest project marker is the best available root, so\n * non-git projects still get hierarchical guidance.\n *\n * Sync `existsSync` only, deliberately: this runs inside the rewrite's 30s\n * budget on every non-trivial prompt, and the async `repoRoot()` helper in\n * `stop-gate-policy` spawns `git rev-parse` — too expensive for a value a\n * directory probe answers. Falls back to `startDir`, and the walk is bounded\n * so a deep or symlinked path can't spin.\n */\nfunction resolveProjectRoot(startDir: string): string {\n const start = path.resolve(startDir)\n const MAX_ROOT_LEVELS = 8\n let current = start\n let nearestMarker: string | undefined\n for (let i = 0; i < MAX_ROOT_LEVELS; i++) {\n if (existsSync(path.join(current, \".git\"))) return current\n if (!nearestMarker && PROJECT_ROOT_MARKERS.some((m) => existsSync(path.join(current, m)))) {\n nearestMarker = current\n }\n const parent = path.dirname(current)\n if (parent === current) break\n current = parent\n }\n return nearestMarker ?? start\n}\n\n/**\n * Read the nearest AGENTS.md / CLAUDE.md guidance for `startDir`, walking up\n * toward (and including) `root`. Frontier guidance treats AGENTS.md as\n * hierarchical: the closest file to the work wins — so the chain is built and\n * joined CLOSEST-FIRST. That ordering is load-bearing, not cosmetic: the caller\n * truncates the joined text with `slice(0, CAP)`, which keeps the head, so\n * closest-first is what makes the nearest file survive the budget. (Root-first\n * ordering plus a head-truncating slice silently starves the nearest guidance.)\n *\n * The walk is bounded to `MAX_LEVELS` directories from the start dir and always\n * includes the root, so a deep subdirectory still sees repo-root conventions\n * without paying to read every level. AGENTS.md and CLAUDE.md are collected\n * independently; the caller uses CLAUDE.md only when no AGENTS.md was found at\n * any level. Returns empty strings when none exist.\n */\nfunction readHierarchicalGuidance(\n startDir: string,\n root: string,\n): { agentsMd: string; claudeMd: string } {\n const start = path.resolve(startDir)\n const rootAbs = path.resolve(root)\n // Closest-first chain: [start, …bounded ancestors…, root].\n const dirs: Array<string> = []\n let current = start\n const MAX_LEVELS = 3\n for (let i = 0; i < MAX_LEVELS; i++) {\n dirs.push(current)\n if (current === rootAbs) break\n const parent = path.dirname(current)\n if (parent === current) break\n current = parent\n }\n if (!dirs.includes(rootAbs)) dirs.push(rootAbs)\n\n const agentsParts: Array<string> = []\n const claudeParts: Array<string> = []\n for (const dir of dirs) {\n const agents = readCappedFile(path.join(dir, \"AGENTS.md\"), CHEAPEST_REWRITE_GUIDANCE_CAP)\n if (agents.length > 0) agentsParts.push(agents)\n const claude = readCappedFile(path.join(dir, \"CLAUDE.md\"), CHEAPEST_REWRITE_GUIDANCE_CAP)\n if (claude.length > 0) claudeParts.push(claude)\n }\n return {\n agentsMd: agentsParts.join(\"\\n\").slice(0, CHEAPEST_REWRITE_GUIDANCE_CAP),\n claudeMd: claudeParts.join(\"\\n\").slice(0, CHEAPEST_REWRITE_GUIDANCE_CAP),\n }\n}\n\n// ---------------------------------------------------------------------------\n// VERIFY COMMAND detection — ecosystem generic on purpose.\n//\n// The line is presented to Luna as *the* exact command to verify the work, so\n// a wrong guess is worse than no guess: an `npm`-only implementation (the\n// previous behavior) emitted `npm test` for bun/yarn/pnpm repos, `npx npm\n// test` whenever vitest happened to be a dependency, and `\"\"` for every\n// non-JavaScript repo. Three tiers, first hit wins, and `\"\"` stays the honest\n// answer when nothing is derivable:\n//\n// Tier 0 first-class toolchains with one canonical command\n// 0a package.json scripts at the session cwd\n// 0b an ancestor workspace manifest (monorepo sub-package), labeled\n// with the directory to run it in\n// 0c .NET (`*.sln` / `*.csproj`)\n// Tier 1 marker ladder: go, rust, python, elixir, ruby, deno, make\n//\n// Tier 0 outranks the ladder because a repo with a `Makefile` *and* a\n// `package.json` normally uses the Makefile as a wrapper, not as the gate.\n// ---------------------------------------------------------------------------\n\ntype PackageRunner = \"npm\" | \"pnpm\" | \"yarn\" | \"bun\"\n\n/** `packageManager` is versioned (`\"pnpm@9.1.0\"`) — take the leading name. */\nfunction runnerFromPackageManager(value: string | undefined): PackageRunner | undefined {\n if (typeof value !== \"string\") return undefined\n // Manager names are never scoped, so the version is everything after the\n // first `@`; taking the last segment would yield \"9.1.0\".\n const name = value.trim().split(\"@\")[0]?.trim() ?? \"\"\n return name === \"npm\" || name === \"pnpm\" || name === \"yarn\" || name === \"bun\"\n ? name\n : undefined\n}\n\n/** Lockfile → runner, searching `dirs` in order (nearest first). */\nfunction runnerFromLockfiles(dirs: Array<string>): PackageRunner | undefined {\n const table: Array<[string, PackageRunner]> = [\n [\"bun.lock\", \"bun\"],\n [\"bun.lockb\", \"bun\"],\n [\"pnpm-lock.yaml\", \"pnpm\"],\n [\"yarn.lock\", \"yarn\"],\n [\"package-lock.json\", \"npm\"],\n ]\n for (const dir of dirs) {\n for (const [lockfile, runner] of table) {\n if (existsSync(path.join(dir, lockfile))) return runner\n }\n }\n return undefined\n}\n\n/** Lockfile-less repos still name their runner in the script bodies. */\nfunction runnerFromScriptBodies(scripts: Record<string, string>): PackageRunner | undefined {\n for (const body of Object.values(scripts)) {\n if (typeof body !== \"string\") continue\n const head = body.trimStart()\n if (head.startsWith(\"bun \")) return \"bun\"\n if (head.startsWith(\"pnpm \")) return \"pnpm\"\n if (head.startsWith(\"yarn \")) return \"yarn\"\n if (head.startsWith(\"npm \")) return \"npm\"\n }\n return undefined\n}\n\n/** Resolve the package runner for `dir`'s project. */\nfunction resolvePackageRunner(\n dir: string,\n root: string,\n pkg: PackageJsonShape,\n): PackageRunner {\n return runnerFromPackageManager(pkg.packageManager)\n ?? runnerFromLockfiles([dir, root])\n ?? runnerFromScriptBodies(pkg.scripts ?? {})\n ?? \"npm\"\n}\n\n/**\n * `<runner> run <name>` for EVERY script name, including `test`.\n *\n * The obvious shorthand (`npm test`) is NOT safe: `bun test` invokes Bun's\n * built-in test runner and ignores the `test` script entirely, so a repo whose\n * `test` script is `bun run build && bun scripts/run-tests.ts` would be told to\n * skip its own build and orchestrator. `run` is accepted by npm, pnpm, yarn\n * (1 and berry) and bun alike.\n */\nfunction scriptCommand(runner: PackageRunner, name: string): string {\n return `${runner} run ${name}`\n}\n\n/** Pick test/build/lint scripts, in preference order. */\nfunction pickVerifyScripts(scripts: Record<string, string>): Array<string> {\n const preferred = [\"test\", \"test:unit\", \"build\", \"typecheck\", \"lint\"]\n return preferred.filter((name) => {\n const body = scripts[name]\n return typeof body === \"string\" && body.trim().length > 0\n })\n}\n\n/** Directories never worth descending when looking for project files. */\nconst SCAN_SKIP_DIRS = new Set([\n \".git\", \"node_modules\", \"dist\", \"build\", \"out\", \"target\", \"bin\", \"obj\",\n \"vendor\", \"venv\", \".venv\", \"__pycache__\", \"coverage\", \".next\", \".turbo\",\n])\n\n/**\n * Bounded search for a project file (`*.sln`, `*.csproj`) at `dir` and up to\n * `maxDepth` levels below it. Entries are capped per directory so a huge tree\n * can't stall the hook, and heavy/known-noise directories are skipped.\n */\nfunction findProjectFile(\n dir: string,\n matches: (name: string) => boolean,\n maxDepth = 2,\n): string | undefined {\n if (maxDepth < 0) return undefined\n let entries: Array<{ name: string; isDirectory: () => boolean }>\n try {\n entries = readdirSync(dir, { withFileTypes: true }).slice(0, 200)\n } catch {\n return undefined\n }\n for (const entry of entries) {\n if (matches(entry.name)) return entry.name\n }\n if (maxDepth === 0) return undefined\n for (const entry of entries) {\n if (!entry.isDirectory() || SCAN_SKIP_DIRS.has(entry.name)) continue\n const hit = findProjectFile(path.join(dir, entry.name), matches, maxDepth - 1)\n if (hit) return hit\n }\n return undefined\n}\n\ninterface Verification {\n /** Short ecosystem label for repoStructure; \"\" when undetermined. */\n ecosystem: string\n /** The VERIFY COMMAND line, or \"\" when nothing is derivable. */\n verifyCommand: string\n}\n\nconst NO_VERIFICATION: Verification = { ecosystem: \"\", verifyCommand: \"\" }\n\n/** Tier 0c: .NET. `dotnet test` restores + builds, but a solution-wide build\n * is still the gate, and `dotnet format` is only proposed when the repo\n * actually carries an .editorconfig to check against. */\nfunction dotnetVerification(root: string, cwd: string): Verification | undefined {\n for (const dir of root === cwd ? [cwd] : [root, cwd]) {\n const project = findProjectFile(dir, (name) => /\\.(sln|csproj)$/i.test(name))\n if (!project) continue\n const commands = [\"dotnet build\", \"dotnet test\"]\n if (existsSync(path.join(dir, \".editorconfig\"))) {\n commands.push(\"dotnet format --verify-no-changes\")\n }\n return {\n ecosystem: `dotnet (${project})`,\n verifyCommand: `VERIFY COMMAND: ${commands.join(\" ; \")}`,\n }\n }\n return undefined\n}\n\n/** Parse `name:` target lines out of a Makefile (skipping `%` pattern rules). */\nfunction makeTargets(dir: string): Set<string> {\n const body = readCappedFile(\n [\"Makefile\", \"makefile\", \"GNUmakefile\"]\n .map((name) => path.join(dir, name))\n .find((abs) => existsSync(abs)) ?? path.join(dir, \"Makefile\"),\n 8 * 1024,\n )\n const targets = new Set<string>()\n for (const line of body.split(\"\\n\")) {\n const match = /^([A-Za-z0-9][A-Za-z0-9_.-]*)\\s*:(?!=)/.exec(line)\n if (match?.[1] && !match[1].includes(\"%\")) targets.add(match[1])\n }\n return targets\n}\n\n/** Tier 1 ladder. First marker hit wins; each entry returns \"\" for a repo it\n * recognizes but can't derive a command for (which lets the next probe try). */\nfunction markerVerification(cwd: string, root: string): Verification {\n for (const dir of root === cwd ? [cwd] : [cwd, root]) {\n if (existsSync(path.join(dir, \"go.mod\"))) {\n return {\n ecosystem: \"go (go.mod)\",\n verifyCommand: \"VERIFY COMMAND: go build ./... ; go test ./... ; go vet ./...\",\n }\n }\n if (existsSync(path.join(dir, \"Cargo.toml\"))) {\n return {\n ecosystem: \"rust (Cargo.toml)\",\n verifyCommand: \"VERIFY COMMAND: cargo build ; cargo test\",\n }\n }\n if (existsSync(path.join(dir, \"mix.exs\"))) {\n return { ecosystem: \"elixir (mix.exs)\", verifyCommand: \"VERIFY COMMAND: mix test\" }\n }\n if (existsSync(path.join(dir, \"Gemfile\"))) {\n const spec = findProjectFile(dir, (name) => name === \"spec\", 0) !== undefined\n return {\n ecosystem: \"ruby (Gemfile)\",\n verifyCommand: spec\n ? \"VERIFY COMMAND: bundle exec rspec\"\n : \"VERIFY COMMAND: bundle exec rake test\",\n }\n }\n const denoConfig = [\"deno.json\", \"deno.jsonc\"]\n .map((name) => path.join(dir, name))\n .find((abs) => existsSync(abs))\n if (denoConfig) {\n const tasks = readCappedFile(denoConfig, 32 * 1024)\n if (/\"test\"\\s*:/.test(tasks) || /'test'\\s*:/.test(tasks)) {\n return { ecosystem: \"deno (deno.json)\", verifyCommand: \"VERIFY COMMAND: deno task test\" }\n }\n }\n // Python: propose a pytest line when a pytest config OR a test directory is\n // present — most projects run pytest with zero config, so requiring a\n // config section would miss them, while a repo with no tests at all still\n // gets no guess.\n const pyproject = path.join(dir, \"pyproject.toml\")\n const pyprojectBody = readCappedFile(pyproject, 32 * 1024)\n const setupCfg = readCappedFile(path.join(dir, \"setup.cfg\"), 32 * 1024)\n const hasTests = [\"tests\", \"test\"].some(\n (name) => findProjectFile(dir, (entry) => entry === name, 0) !== undefined,\n )\n const hasPytest = hasTests\n || existsSync(path.join(dir, \"pytest.ini\"))\n || existsSync(path.join(dir, \"tox.ini\"))\n || /\\[tool\\.pytest/.test(pyprojectBody)\n || /\\[tool:pytest\\]/.test(setupCfg)\n if (hasPytest) {\n const test = existsSync(path.join(dir, \"uv.lock\"))\n ? \"uv run pytest\"\n : existsSync(path.join(dir, \"poetry.lock\"))\n ? \"poetry run pytest\"\n : existsSync(path.join(dir, \"Pipfile\"))\n ? \"pipenv run pytest\"\n : \"pytest\"\n const commands = [test]\n if (existsSync(path.join(dir, \"mypy.ini\")) || /\\[tool\\.mypy/.test(pyprojectBody)) {\n commands.push(\"mypy .\")\n }\n if (existsSync(path.join(dir, \"ruff.toml\")) || /\\[tool\\.ruff/.test(pyprojectBody)) {\n commands.push(\"ruff check .\")\n }\n return {\n ecosystem: `python (${path.basename(pyproject)})`,\n verifyCommand: `VERIFY COMMAND: ${commands.join(\" ; \")}`,\n }\n }\n if (existsSync(path.join(dir, \"Makefile\")) || existsSync(path.join(dir, \"makefile\"))\n || existsSync(path.join(dir, \"GNUmakefile\"))) {\n const targets = makeTargets(dir)\n const picked = [\"test\", \"tests\", \"check\", \"ci\", \"verify\", \"build\", \"lint\"]\n .filter((name) => targets.has(name))\n .slice(0, 2)\n if (picked.length > 0) {\n return {\n ecosystem: \"make (Makefile)\",\n verifyCommand: `VERIFY COMMAND: ${picked.map((t) => `make ${t}`).join(\" ; \")}`,\n }\n }\n }\n }\n return NO_VERIFICATION\n}\n\n/** Full detection: JS/TS first, then .NET, then the marker ladder. */\nfunction detectVerification(cwd: string, root: string): Verification {\n const cwdPkg = readPackageJson(cwd)\n if (cwdPkg) {\n const picks = pickVerifyScripts(cwdPkg.scripts ?? {})\n if (picks.length > 0) {\n const runner = resolvePackageRunner(cwd, root, cwdPkg)\n return {\n ecosystem: `node (${runner})`,\n verifyCommand: `VERIFY COMMAND: ${picks.map((n) => scriptCommand(runner, n)).join(\" ; \")}`,\n }\n }\n }\n // Monorepo sub-package: an ancestor workspace manifest is the real gate, and\n // its scripts must be run from that directory — so say so in the line itself.\n // Walked explicitly (rather than only checking the project root) so a\n // workspace root several levels up is still found, and bounded so a deep\n // sub-package can't pay for a long ascent.\n const ancestor = findAncestorScriptRoot(cwd, root)\n if (ancestor) {\n const { dir, pkg } = ancestor\n const runner = resolvePackageRunner(dir, root, pkg)\n return {\n ecosystem: `node (${runner}, workspace root)`,\n verifyCommand:\n `VERIFY COMMAND (run from ${dir}): `\n + pickVerifyScripts(pkg.scripts ?? {}).map((n) => scriptCommand(runner, n)).join(\" ; \"),\n }\n }\n return dotnetVerification(root, cwd) ?? markerVerification(cwd, root)\n}\n\n/**\n * Nearest strict ancestor of `cwd` whose package.json declares at least one\n * recognized verify script — the monorepo case, where the workspace manifest is\n * the real gate. Never ascends above `root` (so a stray `~/package.json` can't\n * be picked up for a session already at the project root), and bounded so a\n * deep sub-package can't pay for a long ascent.\n */\nfunction findAncestorScriptRoot(\n cwd: string,\n root: string,\n): { dir: string; pkg: PackageJsonShape } | undefined {\n const start = path.resolve(cwd)\n const rootAbs = path.resolve(root)\n if (rootAbs === start) return undefined\n const MAX_ASCENT = 4\n let current = path.dirname(start)\n for (let i = 0; i <= MAX_ASCENT; i++) {\n const pkg = readPackageJson(current)\n if (pkg && pickVerifyScripts(pkg.scripts ?? {}).length > 0) {\n return { dir: current, pkg }\n }\n if (current === rootAbs) break\n const parent = path.dirname(current)\n if (parent === current) break\n current = parent\n }\n return undefined\n}\n\nfunction readPackageJson(dir: string): PackageJsonShape | undefined {\n const raw = readCappedFile(path.join(dir, \"package.json\"), 64 * 1024)\n if (raw.length === 0) return undefined\n try {\n const parsed: unknown = JSON.parse(raw)\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as PackageJsonShape\n }\n } catch {\n /* malformed package.json is not fatal — fall through to the other tiers */\n }\n return undefined\n}\n\n/**\n * Static repo context for the cheapest rewrite: hierarchical AGENTS.md\n * (preferred) / CLAUDE.md (fallback) + top-level structure + a detected\n * ecosystem + its VERIFY COMMAND line. All synchronous (tiny reads) and\n * capped; missing files yield \"\".\n */\nexport function buildStaticPack(workspace: string): {\n agentsMd: string\n claudeMd: string\n repoStructure: string\n verifyCommand: string\n} {\n // The hook runs in the session cwd; walk guidance from there up to the repo\n // root, and reuse that root for lockfile/root-manifest detection.\n const root = resolveProjectRoot(workspace)\n const guidance = readHierarchicalGuidance(workspace, root)\n const agentsMd = guidance.agentsMd\n const claudeMd = agentsMd.length > 0 ? \"\" : guidance.claudeMd\n let listing: string\n try {\n const entries = readdirSync(workspace, { withFileTypes: true })\n .slice(0, 60)\n .map((e) => (e.isDirectory() ? `${e.name}/` : e.name))\n listing = entries.join(\", \")\n } catch {\n listing = \"\"\n }\n let pkgSnippet: string\n const pkg = readPackageJson(workspace)\n if (pkg) {\n const scripts = pkg.scripts ? Object.keys(pkg.scripts).slice(0, 20).join(\", \") : \"\"\n const deps = Object.keys(pkg.dependencies ?? {}).slice(0, 20).join(\", \")\n pkgSnippet = `scripts: [${scripts}] deps: [${deps}]`\n } else {\n pkgSnippet = \"\"\n }\n const { ecosystem, verifyCommand: detected } = detectVerification(workspace, root)\n // The ecosystem line gives Sol a type signal even when no command could be\n // derived, which is what makes an empty VERIFY COMMAND interpretable.\n const repoStructure = [\n `top-level: ${listing}`,\n ecosystem ? `ecosystem: ${ecosystem}` : \"\",\n pkgSnippet,\n ]\n .filter((s) => s.trim().length > 0 && s !== \"top-level: \")\n .join(\"\\n\")\n .slice(0, CHEAPEST_REWRITE_STRUCTURE_CAP)\n return {\n agentsMd,\n claudeMd,\n repoStructure,\n verifyCommand: detected.slice(0, CHEAPEST_REWRITE_TEST_CMD_CAP),\n }\n}\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 bluebirdEnabled = process.env.GH_ROUTER_BLUEBIRD_ENABLED === \"1\"\n const runtime = hookMcpRuntimeFromEnv()\n\n let decision: PromptSubmitDecision\n if (runtime) {\n const workspace = workspaceFromStdin(stdin)\n // Cheapest-only Sol rewrite identity: the launcher exports\n // GH_ROUTER_PROFILE; only the literal \"cheapest\" alias enables the\n // rewrite branch (checked again inside decidePromptSubmitV2).\n const profile = (process.env.GH_ROUTER_PROFILE ?? \"\").trim().toLowerCase()\n const rewriteDisabled = isCheapestRewriteDisabledEnv()\n decision = await decidePromptSubmitV2({\n stdin,\n steerEnabled,\n searchEnabled,\n bluebirdEnabled,\n profile,\n rewriteDisabled,\n rewrite: {\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 inferSol: (system, user, signal) =>\n callInference({\n serverUrl: runtime.serverUrl,\n model: CHEAPEST_REWRITE_MODEL,\n instructions: system,\n input: user,\n effort: CHEAPEST_REWRITE_EFFORT,\n timeoutMs: INFER_TIMEOUT_MS,\n signal,\n }),\n // Lazy: fs reads run only when the cheapest branch actually fires.\n staticPack: async () => buildStaticPack(workspace),\n // Session-keyed one-shot flag: first non-trivial prompt per\n // session spends the rewrite; later prompts use the Luna path.\n hasRewriteRun: (sid) => fileRewriteFlagStore(stopReviewStateDir()).hasRun(sid),\n markRewriteRun: (sid) => fileRewriteFlagStore(stopReviewStateDir()).markRun(sid),\n timeoutMs: REWRITE_TIMEOUT_MS,\n },\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-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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkEA,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;;;;;;;;AAQzB,MAAM,qBAAqB;;AAG3B,SAAS,eAAe,SAAiB,KAAqB;CAC5D,IAAI;EACF,OAAO,aAAa,SAAS,MAAM,CAAC,CAAC,MAAM,GAAG,GAAG;CACnD,QAAQ;EACN,OAAO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AAO,WAAW,QAAQ,CAAC,CAAC;EAEtG,QAAQ,CAER;EAIA,QAAQ,WAAW;CACrB;AACF,CAAC"}
@@ -1,4 +1,4 @@
1
- import { a as isSubagentContext } from "./stop-gate-policy-Gd_cNT9-.js";
1
+ import { o as isSubagentContext } from "./stop-gate-policy-CbLklfV2.js";
2
2
  import { defineCommand } from "citty";
3
3
  import { mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
4
4
  import path from "node:path";
@@ -130,4 +130,4 @@ const internalSessionBind = defineCommand({
130
130
  //#endregion
131
131
  export { internalSessionBind };
132
132
 
133
- //# sourceMappingURL=internal-session-bind-IpZ5hJzR.js.map
133
+ //# sourceMappingURL=internal-session-bind-LrYEo-kg.js.map