yolont 0.6.0 → 0.7.0
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/README.md +1 -0
- package/dist/cli.js +3481 -2793
- package/dist/cli.js.map +4 -4
- package/docs/GUIDE.md +43 -0
- package/package.json +2 -1
- package/templates/zones-example.yaml +62 -0
package/dist/cli.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../local/paths.ts", "../
|
|
4
|
-
"sourcesContent": ["import { existsSync, renameSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\n/** Where Yolont is installed. Read-only at runtime: only built-in defaults live here, never\n * user state \u2014 an npm install may not be writable, and an upgrade replaces it. */\nexport const INSTALL_ROOT = join(__dirname, \"..\");\nexport const DEFAULT_RUBRIC_PATH = join(INSTALL_ROOT, \".pr-reviewer\", \"rubric.yml\");\n/** Built-in convention files, offered as starting points when a project has none. */\nexport const BUILTIN_CONVENTIONS_DIR = join(INSTALL_ROOT, \"conventions\");\nexport const DEFAULT_CONVENTIONS_PATH = join(BUILTIN_CONVENTIONS_DIR, \"default.md\");\n/** Built-in zone templates per stack (react-spa, nextjs, node-api, generic). */\nexport const ZONE_TEMPLATES_DIR = join(INSTALL_ROOT, \"templates\", \"zones\");\n\nconst env = process.env;\nconst win = process.platform === \"win32\";\n\n// ---- renamed from Ethos (2026-11-29): old names keep working ----\n// ETHOS_* env vars count as YOLONT_* when those aren't set.\nfor (const [k, v] of Object.entries(env)) if (k.startsWith(\"ETHOS_\") && env[`YOLONT_${k.slice(6)}`] === undefined) env[`YOLONT_${k.slice(6)}`] = v;\n\n/**\n * The default folder, taking over the old Ethos one once: a rename (same disk, atomic), so the\n * reviews DB, memory repo clones and credentials file move together. If the move fails (another\n * disk, permissions) the old folder keeps being used, so nothing is ever left behind.\n */\nfunction adopt(base: string): string {\n const dir = join(base, \"yolont\");\n const old = join(base, \"ethos\");\n if (existsSync(dir) || !existsSync(old)) return dir;\n try {\n renameSync(old, dir);\n return dir;\n } catch {\n return old;\n }\n}\n\n/** User config (no secrets in files here except the credentials fallback). YOLONT_CONFIG_DIR overrides. */\nexport const CONFIG_DIR = env.YOLONT_CONFIG_DIR ?? adopt(win ? (env.APPDATA ?? join(homedir(), \"AppData\", \"Roaming\")) : env.XDG_CONFIG_HOME || join(homedir(), \".config\"));\n/** Reviews DB + resume cache. YOLONT_DATA_DIR overrides. */\nexport const DATA_DIR = env.YOLONT_DATA_DIR ?? adopt(win ? (env.LOCALAPPDATA ?? join(homedir(), \"AppData\", \"Local\")) : env.XDG_DATA_HOME || join(homedir(), \".local\", \"share\"));\n\nexport const DB_PATH = join(DATA_DIR, \"yolont.db\");\n// The DB file inside a taken-over folder (plus SQLite's -wal/-shm side files, so nothing is lost).\nif (!existsSync(DB_PATH) && existsSync(join(DATA_DIR, \"ethos.db\"))) {\n for (const ext of [\"\", \"-wal\", \"-shm\"]) {\n const from = join(DATA_DIR, `ethos.db${ext}`);\n if (existsSync(from)) renameSync(from, `${DB_PATH}${ext}`);\n }\n}\nexport const SESSIONS_PATH = join(DATA_DIR, \"sessions.json\");\n\n/** ~/.config/yolont/projects/<host>/<group>/<project> \u2014 `host` is a URL or bare host. */\nexport function userProjectDir(host: string, pathWithNamespace: string): string {\n // ':' (from a port) is illegal in Windows paths.\n return join(CONFIG_DIR, \"projects\", bareHost(host).replace(/:/g, \"_\"), ...pathWithNamespace.toLowerCase().split(\"/\"));\n}\n\n/** \"https://Git.Example.com:8443/gitlab\" -> \"git.example.com:8443\"; a bare host passes through lowercased. */\nexport function bareHost(hostOrUrl: string): string {\n return (/^[a-z]+:\\/\\//i.test(hostOrUrl) ? new URL(hostOrUrl).host : hostOrUrl).toLowerCase();\n}\n", "import { spawnSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { DATA_DIR } from \"../paths.js\";\n\n/**\n * gitleaks is a Go binary, not an npm package, so `npm install` can't bring it. Instead of a\n * postinstall download (skipped by --ignore-scripts and npx, and a supply-chain smell), the\n * wizard offers to fetch one pinned official release, verified against these SHA-256 sums\n * (copied from that release's checksums.txt), into Yolont's own data dir.\n */\nexport const GITLEAKS_VERSION = \"8.30.1\";\nconst SHA256: Record<string, string> = {\n darwin_arm64: \"b40ab0ae55c505963e365f271a8d3846efbc170aa17f2607f13df610a9aeb6a5\",\n darwin_x64: \"dfe101a4db2255fc85120ac7f3d25e4342c3c20cf749f2c20a18081af1952709\",\n linux_arm64: \"e4a487ee7ccd7d3a7f7ec08657610aa3606637dab924210b3aee62570fb4b080\",\n linux_x64: \"551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb\",\n windows_arm64: \"b95f5e4f5c425cedca7ee203d9afd29597e692c4924a12ed42f970537c72cc0f\",\n windows_x64: \"d29144deff3a68aa93ced33dddf84b7fdc26070add4aa0f4513094c8332afc4e\",\n};\n\nconst win = process.platform === \"win32\";\nexport const LOCAL_GITLEAKS = join(DATA_DIR, \"bin\", win ? \"gitleaks.exe\" : \"gitleaks\");\n\n/** Prefer our downloaded copy when there is one (src/checks/secrets.ts reads YOLONT_GITLEAKS). */\nexport function useLocalGitleaks(env: NodeJS.ProcessEnv = process.env): void {\n if (!env.YOLONT_GITLEAKS && existsSync(LOCAL_GITLEAKS)) env.YOLONT_GITLEAKS = LOCAL_GITLEAKS;\n}\n\nexport const gitleaksWorks = (): boolean => spawnSync(process.env.YOLONT_GITLEAKS || \"gitleaks\", [\"version\"], { stdio: \"ignore\" }).status === 0;\n\n/** The release asset for this machine, or undefined when there's no official build for it. */\nexport function gitleaksAsset(platform = process.platform, arch = process.arch): { name: string; sha256: string } | undefined {\n const os = platform === \"win32\" ? \"windows\" : platform;\n const key = `${os}_${arch === \"x64\" ? \"x64\" : arch === \"arm64\" ? \"arm64\" : arch}`;\n const sha256 = SHA256[key];\n return sha256 ? { name: `gitleaks_${GITLEAKS_VERSION}_${key}.${os === \"windows\" ? \"zip\" : \"tar.gz\"}`, sha256 } : undefined;\n}\n\n/** Downloads, checks the SHA-256, unpacks into DATA_DIR/bin. Throws on any mismatch; nothing is kept then. */\nexport async function installGitleaks(): Promise<string> {\n const asset = gitleaksAsset();\n if (!asset) throw new Error(`No official gitleaks build for ${process.platform}/${process.arch}.`);\n const res = await fetch(`https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/${asset.name}`, { signal: AbortSignal.timeout(120_000) });\n if (!res.ok) throw new Error(`Download failed: HTTP ${res.status}`);\n const bytes = Buffer.from(await res.arrayBuffer());\n const got = createHash(\"sha256\").update(bytes).digest(\"hex\");\n if (got !== asset.sha256) throw new Error(`Checksum mismatch for ${asset.name} (got ${got}). Not installed.`);\n\n const dir = mkdtempSync(join(tmpdir(), \"yolont-gitleaks-dl-\"));\n try {\n const archive = join(dir, asset.name);\n writeFileSync(archive, bytes);\n const exe = win ? \"gitleaks.exe\" : \"gitleaks\";\n // bsdtar (macOS, Windows 10+) reads .zip too; GNU tar on Linux gets .tar.gz.\n const tar = spawnSync(\"tar\", [\"-xf\", archive, \"-C\", dir, exe], { stdio: \"ignore\" });\n if (tar.status !== 0 || !existsSync(join(dir, exe))) throw new Error(\"Couldn't unpack the archive (is `tar` installed?).\");\n mkdirSync(join(DATA_DIR, \"bin\"), { recursive: true });\n copyFileSync(join(dir, exe), LOCAL_GITLEAKS);\n if (!win) chmodSync(LOCAL_GITLEAKS, 0o755);\n } finally {\n rmSync(dir, { recursive: true, force: true });\n }\n process.env.YOLONT_GITLEAKS = LOCAL_GITLEAKS;\n return LOCAL_GITLEAKS;\n}\n", "import { spawnSync } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/** This install's version: the nearest package.json named \"yolont\" above this file (bundle or source checkout). */\nexport function ownVersion(from = dirname(fileURLToPath(import.meta.url))): string | undefined {\n for (let dir = from, i = 0; i < 5; dir = dirname(dir), i++) {\n const file = join(dir, \"package.json\");\n if (!existsSync(file)) continue;\n try {\n const pkg = JSON.parse(readFileSync(file, \"utf8\")) as { name?: string; version?: string };\n if (pkg.name === \"yolont\") return pkg.version;\n } catch {\n // unreadable: keep walking\n }\n }\n return undefined;\n}\n\n/** True when `latest` is a higher x.y.z than `current` (pre-release suffixes ignored). */\nexport function isNewer(latest: string, current: string): boolean {\n const parts = (v: string) => v.split(/[-+]/)[0]!.split(\".\").map((n) => Number(n) || 0);\n const [a, b] = [parts(latest), parts(current)];\n for (let i = 0; i < 3; i++) if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) > (b[i] ?? 0);\n return false;\n}\n\n/** The `latest` version on npm, or undefined when offline, slow, or opted out. Sends nothing but the GET. */\nexport async function latestVersion(timeoutMs = 1500): Promise<string | undefined> {\n if (process.env.YOLONT_NO_UPDATE_CHECK || process.env.CI) return undefined;\n try {\n const res = await fetch(\"https://registry.npmjs.org/yolont/latest\", { signal: AbortSignal.timeout(timeoutMs) });\n if (!res.ok) return undefined;\n return ((await res.json()) as { version?: string }).version;\n } catch {\n return undefined;\n }\n}\n\n/** How this copy runs: npx cache, a global/local npm install, or a source checkout (tsx / alias). */\nexport function installKind(script = process.argv[1] ?? \"\"): \"npx\" | \"npm\" | \"source\" {\n if (/[\\\\/]_npx[\\\\/]/.test(script)) return \"npx\";\n if (/[\\\\/]node_modules[\\\\/]yolont[\\\\/]/.test(script) || /[\\\\/]bin[\\\\/]yolont$/.test(script)) return \"npm\";\n return \"source\";\n}\n\n/** Updates a global npm install. Returns false if npm failed (often EACCES on the global folder). */\nexport function installLatest(version: string): boolean {\n return spawnSync(\"npm\", [\"install\", \"-g\", `yolont@${version}`], { stdio: \"inherit\", shell: process.platform === \"win32\" }).status === 0;\n}\n", "import { existsSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { parseArgs } from \"node:util\";\nimport { openDb } from \"./db/client.js\";\nimport { findProjectId, stampLegacyProjectHost } from \"./db/repo.js\";\nimport { runBackfill } from \"./mining/backfill.js\";\nimport { runDistill } from \"./memory/distill.js\";\nimport { runInteractiveReview } from \"./review/interactiveReview.js\";\nimport { runSyncReplies } from \"./review/syncReplies.js\";\nimport { startDashboard } from \"./backoffice/server.js\";\nimport { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { parseEnv } from \"node:util\";\nimport { password } from \"@clack/prompts\";\nimport { resolveProjectFiles } from \"./conventions/resolve.js\";\nimport { defaultForgeHost, forgeFor, parseChange } from \"./forge.js\";\nimport { runSetup } from \"./setup/wizard.js\";\nimport type { Step } from \"./setup/state.js\";\nimport type { ForgeClient, ProjectRef } from \"../src/forge/types.js\";\nimport { applyConfigToEnv, CONFIG_PATH, forgeUrl, loadConfig, saveConfig } from \"./config/config.js\";\nimport { importEnv } from \"./config/importEnv.js\";\nimport { CREDENTIALS_PATH, deleteSecret, getSecret, maskSecret, secretBackend, setSecret } from \"./config/secrets.js\";\nimport { migrateLegacyState } from \"./legacyMigrate.js\";\nimport { addSource, describeRun, displayUrl, getSource, keepLocal, pendingToSend, removeSource, reviewMode, shareProject, sourceDir, sourceFor, sourceHost, sourcesForHost, stopUsing, syncAll } from \"./sync/source.js\";\nimport { parseGitAddress } from \"../src/forge/index.js\";\nimport { bareHost } from \"./paths.js\";\nimport { buildZoneGraph } from \"./zones/graph.js\";\nimport { loadZones, renderZonesMermaid } from \"../src/zones/zones.js\";\n\n// Precedence: shell env > ~/.config/yolont (config.yaml + secrets). An old .env is moved in\n// once with `yolont config import-env <path>`.\n\n/** `<MR/PR URL>` or legacy `<project-id> <mr-iid>` (on the default forge). */\nfunction changeArgs(positionals: string[], usage: string): { forge: ForgeClient; project: ProjectRef; mrIid: number } {\n const ref = positionals[0] ? parseChange(positionals[0]) : null;\n if (ref) return { forge: forgeFor(ref.host, ref.type), project: ref.projectPath, mrIid: ref.number };\n const project = Number(positionals[0]);\n const mrIid = Number(positionals[1]);\n if (!project || !mrIid) throw new Error(`Usage: ${usage}`);\n return { forge: forgeFor(defaultForgeHost()), project, mrIid };\n}\n\n/** `<project-id | group/project>` on `--host` (default forge). */\nfunction projectArg(arg: string | undefined, host: string | undefined, usage: string): { forge: ForgeClient; project: ProjectRef } {\n if (!arg) throw new Error(`Usage: ${usage}`);\n return { forge: forgeFor(host ?? defaultForgeHost()), project: /^\\d+$/.test(arg) ? Number(arg) : arg };\n}\n\n/** `yolont config \u2026` \u2014 inspect and fill ~/.config/yolont. The setup wizard (Phase 2) builds on this. */\nasync function runConfigCommand(args: string[]): Promise<void> {\n const [sub, arg] = args;\n const config = loadConfig();\n if (sub === \"import-env\") {\n if (!arg) throw new Error(\"Usage: yolont config import-env <path to .env>\");\n const path = resolve(arg);\n if (!existsSync(path)) throw new Error(`No env file at ${path}`);\n const { config: next, secrets, skipped } = importEnv(parseEnv(readFileSync(path, \"utf8\")), config);\n for (const [name, value] of Object.entries(secrets)) setSecret(name, value);\n saveConfig(next);\n console.log(`Wrote ${CONFIG_PATH}; ${Object.keys(secrets).length} secret(s) saved to ${secretBackend()}.`);\n for (const s of skipped) console.log(` skipped: ${s}`);\n console.log(`Secrets are now in ${secretBackend()}: delete ${path} once \\`yolont config show\\` looks right.`);\n return;\n }\n if (sub === \"set-secret\" || sub === \"delete-secret\") {\n if (!arg) throw new Error(`Usage: yolont config ${sub} <forge:<host> | llm:<profile> | jev>`);\n if (sub === \"delete-secret\") {\n deleteSecret(arg);\n console.log(`Deleted ${arg}.`);\n return;\n }\n const value = await password({ message: `Value for ${arg}` });\n if (typeof value !== \"string\" || !value.trim()) return;\n setSecret(arg, value.trim());\n console.log(`Saved ${arg} to ${secretBackend()}.`);\n return;\n }\n if (sub && sub !== \"show\") throw new Error(\"Usage: yolont config [show | import-env <path> | set-secret <name> | delete-secret <name>]\");\n\n console.log(`Config: ${CONFIG_PATH}${existsSync(CONFIG_PATH) ? \"\" : \" (not created yet)\"}`);\n console.log(`Secrets: ${secretBackend()}${secretBackend() === \"keychain\" ? \"\" : ` \u2014 ${CREDENTIALS_PATH}`}`);\n console.log(\"\\nForges:\");\n for (const f of config.forges) console.log(` ${f.host === config.defaultForge ? \"*\" : \" \"} ${f.host} ${f.type} ${forgeUrl(f)} token ${maskSecret(getSecret(`forge:${f.host}`))}`);\n console.log(\"\\nLLM profiles:\");\n for (const p of config.llmProfiles)\n console.log(` ${p.name === config.defaultLlmProfile ? \"*\" : \" \"} ${p.name} ${p.provider} ${p.model}${p.baseUrl ? ` ${p.baseUrl}` : \"\"} key ${p.provider === \"ollama\" ? \"(none needed)\" : maskSecret(getSecret(`llm:${p.name}`))}`);\n console.log(`\\nJev: key ${maskSecret(getSecret(\"jev\"))}${config.jev?.disabled ? \" (disabled)\" : \"\"}`);\n}\n\nasync function main(): Promise<void> {\n const [command, ...rest] = process.argv.slice(2);\n if (command === \"config\") return runConfigCommand(rest);\n if (command === \"--version\" || command === \"-v\" || command === \"version\") {\n const { ownVersion } = await import(\"./setup/version.js\");\n console.log(ownVersion() ?? \"unknown\");\n return;\n }\n applyConfigToEnv(loadConfig());\n (await import(\"./setup/gitleaks.js\")).useLocalGitleaks();\n // ponytail: legacy data has no host, so it's assumed to belong to CI_SERVER_URL; drop with the DB host migration.\n // Only into the default dirs: a sandbox (YOLONT_CONFIG_DIR / YOLONT_DATA_DIR, e.g. a fresh-setup\n // test) must never get a copy of the old install-dir DB \u2014 it holds colleagues' review data.\n const sandboxed = !!(process.env.YOLONT_CONFIG_DIR || process.env.YOLONT_DATA_DIR);\n const migrated = sandboxed ? [] : migrateLegacyState(process.env.CI_SERVER_URL);\n if (migrated.length > 0) console.error(`[yolont] copied pre-Yolont data to the user dirs:\\n${migrated.map((p) => ` ${p}`).join(\"\\n\")}`);\n // Must run before any upsertProject: a host-less legacy row never conflicts (NULL), so it'd be duplicated.\n if (process.env.CI_SERVER_URL) {\n const db = openDb();\n const stamped = stampLegacyProjectHost(db, process.env.CI_SERVER_URL);\n db.close();\n if (stamped > 0) console.error(`[yolont] ${stamped} pre-Yolont project(s) assigned to ${process.env.CI_SERVER_URL}.`);\n }\n\n // Bare `yolont` in a terminal: ask for whatever setup is missing, then pick a PR to review.\n if (!command && process.stdin.isTTY) return runSetup({ review: true });\n\n switch (command) {\n case \"setup\": {\n const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { step: { type: \"string\", multiple: true } } });\n const steps = values.step as Step[] | undefined;\n const bad = steps?.find((s) => ![\"forge\", \"llm\", \"conventions\", \"zones\", \"weights\"].includes(s));\n if (bad) throw new Error(`Unknown step '${bad}' \u2014 one of: forge, llm, conventions, zones, weights`);\n if (!process.stdin.isTTY) throw new Error(\"setup is interactive \u2014 run it in a terminal.\");\n await runSetup({ address: positionals[0], steps, all: !steps });\n return;\n }\n\n case \"conventions\": {\n const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { repo: { type: \"string\" } } });\n const action = positionals[0];\n if (action !== \"generate\" && action !== \"edit\") throw new Error(\"Usage: yolont conventions generate|edit [<git address | MR/PR URL>] [--repo <checkout>]\");\n if (!process.stdin.isTTY) throw new Error(\"conventions is interactive \u2014 run it in a terminal.\");\n await runSetup({ address: positionals[1], steps: [\"conventions\"], conventions: action, repo: values.repo && resolve(values.repo) });\n return;\n }\n\n case \"backfill\": {\n const { values, positionals } = parseArgs({\n args: rest,\n allowPositionals: true,\n options: {\n host: { type: \"string\" },\n \"max-mrs\": { type: \"string\", default: \"1000\" },\n \"with-llm\": { type: \"boolean\", default: false },\n zones: { type: \"boolean\", default: false },\n },\n });\n await runBackfill({\n ...projectArg(positionals[0], values.host, \"yolont backfill <project-id | group/project> [--host h] [--max-mrs 1000] [--with-llm] [--zones]\"),\n maxMrs: Number(values[\"max-mrs\"]),\n withLlm: Boolean(values[\"with-llm\"]),\n zones: Boolean(values.zones),\n });\n return;\n }\n\n case \"review\": {\n const { values, positionals } = parseArgs({\n args: rest,\n allowPositionals: true,\n options: {\n \"pipeline-id\": { type: \"string\" },\n focus: { type: \"string\" },\n },\n });\n // No target: same as bare `yolont` \u2014 setup check, then the open-PR picker.\n if (positionals.length === 0) {\n if (!process.stdin.isTTY) throw new Error('Usage: yolont review <MR/PR URL> | <project-id> <mr-iid> [--pipeline-id N] [--focus \"...\"]');\n return runSetup({ review: true });\n }\n await runInteractiveReview({\n ...changeArgs(positionals, 'yolont review <MR/PR URL> | <project-id> <mr-iid> [--pipeline-id N] [--focus \"...\"]'),\n pipelineId: values[\"pipeline-id\"] ? Number(values[\"pipeline-id\"]) : undefined,\n reviewerFocus: values.focus,\n });\n return;\n }\n\n case \"sync-replies\": {\n const { positionals } = parseArgs({ args: rest, allowPositionals: true, options: {} });\n await runSyncReplies(changeArgs(positionals, \"yolont sync-replies <MR/PR URL> | <project-id> <mr-iid>\"));\n return;\n }\n\n case \"distill\": {\n const { values } = parseArgs({\n args: rest,\n options: {\n author: { type: \"string\" },\n project: { type: \"string\" },\n host: { type: \"string\" },\n },\n });\n const db = openDb();\n // --project is the forge's project id (as everywhere on the CLI); memory is keyed by Yolont's own id.\n const projectId = values.project ? findProjectId(db, values.host ?? defaultForgeHost(), values.project) : undefined;\n if (values.project && projectId === undefined) throw new Error(`Project ${values.project} isn't in the DB yet \u2014 review or backfill it first.`);\n const author = values.author ? { host: bareHost(values.host ?? defaultForgeHost()), username: values.author } : undefined;\n await runDistill(db, { author, projectId });\n db.close();\n return;\n }\n\n case \"panel\":\n case \"dashboard\": {\n const { values } = parseArgs({\n args: rest,\n options: {\n port: { type: \"string\", default: \"4173\" },\n },\n });\n // Clients are made per finding's host on demand; a host without a token fails that sync only.\n await startDashboard({ port: Number(values.port), forgeFor: (host) => forgeFor(host) });\n return;\n }\n\n case \"zones\": {\n const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { repo: { type: \"string\" }, host: { type: \"string\" } } });\n if (positionals[0] === \"generate\" || positionals[0] === \"edit\") {\n if (!process.stdin.isTTY) throw new Error(\"zones generate|edit is interactive \u2014 run it in a terminal.\");\n await runSetup({ address: positionals[1], steps: [\"zones\"], zones: positionals[0], repo: values.repo && resolve(values.repo) });\n return;\n }\n const graphMode = positionals[0] === \"graph\";\n const projectPath = graphMode ? positionals[1] : positionals[0];\n if (!projectPath || (graphMode && !values.repo)) {\n throw new Error(\"Usage: yolont zones <group/project> | yolont zones graph <group/project> --repo <checkout>\");\n }\n const files = resolveProjectFiles(values.host ?? defaultForgeHost(), projectPath);\n const zones = files.zones ? loadZones(files.zones) : null;\n if (!zones) throw new Error(`No zones.yaml in .yolont/ or ${files.dir}`);\n if (!graphMode) {\n console.log(renderZonesMermaid(zones));\n return;\n }\n console.log(`[zones] building import graph of ${values.repo} (can take a while on big repos)\u2026`);\n const graph = await buildZoneGraph(values.repo!, zones);\n mkdirSync(files.dir, { recursive: true });\n const out = join(files.dir, \"zones.graph.json\");\n writeFileSync(out, `${JSON.stringify(graph, null, 2)}\\n`);\n for (const [id, files] of Object.entries(graph.reachable)) console.log(` ${id}: ${files.length} file(s) reachable via import`);\n console.log(`[zones] wrote ${out}${graph.sha ? ` (@ ${graph.sha.slice(0, 8)})` : \"\"} \u2014 for CI, commit it to the target repo as .yolont/zones.graph.json`);\n return;\n }\n\n case \"source\": {\n const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { source: { type: \"string\" }, name: { type: \"string\" }, host: { type: \"string\" }, force: { type: \"boolean\", default: false } } });\n const [action, a, b] = positionals;\n const addressOf = (raw: string) => {\n const address = parseGitAddress(raw, loadConfig().forges.filter((f) => f.type === \"gitlab\" && f.url).map(forgeUrl));\n if (!address) throw new Error(`Not a git address: ${raw}`);\n return address;\n };\n if (action === \"add\" && a && b) {\n const source = await addSource(a, b, values.name, values.host);\n console.log(`Connected memory repo '${source.name}' (${sourceDir(source.name)}). Use it for a project with: yolont source use <git address> --source ${source.name}`);\n return;\n }\n if ((action === \"use\" || action === \"share\") && a) {\n const address = addressOf(a);\n // Pick by name, or the only repo on the project's host: never one from another host.\n const onHost = sourcesForHost(address.host);\n if (!values.source && onHost.length !== 1) throw new Error(onHost.length ? `Several memory repos on ${address.host} (${onHost.map((s) => s.name).join(\", \")}): pick one with --source <name>.` : `No memory repo on ${address.host} yet: yolont source add <name> <git-url>.`);\n const source = values.source ? getSource(values.source) : onHost[0]!;\n const db = openDb();\n try {\n const current = sourceFor(address.host, address.projectPath);\n if (current?.name === source.name) {\n console.log(`${address.host}/${address.projectPath} already uses '${source.name}'.`);\n return;\n }\n if (current) stopUsing(db, address.host, address.projectPath);\n const { copied, kept } = await shareProject(source.name, address.host, address.projectPath);\n console.log(`${address.host}/${address.projectPath} now uses memory repo '${source.name}'${current ? ` (was '${current.name}')` : \"\"}.${copied.length ? ` Moved in: ${copied.join(\", \")}.` : \"\"}${kept.length ? ` The repo's ${kept.join(\", \")} kept (yours stays in the user dir).` : \"\"} Run \\`yolont sync\\` to get and send.`);\n } finally {\n db.close();\n }\n return;\n }\n if (action === \"stop\" && a) {\n const address = addressOf(a);\n const db = openDb();\n try {\n const was = stopUsing(db, address.host, address.projectPath);\n keepLocal(address.host, address.projectPath);\n console.log(was ? `${address.host}/${address.projectPath} no longer uses '${was}'; only your own memory from now on.` : \"That project doesn't use a memory repo.\");\n } finally {\n db.close();\n }\n return;\n }\n if (action === \"rm\" && a) {\n const db = openDb();\n try {\n const unsent = await pendingToSend(db, getSource(a)).catch(() => 0);\n if (unsent && !values.force) throw new Error(`'${a}' has ${unsent} change(s) of yours that were never sent; run \\`yolont sync --source ${a}\\` first, or pass --force to drop them.`);\n removeSource(db, a);\n console.log(`Removed memory repo '${a}' from this machine (its local copy and what came from it). The repo itself is untouched.`);\n } finally {\n db.close();\n }\n return;\n }\n if (action === \"ls\" || !action) {\n const config = loadConfig();\n if (!config.sources?.length) console.log(\"No memory repos. Add one: yolont source add <name> <git-url>\");\n for (const src of config.sources ?? []) console.log(`${src.name} ${displayUrl(src.url)} (${sourceHost(src) ?? \"?\"}${reviewMode(sourceDir(src.name)) ? \", merge requests\" : \", direct push\"})\\n used by: ${src.projects.map((p) => (p.split(\"/\")[0] === sourceHost(src) ? p : `${p} (ignored: not on ${sourceHost(src) ?? \"its host\"})`)).join(\", \") || \"(nothing yet)\"}`);\n if (config.member) console.log(`\\nYou are '${config.member.name}' (records folder ${config.member.id}).`);\n return;\n }\n throw new Error(\"Usage: yolont source add <name> <git-url> [--name <your name>] [--host <git host>] | yolont source use <git address> [--source <name>] | yolont source stop <git address> | yolont source rm <name> [--force] | yolont source ls\");\n }\n\n case \"sync\": {\n const { values } = parseArgs({ args: rest, options: { source: { type: \"string\" }, pull: { type: \"boolean\", default: false } } });\n // No --source: every repo in turn; one failing doesn't stop the others.\n const sources = values.source ? [getSource(values.source)] : (loadConfig().sources ?? []);\n if (sources.length === 0) getSource();\n const db = openDb();\n let failed = 0;\n try {\n for (const run of await syncAll(db, values.pull ? \"pull\" : \"sync\", sources)) {\n if (run.error) failed++;\n (run.error ? console.error : console.log)(`[sync] ${describeRun(run)}`);\n for (const f of run.result?.rejected ?? []) console.warn(`[sync] skipped (doesn't belong there): ${f}`);\n }\n } finally {\n db.close();\n }\n if (failed) process.exitCode = 1;\n return;\n }\n\n default:\n console.log(\n [\n \"Yolont \u2014 usage:\",\n \" yolont (no args) guided: set up whatever is missing, then pick an open MR/PR to review\",\n \" yolont conventions generate|edit [<git address | MR/PR URL>] [--repo <checkout>] (LLM drafts from the repo; you approve/edit; max 300 lines, conventionsMaxLines in config.yaml)\",\n \" yolont setup [<git address | MR/PR URL>] [--step forge|llm|conventions|zones|weights] (re-run setup; every step shows the saved value first)\",\n \" yolont review <MR/PR URL> [--pipeline-id N] [--focus \\\"...\\\"] (or <project-id> <mr-iid> on the default host)\",\n \" yolont sync-replies <MR/PR URL> (or <project-id> <mr-iid>)\",\n \" yolont backfill <project-id | group/project> [--host h] [--max-mrs 1000] [--with-llm] [--zones] (--zones: match MRs to the project's zones.yaml, no LLM)\",\n \" yolont distill [--author <username>] [--project <project-id>] [--host h]\",\n \" yolont panel [--port 4173] (alias: dashboard; prints a URL with a per-start access token)\",\n \" yolont zones generate|edit [<git address | MR/PR URL>] [--repo <checkout>] (draft zones from the stack's template; edit / skip)\",\n \" yolont zones <group/project> [--host h] (print the project's zone map as Mermaid)\",\n \" yolont zones graph <group/project> --repo <checkout> [--host h] (write zones.graph.json: files red zones import)\",\n \" yolont config [show | import-env <path> | set-secret <name> | delete-secret <name>]\",\n \" yolont source add <name> <git-url> [--name <your name>] [--host <git host>] (connect a memory repo: shared reviews, memory, conventions, zones)\",\n \" yolont source use <git address> [--source <name>] (a project uses one memory repo, on its own git host; switches if it had another)\",\n \" yolont source stop <git address> \u00B7 yolont source rm <name> [--force] \u00B7 yolont source ls\",\n \" yolont sync [--pull] [--source <name>] (send your records and get the team's, every repo unless --source; --pull only gets)\",\n \"\",\n `Git host, token and LLM come from ${CONFIG_PATH} + the OS keychain (shell env overrides).`,\n ].join(\"\\n\"),\n );\n process.exitCode = command && command !== \"help\" && command !== \"--help\" ? 1 : 0;\n }\n}\n\nmain().catch((err) => {\n console.error(`[yolont] ${(err as Error).message}`);\n process.exitCode = 1;\n});\n", "import { DatabaseSync } from \"node:sqlite\";\nimport { mkdirSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { DB_PATH, INSTALL_ROOT } from \"../paths.js\";\nimport { backfillInsightHosts } from \"./repo.js\";\n// From INSTALL_ROOT, not this file: in the published bundle this code lives in dist/cli.js.\nconst SCHEMA_PATH = join(INSTALL_ROOT, \"local\", \"db\", \"schema.sql\");\nexport const DEFAULT_DB_PATH = DB_PATH;\n\n/**\n * node:sqlite (built into Node 22+), not better-sqlite3 \u2014 the native better-sqlite3\n * binding segfaulted on this machine (prebuild/ABI mismatch unrelated to this project),\n * while node:sqlite is compiled into the exact Node binary running it, so there's no\n * separate native binary to mismatch. One less native dependency either way.\n */\nexport function openDb(dbPath: string = DEFAULT_DB_PATH): DatabaseSync {\n if (dbPath !== \":memory:\") mkdirSync(dirname(dbPath), { recursive: true });\n const db = new DatabaseSync(dbPath);\n db.exec(\"PRAGMA foreign_keys = ON;\");\n db.exec(readFileSync(SCHEMA_PATH, \"utf8\"));\n migrate(db);\n return db;\n}\n\n/**\n * `CREATE TABLE IF NOT EXISTS` (above) only affects brand-new databases \u2014 an existing\n * local/data/pr-score.db predates a column added later needs it added in place. Kept as\n * plain, additive `ALTER TABLE ... ADD COLUMN` steps (SQLite has no real migration\n * framework and this DB is a local cache, not something to over-engineer for).\n */\nexport const SYNCED_TABLES = [\"scores\", \"corrections\", \"insights\", \"finding_votes\", \"finding_tags\"] as const;\n\nfunction migrate(db: DatabaseSync): void {\n const projectCols = db.prepare(\"PRAGMA table_info(projects)\").all() as { name: string }[];\n if (!projectCols.some((c) => c.name === \"forge_host\")) {\n db.exec(\"ALTER TABLE projects ADD COLUMN forge_host TEXT\");\n db.exec(\"ALTER TABLE projects ADD COLUMN forge_project_id TEXT\");\n // Pre-Yolont: id was the GitLab project id.\n db.exec(\"UPDATE projects SET forge_project_id = CAST(id AS TEXT)\");\n }\n db.exec(\"CREATE UNIQUE INDEX IF NOT EXISTS idx_projects_forge ON projects (forge_host, forge_project_id)\");\n\n const insightsCols = db.prepare(\"PRAGMA table_info(insights)\").all() as { name: string }[];\n if (!insightsCols.some((c) => c.name === \"project_id\")) {\n db.exec(\"ALTER TABLE insights ADD COLUMN project_id INTEGER REFERENCES projects (id)\");\n }\n db.exec(\"CREATE INDEX IF NOT EXISTS idx_insights_project ON insights (project_id)\");\n if (!insightsCols.some((c) => c.name === \"host\")) {\n db.exec(\"ALTER TABLE insights ADD COLUMN host TEXT\");\n }\n\n const correctionsCols = db.prepare(\"PRAGMA table_info(corrections)\").all() as { name: string }[];\n if (!correctionsCols.some((c) => c.name === \"corrected_note\")) {\n db.exec(\"ALTER TABLE corrections ADD COLUMN corrected_note TEXT\");\n }\n\n const discussionCols = db.prepare(\"PRAGMA table_info(finding_discussions)\").all() as { name: string }[];\n if (!discussionCols.some((c) => c.name === \"decision_note_id\")) {\n db.exec(\"ALTER TABLE finding_discussions ADD COLUMN decision_note_id INTEGER\");\n db.exec(\"ALTER TABLE finding_discussions ADD COLUMN decision_sync_error TEXT\");\n }\n\n const scoresCols = db.prepare(\"PRAGMA table_info(scores)\").all() as { name: string }[];\n if (!scoresCols.some((c) => c.name === \"volume_factor\")) {\n db.exec(\"ALTER TABLE scores ADD COLUMN volume_factor REAL NOT NULL DEFAULT 1\");\n }\n if (!scoresCols.some((c) => c.name === \"base_json\")) {\n db.exec(\"ALTER TABLE scores ADD COLUMN base_json TEXT\");\n }\n if (!scoresCols.some((c) => c.name === \"change_type\")) {\n db.exec(\"ALTER TABLE scores ADD COLUMN change_type TEXT\");\n }\n\n widenFindingTagsCheck(db); // rebuilds finding_tags from schema.sql, so the sync columns come after\n // Memory repos: uid = the record's id in a team data repo, origin = the source a\n // row was imported from (NULL = made here).\n for (const table of SYNCED_TABLES) {\n const cols = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];\n if (!cols.some((c) => c.name === \"uid\")) {\n db.exec(`ALTER TABLE ${table} ADD COLUMN uid TEXT`);\n db.exec(`ALTER TABLE ${table} ADD COLUMN origin TEXT`);\n }\n db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${table}_uid ON ${table} (uid) WHERE uid IS NOT NULL`);\n }\n\n backfillFindings(db);\n backfillInsightHosts(db);\n}\n\n/**\n * SQLite can't ALTER a CHECK constraint, so a DB created before 'danger-zone' was a valid\n * tag rejects it forever. Rebuild finding_tags once (rows copied as-is) when its stored\n * DDL predates that tag.\n */\nfunction widenFindingTagsCheck(db: DatabaseSync): void {\n const { sql } = db.prepare(\"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'finding_tags'\").get() as { sql: string };\n if (sql.includes(\"'danger-zone'\")) return;\n const createSql = readFileSync(SCHEMA_PATH, \"utf8\").match(/CREATE TABLE IF NOT EXISTS finding_tags \\([\\s\\S]*?\\n\\);/)![0];\n // SQLite's documented table-rebuild procedure: FKs off (only settable outside a transaction).\n db.exec(\"PRAGMA foreign_keys = OFF\");\n db.exec(\"BEGIN\");\n try {\n db.exec(\"ALTER TABLE finding_tags RENAME TO finding_tags_old\");\n db.exec(createSql);\n db.exec(\"INSERT INTO finding_tags (id, finding_id, tag, created_at) SELECT id, finding_id, tag, created_at FROM finding_tags_old\");\n db.exec(\"DROP TABLE finding_tags_old\");\n db.exec(\"CREATE INDEX IF NOT EXISTS idx_finding_tags_finding ON finding_tags (finding_id)\");\n db.exec(\"CREATE INDEX IF NOT EXISTS idx_finding_tags_tag ON finding_tags (tag)\");\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw err;\n } finally {\n db.exec(\"PRAGMA foreign_keys = ON\");\n }\n}\n\n/**\n * One-time backfill: the `findings` table didn't exist before this feature, so MRs scored\n * prior to it have no rows there. Guarded on `findings` being empty so this only ever runs\n * once \u2014 after that, `upsertFindingsForScore` is the sole writer.\n */\nfunction backfillFindings(db: DatabaseSync): void {\n const { count } = db.prepare(\"SELECT COUNT(*) AS count FROM findings\").get() as { count: number };\n if (count > 0) return;\n\n const scores = db.prepare(\"SELECT merge_request_id, findings_json FROM scores\").all() as {\n merge_request_id: number;\n findings_json: string;\n }[];\n const insert = db.prepare(\n `INSERT INTO findings (merge_request_id, category, severity, issue, file, line)\n VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT (merge_request_id, file, line, issue) DO NOTHING`,\n );\n for (const s of scores) {\n const findings = JSON.parse(s.findings_json) as {\n category?: string;\n severity: string;\n issue: string;\n file?: string;\n line?: number;\n }[];\n for (const f of findings) {\n insert.run(s.merge_request_id, f.category ?? null, f.severity, f.issue, f.file ?? null, f.line ?? null);\n }\n }\n}\n", "import { z } from \"zod\";\n\nexport const CategoryTypeSchema = z.enum([\"deterministic\", \"llm\", \"hybrid\"]);\nexport type CategoryType = z.infer<typeof CategoryTypeSchema>;\n\nexport const CategorySchema = z.object({\n name: z.string().min(1),\n weight: z.number().min(0).max(100),\n type: CategoryTypeSchema,\n // Required for deterministic/hybrid categories. One of: \"diff_size\", \"test_report\",\n // or \"job:<substring>\" (matched against this pipeline's job names). \"secrets\" is not\n // a valid source here \u2014 the gitleaks scan is an unconditional pre-check in index.ts\n // that runs before any category is scored; a hit short-circuits the whole run before\n // this code path is reached, so wiring it as a source can only ever produce a\n // constant pass-through score (a real bug this schema previously allowed).\n source: z.string().optional(),\n min_coverage: z.number().min(0).max(100).optional(),\n // Fed to the LLM as rubric context for llm/hybrid categories. Falls back to a generic prompt if omitted.\n description: z.string().optional(),\n});\nexport type Category = z.infer<typeof CategorySchema>;\n\nexport const SeverityPenaltiesSchema = z.object({\n minor: z.number().min(0).default(3),\n major: z.number().min(0).default(8),\n critical: z.number().min(0).default(20),\n});\n\n// Findings are scored as density, not raw count: each penalty is multiplied by\n// clamp((reference_size / mr_size) ^ exponent, min_factor, max_factor), where\n// mr_size = changed_lines + lines_per_file * changed_files. exponent 0 disables scaling.\nexport const VolumeScalingSchema = z.object({\n reference_size: z.number().positive().default(200),\n lines_per_file: z.number().min(0).default(30),\n exponent: z.number().min(0).default(0.7),\n min_factor: z.number().positive().default(0.25),\n max_factor: z.number().positive().default(3),\n}).refine((v) => v.min_factor <= v.max_factor, { message: \"min_factor must be <= max_factor\", path: [\"min_factor\"] });\nexport type VolumeScaling = z.infer<typeof VolumeScalingSchema>;\n\nexport const DEFAULT_VOLUME_SCALING: VolumeScaling = {\n reference_size: 200,\n lines_per_file: 30,\n exponent: 0.7,\n min_factor: 0.25,\n max_factor: 3,\n};\n\nexport const RubricSchema = z\n .object({\n version: z.literal(1),\n gate: z.boolean().default(false),\n threshold: z.number().min(0).max(100).default(80),\n max_diff_bytes: z.number().positive().default(100_000),\n max_lines: z.number().positive().default(500),\n severity_penalties: SeverityPenaltiesSchema.default({ minor: 3, major: 8, critical: 20 }),\n volume_scaling: VolumeScalingSchema.default(DEFAULT_VOLUME_SCALING),\n categories: z.array(CategorySchema).min(1),\n })\n .superRefine((rubric, ctx) => {\n const sum = rubric.categories.reduce((total, c) => total + c.weight, 0);\n if (sum !== 100) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Rubric weights must sum to 100, got ${sum}`,\n path: [\"categories\"],\n });\n }\n\n const seen = new Set<string>();\n for (let i = 0; i < rubric.categories.length; i++) {\n const c = rubric.categories[i]!;\n if (seen.has(c.name)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Duplicate category name '${c.name}'`,\n path: [\"categories\", i, \"name\"],\n });\n }\n seen.add(c.name);\n\n if ((c.type === \"deterministic\" || c.type === \"hybrid\") && !c.source) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Category '${c.name}' has type '${c.type}' and requires a 'source'`,\n path: [\"categories\", i, \"source\"],\n });\n }\n\n if (c.source === \"secrets\") {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Category '${c.name}': source 'secrets' is not supported \u2014 the secrets scan is an unconditional pre-check that runs before category scoring and always short-circuits before this source would be read, so it can only produce a constant pass-through score. Use type: llm for a narrative security review instead.`,\n path: [\"categories\", i, \"source\"],\n });\n }\n }\n });\n\nexport type Rubric = z.infer<typeof RubricSchema>;\n", "import type { VolumeScaling } from \"../rubric/schema.js\";\nimport type { CategoryResult, Finding, FinalScoreResult, ScoredCategory, SeverityPenalties } from \"./types.js\";\n\n/**\n * The LLM's own `score` field is advisory only \u2014 the real category\n * score is always recomputed here from findings + severity, so a model can\n * never freehand the number.\n */\nexport function scoreFromFindings(findings: Finding[], penalties: SeverityPenalties, volumeFactor = 1): number {\n const totalPenalty = findings.reduce((sum, f) => sum + penalties[f.severity], 0) * volumeFactor;\n return Math.round(clamp(100 - totalPenalty, 0, 100));\n}\n\n/**\n * Penalty multiplier from MR size, so findings count as density rather than raw totals:\n * one major in a 1-file change hurts more than two criticals spread over 30 files.\n * Sublinear (exponent < 1) on purpose \u2014 reviewers catch proportionally fewer issues in\n * big diffs, so fully linear dilution would reward oversized MRs.\n */\nexport function volumeFactor(stats: { added: number; deleted: number; files: number }, cfg: VolumeScaling): number {\n const size = Math.max(1, stats.added + stats.deleted + cfg.lines_per_file * stats.files);\n return clamp((cfg.reference_size / size) ** cfg.exponent, cfg.min_factor, cfg.max_factor);\n}\n\nexport function computeFinalScore(categories: CategoryResult[], threshold: number): FinalScoreResult {\n const availableWeight = categories.filter((c) => c.available).reduce((sum, c) => sum + c.weight, 0);\n\n const scored: ScoredCategory[] = categories.map((c) => {\n if (!c.available) {\n return { ...c, effectiveWeight: 0 };\n }\n // Renormalize so available categories' weights still sum to 100 when some are excluded.\n const effectiveWeight = availableWeight > 0 ? (c.weight / availableWeight) * 100 : 0;\n return { ...c, effectiveWeight };\n });\n\n const finalScoreRaw =\n availableWeight > 0\n ? scored.reduce((sum, c) => sum + (c.score * c.effectiveWeight) / 100, 0)\n : 50; // nothing was available this run \u2014 neutral, documented via each category's note\n\n const finalScore = Math.round(clamp(finalScoreRaw, 0, 100));\n\n return {\n categories: scored,\n finalScore,\n pass: finalScore >= threshold,\n };\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, value));\n}\n", "import type { DatabaseSync } from \"node:sqlite\";\nimport type { ZoneLevel, ZoneReport } from \"../../src/zones/zones.js\";\nimport { SeverityPenaltiesSchema } from \"../../src/rubric/schema.js\";\nimport { computeFinalScore } from \"../../src/scoring/engine.js\";\nimport { bareHost } from \"../paths.js\";\nimport type { CategoryResult, SeverityPenalties } from \"../../src/scoring/types.js\";\n\n// ponytail: rubric defaults, not the repo's .pr-score rubric (not stored locally); the vote UI lets you override the score.\nconst DEFAULT_PENALTIES: SeverityPenalties = SeverityPenaltiesSchema.parse({});\n\nexport interface MergeRequestRow {\n id: number;\n mined_discussions_at: string | null;\n}\n\n/** Returns the Yolont project id (projects.id) \u2014 use it for every DB call; `project.id` is the\n * forge's id, only for API calls. Same forge id on two hosts = two projects. */\nexport function upsertProject(db: DatabaseSync, project: { host: string; id: number | string; pathWithNamespace: string; name: string }): number {\n const row = db\n .prepare(\n `INSERT INTO projects (forge_host, forge_project_id, path_with_namespace, name) VALUES (?, ?, ?, ?)\n ON CONFLICT(forge_host, forge_project_id) DO UPDATE SET path_with_namespace = excluded.path_with_namespace, name = excluded.name\n RETURNING id`,\n )\n .get(bareHost(project.host), String(project.id), project.pathWithNamespace, project.name) as unknown as { id: number };\n return row.id;\n}\n\nexport function findProjectId(db: DatabaseSync, host: string, forgeProjectId: number | string): number | undefined {\n const row = db.prepare(`SELECT id FROM projects WHERE forge_host = ? AND forge_project_id = ?`).get(bareHost(host), String(forgeProjectId)) as\n | { id: number }\n | undefined;\n return row?.id;\n}\n\n/** Pre-Yolont rows have no host; they all came from one GitLab, so claim them for it. Idempotent. */\nexport function stampLegacyProjectHost(db: DatabaseSync, host: string): number {\n const changes = Number(db.prepare(`UPDATE projects SET forge_host = ? WHERE forge_host IS NULL`).run(bareHost(host)).changes);\n backfillInsightHosts(db);\n return changes;\n}\n\n/**\n * A person is (git host, username): `alice` on GitHub and `alice` on a company GitLab are two\n * people, and one's memory must never reach the other's reviews.\n */\nexport interface AuthorKey {\n host: string;\n username: string;\n}\n\n/**\n * Gives every insight the host it belongs to. Idempotent (only fills NULLs), so it's run on\n * every DB open and again right after legacy projects get their host: from its project, else\n * from its evidence MRs when they agree on one host, else \u2014 on a single-host DB \u2014 that host.\n * Whatever is still NULL is ambiguous and stays out of review prompts.\n */\nexport function backfillInsightHosts(db: DatabaseSync): void {\n db.exec(`UPDATE insights SET host = (SELECT forge_host FROM projects WHERE id = insights.project_id)\n WHERE host IS NULL AND project_id IS NOT NULL`);\n db.exec(`UPDATE insights SET host = (\n SELECT MIN(p.forge_host) FROM json_each(insights.evidence_mr_ids_json) j\n JOIN merge_requests mr ON mr.id = j.value JOIN projects p ON p.id = mr.project_id)\n WHERE host IS NULL AND (\n SELECT COUNT(DISTINCT p.forge_host) = 1 AND COUNT(*) = COUNT(p.forge_host) FROM json_each(insights.evidence_mr_ids_json) j\n JOIN merge_requests mr ON mr.id = j.value JOIN projects p ON p.id = mr.project_id)`);\n db.exec(`UPDATE insights SET host = (SELECT forge_host FROM projects LIMIT 1)\n WHERE host IS NULL\n AND (SELECT COUNT(DISTINCT forge_host) FROM projects) = 1\n AND NOT EXISTS (SELECT 1 FROM projects WHERE forge_host IS NULL)`);\n}\n\nexport function upsertMergeRequest(\n db: DatabaseSync,\n mr: {\n projectId: number;\n mrIid: number;\n authorUsername: string;\n sha: string;\n title: string;\n mergedAt: string | null;\n source: \"backfill\" | \"live\";\n },\n): MergeRequestRow {\n const row = db\n .prepare(\n `INSERT INTO merge_requests (project_id, mr_iid, author_username, sha, title, merged_at, source)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(project_id, mr_iid) DO UPDATE SET sha = excluded.sha, title = excluded.title, merged_at = excluded.merged_at\n RETURNING id, mined_discussions_at`,\n )\n .get(mr.projectId, mr.mrIid, mr.authorUsername, mr.sha, mr.title, mr.mergedAt, mr.source) as unknown as MergeRequestRow;\n return row;\n}\n\nexport function getMergeRequestByProjectAndIid(db: DatabaseSync, projectId: number, mrIid: number): MergeRequestRow | undefined {\n return db\n .prepare(`SELECT id, mined_discussions_at FROM merge_requests WHERE project_id = ? AND mr_iid = ?`)\n .get(projectId, mrIid) as unknown as MergeRequestRow | undefined;\n}\n\nexport function markDiscussionsMined(db: DatabaseSync, mergeRequestId: number): void {\n db.prepare(`UPDATE merge_requests SET mined_discussions_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') WHERE id = ?`).run(\n mergeRequestId,\n );\n}\n\nexport function insertHumanComment(\n db: DatabaseSync,\n c: { mergeRequestId: number; authorUsername: string; body: string; file?: string; line?: number; createdAt: string },\n): void {\n db.prepare(\n `INSERT INTO human_review_comments (merge_request_id, author_username, body, file, line, created_at) VALUES (?, ?, ?, ?, ?, ?)`,\n ).run(c.mergeRequestId, c.authorUsername, c.body, c.file ?? null, c.line ?? null, c.createdAt);\n}\n\nexport function upsertScore(\n db: DatabaseSync,\n s: {\n mergeRequestId: number;\n scoredAt: string;\n finalScore: number;\n categoryScores: Record<string, number>;\n findings: unknown;\n source: \"llm_backfill\" | \"llm_live\";\n modelUsed?: string;\n volumeFactor?: number;\n /** Machine scores + rubric weights before any human correction \u2014 what refreshScores\n * rebuilds the total from. Without it a past review can't be recomputed. */\n base: ScoreBase;\n /** src/changeType.ts; null = not classified. */\n changeType?: string | null;\n },\n): void {\n db.prepare(\n `INSERT INTO scores (merge_request_id, scored_at, final_score, category_scores_json, findings_json, source, model_used, volume_factor, base_json, change_type)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(merge_request_id, source) DO UPDATE SET\n -- Re-reviewing makes the row yours again: a teammate's imported row must not keep\n -- their uid/origin, or your newer review would never be shared and their file would\n -- overwrite it on the next import. Your own row keeps its uid (its file is rewritten).\n uid = CASE WHEN origin IS NULL THEN uid ELSE NULL END,\n origin = NULL,\n scored_at = excluded.scored_at,\n final_score = excluded.final_score,\n category_scores_json = excluded.category_scores_json,\n findings_json = excluded.findings_json,\n model_used = excluded.model_used,\n volume_factor = excluded.volume_factor,\n base_json = excluded.base_json,\n change_type = excluded.change_type`,\n ).run(\n s.mergeRequestId,\n s.scoredAt,\n s.finalScore,\n JSON.stringify(s.categoryScores),\n JSON.stringify(s.findings),\n s.source,\n s.modelUsed ?? null,\n s.volumeFactor ?? 1,\n JSON.stringify(s.base),\n s.changeType ?? null,\n );\n upsertFindingsForScore(db, s.mergeRequestId, s.findings as { category?: string; severity: string; issue: string; file?: string; line?: number }[]);\n refreshScores(db, s.mergeRequestId);\n}\n\nexport type ScoreBase = Pick<CategoryResult, \"name\" | \"score\" | \"weight\" | \"available\">[];\n\n/**\n * Re-derives final_score + category_scores_json for every score row of an MR from its\n * machine base plus the corrections made since that row was scored (latest per category\n * wins; a category-less correction overrides the total). Same computeFinalScore the\n * review used, so TUI, panel edits and finding votes all agree. Called after every\n * score/correction write. Corrections older than the score belong to a previous review\n * of this MR and are ignored. Rows from before base_json existed are left as stored.\n */\nexport function refreshScores(db: DatabaseSync, mergeRequestId: number): void {\n const rows = db\n .prepare(`SELECT id, scored_at, base_json FROM scores WHERE merge_request_id = ? AND base_json IS NOT NULL`)\n .all(mergeRequestId) as unknown as { id: number; scored_at: string; base_json: string }[];\n const update = db.prepare(`UPDATE scores SET final_score = ?, category_scores_json = ? WHERE id = ?`);\n for (const row of rows) {\n const r = scoreFromBase(JSON.parse(row.base_json) as ScoreBase, correctionsSince(db, mergeRequestId, row.scored_at));\n update.run(r.finalScore, JSON.stringify(r.categoryScores), row.id);\n }\n}\n\ntype BaseCorrection = { category: string | null; corrected_score: number };\n\nfunction correctionsSince(db: DatabaseSync, mergeRequestId: number, scoredAt: string): BaseCorrection[] {\n return db\n .prepare(`SELECT category, corrected_score FROM corrections WHERE merge_request_id = ? AND created_at >= ? ORDER BY created_at, id`)\n .all(mergeRequestId, scoredAt) as unknown as BaseCorrection[];\n}\n\n/** The one place a total is derived: machine base + latest correction per category (+ optional new weights). */\nexport function scoreFromBase(base: ScoreBase, corrections: BaseCorrection[], weights?: Record<string, number>): { finalScore: number; categoryScores: Record<string, number>; overridden: boolean } {\n const latest = new Map(corrections.map((c) => [c.category, c.corrected_score]));\n const categories = base.map((c) => ({ ...c, weight: weights?.[c.name] ?? c.weight, score: latest.get(c.name) ?? c.score, findings: [] }));\n const { finalScore } = computeFinalScore(categories, 0);\n const override = latest.get(null);\n return { finalScore: override ?? finalScore, categoryScores: Object.fromEntries(categories.map((c) => [c.name, c.score])), overridden: override !== undefined };\n}\n\nexport interface ReplayRow {\n mergeRequestId: number;\n mrIid: number;\n title: string | null;\n scoredAt: string;\n oldScore: number;\n newScore: number;\n oldPass: boolean;\n newPass: boolean;\n /** A total-score correction pins the result; weights can't move it. */\n overridden: boolean;\n}\n\n/**\n * \"Last N reviews with these weights\": same scoreFromBase as refreshScores, so replay and the\n * stored totals agree. Rows without a base snapshot (pre-Phase 0) can't be replayed and are skipped.\n */\nexport function replayScores(\n db: DatabaseSync,\n projectId: number,\n weights: Record<string, number>,\n threshold: number,\n limit = 20,\n /** Threshold the stored scores were judged by (the saved rubric's) \u2014 so moving only the slider shows flips. */\n oldThreshold = threshold,\n): { rows: ReplayRow[]; skipped: number } {\n const all = db\n .prepare(\n `SELECT s.merge_request_id, s.scored_at, s.final_score, s.base_json, m.mr_iid, m.title\n FROM scores s JOIN merge_requests m ON m.id = s.merge_request_id\n WHERE m.project_id = ? ORDER BY s.scored_at DESC LIMIT ?`,\n )\n .all(projectId, limit) as unknown as { merge_request_id: number; scored_at: string; final_score: number; base_json: string | null; mr_iid: number; title: string | null }[];\n const rows: ReplayRow[] = [];\n for (const r of all) {\n if (!r.base_json) continue;\n const next = scoreFromBase(JSON.parse(r.base_json) as ScoreBase, correctionsSince(db, r.merge_request_id, r.scored_at), weights);\n rows.push({\n mergeRequestId: r.merge_request_id,\n mrIid: r.mr_iid,\n title: r.title,\n scoredAt: r.scored_at,\n oldScore: r.final_score,\n newScore: next.finalScore,\n oldPass: r.final_score >= oldThreshold,\n newPass: next.finalScore >= threshold,\n overridden: next.overridden,\n });\n }\n return { rows, skipped: all.length - rows.length };\n}\n\n/** Gives each finding a stable row/id \u2014 see `findings` table comment in schema.sql for the\n * dedupe rationale. `ON CONFLICT DO NOTHING` means a finding that reappears across a\n * re-review keeps its original id, so votes/tags on it survive a rescore. */\nexport function upsertFindingsForScore(\n db: DatabaseSync,\n mergeRequestId: number,\n findings: { category?: string; severity: string; issue: string; file?: string; line?: number }[],\n): void {\n const insert = db.prepare(\n `INSERT INTO findings (merge_request_id, category, severity, issue, file, line)\n VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT (merge_request_id, file, line, issue) DO NOTHING`,\n );\n for (const f of findings) {\n insert.run(mergeRequestId, f.category ?? null, f.severity, f.issue, f.file ?? null, f.line ?? null);\n }\n}\n\nexport function insertCorrection(\n db: DatabaseSync,\n c: {\n mergeRequestId: number;\n category: string | null;\n originalScore: number;\n correctedScore: number;\n reason: string;\n correctedNote?: string;\n },\n): number {\n const row = db\n .prepare(\n `INSERT INTO corrections (merge_request_id, category, original_score, corrected_score, reason, corrected_note)\n VALUES (?, ?, ?, ?, ?, ?) RETURNING id`,\n )\n .get(c.mergeRequestId, c.category, c.originalScore, c.correctedScore, c.reason, c.correctedNote ?? null) as unknown as {\n id: number;\n };\n refreshScores(db, c.mergeRequestId);\n return row.id;\n}\n\nexport function insertInsight(\n db: DatabaseSync,\n i: {\n authorUsername: string | null;\n /** The git host this insight belongs to; NULL only for legacy rows nobody could place. */\n host: string | null;\n projectId: number | null;\n category: string | null;\n insightText: string;\n evidenceMrIds: number[];\n },\n): number {\n const row = db\n .prepare(\n `INSERT INTO insights (author_username, host, project_id, category, insight_text, evidence_mr_ids_json)\n VALUES (?, ?, ?, ?, ?, ?) RETURNING id`,\n )\n .get(i.authorUsername, i.host, i.projectId, i.category, i.insightText, JSON.stringify(i.evidenceMrIds)) as unknown as { id: number };\n return row.id;\n}\n\nexport function insertFindingDiscussion(\n db: DatabaseSync,\n d: {\n mergeRequestId: number;\n discussionId: string;\n category: string;\n severity: string;\n issue: string;\n file?: string;\n line?: number;\n postedNoteId: number;\n },\n): void {\n db.prepare(\n `INSERT INTO finding_discussions (merge_request_id, discussion_id, category, severity, issue, file, line, posted_note_id)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(merge_request_id, file, line, issue) DO NOTHING`,\n ).run(d.mergeRequestId, d.discussionId, d.category, d.severity, d.issue, d.file ?? null, d.line ?? null, d.postedNoteId);\n}\n\nexport interface FindingRow {\n id: number;\n merge_request_id: number;\n category: string | null;\n severity: string;\n issue: string;\n file: string | null;\n line: number | null;\n vote: \"up\" | \"down\" | null;\n note: string | null;\n tags: string[];\n replies: ThreadNote[];\n nearby: ThreadNote[];\n /** Posted as its own GitLab thread, so votes/tags can be synced back to it. */\n has_thread: boolean;\n /** Our decision reply currently exists on that thread. */\n posted: boolean;\n sync_error: string | null;\n}\n\nexport interface ThreadNote {\n author_username: string;\n body: string;\n created_at: string;\n}\n\nconst NEARBY_LINES = 5;\n\n/** A finding's discussion: `replies` are exact (notes on the finding's own GitLab thread,\n * joined via finding_discussions' shared dedupe key); `nearby` are mined human comments on\n * the same file within NEARBY_LINES \u2014 fuzzy, since backfill flattens threads and file/line\n * is the only link left. */\nexport function getFindingThread(\n db: DatabaseSync,\n f: { merge_request_id: number; file: string | null; line: number | null; issue: string },\n): { replies: ThreadNote[]; nearby: ThreadNote[] } {\n const replies = db\n .prepare(\n `SELECT fr.author_username, fr.body, fr.created_at\n FROM finding_responses fr\n JOIN finding_discussions fd ON fd.id = fr.finding_discussion_id\n WHERE fd.merge_request_id = ? AND fd.file IS ? AND fd.line IS ? AND fd.issue = ?\n ORDER BY fr.created_at ASC`,\n )\n .all(f.merge_request_id, f.file, f.line, f.issue) as unknown as ThreadNote[];\n if (!f.file) return { replies, nearby: [] };\n\n const replyBodies = new Set(replies.map((r) => r.body));\n const nearby = (\n db\n .prepare(\n `SELECT author_username, body, created_at FROM human_review_comments\n WHERE merge_request_id = ? AND file = ? AND (? IS NULL OR ABS(line - ?) <= ?)\n ORDER BY created_at ASC`,\n )\n .all(f.merge_request_id, f.file, f.line, f.line, NEARBY_LINES) as unknown as ThreadNote[]\n ).filter((c) => !replyBodies.has(c.body)); // a later backfill also mines our own threads' replies\n return { replies, nearby };\n}\n\n/** Findings for one MR, each with its vote (if any), tags and thread \u2014 backs the review-detail page. */\nexport function listFindingsForMr(db: DatabaseSync, mergeRequestId: number): FindingRow[] {\n const rows = db\n .prepare(\n `SELECT f.*, fv.vote AS vote, fv.note AS note, fd.id IS NOT NULL AS has_thread, fd.decision_note_id IS NOT NULL AS posted, fd.decision_sync_error AS sync_error,\n (SELECT GROUP_CONCAT(ft.tag) FROM finding_tags ft WHERE ft.finding_id = f.id) AS tags_concat\n FROM findings f\n LEFT JOIN finding_votes fv ON fv.finding_id = f.id\n LEFT JOIN finding_discussions fd\n ON fd.merge_request_id = f.merge_request_id AND fd.file IS f.file AND fd.line IS f.line AND fd.issue = f.issue\n WHERE f.merge_request_id = ?\n ORDER BY f.id ASC`,\n )\n .all(mergeRequestId) as unknown as (Omit<FindingRow, \"tags\" | \"replies\" | \"nearby\" | \"has_thread\" | \"posted\"> & {\n tags_concat: string | null;\n has_thread: number;\n posted: number;\n })[];\n return rows.map(({ tags_concat, has_thread, posted, ...f }) => ({\n ...f,\n has_thread: has_thread === 1,\n posted: posted === 1,\n tags: tags_concat ? tags_concat.split(\",\") : [],\n ...getFindingThread(db, f),\n }));\n}\n\nexport interface FindingContext {\n id: number;\n merge_request_id: number;\n category: string | null;\n severity: string;\n issue: string;\n file: string | null;\n line: number | null;\n author_username: string;\n project_id: number;\n original_score: number;\n volume_factor: number;\n}\n\n/** Finding + its MR + latest score's category/final score \u2014 used to default a vote-driven\n * correction's `original_score` without the caller needing to know the scoring shape. */\nexport function getFindingContext(db: DatabaseSync, findingId: number): FindingContext | undefined {\n const finding = db.prepare(`SELECT * FROM findings WHERE id = ?`).get(findingId) as unknown as\n | { id: number; merge_request_id: number; category: string | null; severity: string; issue: string; file: string | null; line: number | null }\n | undefined;\n if (!finding) return undefined;\n\n const mr = db.prepare(`SELECT author_username, project_id FROM merge_requests WHERE id = ?`).get(finding.merge_request_id) as unknown as\n | { author_username: string; project_id: number }\n | undefined;\n if (!mr) return undefined;\n\n const score = db\n .prepare(`SELECT category_scores_json, final_score, volume_factor FROM scores WHERE merge_request_id = ? ORDER BY scored_at DESC LIMIT 1`)\n .get(finding.merge_request_id) as unknown as { category_scores_json: string; final_score: number; volume_factor: number } | undefined;\n\n let originalScore = score?.final_score ?? 0;\n if (score && finding.category) {\n const categoryScores = JSON.parse(score.category_scores_json) as Record<string, number>;\n if (finding.category in categoryScores) originalScore = categoryScores[finding.category] ?? originalScore;\n }\n\n return {\n id: finding.id,\n merge_request_id: finding.merge_request_id,\n category: finding.category,\n severity: finding.severity,\n issue: finding.issue,\n file: finding.file,\n line: finding.line,\n author_username: mr.author_username,\n project_id: mr.project_id,\n original_score: originalScore,\n volume_factor: score?.volume_factor ?? 1,\n };\n}\n\n/** One active vote per finding \u2014 re-voting deletes the old vote and its linked\n * correction/insight first, so re-voting never double-counts a score adjustment. */\nexport function upsertFindingVote(\n db: DatabaseSync,\n findingId: number,\n v: { vote: \"up\" | \"down\"; note: string; adjustScore: boolean; category?: string | null; correctedScore?: number },\n): void {\n deleteFindingVote(db, findingId);\n\n const ctx = getFindingContext(db, findingId);\n if (!ctx) throw new Error(`finding ${findingId} not found`);\n\n // A \uD83D\uDC4E means false positive: with no explicit score, give back the finding's size-scaled severity penalty.\n let correctedScore = v.correctedScore;\n if (correctedScore == null && v.vote === \"down\") {\n const penalty = (DEFAULT_PENALTIES[ctx.severity as keyof SeverityPenalties] ?? 0) * ctx.volume_factor;\n correctedScore = Math.min(100, Math.round(ctx.original_score + penalty));\n }\n\n let correctionId: number | null = null;\n if (v.adjustScore) {\n const category = v.category ?? ctx.category;\n correctionId = insertCorrection(db, {\n mergeRequestId: ctx.merge_request_id,\n category: category ?? null,\n originalScore: ctx.original_score,\n correctedScore: correctedScore ?? ctx.original_score,\n reason: v.note,\n });\n }\n\n // The vote judges the finding, not the contributor's reaction \u2014 the reply is quoted so memory\n // learns *why*. \uD83D\uDC4D is about this author's code (author-scoped); \uD83D\uDC4E is reviewer calibration for\n // the whole project (author NULL), since a false positive says nothing about the author.\n const { replies } = getFindingThread(db, ctx);\n const lastReply = replies.at(-1);\n const replyText = lastReply ? ` Contributor ${lastReply.author_username} replied: \"${lastReply.body.slice(0, 300)}\".` : \"\";\n const insightText =\n v.vote === \"up\"\n ? `Confirmed issue in ${ctx.author_username}'s code: ${ctx.issue}.${replyText} Maintainer: ${v.note}`\n : `False positive \u2014 do not flag: ${ctx.issue}.${replyText} Maintainer agrees with contributor: ${v.note}`;\n const { forge_host } = db.prepare(`SELECT forge_host FROM projects WHERE id = ?`).get(ctx.project_id) as { forge_host: string | null };\n const insightId = insertInsight(db, {\n authorUsername: v.vote === \"up\" ? ctx.author_username : null,\n host: forge_host,\n projectId: ctx.project_id,\n category: ctx.category,\n insightText,\n evidenceMrIds: [ctx.merge_request_id],\n });\n\n db.prepare(\n `INSERT INTO finding_votes (finding_id, vote, note, correction_id, insight_id) VALUES (?, ?, ?, ?, ?)`,\n ).run(findingId, v.vote, v.note, correctionId, insightId);\n}\n\n/** Undo: removes the vote and any correction/insight it created. */\nexport function deleteFindingVote(db: DatabaseSync, findingId: number): void {\n const existing = db.prepare(`SELECT correction_id, insight_id FROM finding_votes WHERE finding_id = ?`).get(findingId) as unknown as\n | { correction_id: number | null; insight_id: number | null }\n | undefined;\n if (!existing) return;\n\n db.prepare(`DELETE FROM finding_votes WHERE finding_id = ?`).run(findingId);\n if (existing.correction_id != null) deleteCorrection(db, existing.correction_id);\n if (existing.insight_id != null) db.prepare(`DELETE FROM insights WHERE id = ?`).run(existing.insight_id);\n}\n\nexport function addFindingTag(db: DatabaseSync, findingId: number, tag: string): void {\n db.prepare(`INSERT INTO finding_tags (finding_id, tag) VALUES (?, ?) ON CONFLICT (finding_id, tag) DO NOTHING`).run(findingId, tag);\n}\n\nexport function removeFindingTag(db: DatabaseSync, findingId: number, tag: string): void {\n db.prepare(`DELETE FROM finding_tags WHERE finding_id = ? AND tag = ?`).run(findingId, tag);\n}\n\nexport interface QueryFindingRow {\n id: number;\n merge_request_id: number;\n mr_iid: number;\n project_id: number;\n project_path: string | null;\n author_username: string;\n category: string | null;\n severity: string;\n issue: string;\n file: string | null;\n line: number | null;\n vote: \"up\" | \"down\" | null;\n note: string | null;\n tags: string[];\n replies: ThreadNote[];\n nearby: ThreadNote[];\n}\n\n/** Cross-project/author/tag finding browser \u2014 filters combine with AND; any unset filter\n * matches everything. */\nexport function queryFindings(\n db: DatabaseSync,\n filter: { projectId?: number; author?: AuthorKey; tag?: string },\n): QueryFindingRow[] {\n const rows = db\n .prepare(\n `SELECT f.id, f.merge_request_id, mr.mr_iid, mr.project_id, p.path_with_namespace AS project_path, mr.author_username,\n f.category, f.severity, f.issue, f.file, f.line, fv.vote AS vote, fv.note AS note,\n (SELECT GROUP_CONCAT(ft.tag) FROM finding_tags ft WHERE ft.finding_id = f.id) AS tags_concat\n FROM findings f\n JOIN merge_requests mr ON mr.id = f.merge_request_id\n LEFT JOIN projects p ON p.id = mr.project_id\n LEFT JOIN finding_votes fv ON fv.finding_id = f.id\n WHERE (? IS NULL OR mr.project_id = ?)\n AND (? IS NULL OR (mr.author_username = ? AND p.forge_host = ?))\n AND (? IS NULL OR EXISTS (SELECT 1 FROM finding_tags ft WHERE ft.finding_id = f.id AND ft.tag = ?))\n ORDER BY f.created_at DESC`,\n )\n .all(\n filter.projectId ?? null,\n filter.projectId ?? null,\n filter.author?.username ?? null,\n filter.author?.username ?? null,\n filter.author?.host ?? null,\n filter.tag ?? null,\n filter.tag ?? null,\n ) as unknown as (Omit<QueryFindingRow, \"tags\" | \"replies\" | \"nearby\"> & { tags_concat: string | null })[];\n // ponytail: 2 queries per finding for the thread; fine for a local SQLite DB, fold into one JOIN if this page gets slow.\n return rows.map(({ tags_concat, ...f }) => ({ ...f, tags: tags_concat ? tags_concat.split(\",\") : [], ...getFindingThread(db, f) }));\n}\n\nexport interface FindingDiscussionRow {\n id: number;\n merge_request_id: number;\n discussion_id: string;\n category: string;\n severity: string;\n issue: string;\n file: string | null;\n line: number | null;\n posted_note_id: number;\n created_at: string;\n}\n\nexport function listFindingDiscussionsForMr(db: DatabaseSync, mergeRequestId: number): FindingDiscussionRow[] {\n return db\n .prepare(`SELECT * FROM finding_discussions WHERE merge_request_id = ? ORDER BY created_at ASC`)\n .all(mergeRequestId) as unknown as FindingDiscussionRow[];\n}\n\n/** Stores a reply on a finding thread. An edited reply (same note, new text) is updated. */\nexport function insertFindingResponse(\n db: DatabaseSync,\n r: { findingDiscussionId: number; noteId: number; authorUsername: string; body: string; createdAt: string },\n): \"new\" | \"updated\" | null {\n const prev = db.prepare(`SELECT body FROM finding_responses WHERE note_id = ?`).get(r.noteId) as { body: string } | undefined;\n if (prev) {\n if (prev.body === r.body) return null;\n db.prepare(`UPDATE finding_responses SET body = ? WHERE note_id = ?`).run(r.body, r.noteId);\n return \"updated\";\n }\n db.prepare(\n `INSERT INTO finding_responses (finding_discussion_id, note_id, author_username, body, created_at) VALUES (?, ?, ?, ?, ?)`,\n ).run(r.findingDiscussionId, r.noteId, r.authorUsername, r.body, r.createdAt);\n return \"new\";\n}\n\nexport interface FindingResponseRow {\n id: number;\n finding_discussion_id: number;\n note_id: number;\n author_username: string;\n body: string;\n created_at: string;\n category: string;\n severity: string;\n issue: string;\n file: string | null;\n line: number | null;\n merge_request_id: number;\n mr_iid: number;\n project_id: number;\n}\n\nexport function listAuthorFindingResponses(\n db: DatabaseSync,\n author: AuthorKey,\n limit = 20,\n projectId?: number,\n): FindingResponseRow[] {\n return db\n .prepare(\n `SELECT fr.*, fd.category, fd.severity, fd.issue, fd.file, fd.line, fd.merge_request_id, mr.mr_iid, mr.project_id\n FROM finding_responses fr\n JOIN finding_discussions fd ON fd.id = fr.finding_discussion_id\n JOIN merge_requests mr ON mr.id = fd.merge_request_id\n JOIN projects p ON p.id = mr.project_id\n WHERE mr.author_username = ? AND p.forge_host = ? AND (? IS NULL OR mr.project_id = ?)\n ORDER BY fr.created_at DESC\n LIMIT ?`,\n )\n .all(author.username, author.host, projectId ?? null, projectId ?? null, limit) as unknown as FindingResponseRow[];\n}\n\n/** Everyone with an MR in the DB, per host. Projects not yet given a host (pre-Yolont, before\n * the legacy stamp) are left out until they have one. */\n/** `projectIds`: only authors with MRs in these projects (the panel's source filter). */\nexport function listAuthors(db: DatabaseSync, projectIds?: number[]): AuthorKey[] {\n const ids = projectIds ? JSON.stringify(projectIds) : null;\n return db\n .prepare(\n `SELECT DISTINCT p.forge_host AS host, mr.author_username AS username\n FROM merge_requests mr JOIN projects p ON p.id = mr.project_id\n WHERE p.forge_host IS NOT NULL AND (? IS NULL OR p.id IN (SELECT value FROM json_each(?)))\n ORDER BY username, host`,\n )\n .all(ids, ids) as unknown as AuthorKey[];\n}\n\nexport interface ScoreRow {\n id: number;\n merge_request_id: number;\n scored_at: string;\n final_score: number;\n category_scores_json: string;\n findings_json: string;\n source: string;\n model_used: string | null;\n mr_iid: number;\n project_id: number;\n}\n\n/** Latest score per MR for this author, oldest first \u2014 what trend.ts regresses over. */\nexport function listAuthorScores(db: DatabaseSync, author: AuthorKey): ScoreRow[] {\n return db\n .prepare(\n `SELECT s.*, mr.mr_iid, mr.project_id FROM scores s\n JOIN merge_requests mr ON mr.id = s.merge_request_id\n JOIN projects p ON p.id = mr.project_id\n WHERE mr.author_username = ? AND p.forge_host = ?\n ORDER BY s.scored_at ASC`,\n )\n .all(author.username, author.host) as unknown as ScoreRow[];\n}\n\nexport interface CorrectionRow {\n id: number;\n merge_request_id: number;\n category: string | null;\n original_score: number;\n corrected_score: number;\n reason: string;\n corrected_note: string | null;\n created_at: string;\n mr_iid: number;\n project_id: number;\n project_path: string;\n /** Team data source it was imported from; null = made here. */\n origin: string | null;\n}\n\nexport function listAuthorCorrections(\n db: DatabaseSync,\n author: AuthorKey,\n limit = 20,\n projectId?: number,\n): CorrectionRow[] {\n return db\n .prepare(\n `SELECT c.*, mr.mr_iid, mr.project_id, p.path_with_namespace AS project_path FROM corrections c\n JOIN merge_requests mr ON mr.id = c.merge_request_id\n JOIN projects p ON p.id = mr.project_id\n WHERE mr.author_username = ? AND p.forge_host = ? AND (? IS NULL OR mr.project_id = ?)\n ORDER BY c.created_at DESC\n LIMIT ?`,\n )\n .all(author.username, author.host, projectId ?? null, projectId ?? null, limit) as unknown as CorrectionRow[];\n}\n\nexport interface CommentRow {\n id: number;\n merge_request_id: number;\n author_username: string;\n body: string;\n file: string | null;\n line: number | null;\n created_at: string;\n}\n\nexport function listAuthorComments(db: DatabaseSync, author: AuthorKey): CommentRow[] {\n return db\n .prepare(\n `SELECT hrc.* FROM human_review_comments hrc\n JOIN merge_requests mr ON mr.id = hrc.merge_request_id\n JOIN projects p ON p.id = mr.project_id\n WHERE mr.author_username = ? AND p.forge_host = ?\n ORDER BY hrc.created_at DESC`,\n )\n .all(author.username, author.host) as unknown as CommentRow[];\n}\n\n/** Comment volume per author \u2014 the zero-LLM-cost effort signal available right after a plain backfill. */\nexport function commentVolumeByAuthor(db: DatabaseSync, projectIds?: number[]): { host: string | null; author_username: string; comment_count: number; mr_count: number }[] {\n const ids = projectIds ? JSON.stringify(projectIds) : null;\n return db\n .prepare(\n `SELECT p.forge_host AS host, mr.author_username, COUNT(hrc.id) AS comment_count, COUNT(DISTINCT mr.id) AS mr_count\n FROM merge_requests mr\n JOIN projects p ON p.id = mr.project_id\n LEFT JOIN human_review_comments hrc ON hrc.merge_request_id = mr.id\n WHERE ? IS NULL OR p.id IN (SELECT value FROM json_each(?))\n GROUP BY p.forge_host, mr.author_username\n ORDER BY comment_count DESC`,\n )\n .all(ids, ids) as unknown as { host: string | null; author_username: string; comment_count: number; mr_count: number }[];\n}\n\nexport interface InsightRow {\n id: number;\n author_username: string | null;\n host: string | null;\n project_id: number | null;\n project_path: string | null;\n category: string | null;\n insight_text: string;\n evidence_mr_ids_json: string;\n created_at: string;\n /** Team data source it was imported from; null = made here. */\n origin: string | null;\n}\n\n/**\n * Unset filters match everything. `username`/`projectId` also take rows marked for every\n * author / every project (NULL). `host` is strict: an insight from another git host \u2014 or one\n * whose host is unknown \u2014 never comes back, so memory can't cross hosts. Pass it whenever the\n * result feeds a review.\n */\nexport function listInsights(db: DatabaseSync, filter: { host?: string; username?: string; projectId?: number } = {}): InsightRow[] {\n const { host = null, username = null, projectId = null } = filter;\n return db\n .prepare(\n `SELECT i.*, p.path_with_namespace AS project_path FROM insights i\n LEFT JOIN projects p ON p.id = i.project_id\n WHERE (? IS NULL OR i.host = ?)\n AND (? IS NULL OR i.author_username = ? OR i.author_username IS NULL)\n AND (? IS NULL OR i.project_id = ? OR i.project_id IS NULL)\n ORDER BY i.created_at DESC`,\n )\n .all(host, host, username, username, projectId, projectId) as unknown as InsightRow[];\n}\n\nexport function deleteInsight(db: DatabaseSync, id: number): void {\n db.prepare(`DELETE FROM insights WHERE id = ?`).run(id);\n}\n\nexport interface ReviewSummaryRow {\n score_id: number;\n merge_request_id: number;\n project_id: number;\n project_path: string | null;\n mr_iid: number;\n author_username: string;\n title: string;\n source: string;\n final_score: number;\n scored_at: string;\n change_type: string | null;\n correction_count: number;\n}\n\n/** One row per (merge_request, source) score \u2014 a backfilled baseline and a live re-review\n * of the same MR are two distinct entries in this history, not a duplicate. */\nexport function listReviews(db: DatabaseSync): ReviewSummaryRow[] {\n return db\n .prepare(\n `SELECT s.id AS score_id, mr.id AS merge_request_id, mr.project_id, p.path_with_namespace AS project_path,\n mr.mr_iid, mr.author_username, mr.title, s.source, s.final_score, s.scored_at, s.change_type,\n (SELECT COUNT(*) FROM corrections c WHERE c.merge_request_id = mr.id) AS correction_count\n FROM scores s\n JOIN merge_requests mr ON mr.id = s.merge_request_id\n LEFT JOIN projects p ON p.id = mr.project_id\n ORDER BY s.scored_at DESC`,\n )\n .all() as unknown as ReviewSummaryRow[];\n}\n\nexport interface MergeRequestDetailRow {\n id: number;\n project_id: number;\n project_path: string | null;\n mr_iid: number;\n author_username: string;\n title: string;\n sha: string;\n merged_at: string | null;\n source: string;\n}\n\nexport function getMergeRequestById(db: DatabaseSync, id: number): MergeRequestDetailRow | undefined {\n return db\n .prepare(\n `SELECT mr.*, p.path_with_namespace AS project_path FROM merge_requests mr\n LEFT JOIN projects p ON p.id = mr.project_id\n WHERE mr.id = ?`,\n )\n .get(id) as unknown as MergeRequestDetailRow | undefined;\n}\n\nexport function listScoresForMr(db: DatabaseSync, mergeRequestId: number): ScoreRow[] {\n return db\n .prepare(\n `SELECT s.*, mr.mr_iid, mr.project_id FROM scores s\n JOIN merge_requests mr ON mr.id = s.merge_request_id\n WHERE s.merge_request_id = ?\n ORDER BY s.scored_at DESC`,\n )\n .all(mergeRequestId) as unknown as ScoreRow[];\n}\n\nexport function listCorrectionsForMr(db: DatabaseSync, mergeRequestId: number): CorrectionRow[] {\n return db\n .prepare(\n `SELECT c.*, mr.mr_iid, mr.project_id, p.path_with_namespace AS project_path FROM corrections c\n JOIN merge_requests mr ON mr.id = c.merge_request_id\n LEFT JOIN projects p ON p.id = mr.project_id\n WHERE c.merge_request_id = ?\n ORDER BY c.created_at DESC`,\n )\n .all(mergeRequestId) as unknown as CorrectionRow[];\n}\n\nexport function listCommentsForMr(db: DatabaseSync, mergeRequestId: number): CommentRow[] {\n return db\n .prepare(`SELECT * FROM human_review_comments WHERE merge_request_id = ? ORDER BY created_at DESC`)\n .all(mergeRequestId) as unknown as CommentRow[];\n}\n\nexport function deleteScore(db: DatabaseSync, scoreId: number): void {\n db.prepare(`DELETE FROM scores WHERE id = ?`).run(scoreId);\n}\n\n/** Wipes a review end to end \u2014 scores, corrections, findings (+ their votes/tags), mined\n * comments/discussions, and the MR row itself. Use for a review that shouldn't have been\n * recorded at all; to just stop one bad score from skewing history/memory, delete the\n * score (or correction) alone.\n *\n * Deletion order matters \u2014 foreign_keys is ON, so children go before their parents:\n * finding_votes/finding_tags before findings, finding_responses before finding_discussions. */\nexport function deleteMergeRequest(db: DatabaseSync, mergeRequestId: number): void {\n db.prepare(\n `DELETE FROM finding_votes WHERE finding_id IN (SELECT id FROM findings WHERE merge_request_id = ?)`,\n ).run(mergeRequestId);\n db.prepare(\n `DELETE FROM finding_tags WHERE finding_id IN (SELECT id FROM findings WHERE merge_request_id = ?)`,\n ).run(mergeRequestId);\n db.prepare(`DELETE FROM findings WHERE merge_request_id = ?`).run(mergeRequestId);\n db.prepare(\n `DELETE FROM finding_responses WHERE finding_discussion_id IN (SELECT id FROM finding_discussions WHERE merge_request_id = ?)`,\n ).run(mergeRequestId);\n db.prepare(`DELETE FROM finding_discussions WHERE merge_request_id = ?`).run(mergeRequestId);\n db.prepare(`DELETE FROM corrections WHERE merge_request_id = ?`).run(mergeRequestId);\n db.prepare(`DELETE FROM scores WHERE merge_request_id = ?`).run(mergeRequestId);\n db.prepare(`DELETE FROM human_review_comments WHERE merge_request_id = ?`).run(mergeRequestId);\n db.prepare(`DELETE FROM zone_hits WHERE merge_request_id = ?`).run(mergeRequestId);\n db.prepare(`DELETE FROM merge_requests WHERE id = ?`).run(mergeRequestId);\n}\n\nexport function deleteCorrection(db: DatabaseSync, id: number): void {\n const row = db.prepare(`DELETE FROM corrections WHERE id = ? RETURNING merge_request_id`).get(id) as unknown as { merge_request_id: number } | undefined;\n if (row) refreshScores(db, row.merge_request_id);\n}\n\n/** Full replace, not a partial patch \u2014 the edit form always submits every field, and a\n * correction's whole point is its reason text, so there's no meaningful \"partial\" edit. */\nexport function updateCorrection(\n db: DatabaseSync,\n id: number,\n patch: { category: string | null; correctedScore: number; reason: string; correctedNote: string | null },\n): void {\n db.prepare(`UPDATE corrections SET category = ?, corrected_score = ?, reason = ?, corrected_note = ? WHERE id = ?`).run(\n patch.category,\n patch.correctedScore,\n patch.reason,\n patch.correctedNote,\n id,\n );\n const row = db.prepare(`SELECT merge_request_id FROM corrections WHERE id = ?`).get(id) as unknown as { merge_request_id: number } | undefined;\n if (row) refreshScores(db, row.merge_request_id);\n}\n\n// ---- Performance zones ----\n\nexport interface ZoneHitRow {\n id: number;\n merge_request_id: number;\n zone_id: string;\n level: ZoneLevel;\n files: string[];\n impact: \"none\" | \"low\" | \"high\" | null;\n verdict: string | null;\n vote: \"up\" | \"down\" | null;\n vote_note: string | null;\n created_at: string;\n}\n\nexport interface ProjectZoneHitRow extends ZoneHitRow {\n mr_iid: number;\n title: string;\n author_username: string;\n}\n\ntype RawZoneHit<T extends ZoneHitRow> = Omit<T, \"files\"> & { files_json: string };\nconst parseZoneHit = <T extends ZoneHitRow>({ files_json, ...row }: RawZoneHit<T>): T => ({ ...row, files: JSON.parse(files_json) }) as unknown as T;\n\n/** Re-review overwrites what the machine said (a run with no verdict \u2014 LLM failed, or a\n * zones-only backfill \u2014 keeps the old one); the human vote survives. Zones this MR no\n * longer touches (files moved after a push) are dropped unless someone voted on them. */\nexport function upsertZoneHits(db: DatabaseSync, mergeRequestId: number, report: ZoneReport): void {\n const touched = report.hits.map((h) => h.zone.id);\n db.prepare(\n `DELETE FROM zone_hits WHERE merge_request_id = ? AND vote IS NULL AND zone_id NOT IN (SELECT value FROM json_each(?))`,\n ).run(mergeRequestId, JSON.stringify(touched));\n const stmt = db.prepare(\n `INSERT INTO zone_hits (merge_request_id, zone_id, level, files_json, impact, verdict)\n VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT (merge_request_id, zone_id) DO UPDATE SET\n level = excluded.level, files_json = excluded.files_json,\n impact = COALESCE(excluded.impact, impact), verdict = COALESCE(excluded.verdict, verdict)`,\n );\n for (const { zone, files } of report.hits) {\n const verdict = report.verdicts.find((v) => v.zone_id === zone.id);\n stmt.run(mergeRequestId, zone.id, zone.level, JSON.stringify(files), verdict?.impact ?? null, verdict?.verdict ?? null);\n }\n}\n\n/** Live review owns an MR's zone rows once it has run \u2014 backfill leaves those MRs alone. */\nexport function hasLiveScore(db: DatabaseSync, mergeRequestId: number): boolean {\n return db.prepare(`SELECT 1 FROM scores WHERE merge_request_id = ? AND source = 'llm_live'`).get(mergeRequestId) !== undefined;\n}\n\nexport function listZoneHitsForMr(db: DatabaseSync, mergeRequestId: number): ZoneHitRow[] {\n const rows = db\n .prepare(`SELECT * FROM zone_hits WHERE merge_request_id = ? ORDER BY CASE level WHEN 'red' THEN 0 WHEN 'amber' THEN 1 ELSE 2 END, zone_id`)\n .all(mergeRequestId) as unknown as RawZoneHit<ZoneHitRow>[];\n return rows.map(parseZoneHit);\n}\n\nexport function listZoneHitsForProject(db: DatabaseSync, projectId: number): ProjectZoneHitRow[] {\n const rows = db\n .prepare(\n `SELECT zh.*, mr.mr_iid, mr.title, mr.author_username\n FROM zone_hits zh JOIN merge_requests mr ON mr.id = zh.merge_request_id\n WHERE mr.project_id = ?\n ORDER BY zh.created_at DESC`,\n )\n .all(projectId) as unknown as RawZoneHit<ProjectZoneHitRow>[];\n return rows.map(parseZoneHit);\n}\n\nexport function setZoneHitVote(db: DatabaseSync, id: number, vote: \"up\" | \"down\" | null, note: string | null): void {\n db.prepare(`UPDATE zone_hits SET vote = ?, vote_note = ? WHERE id = ?`).run(vote, vote ? note : null, id);\n}\n\n/** Findings a reviewer tagged 'danger-zone' in this project \u2014 the human-taught red zone. */\nexport function listDangerTaggedFindings(\n db: DatabaseSync,\n projectId: number,\n): { file: string; issue: string; merge_request_id: number; mr_iid: number }[] {\n return db\n .prepare(\n `SELECT DISTINCT f.file, f.issue, f.merge_request_id, mr.mr_iid\n FROM findings f\n JOIN finding_tags ft ON ft.finding_id = f.id AND ft.tag = 'danger-zone'\n JOIN merge_requests mr ON mr.id = f.merge_request_id\n WHERE mr.project_id = ? AND f.file IS NOT NULL\n ORDER BY f.created_at DESC`,\n )\n .all(projectId) as { file: string; issue: string; merge_request_id: number; mr_iid: number }[];\n}\n", "import { readFile } from \"node:fs/promises\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { scanDiffForSecrets } from \"../../src/checks/secrets.js\";\nimport { runDeterministicChecks } from \"../../src/checks/runner.js\";\nimport { truncateDiff } from \"../../src/git.js\";\nimport type { ForgeClient, ProjectMrSummary, ProjectRef } from \"../../src/forge/types.js\";\nimport { createLlmProvider, withRetry, type ReviewCategorySpec } from \"../../src/llm/index.js\";\nimport { loadRubric } from \"../../src/rubric/loader.js\";\nimport { computeFinalScore, volumeFactor } from \"../../src/scoring/engine.js\";\nimport { DEFAULT_CATEGORY_DESCRIPTIONS, resolveCategory, type LlmOutcome } from \"../../src/scoring/resolve.js\";\nimport { keepKnownVerdicts, loadZoneGraph, loadZones, matchZones, type Zone, type ZoneGraph, type ZoneReport } from \"../../src/zones/zones.js\";\nimport { resolveProjectFiles } from \"../conventions/resolve.js\";\nimport { openDb } from \"../db/client.js\";\nimport { hasLiveScore, insertHumanComment, markDiscussionsMined, upsertMergeRequest, upsertProject, upsertScore, upsertZoneHits } from \"../db/repo.js\";\nimport { DEFAULT_CONVENTIONS_PATH } from \"../paths.js\";\n\nexport interface BackfillOptions {\n forge: ForgeClient;\n project: ProjectRef;\n maxMrs?: number;\n withLlm?: boolean;\n /** Match every MR's changed files to the project's zones (one diff fetch per MR, no LLM). */\n zones?: boolean;\n rubricPath?: string;\n conventionsPath?: string;\n}\n\n/**\n * Bulk-scans a project's merged MRs. Default (no withLlm): mines real human review\n * comments only \u2014 GitLab-API-only, no LLM cost, resumable (a merge_request's\n * mined_discussions_at is only set once discussions are actually fetched, so a rerun\n * skips already-mined MRs). This is the \"scan once, gather historical data\" step.\n */\nexport async function runBackfill(opts: BackfillOptions): Promise<void> {\n const db = openDb();\n const client = opts.forge;\n\n const me = await client.getCurrentUser();\n const project = await client.getProject(opts.project);\n const dbProjectId = upsertProject(db, { ...project, host: client.host });\n\n const projectFiles = resolveProjectFiles(client.host, project.pathWithNamespace);\n const conventionsPath = opts.conventionsPath ?? projectFiles.conventions ?? DEFAULT_CONVENTIONS_PATH;\n // project: the numeric id from here on, so API calls don't re-resolve a path.\n opts = { ...opts, project: project.id, conventionsPath, rubricPath: opts.rubricPath ?? projectFiles.rubric };\n\n // --zones requires the file; --with-llm picks zones up whenever the project has one.\n const zonesPath = projectFiles.zones;\n const zones = (opts.zones || opts.withLlm) && zonesPath ? loadZones(zonesPath) : null;\n if (opts.zones && !zones) throw new Error(`--zones: no zones.yaml in .yolont/ or ${projectFiles.dir}`);\n // ponytail: today's graph applied to old MRs \u2014 files imported by red code now may not have been then. Fine for a heatmap.\n const graph = zones && projectFiles.zonesGraph ? loadZoneGraph(projectFiles.zonesGraph) : null;\n\n const maxMrs = opts.maxMrs ?? 1000;\n const maxPages = Math.max(1, Math.ceil(maxMrs / 100));\n const mrs = (await client.listProjectMergeRequests(opts.project, { state: \"merged\", maxPages })).slice(0, maxMrs);\n\n console.log(`[backfill] project ${project.pathWithNamespace}: found ${mrs.length} merged MR(s) (cap ${maxMrs}). Conventions: ${conventionsPath}`);\n\n let mined = 0;\n let alreadyMined = 0;\n let scored = 0;\n let zoneMatched = 0;\n\n for (const mr of mrs) {\n const row = upsertMergeRequest(db, {\n projectId: dbProjectId,\n mrIid: mr.iid,\n authorUsername: mr.authorUsername,\n sha: mr.sha,\n title: mr.title,\n mergedAt: mr.mergedAt,\n source: \"backfill\",\n });\n\n if (row.mined_discussions_at) {\n alreadyMined++;\n } else {\n const comments = await client.listMrDiscussions(opts.project, mr.iid);\n for (const comment of comments) {\n if (comment.authorUsername === me.username) continue; // exclude the pr-score bot's own notes\n insertHumanComment(db, {\n mergeRequestId: row.id,\n authorUsername: comment.authorUsername,\n body: comment.body,\n file: comment.file,\n line: comment.line,\n createdAt: comment.createdAt,\n });\n }\n markDiscussionsMined(db, row.id);\n mined++;\n }\n\n // Historical replay uses only the YAML zones: danger-zone tags/votes are later human\n // knowledge, same reason author memory isn't replayed (see scoreMrForBackfill).\n const zonesForMr = zones && !hasLiveScore(db, row.id) ? zones : null;\n if (opts.withLlm) {\n const result = await scoreMrForBackfill(db, client, opts, mr, row.id, zonesForMr, graph);\n if (result.scored) scored++;\n if (result.zoneMatched) zoneMatched++;\n } else if (zonesForMr) {\n try {\n const files = truncateDiff(await client.getMrDiffText(opts.project, mr.iid), Infinity).files;\n upsertZoneHits(db, row.id, { zones: zonesForMr, hits: matchZones(zonesForMr, files, graph), verdicts: [] });\n zoneMatched++;\n } catch (err) {\n console.error(`[backfill] MR !${mr.iid}: zone matching failed: ${(err as Error).message}`);\n }\n }\n }\n\n console.log(\n `[backfill] done. Mined discussions for ${mined} MR(s), ${alreadyMined} already mined.` +\n (opts.withLlm ? ` Scored ${scored}/${mrs.length} via LLM.` : \"\") +\n (zones ? ` Zone-matched ${zoneMatched} MR(s) (MRs reviewed live keep their own zones).` : \"\"),\n );\n db.close();\n}\n\nasync function scoreMrForBackfill(\n db: DatabaseSync,\n client: ForgeClient,\n opts: BackfillOptions,\n mr: ProjectMrSummary,\n mergeRequestId: number,\n zones: Zone[] | null,\n graph: ZoneGraph | null,\n): Promise<{ scored: boolean; zoneMatched: boolean }> {\n let zoneReport: ZoneReport | undefined;\n try {\n const rubric = loadRubric(opts.rubricPath!);\n const diffText = await client.getMrDiffText(opts.project, mr.iid);\n const diff = truncateDiff(diffText, rubric.max_diff_bytes);\n\n // Matched (and stored) before the secrets gate \u2014 file paths alone are safe to record\n // even when the diff itself must never reach the LLM.\n if (zones) {\n zoneReport = { zones, hits: matchZones(zones, diff.files, graph), verdicts: [] };\n upsertZoneHits(db, mergeRequestId, zoneReport);\n }\n\n const secretsResult = await scanDiffForSecrets(diff.text);\n if (secretsResult.scannerFailed || secretsResult.findings.length > 0) {\n console.log(`[backfill] MR !${mr.iid}: skipping LLM score (secrets check ${secretsResult.scannerFailed ? \"failed to run\" : \"flagged a hit\"}).`);\n return { scored: false, zoneMatched: Boolean(zoneReport) };\n }\n\n // Historical replay has no live pipeline to consume job/coverage/test-report data\n // from \u2014 those categories are honestly scored \"excluded, no data\", not faked.\n const detResults = runDeterministicChecks(rubric.categories, {\n diffText: diff.text,\n maxLines: rubric.max_lines,\n jobs: [],\n testReportSummary: null,\n });\n\n const llmCategories = rubric.categories.filter((c) => c.type === \"llm\" || c.type === \"hybrid\");\n let llmOutcome: LlmOutcome;\n if (llmCategories.length === 0) {\n llmOutcome = { status: \"ok\", categories: new Map() };\n } else {\n const provider = createLlmProvider(process.env);\n const conventions = await readFile(opts.conventionsPath ?? DEFAULT_CONVENTIONS_PATH, \"utf8\").catch(\n () => \"(no CONVENTIONS.md found)\",\n );\n const categorySpecs: ReviewCategorySpec[] = llmCategories.map((c) => ({\n name: c.name,\n description: c.description ?? DEFAULT_CATEGORY_DESCRIPTIONS[c.name] ?? \"Review this category based on the team conventions above.\",\n }));\n try {\n const response = await withRetry(() =>\n provider.review({\n diff: diff.text,\n truncated: diff.truncated,\n conventions,\n categories: categorySpecs,\n // Chronological memory bootstrap during a bulk backfill is deliberately not\n // attempted here \u2014 it entangles correctness with MR processing order. The\n // interactive `review` command is where local-DB memory feeds back in.\n authorHistorySummary: \"Historical backfill \u2014 no author memory applied.\",\n zones: zoneReport?.hits,\n }),\n );\n if (zoneReport) {\n upsertZoneHits(db, mergeRequestId, { ...zoneReport, verdicts: keepKnownVerdicts(response.zone_verdicts, zoneReport.hits) });\n }\n const categoryMap = new Map(response.categories.map((c) => [c.category, { findings: c.findings, summary: c.summary }]));\n llmOutcome = { status: \"ok\", categories: categoryMap };\n } catch (err) {\n llmOutcome = { status: \"error\", reason: (err as Error).message };\n }\n }\n\n const sizeFactor = volumeFactor(diff.stats, rubric.volume_scaling);\n const categoryResults = rubric.categories.map((category) =>\n resolveCategory(category, detResults, llmOutcome, rubric.severity_penalties, sizeFactor),\n );\n const { finalScore, categories: scoredCategories } = computeFinalScore(categoryResults, rubric.threshold);\n\n upsertScore(db, {\n mergeRequestId,\n scoredAt: new Date().toISOString(),\n finalScore,\n categoryScores: Object.fromEntries(scoredCategories.map((c) => [c.name, c.score])),\n findings: scoredCategories.flatMap((c) => c.findings.map((f) => ({ ...f, category: c.name }))),\n source: \"llm_backfill\",\n volumeFactor: sizeFactor,\n base: scoredCategories,\n modelUsed: process.env.ANTHROPIC_MODEL ?? process.env.OPENCODE_ZEN_MODEL ?? process.env.OLLAMA_MODEL,\n });\n\n console.log(`[backfill] MR !${mr.iid}: scored ${finalScore}/100.`);\n return { scored: true, zoneMatched: Boolean(zoneReport) };\n } catch (err) {\n console.error(`[backfill] MR !${mr.iid}: scoring failed: ${(err as Error).message}`);\n return { scored: false, zoneMatched: Boolean(zoneReport) };\n }\n}\n", "import { execFile } from \"node:child_process\";\nimport { mkdtemp, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { promisify } from \"node:util\";\n\nconst execFileAsync = promisify(execFile);\n\nexport interface SecretFinding {\n ruleId: string;\n file: string;\n line: number;\n description: string;\n}\n\nexport interface SecretsScanResult {\n score: number;\n findings: SecretFinding[];\n /** true when gitleaks itself could not run (missing binary, crash, ...) \u2014 distinct from a real hit. */\n scannerFailed: boolean;\n scannerError?: string;\n}\n\ninterface GitleaksReportEntry {\n RuleID?: string;\n File?: string;\n StartLine?: number;\n Description?: string;\n}\n\n/**\n * gitleaks scans the diff as one file, so its line is a line of the patch. Maps it back to the\n * changed file and its new-file line (old-file line for a removed line), so people can find it.\n */\nexport function locateInDiff(diffText: string, patchLine: number): { file: string; line: number } {\n let file = \"(diff)\";\n let oldLine = 0;\n let newLine = 0;\n const lines = diffText.split(\"\\n\");\n for (let i = 0; i < Math.min(patchLine, lines.length); i++) {\n const l = lines[i]!;\n const hunk = /^@@ -(\\d+)(?:,\\d+)? \\+(\\d+)/.exec(l);\n const isLast = i === patchLine - 1;\n if (l.startsWith(\"diff --git \")) file = l.replace(/^diff --git a\\/.* b\\//, \"\");\n else if (l.startsWith(\"+++ \") && l !== \"+++ /dev/null\") file = l.slice(4).replace(/^b\\//, \"\");\n else if (hunk) [oldLine, newLine] = [Number(hunk[1]), Number(hunk[2])];\n else if (l.startsWith(\"-\") && !l.startsWith(\"--- \")) {\n if (isLast) return { file, line: oldLine };\n oldLine++;\n } else if (l.startsWith(\"+\") || l.startsWith(\" \")) {\n if (isLast) return { file, line: newLine };\n newLine++;\n if (l.startsWith(\" \")) oldLine++;\n }\n }\n return { file, line: 0 };\n}\n\n/** Runs gitleaks against the raw diff text. Never throws \u2014 a scan failure fails closed (treated as a hit). */\nexport async function scanDiffForSecrets(diffText: string): Promise<SecretsScanResult> {\n const dir = await mkdtemp(join(tmpdir(), \"yolont-gitleaks-\"));\n const sourceFile = join(dir, \"diff.patch\");\n const reportFile = join(dir, \"report.json\");\n\n try {\n await writeFile(sourceFile, diffText, \"utf8\");\n // YOLONT_GITLEAKS: a binary the local CLI downloaded (see local/setup/gitleaks.ts); else PATH.\n await execFileAsync(process.env.YOLONT_GITLEAKS || \"gitleaks\", [\n \"detect\",\n \"--no-git\",\n \"--source\",\n sourceFile,\n \"--report-format\",\n \"json\",\n \"--report-path\",\n reportFile,\n \"--exit-code\",\n \"0\",\n \"--redact\",\n ]);\n\n const raw = await readFile(reportFile, \"utf8\").catch(() => \"[]\");\n const entries: GitleaksReportEntry[] = raw.trim().length > 0 ? JSON.parse(raw) : [];\n const findings: SecretFinding[] = entries.map((e) => ({\n ruleId: e.RuleID ?? \"unknown-rule\",\n ...locateInDiff(diffText, e.StartLine ?? 0),\n description: e.Description ?? \"Potential secret detected\",\n }));\n\n return { score: findings.length === 0 ? 100 : 0, findings, scannerFailed: false };\n } catch (err) {\n // fail closed: if the scanner itself couldn't run, block the LLM call same as a real hit,\n // but keep it distinguishable so the comment doesn't tell a dev to \"rotate\" a secret that\n // was never actually found.\n return {\n score: 0,\n findings: [],\n scannerFailed: true,\n scannerError: (err as Error).message,\n };\n } finally {\n await rm(dir, { recursive: true, force: true });\n }\n}\n", "export interface DiffStats {\n added: number;\n deleted: number;\n files: number;\n}\n\nexport function computeDiffStats(diffText: string): DiffStats {\n let added = 0;\n let deleted = 0;\n let files = 0;\n for (const line of diffText.split(\"\\n\")) {\n if (line.startsWith(\"diff --git \")) files++;\n if (line.startsWith(\"+++\") || line.startsWith(\"---\")) continue;\n if (line.startsWith(\"+\")) added++;\n else if (line.startsWith(\"-\")) deleted++;\n }\n return { added, deleted, files };\n}\n\n/** 100 at or under maxLines, linearly down to 0 by 2x maxLines. */\nexport function scoreDiffSize(stats: DiffStats, maxLines: number): { score: number; note?: string } {\n const total = stats.added + stats.deleted;\n if (total <= maxLines) {\n return { score: 100 };\n }\n const over = total - maxLines;\n const score = Math.max(0, Math.round(100 - (over / maxLines) * 100));\n return { score, note: `Diff is ${total} lines (+${stats.added}/-${stats.deleted}), over the ${maxLines}-line guideline.` };\n}\n", "import type { JobSummary } from \"../forge/types.js\";\n\nexport interface DetPartial {\n score: number;\n available: boolean;\n note?: string;\n}\n\nexport function scoreFromTestReport(summary: { total: number; success: number } | null): DetPartial {\n if (!summary) {\n return { score: 50, available: false, note: \"No test report found on this pipeline \u2014 category excluded from scoring.\" };\n }\n const score = Math.round((summary.success / summary.total) * 100);\n return { score, available: true, note: `${summary.success}/${summary.total} tests passed.` };\n}\n\n/** Matches by substring against job names in this pipeline (rubric `source: job:<substring>`). */\nexport function scoreFromJob(jobs: JobSummary[], nameSubstring: string, minCoverage?: number): DetPartial {\n const job = jobs.find((j) => j.name.includes(nameSubstring));\n if (!job) {\n return { score: 50, available: false, note: `No job matching '${nameSubstring}' found on this pipeline \u2014 category excluded from scoring.` };\n }\n\n if (minCoverage != null && job.coverage != null) {\n const score = Math.max(0, Math.min(100, Math.round((job.coverage / minCoverage) * 100)));\n return { score, available: true, note: `Job '${job.name}' reported ${job.coverage}% coverage (target ${minCoverage}%).` };\n }\n\n if (job.status === \"success\") return { score: 100, available: true, note: `Job '${job.name}' passed.` };\n if (job.status === \"failed\") return { score: 0, available: true, note: `Job '${job.name}' failed.` };\n return { score: 50, available: false, note: `Job '${job.name}' status '${job.status}' \u2014 category excluded from scoring.` };\n}\n", "import type { Category } from \"../rubric/schema.js\";\nimport type { JobSummary } from \"../forge/types.js\";\nimport { computeDiffStats, scoreDiffSize } from \"./diffSize.js\";\nimport { scoreFromJob, scoreFromTestReport, type DetPartial } from \"./pipelineResults.js\";\n\nconst JOB_SOURCE_PREFIX = \"job:\";\n\nexport interface DeterministicContext {\n diffText: string;\n maxLines: number;\n jobs: JobSummary[];\n testReportSummary: { total: number; success: number } | null;\n}\n\n/**\n * Resolves the deterministic component for every `deterministic`/`hybrid` category\n * (per its rubric `source`). `llm`-only categories are not touched here \u2014 they're\n * scored entirely from the single combined LLM call in the orchestrator.\n */\nexport function runDeterministicChecks(categories: Category[], ctx: DeterministicContext): Map<string, DetPartial> {\n const results = new Map<string, DetPartial>();\n\n for (const category of categories) {\n if (category.type === \"llm\") continue;\n\n const source = category.source ?? \"\";\n if (source === \"diff_size\") {\n const stats = computeDiffStats(ctx.diffText);\n const { score, note } = scoreDiffSize(stats, ctx.maxLines);\n results.set(category.name, { score, available: true, note });\n } else if (source === \"test_report\") {\n results.set(category.name, scoreFromTestReport(ctx.testReportSummary));\n } else if (source.startsWith(JOB_SOURCE_PREFIX)) {\n const nameSubstring = source.slice(JOB_SOURCE_PREFIX.length);\n results.set(category.name, scoreFromJob(ctx.jobs, nameSubstring, category.min_coverage));\n } else {\n results.set(category.name, {\n score: 50,\n available: false,\n note: `Unknown source '${source}' for category '${category.name}' \u2014 excluded from scoring.`,\n });\n }\n }\n\n return results;\n}\n", "import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { computeDiffStats, type DiffStats } from \"./checks/diffSize.js\";\n\nconst execFileAsync = promisify(execFile);\n\nexport interface DiffResult {\n text: string;\n truncated: boolean;\n /** Paths of generated/vendored files stripped before the size limit was applied \u2014 see omitGeneratedFiles. */\n omittedFiles: string[];\n /** Size of the full (post-omission, pre-truncation) diff \u2014 truncation must not make a big MR look small to scoring. */\n stats: DiffStats;\n /** Every reviewed file path in the full (post-omission, pre-truncation) diff \u2014 zone matching must see files past the byte cut too. */\n files: string[];\n}\n\nexport class DiffError extends Error {}\n\n/** Cheap check so callers can skip straight to the GitLab-API diff fallback when there's no local checkout at all. */\nexport async function isInsideGitWorkTree(): Promise<boolean> {\n try {\n await execFileAsync(\"git\", [\"rev-parse\", \"--is-inside-work-tree\"]);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Full local `git diff` \u2014 not the GitLab diff API, which truncates per-file\n * independent of our own size limit.\n *\n * Prefers `CI_MERGE_REQUEST_DIFF_BASE_SHA` (GitLab's own merge-base for this\n * MR) diffed directly against HEAD: fetching that one specific commit avoids\n * depending on a branch ref existing locally or a depth guess containing the\n * actual merge base. Falls back to a three-dot diff against a freshly\n * fetched target branch if the base SHA is unavailable (older GitLab) or the\n * server rejects fetching by bare SHA.\n */\nexport async function getMrDiff(opts: { targetBranch: string; baseSha?: string }, maxBytes: number): Promise<DiffResult> {\n let stdout: string;\n\n if (opts.baseSha) {\n try {\n await execFileAsync(\"git\", [\"fetch\", \"--depth\", \"1\", \"origin\", opts.baseSha]);\n stdout = (await execFileAsync(\"git\", [\"diff\", opts.baseSha, \"HEAD\"], { maxBuffer: 1024 * 1024 * 50 })).stdout;\n return truncateDiff(stdout, maxBytes);\n } catch {\n // fall through to the target-branch fallback below\n }\n }\n\n try {\n await execFileAsync(\"git\", [\"fetch\", \"--depth\", \"50\", \"origin\", opts.targetBranch]);\n stdout = (\n await execFileAsync(\"git\", [\"diff\", `origin/${opts.targetBranch}...HEAD`], { maxBuffer: 1024 * 1024 * 50 })\n ).stdout;\n return truncateDiff(stdout, maxBytes);\n } catch (err) {\n throw new DiffError(`Could not compute the MR diff (tried base SHA and target branch fallback): ${(err as Error).message}`);\n }\n}\n\n// Lockfiles and codegen output: huge, low-signal for LLM/Jev review, and the first\n// thing to eat the byte budget on a \"huge file changes\" MR \u2014 stripped before size\n// truncation so the limit is spent on hand-written code instead.\nconst GENERATED_FILE_PATTERNS: RegExp[] = [\n /(^|\\/)pnpm-lock\\.ya?ml$/,\n /(^|\\/)package-lock\\.json$/,\n /(^|\\/)yarn\\.lock$/,\n /(^|\\/)Cargo\\.lock$/,\n /(^|\\/)poetry\\.lock$/,\n /(^|\\/)composer\\.lock$/,\n /(^|\\/)Gemfile\\.lock$/,\n /(^|\\/)go\\.sum$/,\n /(^|\\/)(generated|gen)\\//i,\n /\\.gen\\.(ts|tsx|js|py|go)$/,\n /(^|\\/)(swagger|openapi)\\.(json|ya?ml)$/i,\n];\n\nconst GENERATED_CONTENT_MARKERS = [\"@generated\", \"do not edit\", \"generated by orval\", \"automatically generated\", \"code generated\"];\n\n/** Strips diff blocks for generated/vendored files (lockfiles, orval/openapi clients, etc.) before review. */\nexport function omitGeneratedFiles(text: string): { text: string; omittedFiles: string[] } {\n const blocks = text.split(/(?=^diff --git )/m).filter((b) => b.length > 0);\n const kept: string[] = [];\n const omittedFiles: string[] = [];\n\n for (const block of blocks) {\n const path = extractFilePath(block);\n if (path && isGeneratedFile(path, block)) {\n omittedFiles.push(path);\n } else {\n kept.push(block);\n }\n }\n\n return { text: kept.join(\"\"), omittedFiles };\n}\n\nexport function listDiffFiles(text: string): string[] {\n return text\n .split(/(?=^diff --git )/m)\n .map(extractFilePath)\n .filter((p): p is string => p !== null);\n}\n\nfunction extractFilePath(block: string): string | null {\n return block.match(/^diff --git a\\/.+? b\\/(.+)$/m)?.[1] ?? null;\n}\n\nfunction isGeneratedFile(path: string, block: string): boolean {\n if (GENERATED_FILE_PATTERNS.some((re) => re.test(path))) return true;\n // Markers live in a generated file's header \u2014 scanning the first few lines of the\n // block is enough and avoids re-scanning multi-thousand-line hunks for no reason.\n const head = block.split(\"\\n\", 20).join(\"\\n\").toLowerCase();\n return GENERATED_CONTENT_MARKERS.some((marker) => head.includes(marker));\n}\n\n/**\n * GitLab's discussion-position API requires `old_line` in addition to `new_line` for any\n * comment on an unchanged (context) line \u2014 `new_line` alone only works for a line that was\n * actually added. A finding's line number is always in new-file numbering; this walks the\n * unified diff hunks for `filePath` to classify that line and return the position GitLab\n * will actually accept. Returns null if the line isn't part of the diff at all (LLM\n * hallucinated a location) \u2014 callers should skip posting rather than guess.\n */\nexport function resolveDiffPosition(diffText: string, filePath: string, newLine: number): { oldLine?: number; newLine: number } | null {\n const blocks = diffText.split(/(?=^diff --git )/m).filter((b) => b.length > 0);\n const block = blocks.find((b) => extractFilePath(b) === filePath);\n if (!block) return null;\n\n const lines = block.split(\"\\n\");\n let oldLineNum = 0;\n let newLineNum = 0;\n\n for (const line of lines) {\n const hunkHeader = line.match(/^@@ -(\\d+)(?:,\\d+)? \\+(\\d+)(?:,\\d+)? @@/);\n if (hunkHeader) {\n oldLineNum = Number(hunkHeader[1]);\n newLineNum = Number(hunkHeader[2]);\n continue;\n }\n if (oldLineNum === 0 && newLineNum === 0) continue; // before the first hunk (file headers)\n\n if (line.startsWith(\"+\")) {\n if (newLineNum === newLine) return { newLine };\n newLineNum++;\n } else if (line.startsWith(\"-\")) {\n oldLineNum++;\n } else if (line.startsWith(\" \")) {\n if (newLineNum === newLine) return { oldLine: oldLineNum, newLine };\n oldLineNum++;\n newLineNum++;\n }\n // lines like \"\\" affect neither counter\n }\n\n return null;\n}\n\n/**\n * The diff as the LLM sees it: every added (+) and unchanged line starts with its new-file\n * line number, removed (-) lines get a blank gutter. Models miscount when they have to\n * work line numbers out from the @@ headers, and a miscounted finding lands on the wrong line\n * of the PR (resolveDiffPosition only checks that the line is somewhere in the diff).\n */\nexport function numberDiffLines(diffText: string): string {\n let newLineNum = 0;\n let inHunk = false;\n const blank = \" \".repeat(6);\n return diffText\n .split(\"\\n\")\n .map((line) => {\n if (line.startsWith(\"diff --git \")) {\n inHunk = false;\n return line;\n }\n const hunkHeader = line.match(/^@@ -\\d+(?:,\\d+)? \\+(\\d+)(?:,\\d+)? @@/);\n if (hunkHeader) {\n newLineNum = Number(hunkHeader[1]);\n inHunk = true;\n return line;\n }\n if (!inHunk) return line;\n if (line.startsWith(\"+\") || line.startsWith(\" \")) return `${String(newLineNum++).padStart(5)} ${line}`;\n if (line.startsWith(\"-\") || line.startsWith(\"\\\\\")) return `${blank}${line}`;\n return line;\n })\n .join(\"\\n\");\n}\n\nexport function truncateDiff(text: string, maxBytes: number): DiffResult {\n const { text: filtered, omittedFiles } = omitGeneratedFiles(text);\n const stats = computeDiffStats(filtered);\n const files = listDiffFiles(filtered);\n if (Buffer.byteLength(filtered, \"utf8\") <= maxBytes) {\n return { text: filtered, truncated: false, omittedFiles, stats, files };\n }\n return { text: Buffer.from(filtered, \"utf8\").subarray(0, maxBytes).toString(\"utf8\"), truncated: true, omittedFiles, stats, files };\n}\n", "import Anthropic from \"@anthropic-ai/sdk\";\nimport { LlmReviewResponseSchema, type LlmReviewResponse } from \"./schema.js\";\nimport { LlmParseError, buildReviewJsonSchema, buildReviewPrompt, type LLMProvider, type ReviewInput } from \"./provider.js\";\n\nconst REVIEW_TOOL_NAME = \"submit_pr_review\";\n\nexport class AnthropicProvider implements LLMProvider {\n private client: Anthropic;\n private model: string;\n\n constructor(opts: { apiKey: string; model?: string }) {\n this.client = new Anthropic({ apiKey: opts.apiKey });\n this.model = opts.model ?? \"claude-sonnet-5\";\n }\n\n async review(input: ReviewInput): Promise<LlmReviewResponse> {\n const schema = buildReviewJsonSchema(input.categories.map((c) => c.name), input.zones?.map((h) => h.zone.id), !!input.reviewerFocus) as Anthropic.Tool.InputSchema;\n const response = await this.client.messages.create({\n model: this.model,\n // Thinking is always on for current models (Opus 5.5, Sonnet 5.5) and counts toward this cap.\n max_tokens: 16000,\n tools: [\n {\n name: REVIEW_TOOL_NAME,\n description: \"Submit the structured PR review, one entry per requested category.\",\n input_schema: schema,\n },\n ],\n // Forced tool_choice (\"tool\"/\"any\") is a 400 on Opus 5.5 / Sonnet 5.5 / Fable 5.1 \u2014 use auto + an explicit\n // instruction. A reply without the tool call still fails loudly below (LlmParseError \u2192 retried).\n tool_choice: { type: \"auto\" },\n messages: [{ role: \"user\", content: `${buildReviewPrompt(input)}\\n\\nSubmit your review by calling the ${REVIEW_TOOL_NAME} tool exactly once.` }],\n });\n\n const toolUse = response.content.find((block) => block.type === \"tool_use\");\n if (!toolUse || toolUse.type !== \"tool_use\") {\n throw new LlmParseError(\"Model response did not include a tool_use block\", JSON.stringify(response.content, null, 2));\n }\n\n const parsed = LlmReviewResponseSchema.safeParse(toolUse.input);\n if (!parsed.success) {\n throw new LlmParseError(`Schema validation failed: ${parsed.error.message}`, JSON.stringify(toolUse.input, null, 2));\n }\n return parsed.data;\n }\n\n async complete(prompt: string): Promise<string> {\n const response = await this.client.messages.create({ model: this.model, max_tokens: 16000, messages: [{ role: \"user\", content: prompt }] });\n // Thinking blocks come first on current models; only the text is the answer.\n const text = response.content.flatMap((b) => (b.type === \"text\" ? [b.text] : [])).join(\"\");\n if (!text) throw new LlmParseError(`Model returned no text (stop_reason: ${response.stop_reason})`);\n return text;\n }\n}\n", "import { z } from \"zod\";\nimport { ChangeTypeSchema } from \"../changeType.js\";\n\nexport const SeveritySchema = z.enum([\"minor\", \"major\", \"critical\"]);\n\nexport const LlmFindingSchema = z.object({\n severity: SeveritySchema,\n file: z.string().optional(),\n line: z.number().int().positive().optional(),\n issue: z.string(),\n suggestion: z.string().optional(),\n});\n\nexport const LlmCategoryResultSchema = z.object({\n category: z.string(),\n // Advisory only \u2014 the score engine recomputes from findings (see scoring/engine.ts) and\n // never reads this field. Optional because some free models omit it despite the\n // schema/prompt asking for it.\n score: z.number().min(0).max(100).optional(),\n findings: z.array(LlmFindingSchema),\n summary: z.string(),\n});\n\nexport const ZoneVerdictSchema = z.object({\n zone_id: z.string(),\n impact: z.enum([\"none\", \"low\", \"high\"]),\n verdict: z.string(),\n});\n\nexport const LlmReviewResponseSchema = z.object({\n categories: z.array(LlmCategoryResultSchema),\n // Separate from scoring by design. `.catch` so a model that drops\n // or mangles this optional block never fails the whole review.\n zone_verdicts: z.array(ZoneVerdictSchema).optional().catch(undefined),\n // Only requested when the reviewer gave a focus; same never-fail treatment.\n focus_notes: z.string().optional().catch(undefined),\n // Label mode asks for it; never fails the review either.\n change_type: z.object({ type: ChangeTypeSchema, reason: z.string() }).optional().catch(undefined),\n});\n\nexport type ZoneVerdict = z.infer<typeof ZoneVerdictSchema>;\n\nexport type LlmCategoryResult = z.infer<typeof LlmCategoryResultSchema>;\nexport type LlmReviewResponse = z.infer<typeof LlmReviewResponseSchema>;\n", "import { z } from \"zod\";\n\n/**\n * What kind of change a PR is. Two modes (config `changeType`, env ETHOS_CHANGE_TYPE in CI):\n * - \"label\": the review call also names the type; shown, saved, filterable. Review unchanged.\n * - \"steer\": the type is settled first (free hints, else one small LLM call; the TUI lets you\n * change it), then the review gets that type's checks.\n */\nexport const CHANGE_TYPES = [\"feature\", \"bugfix\", \"refactor\", \"performance\", \"tests\", \"docs\", \"chore\", \"ci\", \"revert\", \"mixed\"] as const;\nexport const ChangeTypeSchema = z.enum(CHANGE_TYPES);\nexport type ChangeType = z.infer<typeof ChangeTypeSchema>;\nexport type ChangeTypeMode = \"off\" | \"label\" | \"steer\";\n\nexport const CHANGE_TYPE_LABELS: Record<ChangeType, string> = {\n feature: \"Feature\",\n bugfix: \"Bug fix\",\n refactor: \"Refactor\",\n performance: \"Performance\",\n tests: \"Tests only\",\n docs: \"Docs\",\n chore: \"Chore / dependencies\",\n ci: \"CI / build / config\",\n revert: \"Revert\",\n mixed: \"Mixed\",\n};\n\nexport interface ChangeTypeGuess {\n type: ChangeType;\n reason: string;\n /** Where it came from: the title/branch/labels (free) or the LLM. */\n from: \"hint\" | \"llm\";\n}\n\n// Conventional-commit prefixes and common branch/label words.\nconst WORDS: [RegExp, ChangeType][] = [\n [/^(feat|feature|enhancement)$/, \"feature\"],\n [/^(fix|bugfix|hotfix|bug)$/, \"bugfix\"],\n [/^refactor(ing)?$/, \"refactor\"],\n [/^(perf|performance)$/, \"performance\"],\n [/^tests?$/, \"tests\"],\n [/^(docs?|documentation)$/, \"docs\"],\n [/^(chore|deps|dependencies|dependabot|renovate)$/, \"chore\"],\n [/^(ci|build)$/, \"ci\"],\n [/^revert$/, \"revert\"],\n];\nconst typeOfWord = (w: string) => WORDS.find(([re]) => re.test(w.toLowerCase()))?.[1];\n\n/** Free hints, no LLM: `fix(api): \u2026` titles, `feat/\u2026` branches, `type::bug` / `bug` labels. */\nexport function hintFromMr(mr: { title: string; sourceBranch?: string; labels?: string[] }): ChangeTypeGuess | null {\n if (/^revert\\b/i.test(mr.title)) return { type: \"revert\", reason: \"title starts with Revert\", from: \"hint\" };\n const m = mr.title.match(/^(?:draft:\\s*)?([a-z]+)(?:\\(([^)]*)\\))?!?:/i);\n const prefix = m?.[1];\n // `build(deps):` / `chore(deps):` are dependency bumps whatever the word.\n const byTitle = m?.[2]?.toLowerCase() === \"deps\" ? \"chore\" : prefix && typeOfWord(prefix);\n if (byTitle) return { type: byTitle, reason: `title prefix \"${prefix}:\"`, from: \"hint\" };\n const branch = mr.sourceBranch?.split(\"/\")[0];\n const byBranch = branch && mr.sourceBranch!.includes(\"/\") ? typeOfWord(branch) : undefined;\n if (byBranch) return { type: byBranch, reason: `branch ${mr.sourceBranch}`, from: \"hint\" };\n for (const label of mr.labels ?? []) {\n const t = typeOfWord(label.replace(/^type::?\\s*/i, \"\"));\n if (t) return { type: t, reason: `label \"${label}\"`, from: \"hint\" };\n }\n return null;\n}\n\n/** Steer mode only: one small call on the title, file list and the diff's start. */\nexport async function classifyChange(complete: (prompt: string) => Promise<string>, mr: { title: string; description?: string }, diff: string, files: string[]): Promise<ChangeTypeGuess> {\n const prompt = `Classify this merge request as exactly one of: ${CHANGE_TYPES.join(\", \")}.\n\"mixed\" only when it clearly does two unrelated kinds of work. Answer with JSON only: {\"type\": \"...\", \"reason\": \"one short sentence\"}.\n\nTitle: ${mr.title}\nDescription: ${(mr.description ?? \"\").slice(0, 1500)}\nChanged files (${files.length}): ${files.slice(0, 80).join(\", \")}\n\nDiff (start):\n${diff.slice(0, 6000)}`;\n const raw = await complete(prompt);\n const json = raw.match(/\\{[\\s\\S]*\\}/)?.[0];\n const parsed = z.object({ type: ChangeTypeSchema, reason: z.string() }).safeParse(json ? JSON.parse(json) : null);\n if (!parsed.success) throw new Error(`couldn't read a change type from: ${raw.slice(0, 200)}`);\n return { ...parsed.data, from: \"llm\" };\n}\n\n// The types whose checks are lighter. The author controls the title, branch, labels and\n// description, so they only count when every changed file fits: a \"docs:\" PR that edits\n// src/payment.ts must not get a docs-only review (that would be a way around the gate).\nconst LIGHTER: Partial<Record<ChangeType, RegExp>> = {\n docs: /(\\.(md|mdx|rst|adoc|txt)$|(^|\\/)docs?\\/)/i,\n tests: /((^|\\/)(tests?|__tests__|specs?)\\/|\\.(test|spec)\\.[a-z0-9]+$|_test\\.(go|py)$)/i,\n chore: /(^|\\/)(package(-lock)?\\.json|pnpm-lock\\.yaml|yarn\\.lock|bun\\.lockb|go\\.(mod|sum)|Cargo\\.(toml|lock)|requirements[^/]*\\.txt|poetry\\.lock|pyproject\\.toml|Gemfile(\\.lock)?|composer\\.(json|lock)|\\.npmrc|\\.nvmrc|renovate\\.json|\\.github\\/dependabot\\.ya?ml)$/i,\n ci: /((^|\\/)\\.github\\/workflows\\/|(^|\\/)\\.gitlab-ci|(^|\\/)\\.circleci\\/|(^|\\/)Dockerfile|(^|\\/)docker-compose|(^|\\/)Jenkinsfile|(^|\\/)Makefile$|(^|\\/)\\.dockerignore$)/i,\n};\nexport const fitsFiles = (type: ChangeType, files: string[]) => !LIGHTER[type] || (files.length > 0 && files.every((f) => LIGHTER[type]!.test(f)));\n\n/**\n * Steer mode's guess: free hints first, else the classifier; null when the LLM call fails (the\n * review goes on without a type). A lighter type the files don't back up is never used.\n */\nexport async function guessForSteer(complete: (prompt: string) => Promise<string>, mr: { title: string; description?: string; sourceBranch?: string; labels?: string[] }, diff: string, files: string[]): Promise<ChangeTypeGuess | null> {\n const hint = hintFromMr(mr);\n if (hint && fitsFiles(hint.type, files)) return hint;\n const guess = await classifyChange(complete, mr, diff, files).catch(() => null);\n if (guess && !fitsFiles(guess.type, files)) return { type: \"mixed\", reason: `called ${guess.type}, but it changes other files too`, from: \"llm\" };\n return guess;\n}\n\n/** `off` | `label` | `steer`; anything else falls back to label. */\nexport const parseChangeTypeMode = (v: string | undefined): ChangeTypeMode => (v === \"off\" || v === \"steer\" ? v : \"label\");\n\n/** Steer mode: what the reviewer should check for each type. */\nexport const CHANGE_TYPE_CHECKS: Record<ChangeType, string> = {\n feature: \"New behavior: check it has tests for the main path and edge cases (empty, error, limits), docs or comments where users meet it, and no unrelated changes riding along.\",\n bugfix: \"A fix: check it addresses the root cause rather than the symptom, that a regression test reproduces the bug, and that the fix doesn't change unrelated behavior.\",\n refactor: \"Should not change behavior: flag anything that does (changed conditions, defaults, error handling, public signatures, ordering). Existing tests should pass unchanged; flag tests that were edited to pass.\",\n performance: \"Ask for evidence (a benchmark, a measurement, or clear reasoning about complexity), and check the faster path keeps results, errors and edge cases identical.\",\n tests: \"Tests only: check they assert real behavior (not implementation details), would fail if the code broke, and aren't flaky (timing, order, network). Don't penalize missing tests.\",\n docs: \"Docs: check accuracy against the code, broken links and examples that wouldn't run. Lighter review; don't penalize missing tests.\",\n chore: \"Chore / dependencies: check version bumps for breaking changes and lockfile consistency, and that nothing functional is hidden inside. Lighter review.\",\n ci: \"CI / build / config: check secrets aren't exposed, jobs still gate what they should, and caching or conditions don't silently skip steps.\",\n revert: \"A revert: check it cleanly undoes the named change and nothing else, and whether anything since depends on what's being removed.\",\n mixed: \"Mixed changes: review each part by its own kind, and note that splitting it into separate PRs would make it easier to review.\",\n};\n\nexport function changeTypePromptSection(mode: { steer?: ChangeType; ask?: boolean }): string {\n if (mode.steer) return `Change type (confirmed by the reviewer): ${mode.steer}.\\n${CHANGE_TYPE_CHECKS[mode.steer]}\\n\\n`;\n if (mode.ask) return `Also fill change_type: what kind of change this is (one of ${CHANGE_TYPES.join(\", \")}), with a one-sentence reason. It doesn't affect scores.\\n\\n`;\n return \"\";\n}\n\n/** For the review comment: \"Type: Refactor (title prefix \"refactor:\")\". */\nexport const describeChangeType = (t: ChangeType, reason?: string) => `${CHANGE_TYPE_LABELS[t]}${reason ? ` (${reason})` : \"\"}`;\n", "import { CHANGE_TYPES, changeTypePromptSection, type ChangeType } from \"../changeType.js\";\nimport type { ZoneHit } from \"../zones/zones.js\";\nimport type { LlmReviewResponse } from \"./schema.js\";\nimport { numberDiffLines } from \"../git.js\";\n\nexport interface ReviewCategorySpec {\n name: string;\n /** Human description of what this category means, fed to the model as rubric context. */\n description: string;\n}\n\nexport interface ReviewInput {\n diff: string;\n truncated: boolean;\n conventions: string;\n categories: ReviewCategorySpec[];\n /** e.g. \"Recurring weak categories: conventions (avg 65/100 over last 5 MRs).\" */\n authorHistorySummary: string;\n /** Free-text, per-review ask from whoever triggered this run \u2014 e.g. \"focus on the retry\n * logic in the payment client, ignore unrelated lint churn.\" Optional, one-off, not\n * persisted as a convention or memory; unset for the unattended CI path. */\n reviewerFocus?: string;\n /** Zones the diff's files matched (matched in code, see src/zones). Empty/unset = no zone section. */\n zones?: ZoneHit[];\n /** Steer mode: the settled change type, whose checks go into the prompt. */\n changeType?: ChangeType;\n /** Label mode: ask the model to name the change type (change_type in the response). */\n askChangeType?: boolean;\n}\n\n/**\n * Retries a flaky call with exponential backoff. Free-tier LLM gateways in particular\n * fail transiently a lot \u2014 rate limits, transport-level \"fetch failed\", \"model\n * unavailable\" \u2014 and those are worth a couple of retries before giving up and scoring\n * the LLM categories 0 for the run. Not selective about error type: every failure\n * observed against OpenCode Zen's free tier has been transient, and a wasted retry on a\n * genuinely broken config just costs a few seconds.\n */\nexport async function withRetry<T>(fn: () => Promise<T>, opts: { attempts?: number; baseDelayMs?: number } = {}): Promise<T> {\n const attempts = opts.attempts ?? 3;\n const baseDelayMs = opts.baseDelayMs ?? 2000;\n let lastError: unknown;\n\n for (let attempt = 0; attempt < attempts; attempt++) {\n try {\n return await fn();\n } catch (err) {\n lastError = err;\n if (attempt < attempts - 1) {\n const delayMs = baseDelayMs * 2 ** attempt;\n console.error(`[yolont] LLM call failed (attempt ${attempt + 1}/${attempts}): ${(err as Error).message}${(err as Error).cause ? ` (${String((err as Error).cause)})` : \"\"} \u2014 retrying in ${delayMs}ms`);\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n }\n }\n\n throw lastError;\n}\n\nexport interface LLMProvider {\n /** One call covering every llm/hybrid category \u2014 keeps cost/latency to a single request per MR. */\n review(input: ReviewInput): Promise<LlmReviewResponse>;\n /** Plain text answer to a free-form prompt (conventions generation). */\n complete(prompt: string): Promise<string>;\n}\n\nexport class LlmParseError extends Error {\n /** The raw model output that failed to parse/validate \u2014 undefined for transport-level\n * failures (non-2xx, network error) where there's no model output to show. Callers\n * (e.g. the review TUI) print this on failure since the short message alone often\n * isn't enough to tell what the model actually did wrong. */\n constructor(\n message: string,\n public rawResponse?: string,\n ) {\n super(message);\n }\n}\n\n/**\n * Shared JSON schema shape for both providers. `category` is constrained to an enum of\n * the exact requested category names \u2014 without it, a model returning e.g. \"Conventions\"\n * or \"pr hygiene\" instead of \"conventions\"/\"pr_hygiene\" fails the lookup in index.ts\n * silently (that category just scores 0 with \"LLM did not return this category\"), which\n * is a scoring-corruption bug a human reviewing the diff would never catch.\n */\nexport function buildReviewJsonSchema(categoryNames: string[], zoneIds: string[] = [], withFocus = false): Record<string, unknown> {\n return {\n type: \"object\",\n properties: {\n change_type: {\n type: \"object\",\n description: \"Only when asked: what kind of change this is.\",\n properties: { type: { type: \"string\", enum: [...CHANGE_TYPES] }, reason: { type: \"string\" } },\n required: [\"type\", \"reason\"],\n },\n ...(withFocus && {\n focus_notes: { type: \"string\", description: \"What you checked for the reviewer's focus and what you found, including 'checked X, Y, Z \u2014 no issues'.\" },\n }),\n ...(zoneIds.length > 0 && {\n zone_verdicts: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n zone_id: { type: \"string\", enum: zoneIds },\n impact: { type: \"string\", enum: [\"none\", \"low\", \"high\"] },\n verdict: { type: \"string\" },\n },\n required: [\"zone_id\", \"impact\", \"verdict\"],\n },\n },\n }),\n categories: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n category: { type: \"string\", enum: categoryNames },\n score: { type: \"number\", description: \"Advisory only; the caller recomputes the real score from findings.\" },\n findings: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n severity: { type: \"string\", enum: [\"minor\", \"major\", \"critical\"] },\n file: { type: \"string\" },\n line: { type: \"number\", description: \"The number printed at the start of the diff line the issue is on (new-file numbering).\" },\n issue: { type: \"string\" },\n suggestion: { type: \"string\" },\n },\n required: [\"severity\", \"issue\"],\n },\n },\n summary: { type: \"string\" },\n },\n required: [\"category\", \"findings\", \"summary\"],\n },\n },\n },\n required: [\"categories\"],\n };\n}\n\nexport function buildReviewPrompt(input: ReviewInput): string {\n const categoryList = input.categories.map((c) => `- ${c.name}: ${c.description}`).join(\"\\n\");\n return `You are reviewing a GitLab merge request diff against a team rubric.\n\nCategories to score (0-100 each, return exactly one entry per category, using the same category name):\n${categoryList}\n\n${changeTypePromptSection({ steer: input.changeType, ask: input.askChangeType })}${input.reviewerFocus ? buildFocusPromptSection(input.reviewerFocus) : \"\"}Team conventions:\n${input.conventions}\n\nAuthor history (context only \u2014 do not penalize for past MRs, only for issues present in this diff):\n${input.authorHistorySummary}\n\n${input.zones?.length ? `${buildZonesPromptSection(input.zones)}\\n` : \"\"}${input.truncated ? \"NOTE: this diff was truncated to fit size limits; review only what is shown.\\n\" : \"\"}\nDiff (each added \"+\" or unchanged \" \" line starts with its line number in the new file; removed \"-\" lines have none).\nFor a finding's \"line\", copy that number exactly from the line the issue is on, preferably a \"+\" line. Never count lines yourself.\n${numberDiffLines(input.diff)}\n`;\n}\n\nfunction buildFocusPromptSection(focus: string): string {\n return `Reviewer's focus for this review (top priority \u2014 still score every category):\n${focus}\n\nHow to apply it:\n- Before scoring, go through the diff and list for yourself every changed line related to this focus (e.g. for \"dependency injection\": every constructor, provider, injection token, registration and consumer; for \"wrong function call\": every changed call site \u2014 check the callee, argument order/types and the return value use against what the diff shows).\n- Check each one. Do not skip an item because it looks fine at a glance.\n- Report every real issue you find as a finding in the best-fitting category.\n- Fill focus_notes with one or two sentences: what you checked for this focus and what you found (say \"no issues\" explicitly if so).\n\n`;\n}\n\nfunction buildZonesPromptSection(hits: ZoneHit[]): string {\n const zones = hits\n .map(({ zone, files, viaImport, feedback }) =>\n [\n `- ${zone.id} (${zone.level}): ${zone.why}`,\n zone.watch_for.length > 0 ? ` watch for: ${zone.watch_for.join(\"; \")}` : \"\",\n zone.budget ? ` budget: ${zone.budget}` : \"\",\n ` changed files here: ${files.map((f) => (viaImport?.includes(f) ? `${f} (not in this zone's folders, but imported by it \u2014 so it runs with it)` : f)).join(\", \")}`,\n feedback?.length ? ` past reviewer feedback on this zone's flags (weight heavily):\\n${feedback.map((f) => ` - ${f}`).join(\"\\n\")}` : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\"),\n )\n .join(\"\\n\");\n return `Sensitive zones this diff touches (red = runs on every start, request or render, or is hard to undo; amber = widely shared; green = rarely runs):\n${zones}\n\nFor each zone above, add one zone_verdicts entry: impact none/low/high and one sentence naming the concrete effect, judged against that zone's own reason and watch-for list (e.g. \"adds a blocking fetch at mount\", \"migration rewrites a large table without a batch\"). This is independent of code quality, and must not change category findings or scores.\n`;\n}\n", "import { LlmReviewResponseSchema, type LlmReviewResponse } from \"./schema.js\";\nimport { LlmParseError, buildReviewJsonSchema, buildReviewPrompt, type LLMProvider, type ReviewInput } from \"./provider.js\";\n\n/**\n * Local/self-hosted fallback. Not the default \u2014 only used when\n * OLLAMA_URL is set and no ANTHROPIC_API_KEY is present. Same schema contract\n * as AnthropicProvider via Ollama's structured-output `format` parameter.\n */\nexport class OllamaProvider implements LLMProvider {\n constructor(private opts: { baseUrl: string; model: string }) {}\n\n async review(input: ReviewInput): Promise<LlmReviewResponse> {\n const res = await fetch(`${this.opts.baseUrl.replace(/\\/$/, \"\")}/api/chat`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n model: this.opts.model,\n stream: false,\n format: buildReviewJsonSchema(input.categories.map((c) => c.name), input.zones?.map((h) => h.zone.id), !!input.reviewerFocus),\n messages: [{ role: \"user\", content: buildReviewPrompt(input) }],\n }),\n });\n\n if (!res.ok) {\n throw new LlmParseError(`Ollama request failed: ${res.status} ${await res.text()}`);\n }\n\n const body = (await res.json()) as { message?: { content?: string } };\n const content = body.message?.content;\n if (!content) {\n throw new LlmParseError(\"Ollama response had no message content\");\n }\n\n let json: unknown;\n try {\n json = JSON.parse(content);\n } catch (err) {\n throw new LlmParseError(`Ollama response was not valid JSON: ${(err as Error).message}`, content);\n }\n\n const parsed = LlmReviewResponseSchema.safeParse(json);\n if (!parsed.success) {\n throw new LlmParseError(`Schema validation failed: ${parsed.error.message}`, content);\n }\n return parsed.data;\n }\n\n async complete(prompt: string): Promise<string> {\n const res = await fetch(`${this.opts.baseUrl.replace(/\\/$/, \"\")}/api/chat`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ model: this.opts.model, stream: false, messages: [{ role: \"user\", content: prompt }] }),\n });\n if (!res.ok) throw new LlmParseError(`Ollama request failed: ${res.status} ${await res.text()}`);\n const content = ((await res.json()) as { message?: { content?: string } }).message?.content;\n if (!content) throw new LlmParseError(\"Ollama response had no message content\");\n return content;\n }\n}\n", "import { LlmReviewResponseSchema, type LlmReviewResponse } from \"./schema.js\";\nimport { LlmParseError, buildReviewJsonSchema, buildReviewPrompt, type LLMProvider, type ReviewInput } from \"./provider.js\";\n\nconst TOOL_NAME = \"submit_pr_review\";\n\n/**\n * Any OpenAI-compatible /v1 gateway: OpenCode (https://opencode.ai/zen, formerly \"Zen\"),\n * OpenAI, OpenRouter, \u2026 Defaults to OpenCode, which has a\n * rotating set of free models. Same schema contract as the other providers via\n * OpenAI-style function-calling (`tools` + forced `tool_choice`).\n *\n * Free models are smaller and sometimes ignore forced tool-calling and answer with\n * plain JSON in the message content instead \u2014 this provider falls back to parsing\n * that directly rather than treating it as a hard failure.\n *\n * The Go gateway (zen/go) requires an `x-opencode-session` header to route the\n * request \u2014 without it the provider rejects with `MissingSessionID`. Generate\n * one lazily so plain Zen callers (no session needed) don't send it.\n */\nexport class OpenCodeZenProvider implements LLMProvider {\n private sessionId: string | undefined;\n\n constructor(private opts: { apiKey: string; model: string; baseUrl?: string; useSession?: boolean }) {}\n\n /** Errors name the host the request went to (api.openai.com, opencode.ai, \u2026), not a fixed brand. */\n private get label(): string {\n try {\n return new URL(this.opts.baseUrl ?? \"https://opencode.ai/zen/v1\").host;\n } catch {\n return \"LLM gateway\";\n }\n }\n\n async review(input: ReviewInput): Promise<LlmReviewResponse> {\n const schema = buildReviewJsonSchema(input.categories.map((c) => c.name), input.zones?.map((h) => h.zone.id), !!input.reviewerFocus);\n\n const { toolCallArgs, content } = await this.stream({\n model: this.opts.model,\n stream: true,\n messages: [{ role: \"user\", content: buildReviewPrompt(input) }],\n tools: [\n {\n type: \"function\",\n function: {\n name: TOOL_NAME,\n description: \"Submit the structured PR review, one entry per requested category.\",\n parameters: schema,\n },\n },\n ],\n tool_choice: { type: \"function\", function: { name: TOOL_NAME } },\n });\n\n const raw = toolCallArgs || content;\n if (!raw) {\n throw new LlmParseError(`${this.label} response had neither a tool call nor message content`);\n }\n\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch (err) {\n throw new LlmParseError(`${this.label} response was not valid JSON: ${(err as Error).message}`, raw);\n }\n\n const parsed = LlmReviewResponseSchema.safeParse(json);\n if (!parsed.success) {\n throw new LlmParseError(`Schema validation failed: ${parsed.error.message}`, raw);\n }\n return parsed.data;\n }\n\n async complete(prompt: string): Promise<string> {\n const { content } = await this.stream({ model: this.opts.model, stream: true, messages: [{ role: \"user\", content: prompt }] });\n if (!content) throw new LlmParseError(`${this.label} response had no message content`);\n return content;\n }\n\n /** POSTs a streamed chat completion; returns the concatenated tool-call args and message content (reasoning deltas ignored). */\n private async stream(body: Record<string, unknown>): Promise<{ toolCallArgs: string; content: string }> {\n const baseUrl = (this.opts.baseUrl ?? \"https://opencode.ai/zen/v1\").replace(/\\/$/, \"\");\n if (this.opts.useSession && !this.sessionId) {\n this.sessionId = crypto.randomUUID();\n }\n\n const res = await fetch(`${baseUrl}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${this.opts.apiKey}`,\n ...(this.sessionId ? { \"x-opencode-session\": this.sessionId } : {}),\n },\n body: JSON.stringify(body),\n });\n\n if (!res.ok) {\n throw new LlmParseError(`${this.label} request failed: ${res.status} ${await res.text()}`);\n }\n\n // Streamed SSE: reasoning models can think for 5+ min on a big diff, past undici's\n // 300s headers timeout (\"fetch failed\"). Streaming gets headers back immediately and\n // keeps bytes flowing, so neither that nor an idle NAT/VPN drop kills the request.\n let toolCallArgs = \"\";\n let content = \"\";\n let buffer = \"\";\n for await (const chunk of res.body!.pipeThrough(new TextDecoderStream())) {\n buffer += chunk;\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop()!;\n for (const line of lines) {\n const data = line.startsWith(\"data:\") ? line.slice(5).trim() : \"\";\n if (!data || data === \"[DONE]\") continue;\n const delta = (\n JSON.parse(data) as {\n choices?: Array<{ delta?: { content?: string | null; tool_calls?: Array<{ function?: { arguments?: string } }> } }>;\n }\n ).choices?.[0]?.delta;\n toolCallArgs += delta?.tool_calls?.[0]?.function?.arguments ?? \"\";\n content += delta?.content ?? \"\";\n }\n }\n\n return { toolCallArgs, content };\n }\n}\n", "import type { LlmReviewResponse } from \"./schema.js\";\n\n/**\n * Deterministic, no-cost rewrite of LLM prose into plainer, more direct phrasing.\n * Wired into every provider via `createLlmProvider` (see index.ts) so review comments\n * read like a teammate wrote them instead of carrying typical LLM hedging/filler \u2014\n * a second LLM call to \"humanize\" the text would add latency/cost for the same result,\n * and these phrases are common enough to catch with fixed rules without touching the\n * technical content (file/line/severity are untouched; only issue/suggestion/summary\n * prose is rewritten).\n */\n\n// Phrase-level filler that adds no information \u2014 stripped outright, anchored so we don't\n// eat similar words mid-sentence.\nconst FILLER_PHRASES: RegExp[] = [\n /\\bit is (?:important|worth) to note that\\b,?\\s*/gi,\n /\\bit'?s worth noting that\\b,?\\s*/gi,\n /\\bit should be noted that\\b,?\\s*/gi,\n /\\bplease note that\\b,?\\s*/gi,\n /\\bkeep in mind that\\b,?\\s*/gi,\n /\\bas (?:previously )?mentioned,?\\s*/gi,\n /^overall,\\s*/gi,\n /^in summary,\\s*/gi,\n /^in conclusion,\\s*/gi,\n];\n\n// word/phrase -> plainer equivalent. Applied whole-word, case-preserved on the first\n// letter so \"Utilize\" -> \"Use\" and \"utilize\" -> \"use\".\nconst WORD_SWAPS: [RegExp, string][] = [\n [/\\bin order to\\b/gi, \"to\"],\n [/\\bdue to the fact that\\b/gi, \"because\"],\n [/\\bat this point in time\\b/gi, \"now\"],\n [/\\bin the event that\\b/gi, \"if\"],\n [/\\ba number of\\b/gi, \"some\"],\n [/\\bprior to\\b/gi, \"before\"],\n [/\\bsubsequent to\\b/gi, \"after\"],\n];\n\nconst SUFFIX_SWAPS: [RegExp, Record<string, string>][] = [\n [/\\butiliz(e|es|ed|ing)\\b/gi, { e: \"use\", es: \"uses\", ed: \"used\", ing: \"using\" }],\n [/\\bleverag(e|es|ed|ing)\\b/gi, { e: \"use\", es: \"uses\", ed: \"used\", ing: \"using\" }],\n [/\\bfacilitat(e|es|ed|ing)\\b/gi, { e: \"help\", es: \"helps\", ed: \"helped\", ing: \"helping\" }],\n];\n\nfunction preserveCase(original: string, replacement: string): string {\n if (original[0] && original[0] === original[0].toUpperCase() && original[0] !== original[0].toLowerCase()) {\n return replacement[0]!.toUpperCase() + replacement.slice(1);\n }\n return replacement;\n}\n\nexport function sanitizeReviewText(text: string): string {\n let result = text;\n\n for (const phrase of FILLER_PHRASES) {\n result = result.replace(phrase, \"\");\n }\n\n for (const [pattern, suffixMap] of SUFFIX_SWAPS) {\n result = result.replace(pattern, (match, suffix: string) => preserveCase(match, suffixMap[suffix.toLowerCase()] ?? match));\n }\n for (const [pattern, replacement] of WORD_SWAPS) {\n result = result.replace(pattern, (match) => preserveCase(match, replacement));\n }\n\n // Collapse whitespace left behind by stripped phrases, and re-capitalize if a leading\n // phrase strip left a lowercase word starting the sentence.\n result = result.replace(/[ \\t]{2,}/g, \" \").replace(/^\\n+/, \"\").trim();\n if (result && result[0] === result[0]!.toLowerCase() && result[0] !== result[0]!.toUpperCase()) {\n result = result[0]!.toUpperCase() + result.slice(1);\n }\n return result;\n}\n\nexport function sanitizeReviewResponse(response: LlmReviewResponse): LlmReviewResponse {\n return {\n zone_verdicts: response.zone_verdicts?.map((v) => ({ ...v, verdict: sanitizeReviewText(v.verdict) })),\n focus_notes: response.focus_notes && sanitizeReviewText(response.focus_notes),\n categories: response.categories.map((c) => ({\n ...c,\n summary: sanitizeReviewText(c.summary),\n findings: c.findings.map((f) => ({\n ...f,\n issue: sanitizeReviewText(f.issue),\n suggestion: f.suggestion ? sanitizeReviewText(f.suggestion) : f.suggestion,\n })),\n })),\n };\n}\n", "import { listDiffFiles, resolveDiffPosition } from \"../git.js\";\nimport type { LlmCategoryResult } from \"./schema.js\";\n\nconst ENDPOINT = \"https://api.typesafe.ai/v1/systemone\";\nconst DEFAULT_MODEL = \"jev-latest\";\nconst DEFAULT_NOISE_THRESHOLD = 0.5;\n\ninterface JevAnswer {\n noul?: number;\n}\n\ninterface JevResponse {\n answers: Record<string, JevAnswer>;\n}\n\nexport interface JevEnv {\n TYPESAFE_API_KEY?: string;\n JEV_MODEL?: string;\n JEV_NOISE_THRESHOLD?: string;\n JEV_DISABLED?: string;\n}\n\n// JEV_DISABLED=1 (or true) skips Jev even with a key set \u2014 temporary kill switch.\nexport const jevEnabled = (env: JevEnv): boolean => !!env.TYPESAFE_API_KEY && !/^(1|true)$/i.test(env.JEV_DISABLED ?? \"\");\n\n/**\n * Cross-checks LLM findings against Jev (typesafe.ai) \u2014 a fast, cheap, calibrated\n * classifier \u2014 and drops the ones it flags as likely noise/false-positives before they\n * reach scoring/comments. Purely an accuracy layer on top of the LLM review, not a gate:\n * unset TYPESAFE_API_KEY, a transport error, or a malformed response all fail open\n * (findings pass through unfiltered) rather than blocking or zeroing a review the LLM\n * already produced. Failing closed would be wrong here too: dropped findings raise the\n * score, so a Jev outage must never make MRs pass more easily.\n *\n * With a key set, findings naming a file absent from the diff are dropped before Jev is\n * asked \u2014 the LLM saw this same diff text, so that location cannot be real.\n */\nexport async function filterNoiseWithJev(\n categories: LlmCategoryResult[],\n diffText: string,\n env: JevEnv,\n // Same memory string the LLM saw (insights, human corrections, disputed/confirmed\n // findings) so Jev judges findings against what reviewers already accepted/rejected.\n memory?: string,\n // The reviewer's per-run focus (TUI/--focus). Findings on it often hinge on code just\n // outside the diff (callee signatures, DI wiring), which rule 2 alone would reject.\n focus?: string,\n): Promise<LlmCategoryResult[]> {\n if (!jevEnabled(env)) return categories;\n const diffFiles = new Set(listDiffFiles(diffText));\n // filter, not map: interactiveReview finds dropped findings by object identity.\n const grounded = categories.map((c) => ({ ...c, findings: c.findings.filter((f) => !f.file || diffPath(f.file, diffFiles)) }));\n if (grounded.every((c) => c.findings.length === 0)) return grounded;\n\n const questions: Record<string, { type: \"noul\"; instructions: string }> = {};\n grounded.forEach((c, ci) => {\n c.findings.forEach((f, fi) => {\n const path = f.file && diffPath(f.file, diffFiles);\n const lineOutsideDiff = path && f.line && !resolveDiffPosition(diffText, path, f.line);\n questions[`${ci}_${fi}`] = {\n type: \"noul\",\n instructions: [\n \"Judge this code review finding strictly against the diff. Answer yes only if ALL hold; if unsure, answer no.\",\n \"1. The diff itself shows the code the finding describes, and the claim about it is factually correct.\",\n \"2. It is a concrete problem this change introduces or worsens \u2014 not speculation (\\\"might\\\", \\\"could\\\") about code not shown, and not a style preference.\",\n \"3. The claimed severity fits the actual impact.\",\n ...(memory ? [\"4. Reviewer memory does not show this kind of finding being rejected.\"] : []),\n ...(focus\n ? [`The human reviewer asked to focus on: ${focus}. If this finding is about that focus and the diff shows the code it points at (e.g. the call site or injection), do not reject it under rule 2 only because confirming it needs code outside the diff.`]\n : []),\n `Category: ${c.category}`,\n `Severity claimed: ${f.severity}`,\n `File: ${f.file ?? \"(unspecified)\"}${f.line ? `:${f.line}` : \"\"}${lineOutsideDiff ? \" (this line is NOT part of the diff)\" : \"\"}`,\n `Issue: ${f.issue}`,\n ...(f.suggestion ? [`Suggestion: ${f.suggestion}`] : []),\n ].join(\"\\n\"),\n };\n });\n });\n\n let response: JevResponse;\n try {\n const res = await fetch(ENDPOINT, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", authorization: `Bearer ${env.TYPESAFE_API_KEY}` },\n body: JSON.stringify({ model: env.JEV_MODEL ?? DEFAULT_MODEL, state: memory ? `Reviewer memory (past human feedback on findings \u2014 weight heavily):\\n${memory}\\n\\n--- DIFF ---\\n${diffText}` : diffText, questions }),\n });\n if (!res.ok) throw new Error(`Jev returned ${res.status}: ${await res.text()}`);\n response = (await res.json()) as JevResponse;\n if (!response?.answers || typeof response.answers !== \"object\") throw new Error(\"Jev response has no answers\");\n } catch (err) {\n console.error(`[yolont] Jev noise filter failed, keeping findings unfiltered: ${(err as Error).message}`);\n return grounded;\n }\n\n // A garbage threshold becomes NaN, and `x >= NaN` would silently drop every finding.\n const parsed = Number(env.JEV_NOISE_THRESHOLD || NaN);\n const threshold = parsed >= 0 && parsed <= 1 ? parsed : DEFAULT_NOISE_THRESHOLD;\n\n return grounded.map((c, ci) => ({\n ...c,\n findings: c.findings.filter((_, fi) => {\n // Missing/malformed answer for this key \u2192 keep the finding (fail open per-finding).\n const noul = response.answers[`${ci}_${fi}`]?.noul;\n return typeof noul !== \"number\" || !Number.isFinite(noul) || noul >= threshold;\n }),\n }));\n}\n\n/** The finding's path as the diff spells it (LLMs sometimes keep the a/ b/ ./ prefix), or null if not in the diff. */\nfunction diffPath(file: string, diffFiles: Set<string>): string | null {\n if (diffFiles.has(file)) return file;\n const stripped = file.replace(/^(\\.\\/|[ab]\\/)/, \"\");\n return diffFiles.has(stripped) ? stripped : null;\n}\n", "import { AnthropicProvider } from \"./anthropicProvider.js\";\nimport { OllamaProvider } from \"./ollamaProvider.js\";\nimport { OpenCodeZenProvider } from \"./opencodeZenProvider.js\";\nimport type { LLMProvider, ReviewInput } from \"./provider.js\";\nimport { sanitizeReviewResponse } from \"./sanitizeTone.js\";\nimport type { LlmReviewResponse } from \"./schema.js\";\n\nexport * from \"./provider.js\";\nexport * from \"./schema.js\";\nexport { sanitizeReviewText, sanitizeReviewResponse } from \"./sanitizeTone.js\";\nexport { filterNoiseWithJev, jevEnabled, type JevEnv } from \"./jevValidate.js\";\n\nexport interface LlmEnv {\n ANTHROPIC_API_KEY?: string;\n ANTHROPIC_MODEL?: string;\n OPENCODE_ZEN_API_KEY?: string;\n OPENCODE_ZEN_MODEL?: string;\n OPENCODE_ZEN_BASE_URL?: string;\n OPENCODE_ZEN_GO_API_KEY?: string;\n OPENCODE_ZEN_GO_MODEL?: string;\n OPENCODE_ZEN_GO_BASE_URL?: string;\n OMNI_API_KEY?: string;\n OMNI_MODEL?: string;\n OMNI_BASE_URL?: string;\n OLLAMA_URL?: string;\n OLLAMA_MODEL?: string;\n}\n\n// Free tier rotates (see https://opencode.ai/zen/v1/models) \u2014 override with\n// OPENCODE_ZEN_MODEL if this one has been retired.\nconst DEFAULT_OPENCODE_ZEN_FREE_MODEL = \"deepseek-v4-flash-free\";\nconst DEFAULT_OPENCODE_ZEN_GO_BASE_URL = \"https://opencode.ai/zen/go/v1\";\n\n/**\n * Claude API is the default (per team decision). OpenCode Zen is the free-tier\n * cloud fallback, OpenCode Zen Go is a second cloud fallback tier (separate\n * gateway/key). Omni is a paid OpenAI-compatible gateway (same wire protocol\n * as OpenCode Zen, just a different host/key), used if configured and none\n * of the above is set. Ollama is fully offline, used only if explicitly\n * configured and none of the above is set.\n */\nexport function createLlmProvider(env: LlmEnv): LLMProvider {\n return withToneSanitizer(createRawLlmProvider(env));\n}\n\n/** A saved LLM profile (see local/config). openai-compatible covers OpenCode Zen, OpenRouter, OpenAI, any /v1 gateway. */\nexport interface LlmProfileSpec {\n provider: \"anthropic\" | \"openai-compatible\" | \"ollama\";\n model: string;\n baseUrl?: string;\n}\n\nexport function createProviderFromProfile(profile: LlmProfileSpec, apiKey: string | undefined): LLMProvider {\n if (profile.provider === \"ollama\") return withToneSanitizer(new OllamaProvider({ baseUrl: profile.baseUrl ?? \"http://localhost:11434\", model: profile.model }));\n if (!apiKey) throw new Error(`No API key for this ${profile.provider} profile.`);\n if (profile.provider === \"anthropic\") return withToneSanitizer(new AnthropicProvider({ apiKey, model: profile.model }));\n if (!profile.baseUrl) throw new Error(\"An openai-compatible profile needs a base URL (the gateway's /v1 URL).\");\n return withToneSanitizer(new OpenCodeZenProvider({ apiKey, model: profile.model, baseUrl: profile.baseUrl }));\n}\n\nfunction createRawLlmProvider(env: LlmEnv): LLMProvider {\n if (env.ANTHROPIC_API_KEY) {\n return new AnthropicProvider({ apiKey: env.ANTHROPIC_API_KEY, model: env.ANTHROPIC_MODEL });\n }\n if (env.OPENCODE_ZEN_API_KEY) {\n return new OpenCodeZenProvider({\n apiKey: env.OPENCODE_ZEN_API_KEY,\n model: env.OPENCODE_ZEN_MODEL ?? DEFAULT_OPENCODE_ZEN_FREE_MODEL,\n baseUrl: env.OPENCODE_ZEN_BASE_URL,\n });\n }\n if (env.OPENCODE_ZEN_GO_API_KEY) {\n return new OpenCodeZenProvider({\n apiKey: env.OPENCODE_ZEN_GO_API_KEY,\n model: env.OPENCODE_ZEN_GO_MODEL ?? DEFAULT_OPENCODE_ZEN_FREE_MODEL,\n baseUrl: env.OPENCODE_ZEN_GO_BASE_URL ?? DEFAULT_OPENCODE_ZEN_GO_BASE_URL,\n useSession: true,\n });\n }\n if (env.OMNI_API_KEY) {\n // No built-in default host: a key alone must not silently send code to someone's gateway.\n if (!env.OMNI_BASE_URL) throw new Error(\"OMNI_API_KEY is set but OMNI_BASE_URL is not \u2014 set the gateway's /v1 URL.\");\n return new OpenCodeZenProvider({\n apiKey: env.OMNI_API_KEY,\n model: env.OMNI_MODEL ?? \"google/gemini-3.7-flash\",\n baseUrl: env.OMNI_BASE_URL,\n });\n }\n if (env.OLLAMA_URL) {\n return new OllamaProvider({ baseUrl: env.OLLAMA_URL, model: env.OLLAMA_MODEL ?? \"qwen2.5-coder\" });\n }\n throw new Error(\n \"No LLM provider configured: set ANTHROPIC_API_KEY, OPENCODE_ZEN_API_KEY, OPENCODE_ZEN_GO_API_KEY, OMNI_API_KEY, or OLLAMA_URL\",\n );\n}\n\n/**\n * Every provider's raw prose tends to read \"rich and heavy\" (LLM hedging/filler) rather\n * than like a teammate's comment. Wrapping here \u2014 instead of inside each provider \u2014 means\n * every call site (CI's src/index.ts and the local review TUI) gets plain-tone output for\n * free, with no per-provider duplication.\n */\nfunction withToneSanitizer(provider: LLMProvider): LLMProvider {\n return {\n review: async (input: ReviewInput): Promise<LlmReviewResponse> => sanitizeReviewResponse(await provider.review(input)),\n // Unsanitized: tone cleanup is for review prose, not generated files.\n complete: (prompt) => provider.complete(prompt),\n };\n}\n", "import { readFileSync } from \"node:fs\";\nimport yaml from \"js-yaml\";\nimport { RubricSchema, type Rubric } from \"./schema.js\";\n\nexport class RubricError extends Error {}\n\nexport function loadRubric(path: string): Rubric {\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch (err) {\n throw new RubricError(`Could not read rubric file at '${path}': ${(err as Error).message}`);\n }\n\n let parsed: unknown;\n try {\n parsed = yaml.load(raw);\n } catch (err) {\n throw new RubricError(`Rubric file at '${path}' is not valid YAML: ${(err as Error).message}`);\n }\n\n const result = RubricSchema.safeParse(parsed);\n if (!result.success) {\n const messages = result.error.issues.map((issue) => `- ${issue.path.join(\".\")}: ${issue.message}`);\n throw new RubricError(`Rubric file at '${path}' is invalid:\\n${messages.join(\"\\n\")}`);\n }\n\n return result.data;\n}\n", "import { scoreFromFindings } from \"./engine.js\";\nimport type { Category } from \"../rubric/schema.js\";\nimport type { CategoryResult, Finding } from \"./types.js\";\n\nexport const DEFAULT_CATEGORY_DESCRIPTIONS: Record<string, string> = {\n conventions: \"Naming, structure, and style conventions. Flag deviations with the specific rule violated.\",\n maintainability: \"Readability, complexity, duplication, and architectural drift.\",\n security: \"Injection risks, unsafe deserialization, missing auth checks, and other OWASP-style issues.\",\n};\n\nexport type LlmOutcome =\n | { status: \"skipped\"; reason: string }\n | { status: \"error\"; reason: string }\n | { status: \"ok\"; categories: Map<string, { findings: Finding[]; summary: string }> };\n\nexport type DetPartialResult = { score: number; available: boolean; note?: string };\n\n/**\n * Combines a category's deterministic and/or LLM components into the final per-category\n * result the scoring engine weights. Shared by the CI entrypoint (src/index.ts) and the\n * local-only tooling (local/mining/backfill.ts, local/review/interactiveReview.ts) \u2014 this\n * used to live only in src/index.ts's private scope, which made it unreusable since\n * index.ts self-executes `main()` and calls `process.exit` on import.\n */\nexport function resolveCategory(\n category: Category,\n detResults: Map<string, DetPartialResult>,\n llmOutcome: LlmOutcome,\n severityPenalties: { minor: number; major: number; critical: number },\n volumeFactor = 1,\n): CategoryResult {\n if (category.type === \"deterministic\") {\n const det = detResults.get(category.name);\n return {\n name: category.name,\n weight: category.weight,\n available: det?.available ?? false,\n score: det?.score ?? 50,\n findings: [],\n note: det?.note,\n };\n }\n\n const llmComponent = resolveLlmComponent(category.name, llmOutcome, severityPenalties, volumeFactor);\n\n if (category.type === \"llm\") {\n return {\n name: category.name,\n weight: category.weight,\n available: llmComponent.available,\n score: llmComponent.score,\n findings: llmComponent.findings,\n note: llmComponent.note,\n };\n }\n\n // hybrid: blend deterministic + LLM components\n const det = detResults.get(category.name);\n if (!det) {\n return {\n name: category.name,\n weight: category.weight,\n available: llmComponent.available,\n score: llmComponent.score,\n findings: llmComponent.findings,\n note: `${llmComponent.note ?? \"\"} (no deterministic source configured)`.trim(),\n };\n }\n\n if (!det.available) {\n return {\n name: category.name,\n weight: category.weight,\n available: llmComponent.available,\n score: llmComponent.score,\n findings: llmComponent.findings,\n note: `${det.note ?? \"\"} \u2014 falling back to LLM-only score.`,\n };\n }\n\n if (!llmComponent.available) {\n return {\n name: category.name,\n weight: category.weight,\n available: det.available,\n score: det.score,\n findings: [],\n note: `${det.note ?? \"\"} (${llmComponent.note ?? \"LLM component unavailable\"})`,\n };\n }\n\n return {\n name: category.name,\n weight: category.weight,\n available: true,\n score: Math.round((det.score + llmComponent.score) / 2),\n findings: llmComponent.findings,\n note: [det.note, llmComponent.note].filter(Boolean).join(\" \"),\n };\n}\n\nfunction resolveLlmComponent(\n categoryName: string,\n llmOutcome: LlmOutcome,\n severityPenalties: { minor: number; major: number; critical: number },\n volumeFactor: number,\n): { available: boolean; score: number; findings: Finding[]; note?: string } {\n if (llmOutcome.status === \"skipped\") {\n return { available: false, score: 50, findings: [], note: `LLM skipped: ${llmOutcome.reason}` };\n }\n if (llmOutcome.status === \"error\") {\n return { available: true, score: 0, findings: [], note: `LLM parse error: ${llmOutcome.reason}` };\n }\n const found = llmOutcome.categories.get(categoryName);\n if (!found) {\n return { available: true, score: 0, findings: [], note: \"LLM did not return this category\" };\n }\n return {\n available: true,\n score: scoreFromFindings(found.findings, severityPenalties, volumeFactor),\n findings: found.findings,\n note: found.findings.length > 0 ? `${found.summary} (penalties \u00D7${volumeFactor.toFixed(2)} for MR size)` : found.summary,\n };\n}\n", "import { readFileSync } from \"node:fs\";\nimport yaml from \"js-yaml\";\nimport { z } from \"zod\";\nimport type { ZoneVerdict } from \"../llm/schema.js\";\n\n/**\n * Zones: parts of a project rated by how costly a mistake there is \u2014\n * red = runs on every start/request/render or is hard to undo, green = rarely runs. Matching changed files to\n * zones is done here in code; the LLM only gives a verdict on the zones that matched.\n */\n\nexport const ZoneLevelSchema = z.enum([\"red\", \"amber\", \"green\"]);\n\nexport const ZoneSchema = z.object({\n id: z.string().regex(/^[a-z0-9][a-z0-9-]*$/, \"use lowercase-kebab-case\"),\n level: ZoneLevelSchema,\n paths: z.array(z.string().min(1)).min(1),\n why: z.string(),\n watch_for: z.array(z.string()).default([]),\n budget: z.string().optional(),\n});\n\nexport const ZonesFileSchema = z.object({\n zones: z.array(ZoneSchema).superRefine((zones, ctx) => {\n const seen = new Set<string>();\n zones.forEach((zone, i) => {\n if (seen.has(zone.id)) ctx.addIssue({ code: z.ZodIssueCode.custom, path: [i, \"id\"], message: `duplicate zone id '${zone.id}'` });\n seen.add(zone.id);\n });\n }),\n});\n\nexport type ZoneLevel = z.infer<typeof ZoneLevelSchema>;\nexport type Zone = z.infer<typeof ZoneSchema>;\n\nexport interface ZoneHit {\n zone: Zone;\n files: string[];\n /** Subset of `files` that matched only because a red zone imports them (zones graph), not by path. */\n viaImport?: string[];\n /** Past reviewer votes on this zone's verdicts in the same project (local memory only). */\n feedback?: string[];\n}\n\n/** What a review carries about zones \u2014 every zone of the project (for the map) plus what this diff touched. */\nexport interface ZoneReport {\n zones: Zone[];\n hits: ZoneHit[];\n verdicts: ZoneVerdict[];\n}\n\nexport class ZonesError extends Error {}\n\nconst LEVEL_RANK: Record<ZoneLevel, number> = { red: 0, amber: 1, green: 2 };\n\n/** Missing file = zones are simply off for this project (null), not an error. */\nexport function loadZones(path: string): Zone[] | null {\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw new ZonesError(`Could not read zones file at '${path}': ${(err as Error).message}`);\n }\n return parseZones(raw, `Zones file at '${path}'`);\n}\n\n/** Validates zones YAML from a string (editor output, generated drafts). Throws ZonesError. */\nexport function parseZones(raw: string, label = \"Zones file\"): Zone[] {\n let parsed: unknown;\n try {\n parsed = yaml.load(raw);\n } catch (err) {\n throw new ZonesError(`${label} is not valid YAML: ${(err as Error).message}`);\n }\n\n const result = ZonesFileSchema.safeParse(parsed);\n if (!result.success) {\n const messages = result.error.issues.map((issue) => `- ${issue.path.join(\".\")}: ${issue.message}`);\n throw new ZonesError(`${label} is invalid:\\n${messages.join(\"\\n\")}`);\n }\n return result.data.zones;\n}\n\n/** Minimal glob: `**` spans directories, `*` and `?` stay within one path segment. No braces/classes \u2014 list several paths instead. */\nexport function globToRegExp(glob: string): RegExp {\n let re = \"\";\n for (let i = 0; i < glob.length; i++) {\n const ch = glob[i]!;\n if (ch === \"*\" && glob[i + 1] === \"*\") {\n const slashAfter = glob[i + 2] === \"/\";\n re += slashAfter ? \"(?:.*/)?\" : \".*\";\n i += slashAfter ? 2 : 1;\n } else if (ch === \"*\") {\n re += \"[^/]*\";\n } else if (ch === \"?\") {\n re += \"[^/]\";\n } else {\n re += ch.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\");\n }\n }\n return new RegExp(`^${re}$`);\n}\n\n/**\n * Every zone a file falls into is recorded (overlaps allowed); hits are sorted most severe\n * first. With a zones graph, a file a zone transitively imports counts as in that zone too\n * \u2014 catches a \"green\" file that a red one pulls into first load.\n */\nexport function matchZones(zones: Zone[], files: string[], graph?: ZoneGraph | null): ZoneHit[] {\n const hits: ZoneHit[] = [];\n for (const zone of zones) {\n const patterns = zone.paths.map(globToRegExp);\n const direct = files.filter((f) => patterns.some((re) => re.test(f)));\n const reachable = new Set(graph?.reachable[zone.id] ?? []);\n const viaImport = files.filter((f) => reachable.has(f) && !direct.includes(f));\n if (direct.length + viaImport.length === 0) continue;\n hits.push({ zone, files: [...direct, ...viaImport], ...(viaImport.length > 0 && { viaImport }) });\n }\n return hits.sort((a, b) => LEVEL_RANK[a.zone.level] - LEVEL_RANK[b.zone.level]);\n}\n\n/** Offline-generated import reachability (local `yolont zones graph`): zone id \u2192 repo files its files transitively import. */\nexport const ZoneGraphSchema = z.object({\n generated_at: z.string(),\n sha: z.string().nullable(),\n reachable: z.record(z.array(z.string())),\n});\nexport type ZoneGraph = z.infer<typeof ZoneGraphSchema>;\n\n/** Missing = path-only matching. Invalid throws ZonesError, which callers already treat as \"log, continue without zones\". */\nexport function loadZoneGraph(path: string): ZoneGraph | null {\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw new ZonesError(`Could not read zones graph at '${path}': ${(err as Error).message}`);\n }\n const result = ZoneGraphSchema.safeParse(JSON.parse(raw));\n if (!result.success) throw new ZonesError(`Zones graph at '${path}' is invalid: ${result.error.message}`);\n return result.data;\n}\n\n// Device variants (e.g. Foo.mobile.tsx / Foo.desktop.tsx / Foo.ssr.tsx) are one module\n// at build time; TS resolution only ever picks one suffix, so the walk treats siblings as one.\nconst VARIANT_SUFFIX = /\\.(mobile|desktop|ssr)(?=\\.[cm]?[jt]sx?$)/;\n\n/**\n * Pure part of graph generation: BFS from each red zone's own files through the import\n * graph (madge `.obj()` shape: file \u2192 files it imports), minus the zone's own files.\n * Only red zones \u2014 \"imported by first-load code\" is what the graph is for; doing it for\n * amber would paint every shared util amber and drown the signal.\n */\nexport function computeReachable(zones: Zone[], repoFiles: string[], imports: Record<string, string[]>): Record<string, string[]> {\n const siblings = new Map<string, string[]>();\n for (const f of repoFiles) {\n const key = f.replace(VARIANT_SUFFIX, \"\");\n siblings.set(key, [...(siblings.get(key) ?? []), f]);\n }\n const variantsOf = (f: string) => siblings.get(f.replace(VARIANT_SUFFIX, \"\")) ?? [f];\n\n const reachable: Record<string, string[]> = {};\n for (const hit of matchZones(zones.filter((z) => z.level === \"red\"), repoFiles)) {\n const own = new Set(hit.files);\n const seen = new Set<string>(hit.files.flatMap(variantsOf));\n const queue = [...seen];\n while (queue.length > 0) {\n for (const dep of imports[queue.pop()!] ?? []) {\n for (const v of variantsOf(dep)) {\n if (seen.has(v)) continue;\n seen.add(v);\n queue.push(v);\n }\n }\n }\n reachable[hit.zone.id] = [...seen].filter((f) => !own.has(f)).sort();\n }\n return reachable;\n}\n\n/** Drops verdicts for zones that weren't in the prompt \u2014 the schema enum is a hint, not a guarantee. */\nexport function keepKnownVerdicts(verdicts: ZoneVerdict[] | undefined, hits: ZoneHit[]): ZoneVerdict[] {\n const ids = new Set(hits.map((h) => h.zone.id));\n return (verdicts ?? []).filter((v) => ids.has(v.zone_id));\n}\n\nconst LEVEL_STYLE: Record<ZoneLevel, string> = {\n red: \"fill:#fde2e2,stroke:#c62828,color:#000\",\n amber: \"fill:#fff3cd,stroke:#b8860b,color:#000\",\n green: \"fill:#e3f5e1,stroke:#2e7d32,color:#000\",\n};\n\n/**\n * Mermaid map of the project's zones, grouped by level. With `hits`, touched zones are\n * bold with their changed-file count and untouched ones are faded \u2014 the per-review view.\n * Without, it's the plain project map. GitLab renders ```mermaid blocks natively.\n */\nexport function renderZonesMermaid(zones: Zone[], hits?: ZoneHit[]): string {\n const touched = new Map(hits?.map((h) => [h.zone.id, h.files.length]));\n const lines = [\"```mermaid\", \"flowchart LR\"];\n for (const level of ZoneLevelSchema.options) {\n const inLevel = zones.filter((z) => z.level === level);\n if (inLevel.length === 0) continue;\n lines.push(` subgraph lvl_${level}[\"${level.toUpperCase()}\"]`);\n for (const zone of inLevel) {\n const count = touched.get(zone.id);\n const label = count ? `${zone.id} \u00B7 ${count} file(s)` : zone.id;\n lines.push(` ${nodeId(zone.id)}[\"${label}\"]:::${level}${hits && !count ? \"Faded\" : \"\"}`);\n }\n lines.push(\" end\");\n }\n for (const level of ZoneLevelSchema.options) {\n lines.push(` classDef ${level} ${LEVEL_STYLE[level]},stroke-width:3px`);\n lines.push(` classDef ${level}Faded ${LEVEL_STYLE[level]},opacity:0.35`);\n }\n lines.push(\"```\");\n return lines.join(\"\\n\");\n}\n\n// Mermaid node ids can't contain '-' reliably in every renderer version.\nfunction nodeId(zoneId: string): string {\n return `z_${zoneId.replace(/-/g, \"_\")}`;\n}\n", "import { execFileSync } from \"node:child_process\";\nimport { existsSync, readdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { BUILTIN_CONVENTIONS_DIR, DEFAULT_CONVENTIONS_PATH, DEFAULT_RUBRIC_PATH } from \"../paths.js\";\nimport { projectSettingsDir } from \"../sync/source.js\";\n\n/** Built-in convention files to pick from when a project has none of its own. */\nexport function listConventionFiles(): string[] {\n return readdirSync(BUILTIN_CONVENTIONS_DIR)\n .filter((f) => f.endsWith(\".md\"))\n .sort()\n .map((f) => join(BUILTIN_CONVENTIONS_DIR, f));\n}\n\n/** \"group/app\" -> \"group-app\" \u2014 the pre-Yolont flat file naming (legacy migration only). */\nexport function slugifyProjectPath(pathWithNamespace: string): string {\n return pathWithNamespace\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/(^-|-$)/g, \"\");\n}\n\n/** git@host:g/p.git | https://host/g/p(.git) -> \"g/p\" (lowercase), or null. */\nexport function remoteProjectPath(remoteUrl: string): string | null {\n const m = remoteUrl.trim().match(/^(?:[a-z+]+:\\/\\/)?(?:[^@/]+@)?[^/:]+(?::\\d+)?[:/](.+?)(?:\\.git)?\\/?$/i);\n return m ? m[1]!.toLowerCase() : null;\n}\n\nfunction git(args: string[]): string | null {\n try {\n return execFileSync(\"git\", args, { encoding: \"utf8\", stdio: [\"ignore\", \"pipe\", \"ignore\"] }).trim();\n } catch {\n return null;\n }\n}\n\n/** `<checkout>/.yolont` when cwd is a checkout of this very project (origin matches), else null.\n * The match check matters: reviewing project A from inside a checkout of B must not use B's config. */\nexport function repoYolontDir(pathWithNamespace: string, cwd = process.cwd()): string | null {\n const top = git([\"-C\", cwd, \"rev-parse\", \"--show-toplevel\"]);\n const origin = top && git([\"-C\", top, \"remote\", \"get-url\", \"origin\"]);\n if (!top || !origin || remoteProjectPath(origin) !== pathWithNamespace.toLowerCase()) return null;\n // .ethos/ = the folder's name before the rename; still read.\n return [join(top, \".yolont\"), join(top, \".ethos\")].find((d) => existsSync(d)) ?? null;\n}\n\n/** cwd is a checkout of this project (origin matches) with `sha` checked out at HEAD. */\nexport function isCheckoutOf(pathWithNamespace: string, sha: string, cwd = process.cwd()): boolean {\n const origin = git([\"-C\", cwd, \"remote\", \"get-url\", \"origin\"]);\n return !!origin && remoteProjectPath(origin) === pathWithNamespace.toLowerCase() && git([\"-C\", cwd, \"rev-parse\", \"HEAD\"]) === sha;\n}\n\nexport interface ProjectFiles {\n /** Where this project's files are written (user config dir). */\n dir: string;\n conventions: string | null;\n zones: string | null;\n zonesGraph: string | null;\n rubric: string;\n}\n\n/**\n * Per-project config, first hit wins: the project's own committed `.yolont/` (team-reviewed,\n * also what CI reads) > its team data repo when the project is shared there, else\n * the user's ~/.config/yolont/projects/<host>/<path>/ > built-in rubric.\n * conventions/zones are null when nothing exists \u2014 callers decide the fallback.\n */\nexport function resolveProjectFiles(host: string, pathWithNamespace: string, cwd?: string): ProjectFiles {\n const dir = projectSettingsDir(host, pathWithNamespace);\n const dirs = [repoYolontDir(pathWithNamespace, cwd), dir].filter((d): d is string => !!d);\n const find = (name: string) => dirs.map((d) => join(d, name)).find((p) => existsSync(p)) ?? null;\n return {\n dir,\n conventions: find(\"conventions.md\"),\n zones: find(\"zones.yaml\"),\n zonesGraph: find(\"zones.graph.json\"),\n rubric: find(\"rubric.yml\") ?? DEFAULT_RUBRIC_PATH,\n };\n}\n\nexport { DEFAULT_CONVENTIONS_PATH };\n", "import { execFile } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { userInfo } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport yaml from \"js-yaml\";\nimport { z } from \"zod\";\nimport { scanDiffForSecrets } from \"../../src/checks/secrets.js\";\nimport { parseGitAddress } from \"../../src/forge/index.js\";\nimport { loadConfig, saveConfig, type YolontConfig, type SourceConfig } from \"../config/config.js\";\nimport { DATA_DIR, bareHost, userProjectDir } from \"../paths.js\";\nimport { forgeFor } from \"../forge.js\";\nimport { SyncRecord, exportRecords, importRecords, projectKey, sourceProjectDir, type ImportResult, type ProjectKey, type SyncScope } from \"./records.js\";\n\n/**\n * Memory repos (\"sources\"), git side. Yolont only ever runs the system `git`,\n * so the user's own credentials are used and Yolont never sees a token for these repos.\n */\n\nexport const MANIFEST = \"yolont-source.yaml\";\n/** A memory repo started before the rename keeps its ethos-source.yaml (read and updated in place). */\nconst manifestFile = (dir: string) => (!existsSync(join(dir, MANIFEST)) && existsSync(join(dir, \"ethos-source.yaml\")) ? join(dir, \"ethos-source.yaml\") : join(dir, MANIFEST));\n/** Shared per-project files a source can carry (setup.yaml stays personal, in the user dir). */\nexport const SHARED_FILES = [\"conventions.md\", \"zones.yaml\", \"zones.graph.json\", \"rubric.yml\"] as const;\n\n// review (default on): members push to their own branch and open an MR; only `main` is read.\nconst Manifest = z.object({ projects: z.array(z.string()).default([]), review: z.boolean().default(true) });\n\n/** A repo address for display: drops any `user:token@` from an https URL. */\nexport const displayUrl = (url: string) => url.replace(/^([a-z+]+:\\/\\/)[^@/]*@/i, \"$1\");\n\nexport const sourceDir = (name: string) => join(DATA_DIR, \"sources\", name);\n\nexport class GitError extends Error {}\n\n/** git that never prompts: no credential questions in the middle of the TUI, no hang. */\nexport function git(dir: string, args: string[], timeoutMs = 60_000): Promise<string> {\n // GIT_OPTIONAL_LOCKS=0: read-only commands (the panel's 30 s `git status`) don't take index.lock,\n // so they can't make a running sync fail.\n const env = { ...process.env, GIT_TERMINAL_PROMPT: \"0\", GIT_OPTIONAL_LOCKS: \"0\", GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND ?? \"ssh -o BatchMode=yes\" };\n return new Promise((resolve, reject) => {\n execFile(\"git\", [\"-C\", dir, ...args], { env, timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024 }, (err, stdout, stderr) => {\n if (!err) return resolve(stdout);\n const why = (stderr || err.message).trim().split(\"\\n\").filter(Boolean).at(-1) ?? \"git failed\";\n reject(new GitError((err as { killed?: boolean }).killed ? `timed out (git ${args[0]})` : why));\n });\n });\n}\n\nexport function readManifest(dir: string): Set<ProjectKey> {\n const file = manifestFile(dir);\n if (!existsSync(file)) return new Set();\n const parsed = Manifest.safeParse(yaml.load(readFileSync(file, \"utf8\")) ?? {});\n return new Set(parsed.success ? parsed.data.projects.map((p) => p.toLowerCase()) : []);\n}\n\n/** Review mode: changes go through a merge request (the repo's `review:`; on unless it says false). */\nexport function reviewMode(dir: string): boolean {\n const file = manifestFile(dir);\n if (!existsSync(file)) return true;\n const parsed = Manifest.safeParse(yaml.load(readFileSync(file, \"utf8\")) ?? {});\n return parsed.success ? parsed.data.review : true;\n}\n\nfunction writeManifest(dir: string, projects: Set<ProjectKey>): void {\n const file = manifestFile(dir);\n const current = existsSync(file) ? ((yaml.load(readFileSync(file, \"utf8\")) ?? {}) as Record<string, unknown>) : { review: true };\n writeFileSync(file, `# Yolont memory repo: the projects using it. review: true = members send changes as merge requests.\\n${yaml.dump({ ...current, projects: [...projects].sort() })}`);\n}\n\n/** The git host a memory repo lives on: `host` in config (for a local path), else from its address. */\nexport function sourceHost(source: Pick<SourceConfig, \"url\" | \"host\">): string | null {\n if (source.host) return bareHost(source.host);\n const a = parseGitAddress(source.url);\n return a ? bareHost(a.host) : null;\n}\n\n/** The memory repo's own project path on its host (for opening merge requests), if its address has one. */\nconst sourceRepoPath = (source: SourceConfig) => parseGitAddress(source.url)?.projectPath ?? null;\n\n/** Your member id, created once: a readable name plus a random suffix so two \"alex\"es don't collide. */\nexport function ensureMember(config: YolontConfig, name = userInfo().username): YolontConfig {\n if (config.member) return config;\n const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/(^-|-$)/g, \"\") || \"member\";\n return { ...config, member: { id: `${slug}-${randomBytes(2).toString(\"hex\")}`, name } };\n}\n\n/**\n * Clones a memory repo (or initialises an empty one) and saves it in config. `host`: only for an\n * address with no host in it (a local path); otherwise it must match the address.\n */\nexport async function addSource(name: string, url: string, memberName?: string, host?: string): Promise<SourceConfig> {\n let config = loadConfig();\n const fromUrl = parseGitAddress(url)?.host;\n // An ssh address may use a host alias from ~/.ssh/config (git@github-personal:me/x.git): there\n // --host names the real host. An https address names its host itself.\n const ssh = !/^https?:\\/\\//i.test(url);\n if (host && fromUrl && bareHost(host) !== bareHost(fromUrl) && !ssh) throw new Error(`${displayUrl(url)} is on ${fromUrl}, not ${host}.`);\n if (!host && !fromUrl) throw new Error(\"Can't tell the git host from that address; pass --host <git host> (only projects on that host can use it).\");\n if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) throw new Error(\"Source name: lowercase letters, digits and '-' only.\");\n if ((config.sources ?? []).some((s) => s.name === name)) throw new Error(`A source named '${name}' already exists.`);\n const dir = sourceDir(name);\n if (existsSync(dir)) throw new Error(`${dir} already exists; remove it or pick another name.`);\n mkdirSync(join(DATA_DIR, \"sources\"), { recursive: true });\n await git(join(DATA_DIR, \"sources\"), [\"clone\", \"--quiet\", url, name], 120_000);\n config = ensureMember(config, memberName);\n saveConfig(config); // the commit below is signed with the member name\n if (!existsSync(manifestFile(dir))) {\n // An empty repo: the first commit goes straight to its main branch (there's nothing to review against).\n writeManifest(dir, new Set());\n await commit(dir, \"yolont: start memory repo\");\n await git(dir, [\"push\", \"--quiet\", \"-u\", \"origin\", \"HEAD\"]);\n }\n const source: SourceConfig = { name, url, projects: [], autoSync: true, ...(host && (!fromUrl || bareHost(host) !== bareHost(fromUrl)) ? { host: bareHost(host) } : {}) };\n saveConfig({ ...loadConfig(), sources: [...(loadConfig().sources ?? []), source] });\n return source;\n}\n\nasync function commit(dir: string, message: string): Promise<boolean> {\n await git(dir, [\"add\", \"-A\"]);\n if (!(await git(dir, [\"status\", \"--porcelain\"])).trim()) return false;\n // Identity only for this commit, so it works on machines with no git user configured.\n const name = loadConfig().member?.name ?? \"yolont\";\n await git(dir, [\"-c\", `user.name=${name}`, \"-c\", \"user.email=yolont@localhost\", \"commit\", \"--quiet\", \"-m\", message]);\n return true;\n}\n\n/** A source by name; without a name only when there's exactly one, so data never goes to a guessed repo. */\nexport function getSource(name?: string): SourceConfig {\n const sources = loadConfig().sources ?? [];\n if (!name && sources.length > 1) throw new Error(`Several memory repos (${sources.map((s) => s.name).join(\", \")}): pick one with --source <name>.`);\n const source = name ? sources.find((s) => s.name === name) : sources[0];\n if (!source) throw new Error(name ? `No source named '${name}'.` : \"No team data repo yet: run `yolont source add <name> <git-url>`.\");\n return source;\n}\n\n/** The memory repo you chose for a project (your config only; on the project's own host), if any. */\nexport function sourceFor(host: string, path: string): SourceConfig | undefined {\n const name = projectOwners()(projectKey(bareHost(host), path));\n return name ? getSource(name) : undefined;\n}\n\n/**\n * Which memory repo a project uses, for import, export, prompt memory and the panel (one rule for\n * all): only the one you chose for it, and only if it's on the project's git host. What a repo's\n * manifest lists never binds anything: memory repos switch, they never mix.\n */\nexport function projectOwners(sources: SourceConfig[] = loadConfig().sources ?? []): (key: ProjectKey) => string | null {\n return (key) => {\n const s = sources.find((r) => r.projects.some((p) => p.toLowerCase() === key));\n return s && sourceHost(s) === key.split(\"/\")[0] ? s.name : null;\n };\n}\n\n/** Owner of a DB project row (null host = pre-host legacy row: local). */\nexport function ownerOfProject(db: DatabaseSync, projectId: number, owner: (key: ProjectKey) => string | null): string | null {\n const p = db.prepare(`SELECT forge_host, path_with_namespace FROM projects WHERE id = ?`).get(projectId) as { forge_host: string | null; path_with_namespace: string } | undefined;\n return p?.forge_host ? owner(projectKey(bareHost(p.forge_host), p.path_with_namespace)) : null;\n}\n\n/**\n * The source an insight belongs to: where it was imported from; for your own, where its project\n * (or, for a host-wide one, every evidence MR's project) is owned. `false` = evidence spans sources.\n */\nexport function insightSource(\n db: DatabaseSync,\n i: { origin?: string | null; project_id: number | null; evidence_mr_ids_json: string },\n owner: (key: ProjectKey) => string | null,\n): string | null | false {\n if (i.origin) return i.origin;\n if (i.project_id != null) return ownerOfProject(db, i.project_id, owner);\n const mrProject = db.prepare(`SELECT project_id FROM merge_requests WHERE id = ?`);\n const ids = (JSON.parse(i.evidence_mr_ids_json) as number[]).map((id) => (mrProject.get(id) as { project_id: number } | undefined)?.project_id);\n const owners = new Set(ids.map((pid) => (pid == null ? null : ownerOfProject(db, pid, owner))));\n if (owners.size === 0) return null;\n return owners.size === 1 ? [...owners][0]! : false;\n}\n\n/** Where a project's conventions/zones/rubric live: its team data repo when shared, else the user dir. */\nexport function projectSettingsDir(host: string, path: string): string {\n const source = sourceFor(host, path);\n return source ? sourceProjectDir(sourceDir(source.name), projectKey(bareHost(host), path)) : userProjectDir(host, path);\n}\n\n/**\n * Stops using a project's memory repo: unbinds it and drops what was imported from that repo for\n * it (memory repos switch, they don't mix). Your own records stay; they're in the repo too.\n */\nexport function stopUsing(db: DatabaseSync, host: string, path: string): string | null {\n const key = projectKey(bareHost(host), path);\n const config = loadConfig();\n const source = (config.sources ?? []).find((s) => s.projects.some((p) => p.toLowerCase() === key));\n if (!source) return null;\n saveConfig({ ...config, sources: (config.sources ?? []).map((s) => (s.name === source.name ? { ...s, projects: s.projects.filter((p) => p.toLowerCase() !== key) } : s)) });\n // Re-import the projects still bound with prune: everything else from this repo goes.\n const after = getSource(source.name);\n if (loadConfig().member) importRecords(db, scopes(after).importScope, true);\n return source.name;\n}\n\n/**\n * Disconnects a memory repo on this machine only: its projects go back to your own memory, what\n * was imported from it is dropped, and its local clone is deleted. The repo itself (and what you\n * already sent to it) is untouched. `unsent` (from pendingToSend) is checked by the caller first.\n */\nexport function removeSource(db: DatabaseSync, name: string): void {\n const source = getSource(name);\n const config = loadConfig();\n saveConfig({ ...config, sources: (config.sources ?? []).filter((s) => s.name !== name) });\n // Nothing bound any more: an import with no projects + prune drops every row that came from it.\n if (config.member) importRecords(db, { dir: sourceDir(name), name, member: config.member.id, projects: new Set() }, true);\n db.prepare(`DELETE FROM sync_exported WHERE source = ?`).run(name);\n rmSync(sourceDir(source.name), { recursive: true, force: true });\n}\n\n/** Remembers that a project keeps your own memory only, so the wizard doesn't ask again. */\nexport function keepLocal(host: string, path: string, local = true): void {\n const key = projectKey(bareHost(host), path);\n const config = loadConfig();\n const list = new Set(config.localProjects ?? []);\n if (local) list.add(key);\n else list.delete(key);\n saveConfig({ ...config, localProjects: [...list].sort() });\n}\n\nexport const isKeptLocal = (host: string, path: string) => (loadConfig().localProjects ?? []).includes(projectKey(bareHost(host), path));\n\n/** Memory repos a project may use: the ones on its own git host. */\nexport const sourcesForHost = (host: string) => (loadConfig().sources ?? []).filter((s) => sourceHost(s) === bareHost(host));\n\n/** Starts sharing a project through a source. Your own files are copied in unless the team already has that file. */\nexport async function shareProject(sourceName: string, host: string, path: string): Promise<{ copied: string[]; kept: string[] }> {\n const config = loadConfig();\n const source = getSource(sourceName);\n const key = projectKey(bareHost(host), path);\n if (sourceHost(source) !== bareHost(host)) throw new Error(`'${source.name}' is on ${sourceHost(source) ?? \"an unknown host\"}; ${key} is on ${bareHost(host)}. A project only uses a memory repo on its own git host.`);\n const other = (config.sources ?? []).find((s) => s.name !== source.name && s.projects.includes(key));\n if (other) throw new Error(`${key} uses '${other.name}'. Switch it in the Team data menu (or \\`yolont source use\\`); a project uses one memory repo at a time.`);\n const dir = sourceDir(source.name);\n const manifest = readManifest(dir);\n manifest.add(key);\n writeManifest(dir, manifest);\n\n const copied: string[] = [];\n const kept: string[] = [];\n const target = sourceProjectDir(dir, key);\n for (const f of SHARED_FILES) {\n const mine = join(userProjectDir(host, path), f);\n if (!existsSync(mine)) continue;\n if (existsSync(join(target, f))) kept.push(f);\n else {\n mkdirSync(target, { recursive: true });\n copyFileSync(mine, join(target, f));\n copied.push(f);\n }\n }\n if (!source.projects.includes(key)) saveConfig({ ...config, sources: (config.sources ?? []).map((s) => (s.name === source.name ? { ...s, projects: [...s.projects, key] } : s)) });\n keepLocal(host, path, false);\n return { copied, kept };\n}\n\nfunction scopes(source: SourceConfig): { exportScope: SyncScope; importScope: SyncScope } {\n const member = loadConfig().member?.id;\n if (!member) throw new Error(\"No member id in config; re-add the memory repo.\");\n const dir = sourceDir(source.name);\n // Both directions: only the projects you chose this repo for (what its manifest lists binds nothing).\n const owner = projectOwners();\n const mine = new Set(source.projects.map((p) => p.toLowerCase()).filter((k) => owner(k) === source.name));\n return { exportScope: { dir, name: source.name, member, projects: mine }, importScope: { dir, name: source.name, member, projects: mine } };\n}\n\nexport interface SourceStatus {\n name: string;\n /** Team commits not pulled yet. */\n incoming: number;\n /** Your records and shared-file edits not sent yet, plus unpushed commits. */\n outgoing: number;\n /** Review mode: files you sent that aren't merged into main yet. */\n waiting: number;\n error?: string;\n}\n\n// ---- review mode: your own branch + a merge request; only main is read ----\n\nexport const memberBranch = (member: string) => `yolont/${member}`;\n\n/** The repo's main branch name, from the clone (no network). */\nasync function mainBranch(dir: string): Promise<string> {\n const head = await git(dir, [\"symbolic-ref\", \"--quiet\", \"--short\", \"refs/remotes/origin/HEAD\"]).catch(() => \"\");\n if (head.trim()) return head.trim().replace(/^origin\\//, \"\");\n for (const b of [\"main\", \"master\"]) if (await git(dir, [\"rev-parse\", \"--verify\", \"--quiet\", `refs/remotes/origin/${b}`]).then(() => true, () => false)) return b;\n return \"main\";\n}\n\n/**\n * Puts the clone where this mode works: review mode on your branch `yolont/<member>` (made from the\n * current HEAD, so nothing unsent is lost), always tracking main, so pulls rebase onto main.\n */\nasync function prepareBranch(dir: string, member: string): Promise<{ review: boolean; main: string; branch: string }> {\n const main = await mainBranch(dir);\n const review = reviewMode(dir);\n const branch = memberBranch(member);\n if (review && (await git(dir, [\"rev-parse\", \"--abbrev-ref\", \"HEAD\"])).trim() !== branch) {\n const exists = await git(dir, [\"rev-parse\", \"--verify\", \"--quiet\", `refs/heads/${branch}`]).then(() => true, () => false);\n await git(dir, [\"checkout\", \"--quiet\", ...(exists ? [branch] : [\"-b\", branch])]);\n }\n if (await git(dir, [\"rev-parse\", \"--verify\", \"--quiet\", `refs/remotes/origin/${main}`]).then(() => true, () => false)) {\n await git(dir, [\"branch\", \"--quiet\", `--set-upstream-to=origin/${main}`]);\n }\n return { review, main, branch };\n}\n\nconst count = async (dir: string, range: string) => Number((await git(dir, [\"rev-list\", \"--count\", range]).catch(() => \"0\")).trim()) || 0;\nconst remoteHas = (dir: string, branch: string) => git(dir, [\"rev-parse\", \"--verify\", \"--quiet\", `refs/remotes/origin/${branch}`]).then(() => true, () => false);\n\n/** Commits not on the remote yet: in review mode compared with your pushed branch. */\nasync function unpushed(dir: string, review: boolean, branch: string): Promise<number> {\n return review && (await remoteHas(dir, branch)) ? count(dir, `origin/${branch}..HEAD`) : count(dir, \"@{u}..HEAD\");\n}\n\n/** Files on your branch that main doesn't have yet (what your merge request carries). */\nasync function waitingFiles(dir: string): Promise<string[]> {\n return (await git(dir, [\"diff\", \"--name-only\", \"@{u}...HEAD\"]).catch(() => \"\")).split(\"\\n\").filter(Boolean);\n}\n\nexport interface ReviewRequest {\n branch: string;\n target: string;\n /** The merge request's page, or a link to open one; null when the host is unknown. */\n url: string | null;\n /** Why it wasn't opened for you (no token, unknown host type, \u2026). */\n note?: string;\n waiting: number;\n}\n\n/** What a merge request changes, for its description: what steers reviews first, in plain words. */\nasync function describeChanges(dir: string, files: string[], who: string): Promise<string> {\n const lines: string[] = [];\n let removed = 0;\n for (const rel of files) {\n if (!existsSync(join(dir, rel))) {\n removed++;\n continue;\n }\n if (!rel.includes(\"/records/\")) {\n lines.push(`- shared file: \\`${rel}\\``);\n continue;\n }\n try {\n const r = SyncRecord.parse(JSON.parse(readFileSync(join(dir, rel), \"utf8\")));\n const at = \"mr\" in r ? `${r.mr.project.path} !${r.mr.iid}` : r.project?.path ?? r.host;\n const clip = (t: string) => (t.length > 140 ? `${t.slice(0, 140)}\u2026` : t).replace(/\\s+/g, \" \");\n if (r.kind === \"insight\") lines.unshift(`- **memory** (${at}): ${clip(r.text)}`);\n else if (r.kind === \"correction\") lines.unshift(`- **correction** ${at} [${r.category ?? \"overall\"}] ${r.originalScore} \u2192 ${r.correctedScore}: ${clip(r.reason)}`);\n else if (r.kind === \"vote\") lines.push(`- vote ${r.vote} on \"${clip(r.finding.issue)}\" (${at})${r.note ? `: ${clip(r.note)}` : \"\"}`);\n else if (r.kind === \"tag\") lines.push(`- tag \\`${r.tag}\\` on \"${clip(r.finding.issue)}\" (${at})`);\n else lines.push(`- review ${at}: score ${r.finalScore}, ${r.findings.length} finding(s)`);\n } catch {\n lines.push(`- \\`${rel}\\``);\n }\n }\n if (removed) lines.push(`- removed ${removed} record(s)`);\n const shown = lines.slice(0, 60);\n if (lines.length > shown.length) shown.push(`- \u2026 and ${lines.length - shown.length} more`);\n return `Yolont memory update from **${who}**. Merging it makes these part of every member's reviews.\\n\\n${shown.join(\"\\n\")}\\n`;\n}\n\n/** Opens (or updates) the merge request with your saved token for the repo's host; else a link. */\nasync function requestReview(source: SourceConfig, branch: string, target: string, description: string): Promise<{ url: string | null; note?: string }> {\n const host = sourceHost(source);\n const path = sourceRepoPath(source);\n if (!host || !path) return { url: null, note: `Sent to branch ${branch}; open a merge request into ${target} on the repo's git host.` };\n const config = loadConfig();\n const type = config.forges.find((f) => f.host === host)?.type ?? (host === \"github.com\" ? \"github\" : \"gitlab\");\n const link =\n type === \"github\"\n ? `https://${host}/${path}/compare/${encodeURIComponent(target)}...${encodeURIComponent(branch)}?expand=1`\n : `https://${host}/${path}/-/merge_requests/new?merge_request%5Bsource_branch%5D=${encodeURIComponent(branch)}&merge_request%5Btarget_branch%5D=${encodeURIComponent(target)}`;\n try {\n const forge = forgeFor(host);\n const who = config.member?.name ?? branch;\n const r = await forge.openOrUpdateChangeRequest(path, { sourceBranch: branch, targetBranch: target, title: `Yolont memory: ${who}`, description });\n return { url: r.url };\n } catch (err) {\n return { url: link, note: `Open the merge request yourself (${(err as Error).message})` };\n }\n}\n\n/** Test seam: how a merge request is opened. */\nexport type RequestReview = typeof requestReview;\n\n/**\n * One git operation per repo at a time in this process: the panel's start sync, its button and an\n * after-review sync can overlap, and two git commands in one clone fight over its lock files.\n */\nconst queues = new Map<string, Promise<unknown>>();\nfunction queued<T>(name: string, fn: () => Promise<T>): Promise<T> {\n const next = (queues.get(name) ?? Promise.resolve()).catch(() => {}).then(fn);\n queues.set(name, next);\n return next;\n}\n\n/** Quick check for the wizard: fetch (short timeout) and count both directions. Never throws. */\nexport function checkSource(db: DatabaseSync, source: SourceConfig, timeoutMs = 15_000): Promise<SourceStatus> {\n return queued(source.name, () => checkNow(db, source, timeoutMs));\n}\n\nasync function checkNow(db: DatabaseSync, source: SourceConfig, timeoutMs: number): Promise<SourceStatus> {\n const dir = sourceDir(source.name);\n try {\n await git(dir, [\"fetch\", \"--quiet\", \"--prune\"], timeoutMs);\n const { review, branch } = await prepareBranch(dir, member());\n const incoming = await count(dir, \"HEAD..@{u}\");\n return { name: source.name, incoming, outgoing: await pendingNow(db, source, review, branch), waiting: review ? (await waitingFiles(dir)).length : 0 };\n } catch (err) {\n return { name: source.name, incoming: 0, outgoing: 0, waiting: 0, error: (err as Error).message };\n }\n}\n\nfunction member(): string {\n const id = loadConfig().member?.id;\n if (!id) throw new Error(\"No member id in config; re-add the memory repo.\");\n return id;\n}\n\nasync function pendingNow(db: DatabaseSync, source: SourceConfig, review: boolean, branch: string): Promise<number> {\n const dir = sourceDir(source.name);\n const { written, deleted } = exportRecords(db, scopes(source).exportScope, true);\n const dirty = (await git(dir, [\"status\", \"--porcelain\"]).catch(() => \"\")).split(\"\\n\").filter(Boolean).length;\n return written.length + deleted.length + dirty + (await unpushed(dir, review, branch));\n}\n\n/** Review mode: files you sent that main doesn't have yet (no network; as of the last fetch). */\nexport async function waitingForMerge(source: SourceConfig): Promise<number> {\n const dir = sourceDir(source.name);\n const onBranch = (await git(dir, [\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]).catch(() => \"\")).trim() === memberBranch(member());\n return onBranch ? (await waitingFiles(dir)).length : 0;\n}\n\n/** What's waiting to be sent, without touching the network or the branch (for the menu and panel). */\nexport async function pendingToSend(db: DatabaseSync, source: SourceConfig): Promise<number> {\n const branch = memberBranch(member());\n const onBranch = (await git(sourceDir(source.name), [\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]).catch(() => \"\")).trim() === branch;\n return pendingNow(db, source, onBranch, branch);\n}\n\nasync function pullRebase(dir: string): Promise<void> {\n try {\n // --prune: a merged-and-deleted review branch must not leave a stale lease for the next push.\n await git(dir, [\"fetch\", \"--quiet\", \"--prune\"], 120_000);\n await git(dir, [\"pull\", \"--quiet\", \"--rebase\", \"--autostash\"], 120_000);\n } catch (err) {\n await git(dir, [\"rebase\", \"--abort\"]).catch(() => {});\n throw new GitError(`Couldn't merge the team's changes (${(err as Error).message}). Nothing was lost; resolve it in ${dir} with git, then sync again.`);\n }\n}\n\n/**\n * Review mode: pull --rebase, and when that conflicts only on your own record files (e.g. main has\n * a squash-merged copy of them), rebuild your branch from main instead. Those files are derived\n * from the DB, so the next export writes them again; your unmerged edits of shared files are kept\n * (as working-tree changes). A real conflict on a shared file still stops with the message.\n * Returns true when it rebuilt (the caller must export again).\n */\nasync function pullOrRebuild(dir: string, member: string, main: string): Promise<boolean> {\n try {\n await pullRebase(dir);\n return false;\n } catch (err) {\n const base = (await git(dir, [\"merge-base\", \"HEAD\", `origin/${main}`]).catch(() => \"\")).trim();\n if (!base) throw err;\n const names = async (range: string[]) => (await git(dir, [\"diff\", \"--name-only\", ...range])).split(\"\\n\").filter(Boolean);\n const mine = await names([base, \"HEAD\"]);\n const theirs = new Set(await names([base, `origin/${main}`]));\n const own = (f: string) => f.includes(`/records/${member}/`);\n const shared = mine.filter((f) => !own(f));\n if (shared.some((f) => theirs.has(f))) throw err;\n const keep = shared.map((f) => ({ f, text: existsSync(join(dir, f)) ? readFileSync(join(dir, f)) : null }));\n await git(dir, [\"reset\", \"--quiet\", \"--hard\", `origin/${main}`]);\n for (const { f, text } of keep) {\n if (text === null) rmSync(join(dir, f), { force: true });\n else {\n mkdirSync(join(dir, f, \"..\"), { recursive: true });\n writeFileSync(join(dir, f), text);\n }\n }\n return true;\n }\n}\n\n/** Get the team's updates only. */\nexport function pullSource(db: DatabaseSync, source: SourceConfig): Promise<ImportResult> {\n return queued(source.name, async () => {\n const dir = sourceDir(source.name);\n const { review, main } = await prepareBranch(dir, member());\n if (review) await pullOrRebuild(dir, member(), main);\n else await pullRebase(dir);\n return importRecords(db, scopes(source).importScope, true);\n });\n}\n\nexport interface SyncResult extends ImportResult {\n sent: number;\n deletedShared: number;\n /** Review mode: where your changes wait for a maintainer. */\n review?: ReviewRequest;\n}\n\n/**\n * Send and get: export your records \u2192 gitleaks on exactly what would be pushed (fails closed)\n * \u2192 commit \u2192 pull --rebase onto main \u2192 import \u2192 push. Review mode pushes your own branch and\n * opens/updates its merge request; otherwise main (one retry if someone pushed in between).\n */\nexport function syncSource(db: DatabaseSync, source: SourceConfig, opts: { requestReview?: RequestReview } = {}): Promise<SyncResult> {\n return queued(source.name, () => syncNow(db, source, opts.requestReview ?? requestReview));\n}\n\nasync function syncNow(db: DatabaseSync, source: SourceConfig, openReview: RequestReview, rebuilt = false): Promise<SyncResult> {\n const dir = sourceDir(source.name);\n const { review, main, branch } = await prepareBranch(dir, member());\n const { exportScope, importScope } = scopes(source);\n const { written, deleted } = exportRecords(db, exportScope);\n await git(dir, [\"add\", \"-A\"]);\n const staged = await git(dir, [\"diff\", \"--cached\"]);\n if (staged.trim()) {\n const scan = await scanDiffForSecrets(staged);\n if (scan.scannerFailed || scan.findings.length > 0) {\n // Undo exactly what this export wrote, so a blocked record doesn't sit in the clone and\n // block every later sync; the DB row stays, and the next sync checks it again.\n await git(dir, [\"reset\", \"--quiet\"]);\n for (const rel of written) {\n const tracked = await git(dir, [\"ls-files\", \"--\", rel]);\n if (tracked.trim()) await git(dir, [\"checkout\", \"--quiet\", \"--\", rel]);\n else rmSync(join(dir, rel), { force: true });\n }\n for (const rel of deleted) await git(dir, [\"checkout\", \"--quiet\", \"--\", rel]).catch(() => {});\n db.prepare(`DELETE FROM sync_exported WHERE source = ? AND path IN (SELECT value FROM json_each(?))`).run(source.name, JSON.stringify(written));\n const why = scan.scannerFailed ? `gitleaks couldn't run (${scan.scannerError})` : `gitleaks flagged ${scan.findings.map((f) => `${f.ruleId} at line ${f.line}`).join(\", \")}`;\n throw new Error(`Not sent: ${why}. Nothing left this machine. Remove or fix that review/memory in Yolont, then sync again.`);\n }\n await commit(dir, `yolont sync: ${loadConfig().member?.name ?? exportScope.member}`);\n }\n if (review) {\n // Rebuilt from main: export, scan and commit again on top of it (once).\n if ((await pullOrRebuild(dir, exportScope.member, main)) && !rebuilt) return syncNow(db, source, openReview, true);\n } else await pullRebase(dir);\n const imported = importRecords(db, importScope, true);\n const result: SyncResult = { ...imported, sent: written.length, deletedShared: deleted.length };\n if (review) {\n const files = await waitingFiles(dir);\n if (files.length === 0) return result; // everything you sent is merged\n // Your own branch, rebased onto main on every sync: a lease, not a blind force.\n if ((await unpushed(dir, true, branch)) > 0 || !(await remoteHas(dir, branch))) await git(dir, [\"push\", \"--quiet\", \"--force-with-lease\", \"origin\", `HEAD:refs/heads/${branch}`], 120_000);\n const request = await openReview(source, branch, main, await describeChanges(dir, files, loadConfig().member?.name ?? branch));\n return { ...result, review: { branch, target: main, waiting: files.length, ...request } };\n }\n const push = () => git(dir, [\"push\", \"--quiet\", \"origin\", `HEAD:refs/heads/${main}`], 120_000);\n try {\n await push();\n } catch {\n await pullRebase(dir);\n await push().catch((err: Error) => {\n throw new GitError(/protect/i.test(err.message) ? `${main} is protected: set \\`review: true\\` in ${MANIFEST} (via a merge request) so members send merge requests. (${err.message})` : err.message);\n });\n }\n return result;\n}\n\nexport interface SourceRun {\n name: string;\n result?: ImportResult & Partial<SyncResult>;\n error?: string;\n}\n\n/** Each repo in turn; one failing never stops the others (errors come back per repo). */\nexport async function syncAll(db: DatabaseSync, mode: \"sync\" | \"pull\", sources: SourceConfig[] = loadConfig().sources ?? []): Promise<SourceRun[]> {\n const out: SourceRun[] = [];\n for (const source of sources) {\n try {\n out.push({ name: source.name, result: mode === \"sync\" ? await syncSource(db, source) : await pullSource(db, source) });\n } catch (err) {\n out.push({ name: source.name, error: (err as Error).message });\n }\n }\n return out;\n}\n\n/** One line per repo, for terminals and logs. */\nexport function describeRun(r: SourceRun): string {\n if (r.error) return `${r.name}: not synced: ${r.error}`;\n const x = r.result!;\n const mr = x.review ? `; ${x.review.waiting} file(s) waiting for merge${x.review.url ? `: ${x.review.url}` : \"\"}${x.review.note ? ` (${x.review.note})` : \"\"}` : \"\";\n return `${r.name}: got ${x.imported}, removed ${x.removed}, restored ${x.restored}${x.sent !== undefined ? `, sent ${x.sent}, deleted ${x.deletedShared}` : \"\"}${x.rejected.length ? `, skipped ${x.rejected.length} misplaced file(s)` : \"\"}${mr}`;\n}\n", "// Stable contract, not branding: existing MR/PR comments are found (and updated, and mined for\n// author history) by this exact string. Renaming it would orphan every past comment.\nexport const PR_SCORE_MARKER = \"<!-- pr-score:v1 -->\";\n\n/** Added to an MR/PR once a score is posted, so the forge's list can filter reviewed vs not. */\nexport const PR_SCORE_LABEL = \"llm-reviewed\";\n\nexport type ForgeType = \"gitlab\" | \"github\";\n\n/** GitLab: numeric id or \"group/sub/project\". GitHub: numeric repo id or \"owner/repo\". */\nexport type ProjectRef = number | string;\n\nexport interface MrMetadata {\n projectId: ProjectRef;\n iid: number;\n title: string;\n description: string;\n authorUsername: string;\n draft: boolean;\n labels: string[];\n targetBranch: string;\n sourceBranch: string;\n sha: string;\n webUrl: string;\n diffRefs: { baseSha: string; startSha: string; headSha: string };\n}\n\nexport interface JobSummary {\n name: string;\n /** Normalized: \"success\" | \"failed\" | anything else (= not conclusive). */\n status: string;\n coverage: number | null;\n}\n\nexport interface PastMrNote {\n mrIid: number;\n body: string;\n createdAt: string;\n}\n\nexport interface ProjectMrSummary {\n iid: number;\n authorUsername: string;\n sha: string;\n title: string;\n mergedAt: string | null;\n}\n\nexport interface DiscussionComment {\n id: number;\n authorUsername: string;\n body: string;\n system: boolean;\n createdAt: string;\n file?: string;\n line?: number;\n}\n\nexport interface ForgeProject {\n /** Numeric forge id \u2014 what the DB stores as forge_project_id. */\n id: number;\n pathWithNamespace: string;\n name: string;\n /** Project home page, for file links in comments. */\n webUrl: string;\n defaultBranch: string;\n}\n\nexport interface FindingPosition {\n baseSha: string;\n startSha: string;\n headSha: string;\n filePath: string;\n /** New-file line (see resolveDiffPosition). */\n line: number;\n /** Set for an unchanged context line \u2014 GitLab needs it, GitHub ignores it. */\n oldLine?: number;\n}\n\n/** One git host. GitLab \"MR iid\" and GitHub \"PR number\" are both `mrIid` here. */\nexport interface ForgeClient {\n readonly type: ForgeType;\n /** Web host (\"github.com\", \"git.example.com:8443\") \u2014 the identity key, never the API host. */\n readonly host: string;\n getMergeRequest(project: ProjectRef, mrIid: number): Promise<MrMetadata>;\n upsertPrScoreNote(project: ProjectRef, mrIid: number, body: string): Promise<void>;\n markReviewed(project: ProjectRef, mrIid: number): Promise<boolean>;\n listPrScoreNotes(project: ProjectRef, mrIid: number): Promise<PastMrNote[]>;\n /** `within`: limit to this project where the forge's search would otherwise span every repo. */\n listAuthorMergeRequests(authorUsername: string, limit?: number, within?: ProjectRef): Promise<{ projectId: ProjectRef; iid: number }[]>;\n listPipelineJobs(project: ProjectRef, pipelineId: number): Promise<JobSummary[]>;\n getTestReportSummary(project: ProjectRef, pipelineId: number): Promise<{ total: number; success: number } | null>;\n getMrDiffText(project: ProjectRef, mrIid: number): Promise<string>;\n listProjectMergeRequests(project: ProjectRef, opts?: { state?: \"merged\" | \"opened\" | \"closed\" | \"all\"; maxPages?: number }): Promise<ProjectMrSummary[]>;\n listMrDiscussions(project: ProjectRef, mrIid: number): Promise<DiscussionComment[]>;\n postFindingDiscussion(project: ProjectRef, mrIid: number, body: string, position?: FindingPosition): Promise<{ discussionId: string; noteId: number }>;\n upsertDiscussionReply(project: ProjectRef, mrIid: number, discussionId: string, body: string, noteId?: number | null): Promise<number>;\n deleteDiscussionReply(project: ProjectRef, mrIid: number, discussionId: string, noteId: number): Promise<void>;\n resolveDiscussion(project: ProjectRef, mrIid: number, discussionId: string, resolved: boolean): Promise<void>;\n listMrDiscussionThreads(project: ProjectRef, mrIid: number): Promise<{ discussionId: string; notes: DiscussionComment[] }[]>;\n getCurrentUser(): Promise<{ username: string; id: number }>;\n getProject(project: ProjectRef): Promise<ForgeProject>;\n /** Every file path at `ref` (blobs only). May be partial on huge repos. */\n listFiles(project: ProjectRef, ref: string): Promise<string[]>;\n /** File content at `ref`, or null if missing. */\n readFile(project: ProjectRef, path: string, ref: string): Promise<string | null>;\n /** The open MR/PR from `sourceBranch`: updates its description, or opens one. */\n openOrUpdateChangeRequest(project: ProjectRef, opts: { sourceBranch: string; targetBranch: string; title: string; description: string }): Promise<{ url: string; created: boolean }>;\n}\n\n/** \"MR !12\" / \"PR #12\" \u2014 for user-facing text. */\nexport function changeLabel(type: ForgeType, n: number): string {\n return type === \"github\" ? `PR #${n}` : `MR !${n}`;\n}\n", "import type { DiscussionComment, FindingPosition, ForgeClient, ForgeProject, JobSummary, MrMetadata, PastMrNote, ProjectMrSummary, ProjectRef } from \"./types.js\";\nimport { PR_SCORE_LABEL, PR_SCORE_MARKER } from \"./types.js\";\n\n/** Thrown for a non-2xx GitHub response; `status` lets callers treat 404 as \"gone\". */\nexport class GitHubError extends Error {\n constructor(\n message: string,\n readonly status: number,\n ) {\n super(message);\n }\n}\n\ninterface GhUser {\n login: string;\n id: number;\n type?: string;\n}\ninterface GhComment {\n id: number;\n node_id: string;\n body: string;\n user: GhUser | null;\n author_association?: string;\n created_at: string;\n path?: string;\n line?: number | null;\n original_line?: number | null;\n in_reply_to_id?: number;\n}\ninterface GhPull {\n number: number;\n title: string;\n body: string | null;\n user: GhUser | null;\n draft?: boolean;\n labels: { name: string }[];\n base: { ref: string; sha: string };\n head: { ref: string; sha: string };\n html_url: string;\n merged_at: string | null;\n}\ninterface GhRepo {\n id: number;\n full_name: string;\n name: string;\n html_url: string;\n default_branch: string;\n}\n\n/**\n * GitHub / GitHub Enterprise over plain fetch (REST + one GraphQL call for resolving threads,\n * which REST can't do). A GitLab \"discussion\" maps to a PR review-comment thread: discussionId\n * is the root review comment's id, replies hang off it.\n */\nexport class GitHubForge implements ForgeClient {\n readonly type = \"github\" as const;\n readonly host: string;\n private readonly api: string;\n private readonly graphqlUrl: string;\n private readonly token: string;\n private readonly fetchImpl: typeof fetch;\n private readonly repoNames = new Map<number, string>();\n\n /** `host`: the web host (\"github.com\" or a GHE host). `fetch` is injectable for tests. */\n constructor(opts: { host?: string; token: string; fetch?: typeof fetch }) {\n this.host = (opts.host ?? \"github.com\").toLowerCase();\n const dotCom = this.host === \"github.com\";\n this.api = dotCom ? \"https://api.github.com\" : `https://${this.host}/api/v3`;\n this.graphqlUrl = dotCom ? \"https://api.github.com/graphql\" : `https://${this.host}/api/graphql`;\n this.token = opts.token;\n this.fetchImpl = opts.fetch ?? fetch;\n }\n\n // ---- http ----\n\n private async request(method: string, pathOrUrl: string, body?: unknown, accept = \"application/vnd.github+json\"): Promise<Response> {\n const res = await this.fetchImpl(pathOrUrl.startsWith(\"http\") ? pathOrUrl : `${this.api}${pathOrUrl}`, {\n method,\n headers: {\n Authorization: `Bearer ${this.token}`,\n Accept: accept,\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n \"User-Agent\": \"yolont\",\n ...(body !== undefined && { \"Content-Type\": \"application/json\" }),\n },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n });\n if (!res.ok) {\n const detail = await res.text().catch(() => \"\");\n throw new GitHubError(`GitHub ${method} ${pathOrUrl} \u2192 ${res.status}${detail ? `: ${detail.slice(0, 300)}` : \"\"}`, res.status);\n }\n return res;\n }\n\n private async json<T>(method: string, path: string, body?: unknown): Promise<T> {\n const res = await this.request(method, path, body);\n return (res.status === 204 ? undefined : await res.json()) as T;\n }\n\n /** Follows `Link: rel=\"next\"` \u2014 the default page is 30, and marker lookups must see every comment. */\n private async paginate<T>(path: string, maxPages = Infinity): Promise<T[]> {\n const out: T[] = [];\n let url: string | undefined = `${path}${path.includes(\"?\") ? \"&\" : \"?\"}per_page=100`;\n for (let page = 0; url && page < maxPages; page++) {\n const res = await this.request(\"GET\", url);\n const data = (await res.json()) as T[] | { jobs: T[] };\n out.push(...(Array.isArray(data) ? data : data.jobs));\n url = res.headers.get(\"link\")?.match(/<([^>]+)>;\\s*rel=\"next\"/)?.[1];\n }\n return out;\n }\n\n /** \"owner/repo\" for API paths; a numeric id (what the DB stores) is resolved once and cached. */\n private async repo(project: ProjectRef): Promise<string> {\n if (typeof project === \"string\" && !/^\\d+$/.test(project)) return project;\n const id = Number(project);\n let name = this.repoNames.get(id);\n if (!name) {\n name = (await this.json<GhRepo>(\"GET\", `/repositories/${id}`)).full_name;\n this.repoNames.set(id, name);\n }\n return name;\n }\n\n private static comment(c: GhComment): DiscussionComment {\n const line = c.line ?? c.original_line ?? undefined;\n return { id: c.id, authorUsername: c.user?.login ?? \"unknown\", body: c.body ?? \"\", system: false, createdAt: c.created_at, file: c.path, line };\n }\n\n // ---- ForgeClient ----\n\n async getMergeRequest(project: ProjectRef, mrIid: number): Promise<MrMetadata> {\n const pr = await this.json<GhPull>(\"GET\", `/repos/${await this.repo(project)}/pulls/${mrIid}`);\n return {\n projectId: project,\n iid: mrIid,\n title: pr.title ?? \"\",\n description: pr.body ?? \"\",\n authorUsername: pr.user?.login ?? \"unknown\",\n draft: Boolean(pr.draft),\n labels: pr.labels.map((l) => l.name),\n targetBranch: pr.base.ref,\n sourceBranch: pr.head.ref,\n sha: pr.head.sha,\n webUrl: pr.html_url,\n diffRefs: { baseSha: pr.base.sha, startSha: pr.base.sha, headSha: pr.head.sha },\n };\n }\n\n private async issueComments(project: ProjectRef, n: number): Promise<GhComment[]> {\n return this.paginate<GhComment>(`/repos/${await this.repo(project)}/issues/${n}/comments`);\n }\n\n /** Score comments carrying the marker, ignoring ones anybody could have pasted it into. */\n private async scoreComments(project: ProjectRef, n: number): Promise<GhComment[]> {\n return (await this.issueComments(project, n)).filter((c) => c.body?.includes(PR_SCORE_MARKER) && isTrustedCommenter(c));\n }\n\n async upsertPrScoreNote(project: ProjectRef, mrIid: number, body: string): Promise<void> {\n const repo = await this.repo(project);\n const existing = (await this.scoreComments(repo, mrIid))[0];\n if (existing) await this.json(\"PATCH\", `/repos/${repo}/issues/comments/${existing.id}`, { body });\n else await this.json(\"POST\", `/repos/${repo}/issues/${mrIid}/comments`, { body });\n }\n\n async markReviewed(project: ProjectRef, mrIid: number): Promise<boolean> {\n try {\n await this.json(\"POST\", `/repos/${await this.repo(project)}/issues/${mrIid}/labels`, { labels: [PR_SCORE_LABEL] });\n return true;\n } catch (err) {\n console.warn(`[yolont] could not add '${PR_SCORE_LABEL}' label: ${(err as Error).message}`);\n return false;\n }\n }\n\n async listPrScoreNotes(project: ProjectRef, mrIid: number): Promise<PastMrNote[]> {\n return (await this.scoreComments(project, mrIid)).map((c) => ({ mrIid, body: c.body, createdAt: c.created_at }));\n }\n\n async listAuthorMergeRequests(authorUsername: string, limit = 20, within?: ProjectRef): Promise<{ projectId: ProjectRef; iid: number }[]> {\n // Without `within` this searches every repo the token can see \u2014 fine for a user's PAT, but in\n // CI it should stay on the reviewed repo.\n const scope = within === undefined ? \"\" : ` repo:${await this.repo(within)}`;\n const q = encodeURIComponent(`type:pr author:${authorUsername} is:merged${scope}`);\n const res = await this.json<{ items: { number: number; repository_url: string }[] }>(\"GET\", `/search/issues?q=${q}&sort=updated&order=desc&per_page=${Math.min(limit, 100)}`);\n return res.items.map((i) => ({ projectId: i.repository_url.replace(/^.*\\/repos\\//, \"\"), iid: i.number }));\n }\n\n /** `pipelineId` is an Actions workflow run id. Best-effort, like GitLab's. */\n async listPipelineJobs(project: ProjectRef, pipelineId: number): Promise<JobSummary[]> {\n try {\n const jobs = await this.paginate<{ name: string; status: string; conclusion: string | null }>(`/repos/${await this.repo(project)}/actions/runs/${pipelineId}/jobs`);\n return jobs.map((j) => ({ name: j.name, status: normalizeConclusion(j.status, j.conclusion), coverage: null }));\n } catch {\n return [];\n }\n }\n\n /** GitHub has no pipeline test-report API \u2014 the category is excluded, as for a GitLab pipeline without one. */\n async getTestReportSummary(): Promise<null> {\n return null;\n }\n\n async getMrDiffText(project: ProjectRef, mrIid: number): Promise<string> {\n return (await this.request(\"GET\", `/repos/${await this.repo(project)}/pulls/${mrIid}`, undefined, \"application/vnd.github.diff\")).text();\n }\n\n async listProjectMergeRequests(project: ProjectRef, opts: { state?: \"merged\" | \"opened\" | \"closed\" | \"all\"; maxPages?: number } = {}): Promise<ProjectMrSummary[]> {\n const state = opts.state === \"opened\" ? \"open\" : opts.state === \"merged\" || opts.state === \"closed\" ? \"closed\" : \"all\";\n const pulls = await this.paginate<GhPull>(`/repos/${await this.repo(project)}/pulls?state=${state}&sort=updated&direction=desc`, opts.maxPages);\n return pulls\n .filter((p) => (opts.state === \"merged\" ? p.merged_at !== null : opts.state === \"closed\" ? p.merged_at === null : true))\n .map((p) => ({ iid: p.number, authorUsername: p.user?.login ?? \"unknown\", sha: p.head.sha, title: p.title ?? \"\", mergedAt: p.merged_at }));\n }\n\n async listMrDiscussions(project: ProjectRef, mrIid: number): Promise<DiscussionComment[]> {\n const repo = await this.repo(project);\n const [review, issue] = await Promise.all([this.paginate<GhComment>(`/repos/${repo}/pulls/${mrIid}/comments`), this.issueComments(repo, mrIid)]);\n return [...review, ...issue].map(GitHubForge.comment);\n }\n\n async postFindingDiscussion(project: ProjectRef, mrIid: number, body: string, position?: FindingPosition): Promise<{ discussionId: string; noteId: number }> {\n // GitHub issue comments aren't threads (no reply/resolve), so there's nothing honest to map a position-less finding to.\n if (!position) throw new Error(\"GitHub finding threads need a file/line position\");\n const c = await this.json<GhComment>(\"POST\", `/repos/${await this.repo(project)}/pulls/${mrIid}/comments`, {\n body,\n commit_id: position.headSha,\n path: position.filePath,\n line: position.line,\n side: \"RIGHT\",\n });\n return { discussionId: String(c.id), noteId: c.id };\n }\n\n async upsertDiscussionReply(project: ProjectRef, mrIid: number, discussionId: string, body: string, noteId?: number | null): Promise<number> {\n const repo = await this.repo(project);\n if (noteId != null) {\n try {\n await this.json(\"PATCH\", `/repos/${repo}/pulls/comments/${noteId}`, { body });\n return noteId;\n } catch (err) {\n if ((err as GitHubError).status !== 404) throw err;\n }\n }\n return (await this.json<GhComment>(\"POST\", `/repos/${repo}/pulls/${mrIid}/comments/${discussionId}/replies`, { body })).id;\n }\n\n async deleteDiscussionReply(project: ProjectRef, _mrIid: number, _discussionId: string, noteId: number): Promise<void> {\n try {\n await this.json(\"DELETE\", `/repos/${await this.repo(project)}/pulls/comments/${noteId}`);\n } catch (err) {\n if ((err as GitHubError).status !== 404) throw err;\n }\n }\n\n /** REST can't resolve review threads; find the thread whose first comment is our root (by node id) and use GraphQL. */\n async resolveDiscussion(project: ProjectRef, mrIid: number, discussionId: string, resolved: boolean): Promise<void> {\n const repo = await this.repo(project);\n const root = await this.json<GhComment>(\"GET\", `/repos/${repo}/pulls/comments/${discussionId}`);\n const [owner, name] = repo.split(\"/\");\n let after: string | null = null;\n let threadId: string | undefined;\n do {\n type Page = { repository: { pullRequest: { reviewThreads: { pageInfo: { hasNextPage: boolean; endCursor: string | null }; nodes: { id: string; comments: { nodes: { id: string }[] } }[] } } } };\n const data: Page = await this.graphql<Page>(\n `query($owner:String!,$name:String!,$n:Int!,$after:String){repository(owner:$owner,name:$name){pullRequest(number:$n){reviewThreads(first:100,after:$after){pageInfo{hasNextPage endCursor}nodes{id comments(first:1){nodes{id}}}}}}}`,\n { owner, name, n: mrIid, after },\n );\n const threads = data.repository.pullRequest.reviewThreads;\n threadId = threads.nodes.find((t) => t.comments.nodes[0]?.id === root.node_id)?.id;\n after = threads.pageInfo.hasNextPage ? threads.pageInfo.endCursor : null;\n } while (!threadId && after);\n if (!threadId) throw new Error(`No review thread found for comment ${discussionId}`);\n const mutation = resolved ? \"resolveReviewThread\" : \"unresolveReviewThread\";\n await this.graphql(`mutation($id:ID!){${mutation}(input:{threadId:$id}){thread{id}}}`, { id: threadId });\n }\n\n private async graphql<T>(query: string, variables: Record<string, unknown>): Promise<T> {\n const res = await this.json<{ data?: T; errors?: { message: string }[] }>(\"POST\", this.graphqlUrl, { query, variables });\n if (res.errors?.length) throw new Error(`GitHub GraphQL: ${res.errors.map((e) => e.message).join(\"; \")}`);\n return res.data as T;\n }\n\n /** Review comments grouped by thread root (GitHub's in_reply_to_id always points at the root). */\n async listMrDiscussionThreads(project: ProjectRef, mrIid: number): Promise<{ discussionId: string; notes: DiscussionComment[] }[]> {\n const comments = await this.paginate<GhComment>(`/repos/${await this.repo(project)}/pulls/${mrIid}/comments`);\n const threads = new Map<string, DiscussionComment[]>();\n for (const c of comments) {\n const root = String(c.in_reply_to_id ?? c.id);\n threads.set(root, [...(threads.get(root) ?? []), GitHubForge.comment(c)]);\n }\n return [...threads].map(([discussionId, notes]) => ({ discussionId, notes }));\n }\n\n async getCurrentUser(): Promise<{ username: string; id: number }> {\n const u = await this.json<GhUser>(\"GET\", \"/user\");\n return { username: u.login, id: u.id };\n }\n\n async getProject(project: ProjectRef): Promise<ForgeProject> {\n const r = await this.json<GhRepo>(\"GET\", typeof project === \"number\" || /^\\d+$/.test(project) ? `/repositories/${project}` : `/repos/${project}`);\n this.repoNames.set(r.id, r.full_name);\n return { id: r.id, pathWithNamespace: r.full_name, name: r.name, webUrl: r.html_url, defaultBranch: r.default_branch };\n }\n\n async listFiles(project: ProjectRef, ref: string): Promise<string[]> {\n // `truncated: true` past ~100k entries \u2014 a partial list is fine for sampling.\n const t = await this.json<{ tree: { path: string; type: string }[] }>(\"GET\", `/repos/${await this.repo(project)}/git/trees/${encodeURIComponent(ref)}?recursive=1`);\n return t.tree.filter((e) => e.type === \"blob\").map((e) => e.path);\n }\n\n async readFile(project: ProjectRef, path: string, ref: string): Promise<string | null> {\n const p = path.split(\"/\").map(encodeURIComponent).join(\"/\");\n try {\n const res = await this.request(\"GET\", `/repos/${await this.repo(project)}/contents/${p}?ref=${encodeURIComponent(ref)}`, undefined, \"application/vnd.github.raw\");\n return await res.text();\n } catch (err) {\n if (err instanceof GitHubError && err.status === 404) return null;\n throw err;\n }\n }\n\n\n async openOrUpdateChangeRequest(project: ProjectRef, opts: { sourceBranch: string; targetBranch: string; title: string; description: string }): Promise<{ url: string; created: boolean }> {\n const repo = await this.repo(project);\n const owner = repo.split(\"/\")[0]!;\n const open = await this.json<{ number: number; html_url: string }[]>(\"GET\", `/repos/${repo}/pulls?state=open&head=${encodeURIComponent(`${owner}:${opts.sourceBranch}`)}&base=${encodeURIComponent(opts.targetBranch)}`);\n if (open[0]) {\n await this.json(\"PATCH\", `/repos/${repo}/pulls/${open[0].number}`, { body: opts.description });\n return { url: open[0].html_url, created: false };\n }\n const pr = await this.json<{ html_url: string }>(\"POST\", `/repos/${repo}/pulls`, { title: opts.title, head: opts.sourceBranch, base: opts.targetBranch, body: opts.description });\n return { url: pr.html_url, created: true };\n }\n}\n\n/** Check-run conclusion \u2192 the \"success\"/\"failed\" vocabulary scoreFromJob understands. */\nexport function normalizeConclusion(status: string, conclusion: string | null): string {\n if (conclusion === \"success\") return \"success\";\n if (conclusion === \"failure\" || conclusion === \"timed_out\") return \"failed\";\n return conclusion ?? status;\n}\n\n/** On a public repo anyone can comment, so a marker comment only counts from a bot (the Actions\n * token posts as github-actions[bot]) or someone with a role on the repo. */\nfunction isTrustedCommenter(c: GhComment): boolean {\n return c.user?.type === \"Bot\" || [\"OWNER\", \"MEMBER\", \"COLLABORATOR\"].includes(c.author_association ?? \"\");\n}\n", "import { Gitlab } from \"@gitbeaker/rest\";\n\nimport type { DiscussionComment, FindingPosition, ForgeClient, ForgeProject, JobSummary, MrMetadata, PastMrNote, ProjectMrSummary, ProjectRef } from \"./types.js\";\nimport { PR_SCORE_LABEL, PR_SCORE_MARKER } from \"./types.js\";\n\ninterface DiscussionNotePosition {\n new_path?: string;\n old_path?: string;\n new_line?: string;\n old_line?: string;\n}\n\nexport class GitLabForge implements ForgeClient {\n readonly type = \"gitlab\" as const;\n readonly host: string;\n private api: Gitlab;\n\n /** `url`: the instance base URL (\"https://gitlab.com\", \"https://host/gitlab\"). */\n constructor(opts: { url: string; token: string }) {\n this.host = new URL(opts.url).host.toLowerCase();\n this.api = new Gitlab({ host: opts.url, token: opts.token });\n }\n\n async getMergeRequest(projectId: ProjectRef, mrIid: number): Promise<MrMetadata> {\n const mr = await this.api.MergeRequests.show(projectId, mrIid);\n return {\n projectId,\n iid: mrIid,\n title: mr.title ?? \"\",\n description: mr.description ?? \"\",\n authorUsername: mr.author?.username ?? \"unknown\",\n draft: Boolean(mr.draft || mr.work_in_progress),\n labels: Array.isArray(mr.labels) ? mr.labels.map((l) => (typeof l === \"string\" ? l : l.name)) : [],\n targetBranch: mr.target_branch ?? \"main\",\n sourceBranch: mr.source_branch ?? \"\",\n sha: mr.sha ?? \"\",\n webUrl: mr.web_url ?? \"\",\n diffRefs: {\n baseSha: mr.diff_refs?.base_sha ?? \"\",\n startSha: mr.diff_refs?.start_sha ?? \"\",\n headSha: mr.diff_refs?.head_sha ?? \"\",\n },\n };\n }\n\n async upsertPrScoreNote(projectId: ProjectRef, mrIid: number, body: string): Promise<void> {\n const notes = await this.api.MergeRequestNotes.all(projectId, mrIid);\n const existing = notes.find((n) => typeof n.body === \"string\" && n.body.includes(PR_SCORE_MARKER));\n if (existing) {\n await this.api.MergeRequestNotes.edit(projectId, mrIid, existing.id, { body });\n } else {\n await this.api.MergeRequestNotes.create(projectId, mrIid, body);\n }\n }\n\n /** Best-effort: `add_labels` keeps existing labels, and GitLab creates the project label on\n * first use. A token without label rights shouldn't fail an otherwise-posted review. */\n async markReviewed(projectId: ProjectRef, mrIid: number): Promise<boolean> {\n try {\n await this.api.MergeRequests.edit(projectId, mrIid, { addLabels: PR_SCORE_LABEL });\n return true;\n } catch (err) {\n console.warn(`[yolont] could not add '${PR_SCORE_LABEL}' label: ${(err as Error).message}`);\n return false;\n }\n }\n\n /** All notes on an MR that carry our marker, oldest first \u2014 used for history rebuild. */\n async listPrScoreNotes(projectId: ProjectRef, mrIid: number): Promise<PastMrNote[]> {\n const notes = await this.api.MergeRequestNotes.all(projectId, mrIid);\n return notes\n .filter((n) => typeof n.body === \"string\" && n.body.includes(PR_SCORE_MARKER))\n .map((n) => ({ mrIid, body: n.body as string, createdAt: (n.created_at as string) ?? \"\" }));\n }\n\n /** Past MRs by this author across all projects the token can see, newest first. */\n async listAuthorMergeRequests(authorUsername: string, limit = 20): Promise<{ projectId: ProjectRef; iid: number }[]> {\n const mrs = await this.api.MergeRequests.all({\n authorUsername,\n scope: \"all\",\n state: \"merged\",\n orderBy: \"updated_at\",\n sort: \"desc\",\n perPage: limit,\n });\n return mrs.map((mr) => ({ projectId: mr.project_id as number, iid: mr.iid as number }));\n }\n\n /** Best-effort like getTestReportSummary: a bad/inaccessible pipeline ID degrades to \"no\n * job data\" (job:<name> categories excluded, per pipelineResults.ts), not a crash. */\n async listPipelineJobs(projectId: ProjectRef, pipelineId: number): Promise<JobSummary[]> {\n try {\n const jobs = await this.api.Jobs.all(projectId, { pipelineId });\n return jobs.map((j) => ({\n name: j.name,\n status: j.status,\n coverage: j.coverage != null ? Number(j.coverage) : null,\n }));\n } catch {\n return [];\n }\n }\n\n /**\n * Fetches the MR diff via the GitLab API instead of local `git` \u2014 the fallback used\n * when there's no local checkout of the target repo at all (ad-hoc/local testing\n * against a project you haven't cloned, or scoring across repos generically). Not the\n * default in a real CI job: this endpoint truncates large diffs per-file independent\n * of our own `max_diff_bytes`, whereas a local `git diff` is complete.\n *\n * GitLab's diff entries omit the `--- a/...`/`+++ b/...` header lines (implied by\n * old_path/new_path), so they're reconstructed here into a standard unified diff \u2014\n * good enough for the diff-size count, gitleaks, and the LLM prompt, none of which\n * need real git plumbing, just the patch text.\n */\n async getMrDiffText(projectId: ProjectRef, mrIid: number): Promise<string> {\n const diffs = await this.api.MergeRequests.allDiffs(projectId, mrIid);\n return diffs\n .map((d) => {\n const header = `diff --git a/${d.old_path} b/${d.new_path}\\n--- a/${d.old_path}\\n+++ b/${d.new_path}\\n`;\n return header + d.diff;\n })\n .join(\"\\n\");\n }\n\n /** All MRs in a project (not scoped to one author) \u2014 used by the local backfill/mining tool. */\n async listProjectMergeRequests(\n projectId: ProjectRef,\n opts: { state?: \"merged\" | \"opened\" | \"closed\" | \"all\"; maxPages?: number } = {},\n ): Promise<ProjectMrSummary[]> {\n const mrs = await this.api.MergeRequests.all({\n projectId,\n state: opts.state === \"all\" ? undefined : opts.state,\n orderBy: \"updated_at\",\n sort: \"desc\",\n perPage: 100,\n maxPages: opts.maxPages,\n });\n return mrs.map((mr) => ({\n iid: mr.iid,\n authorUsername: mr.author?.username ?? \"unknown\",\n sha: mr.sha ?? \"\",\n title: mr.title ?? \"\",\n mergedAt: mr.merged_at,\n }));\n }\n\n /**\n * Real human review comments on an MR (diff-line and general discussion notes),\n * filtered to non-system notes only \u2014 used by the local mining tool to build the\n * `human_review_comments` table. Caller is responsible for excluding the Yolont\n * bot's own notes (see getCurrentUser) since a bot's Yolont comment is itself a\n * non-system note and would otherwise be mined as \"human\" signal.\n */\n async listMrDiscussions(projectId: ProjectRef, mrIid: number): Promise<DiscussionComment[]> {\n const discussions = await this.api.MergeRequestDiscussions.all(projectId, mrIid);\n const comments: DiscussionComment[] = [];\n for (const discussion of discussions) {\n for (const note of discussion.notes ?? []) {\n if (note.system) continue;\n const position = (note as { position?: DiscussionNotePosition }).position;\n comments.push({\n id: note.id,\n authorUsername: note.author?.username ?? \"unknown\",\n body: note.body ?? \"\",\n system: false,\n createdAt: note.created_at ?? \"\",\n file: position?.new_path ?? position?.old_path,\n line: position?.new_line ? Number(position.new_line) : position?.old_line ? Number(position.old_line) : undefined,\n });\n }\n }\n return comments;\n }\n\n /**\n * Posts one finding as its own discussion thread \u2014 repliable by the contributor,\n * unlike the single aggregate note from upsertPrScoreNote. `position` pins it to a\n * diff line (from MrMetadata.diffRefs, captured at review time); omit it to post a\n * general (still repliable) discussion for a finding with no file/line.\n *\n * `oldLine` matters: GitLab rejects a position with only `new_line` unless that line\n * was actually added \u2014 a comment on an unchanged/context line needs `old_line` too (see\n * resolveDiffPosition in src/git.ts, which is what callers should use to compute this).\n */\n async postFindingDiscussion(\n projectId: ProjectRef,\n mrIid: number,\n body: string,\n position?: FindingPosition,\n ): Promise<{ discussionId: string; noteId: number }> {\n const discussion = await this.api.MergeRequestDiscussions.create(projectId, mrIid, body, {\n position: position\n ? {\n baseSha: position.baseSha,\n startSha: position.startSha,\n headSha: position.headSha,\n newPath: position.filePath,\n newLine: String(position.line),\n ...(position.oldLine != null ? { oldLine: String(position.oldLine) } : {}),\n positionType: \"text\",\n }\n : undefined,\n });\n return { discussionId: String(discussion.id), noteId: discussion.notes?.[0]?.id as number };\n }\n\n /** Replies on a discussion thread, or edits our earlier reply in place when `noteId` is\n * given. Falls back to a fresh reply if that note is gone (e.g. deleted by hand in GitLab).\n * Returns the note id to keep for the next edit. */\n async upsertDiscussionReply(projectId: ProjectRef, mrIid: number, discussionId: string, body: string, noteId?: number | null): Promise<number> {\n if (noteId != null) {\n try {\n await this.api.MergeRequestDiscussions.editNote(projectId, mrIid, discussionId, noteId, { body });\n return noteId;\n } catch (err) {\n if (!isNotFound(err)) throw err;\n }\n }\n const note = await this.api.MergeRequestDiscussions.addNote(projectId, mrIid, discussionId, body);\n return note.id;\n }\n\n async deleteDiscussionReply(projectId: ProjectRef, mrIid: number, discussionId: string, noteId: number): Promise<void> {\n try {\n await this.api.MergeRequestDiscussions.removeNote(projectId, mrIid, discussionId, noteId);\n } catch (err) {\n if (!isNotFound(err)) throw err;\n }\n }\n\n async resolveDiscussion(projectId: ProjectRef, mrIid: number, discussionId: string, resolved: boolean): Promise<void> {\n await this.api.MergeRequestDiscussions.resolve(projectId, mrIid, discussionId, resolved);\n }\n\n /** Like listMrDiscussions, but keeps notes grouped by their discussion thread \u2014 used by\n * the local sync-replies command to find replies on a specific tracked finding thread. */\n async listMrDiscussionThreads(projectId: ProjectRef, mrIid: number): Promise<{ discussionId: string; notes: DiscussionComment[] }[]> {\n const discussions = await this.api.MergeRequestDiscussions.all(projectId, mrIid);\n return discussions.map((discussion) => ({\n discussionId: String(discussion.id),\n notes: (discussion.notes ?? [])\n .filter((note) => !note.system)\n .map((note) => {\n const position = (note as { position?: DiscussionNotePosition }).position;\n return {\n id: note.id,\n authorUsername: note.author?.username ?? \"unknown\",\n body: note.body ?? \"\",\n system: false,\n createdAt: note.created_at ?? \"\",\n file: position?.new_path ?? position?.old_path,\n line: position?.new_line ? Number(position.new_line) : position?.old_line ? Number(position.old_line) : undefined,\n };\n }),\n }));\n }\n\n /** Used once at the start of a mining run to identify (and exclude) the bot's own notes. */\n async getCurrentUser(): Promise<{ username: string; id: number }> {\n const user = await this.api.Users.showCurrentUser();\n return { username: user.username, id: user.id };\n }\n\n async getProject(projectId: ProjectRef): Promise<ForgeProject> {\n const project = await this.api.Projects.show(projectId);\n return { id: project.id, pathWithNamespace: project.path_with_namespace, name: project.name, webUrl: project.web_url, defaultBranch: project.default_branch };\n }\n\n async listFiles(projectId: ProjectRef, ref: string): Promise<string[]> {\n // ponytail: capped at 20 pages (2000 entries) \u2014 enough to sample from; huge monorepos get a partial tree.\n const tree = await this.api.Repositories.allRepositoryTrees(projectId, { ref, recursive: true, perPage: 100, maxPages: 20 });\n return (tree as { path: string; type: string }[]).filter((e) => e.type === \"blob\").map((e) => e.path);\n }\n\n async readFile(projectId: ProjectRef, path: string, ref: string): Promise<string | null> {\n try {\n const raw = await this.api.RepositoryFiles.showRaw(projectId, path, ref);\n return typeof raw === \"string\" ? raw : await (raw as Blob).text();\n } catch (err) {\n if (isNotFound(err)) return null;\n throw err;\n }\n }\n\n /** Best-effort: returns null if the pipeline has no test report (not all repos publish one). */\n async getTestReportSummary(projectId: ProjectRef, pipelineId: number): Promise<{ total: number; success: number } | null> {\n try {\n const report = await this.api.Pipelines.showTestReportSummary(projectId, pipelineId);\n const total = report.total?.count ?? 0;\n const success = report.total?.success ?? 0;\n if (total === 0) return null;\n return { total, success };\n } catch {\n return null;\n }\n }\n\n async openOrUpdateChangeRequest(projectId: ProjectRef, opts: { sourceBranch: string; targetBranch: string; title: string; description: string }): Promise<{ url: string; created: boolean }> {\n const open = await this.api.MergeRequests.all({ projectId, sourceBranch: opts.sourceBranch, targetBranch: opts.targetBranch, state: \"opened\" });\n const mr = open[0];\n if (mr) {\n await this.api.MergeRequests.edit(projectId, mr.iid, { description: opts.description });\n return { url: (mr.web_url as string) ?? \"\", created: false };\n }\n const created = await this.api.MergeRequests.create(projectId, opts.sourceBranch, opts.targetBranch, opts.title, { description: opts.description, removeSourceBranch: true });\n return { url: (created.web_url as string) ?? \"\", created: true };\n }\n}\n\nfunction isNotFound(err: unknown): boolean {\n return (err as { cause?: { response?: { status?: number } } }).cause?.response?.status === 404;\n}\n", "import { GitHubForge } from \"./github.js\";\nimport { GitLabForge } from \"./gitlab.js\";\nimport type { ForgeClient, ForgeType } from \"./types.js\";\n\nexport * from \"./types.js\";\nexport { GitHubForge, GitLabForge };\n\nexport interface ChangeRef {\n type: ForgeType;\n /** Bare web host, lowercased, with port: the identity key. */\n host: string;\n /** \"group/sub/project\" | \"owner/repo\", as written in the URL. */\n projectPath: string;\n number: number;\n}\n\n/**\n * Parses an MR/PR web URL. The URL shape alone tells the forge apart (`/-/merge_requests/N`\n * vs `/pull/N`), so no network probe is needed. `gitlabBaseUrls` are configured instance URLs:\n * a GitLab served under a sub-path (\"https://host/gitlab\") has that prefix stripped.\n */\nexport function parseChangeUrl(input: string, gitlabBaseUrls: string[] = []): ChangeRef | null {\n let url: URL;\n try {\n url = new URL(input.trim());\n } catch {\n return null;\n }\n const host = url.host.toLowerCase();\n const path = url.pathname.replace(/\\/+$/, \"\");\n\n const gh = path.match(/^\\/([^/]+)\\/([^/]+)\\/pull\\/(\\d+)(?:\\/|$)/);\n if (gh) return { type: \"github\", host, projectPath: `${gh[1]}/${gh[2]}`, number: Number(gh[3]) };\n\n const gl = path.match(/^(.+?)\\/-\\/merge_requests\\/(\\d+)(?:\\/|$)/);\n if (!gl) return null;\n let projectPath = gl[1]!;\n const base = gitlabBaseUrls.map((b) => new URL(b)).find((b) => b.host.toLowerCase() === host && b.pathname !== \"/\" && projectPath.startsWith(`${b.pathname.replace(/\\/$/, \"\")}/`));\n if (base) projectPath = projectPath.slice(base.pathname.replace(/\\/$/, \"\").length);\n return { type: \"gitlab\", host, projectPath: decodeURIComponent(projectPath.replace(/^\\//, \"\")), number: Number(gl[2]) };\n}\n\n/** `url` is the GitLab instance URL (may carry a sub-path); ignored for GitHub, which derives its API from `host`. */\nexport function createForge(opts: { type: ForgeType; host: string; url?: string; token: string }): ForgeClient {\n return opts.type === \"github\" ? new GitHubForge({ host: opts.host, token: opts.token }) : new GitLabForge({ url: opts.url ?? `https://${opts.host}`, token: opts.token });\n}\n\nexport interface GitAddress {\n /** Bare web host. For ssh remotes the ssh port is dropped \u2014 it isn't the web port. */\n host: string;\n projectPath: string;\n /** Set when the address was an MR/PR URL. */\n ref?: ChangeRef;\n}\n\n/**\n * Anything a user might paste or `git remote` prints: an MR/PR URL, `https://host/g/p(.git)`,\n * `git@host:g/p.git`, `ssh://git@host:2222/g/p.git`. Paths keep their case (GitHub API is\n * case-insensitive, GitLab paths are lowercase anyway).\n */\nexport function parseGitAddress(input: string, gitlabBaseUrls: string[] = []): GitAddress | null {\n const s = input.trim();\n const ref = parseChangeUrl(s, gitlabBaseUrls);\n if (ref) return { host: ref.host, projectPath: ref.projectPath, ref };\n // scp-like ssh: git@host:group/project.git (no scheme)\n const scp = !s.includes(\"://\") && s.match(/^(?:[^@/\\s]+@)?([^:/\\s]+):(?!\\/)(.+?)(?:\\.git)?\\/?$/);\n if (scp) return { host: scp[1]!.toLowerCase(), projectPath: scp[2]! };\n let url: URL;\n try {\n url = new URL(s);\n } catch {\n return null;\n }\n const path = url.pathname.replace(/^\\/+|\\/+$/g, \"\").replace(/\\.git$/, \"\").replace(/\\/-\\/.*$/, \"\");\n if (!path.includes(\"/\")) return null;\n const host = (url.protocol.startsWith(\"ssh\") || url.protocol === \"git:\" ? url.hostname : url.host).toLowerCase();\n let projectPath = path;\n const base = gitlabBaseUrls.map((b) => new URL(b)).find((b) => b.host.toLowerCase() === host && b.pathname !== \"/\" && `/${path}`.startsWith(`${b.pathname.replace(/\\/$/, \"\")}/`));\n if (base) projectPath = path.slice(base.pathname.replace(/^\\/|\\/$/g, \"\").length + 1);\n return { host, projectPath: decodeURIComponent(projectPath) };\n}\n\n/**\n * Which forge runs on `host`? github.com is known; otherwise GitLab answers /api/v4/version\n * (401 without a token still counts \u2014 it's GitLab saying no), and GitHub Enterprise answers\n * /api/v3/meta without auth. null = couldn't tell (offline, VPN, something else): ask the user.\n */\nexport async function probeForgeType(host: string, fetchImpl: typeof fetch = fetch): Promise<ForgeType | null> {\n if (host === \"github.com\") return \"github\";\n const get = (path: string) => fetchImpl(`https://${host}${path}`, { signal: AbortSignal.timeout(8000), redirect: \"manual\" }).catch(() => null);\n const gl = await get(\"/api/v4/version\");\n if (gl && (gl.status === 200 || gl.status === 401) && gl.headers.get(\"content-type\")?.includes(\"json\")) return \"gitlab\";\n const gh = await get(\"/api/v3/meta\");\n if (gh?.ok && gh.headers.get(\"content-type\")?.includes(\"json\")) return \"github\";\n return null;\n}\n", "import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport yaml from \"js-yaml\";\nimport { z } from \"zod\";\nimport { CONFIG_DIR } from \"../paths.js\";\nimport { getSecret } from \"./secrets.js\";\n\nexport const CONFIG_PATH = join(CONFIG_DIR, \"config.yaml\");\n\nconst ForgeSchema = z.object({\n /** Bare host, the key everything else uses: \"gitlab.com\", \"git.example.com:8443\". */\n host: z.string().min(1),\n type: z.enum([\"gitlab\", \"github\"]),\n /** API base URL; defaults to https://<host>. */\n url: z.string().url().optional(),\n});\n\nconst LlmProfileSchema = z.object({\n name: z.string().min(1),\n /** openai-compatible covers OpenCode Zen, OpenRouter, any /v1/chat/completions gateway. */\n provider: z.enum([\"anthropic\", \"openai-compatible\", \"ollama\"]),\n model: z.string().min(1),\n baseUrl: z.string().url().optional(),\n});\n\nconst SourceSchema = z.object({\n name: z.string().regex(/^[a-z0-9][a-z0-9-]*$/),\n url: z.string().min(1),\n projects: z.array(z.string()).default([]),\n /** Git host, kept only when the address has none (a local path). Projects on other hosts can't use it. */\n host: z.string().optional(),\n /** Sync on its own after each review and when the panel starts. */\n autoSync: z.boolean().default(true),\n});\n\nconst ConfigSchema = z.object({\n forges: z.array(ForgeSchema).default([]),\n defaultForge: z.string().optional(),\n llmProfiles: z.array(LlmProfileSchema).default([]),\n defaultLlmProfile: z.string().optional(),\n jev: z.object({ model: z.string().optional(), threshold: z.number().min(0).max(1).optional(), disabled: z.boolean().optional() }).optional(),\n /** Memory repos: who you are in team data repos \u2014 your records folder. */\n member: z.object({ id: z.string().regex(/^[a-z0-9-]+$/), name: z.string() }).optional(),\n /** Team data repos. `projects` is YOUR list of what you share there (\"host/path\"): a project is\n * only ever exported when both this list and the repo's manifest name it. */\n sources: z.array(SourceSchema).optional(),\n /** Wizard look: Nerd Font icons (\"nerd\") or plain text. Asked once. */\n icons: z.enum([\"nerd\", \"plain\"]).optional(),\n /** Run through npx: the offer to install the `yolont` command was answered (asked once). */\n installOffered: z.boolean().optional(),\n /** Save limit for conventions files (default 300 lines; they go into every review prompt). */\n conventionsMaxLines: z.number().int().min(20).max(2000).optional(),\n /** Change type (src/changeType.ts): off, label (named with the review) or steer (settled first, then type-specific checks). */\n changeType: z.enum([\"off\", \"label\", \"steer\"]).optional(),\n /** Projects (\"host/path\") you chose to keep on your own memory only, so the wizard doesn't ask again. */\n localProjects: z.array(z.string()).optional(),\n});\n\nexport type YolontConfig = z.infer<typeof ConfigSchema>;\nexport type ForgeConfig = z.infer<typeof ForgeSchema>;\nexport type LlmProfile = z.infer<typeof LlmProfileSchema>;\nexport type SourceConfig = z.infer<typeof SourceSchema>;\n\n/** Never contains secrets \u2014 those go through secrets.ts, keyed `forge:<host>` / `llm:<name>` / `jev`. */\nexport function loadConfig(path = CONFIG_PATH): YolontConfig {\n if (!existsSync(path)) return ConfigSchema.parse({});\n const parsed = ConfigSchema.safeParse(yaml.load(readFileSync(path, \"utf8\")) ?? {});\n if (!parsed.success) throw new Error(`Invalid ${path}: ${parsed.error.issues.map((i) => `${i.path.join(\".\")}: ${i.message}`).join(\"; \")}`);\n return parsed.data;\n}\n\nexport function saveConfig(config: YolontConfig, path = CONFIG_PATH): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `# Yolont config \u2014 no secrets here (see \\`yolont config show\\` for where they live).\\n${yaml.dump(ConfigSchema.parse(config))}`);\n}\n\n/** Any of these in the shell selects an LLM provider directly (createLlmProvider), bypassing profiles. */\nexport const LLM_ENV_KEYS = [\"ANTHROPIC_API_KEY\", \"OPENCODE_ZEN_API_KEY\", \"OPENCODE_ZEN_GO_API_KEY\", \"OMNI_API_KEY\", \"OLLAMA_URL\"] as const;\n\nexport const forgeUrl = (f: ForgeConfig) => f.url ?? `https://${f.host}`;\n\n/**\n * Bridge until the forge/LLM code reads config directly (Phase 1/2): fills the env vars\n * the existing code reads, from config + secrets, **only where unset** \u2014 shell env and\n * CI variables always win. Returns the names it filled, for `config show`.\n */\nexport function applyConfigToEnv(config: YolontConfig, env: NodeJS.ProcessEnv = process.env): string[] {\n const filled: string[] = [];\n const put = (k: string, v: string | undefined) => {\n if (v !== undefined && v !== \"\" && !env[k]) {\n env[k] = v;\n filled.push(k);\n }\n };\n\n const forge = config.forges.find((f) => f.host === config.defaultForge) ?? config.forges[0];\n // ponytail: one default forge feeds CI_SERVER_URL; per-MR forge choice comes with `review <url>` in Phase 1.\n if (forge?.type === \"gitlab\") {\n put(\"CI_SERVER_URL\", forgeUrl(forge));\n put(\"GITLAB_API_TOKEN\", getSecret(`forge:${forge.host}`));\n }\n\n const profile = config.llmProfiles.find((p) => p.name === config.defaultLlmProfile) ?? config.llmProfiles[0];\n // createLlmProvider picks the first provider whose key is set, so only fill one \u2014 and\n // only if the shell hasn't already chosen one, or we'd silently override that choice.\n if (profile && !LLM_ENV_KEYS.some((k) => env[k])) {\n const key = getSecret(`llm:${profile.name}`);\n if (profile.provider === \"anthropic\") {\n put(\"ANTHROPIC_API_KEY\", key);\n put(\"ANTHROPIC_MODEL\", profile.model);\n } else if (profile.provider === \"openai-compatible\") {\n put(\"OPENCODE_ZEN_API_KEY\", key);\n put(\"OPENCODE_ZEN_MODEL\", profile.model);\n put(\"OPENCODE_ZEN_BASE_URL\", profile.baseUrl);\n } else {\n put(\"OLLAMA_URL\", profile.baseUrl ?? \"http://localhost:11434\");\n put(\"OLLAMA_MODEL\", profile.model);\n }\n }\n\n put(\"TYPESAFE_API_KEY\", getSecret(\"jev\"));\n put(\"JEV_MODEL\", config.jev?.model);\n put(\"JEV_NOISE_THRESHOLD\", config.jev?.threshold?.toString());\n if (config.jev?.disabled) put(\"JEV_DISABLED\", \"1\");\n lastFilled.set(env, filled);\n return filled;\n}\n\nconst lastFilled = new WeakMap<NodeJS.ProcessEnv, string[]>();\n\n/** Env vars the last applyConfigToEnv filled \u2014 anything else set was set by the user's shell. */\nexport const configFilledKeys = (env: NodeJS.ProcessEnv = process.env): string[] => lastFilled.get(env) ?? [];\n\n/** After the wizard changes config: drop what the last apply filled (never shell-set vars), then apply again. */\nexport function reapplyConfigToEnv(env: NodeJS.ProcessEnv = process.env): string[] {\n for (const k of lastFilled.get(env) ?? []) delete env[k];\n return applyConfigToEnv(loadConfig(), env);\n}\n", "import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from \"node:crypto\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport { CONFIG_DIR } from \"../paths.js\";\n\n/**\n * Secret names: `forge:<host>` (git token), `llm:<profile>` (LLM key), `jev` (typesafe.ai).\n *\n * Backend: the OS keychain (macOS Keychain, Windows Credential Manager, Linux Secret\n * Service) when it works; otherwise ~/.config/yolont/credentials.json, mode 0600.\n * That file is AES-256-GCM encrypted when YOLONT_PASSPHRASE is set. Without a passphrase it\n * stays plaintext: a key kept on the same disk would be obfuscation, not protection.\n * Reads check the keychain, then the file, so a secret saved while the keychain was\n * unavailable (e.g. over SSH) is still found later.\n */\nconst SERVICE = \"yolont\";\n/** Keychain service from before the rename: read once and copied over. */\nconst OLD_SERVICE = \"ethos\";\nexport const CREDENTIALS_PATH = join(CONFIG_DIR, \"credentials.json\");\n\ninterface KeyringEntry {\n getPassword(): string | null | undefined;\n setPassword(v: string): void;\n deletePassword(): boolean | void;\n}\ntype EntryCtor = new (service: string, account: string) => KeyringEntry;\n\nlet keyringCtor: EntryCtor | null | undefined;\n/** null when the native module is missing or there's no keychain service (headless Linux, WSL, CI). */\nfunction keyring(): EntryCtor | null {\n if (keyringCtor !== undefined) return keyringCtor;\n keyringCtor = null;\n if (process.env.YOLONT_NO_KEYCHAIN === \"1\") return null;\n try {\n const { Entry } = createRequire(import.meta.url)(\"@napi-rs/keyring\") as { Entry: EntryCtor };\n new Entry(SERVICE, \"__probe__\").getPassword(); // throws when no Secret Service is running\n keyringCtor = Entry;\n } catch {\n /* fall back to file */\n }\n return keyringCtor;\n}\n\nexport function secretBackend(): \"keychain\" | \"file (encrypted)\" | \"file (plaintext 0600)\" {\n if (keyring()) return \"keychain\";\n return process.env.YOLONT_PASSPHRASE ? \"file (encrypted)\" : \"file (plaintext 0600)\";\n}\n\n// ---- file backend ----\n\ntype FileShape = { v: 1; secrets: Record<string, string> } | { v: 1; enc: { salt: string; iv: string; tag: string; data: string } };\n\nfunction deriveKey(passphrase: string, salt: Buffer): Buffer {\n return scryptSync(passphrase, salt, 32);\n}\n\nfunction readFileSecrets(): Record<string, string> {\n if (!existsSync(CREDENTIALS_PATH)) return {};\n const raw = JSON.parse(readFileSync(CREDENTIALS_PATH, \"utf8\")) as FileShape;\n if (\"secrets\" in raw) return raw.secrets;\n const passphrase = process.env.YOLONT_PASSPHRASE;\n if (!passphrase) throw new Error(`${CREDENTIALS_PATH} is encrypted \u2014 set YOLONT_PASSPHRASE to read it.`);\n const d = createDecipheriv(\"aes-256-gcm\", deriveKey(passphrase, Buffer.from(raw.enc.salt, \"base64\")), Buffer.from(raw.enc.iv, \"base64\"));\n d.setAuthTag(Buffer.from(raw.enc.tag, \"base64\"));\n try {\n return JSON.parse(Buffer.concat([d.update(Buffer.from(raw.enc.data, \"base64\")), d.final()]).toString(\"utf8\"));\n } catch {\n throw new Error(`Could not decrypt ${CREDENTIALS_PATH} \u2014 wrong YOLONT_PASSPHRASE?`);\n }\n}\n\nfunction writeFileSecrets(secrets: Record<string, string>): void {\n mkdirSync(dirname(CREDENTIALS_PATH), { recursive: true });\n let body: FileShape = { v: 1, secrets };\n const passphrase = process.env.YOLONT_PASSPHRASE;\n if (passphrase) {\n const salt = randomBytes(16);\n const iv = randomBytes(12);\n const c = createCipheriv(\"aes-256-gcm\", deriveKey(passphrase, salt), iv);\n const data = Buffer.concat([c.update(JSON.stringify(secrets), \"utf8\"), c.final()]);\n body = { v: 1, enc: { salt: salt.toString(\"base64\"), iv: iv.toString(\"base64\"), tag: c.getAuthTag().toString(\"base64\"), data: data.toString(\"base64\") } };\n }\n writeFileSync(CREDENTIALS_PATH, `${JSON.stringify(body, null, 2)}\\n`, { mode: 0o600 });\n chmodSync(CREDENTIALS_PATH, 0o600); // mode only applies on create\n}\n\n// ---- public API ----\n\nexport function getSecret(name: string): string | undefined {\n const Entry = keyring();\n if (Entry) {\n const v = new Entry(SERVICE, name).getPassword();\n if (v) return v;\n const old = (() => {\n try {\n return new Entry(OLD_SERVICE, name).getPassword();\n } catch {\n return null;\n }\n })();\n if (old) {\n new Entry(SERVICE, name).setPassword(old);\n return old;\n }\n }\n return readFileSecrets()[name];\n}\n\nexport function setSecret(name: string, value: string): void {\n const Entry = keyring();\n if (Entry) {\n new Entry(SERVICE, name).setPassword(value);\n // Don't leave an older copy behind in the file that a later read could shadow.\n const file = readFileSecrets();\n if (name in file) {\n delete file[name];\n writeFileSecrets(file);\n }\n return;\n }\n writeFileSecrets({ ...readFileSecrets(), [name]: value });\n}\n\nexport function deleteSecret(name: string): void {\n const Entry = keyring();\n if (Entry) {\n for (const service of [SERVICE, OLD_SERVICE]) {\n try {\n new Entry(service, name).deletePassword();\n } catch {\n /* not there */\n }\n }\n }\n const file = readFileSecrets();\n if (name in file) {\n delete file[name];\n writeFileSecrets(file);\n }\n}\n\n/** \"glpat-abc\u20263f2a\" -> \"glpa\u2022\u2022\u2022\u20223f2a\" \u2014 for display only. */\nexport function maskSecret(v: string | undefined): string {\n if (!v) return \"(not set)\";\n return v.length <= 8 ? \"\u2022\u2022\u2022\u2022\" : `${v.slice(0, 4)}\u2022\u2022\u2022\u2022${v.slice(-4)}`;\n}\n", "import { createForge, parseChangeUrl, type ChangeRef, type ForgeClient, type ForgeType } from \"../src/forge/index.js\";\nimport { forgeUrl, loadConfig, saveConfig } from \"./config/config.js\";\nimport { getSecret } from \"./config/secrets.js\";\nimport { bareHost } from \"./paths.js\";\n\n/**\n * Env tokens are bound to the host they were issued for: GITLAB_API_TOKEN only for\n * CI_SERVER_URL's host, GITHUB_TOKEN/GH_TOKEN only for github.com. Never hand one host's token\n * to another: \"github\" is detected from the URL's path shape, so any host can claim it, and\n * a pasted https://evil.example/a/b/pull/1 must not receive the github.com token. A GitHub\n * Enterprise host needs its own `forge:<host>` secret.\n */\nfunction envToken(type: ForgeType, host: string, env: NodeJS.ProcessEnv): string | undefined {\n if (type === \"gitlab\") return env.CI_SERVER_URL && bareHost(env.CI_SERVER_URL) === host ? env.GITLAB_API_TOKEN : undefined;\n return host === \"github.com\" ? env.GITHUB_TOKEN || env.GH_TOKEN || undefined : undefined;\n}\n\n/** Saved secret first, then the env token bound to this host (if any). */\nexport function forgeToken(host: string, type: ForgeType, env: NodeJS.ProcessEnv = process.env): string | undefined {\n return getSecret(`forge:${host}`) ?? envToken(type, host, env);\n}\n\n/** A client for `host`. `typeHint` (from a parsed URL) lets a new host work without prior setup; its type is then saved. */\nexport function forgeFor(hostOrUrl: string, typeHint?: ForgeType, env: NodeJS.ProcessEnv = process.env): ForgeClient {\n const host = bareHost(hostOrUrl);\n const config = loadConfig();\n const saved = config.forges.find((f) => f.host === host);\n const ciHost = env.CI_SERVER_URL ? bareHost(env.CI_SERVER_URL) : undefined;\n const type = saved?.type ?? typeHint ?? (host === \"github.com\" ? \"github\" : host === ciHost ? \"gitlab\" : undefined);\n if (!type) throw new Error(`Unknown git host ${host} \u2014 pass a full MR/PR URL so its type can be detected.`);\n\n const token = forgeToken(host, type, env);\n if (!token) throw new Error(`No token for ${host}. Save one with \\`yolont config set-secret forge:${host}\\`${host === \"github.com\" ? \" (or set GITHUB_TOKEN)\" : \"\"}.`);\n\n if (!saved) {\n // Remember host\u2192type only; tokens are never saved implicitly.\n config.forges.push({ host, type });\n config.defaultForge ??= host;\n saveConfig(config);\n }\n const url = saved ? forgeUrl(saved) : host === ciHost ? env.CI_SERVER_URL : undefined;\n return createForge({ type, host, url, token });\n}\n\n/** The forge `<project-id> <mr-iid>` style commands use: config default, else CI_SERVER_URL. */\nexport function defaultForgeHost(env: NodeJS.ProcessEnv = process.env): string {\n const host = loadConfig().defaultForge ?? (env.CI_SERVER_URL ? bareHost(env.CI_SERVER_URL) : undefined);\n if (!host) throw new Error(\"No default git host \u2014 use an MR/PR URL, or run `yolont config import-env`.\");\n return host;\n}\n\n/** Parses an MR/PR URL, honoring configured GitLab sub-path installs. */\nexport function parseChange(url: string): ChangeRef | null {\n return parseChangeUrl(url, loadConfig().forges.filter((f) => f.type === \"gitlab\" && f.url).map(forgeUrl));\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { ChangeTypeSchema, type ChangeType } from \"../../src/changeType.js\";\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { z } from \"zod\";\nimport { refreshScores, scoreFromBase, upsertFindingsForScore, upsertMergeRequest, upsertProject, type ScoreBase } from \"../db/repo.js\";\n\n/**\n * Memory repos, file side. A source folder holds one JSON file per record:\n *\n * projects/<host>/<path>/records/<member>/<uid>.json\n *\n * Every member writes only their own folder, so git never has to merge two people's edits.\n * Export mirrors this DB's own rows (origin NULL) of bound projects into the member's folder;\n * import upserts everyone else's files by uid (origin = the source's name).\n */\n\n/** \"host/group/project\", lowercased: how projects are named in manifests and config. */\nexport type ProjectKey = string;\nexport const projectKey = (host: string, path: string): ProjectKey => `${host}/${path}`.toLowerCase();\n\n/** Folder of one project inside a source. ':' (a port) is illegal in Windows paths. */\nexport function sourceProjectDir(sourceDir: string, key: ProjectKey): string {\n const [host, ...path] = key.split(\"/\");\n return join(sourceDir, \"projects\", host!.replace(/:/g, \"_\"), ...path);\n}\n\nconst ProjectRef = z.object({ host: z.string().min(1), id: z.string().min(1), path: z.string().min(1), name: z.string() });\nconst MrRef = z.object({\n project: ProjectRef,\n iid: z.number().int().positive(),\n author: z.string().min(1),\n sha: z.string(),\n title: z.string(),\n mergedAt: z.string().nullable(),\n source: z.enum([\"backfill\", \"live\"]),\n});\nconst FindingRef = z.object({ file: z.string().nullable(), line: z.number().int().nullable(), issue: z.string() });\nconst Base = { uid: z.string().uuid(), by: z.string().min(1) };\n\nconst Review = z.object({\n ...Base,\n kind: z.literal(\"review\"),\n mr: MrRef,\n scoredAt: z.string(),\n source: z.enum([\"llm_backfill\", \"llm_live\"]),\n finalScore: z.number(),\n changeType: ChangeTypeSchema.nullable().optional().catch(null),\n categoryScores: z.record(z.number()),\n findings: z.array(z.object({ category: z.string().optional(), severity: z.string(), issue: z.string(), file: z.string().optional(), line: z.number().optional() }).passthrough()),\n modelUsed: z.string().nullable(),\n volumeFactor: z.number(),\n base: z.unknown().nullable(),\n zoneHits: z.array(\n z.object({\n zoneId: z.string(),\n level: z.enum([\"red\", \"amber\", \"green\"]),\n files: z.array(z.string()),\n impact: z.enum([\"none\", \"low\", \"high\"]).nullable(),\n verdict: z.string().nullable(),\n vote: z.enum([\"up\", \"down\"]).nullable(),\n voteNote: z.string().nullable(),\n createdAt: z.string(),\n }),\n ),\n});\nconst Correction = z.object({\n ...Base,\n kind: z.literal(\"correction\"),\n mr: MrRef,\n category: z.string().nullable(),\n originalScore: z.number(),\n correctedScore: z.number(),\n reason: z.string(),\n correctedNote: z.string().nullable(),\n createdAt: z.string(),\n});\nconst Insight = z.object({\n ...Base,\n kind: z.literal(\"insight\"),\n host: z.string().min(1),\n /** NULL = every project on this host. */\n project: ProjectRef.nullable(),\n author: z.string().nullable(),\n category: z.string().nullable(),\n text: z.string().min(1),\n evidence: z.array(MrRef),\n createdAt: z.string(),\n});\nconst Vote = z.object({\n ...Base,\n kind: z.literal(\"vote\"),\n mr: MrRef,\n finding: FindingRef,\n vote: z.enum([\"up\", \"down\"]),\n note: z.string(),\n correctionUid: z.string().nullable(),\n insightUid: z.string().nullable(),\n createdAt: z.string(),\n});\nconst Tag = z.object({ ...Base, kind: z.literal(\"tag\"), mr: MrRef, finding: FindingRef, tag: z.string(), createdAt: z.string() });\n\nexport const SyncRecord = z.discriminatedUnion(\"kind\", [Review, Correction, Insight, Vote, Tag]);\nexport type SyncRecord = z.infer<typeof SyncRecord>;\ntype MrRef = z.infer<typeof MrRef>;\n\nexport interface SyncScope {\n /** Folder of the source's git clone. */\n dir: string;\n /** Source name; imported rows get it as `origin`. */\n name: string;\n /** This member's id: their records folder. */\n member: string;\n /** Projects to sync: the ones you chose this memory repo for (source.ts projectOwners). */\n projects: Set<ProjectKey>;\n}\n\n// ---------------------------------------------------------------- export\n\ntype MrRow = { mr_id: number; mr_iid: number; author_username: string; sha: string; title: string; merged_at: string | null; mr_source: \"backfill\" | \"live\"; forge_host: string; forge_project_id: string; path_with_namespace: string; project_name: string };\nconst MR_COLS = `mr.id AS mr_id, mr.mr_iid, mr.author_username, mr.sha, mr.title, mr.merged_at, mr.source AS mr_source,\n p.forge_host, p.forge_project_id, p.path_with_namespace, p.name AS project_name`;\n\nconst mrRef = (r: MrRow): MrRef => ({\n project: { host: r.forge_host, id: r.forge_project_id, path: r.path_with_namespace, name: r.project_name },\n iid: r.mr_iid,\n author: r.author_username,\n sha: r.sha,\n title: r.title,\n mergedAt: r.merged_at,\n source: r.mr_source,\n});\n\n/** Stable id for a row, assigned the first time it's shared. */\nfunction uidFor(db: DatabaseSync, table: string, id: number, uid: string | null): string {\n if (uid) return uid;\n const next = randomUUID();\n db.prepare(`UPDATE ${table} SET uid = ? WHERE id = ?`).run(next, id);\n return next;\n}\n\n/** This DB's own records for the scope's projects. Assigns uids to rows shared for the first time. */\nexport function collectOwnRecords(db: DatabaseSync, scope: SyncScope): { key: ProjectKey; record: SyncRecord }[] {\n const out: { key: ProjectKey; record: SyncRecord }[] = [];\n const bound = (r: MrRow) => scope.projects.has(projectKey(r.forge_host, r.path_with_namespace));\n const keyOf = (r: MrRow) => projectKey(r.forge_host, r.path_with_namespace);\n const by = scope.member;\n\n const scores = db\n .prepare(`SELECT s.*, ${MR_COLS} FROM scores s JOIN merge_requests mr ON mr.id = s.merge_request_id JOIN projects p ON p.id = mr.project_id WHERE s.origin IS NULL AND p.forge_host IS NOT NULL`)\n .all() as unknown as (MrRow & { id: number; uid: string | null; scored_at: string; source: \"llm_backfill\" | \"llm_live\"; final_score: number; category_scores_json: string; findings_json: string; model_used: string | null; volume_factor: number; base_json: string | null; change_type: string | null })[];\n for (const s of scores.filter(bound)) {\n // The machine score, before anyone's corrections: those are their own records, and every\n // machine recomputes the total. So a teammate's correction never rewrites your review file.\n const machine = s.base_json ? scoreFromBase(JSON.parse(s.base_json) as ScoreBase, []) : { finalScore: s.final_score, categoryScores: JSON.parse(s.category_scores_json) as Record<string, number> };\n const hits = db.prepare(`SELECT * FROM zone_hits WHERE merge_request_id = ? ORDER BY zone_id`).all(s.mr_id) as unknown as { zone_id: string; level: \"red\" | \"amber\" | \"green\"; files_json: string; impact: \"none\" | \"low\" | \"high\" | null; verdict: string | null; vote: \"up\" | \"down\" | null; vote_note: string | null; created_at: string }[];\n out.push({\n key: keyOf(s),\n record: {\n kind: \"review\",\n uid: uidFor(db, \"scores\", s.id, s.uid),\n by,\n mr: mrRef(s),\n scoredAt: s.scored_at,\n source: s.source,\n finalScore: machine.finalScore,\n // Only when set: an untyped review keeps the exact file it had before this field existed.\n ...(s.change_type ? { changeType: s.change_type as ChangeType } : {}),\n categoryScores: machine.categoryScores,\n findings: JSON.parse(s.findings_json),\n modelUsed: s.model_used,\n volumeFactor: s.volume_factor,\n base: s.base_json ? JSON.parse(s.base_json) : null,\n zoneHits: hits.map((h) => ({ zoneId: h.zone_id, level: h.level, files: JSON.parse(h.files_json), impact: h.impact, verdict: h.verdict, vote: h.vote, voteNote: h.vote_note, createdAt: h.created_at })),\n },\n });\n }\n\n const corrections = db\n .prepare(`SELECT c.*, ${MR_COLS} FROM corrections c JOIN merge_requests mr ON mr.id = c.merge_request_id JOIN projects p ON p.id = mr.project_id WHERE c.origin IS NULL AND p.forge_host IS NOT NULL`)\n .all() as unknown as (MrRow & { id: number; uid: string | null; category: string | null; original_score: number; corrected_score: number; reason: string; corrected_note: string | null; created_at: string })[];\n const correctionUids = new Map<number, string>();\n for (const c of corrections.filter(bound)) {\n const uid = uidFor(db, \"corrections\", c.id, c.uid);\n correctionUids.set(c.id, uid);\n out.push({ key: keyOf(c), record: { kind: \"correction\", uid, by, mr: mrRef(c), category: c.category, originalScore: c.original_score, correctedScore: c.corrected_score, reason: c.reason, correctedNote: c.corrected_note, createdAt: c.created_at } });\n }\n\n // An insight goes with its project, or \u2014 when it's for every project on a host \u2014 only if all\n // its evidence comes from this source's projects (it's then filed under the first of them).\n const insights = db.prepare(`SELECT * FROM insights WHERE origin IS NULL AND host IS NOT NULL`).all() as unknown as { id: number; uid: string | null; author_username: string | null; host: string; project_id: number | null; category: string | null; insight_text: string; evidence_mr_ids_json: string; created_at: string }[];\n const mrById = db.prepare(`SELECT ${MR_COLS} FROM merge_requests mr JOIN projects p ON p.id = mr.project_id WHERE mr.id = ?`);\n const projectById = db.prepare(`SELECT forge_host, forge_project_id, path_with_namespace, name FROM projects WHERE id = ?`);\n const insightUids = new Map<number, string>();\n for (const i of insights) {\n const evidence = (JSON.parse(i.evidence_mr_ids_json) as number[]).map((id) => mrById.get(id) as unknown as MrRow | undefined).filter((r): r is MrRow => !!r);\n let key: ProjectKey | undefined;\n let project: z.infer<typeof ProjectRef> | null = null;\n if (i.project_id != null) {\n const p = projectById.get(i.project_id) as unknown as { forge_host: string | null; forge_project_id: string; path_with_namespace: string; name: string } | undefined;\n if (!p?.forge_host) continue;\n key = projectKey(p.forge_host, p.path_with_namespace);\n project = { host: p.forge_host, id: p.forge_project_id, path: p.path_with_namespace, name: p.name };\n } else if (evidence.length > 0 && evidence.every(bound)) {\n key = keyOf(evidence[0]!);\n }\n if (!key || !scope.projects.has(key)) continue;\n const uid = uidFor(db, \"insights\", i.id, i.uid);\n insightUids.set(i.id, uid);\n out.push({ key, record: { kind: \"insight\", uid, by, host: i.host, project, author: i.author_username, category: i.category, text: i.insight_text, evidence: evidence.map(mrRef), createdAt: i.created_at } });\n }\n\n const votes = db\n .prepare(`SELECT v.*, f.file, f.line, f.issue, ${MR_COLS} FROM finding_votes v JOIN findings f ON f.id = v.finding_id JOIN merge_requests mr ON mr.id = f.merge_request_id JOIN projects p ON p.id = mr.project_id WHERE v.origin IS NULL AND p.forge_host IS NOT NULL`)\n .all() as unknown as (MrRow & { id: number; uid: string | null; vote: \"up\" | \"down\"; note: string; correction_id: number | null; insight_id: number | null; created_at: string; file: string | null; line: number | null; issue: string })[];\n for (const v of votes.filter(bound)) {\n out.push({\n key: keyOf(v),\n record: {\n kind: \"vote\",\n uid: uidFor(db, \"finding_votes\", v.id, v.uid),\n by,\n mr: mrRef(v),\n finding: { file: v.file, line: v.line, issue: v.issue },\n vote: v.vote,\n note: v.note,\n correctionUid: v.correction_id != null ? (correctionUids.get(v.correction_id) ?? null) : null,\n insightUid: v.insight_id != null ? (insightUids.get(v.insight_id) ?? null) : null,\n createdAt: v.created_at,\n },\n });\n }\n\n const tags = db\n .prepare(`SELECT t.*, f.file, f.line, f.issue, ${MR_COLS} FROM finding_tags t JOIN findings f ON f.id = t.finding_id JOIN merge_requests mr ON mr.id = f.merge_request_id JOIN projects p ON p.id = mr.project_id WHERE t.origin IS NULL AND p.forge_host IS NOT NULL`)\n .all() as unknown as (MrRow & { id: number; uid: string | null; tag: string; created_at: string; file: string | null; line: number | null; issue: string })[];\n for (const t of tags.filter(bound)) {\n out.push({ key: keyOf(t), record: { kind: \"tag\", uid: uidFor(db, \"finding_tags\", t.id, t.uid), by, mr: mrRef(t), finding: { file: t.file, line: t.line, issue: t.issue }, tag: t.tag, createdAt: t.created_at } });\n }\n return out;\n}\n\nexport interface ExportResult {\n written: string[];\n deleted: string[];\n}\n\n/**\n * Mirrors this DB's own records into the member's folders. A file is only deleted when this DB\n * once wrote it (sync_exported) and the row is gone \u2014 so a fresh DB never wipes what you shared.\n * `dryRun` counts without touching anything (uids still get assigned).\n */\nexport function exportRecords(db: DatabaseSync, scope: SyncScope, dryRun = false): ExportResult {\n const written: string[] = [];\n const deleted: string[] = [];\n const own = collectOwnRecords(db, scope);\n const live = new Set<string>();\n const remember = db.prepare(`INSERT INTO sync_exported (uid, source, path) VALUES (?, ?, ?) ON CONFLICT (uid) DO UPDATE SET source = excluded.source, path = excluded.path`);\n for (const { key, record } of own) {\n const rel = join(relProjectDir(key), \"records\", scope.member, `${record.uid}.json`);\n live.add(record.uid);\n const file = join(scope.dir, rel);\n const text = `${JSON.stringify(record, null, 2)}\\n`;\n if (existsSync(file) && readFileSync(file, \"utf8\") === text) continue;\n written.push(rel);\n if (dryRun) continue;\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, text);\n remember.run(record.uid, scope.name, rel);\n }\n const exported = db.prepare(`SELECT uid, path FROM sync_exported WHERE source = ?`).all(scope.name) as unknown as { uid: string; path: string }[];\n for (const e of exported) {\n if (live.has(e.uid) || ownRowExists(db, e.uid)) continue; // still here, maybe just unbound\n deleted.push(e.path);\n if (dryRun) continue;\n rmSync(join(scope.dir, e.path), { force: true });\n db.prepare(`DELETE FROM sync_exported WHERE uid = ?`).run(e.uid);\n }\n return { written, deleted };\n}\n\nfunction relProjectDir(key: ProjectKey): string {\n return sourceProjectDir(\"\", key).replace(/^[/\\\\]/, \"\");\n}\n\nfunction ownRowExists(db: DatabaseSync, uid: string): boolean {\n return [\"scores\", \"corrections\", \"insights\", \"finding_votes\", \"finding_tags\"].some((t) => !!db.prepare(`SELECT 1 FROM ${t} WHERE uid = ? AND origin IS NULL`).get(uid));\n}\n\n// ---------------------------------------------------------------- import\n\nexport interface ImportResult {\n imported: number;\n /** Own records found in the source but missing here (e.g. a fresh DB), restored as own rows. */\n restored: number;\n removed: number;\n /** Files that failed validation or don't belong where they sit. */\n rejected: string[];\n}\n\n/**\n * Reads every record of the scope's projects. Others' records become rows with origin = the\n * source; this member's own files restore rows a fresh DB lacks. With `prune`, rows imported\n * from this source whose file is gone are deleted \u2014 pass it only after a clean pull.\n */\nexport function importRecords(db: DatabaseSync, scope: SyncScope, prune = false): ImportResult {\n const result: ImportResult = { imported: 0, restored: 0, removed: 0, rejected: [] };\n const seen = new Set<string>();\n const files: { rel: string; record: SyncRecord; own: boolean }[] = [];\n\n for (const key of scope.projects) {\n const recordsDir = join(sourceProjectDir(scope.dir, key), \"records\");\n if (!existsSync(recordsDir)) continue;\n for (const member of readdirSync(recordsDir)) {\n const memberDir = join(recordsDir, member);\n for (const name of readdirSync(memberDir).filter((f) => f.endsWith(\".json\"))) {\n const rel = join(relProjectDir(key), \"records\", member, name);\n const parsed = (() => {\n try {\n return SyncRecord.safeParse(JSON.parse(readFileSync(join(memberDir, name), \"utf8\")));\n } catch {\n return null;\n }\n })();\n // A record must sit in its own project's folder, under its author's member folder.\n if (!parsed?.success || `${parsed.data.uid}.json` !== name || parsed.data.by !== member || !belongsTo(parsed.data, key)) {\n result.rejected.push(rel);\n continue;\n }\n files.push({ rel, record: parsed.data, own: member === scope.member });\n }\n }\n }\n\n // Order matters: votes point at corrections and insights; findings come from reviews.\n const order = [\"review\", \"correction\", \"insight\", \"vote\", \"tag\"];\n files.sort((a, b) => order.indexOf(a.record.kind) - order.indexOf(b.record.kind));\n const remember = db.prepare(`INSERT INTO sync_exported (uid, source, path) VALUES (?, ?, ?) ON CONFLICT (uid) DO NOTHING`);\n db.exec(\"BEGIN\");\n try {\n for (const f of files) {\n seen.add(f.record.uid);\n if (f.own) {\n // Written by this DB and since deleted here: the deletion is waiting for the next export,\n // so don't bring it back (a fresh DB has no sync_exported rows and restores everything).\n if (db.prepare(`SELECT 1 FROM sync_exported WHERE uid = ?`).get(f.record.uid)) continue;\n if (findByUid(db, f.record) === undefined && applyRecord(db, f.record, null)) {\n remember.run(f.record.uid, scope.name, f.rel);\n result.restored++;\n }\n continue;\n }\n if (applyRecord(db, f.record, scope.name)) result.imported++;\n }\n if (prune) result.removed = pruneMissing(db, scope.name, seen);\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw err;\n }\n return result;\n}\n\nfunction belongsTo(r: SyncRecord, key: ProjectKey): boolean {\n if (r.kind === \"insight\") {\n if (r.project) return projectKey(r.project.host, r.project.path) === key;\n return key.startsWith(`${r.host.toLowerCase()}/`) && r.evidence.every((e) => e.project.host.toLowerCase() === r.host.toLowerCase());\n }\n return projectKey(r.mr.project.host, r.mr.project.path) === key;\n}\n\nconst TABLE: Record<SyncRecord[\"kind\"], string> = { review: \"scores\", correction: \"corrections\", insight: \"insights\", vote: \"finding_votes\", tag: \"finding_tags\" };\n\nfunction findByUid(db: DatabaseSync, r: SyncRecord): { id: number; origin: string | null } | undefined {\n return db.prepare(`SELECT id, origin FROM ${TABLE[r.kind]} WHERE uid = ?`).get(r.uid) as unknown as { id: number; origin: string | null } | undefined;\n}\n\nfunction ensureMr(db: DatabaseSync, m: MrRef): number {\n const projectId = upsertProject(db, { host: m.project.host, id: m.project.id, pathWithNamespace: m.project.path, name: m.project.name });\n const existing = db.prepare(`SELECT id FROM merge_requests WHERE project_id = ? AND mr_iid = ?`).get(projectId, m.iid) as unknown as { id: number } | undefined;\n return existing?.id ?? upsertMergeRequest(db, { projectId, mrIid: m.iid, authorUsername: m.author, sha: m.sha, title: m.title, mergedAt: m.mergedAt, source: m.source }).id;\n}\n\nfunction findingId(db: DatabaseSync, mrId: number, f: z.infer<typeof FindingRef>): number | undefined {\n const row = db.prepare(`SELECT id FROM findings WHERE merge_request_id = ? AND file IS ? AND line IS ? AND issue = ?`).get(mrId, f.file, f.line, f.issue) as unknown as { id: number } | undefined;\n return row?.id;\n}\n\n/** Inserts or updates the row for one record. `origin` NULL = restoring this member's own row. Returns whether anything changed. */\nfunction applyRecord(db: DatabaseSync, r: SyncRecord, origin: string | null): boolean {\n const existing = findByUid(db, r);\n if (existing && existing.origin !== origin) return false; // own row vs someone's file: never overwrite yours\n switch (r.kind) {\n case \"review\": {\n const mrId = ensureMr(db, r.mr);\n let target = existing?.id;\n if (target === undefined) {\n // One score per MR and source across the team: the newest review wins.\n const current = db.prepare(`SELECT id, scored_at FROM scores WHERE merge_request_id = ? AND source = ?`).get(mrId, r.source) as unknown as { id: number; scored_at: string } | undefined;\n if (current && current.scored_at >= r.scoredAt) return false;\n target = current?.id;\n }\n const values = [r.scoredAt, r.finalScore, JSON.stringify(r.categoryScores), JSON.stringify(r.findings), r.modelUsed, r.volumeFactor, r.base == null ? null : JSON.stringify(r.base), r.changeType ?? null, r.uid, origin];\n if (target === undefined) {\n db.prepare(`INSERT INTO scores (merge_request_id, source, scored_at, final_score, category_scores_json, findings_json, model_used, volume_factor, base_json, change_type, uid, origin) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(mrId, r.source, ...values);\n } else {\n const before = db.prepare(`SELECT scored_at, findings_json, base_json, change_type FROM scores WHERE id = ?`).get(target) as unknown as { scored_at: string; findings_json: string; base_json: string | null; change_type: string | null };\n if (existing && before.scored_at === r.scoredAt && before.findings_json === values[3] && before.base_json === values[6] && before.change_type === values[7]) return false;\n db.prepare(`UPDATE scores SET scored_at = ?, final_score = ?, category_scores_json = ?, findings_json = ?, model_used = ?, volume_factor = ?, base_json = ?, change_type = ?, uid = ?, origin = ? WHERE id = ?`).run(...values, target);\n }\n db.prepare(`DELETE FROM zone_hits WHERE merge_request_id = ?`).run(mrId);\n const hit = db.prepare(`INSERT INTO zone_hits (merge_request_id, zone_id, level, files_json, impact, verdict, vote, vote_note, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);\n for (const h of r.zoneHits) hit.run(mrId, h.zoneId, h.level, JSON.stringify(h.files), h.impact, h.verdict, h.vote, h.voteNote, h.createdAt);\n upsertFindingsForScore(db, mrId, r.findings);\n refreshScores(db, mrId);\n return true;\n }\n case \"correction\": {\n const mrId = ensureMr(db, r.mr);\n const values = [r.category, r.originalScore, r.correctedScore, r.reason, r.correctedNote, r.createdAt];\n if (existing) {\n const changed = db.prepare(`UPDATE corrections SET category = ?, original_score = ?, corrected_score = ?, reason = ?, corrected_note = ?, created_at = ? WHERE id = ? AND NOT (category IS ? AND original_score = ? AND corrected_score = ? AND reason = ? AND corrected_note IS ? AND created_at = ?)`).run(...values, existing.id, ...values).changes;\n if (!changed) return false;\n } else {\n // created_at as recorded: refreshScores only applies corrections made after the score.\n db.prepare(`INSERT INTO corrections (merge_request_id, category, original_score, corrected_score, reason, corrected_note, created_at, uid, origin) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(mrId, ...values, r.uid, origin);\n }\n refreshScores(db, mrId);\n return true;\n }\n case \"insight\": {\n const projectId = r.project ? upsertProject(db, { host: r.project.host, id: r.project.id, pathWithNamespace: r.project.path, name: r.project.name }) : null;\n const evidence = r.evidence.map((e) => ensureMr(db, e));\n const values = [r.author, r.host, projectId, r.category, r.text, JSON.stringify(evidence), r.createdAt];\n if (existing) {\n return !!db.prepare(`UPDATE insights SET author_username = ?, host = ?, project_id = ?, category = ?, insight_text = ?, evidence_mr_ids_json = ?, created_at = ? WHERE id = ? AND NOT (author_username IS ? AND host IS ? AND project_id IS ? AND category IS ? AND insight_text = ? AND evidence_mr_ids_json = ? AND created_at = ?)`).run(...values, existing.id, ...values).changes;\n }\n db.prepare(`INSERT INTO insights (author_username, host, project_id, category, insight_text, evidence_mr_ids_json, created_at, uid, origin) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(...values, r.uid, origin);\n return true;\n }\n case \"vote\": {\n if (existing) return false; // a vote is replaced by unvoting, which deletes the file\n const fid = findingId(db, ensureMr(db, r.mr), r.finding);\n // One vote per finding: whoever voted first keeps it.\n if (fid === undefined || db.prepare(`SELECT 1 FROM finding_votes WHERE finding_id = ?`).get(fid)) return false;\n const idOf = (table: string, uid: string | null) => (uid ? ((db.prepare(`SELECT id FROM ${table} WHERE uid = ?`).get(uid) as { id: number } | undefined)?.id ?? null) : null);\n db.prepare(`INSERT INTO finding_votes (finding_id, vote, note, correction_id, insight_id, created_at, uid, origin) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(fid, r.vote, r.note, idOf(\"corrections\", r.correctionUid), idOf(\"insights\", r.insightUid), r.createdAt, r.uid, origin);\n return true;\n }\n case \"tag\": {\n if (existing) return false;\n const fid = findingId(db, ensureMr(db, r.mr), r.finding);\n if (fid === undefined) return false;\n return !!db.prepare(`INSERT INTO finding_tags (finding_id, tag, created_at, uid, origin) VALUES (?, ?, ?, ?, ?) ON CONFLICT (finding_id, tag) DO NOTHING`).run(fid, r.tag, r.createdAt, r.uid, origin).changes;\n }\n }\n}\n\n/** Removes rows imported from `source` whose file no longer exists there. */\nfunction pruneMissing(db: DatabaseSync, source: string, seen: Set<string>): number {\n let removed = 0;\n for (const table of [\"finding_tags\", \"finding_votes\", \"insights\", \"corrections\", \"scores\"]) {\n const rows = db.prepare(`SELECT id, uid FROM ${table} WHERE origin = ?`).all(source) as unknown as { id: number; uid: string }[];\n for (const row of rows.filter((r) => !seen.has(r.uid))) {\n const mr = table === \"corrections\" ? (db.prepare(`SELECT merge_request_id FROM corrections WHERE id = ?`).get(row.id) as { merge_request_id: number }).merge_request_id : null;\n if (table === \"insights\") db.prepare(`UPDATE finding_votes SET insight_id = NULL WHERE insight_id = ?`).run(row.id);\n if (table === \"corrections\") db.prepare(`UPDATE finding_votes SET correction_id = NULL WHERE correction_id = ?`).run(row.id);\n db.prepare(`DELETE FROM ${table} WHERE id = ?`).run(row.id);\n if (mr != null) refreshScores(db, mr);\n removed++;\n }\n }\n return removed;\n}\n", "import type { DatabaseSync } from \"node:sqlite\";\nimport { createLlmProvider } from \"../../src/llm/index.js\";\nimport { insertInsight, listAuthorCorrections, listAuthorFindingResponses, listAuthors, type AuthorKey, type CorrectionRow, type FindingResponseRow } from \"../db/repo.js\";\n\nexport interface DistillOptions {\n /** One person; omit for everyone in the DB. */\n author?: AuthorKey;\n /** Scope to one GitLab project's corrections only \u2014 insights are tagged with this\n * project_id and won't surface in reviews of other repos (one repo's habit\n * shouldn't color a review on a repo with different conventions). Omit for the prior,\n * cross-repo behavior (insight tagged project_id NULL = global). */\n projectId?: number;\n}\n\n/**\n * On-demand (never automatic, to control LLM cost \u2014 see local/cli.ts): turns a human's\n * corrections into reusable insight bullets. Corrections are the highest-signal data\n * here (explicit \"the automated score was wrong, here's why\") \u2014 this is deliberately\n * scoped to corrections rather than also mining human_review_comments/findings, which\n * are numerous and noisy by comparison; that's a reasonable extension later once\n * correction volume alone proves the loop works.\n */\nexport async function runDistill(db: DatabaseSync, opts: DistillOptions = {}): Promise<void> {\n const authors = opts.author ? [opts.author] : listAuthors(db);\n\n for (const author of authors) {\n const corrections = listAuthorCorrections(db, author, 50, opts.projectId);\n const findingResponses = listAuthorFindingResponses(db, author, 50, opts.projectId);\n if (corrections.length === 0 && findingResponses.length === 0) {\n console.log(`[distill] ${author.username}@${author.host}: no corrections or finding replies yet \u2014 skipping.`);\n continue;\n }\n\n try {\n const bullets = await distillToInsights(corrections, findingResponses);\n const evidenceMrIds = [\n ...new Set([...corrections.map((c) => c.merge_request_id), ...findingResponses.map((r) => r.merge_request_id)]),\n ];\n for (const bullet of bullets) {\n insertInsight(db, {\n authorUsername: author.username,\n host: author.host,\n projectId: opts.projectId ?? null,\n category: null,\n insightText: bullet,\n evidenceMrIds,\n });\n }\n console.log(\n `[distill] ${author.username}@${author.host}: wrote ${bullets.length} insight(s) from ${corrections.length} correction(s) and ${findingResponses.length} finding repl${findingResponses.length === 1 ? \"y\" : \"ies\"}.`,\n );\n } catch (err) {\n console.error(`[distill] ${author.username}@${author.host}: failed: ${(err as Error).message}`);\n }\n }\n}\n\n/**\n * Reuses the existing structured-review contract (LLMProvider.review) rather than\n * adding a second parallel \"summarize free text\" API across all three providers \u2014 the\n * schema (category/score/findings/summary) is generic enough for this: one synthetic\n * \"insights\" category, corrections+reply text stands in for the \"diff\", and each returned\n * finding's `issue` field is one insight bullet. The `score` field is ignored entirely.\n *\n * Two distinct input kinds, both human-signal but different in nature: a correction is\n * the *reviewer* overriding a wrong automated score; a finding reply is the *contributor*\n * pushing back on or explaining one specific flagged issue. The prompt tells the model to\n * tell them apart rather than flattening both into \"the automated review was wrong.\"\n */\nasync function distillToInsights(corrections: CorrectionRow[], findingResponses: FindingResponseRow[]): Promise<string[]> {\n const provider = createLlmProvider(process.env);\n const correctionsText = corrections\n .map(\n (c) =>\n `- [correction] [${c.category ?? \"overall\"}] was scored ${c.original_score}, human corrected to ${c.corrected_score}. Reason: ${c.reason}`,\n )\n .join(\"\\n\");\n const repliesText = findingResponses\n .map(\n (r) =>\n `- [contributor reply] [${r.severity}/${r.category}] finding at ${r.file ?? \"?\"}:${r.line ?? \"?\"}: \"${r.issue}\" \u2014 contributor replied: \"${r.body}\"`,\n )\n .join(\"\\n\");\n const combinedText = [correctionsText, repliesText].filter(Boolean).join(\"\\n\");\n\n const response = await provider.review({\n diff: combinedText,\n truncated: false,\n conventions: \"\",\n categories: [\n {\n name: \"insights\",\n description:\n \"Not a code review \u2014 you are given human signal about prior automated PR reviews for one author, of two kinds. \" +\n \"'[correction]' lines are a human reviewer overriding a wrong automated score \u2014 extract what pattern the automation \" +\n \"got wrong. '[contributor reply]' lines are the contributor's own reply on one specific flagged finding \u2014 extract an \" +\n \"insight only when the reply shows the flagged pattern is actually intentional or acceptable in this codebase (so a \" +\n \"future review should stop flagging it); skip a reply that's just 'fixed' or an acknowledgement with no new \" +\n \"information. Extract 2-5 concise, reusable statements total that would help a future reviewer avoid repeating the \" +\n \"same mistake. Put each statement in a finding's `issue` field, severity 'minor' for all of them, no \" +\n \"file/line/suggestion needed.\",\n },\n ],\n authorHistorySummary: \"\",\n });\n\n const insightsCategory = response.categories.find((c) => c.category === \"insights\");\n return (insightsCategory?.findings ?? []).map((f) => f.issue);\n}\n", "import { confirm, intro, isCancel, log, multiline, multiselect, outro, select, spinner, text } from \"@clack/prompts\";\nimport { CHANGE_TYPES, CHANGE_TYPE_LABELS, describeChangeType, fitsFiles, guessForSteer, hintFromMr, parseChangeTypeMode, type ChangeType, type ChangeTypeGuess } from \"../../src/changeType.js\";\nimport { readFile } from \"node:fs/promises\";\nimport { basename, join } from \"node:path\";\nimport pc from \"picocolors\";\nimport { renderComment } from \"../../src/comment/render.js\";\nimport { scanDiffForSecrets } from \"../../src/checks/secrets.js\";\nimport { runDeterministicChecks } from \"../../src/checks/runner.js\";\nimport { getMrDiff, resolveDiffPosition, truncateDiff, type DiffResult } from \"../../src/git.js\";\nimport { changeLabel, PR_SCORE_LABEL, type ForgeClient, type ProjectRef } from \"../../src/forge/types.js\";\nimport { createLlmProvider, filterNoiseWithJev, jevEnabled, LlmParseError, withRetry, type ReviewCategorySpec } from \"../../src/llm/index.js\";\nimport { loadRubric } from \"../../src/rubric/loader.js\";\nimport { computeFinalScore, volumeFactor } from \"../../src/scoring/engine.js\";\nimport { DEFAULT_CATEGORY_DESCRIPTIONS, resolveCategory, type LlmOutcome } from \"../../src/scoring/resolve.js\";\nimport type { ScoredCategory } from \"../../src/scoring/types.js\";\nimport { keepKnownVerdicts, loadZoneGraph, loadZones, matchZones, type ZoneReport } from \"../../src/zones/zones.js\";\nimport { isCheckoutOf, listConventionFiles, resolveProjectFiles } from \"../conventions/resolve.js\";\nimport { loadConfig } from \"../config/config.js\";\nimport { openDb } from \"../db/client.js\";\nimport { sourceFor, syncSource } from \"../sync/source.js\";\nimport { insertCorrection, insertFindingDiscussion, upsertMergeRequest, upsertProject, upsertScore, upsertZoneHits } from \"../db/repo.js\";\nimport { applyZoneMemory, buildAuthorHistorySummary } from \"../memory/context.js\";\nimport { computeAuthorTrend } from \"../memory/trend.js\";\nimport { DEFAULT_CONVENTIONS_PATH } from \"../paths.js\";\nimport { clearSession, getCachedSession, saveSession } from \"./sessionCache.js\";\n\nexport interface ReviewOptions {\n forge: ForgeClient;\n project: ProjectRef;\n mrIid: number;\n pipelineId?: number;\n rubricPath?: string;\n conventionsPath?: string;\n reviewerFocus?: string;\n}\n\nexport async function runInteractiveReview(opts: ReviewOptions): Promise<void> {\n const db = openDb();\n const client = opts.forge;\n const change = changeLabel(client.type, opts.mrIid);\n\n const project = await client.getProject(opts.project);\n intro(`Yolont review \u2014 ${client.host}/${project.pathWithNamespace} ${change}`);\n // pid: the forge's numeric id, for API calls. dbProjectId: Yolont's own key, for DB calls.\n const pid = project.id;\n const mr = await client.getMergeRequest(pid, opts.mrIid);\n const dbProjectId = upsertProject(db, { ...project, host: client.host });\n const projectFiles = resolveProjectFiles(client.host, project.pathWithNamespace);\n const rubricPath = opts.rubricPath ?? projectFiles.rubric;\n const rubric = loadRubric(rubricPath);\n let conventionsPath = opts.conventionsPath ?? projectFiles.conventions;\n if (!conventionsPath) {\n const picked = await select({\n message: `No conventions for \"${project.pathWithNamespace}\" (looked in .yolont/ and ${projectFiles.dir}) \u2014 pick one for this review`,\n options: listConventionFiles().map((f) => ({ value: f, label: basename(f) })),\n initialValue: DEFAULT_CONVENTIONS_PATH,\n });\n if (isCancel(picked)) return cancelled(db);\n conventionsPath = picked as string;\n }\n log.info(`Conventions: ${conventionsPath}`);\n log.info(pc.dim(`Rubric: ${rubricPath}`));\n\n const s = spinner();\n\n // A saved review of this exact commit: resume it (no LLM cost) or review again from scratch.\n let cached = getCachedSession(pid, opts.mrIid, mr.sha);\n if (cached) {\n const choice = await select({\n message: `A review of this commit was saved ${new Date(cached.savedAt).toLocaleString()} (score ${cached.finalScore}/100)`,\n options: [\n { value: \"resume\", label: \"Use the saved review\", hint: \"no new LLM call\" },\n { value: \"fresh\", label: \"Review again\", hint: \"fetch the diff and run the LLM again\" },\n ],\n });\n if (isCancel(choice)) return cancelled(db);\n if (choice === \"fresh\") {\n clearSession(pid, opts.mrIid, mr.sha);\n cached = undefined;\n }\n }\n let finalScore: number;\n let pass: boolean;\n let scoredCategories: ScoredCategory[];\n let diffTruncated: boolean;\n let diffOmittedFiles: string[];\n let sizeFactor: number;\n let zoneReport: ZoneReport | undefined;\n // off | label (named by the review call) | steer (settled first, then type-specific checks)\n const typeMode = parseChangeTypeMode(loadConfig().changeType);\n let changeType: { type: ChangeType; reason: string } | null = null;\n let labelGuess: ChangeTypeGuess | null = null;\n // Only the non-cached path below fetches the diff this run; a resumed cached session\n // skips it entirely. Kept around (rather than only living in that branch's scope) because\n // the posting loop needs the raw diff text to resolve each finding's line position \u2014\n // re-fetched lazily there if this is still unset (see fetchDiffText).\n let diffText: string | undefined;\n\n if (cached) {\n log.info(`Resuming cached review from ${new Date(cached.savedAt).toLocaleString()} (diff + LLM skipped).`);\n if (cached.reviewerFocus) log.info(`Emphasis used: ${cached.reviewerFocus}`);\n finalScore = cached.finalScore;\n pass = cached.pass;\n scoredCategories = cached.scoredCategories;\n diffTruncated = cached.diffTruncated;\n diffOmittedFiles = cached.omittedFiles ?? [];\n sizeFactor = cached.volumeFactor ?? 1;\n zoneReport = cached.zoneReport;\n changeType = cached.changeType ?? null;\n } else {\n let reviewerFocus = opts.reviewerFocus;\n if (reviewerFocus === undefined) {\n // showSubmit: Enter always inserts a newline (so pasted paragraphs with blank lines\n // don't submit early); Tab to the [ submit ] button, then Enter.\n const focusRaw = await multiline({\n message: \"Anything specific to emphasize for this review? (optional \u2014 Tab then Enter to submit/skip)\",\n placeholder: \"e.g. focus on the retry logic in the payment client, ignore unrelated lint churn\",\n showSubmit: true,\n });\n if (isCancel(focusRaw)) return cancelled(db);\n reviewerFocus = String(focusRaw).trim() || undefined;\n }\n\n s.start(\"Fetching diff\");\n const diff = await fetchDiff(client, pid, mr, project.pathWithNamespace, rubric.max_diff_bytes);\n s.stop(\n `Diff fetched${diff.truncated ? \" (truncated)\" : \"\"}${diff.omittedFiles.length > 0 ? ` (${diff.omittedFiles.length} generated file(s) omitted)` : \"\"}`,\n );\n diffText = diff.text;\n\n try {\n const zonesPath = projectFiles.zones;\n const zones = zonesPath ? loadZones(zonesPath) : null;\n if (zones) {\n const graph = projectFiles.zonesGraph ? loadZoneGraph(projectFiles.zonesGraph) : null;\n if (graph) log.info(pc.dim(`Zone graph from ${graph.generated_at}${graph.sha ? ` @ ${graph.sha.slice(0, 8)}` : \"\"}`));\n zoneReport = { zones, hits: matchZones(zones, diff.files, graph), verdicts: [] };\n }\n else log.info(pc.dim(`No zones.yaml in .yolont/ or ${projectFiles.dir} \u2014 only danger-zone tags apply.`));\n } catch (err) {\n log.warn(`${(err as Error).message} \u2014 continuing with danger-zone tags only.`);\n }\n zoneReport = applyZoneMemory(db, dbProjectId, zoneReport, diff.files);\n if (zoneReport) log.info(`Zones: ${zoneReport.hits.length} of ${zoneReport.zones.length} touched`);\n\n s.start(\"Scanning for secrets\");\n const secretsResult = await scanDiffForSecrets(diff.text);\n const secretsBlocked = secretsResult.scannerFailed || secretsResult.findings.length > 0;\n s.stop(\n secretsResult.scannerFailed\n ? \"gitleaks failed to run\"\n : secretsResult.findings.length > 0\n ? `${secretsResult.findings.length} potential secret(s) found`\n : \"clean\",\n );\n if (secretsResult.scannerFailed) {\n log.warn(\n `gitleaks couldn't run: ${secretsResult.scannerError}\\nInstall or update it (v8+): https://github.com/gitleaks/gitleaks#installing \u2014 the LLM is skipped until it runs (fail-closed, same as CI).`,\n );\n } else if (secretsResult.findings.length > 0) {\n const list = secretsResult.findings.map((f) => ` ${f.file}:${f.line} ${f.ruleId} (${f.description})`).join(\"\\n\");\n log.warn(\n `gitleaks flagged these lines, so the LLM is skipped (fail-closed, same as CI):\\n${list}\\nNot a real secret (a test fixture, a hash)? Add a \\`gitleaks:allow\\` comment on that line and push again.`,\n );\n }\n\n // Label: the free hint stands if the LLM is skipped; the picker after the review overrides it.\n if (typeMode === \"label\") {\n const h = hintFromMr(mr);\n changeType = h && { type: h.type, reason: h.reason };\n }\n // Steer: settle the type before the review. Free hints first; the classifier also sends the\n // diff to the LLM, so never when the secrets check blocked it.\n if (typeMode === \"steer\") {\n const hint = hintFromMr(mr);\n let guess = hint && fitsFiles(hint.type, diff.files) ? hint : null;\n if (!guess && !secretsBlocked) {\n s.start(\"Working out the change type\");\n guess = await guessForSteer((p) => createLlmProvider(process.env).complete(p), mr, diff.text, diff.files);\n s.stop(guess ? `Change type: ${CHANGE_TYPE_LABELS[guess.type]}` : \"Couldn't work out the change type\");\n }\n const picked = await pickChangeType(guess, \"The review checks this type's risks\");\n if (picked === CANCEL) return cancelled(db);\n changeType = picked;\n }\n\n const [jobs, testReportSummary] = opts.pipelineId\n ? await Promise.all([\n client.listPipelineJobs(pid, opts.pipelineId),\n client.getTestReportSummary(pid, opts.pipelineId),\n ])\n : [[], null];\n\n const detResults = runDeterministicChecks(rubric.categories, {\n diffText: diff.text,\n maxLines: rubric.max_lines,\n jobs,\n testReportSummary,\n });\n\n const llmCategories = rubric.categories.filter((c) => c.type === \"llm\" || c.type === \"hybrid\");\n let llmOutcome: LlmOutcome;\n\n if (secretsBlocked) {\n llmOutcome = { status: \"skipped\", reason: \"secrets check\" };\n } else if (llmCategories.length === 0) {\n llmOutcome = { status: \"ok\", categories: new Map() };\n } else {\n s.start(\"Running LLM review\");\n try {\n const provider = createLlmProvider(process.env);\n const conventions = await readFile(conventionsPath, \"utf8\").catch(() => \"(no CONVENTIONS.md found)\");\n const categorySpecs: ReviewCategorySpec[] = llmCategories.map((c) => ({\n name: c.name,\n description: c.description ?? DEFAULT_CATEGORY_DESCRIPTIONS[c.name] ?? \"Review this category based on the team conventions above.\",\n }));\n // This is what closes the memory loop: local corrections/insights, not the\n // GitLab-notes history src/index.ts uses. Scoped to this project + global insights.\n const authorHistorySummary = buildAuthorHistorySummary(db, { host: client.host, username: mr.authorUsername }, dbProjectId);\n\n const response = await withRetry(() =>\n provider.review({\n diff: diff.text,\n truncated: diff.truncated,\n conventions,\n categories: categorySpecs,\n authorHistorySummary,\n reviewerFocus,\n zones: zoneReport?.hits,\n changeType: typeMode === \"steer\" ? changeType?.type : undefined,\n askChangeType: typeMode === \"label\" && !hintFromMr(mr),\n }),\n );\n if (typeMode === \"label\" && !changeType && response.change_type) labelGuess = { ...response.change_type, from: \"llm\" };\n if (zoneReport) zoneReport.verdicts = keepKnownVerdicts(response.zone_verdicts, zoneReport.hits);\n s.stop(\"LLM review complete\");\n if (reviewerFocus) log.info(`Focus check: ${response.focus_notes ?? pc.dim(\"(model returned no focus notes)\")}`);\n\n const findingCountBefore = response.categories.reduce((n, c) => n + c.findings.length, 0);\n if (jevEnabled(process.env)) {\n s.start(\"Cross-checking findings with Jev\");\n }\n const filteredCategories = await filterNoiseWithJev(response.categories, diff.text, process.env, authorHistorySummary, reviewerFocus);\n if (jevEnabled(process.env)) {\n const findingCountAfter = filteredCategories.reduce((n, c) => n + c.findings.length, 0);\n s.stop(`Jev cross-check complete (${findingCountBefore - findingCountAfter} of ${findingCountBefore} findings dropped as likely noise)`);\n\n response.categories.forEach((c, ci) => {\n const kept = filteredCategories[ci]?.findings ?? [];\n const dropped = c.findings.filter((f) => !kept.includes(f));\n for (const f of dropped) {\n const loc = f.file ? ` ${f.file}${f.line ? `:${f.line}` : \"\"}` : \"\";\n log.warn(pc.dim(pc.strikethrough(`[jev-dropped] [${c.category}] [${f.severity}]${loc} ${stripStrayTags(f.issue)}`)));\n }\n });\n }\n\n const categoryMap = new Map(filteredCategories.map((c) => [c.category, { findings: c.findings, summary: c.summary }]));\n llmOutcome = { status: \"ok\", categories: categoryMap };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n llmOutcome = { status: \"error\", reason: message };\n s.stop(`LLM review failed: ${message}`);\n if (err instanceof LlmParseError && err.rawResponse) {\n log.error(`Raw LLM response:\\n${err.rawResponse.slice(0, 4000)}`);\n }\n }\n }\n\n // Label: confirm after the review (the paid result is kept whatever you pick; Esc keeps the suggestion).\n if (typeMode === \"label\" && llmOutcome.status === \"ok\") {\n const hint = hintFromMr(mr);\n const guess = hint ?? labelGuess;\n const picked = await pickChangeType(guess, \"A label only; the review is done\");\n changeType = picked === CANCEL ? (guess && { type: guess.type, reason: guess.reason }) : picked;\n }\n\n sizeFactor = volumeFactor(diff.stats, rubric.volume_scaling);\n const categoryResults = rubric.categories.map((category) =>\n resolveCategory(category, detResults, llmOutcome, rubric.severity_penalties, sizeFactor),\n );\n ({ finalScore, pass, categories: scoredCategories } = computeFinalScore(categoryResults, rubric.threshold));\n diffTruncated = diff.truncated;\n diffOmittedFiles = diff.omittedFiles;\n\n saveSession({\n projectId: pid,\n mrIid: opts.mrIid,\n sha: mr.sha,\n finalScore,\n pass,\n scoredCategories,\n diffTruncated,\n omittedFiles: diffOmittedFiles,\n volumeFactor: sizeFactor,\n reviewerFocus,\n zoneReport,\n changeType,\n });\n }\n\n printScoreSummary(finalScore, pass, rubric.threshold, scoredCategories);\n if (zoneReport) printZoneSummary(zoneReport);\n\n const mrRow = upsertMergeRequest(db, {\n projectId: dbProjectId,\n mrIid: opts.mrIid,\n authorUsername: mr.authorUsername,\n sha: mr.sha,\n title: mr.title,\n mergedAt: null,\n source: \"live\",\n });\n\n // Saved before the agree/correct prompts: corrections below are timestamped after\n // scored_at, so refreshScores applies them (and ignores ones from older reviews).\n upsertScore(db, {\n mergeRequestId: mrRow.id,\n scoredAt: new Date().toISOString(),\n finalScore,\n categoryScores: Object.fromEntries(scoredCategories.map((c) => [c.name, c.score])),\n findings: scoredCategories.flatMap((c) => c.findings.map((f) => ({ ...f, category: c.name }))),\n source: \"llm_live\",\n volumeFactor: sizeFactor,\n base: scoredCategories,\n changeType: changeType?.type ?? null,\n modelUsed: process.env.ANTHROPIC_MODEL ?? process.env.OPENCODE_ZEN_MODEL ?? process.env.OLLAMA_MODEL,\n });\n if (zoneReport) upsertZoneHits(db, mrRow.id, zoneReport);\n\n const agree = await confirm({ message: `Agree with the computed score (${finalScore}/100)?` });\n if (isCancel(agree)) return cancelled(db);\n\n if (!agree) {\n const categoryChoices = await multiselect({\n message: \"Which should be corrected? (space to toggle, enter to confirm)\",\n options: [\n { value: \"__overall__\", label: `Overall score (${finalScore}/100)` },\n ...scoredCategories.map((c) => ({ value: c.name, label: `${c.name} (${c.score}/100)` })),\n ],\n required: true,\n });\n if (isCancel(categoryChoices)) return cancelled(db);\n const selectedCategories = categoryChoices as string[];\n\n const categoryCorrections = new Map<string, { score: number; note?: string }>();\n let overallCorrection: number | undefined;\n let appliedCount = 0;\n\n for (const categoryChoice of selectedCategories) {\n const isOverall = categoryChoice === \"__overall__\";\n const category = isOverall ? undefined : scoredCategories.find((c) => c.name === categoryChoice)!;\n const original = isOverall ? finalScore : category!.score;\n const label = isOverall ? \"overall\" : categoryChoice;\n\n if (category && category.findings.length > 0) {\n log.message(`Findings for ${label}:`);\n for (const f of category.findings) {\n const loc = f.file ? ` ${f.file}${f.line ? `:${f.line}` : \"\"}` : \"\";\n log.message(` - [${f.severity}]${loc} ${stripStrayTags(f.issue)}`);\n if (f.suggestion) log.message(` suggestion: ${stripStrayTags(f.suggestion)}`);\n }\n }\n\n const correctedRaw = await text({\n message: `[${label}] Corrected score (was ${original}, Enter to keep)`,\n validate: (v) => {\n if ((v ?? \"\").trim() === \"\") return undefined;\n const n = Number(v);\n return Number.isFinite(n) && n >= 0 && n <= 100 ? undefined : \"Enter a number 0-100\";\n },\n });\n if (isCancel(correctedRaw)) return cancelled(db);\n const correctedRawTrimmed = String(correctedRaw).trim();\n const correctedScore = correctedRawTrimmed === \"\" ? original : Number(correctedRawTrimmed);\n\n const originalNote = category?.note ?? \"\";\n const correctedNoteRaw = await text({\n message: `[${label}] Corrected description (edit or leave as-is)`,\n initialValue: originalNote,\n });\n if (isCancel(correctedNoteRaw)) return cancelled(db);\n const correctedNoteTrimmed = String(correctedNoteRaw).trim();\n\n const noChange = correctedScore === original && correctedNoteTrimmed === originalNote.trim();\n if (noChange) {\n log.info(`[${label}] No change \u2014 skipping.`);\n continue;\n }\n\n const reasonRaw = await text({\n message: `[${label}] Why? (optional \u2014 becomes memory context for future reviews of this author)`,\n });\n if (isCancel(reasonRaw)) return cancelled(db);\n const reason = String(reasonRaw ?? \"\").trim();\n\n insertCorrection(db, {\n mergeRequestId: mrRow.id,\n category: isOverall ? null : (categoryChoice as string),\n originalScore: original,\n correctedScore,\n correctedNote: correctedNoteTrimmed || undefined,\n reason,\n });\n\n if (isOverall) {\n overallCorrection = correctedScore;\n } else {\n categoryCorrections.set(categoryChoice, { score: correctedScore, note: correctedNoteTrimmed || undefined });\n }\n appliedCount++;\n }\n\n if (appliedCount === 0) {\n log.info(\"No corrections applied.\");\n } else {\n log.success(`${appliedCount} correction(s) saved \u2014 will be used as memory context in future reviews of this author.`);\n\n const updatedCategories = scoredCategories.map((c) => {\n const corr = categoryCorrections.get(c.name);\n return corr ? { ...c, score: corr.score, note: corr.note ?? c.note } : c;\n });\n // Same math refreshScores runs on the stored row, so the TUI and DB/panel agree.\n const recomputed = computeFinalScore(updatedCategories, rubric.threshold);\n scoredCategories = recomputed.categories;\n finalScore = overallCorrection ?? recomputed.finalScore;\n pass = finalScore >= rubric.threshold;\n }\n }\n\n\n const shouldPost = await confirm({\n message: `Post this score as a comment on ${change}?`,\n initialValue: false,\n });\n if (isCancel(shouldPost)) return cancelled(db);\n\n if (shouldPost) {\n const trend = computeAuthorTrend(db, { host: client.host, username: mr.authorUsername });\n await client.upsertPrScoreNote(\n pid,\n opts.mrIid,\n renderComment({\n finalScore,\n pass,\n gate: rubric.gate,\n threshold: rubric.threshold,\n truncatedDiff: diffTruncated,\n omittedFiles: diffOmittedFiles,\n categories: scoredCategories,\n projectWebUrl: project.webUrl,\n forge: client.type,\n changeType: changeType ? describeChangeType(changeType.type, changeType.reason) : undefined,\n sha: mr.sha,\n trend: { recentScores: trend.recentScores, weakestCategory: null },\n record: {\n projectId: pid,\n mrIid: opts.mrIid,\n sha: mr.sha,\n scoredAt: new Date().toISOString(),\n finalScore,\n categoryScores: Object.fromEntries(scoredCategories.map((c) => [c.name, c.score])),\n topFindings: scoredCategories.flatMap((c) => c.findings.map((f) => f.issue)).slice(0, 5),\n },\n zones: zoneReport,\n }),\n );\n log.success(`Posted to ${client.host}.`);\n\n const findingsWithFile = scoredCategories.flatMap((c) =>\n c.findings.filter((f) => f.file && f.line != null).map((f) => ({ ...f, category: c.name })),\n );\n if (findingsWithFile.length > 0 && diffText === undefined) {\n // Cached-session resume skipped the diff fetch entirely this run, but posting still\n // needs the raw diff to work out each finding's old_line/new_line (see below).\n diffText = (await fetchDiff(client, pid, mr, project.pathWithNamespace, rubric.max_diff_bytes)).text;\n }\n\n let postedThreads = 0;\n for (const finding of findingsWithFile) {\n // GitLab rejects a position that only sets new_line unless that line was actually\n // added \u2014 a comment on an unchanged/context line needs old_line too, or GitLab 400s\n // and the finding silently never appears as an inline comment (the original bug here:\n // whichever findings happened to land on context lines vs. added lines).\n const resolvedPosition = resolveDiffPosition(diffText!, finding.file!, finding.line!);\n if (!resolvedPosition) {\n log.warn(`Skipping finding thread for ${finding.file}:${finding.line} \u2014 line not found in the diff.`);\n continue;\n }\n\n const body = [\n `**[${finding.severity}/${finding.category}] Yolont finding**`,\n \"\",\n finding.issue,\n finding.suggestion ? `\\n_Suggestion: ${finding.suggestion}_` : \"\",\n \"\",\n \"<sub>Reply here to explain or say you've fixed it \u2014 future reviews will use it as context.</sub>\",\n ].join(\"\\n\");\n try {\n const { discussionId, noteId } = await client.postFindingDiscussion(pid, opts.mrIid, body, {\n ...mr.diffRefs,\n filePath: finding.file!,\n line: resolvedPosition.newLine,\n oldLine: resolvedPosition.oldLine,\n });\n insertFindingDiscussion(db, {\n mergeRequestId: mrRow.id,\n discussionId,\n category: finding.category,\n severity: finding.severity,\n issue: finding.issue,\n file: finding.file,\n line: finding.line,\n postedNoteId: noteId,\n });\n postedThreads++;\n } catch (err) {\n log.warn(`Could not post finding thread for ${finding.file}:${finding.line}: ${(err as Error).message}`);\n }\n }\n if (postedThreads > 0) log.success(`Posted ${postedThreads} finding thread(s) \u2014 replies can be pulled back with 'sync-replies'.`);\n } else {\n log.info(\"Not posted (read-only / local phase).\");\n }\n\n const shouldLabel = await confirm({\n message: `Add the '${PR_SCORE_LABEL}' label to ${change}?`,\n initialValue: Boolean(shouldPost),\n });\n if (isCancel(shouldLabel)) return cancelled(db);\n if (shouldLabel && (await client.markReviewed(pid, opts.mrIid))) log.success(`Labeled '${PR_SCORE_LABEL}'.`);\n\n clearSession(pid, opts.mrIid, mr.sha);\n await sendToTeam(db, client.host, project.pathWithNamespace);\n outro(\"Done.\");\n db.close();\n}\n\nconst CANCEL = Symbol(\"cancel\");\n\n/** The suggested type first (Enter keeps it), the others, or none. */\nasync function pickChangeType(guess: ChangeTypeGuess | null, hint: string): Promise<{ type: ChangeType; reason: string } | null | typeof CANCEL> {\n const picked = await select({\n message: guess ? `Change type \u2014 suggested: ${CHANGE_TYPE_LABELS[guess.type]} (${guess.from === \"hint\" ? guess.reason : `LLM: ${guess.reason}`})` : \"Change type (no suggestion)\",\n options: [\n ...(guess ? [{ value: guess.type, label: `${CHANGE_TYPE_LABELS[guess.type]} (suggested)`, hint }] : []),\n ...CHANGE_TYPES.filter((t) => t !== guess?.type).map((t) => ({ value: t, label: CHANGE_TYPE_LABELS[t] })),\n { value: \"none\", label: \"No type\" },\n ],\n initialValue: guess?.type ?? \"none\",\n });\n if (isCancel(picked)) return CANCEL;\n if (picked === \"none\") return null;\n return { type: picked as ChangeType, reason: picked === guess?.type ? guess.reason : \"set by the reviewer\" };\n}\n\n/** A shared project's review goes to its team data repo right away; failing only warns (the next sync retries). */\nasync function sendToTeam(db: ReturnType<typeof openDb>, host: string, path: string): Promise<void> {\n const source = sourceFor(host, path);\n if (!source?.autoSync) return;\n const s = spinner();\n s.start(`Sending to team data ${source.name}`);\n try {\n const r = await syncSource(db, source);\n s.stop(`Team data ${source.name}: sent ${r.sent}, got ${r.imported}`);\n } catch (err) {\n s.error(`Team data ${source.name}: not sent (kept here; the next sync tries again)`);\n log.warn((err as Error).message);\n }\n}\n\n/**\n * Local `git diff` is complete (the forge diff APIs truncate big files), but it's only the\n * right diff when cwd is a checkout of *this* project with the MR/PR head checked out \u2014\n * `review <URL>` from any other directory would otherwise score an unrelated diff.\n */\nasync function fetchDiff(client: ForgeClient, pid: ProjectRef, mr: { iid: number; sha: string; targetBranch: string }, pathWithNamespace: string, maxDiffBytes: number): Promise<DiffResult> {\n if (isCheckoutOf(pathWithNamespace, mr.sha)) {\n try {\n return await getMrDiff({ targetBranch: mr.targetBranch, baseSha: process.env.CI_MERGE_REQUEST_DIFF_BASE_SHA }, maxDiffBytes);\n } catch {\n /* fall back to the API */\n }\n }\n return truncateDiff(await client.getMrDiffText(pid, mr.iid), maxDiffBytes);\n}\n\n// minimax-m3 (free-tier fallback) occasionally leaks its own JSON-delimiter\n// tags (e.g. \"</summary></item>\") into free-text fields; strip for terminal display.\nfunction stripStrayTags(s: string): string {\n return s.replace(/<\\/?[a-z_]+>/gi, \"\").trim();\n}\n\nconst SEVERITY_COLOR: Record<string, (s: string) => string> = {\n critical: pc.red,\n major: pc.yellow,\n minor: pc.gray,\n};\n\nfunction printScoreSummary(finalScore: number, pass: boolean, threshold: number, categories: ScoredCategory[]): void {\n const scoreColor = pass ? pc.green : pc.red;\n console.log(\"\");\n console.log(`${pc.bold(\"Score:\")} ${scoreColor(pc.bold(`${finalScore}/100`))} ${pass ? pc.green(\"(pass\") : pc.red(\"(fail\")} vs threshold ${threshold})`);\n for (const c of categories) {\n const status = !c.available ? pc.gray(\"excluded\") : c.score >= 70 ? pc.green(\"ok\") : pc.yellow(\"needs work\");\n const scoreColorFn = !c.available ? pc.gray : c.score >= 70 ? pc.green : pc.yellow;\n const scorePadded = `${String(c.score).padStart(3)}/100`;\n console.log(` ${pc.bold(c.name.padEnd(20))} ${scoreColorFn(scorePadded)} ${status}`);\n if (c.note) console.log(pc.dim(` ${stripStrayTags(c.note)}`));\n for (const f of c.findings) {\n const color = SEVERITY_COLOR[f.severity] ?? pc.white;\n const loc = f.file ? ` ${f.file}${f.line ? `:${f.line}` : \"\"}` : \"\";\n console.log(` - ${color(pc.bold(`[${f.severity}]`))}${pc.dim(loc)} ${stripStrayTags(f.issue)}`);\n if (f.suggestion) console.log(pc.cyan(` suggestion: ${stripStrayTags(f.suggestion)}`));\n }\n }\n console.log(\"\");\n}\n\nconst LEVEL_COLOR = { red: pc.red, amber: pc.yellow, green: pc.green } as const;\n\nfunction printZoneSummary(report: ZoneReport): void {\n if (report.hits.length === 0) return;\n console.log(pc.bold(\"Zones touched:\"));\n for (const { zone, files, viaImport } of report.hits) {\n const verdict = report.verdicts.find((v) => v.zone_id === zone.id);\n console.log(` ${LEVEL_COLOR[zone.level](pc.bold(`[${zone.level}]`))} ${zone.id}${verdict ? ` \u2014 impact ${verdict.impact}: ${stripStrayTags(verdict.verdict)}` : \"\"}`);\n console.log(pc.dim(` ${files.map((f) => (viaImport?.includes(f) ? `${f} (via import)` : f)).join(\", \")}`));\n }\n console.log(\"\");\n}\n\nfunction cancelled(db: ReturnType<typeof openDb>): void {\n outro(\"Review stopped.\");\n db.close();\n}\n", "import { PR_SCORE_MARKER, type ForgeType } from \"../forge/types.js\";\nimport type { HistoryTrend } from \"../history/summarize.js\";\nimport type { AuthorHistoryRecord } from \"../history/types.js\";\nimport type { Finding, ScoredCategory } from \"../scoring/types.js\";\nimport { renderZonesMermaid, type ZoneReport } from \"../zones/zones.js\";\n\nexport interface RenderInput {\n finalScore: number;\n pass: boolean;\n gate: boolean;\n threshold: number;\n truncatedDiff: boolean;\n omittedFiles?: string[];\n categories: ScoredCategory[];\n projectWebUrl: string;\n /** File-link shape: GitLab `/-/blob/`, GitHub `/blob/`. Default gitlab. */\n forge?: ForgeType;\n sha: string;\n trend: HistoryTrend;\n record: AuthorHistoryRecord;\n zones?: ZoneReport;\n /** \"Refactor (title prefix \"refactor:\")\" */\n changeType?: string;\n}\n\nconst LEVEL_EMOJI = { red: \"\uD83D\uDD34\", amber: \"\uD83D\uDFE1\", green: \"\uD83D\uDFE2\" } as const;\n\nconst SEVERITY_RANK: Record<Finding[\"severity\"], number> = { critical: 0, major: 1, minor: 2 };\nconst MAX_FINDINGS = 5;\n\nexport function renderComment(input: RenderInput): string {\n const headerEmoji = input.finalScore >= input.threshold ? \"\uD83D\uDFE2\" : input.finalScore >= input.threshold - 15 ? \"\uD83D\uDFE1\" : \"\uD83D\uDD34\";\n const badge = input.gate ? (input.pass ? \"PASS\" : \"FAIL\") : \"INFORMATIONAL\";\n\n const lines: string[] = [];\n lines.push(PR_SCORE_MARKER);\n lines.push(`## ${headerEmoji} PR Score: ${input.finalScore} / 100`);\n lines.push(\"\");\n lines.push(`**Status:** ${badge} (threshold ${input.threshold}${input.gate ? \"\" : \" \u2014 not gating this pipeline\"})`);\n if (input.changeType) lines.push(\"\", `**Type:** ${escapeHtml(input.changeType)}`);\n if (input.truncatedDiff) {\n lines.push(\"\");\n lines.push(\"_Diff truncated to fit the configured size limit \u2014 review is based on the truncated content._\");\n }\n if (input.omittedFiles && input.omittedFiles.length > 0) {\n lines.push(\"\");\n lines.push(`_${input.omittedFiles.length} generated/vendored file(s) omitted from review: ${input.omittedFiles.join(\", \")}._`);\n }\n lines.push(\"\");\n\n lines.push(\"| Category | Score | Weight | Status |\");\n lines.push(\"|---|---|---|---|\");\n for (const c of input.categories) {\n const status = !c.available ? \"excluded (no data)\" : c.score >= 70 ? \"ok\" : \"needs work\";\n lines.push(`| ${c.name} | ${c.score}/100 | ${Math.round(c.effectiveWeight)}% | ${status} |`);\n }\n lines.push(\"\");\n\n // Each category's `note` carries the LLM's own narrative summary (pros as well as\n // cons \u2014 e.g. \"Mostly compliant; one naming violation\") for llm/hybrid categories, or\n // the deterministic check's own explanation otherwise. Without this, a well-scoring\n // category (nothing in \"Top findings\" below, which only lists negatives) shows up as\n // a bare number with no stated reason why.\n const categoryNotes = input.categories.filter((c) => c.note);\n if (categoryNotes.length > 0) {\n lines.push(\"### Category notes\");\n for (const c of categoryNotes) {\n lines.push(`- **${c.name}**: ${escapeHtml(c.note!)}`);\n }\n lines.push(\"\");\n }\n\n const allFindings = input.categories\n .flatMap((c) => c.findings.map((f) => ({ ...f, category: c.name })))\n .sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity])\n .slice(0, MAX_FINDINGS);\n\n if (allFindings.length > 0) {\n lines.push(\"### Top findings\");\n for (const f of allFindings) {\n const location = f.file ? ` (${linkToFile(input.projectWebUrl, input.forge ?? \"gitlab\", input.sha, f.file, f.line)})` : \"\";\n const issue = escapeHtml(f.issue);\n const suggestion = f.suggestion ? ` \u2014 _${escapeHtml(f.suggestion)}_` : \"\";\n lines.push(`- **[${f.severity}/${f.category}]** ${issue}${location}${suggestion}`);\n }\n lines.push(\"\");\n }\n\n if (input.zones && input.zones.hits.length > 0) {\n lines.push(...renderZonesSection(input.zones));\n }\n\n if (input.trend.recentScores.length > 0) {\n const trendLine = input.trend.weakestCategory\n ? `Last ${input.trend.recentScores.length} score(s): ${input.trend.recentScores.join(\", \")}. Recurring weak category: **${input.trend.weakestCategory.name}** (avg ${input.trend.weakestCategory.avgScore}/100).`\n : `Last ${input.trend.recentScores.length} score(s): ${input.trend.recentScores.join(\", \")}.`;\n lines.push(`### Author trend\\n${trendLine}`);\n lines.push(\"\");\n }\n\n lines.push(\"<details><summary>Raw JSON</summary>\");\n lines.push(\"\");\n // Wrapped in our own HTML-comment markers, not just a ```json fence: a finding's `issue`\n // text can itself contain a stray code fence (e.g. quoting JSON), and history rebuild\n // (history/rebuild.ts) must find *this* block, not a fence that happens to appear earlier\n // in the Top findings section above. An LLM reproducing our exact marker text is not\n // a realistic collision; a bare ``` is.\n lines.push(JSON_DATA_START);\n lines.push(\"```json\");\n lines.push(JSON.stringify(input.record, null, 2));\n lines.push(\"```\");\n lines.push(JSON_DATA_END);\n lines.push(\"\");\n lines.push(\"</details>\");\n\n return lines.join(\"\\n\");\n}\n\n/** Informational only \u2014 zone verdicts never feed the score. */\nfunction renderZonesSection(report: ZoneReport): string[] {\n const lines = [\"### Zones\", \"\", renderZonesMermaid(report.zones, report.hits), \"\"];\n for (const { zone, files, viaImport } of report.hits) {\n const verdict = report.verdicts.find((v) => v.zone_id === zone.id);\n const verdictText = verdict ? ` \u2014 impact **${verdict.impact}**: ${escapeHtml(verdict.verdict)}` : \"\";\n lines.push(`- ${LEVEL_EMOJI[zone.level]} **${zone.id}** (${zone.level})${verdictText}`);\n lines.push(` <sub>${files.map((f) => `\\`${escapeHtml(f)}\\`${viaImport?.includes(f) ? \" (imported by this zone)\" : \"\"}`).join(\", \")}</sub>`);\n }\n lines.push(\"\");\n return lines;\n}\n\nexport const JSON_DATA_START = \"<!-- pr-score-json:start -->\";\nexport const JSON_DATA_END = \"<!-- pr-score-json:end -->\";\n\nexport function renderSkippedComment(reason: string): string {\n return `${PR_SCORE_MARKER}\\n## \u26AA Yolont skipped\\n\\n${reason}`;\n}\n\nexport function renderFastFailComment(reason: string): string {\n return `${PR_SCORE_MARKER}\\n## \uD83D\uDD34 Yolont: build broken\\n\\n${reason}\\n\\nLLM review skipped to save cost \u2014 fix the build first.`;\n}\n\nexport function renderSecretsBlockedComment(findings: SecretFindingSummary[]): string {\n // File/line/rule only \u2014 never the secret value itself (gitleaks already runs with\n // --redact). Without at least this much, a dev has to re-run gitleaks locally just to\n // find what tripped the scan.\n const list = findings.map((f) => `- \\`${f.ruleId}\\` in ${f.file}${f.line ? `:${f.line}` : \"\"}`).join(\"\\n\");\n return (\n `${PR_SCORE_MARKER}\\n## \uD83D\uDD34 Yolont: secrets detected\\n\\n` +\n `${findings.length} potential secret(s) found in this diff. The diff was never sent to the LLM.\\n\\n` +\n `${list}\\n\\n` +\n `This is a hard failure independent of the rubric's \\`gate\\` setting \u2014 remove the secret(s) and rotate them, then push again.`\n );\n}\n\nexport interface SecretFindingSummary {\n ruleId: string;\n file: string;\n line: number;\n}\n\nexport function renderErrorComment(context: string, message: string): string {\n return (\n `${PR_SCORE_MARKER}\\n## \u26AA Yolont: error (${context})\\n\\n` +\n `${message}\\n\\nThis is a tooling failure, not a review \u2014 never treat this as a silent pass or fail on its own.`\n );\n}\n\nexport function renderSecretsScanFailedComment(errorMessage: string): string {\n return (\n `${PR_SCORE_MARKER}\\n## \uD83D\uDD34 Yolont: secret scan could not run\\n\\n` +\n `gitleaks failed to run (\\`${errorMessage}\\`) \u2014 this is a tooling problem, **not** a confirmed secret. ` +\n `The diff was not sent to the LLM out of caution. Check the Yolont image/runner setup and retry.`\n );\n}\n\nfunction linkToFile(projectWebUrl: string, forge: ForgeType, sha: string, file: string, line?: number): string {\n const url = `${projectWebUrl.replace(/\\/$/, \"\")}/${forge === \"github\" ? \"blob\" : \"-/blob\"}/${sha}/${encodeURI(file)}`;\n const label = escapeHtml(file);\n return line ? `[${label}:${line}](${url}#L${line})` : `[${label}](${url})`;\n}\n\n/**\n * Every string here (issue/suggestion/note/file) ultimately comes from the LLM's\n * response, not our own code \u2014 the model can put anything in a free-text field,\n * including HTML. Rendering it unescaped into a comment GitLab renders as\n * markdown+HTML (we deliberately use raw <details>/<summary> ourselves) is a real\n * injection surface: a crafted diff could coax the model into emitting arbitrary\n * markup. Observed in practice (not hypothetical) as a stray literal\n * `</summary></item>` fragment leaking out of a model's category summary and\n * corrupting the rendered comment's structure.\n */\nfunction escapeHtml(text: string): string {\n return text.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\");\n}\n", "import type { DatabaseSync } from \"node:sqlite\";\nimport type { Zone, ZoneReport } from \"../../src/zones/zones.js\";\nimport { insightSource, ownerOfProject, projectOwners } from \"../sync/source.js\";\nimport { listAuthorCorrections, listDangerTaggedFindings, listInsights, listZoneHitsForProject, type AuthorKey } from \"../db/repo.js\";\n\n/**\n * The local-DB equivalent of src/history/summarize.ts's summarizeHistoryForPrompt \u2014 but\n * this is what actually closes the memory loop: distilled `insights` and human\n * `corrections` (with their reasons) feed back into the LLM prompt for the next review,\n * which is the whole point of capturing them in the interactive TUI.\n */\nexport function buildAuthorHistorySummary(db: DatabaseSync, author: AuthorKey, projectId: number): string {\n // This text goes into the prompt: host is strict, and a host-wide insight is used only when it\n // belongs to this project's team data repo (company memory never colors a personal review).\n const owner = projectOwners();\n const here = ownerOfProject(db, projectId, owner);\n const insights = listInsights(db, { host: author.host, username: author.username, projectId })\n .filter((i) => insightSource(db, i, owner) === here)\n .slice(0, 5);\n // Imported from a repo that no longer owns this project (shared elsewhere since): left out.\n const corrections = listAuthorCorrections(db, author, 20, projectId)\n .filter((c) => !c.origin || c.origin === here)\n .slice(0, 5);\n\n if (insights.length === 0 && corrections.length === 0) {\n return \"No local memory yet for this author.\";\n }\n\n const lines: string[] = [];\n if (insights.length > 0) {\n lines.push(\"Learned insights:\");\n for (const insight of insights) lines.push(`- ${insight.insight_text}`);\n }\n if (corrections.length > 0) {\n lines.push(\"Recent human corrections (a reviewer disagreed with a prior automated score \u2014 weight these heavily):\");\n for (const c of corrections) {\n const label = c.category ?? \"overall\";\n const reasonSuffix = c.reason?.trim() ? `: ${c.reason}` : \"\";\n lines.push(`- [${label}] was scored ${c.original_score}, human corrected to ${c.corrected_score}${reasonSuffix}`);\n if (c.corrected_note) lines.push(` corrected description: ${c.corrected_note}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\nexport const FLAGGED_DANGER_ZONE_ID = \"flagged-danger\";\n\n/**\n * Closes the zones memory loop for one project:\n * - files whose earlier findings a reviewer tagged `danger-zone` become a synthetic red\n * zone, matched against this diff in code like any YAML zone \u2014 so it works even for a\n * project with no zones file yet;\n * - past \uD83D\uDC4D/\uD83D\uDC4E votes on each touched zone's verdicts ride along as prompt feedback.\n */\nexport function applyZoneMemory(db: DatabaseSync, projectId: number, report: ZoneReport | undefined, changedFiles: string[]): ZoneReport | undefined {\n const flagged = listDangerTaggedFindings(db, projectId);\n // ponytail: exact file match only; widen to the file's directory if tagged files churn through renames.\n const flaggedHere = [...new Set(flagged.filter((f) => changedFiles.includes(f.file)).map((f) => f.file))];\n\n if (flaggedHere.length > 0) {\n const zone: Zone = {\n id: FLAGGED_DANGER_ZONE_ID,\n level: \"red\",\n paths: [...new Set(flagged.map((f) => f.file))],\n why: \"Reviewers tagged earlier findings in these files as danger-zone\",\n watch_for: [...new Set(flagged.filter((f) => flaggedHere.includes(f.file)).map((f) => f.issue))].slice(0, 5),\n };\n report ??= { zones: [], hits: [], verdicts: [] };\n report = { ...report, zones: [zone, ...report.zones], hits: [{ zone, files: flaggedHere }, ...report.hits] };\n }\n if (!report) return undefined;\n\n const voted = listZoneHitsForProject(db, projectId).filter((h) => h.vote && h.verdict);\n return {\n ...report,\n hits: report.hits.map((hit) => {\n const feedback = voted\n .filter((h) => h.zone_id === hit.zone.id)\n .slice(0, 3)\n .map((h) => `${h.vote === \"down\" ? \"rejected\" : \"confirmed\"} on !${h.mr_iid}: \"${h.verdict}\"${h.vote_note ? ` \u2014 ${h.vote_note}` : \"\"}`);\n return feedback.length > 0 ? { ...hit, feedback } : hit;\n }),\n };\n}\n", "import type { DatabaseSync } from \"node:sqlite\";\nimport { listAuthorScores, type AuthorKey } from \"../db/repo.js\";\n\nexport interface AuthorTrend {\n recentScores: number[];\n /** Least-squares slope over recent scores (score/MR). Positive = improving. */\n slope: number;\n /** Naive one-step-ahead projection: last score + slope, clamped to [0, 100]. */\n projectedNextScore: number | null;\n label: \"improving\" | \"declining\" | \"stable\" | \"insufficient-data\";\n}\n\nconst STABLE_SLOPE_THRESHOLD = 1.5; // score points per MR\n\n/**\n * Forward-looking trend from real accumulated scores \u2014 plain least-squares linear\n * regression over (index, final_score), not a trained model. Deliberately simple and\n * transparent: this is the \"statistical, not ML\" half of the (a)+(b) memory design.\n */\nexport function computeAuthorTrend(db: DatabaseSync, author: AuthorKey, lastN = 10): AuthorTrend {\n const rows = listAuthorScores(db, author).slice(-lastN);\n const recentScores = rows.map((r) => r.final_score);\n\n if (recentScores.length < 2) {\n return { recentScores, slope: 0, projectedNextScore: recentScores[0] ?? null, label: \"insufficient-data\" };\n }\n\n const slope = leastSquaresSlope(recentScores);\n const last = recentScores[recentScores.length - 1]!;\n const projectedNextScore = Math.max(0, Math.min(100, Math.round(last + slope)));\n\n const label: AuthorTrend[\"label\"] =\n slope > STABLE_SLOPE_THRESHOLD ? \"improving\" : slope < -STABLE_SLOPE_THRESHOLD ? \"declining\" : \"stable\";\n\n return { recentScores, slope, projectedNextScore, label };\n}\n\nfunction leastSquaresSlope(values: number[]): number {\n const n = values.length;\n const xs = Array.from({ length: n }, (_, i) => i);\n const xMean = xs.reduce((a, b) => a + b, 0) / n;\n const yMean = values.reduce((a, b) => a + b, 0) / n;\n\n let numerator = 0;\n let denominator = 0;\n for (let i = 0; i < n; i++) {\n numerator += (xs[i]! - xMean) * (values[i]! - yMean);\n denominator += (xs[i]! - xMean) ** 2;\n }\n return denominator === 0 ? 0 : numerator / denominator;\n}\n", "import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport type { ScoredCategory } from \"../../src/scoring/types.js\";\nimport type { ZoneReport } from \"../../src/zones/zones.js\";\nimport { SESSIONS_PATH as CACHE_PATH } from \"../paths.js\";\n\nconst MAX_SESSIONS = 3;\n\nimport type { ChangeType } from \"../../src/changeType.js\";\n\nexport interface CachedReviewSession {\n projectId: number;\n mrIid: number;\n sha: string;\n savedAt: string;\n finalScore: number;\n pass: boolean;\n scoredCategories: ScoredCategory[];\n diffTruncated: boolean;\n omittedFiles?: string[];\n volumeFactor?: number;\n reviewerFocus?: string;\n zoneReport?: ZoneReport;\n /** Settled change type (src/changeType.ts) and why. */\n changeType?: { type: ChangeType; reason: string } | null;\n}\n\nfunction key(projectId: number, mrIid: number, sha: string): string {\n return `${projectId}:${mrIid}:${sha}`;\n}\n\nfunction readAll(): CachedReviewSession[] {\n if (!existsSync(CACHE_PATH)) return [];\n try {\n return JSON.parse(readFileSync(CACHE_PATH, \"utf8\"));\n } catch {\n return [];\n }\n}\n\nfunction writeAll(sessions: CachedReviewSession[]): void {\n mkdirSync(dirname(CACHE_PATH), { recursive: true });\n writeFileSync(CACHE_PATH, JSON.stringify(sessions, null, 2));\n}\n\n/** A prior in-progress review left un-finished (terminated before agree/correct/post) \u2014 if\n * still cached, resume from it instead of re-fetching the diff and re-running the LLM. */\nexport function getCachedSession(projectId: number, mrIid: number, sha: string): CachedReviewSession | undefined {\n return readAll().find((s) => key(s.projectId, s.mrIid, s.sha) === key(projectId, mrIid, sha));\n}\n\n/** Called right after scoring, before the agree/correct/post prompts \u2014 so a Ctrl-C or\n * cancel anywhere in that flow leaves the expensive part (diff + LLM) resumable. Capped\n * at MAX_SESSIONS, oldest evicted first \u2014 this is a short-lived crash recovery aid, not a\n * review history (that's the sqlite `scores` table). */\nexport function saveSession(session: Omit<CachedReviewSession, \"savedAt\">): void {\n const sessions = readAll().filter((s) => key(s.projectId, s.mrIid, s.sha) !== key(session.projectId, session.mrIid, session.sha));\n sessions.push({ ...session, savedAt: new Date().toISOString() });\n sessions.sort((a, b) => a.savedAt.localeCompare(b.savedAt));\n while (sessions.length > MAX_SESSIONS) sessions.shift();\n writeAll(sessions);\n}\n\n/** Called once a review finishes cleanly (agree/correct + post decision both made) \u2014 the\n * cached copy is only for resuming an interrupted run, not a completed one. */\nexport function clearSession(projectId: number, mrIid: number, sha: string): void {\n writeAll(readAll().filter((s) => key(s.projectId, s.mrIid, s.sha) !== key(projectId, mrIid, sha)));\n}\n", "import type { DatabaseSync } from \"node:sqlite\";\nimport { changeLabel, type ForgeClient, type ProjectRef } from \"../../src/forge/types.js\";\nimport { openDb } from \"../db/client.js\";\nimport { findProjectId, getMergeRequestByProjectAndIid, insertFindingResponse, listFindingDiscussionsForMr } from \"../db/repo.js\";\n\nexport interface SyncRepliesOptions {\n forge: ForgeClient;\n project: ProjectRef;\n mrIid: number;\n}\n\nexport interface SyncRepliesResult {\n /** Finding threads this review posted. 0 = nothing to sync (the review wasn't posted). */\n tracked: number;\n newReplies: number;\n updatedReplies: number;\n /** Threads that got a new or edited reply. */\n threads: number;\n}\n\n/**\n * Pulls contributor replies (new and edited) on the finding threads `review` posted for one\n * MR. Read + DB only, no LLM cost; turning replies into insights is a separate `distill`.\n * Shared by `yolont sync-replies` and the panel's review page.\n */\nexport async function syncRepliesForMr(db: DatabaseSync, forge: ForgeClient, forgeProject: ProjectRef, mrIid: number, mergeRequestId: number): Promise<SyncRepliesResult> {\n const tracked = listFindingDiscussionsForMr(db, mergeRequestId);\n const result: SyncRepliesResult = { tracked: tracked.length, newReplies: 0, updatedReplies: 0, threads: 0 };\n if (tracked.length === 0) return result;\n\n const me = await forge.getCurrentUser();\n const threadsById = new Map((await forge.listMrDiscussionThreads(forgeProject, mrIid)).map((t) => [t.discussionId, t.notes]));\n for (const t of tracked) {\n const replies = (threadsById.get(t.discussion_id) ?? []).filter((n) => n.id !== t.posted_note_id && n.authorUsername !== me.username);\n let changed = false;\n for (const reply of replies) {\n const outcome = insertFindingResponse(db, { findingDiscussionId: t.id, noteId: reply.id, authorUsername: reply.authorUsername, body: reply.body, createdAt: reply.createdAt });\n if (outcome === \"new\") result.newReplies++;\n if (outcome === \"updated\") result.updatedReplies++;\n if (outcome) changed = true;\n }\n if (changed) result.threads++;\n }\n return result;\n}\n\nexport const describeSyncReplies = (r: SyncRepliesResult): string =>\n r.tracked === 0\n ? \"This review has no posted finding threads, so there are no replies to get.\"\n : `${r.newReplies} new repl${r.newReplies === 1 ? \"y\" : \"ies\"}${r.updatedReplies ? `, ${r.updatedReplies} edited` : \"\"} across ${r.threads} of ${r.tracked} finding thread(s).`;\n\n/** `yolont sync-replies <MR/PR URL>`. */\nexport async function runSyncReplies(opts: SyncRepliesOptions): Promise<void> {\n const db = openDb();\n try {\n const client = opts.forge;\n // A path (\"owner/repo\") from a URL must become the numeric id the DB is keyed by.\n const forgeId = typeof opts.project === \"number\" || /^\\d+$/.test(opts.project) ? opts.project : (await client.getProject(opts.project)).id;\n const dbProjectId = findProjectId(db, client.host, forgeId);\n const mrRow = dbProjectId === undefined ? undefined : getMergeRequestByProjectAndIid(db, dbProjectId, opts.mrIid);\n if (!mrRow) throw new Error(`No tracked findings for ${client.host} project ${opts.project} ${changeLabel(client.type, opts.mrIid)} \u2014 run 'review' and post it first.`);\n console.log(`[sync-replies] ${describeSyncReplies(await syncRepliesForMr(db, client, forgeId, opts.mrIid, mrRow.id))}`);\n } finally {\n db.close();\n }\n}\n", "import fastifyStatic from \"@fastify/static\";\nimport { describeSyncReplies, syncRepliesForMr } from \"../review/syncReplies.js\";\nimport Fastify, { type FastifyInstance, type FastifyReply } from \"fastify\";\nimport { randomBytes, timingSafeEqual } from \"node:crypto\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { join } from \"node:path\";\nimport { INSTALL_ROOT } from \"../paths.js\";\nimport type { ForgeClient } from \"../../src/forge/types.js\";\nimport { loadConfig } from \"../config/config.js\";\nimport { openDb } from \"../db/client.js\";\nimport {\n addFindingTag,\n commentVolumeByAuthor,\n deleteCorrection,\n deleteFindingVote,\n deleteInsight,\n deleteMergeRequest,\n deleteScore,\n getMergeRequestById,\n listAuthorComments,\n listAuthorCorrections,\n listAuthorScores,\n listAuthors,\n listCommentsForMr,\n listCorrectionsForMr,\n listDangerTaggedFindings,\n listFindingsForMr,\n listInsights,\n listReviews,\n listScoresForMr,\n listZoneHitsForMr,\n listZoneHitsForProject,\n queryFindings,\n removeFindingTag,\n setZoneHitVote,\n updateCorrection,\n upsertFindingVote,\n} from \"../db/repo.js\";\nimport { computeAuthorTrend } from \"../memory/trend.js\";\nimport { syncFindingDecision, type Vote } from \"../review/syncDecision.js\";\nimport { registerSettings } from \"./settings.js\";\nimport { describeRun, displayUrl, insightSource, ownerOfProject, pendingToSend, projectOwners, waitingForMerge, syncAll, type SourceRun } from \"../sync/source.js\";\nimport type { SourceConfig } from \"../config/config.js\";\n\nconst FINDING_TAGS = [\n \"technical-debt\",\n \"security\",\n \"performance\",\n \"bug-risk\",\n \"breaking-change\",\n \"missing-tests\",\n \"style\",\n \"documentation\",\n \"duplication\",\n \"accessibility\",\n \"danger-zone\",\n] as const;\n\nconst WEB_DIST = join(INSTALL_ROOT, \"local\", \"backoffice\", \"web\", \"dist\");\n\nexport interface DashboardOptions {\n port?: number;\n /** Client for a finding's forge host \u2014 enables posting vote/tag decisions back to its thread. */\n forgeFor?: (host: string) => ForgeClient;\n}\n\nexport interface PanelOptions extends DashboardOptions {\n db: DatabaseSync;\n /** Required on every /api request as `Authorization: Bearer <token>`. */\n token: string;\n port: number;\n /** Sync every auto-sync team data repo in the background once built (the real panel; not tests). */\n syncOnStart?: boolean;\n}\n\n/**\n * The panel app, not yet listening (tests use `inject`). Security, before any route:\n * - only Host 127.0.0.1:<port> / localhost:<port> (blocks DNS rebinding);\n * - every /api/* route needs the per-start token in a header (a cross-site form or <img>\n * can't attach one, so no CSRF). Static files carry no data and stay open.\n */\nexport async function buildPanel(opts: PanelOptions): Promise<FastifyInstance> {\n const { db } = opts;\n const app = Fastify({ logger: false });\n const want = Buffer.from(opts.token);\n const hosts = new Set([`127.0.0.1:${opts.port}`, `localhost:${opts.port}`]);\n app.addHook(\"onRequest\", async (req, reply) => {\n if (!hosts.has(req.headers.host ?? \"\")) return reply.code(403).send({ error: \"Unexpected Host header\" });\n // Decide on the route that matched, not the raw URL: the router percent-decodes, so\n // \"/%61pi/reviews\" reaches /api/reviews while the raw string doesn't start with \"/api/\".\n const route = req.routeOptions?.url;\n let decoded = req.url;\n try {\n decoded = decodeURIComponent(req.url.split(\"?\")[0]!);\n } catch {\n /* malformed escapes: fall back to the raw path */\n }\n if (!route?.startsWith(\"/api/\") && !decoded.toLowerCase().replace(/\\/+/g, \"/\").startsWith(\"/api/\")) return;\n const got = Buffer.from((req.headers.authorization ?? \"\").replace(/^Bearer\\s+/i, \"\"));\n if (got.length !== want.length || !timingSafeEqual(got, want)) return reply.code(401).send({ error: \"Open the panel with the URL printed in the terminal (it carries the access token).\" });\n });\n\n const currentVote = (findingId: number): Vote =>\n (db.prepare(`SELECT vote FROM finding_votes WHERE finding_id = ?`).get(findingId) as { vote: Vote } | undefined)?.vote ?? null;\n\n /** DB change is already committed; `?sync=1` mirrors it to the finding's GitLab thread. */\n async function maybeSync(findingId: number, prevVote: Vote, sync: string | undefined) {\n if (sync !== \"1\") return { ok: true, synced: false };\n if (!opts.forgeFor) return { ok: true, synced: false, error: \"No git host configured\" };\n const result = await syncFindingDecision(db, opts.forgeFor, findingId, prevVote);\n if (result.error) console.error(`[dashboard] forge sync failed for finding ${findingId}: ${result.error}`);\n return { ok: true, ...result };\n }\n\n /**\n * The panel's memory repo filter: `?source=<team data repo>` or `_local` (not shared),\n * by the same project ownership rule reviews use for memory. Unset = everything, merged.\n */\n type Filter = { projectIds: number[]; has: (projectId: number | null) => boolean; owner: (key: string) => string | null; name: string };\n function sourceFilter(source: string | undefined, reply: FastifyReply): Filter | undefined | null {\n if (!source) return undefined;\n const name = source === \"_local\" ? null : source;\n if (name !== null && !(loadConfig().sources ?? []).some((s) => s.name === name)) {\n void reply.code(400).send({ error: `No team data repo named '${source}'` });\n return null;\n }\n const owner = projectOwners();\n const rows = db.prepare(`SELECT id FROM projects`).all() as { id: number }[];\n const projectIds = rows.map((r) => r.id).filter((id) => ownerOfProject(db, id, owner) === name);\n const set = new Set(projectIds);\n return { projectIds, has: (id) => id != null && set.has(id), owner, name: source };\n }\n\n // ---- memory repo sync: a button, plus once on start ----\n const lastRun = new Map<string, { at: string; summary: string; error: boolean }>();\n async function runTeamSync(sources: SourceConfig[]): Promise<SourceRun[]> {\n const runs = await syncAll(db, \"sync\", sources);\n for (const r of runs) {\n lastRun.set(r.name, { at: new Date().toISOString(), summary: describeRun(r), error: !!r.error });\n console[r.error ? \"error\" : \"log\"](`[panel] team data ${describeRun(r)}`);\n }\n return runs;\n }\n if (opts.syncOnStart) runTeamSync((loadConfig().sources ?? []).filter((s) => s.autoSync)).catch((err) => console.error(`[panel] team data sync failed: ${(err as Error).message}`));\n\n app.get(\"/api/sync\", async () =>\n Promise.all(\n (loadConfig().sources ?? []).map(async (s) => ({ name: s.name, toSend: await pendingToSend(db, s).catch(() => null), waiting: await waitingForMerge(s).catch(() => 0), last: lastRun.get(s.name) ?? null })),\n ),\n );\n\n app.post<{ Querystring: { source?: string } }>(\"/api/sync\", async (req, reply) => {\n const all = loadConfig().sources ?? [];\n const pick = req.query.source ? all.filter((s) => s.name === req.query.source) : all;\n if (req.query.source && pick.length === 0) return reply.code(400).send({ error: `No team data repo named '${req.query.source}'` });\n return (await runTeamSync(pick)).map((r) => ({ name: r.name, summary: describeRun(r), error: r.error ?? null }));\n });\n\n app.get(\"/api/sources\", async () => (loadConfig().sources ?? []).map((s) => ({ name: s.name, url: displayUrl(s.url) })));\n\n app.get<{ Querystring: { source?: string } }>(\"/api/authors\", async (req, reply) => {\n const f = sourceFilter(req.query.source, reply);\n if (f === null) return reply;\n return listAuthors(db, f?.projectIds).map((author) => ({ ...author, trend: computeAuthorTrend(db, author) }));\n });\n\n // A person is (host, username), so the host is required: the same username on another host\n // is someone else.\n app.get<{ Params: { username: string }; Querystring: { host?: string; project?: string } }>(\n \"/api/authors/:username\",\n async (req, reply) => {\n if (!req.query.host) return reply.code(400).send({ error: \"host is required\" });\n const author = { host: req.query.host, username: req.params.username };\n const projectId = req.query.project ? Number(req.query.project) : undefined;\n const scores = listAuthorScores(db, author).map((s) => ({\n ...s,\n category_scores: JSON.parse(s.category_scores_json),\n findings: JSON.parse(s.findings_json),\n }));\n return {\n ...author,\n scores,\n corrections: listAuthorCorrections(db, author, 100, projectId),\n comments: listAuthorComments(db, author),\n insights: listInsights(db, { ...author, projectId }),\n trend: computeAuthorTrend(db, author),\n };\n },\n );\n\n app.get<{ Querystring: { author?: string; host?: string; project?: string; source?: string } }>(\"/api/insights\", async (req, reply) => {\n const { author, host, project } = req.query;\n const f = sourceFilter(req.query.source, reply);\n if (f === null) return reply;\n const rows = listInsights(db, { username: author, host, projectId: project ? Number(project) : undefined });\n const want = f && (f.name === \"_local\" ? null : f.name);\n return f ? rows.filter((i) => insightSource(db, i, f.owner) === want) : rows;\n });\n\n app.get<{ Querystring: { source?: string } }>(\"/api/projects\", async (req, reply) => {\n const f = sourceFilter(req.query.source, reply);\n if (f === null) return reply;\n const owner = f?.owner ?? projectOwners();\n const rows = db.prepare(\"SELECT id, path_with_namespace, name, forge_host FROM projects ORDER BY path_with_namespace, forge_host\").all() as { id: number }[];\n return rows.filter((p) => !f || f.has(p.id)).map((p) => ({ ...p, source: ownerOfProject(db, p.id, owner) }));\n });\n\n app.get<{ Querystring: { source?: string } }>(\"/api/comment-volume\", async (req, reply) => {\n const f = sourceFilter(req.query.source, reply);\n if (f === null) return reply;\n return commentVolumeByAuthor(db, f?.projectIds);\n });\n\n app.get<{ Querystring: { source?: string } }>(\"/api/reviews\", async (req, reply) => {\n const f = sourceFilter(req.query.source, reply);\n if (f === null) return reply;\n const rows = listReviews(db);\n return f ? rows.filter((r) => f.has(r.project_id)) : rows;\n });\n\n app.get<{ Params: { id: string } }>(\"/api/reviews/:id\", async (req, reply) => {\n const mergeRequestId = Number(req.params.id);\n const mr = getMergeRequestById(db, mergeRequestId);\n if (!mr) return reply.code(404).send({ error: \"not found\" });\n return {\n mr,\n scores: listScoresForMr(db, mergeRequestId).map((s) => ({\n ...s,\n category_scores: JSON.parse(s.category_scores_json),\n findings: JSON.parse(s.findings_json),\n })),\n corrections: listCorrectionsForMr(db, mergeRequestId),\n comments: listCommentsForMr(db, mergeRequestId),\n findings: listFindingsForMr(db, mergeRequestId),\n zoneHits: listZoneHitsForMr(db, mergeRequestId),\n };\n });\n\n /** Gets the authors' new and edited replies on this review's posted finding threads. */\n app.post<{ Params: { id: string } }>(\"/api/reviews/:id/sync-replies\", async (req, reply) => {\n const mr = getMergeRequestById(db, Number(req.params.id));\n if (!mr) return reply.code(404).send({ error: \"not found\" });\n const project = db.prepare(`SELECT forge_host, forge_project_id FROM projects WHERE id = ?`).get(mr.project_id) as\n | { forge_host: string | null; forge_project_id: string | null }\n | undefined;\n if (!project?.forge_host || !project.forge_project_id) return reply.code(400).send({ error: \"This review's git host isn't known, so replies can't be fetched.\" });\n if (!opts.forgeFor) return reply.code(400).send({ error: \"No git host configured\" });\n try {\n const ref = /^\\d+$/.test(project.forge_project_id) ? Number(project.forge_project_id) : project.forge_project_id;\n const result = await syncRepliesForMr(db, opts.forgeFor(project.forge_host), ref, mr.mr_iid, mr.id);\n return { ...result, summary: describeSyncReplies(result) };\n } catch (err) {\n return reply.code(502).send({ error: `Couldn't get replies from ${project.forge_host}: ${(err as Error).message}` });\n }\n });\n\n app.get<{ Querystring: { project?: string } }>(\"/api/zones\", async (req, reply) => {\n const projectId = Number(req.query.project);\n if (!projectId) return reply.code(400).send({ error: \"project is required\" });\n return { hits: listZoneHitsForProject(db, projectId), flagged: listDangerTaggedFindings(db, projectId) };\n });\n\n app.post<{ Params: { id: string }; Body: { vote: \"up\" | \"down\"; note?: string } }>(\"/api/zone-hits/:id/vote\", async (req, reply) => {\n const { vote, note } = req.body;\n if (vote !== \"up\" && vote !== \"down\") return reply.code(400).send({ error: \"vote must be 'up' or 'down'\" });\n setZoneHitVote(db, Number(req.params.id), vote, note?.trim() || null);\n return { ok: true };\n });\n\n app.delete<{ Params: { id: string } }>(\"/api/zone-hits/:id/vote\", async (req) => {\n setZoneHitVote(db, Number(req.params.id), null, null);\n return { ok: true };\n });\n\n app.get<{ Querystring: { project?: string; author?: string; authorHost?: string; tag?: string; source?: string } }>(\"/api/findings\", async (req, reply) => {\n const { project, author, authorHost, tag } = req.query;\n if (author && !authorHost) return reply.code(400).send({ error: \"authorHost is required with author\" });\n const f = sourceFilter(req.query.source, reply);\n if (f === null) return reply;\n const rows = queryFindings(db, { projectId: project ? Number(project) : undefined, author: author && authorHost ? { host: authorHost, username: author } : undefined, tag });\n return f ? rows.filter((r) => f.has(r.project_id)) : rows;\n });\n\n app.post<{\n Params: { id: string };\n Querystring: { sync?: string };\n Body: { vote: \"up\" | \"down\"; note: string; adjustScore: boolean; category?: string | null; correctedScore?: number };\n }>(\"/api/findings/:id/vote\", async (req, reply) => {\n const { vote, note, adjustScore, category, correctedScore } = req.body;\n if (vote !== \"up\" && vote !== \"down\") return reply.code(400).send({ error: \"vote must be 'up' or 'down'\" });\n if (!note || !note.trim()) return reply.code(400).send({ error: \"note is required\" });\n const id = Number(req.params.id);\n const prev = currentVote(id);\n upsertFindingVote(db, id, { vote, note: note.trim(), adjustScore, category, correctedScore });\n return maybeSync(id, prev, req.query.sync);\n });\n\n app.delete<{ Params: { id: string }; Querystring: { sync?: string } }>(\"/api/findings/:id/vote\", async (req) => {\n const id = Number(req.params.id);\n const prev = currentVote(id);\n deleteFindingVote(db, id);\n return maybeSync(id, prev, req.query.sync);\n });\n\n app.post<{ Params: { id: string }; Querystring: { sync?: string }; Body: { tag: string } }>(\"/api/findings/:id/tags\", async (req, reply) => {\n const { tag } = req.body;\n if (!(FINDING_TAGS as readonly string[]).includes(tag)) return reply.code(400).send({ error: \"invalid tag\" });\n const id = Number(req.params.id);\n addFindingTag(db, id, tag);\n return maybeSync(id, currentVote(id), req.query.sync);\n });\n\n app.delete<{ Params: { id: string; tag: string }; Querystring: { sync?: string } }>(\"/api/findings/:id/tags/:tag\", async (req) => {\n const id = Number(req.params.id);\n removeFindingTag(db, id, req.params.tag);\n return maybeSync(id, currentVote(id), req.query.sync);\n });\n\n /** Retry after a failed sync. prevVote = current: re-resolves on \uD83D\uDC4E, never reopens. */\n app.post<{ Params: { id: string } }>(\"/api/findings/:id/sync\", async (req) => {\n const id = Number(req.params.id);\n return maybeSync(id, currentVote(id), \"1\");\n });\n\n app.delete<{ Params: { id: string } }>(\"/api/reviews/:id\", async (req) => {\n deleteMergeRequest(db, Number(req.params.id));\n return { ok: true };\n });\n\n app.delete<{ Params: { id: string } }>(\"/api/scores/:id\", async (req) => {\n deleteScore(db, Number(req.params.id));\n return { ok: true };\n });\n\n app.patch<{ Params: { id: string }; Body: { category: string | null; correctedScore: number; reason: string; correctedNote: string | null } }>(\n \"/api/corrections/:id\",\n async (req) => {\n updateCorrection(db, Number(req.params.id), req.body);\n return { ok: true };\n },\n );\n\n app.delete<{ Params: { id: string } }>(\"/api/corrections/:id\", async (req) => {\n deleteCorrection(db, Number(req.params.id));\n return { ok: true };\n });\n\n app.delete<{ Params: { id: string } }>(\"/api/insights/:id\", async (req) => {\n deleteInsight(db, Number(req.params.id));\n return { ok: true };\n });\n\n registerSettings(app, { db, forgeFor: opts.forgeFor ?? ((host) => { throw new Error(`No git host client for ${host}`); }) });\n\n await app.register(fastifyStatic, { root: WEB_DIST, wildcard: false });\n app.setNotFoundHandler((req, reply) => {\n if (req.raw.url?.startsWith(\"/api/\")) {\n reply.code(404).send({ error: \"not found\" });\n return;\n }\n reply.sendFile(\"index.html\");\n });\n\n return app;\n}\n\nexport async function startDashboard(opts: DashboardOptions = {}): Promise<void> {\n const port = opts.port ?? 4173;\n const token = randomBytes(24).toString(\"base64url\");\n const app = await buildPanel({ ...opts, db: openDb(), token, port, syncOnStart: true });\n await app.listen({ port, host: \"127.0.0.1\" });\n console.log(`[panel] open http://127.0.0.1:${port}/?token=${token}`);\n console.log(\"[panel] the token changes on every start; local access only.\");\n}\n", "import type { DatabaseSync } from \"node:sqlite\";\nimport type { ForgeClient } from \"../../src/forge/types.js\";\n\nexport type Vote = \"up\" | \"down\" | null;\n\n/** Body of our decision reply, or null when there's nothing left to say (no vote, no tags). */\nexport function renderDecision(vote: Vote, note: string | null, tags: string[]): string | null {\n if (!vote && tags.length === 0) return null;\n const lines: string[] = [];\n if (vote === \"up\") lines.push(`\u2705 **Maintainer confirmed this finding.**${note ? ` ${note}` : \"\"}`);\n if (vote === \"down\") lines.push(`\u21A9\uFE0F **Finding withdrawn \u2014 the contributor was right.**${note ? ` ${note}` : \"\"}`);\n if (tags.length > 0) lines.push(`\uD83C\uDFF7\uFE0F ${tags.map((t) => `\\`${t}\\``).join(\" \")}`);\n return lines.join(\"\\n\\n\");\n}\n\n/**\n * Mirrors a finding's current vote + tags into one reply on its forge thread, edited in\n * place (deleted when both are cleared). A \uD83D\uDC4E resolves the thread; moving off a \uD83D\uDC4E\n * (`prevVote`) reopens it. Findings never posted as a thread (e.g. backfill) have nothing\n * to sync \u2014 returns false. DB state is already committed by the caller, so a GitLab failure\n * is recorded in decision_sync_error for retry rather than thrown.\n */\nexport async function syncFindingDecision(\n db: DatabaseSync,\n forgeFor: (host: string) => ForgeClient,\n findingId: number,\n prevVote: Vote,\n): Promise<{ synced: boolean; error?: string }> {\n const row = db\n .prepare(\n `SELECT fd.id AS fd_id, fd.discussion_id, fd.decision_note_id, p.forge_host, p.forge_project_id, mr.mr_iid, fv.vote, fv.note,\n (SELECT GROUP_CONCAT(ft.tag) FROM finding_tags ft WHERE ft.finding_id = f.id) AS tags_concat\n FROM findings f\n JOIN merge_requests mr ON mr.id = f.merge_request_id\n JOIN projects p ON p.id = mr.project_id\n JOIN finding_discussions fd ON fd.merge_request_id = f.merge_request_id AND fd.file IS f.file AND fd.line IS f.line AND fd.issue = f.issue\n LEFT JOIN finding_votes fv ON fv.finding_id = f.id\n WHERE f.id = ?`,\n )\n .get(findingId) as\n | {\n fd_id: number;\n discussion_id: string;\n decision_note_id: number | null;\n forge_host: string;\n forge_project_id: string;\n mr_iid: number;\n vote: Vote;\n note: string | null;\n tags_concat: string | null;\n }\n | undefined;\n if (!row) return { synced: false };\n\n const body = renderDecision(row.vote, row.note, row.tags_concat ? row.tags_concat.split(\",\") : []);\n try {\n // Inside the try: a host with no token is recorded as a sync error, not thrown at the panel.\n const client = forgeFor(row.forge_host);\n let noteId = row.decision_note_id;\n if (body) {\n noteId = await client.upsertDiscussionReply(Number(row.forge_project_id), row.mr_iid, row.discussion_id, body, noteId);\n } else if (noteId != null) {\n await client.deleteDiscussionReply(Number(row.forge_project_id), row.mr_iid, row.discussion_id, noteId);\n noteId = null;\n }\n // Saved before resolving, so a resolve failure + Retry edits this note instead of posting a second one.\n db.prepare(`UPDATE finding_discussions SET decision_note_id = ? WHERE id = ?`).run(noteId, row.fd_id);\n if (row.vote === \"down\") await client.resolveDiscussion(Number(row.forge_project_id), row.mr_iid, row.discussion_id, true);\n else if (prevVote === \"down\") await client.resolveDiscussion(Number(row.forge_project_id), row.mr_iid, row.discussion_id, false);\n\n db.prepare(`UPDATE finding_discussions SET decision_sync_error = NULL WHERE id = ?`).run(row.fd_id);\n return { synced: true };\n } catch (err) {\n const error = (err as Error).message;\n db.prepare(`UPDATE finding_discussions SET decision_sync_error = ? WHERE id = ?`).run(error, row.fd_id);\n return { synced: false, error };\n }\n}\n", "import type { FastifyInstance, FastifyReply } from \"fastify\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { createForge, parseGitAddress, probeForgeType, type ForgeClient, type ForgeType } from \"../../src/forge/index.js\";\nimport { createLlmProvider, type LlmEnv } from \"../../src/llm/index.js\";\nimport { ZonesError } from \"../../src/zones/zones.js\";\nimport { configFilledKeys, forgeUrl, LLM_ENV_KEYS, loadConfig, type LlmProfile } from \"../config/config.js\";\nimport { getSecret, maskSecret, secretBackend } from \"../config/secrets.js\";\nimport {\n conventionsMaxLines,\n currentConventions,\n denied,\n dirTree,\n generateConventions,\n lookAtProject,\n pickFiles,\n readSections,\n saveConventions,\n scrubPrompt,\n suggestConventions,\n} from \"../conventions/generate.js\";\nimport { replayScores } from \"../db/repo.js\";\nimport { forgeToken } from \"../forge.js\";\nimport { bareHost } from \"../paths.js\";\nimport {\n currentWeights,\n missingSteps,\n PROFILE_NAME,\n PROVIDER_PRESETS,\n readSetupState,\n removeForge,\n removeLlmProfile,\n saveForge,\n saveLlmProfile,\n saveWeights,\n setDefaultLlmProfile,\n testLlmProfile,\n tokenHelpUrl,\n WEIGHT_PRESETS,\n} from \"../setup/state.js\";\nimport { currentZones, draftZones, renderZonesYaml, saveZones, skipZones } from \"../zones/generate.js\";\n\n/**\n * Panel settings (Phase 5): every wizard step over HTTP, on the same core as the TUI.\n * Secrets are write-only: accepted here, never returned \u2014 GETs show masked values only.\n */\nexport interface SettingsDeps {\n db: DatabaseSync;\n forgeFor: (host: string) => ForgeClient;\n}\n\ntype Q = { host?: string; path?: string };\nconst bad = (reply: FastifyReply, error: string, code = 400) => reply.code(code).send({ error });\nconst msg = (err: unknown) => (err as Error).message;\n/** A masked value echoed back by a client is never a secret \u2014 treat it as \"not given\". */\nconst secretIn = (v?: string) => (v?.trim() && !v.includes(\"\u2022\u2022\u2022\u2022\") ? v.trim() : undefined);\n\nconst gitlabBases = () => loadConfig().forges.filter((f) => f.type === \"gitlab\" && f.url).map(forgeUrl);\n\n/** host + path from the query/body; paths contain '/', so never route params. */\nfunction project(q: Q): { host: string; path: string } | null {\n return q.host && q.path ? { host: bareHost(q.host), path: q.path } : null;\n}\n\nexport function registerSettings(app: FastifyInstance, deps: SettingsDeps): void {\n /** A host with no token makes forgeFor throw; that's a 400 with its message, not a 500. */\n const look = async (reply: FastifyReply, p: { host: string; path: string }) => {\n try {\n return await lookAtProject(deps.forgeFor(p.host), p.path);\n } catch (err) {\n bad(reply, msg(err));\n return null;\n }\n };\n\n // ---- global settings ----\n\n app.get(\"/api/settings\", async () => {\n const config = loadConfig();\n const shellKey = LLM_ENV_KEYS.find((k) => process.env[k] && !configFilledKeys().includes(k)) ?? null;\n return {\n secretBackend: secretBackend(),\n shellOverride: shellKey,\n defaultForge: config.defaultForge ?? null,\n forges: config.forges.map((f) => {\n const saved = getSecret(`forge:${f.host}`);\n const any = forgeToken(f.host, f.type);\n return { host: f.host, type: f.type, url: f.url ?? null, token: any ? maskSecret(any) : null, tokenSource: saved ? \"saved\" : any ? \"env\" : null, tokenHelp: tokenHelpUrl(f.type, f.host, f.url) };\n }),\n defaultLlmProfile: config.defaultLlmProfile ?? null,\n llmProfiles: config.llmProfiles.map((p) => {\n const key = getSecret(`llm:${p.name}`);\n return { ...p, key: key ? maskSecret(key) : null };\n }),\n providerPresets: PROVIDER_PRESETS,\n weightPresets: WEIGHT_PRESETS,\n };\n });\n\n /** Address \u2192 host/path, and the forge type (saved, from the URL shape, or probed). */\n app.get<{ Querystring: { address?: string } }>(\"/api/settings/detect\", async (req, reply) => {\n const raw = req.query.address?.trim() ?? \"\";\n const withScheme = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(raw) || raw.includes(\"@\") ? raw : `https://${raw}`;\n const a = parseGitAddress(withScheme, gitlabBases());\n if (!a) return bad(reply, \"Not a git address or MR/PR URL\");\n const saved = loadConfig().forges.find((f) => f.host === a.host);\n const type: ForgeType | null = saved?.type ?? a.ref?.type ?? (await probeForgeType(a.host));\n return { host: a.host, projectPath: a.projectPath, type, known: !!saved, tokenHelp: type ? tokenHelpUrl(type, a.host, saved?.url) : null };\n });\n\n /** Token from the body, else the saved/env one for that host \u2014 never another host's. */\n app.post<{ Body: { host: string; type: ForgeType; token?: string; projectPath?: string } }>(\"/api/settings/forges/test\", async (req, reply) => {\n const { type, token, projectPath } = req.body;\n if (!req.body.host || (type !== \"gitlab\" && type !== \"github\")) return bad(reply, \"host and type are required\");\n const host = bareHost(req.body.host);\n const t = secretIn(token) ?? forgeToken(host, type);\n if (!t) return bad(reply, `No token for ${host}`);\n const saved = loadConfig().forges.find((f) => f.host === host);\n const forge = createForge({ type, host, url: saved ? forgeUrl(saved) : undefined, token: t });\n try {\n const me = await forge.getCurrentUser();\n const p = projectPath ? await forge.getProject(projectPath) : null;\n return { ok: true, username: me.username, project: p?.pathWithNamespace ?? null };\n } catch (err) {\n return { ok: false, error: msg(err) };\n }\n });\n\n app.post<{ Body: { host: string; type: ForgeType; token?: string } }>(\"/api/settings/forges\", async (req, reply) => {\n const { type, token } = req.body;\n if (!req.body.host || (type !== \"gitlab\" && type !== \"github\")) return bad(reply, \"host and type are required\");\n saveForge(bareHost(req.body.host), type, secretIn(token));\n return { ok: true };\n });\n\n app.delete<{ Querystring: { host?: string } }>(\"/api/settings/forges\", async (req, reply) => {\n if (!req.query.host) return bad(reply, \"host is required\");\n removeForge(bareHost(req.query.host));\n return { ok: true };\n });\n\n type ProfileBody = { name?: string; provider: LlmProfile[\"provider\"]; model: string; baseUrl?: string; key?: string; makeDefault?: boolean };\n const profileOf = (b: ProfileBody) => ({ provider: b.provider, model: b.model?.trim(), ...(b.baseUrl?.trim() && { baseUrl: b.baseUrl.trim() }) });\n\n /** Test with the key in the body, or the saved key of `name`. */\n app.post<{ Body: ProfileBody }>(\"/api/settings/llm/test\", async (req, reply) => {\n const b = req.body;\n if (!b.provider || !b.model) return bad(reply, \"provider and model are required\");\n // A saved key only ever goes to its own profile's endpoint, never one the request names.\n const typed = secretIn(b.key);\n const saved = !typed && b.name ? loadConfig().llmProfiles.find((p) => p.name === b.name) : undefined;\n const key = typed ?? (saved ? getSecret(`llm:${saved.name}`) : undefined);\n const target = saved ? { provider: saved.provider, model: b.model?.trim() || saved.model, ...(saved.baseUrl && { baseUrl: saved.baseUrl }) } : profileOf(b);\n const started = Date.now();\n try {\n await testLlmProfile(target, key);\n return { ok: true, ms: Date.now() - started };\n } catch (err) {\n return { ok: false, ms: Date.now() - started, error: msg(err) };\n }\n });\n\n app.post<{ Body: ProfileBody }>(\"/api/settings/llm\", async (req, reply) => {\n const b = req.body;\n if (!b.name || !PROFILE_NAME.test(b.name)) return bad(reply, \"Profile name: letters, digits, . _ -\");\n if (![\"anthropic\", \"openai-compatible\", \"ollama\"].includes(b.provider) || !b.model?.trim()) return bad(reply, \"provider and model are required\");\n if (b.provider === \"openai-compatible\" && !b.baseUrl?.trim()) return bad(reply, \"An openai-compatible profile needs a base URL\");\n const existing = loadConfig().llmProfiles.find((p) => p.name === b.name);\n const next = profileOf(b);\n if (existing && !secretIn(b.key) && existing.provider !== \"ollama\" && (existing.provider !== next.provider || (existing.baseUrl ?? \"\") !== (next.baseUrl ?? \"\"))) {\n return bad(reply, \"The endpoint changed \u2014 enter the API key again (a saved key never moves to a new endpoint).\");\n }\n try {\n saveLlmProfile({ name: b.name, ...next } as LlmProfile, secretIn(b.key), b.makeDefault ?? true);\n } catch (err) {\n return bad(reply, msg(err));\n }\n return { ok: true };\n });\n\n app.post<{ Body: { name: string } }>(\"/api/settings/llm/default\", async (req, reply) => {\n try {\n setDefaultLlmProfile(req.body.name);\n } catch (err) {\n return bad(reply, msg(err));\n }\n return { ok: true };\n });\n\n app.delete<{ Querystring: { name?: string } }>(\"/api/settings/llm\", async (req, reply) => {\n if (!req.query.name) return bad(reply, \"name is required\");\n removeLlmProfile(req.query.name);\n return { ok: true };\n });\n\n // ---- per project ----\n\n app.get(\"/api/setup/projects\", async () => deps.db.prepare(\"SELECT id, forge_host AS host, path_with_namespace AS path FROM projects WHERE forge_host IS NOT NULL ORDER BY path_with_namespace\").all());\n\n app.get<{ Querystring: Q }>(\"/api/setup/project\", async (req, reply) => {\n const p = project(req.query);\n if (!p) return bad(reply, \"host and path are required\");\n const conv = currentConventions(p.host, p.path);\n const zones = currentZones(p.host, p.path);\n const read = (f: string | null) => (f && existsSync(f) ? readFileSync(f, \"utf8\") : null);\n const row = deps.db.prepare(\"SELECT id FROM projects WHERE forge_host = ? AND lower(path_with_namespace) = lower(?)\").get(p.host, p.path) as { id: number } | undefined;\n return {\n ...p,\n projectId: row?.id ?? null,\n missing: missingSteps({ host: p.host, projectPath: p.path }),\n conventions: { ...conv, text: read(conv.path), maxLines: conventionsMaxLines() },\n zones: { path: zones.path, fromRepo: zones.fromRepo, graph: zones.graph, text: read(zones.path), skipped: readSetupState(p.host, p.path).zones === \"skip\" },\n weights: currentWeights(p.host, p.path),\n llmReady: !!llmOrNull(),\n };\n });\n\n app.put<{ Body: Q & { text: string } }>(\"/api/setup/conventions\", async (req, reply) => {\n const p = project(req.body);\n if (!p || typeof req.body.text !== \"string\") return bad(reply, \"host, path and text are required\");\n if (currentConventions(p.host, p.path).fromRepo) return bad(reply, \"This project's conventions come from the repo's .yolont/ \u2014 edit them there.\");\n try {\n return { ok: true, path: saveConventions(p.host, p.path, req.body.text) };\n } catch (err) {\n return bad(reply, msg(err));\n }\n });\n\n app.post<{ Body: Q }>(\"/api/setup/conventions/suggest\", async (req, reply) => {\n const p = project(req.body);\n if (!p) return bad(reply, \"host and path are required\");\n const found = await look(reply, p);\n if (!found) return reply;\n const file = suggestConventions(found.stack, currentConventions(p.host, p.path).path ?? undefined);\n return { stack: found.stack, file, text: readFileSync(file, \"utf8\") };\n });\n\n /** Step 1 of generation: what would be sent. Nothing leaves the machine here. */\n app.post<{ Body: Q }>(\"/api/setup/conventions/plan\", async (req, reply) => {\n const p = project(req.body);\n if (!p) return bad(reply, \"host and path are required\");\n const found = await look(reply, p);\n if (!found) return reply;\n if (!found.source) return bad(reply, `Couldn't list the project's files: ${found.error}`);\n return { source: found.source.label, local: !!found.local, stack: found.stack, files: pickFiles(found.files) };\n });\n\n /**\n * Step 2: send the approved files. Trust boundary: the list is re-derived server-side \u2014 only\n * paths the fresh crawl would pick (so never `.env`, keys, or anything unlisted) survive, and\n * the exact prompt is gitleaks-scanned. A scanner failure needs an explicit allowUnscanned.\n */\n app.post<{ Body: Q & { files?: string[]; allowUnscanned?: boolean } }>(\"/api/setup/conventions/generate\", async (req, reply) => {\n const p = project(req.body);\n if (!p) return bad(reply, \"host and path are required\");\n const llm = llmOrNull();\n if (!llm) return bad(reply, \"No LLM configured \u2014 add a profile in Settings first.\");\n const found = await look(reply, p);\n if (!found) return reply;\n if (!found.source) return bad(reply, `Couldn't list the project's files: ${found.error}`);\n const { files: all, source, stack } = found;\n if (req.body.files !== undefined && (!Array.isArray(req.body.files) || !req.body.files.every((f) => typeof f === \"string\"))) return bad(reply, \"files must be a list of paths\");\n const allowed = new Set(pickFiles(all));\n const asked = req.body.files ?? [...allowed];\n const rejected = asked.filter((f) => !allowed.has(f) || denied(f));\n if (rejected.length) return bad(reply, `Not allowed to send: ${rejected.join(\", \")}`);\n\n let scrub;\n try {\n scrub = await scrubPrompt(`${p.host}/${p.path}`, stack, dirTree(all), await readSections(source!, asked));\n } catch (err) {\n return bad(reply, `Nothing sent: ${msg(err)}`);\n }\n if (scrub.scannerFailed && !req.body.allowUnscanned) return reply.code(409).send({ scannerFailed: true, error: `gitleaks couldn't run (${scrub.scannerError}). Nothing sent.` });\n try {\n const out = await generateConventions(llm, scrub.prompt);\n return { ...out, dropped: scrub.dropped, sent: scrub.sent.map((s) => s.path), scannerFailed: scrub.scannerFailed };\n } catch (err) {\n return bad(reply, `Generation failed: ${msg(err)}`, 502);\n }\n });\n\n app.put<{ Body: Q & { text: string } }>(\"/api/setup/zones\", async (req, reply) => {\n const p = project(req.body);\n if (!p || typeof req.body.text !== \"string\") return bad(reply, \"host, path and text are required\");\n if (currentZones(p.host, p.path).fromRepo) return bad(reply, \"This project's zones come from the repo's .yolont/ \u2014 edit them there.\");\n try {\n const out = saveZones(p.host, p.path, req.body.text);\n return { ok: true, path: out, skipped: out === null };\n } catch (err) {\n if (err instanceof ZonesError) return bad(reply, err.message);\n throw err;\n }\n });\n\n app.post<{ Body: Q }>(\"/api/setup/zones/draft\", async (req, reply) => {\n const p = project(req.body);\n if (!p) return bad(reply, \"host and path are required\");\n const found = await look(reply, p);\n if (!found) return reply;\n if (!found.source) return bad(reply, `Couldn't list the project's files: ${found.error}`);\n const d = draftZones(found.files, found.stack);\n return { yaml: renderZonesYaml(d.zones, d.templates), matched: d.matched, templates: d.templates, stack: found.stack };\n });\n\n app.post<{ Body: Q }>(\"/api/setup/zones/skip\", async (req, reply) => {\n const p = project(req.body);\n if (!p) return bad(reply, \"host and path are required\");\n skipZones(p.host, p.path);\n return { ok: true };\n });\n\n /** weights null = keep the built-in rubric (remembered). */\n app.put<{ Body: Q & { weights: Record<string, number> | null; threshold?: number } }>(\"/api/setup/weights\", async (req, reply) => {\n const p = project(req.body);\n if (!p) return bad(reply, \"host and path are required\");\n if (currentWeights(p.host, p.path).fromRepo) return bad(reply, \"This project's weights come from the repo's .yolont/rubric.yml \u2014 change them there.\");\n try {\n return { ok: true, path: saveWeights(p.host, p.path, req.body.weights, req.body.threshold) };\n } catch (err) {\n return bad(reply, msg(err));\n }\n });\n\n app.post<{ Body: Q & { weights: Record<string, number>; threshold?: number } }>(\"/api/setup/weights/replay\", async (req, reply) => {\n const p = project(req.body);\n if (!p || !req.body.weights) return bad(reply, \"host, path and weights are required\");\n const row = deps.db.prepare(\"SELECT id FROM projects WHERE forge_host = ? AND lower(path_with_namespace) = lower(?)\").get(p.host, p.path) as { id: number } | undefined;\n if (!row) return { rows: [], skipped: 0 };\n const saved = currentWeights(p.host, p.path).threshold;\n return replayScores(deps.db, row.id, req.body.weights, req.body.threshold ?? saved, 20, saved);\n });\n}\n\nfunction llmOrNull() {\n try {\n return createLlmProvider(process.env as LlmEnv);\n } catch {\n return null;\n }\n}\n", "import { execFileSync } from \"node:child_process\";\nimport { loadConfig } from \"../config/config.js\";\nimport { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ForgeClient, ProjectRef } from \"../../src/forge/types.js\";\nimport type { LLMProvider } from \"../../src/llm/provider.js\";\nimport { scanDiffForSecrets, type SecretsScanResult } from \"../../src/checks/secrets.js\";\nimport { CONFIG_DIR, DEFAULT_CONVENTIONS_PATH } from \"../paths.js\";\nimport { listConventionFiles, remoteProjectPath, resolveProjectFiles } from \"./resolve.js\";\nimport { projectSettingsDir } from \"../sync/source.js\";\n\n/**\n * Phase 3: a project's conventions.md \u2014 suggested from existing files, or generated by the LLM\n * from a crawl of a local checkout or the forge API. Nothing leaves the machine before the exact\n * prompt passes a gitleaks scan.\n */\n/**\n * Save limit for a conventions file (they go into every review prompt: ~300 lines \u2248 3\u20134k\n * tokens). `conventionsMaxLines` in config.yaml changes it. CI reads a repo's file at any length.\n */\nexport const DEFAULT_CONVENTIONS_MAX_LINES = 300;\nexport const conventionsMaxLines = () => loadConfig().conventionsMaxLines ?? DEFAULT_CONVENTIONS_MAX_LINES;\n/** Asked of the model, leaving room for edits under the cap. */\nconst targetLines = () => Math.floor(conventionsMaxLines() * 0.8);\nconst MAX_FILE_CHARS = 6000;\nconst MAX_TOTAL_CHARS = 60000;\n\nexport interface CrawlSource {\n label: string;\n files: () => Promise<string[]>;\n read: (path: string) => Promise<string | null>;\n}\n\n// ---- sources ----\n\n/** `git ls-files` (respects .gitignore). Symlinks are skipped: one could point at ~/.ssh outside the repo. */\nexport function localSource(repoDir: string): CrawlSource {\n return {\n label: repoDir,\n files: async () =>\n execFileSync(\"git\", [\"-C\", repoDir, \"ls-files\", \"-z\"], { encoding: \"utf8\", maxBuffer: 64 * 1024 * 1024 })\n .split(\"\\0\")\n .filter(Boolean),\n read: async (p) => {\n const full = join(repoDir, p);\n try {\n return lstatSync(full).isFile() ? readFileSync(full, \"utf8\") : null;\n } catch {\n return null;\n }\n },\n };\n}\n\nexport function forgeSource(forge: ForgeClient, project: ProjectRef, ref: string): CrawlSource {\n return { label: `${forge.host} @ ${ref}`, files: () => forge.listFiles(project, ref), read: (p) => forge.readFile(project, p, ref) };\n}\n\nexport interface ProjectLook {\n source: CrawlSource | null;\n files: string[];\n /** Local checkout dir, when the crawl is from one. */\n local: string | null;\n stack: string[];\n /** --repo given but its origin isn't this project. */\n mismatch?: string;\n error?: string;\n}\n\nconst git = (args: string[]) => {\n try {\n return execFileSync(\"git\", args, { encoding: \"utf8\", stdio: [\"ignore\", \"pipe\", \"ignore\"] }).trim();\n } catch {\n return null;\n }\n};\n\n/** File list + stack: `repo`, else `cwd` when its origin is this project, else the forge's default branch. */\nexport async function lookAtProject(forge: ForgeClient, projectPath: string, repo?: string, cwd = process.cwd()): Promise<ProjectLook> {\n const top = repo ?? git([\"-C\", cwd, \"rev-parse\", \"--show-toplevel\"]);\n const origin = top ? git([\"-C\", top, \"remote\", \"get-url\", \"origin\"]) : null;\n const matches = !!origin && remoteProjectPath(origin) === projectPath.toLowerCase();\n const local = top && (repo || matches) ? top : null;\n const mismatch = repo && !matches ? `${repo} doesn't look like a checkout of ${projectPath} (origin: ${origin ?? \"none\"}).` : undefined;\n let source: CrawlSource | null = local ? localSource(local) : null;\n try {\n if (!source) {\n const p = await forge.getProject(projectPath);\n source = forgeSource(forge, p.id, p.defaultBranch);\n }\n const files = await source.files();\n const stack = await detectStack(files, source.read).catch(() => []);\n return { source, files, local, stack, mismatch };\n } catch (err) {\n return { source: null, files: [], local, stack: [], mismatch, error: (err as Error).message };\n }\n}\n\n// ---- stack ----\n\n/** Stack tags from root manifests \u2014 used to suggest conventions (and Phase 4 zone templates). */\nexport async function detectStack(files: string[], read: CrawlSource[\"read\"]): Promise<string[]> {\n // ponytail: root manifests only; monorepo packages/*/package.json aren't inspected.\n const has = (f: string) => files.includes(f);\n const tags = new Set<string>();\n if (has(\"package.json\")) {\n tags.add(\"node\");\n try {\n const pkg = JSON.parse((await read(\"package.json\")) ?? \"{}\") as { dependencies?: object; devDependencies?: object };\n const deps = Object.keys({ ...pkg.dependencies, ...pkg.devDependencies });\n const map: Record<string, string> = { react: \"react\", next: \"nextjs\", vue: \"vue\", svelte: \"svelte\", \"@angular/core\": \"angular\", express: \"express\", fastify: \"fastify\", koa: \"koa\", \"@nestjs/core\": \"nestjs\", typescript: \"typescript\" };\n for (const d of deps) if (map[d]) tags.add(map[d]);\n if ([\"express\", \"fastify\", \"koa\", \"nestjs\"].some((t) => tags.has(t))) tags.add(\"node-api\");\n } catch {\n /* unparseable package.json: \"node\" is enough */\n }\n }\n if (has(\"tsconfig.json\")) tags.add(\"typescript\");\n if (has(\"go.mod\")) tags.add(\"go\");\n if (has(\"Cargo.toml\")) tags.add(\"rust\");\n if (has(\"Gemfile\")) tags.add(\"ruby\");\n if (has(\"composer.json\")) tags.add(\"php\");\n if (has(\"pom.xml\") || has(\"build.gradle\") || has(\"build.gradle.kts\")) tags.add(\"java\");\n if (has(\"pyproject.toml\") || has(\"requirements.txt\") || has(\"setup.py\")) {\n tags.add(\"python\");\n const text = ((await read(\"pyproject.toml\")) ?? \"\") + ((await read(\"requirements.txt\")) ?? \"\");\n for (const fw of [\"django\", \"flask\", \"fastapi\"]) if (new RegExp(`\\\\b${fw}\\\\b`, \"i\").test(text)) tags.add(fw);\n }\n return [...tags];\n}\n\n/** Tags that are ordinary English words need a stricter match (\"unrelated refactors go in a separate PR\"). */\nconst STACK_WORDS: Record<string, RegExp> = { go: /\\b(golang|go\\.mod|gofmt|go modules?|go vet)\\b/, node: /\\bnode(\\.js|js)?\\b/ };\n\n/** Built-ins + other projects' conventions, best stack-word overlap; default.md when nothing matches. */\nexport function suggestConventions(stack: string[], exclude?: string): string {\n // ponytail: keyword overlap on file text \u2014 good enough with a handful of files; embeddings if it ever isn't.\n const projectsDir = join(CONFIG_DIR, \"projects\");\n const own: string[] = [];\n const walk = (d: string, depth: number) => {\n if (depth > 6 || !existsSync(d)) return;\n for (const e of readdirSync(d, { withFileTypes: true })) {\n if (e.isDirectory()) walk(join(d, e.name), depth + 1);\n else if (e.name === \"conventions.md\") own.push(join(d, e.name));\n }\n };\n walk(projectsDir, 0);\n let best = DEFAULT_CONVENTIONS_PATH;\n let bestScore = 0;\n for (const f of [...listConventionFiles(), ...own]) {\n if (f === exclude) continue;\n const text = readFileSync(f, \"utf8\").toLowerCase();\n const score = stack.filter((t) => (STACK_WORDS[t] ?? new RegExp(`\\\\b${t.replace(\"-\", \"[- ]\")}\\\\b`)).test(text)).length;\n if (score > bestScore) [best, bestScore] = [f, score];\n }\n return best;\n}\n\n// ---- file picking ----\n\nconst DENY = [\n /(^|\\/)\\.env($|\\.)/i,\n /\\.(pem|key|p12|pfx|jks|keystore|crt|der|asc|gpg)$/i,\n /(^|\\/)id_(rsa|dsa|ecdsa|ed25519)/i,\n /(^|\\/)(credentials|secrets?)([._-]|$)/i,\n /(^|\\/)(package-lock\\.json|npm-shrinkwrap\\.json|pnpm-lock\\.yaml|yarn\\.lock|go\\.sum|[^/]+\\.lock)$/i,\n /(^|\\/)(node_modules|vendor|dist|build|out|coverage|\\.next)\\//,\n /\\.(min\\.js|map|d\\.ts|snap)$/i,\n /\\.(png|jpe?g|gif|webp|ico|svg|bmp|tiff?|woff2?|ttf|otf|eot|pdf|zip|gz|tgz|bz2|7z|rar|jar|war|class|exe|dll|so|dylib|o|a|wasm|mp[34]|mov|avi|webm|wav|ogg|sqlite|db|bin|parquet)$/i,\n];\n\nconst INSTRUCTIONS = /^(\\.yolont\\/conventions\\.md|AGENTS\\.md|CLAUDE\\.md|\\.cursorrules|\\.cursor\\/rules\\/.+|\\.github\\/copilot-instructions\\.md|CONVENTIONS\\.md|(docs\\/)?(CONTRIBUTING|STYLEGUIDE|STYLE_GUIDE)[^/]*)$/i;\nconst README = /^README[^/]*$/i;\nconst CONFIGS = /^(\\.editorconfig|\\.eslintrc[^/]*|eslint\\.config\\.[^/]+|\\.prettierrc[^/]*|prettier\\.config\\.[^/]+|biome\\.jsonc?|tsconfig\\.json|\\.golangci\\.ya?ml|ruff\\.toml|pyproject\\.toml|setup\\.cfg|\\.rubocop\\.yml|rustfmt\\.toml|\\.stylelintrc[^/]*|package\\.json|go\\.mod|Cargo\\.toml|\\.github\\/pull_request_template\\.md)$/i;\nconst SOURCE = /\\.(ts|tsx|js|jsx|mjs|vue|svelte|go|py|rs|rb|php|java|kt|cs|swift|scala)$/i;\nconst TEST = /(\\.|_)(test|spec)\\.|(^|\\/)(tests?|__tests__|spec)\\//i;\n\nexport const denied = (p: string) => DENY.some((r) => r.test(p));\n\n/**\n * Folders worth sampling from: every directory (depth \u2264 3) that holds source files, with how\n * many, busiest first. The user picks the ones that show the project's conventions best.\n */\nexport function sourceDirs(files: string[], max = 80): { dir: string; count: number }[] {\n const counts = new Map<string, number>();\n for (const f of files) {\n if (denied(f) || !SOURCE.test(f)) continue;\n const parts = f.split(\"/\").slice(0, -1);\n for (let i = 1; i <= Math.min(parts.length, 3); i++) {\n const d = parts.slice(0, i).join(\"/\");\n counts.set(d, (counts.get(d) ?? 0) + 1);\n }\n }\n return [...counts].map(([dir, count]) => ({ dir, count })).sort((a, b) => b.count - a.count || a.dir.localeCompare(b.dir)).slice(0, max);\n}\n\n/**\n * What gets read: instruction files, README, lint/format/build configs, then a spread of source\n * + test samples. With `dirs`, samples come only from those folders (more of them: 2 per folder).\n */\nexport function pickFiles(files: string[], samples = 6, tests = 2, dirs: string[] = []): string[] {\n const inDirs = (f: string) => !dirs.length || dirs.some((d) => f.startsWith(`${d}/`));\n if (dirs.length) {\n samples = Math.min(16, Math.max(samples, dirs.length * 2));\n tests = Math.min(6, Math.max(tests, dirs.length));\n }\n const ok = files.filter((f) => !denied(f));\n const picked = [...ok.filter((f) => INSTRUCTIONS.test(f)), ...ok.filter((f) => README.test(f)), ...ok.filter((f) => CONFIGS.test(f))];\n // One file per directory, round-robin, so samples cover the codebase instead of one folder.\n const spread = (list: string[], n: number) => {\n const byDir = new Map<string, string[]>();\n for (const f of list) {\n // Chosen folders each get their share; otherwise spread over the top two levels.\n const dir = dirs.length ? dirs.filter((d) => f.startsWith(`${d}/`)).sort((a, b) => b.length - a.length)[0]! : f.split(\"/\").slice(0, -1).slice(0, 2).join(\"/\");\n byDir.set(dir, [...(byDir.get(dir) ?? []), f]);\n }\n const out: string[] = [];\n for (let i = 0; out.length < n && [...byDir.values()].some((l) => l.length > i); i++) for (const l of byDir.values()) if (l[i] && out.length < n) out.push(l[i]!);\n return out;\n };\n const src = ok.filter((f) => SOURCE.test(f) && inDirs(f));\n picked.push(...spread(src.filter((f) => !TEST.test(f)), samples), ...spread(src.filter((f) => TEST.test(f)), tests));\n return [...new Set(picked)];\n}\n\n/** Directories only, depth \u2264 3, capped \u2014 the shape of the repo without listing every file. */\nexport function dirTree(files: string[], maxLines = 150): string {\n const dirs = new Set<string>();\n for (const f of files) {\n const parts = f.split(\"/\").slice(0, -1);\n for (let i = 1; i <= Math.min(parts.length, 3); i++) dirs.add(parts.slice(0, i).join(\"/\") + \"/\");\n }\n const list = [...dirs].filter((d) => !denied(d)).sort();\n return list.slice(0, maxLines).join(\"\\n\") + (list.length > maxLines ? `\\n\u2026 ${list.length - maxLines} more` : \"\");\n}\n\nexport interface Section {\n path: string;\n text: string;\n}\n\n/** Reads picked files with per-file and total caps; binary-looking content is dropped. */\nexport async function readSections(source: CrawlSource, picked: string[]): Promise<Section[]> {\n const out: Section[] = [];\n let total = 0;\n for (const path of picked) {\n if (total >= MAX_TOTAL_CHARS) break;\n const raw = await source.read(path);\n if (raw == null || raw.includes(\"\\0\")) continue;\n const room = Math.min(MAX_FILE_CHARS, MAX_TOTAL_CHARS - total);\n const text = raw.length > room ? `${raw.slice(0, room)}\\n\u2026 (truncated)` : raw;\n total += text.length;\n out.push({ path, text });\n }\n return out;\n}\n\n// ---- prompt + scan ----\n\n/** The exact prompt sent, plus each file's 1-based line range in it (to map gitleaks hits back). */\nexport function renderPrompt(project: string, stack: string[], tree: string, sections: Section[]): { prompt: string; ranges: { path: string; start: number; end: number }[] } {\n const example = readFileSync(DEFAULT_CONVENTIONS_PATH, \"utf8\");\n const head = `You write the team conventions file for the code-review bot Yolont. The file is fed to an LLM reviewer that grades pull requests on \"conventions\" and \"maintainability\", so every rule must be checkable against a diff.\n\nProject: ${project}\nDetected stack: ${stack.join(\", \") || \"unknown\"}\n\nRules for the file:\n- At most ${targetLines()} lines of Markdown (hard limit). Shorter is better: only rules a reviewer can check in a diff.\n- Only rules the evidence below supports: instruction files (AGENTS.md, CONTRIBUTING, \u2026), lint/format configs, and patterns visible in the sampled code. Don't invent rules or restate generic advice (\"write clean code\").\n- Specific and example-driven: name real directories, helpers, naming patterns and test layout from this repo.\n- Where a tool enforces something (formatter, linter), say so in one line instead of listing its rules.\n- Use headings like the example's (Naming, Structure, Tests, Error handling, PR hygiene, Security); drop ones with no evidence.\n- Never include secrets, hostnames, internal URLs or people's names.\n\nFormat example (generic content \u2014 replace it with this project's rules):\n<example>\n${example.trim()}\n</example>\n\nAnswer with exactly two blocks and nothing else:\n<summary>3\u20136 bullet points: what you understood about the project (purpose, stack, layout, notable conventions).</summary>\n<conventions>\n\u2026the file\u2026\n</conventions>\n\nRepository directory tree:\n${tree}\n\nFiles:\n`;\n let line = head.split(\"\\n\").length;\n const ranges: { path: string; start: number; end: number }[] = [];\n const parts = sections.map((s) => {\n const block = `=== ${s.path} ===\\n${s.text}\\n`;\n const n = block.split(\"\\n\").length - 1;\n ranges.push({ path: s.path, start: line, end: line + n - 1 });\n line += n;\n return block;\n });\n return { prompt: head + parts.join(\"\"), ranges };\n}\n\nexport interface ScrubResult {\n prompt: string;\n sent: Section[];\n /** Files left out because gitleaks flagged them. */\n dropped: string[];\n scannerFailed: boolean;\n scannerError?: string;\n}\n\n/** Scans the exact prompt; drops flagged files and rescans until clean. A hit outside any file section throws. */\nexport async function scrubPrompt(\n project: string,\n stack: string[],\n tree: string,\n sections: Section[],\n scan: (text: string) => Promise<SecretsScanResult> = scanDiffForSecrets,\n): Promise<ScrubResult> {\n let sent = sections;\n const dropped: string[] = [];\n for (;;) {\n const { prompt, ranges } = renderPrompt(project, stack, tree, sent);\n const res = await scan(prompt);\n if (res.scannerFailed) return { prompt, sent, dropped, scannerFailed: true, scannerError: res.scannerError };\n if (!res.findings.length) return { prompt, sent, dropped, scannerFailed: false };\n const bad = new Set<string>();\n for (const f of res.findings) {\n const r = ranges.find((x) => f.line >= x.start && f.line <= x.end);\n if (!r) throw new Error(`gitleaks flagged line ${f.line} of the prompt outside any file (${f.ruleId}) \u2014 not sending.`);\n bad.add(r.path);\n }\n dropped.push(...bad);\n sent = sent.filter((s) => !bad.has(s.path));\n }\n}\n\n// ---- generate + save ----\n\nexport function parseGenerated(text: string): { summary: string; conventions: string } {\n const tag = (name: string) => text.match(new RegExp(`<${name}>([\\\\s\\\\S]*?)(?:</${name}>|$)`))?.[1]?.trim();\n const strip = (s: string) => s.replace(/^```(?:markdown|md)?\\n/, \"\").replace(/\\n```$/, \"\").trim();\n return { summary: tag(\"summary\") ?? \"\", conventions: strip(tag(\"conventions\") ?? text.trim()) + \"\\n\" };\n}\n\nexport async function generateConventions(provider: LLMProvider, prompt: string): Promise<{ summary: string; conventions: string }> {\n return parseGenerated(await provider.complete(prompt));\n}\n\n/**\n * A pasted path as terminals and file managers actually deliver it: file:// URLs (percent-encoded),\n * 'quoted' or \"quoted\", shell-escaped spaces (`my\\ dir`), stray bracketed-paste markers, ~.\n */\nexport function normalizePastedPath(raw: string, home: string): string {\n let p = raw.replace(/\\x1b\\[20[01]~/g, \"\").trim();\n if (/^(['\"]).*\\1$/.test(p)) p = p.slice(1, -1);\n if (/^file:\\/\\//i.test(p)) {\n try {\n p = decodeURIComponent(new URL(p).pathname);\n } catch {\n p = p.replace(/^file:\\/\\//i, \"\");\n }\n } else {\n p = p.replace(/\\\\(.)/g, \"$1\"); // shell escapes: \"my\\ dir\" -> \"my dir\"\n }\n return p.replace(/^~(?=$|\\/)/, home);\n}\n\nexport const lineCount = (text: string) => (text.trimEnd() ? text.trimEnd().split(\"\\n\").length : 0);\n\n/** Writes the project's conventions.md (user dir, or its team data repo when shared). Over the cap is refused, never truncated. */\nexport function saveConventions(host: string, path: string, text: string): string {\n const n = lineCount(text);\n const max = conventionsMaxLines();\n if (n > max) throw new Error(`Conventions are ${n} lines; the limit is ${max} (conventionsMaxLines in config.yaml).`);\n const dir = projectSettingsDir(host, path);\n mkdirSync(dir, { recursive: true });\n const out = join(dir, \"conventions.md\");\n writeFileSync(out, text.trimEnd() + \"\\n\");\n return out;\n}\n\n/** Where this project's conventions come from now. `fromRepo`: the committed .yolont/ file, which shadows ours. */\nexport function currentConventions(host: string, path: string): { path: string | null; fromRepo: boolean } {\n const p = resolveProjectFiles(host, path).conventions;\n return { path: p, fromRepo: !!p && !p.startsWith(projectSettingsDir(host, path)) };\n}\n", "import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport yaml from \"js-yaml\";\nimport type { ForgeClient, ProjectRef } from \"../../src/forge/types.js\";\nimport { createProviderFromProfile } from \"../../src/llm/index.js\";\nimport { loadRubric } from \"../../src/rubric/loader.js\";\nimport { RubricSchema } from \"../../src/rubric/schema.js\";\nimport { LLM_ENV_KEYS, loadConfig, reapplyConfigToEnv, saveConfig, type LlmProfile } from \"../config/config.js\";\nimport { deleteSecret, getSecret, setSecret } from \"../config/secrets.js\";\nimport { resolveProjectFiles } from \"../conventions/resolve.js\";\nimport { forgeToken } from \"../forge.js\";\nimport { DEFAULT_RUBRIC_PATH, userProjectDir } from \"../paths.js\";\nimport { projectSettingsDir } from \"../sync/source.js\";\n\n/**\n * Setup core shared by the TUI wizard and (Phase 5) the panel checklist: what's missing,\n * and the save/test operations behind each step. No prompts here.\n */\nexport type Step = \"forge\" | \"llm\" | \"conventions\" | \"zones\" | \"weights\";\n\nexport interface ProjectCtx {\n host?: string;\n projectPath?: string;\n}\n\n/** Per-project answers that aren't files themselves \u2014 so a \"keep defaults\" isn't re-asked every run. */\nexport interface SetupState {\n weights?: \"default\" | \"custom\";\n /** Zones are optional: \"skip\" means don't ask again. */\n zones?: \"skip\";\n}\n\nconst statePath = (host: string, path: string) => join(userProjectDir(host, path), \"setup.yaml\");\n\nexport function readSetupState(host: string, path: string): SetupState {\n const p = statePath(host, path);\n return existsSync(p) ? ((yaml.load(readFileSync(p, \"utf8\")) as SetupState | null) ?? {}) : {};\n}\n\nexport function writeSetupState(host: string, path: string, patch: SetupState): void {\n const p = statePath(host, path);\n mkdirSync(userProjectDir(host, path), { recursive: true });\n writeFileSync(p, yaml.dump({ ...readSetupState(host, path), ...patch }));\n}\n\nexport function missingSteps(ctx: ProjectCtx, env: NodeJS.ProcessEnv = process.env): Step[] {\n const config = loadConfig();\n const missing: Step[] = [];\n const forge = ctx.host ? config.forges.find((f) => f.host === ctx.host) : undefined;\n const type = forge?.type ?? (ctx.host === \"github.com\" ? \"github\" : undefined);\n if (!ctx.host || !type || !forgeToken(ctx.host, type, env)) missing.push(\"forge\");\n\n const profile = config.llmProfiles.find((p) => p.name === config.defaultLlmProfile) ?? config.llmProfiles[0];\n const profileUsable = profile && (profile.provider === \"ollama\" || !!getSecret(`llm:${profile.name}`));\n if (!profileUsable && !LLM_ENV_KEYS.some((k) => env[k])) missing.push(\"llm\");\n\n if (ctx.host && ctx.projectPath && !resolveProjectFiles(ctx.host, ctx.projectPath).conventions) missing.push(\"conventions\");\n if (ctx.host && ctx.projectPath && !resolveProjectFiles(ctx.host, ctx.projectPath).zones && readSetupState(ctx.host, ctx.projectPath).zones !== \"skip\") missing.push(\"zones\");\n if (ctx.host && ctx.projectPath && resolveProjectFiles(ctx.host, ctx.projectPath).rubric === DEFAULT_RUBRIC_PATH && !readSetupState(ctx.host, ctx.projectPath).weights) {\n missing.push(\"weights\");\n }\n return missing;\n}\n\n// ---- forge ----\n\n/** Proves the token works for this project: who am I + can I see it. */\nexport async function testForge(forge: ForgeClient, project: ProjectRef): Promise<{ username: string; pathWithNamespace: string }> {\n const [me, p] = await Promise.all([forge.getCurrentUser(), forge.getProject(project)]);\n return { username: me.username, pathWithNamespace: p.pathWithNamespace };\n}\n\n/** Where to create a token, prefilled where the forge supports it. */\nexport function tokenHelpUrl(type: \"gitlab\" | \"github\", host: string, baseUrl?: string): string {\n if (type === \"github\") return `https://${host}/settings/tokens/new?scopes=repo&description=Yolont`;\n return `${(baseUrl ?? `https://${host}`).replace(/\\/$/, \"\")}/-/user_settings/personal_access_tokens?name=Yolont&scopes=api`;\n}\n\n/** Records host\u2192type (and the token when given \u2014 only ever on an explicit save). First forge becomes the default. */\nexport function saveForge(host: string, type: \"gitlab\" | \"github\", token?: string): void {\n const config = loadConfig();\n const saved = config.forges.find((f) => f.host === host);\n if (saved) saved.type = type;\n else config.forges.push({ host, type });\n config.defaultForge ??= host;\n saveConfig(config);\n if (token) setSecret(`forge:${host}`, token);\n}\n\nexport function removeForge(host: string): void {\n const config = loadConfig();\n config.forges = config.forges.filter((f) => f.host !== host);\n if (config.defaultForge === host) config.defaultForge = config.forges[0]?.host;\n saveConfig(config);\n deleteSecret(`forge:${host}`);\n}\n\n// ---- llm ----\n\nexport interface ProviderPreset {\n label: string;\n provider: LlmProfile[\"provider\"];\n name: string;\n baseUrl?: string;\n model?: string;\n hint?: string;\n}\n\n// Models aren't guessed for gateways whose catalog we don't track \u2014 the user types the id.\nexport const PROVIDER_PRESETS: ProviderPreset[] = [\n { label: \"Anthropic (Claude API)\", provider: \"anthropic\", name: \"anthropic\", model: \"claude-opus-5-5\", hint: \"or claude-sonnet-5-5 \u2014 cheaper\" },\n { label: \"OpenCode\", provider: \"openai-compatible\", name: \"opencode\", baseUrl: \"https://opencode.ai/zen/v1\", model: \"deepseek-v4.1-flash\", hint: \"formerly Zen \u00B7 key from opencode.ai/console\" },\n { label: \"OpenRouter\", provider: \"openai-compatible\", name: \"openrouter\", baseUrl: \"https://openrouter.ai/api/v1\" },\n { label: \"OpenAI\", provider: \"openai-compatible\", name: \"openai\", baseUrl: \"https://api.openai.com/v1\", hint: \"an OpenAI model id (gpt-\u2026), not another gateway's\" },\n { label: \"Other OpenAI-compatible gateway\", provider: \"openai-compatible\", name: \"gateway\" },\n { label: \"Ollama (local, offline)\", provider: \"ollama\", name: \"ollama\", baseUrl: \"http://localhost:11434\", model: \"qwen2.5-coder\", hint: \"no key\" },\n];\n\nexport const PROFILE_NAME = /^[a-z0-9][a-z0-9._-]*$/i;\n\n/** Adds or updates a profile (names are immutable: the key lives under `llm:<name>`) and makes it the default. */\nexport function saveLlmProfile(profile: LlmProfile, key?: string, makeDefault = true): void {\n if (!PROFILE_NAME.test(profile.name)) throw new Error(\"Profile name: letters, digits, . _ -\");\n const config = loadConfig();\n config.llmProfiles = [...config.llmProfiles.filter((p) => p.name !== profile.name), profile];\n if (makeDefault || !config.defaultLlmProfile) config.defaultLlmProfile = profile.name;\n saveConfig(config);\n if (key) setSecret(`llm:${profile.name}`, key);\n reapplyConfigToEnv();\n}\n\nexport function setDefaultLlmProfile(name: string): void {\n const config = loadConfig();\n if (!config.llmProfiles.some((p) => p.name === name)) throw new Error(`No profile '${name}'`);\n config.defaultLlmProfile = name;\n saveConfig(config);\n reapplyConfigToEnv();\n}\n\nexport function removeLlmProfile(name: string): void {\n const config = loadConfig();\n config.llmProfiles = config.llmProfiles.filter((p) => p.name !== name);\n if (config.defaultLlmProfile === name) config.defaultLlmProfile = config.llmProfiles[0]?.name;\n saveConfig(config);\n deleteSecret(`llm:${name}`);\n reapplyConfigToEnv();\n}\n\n/** A real review call on a one-line diff \u2014 proves key, model, base URL and JSON-schema output all work. */\nexport async function testLlmProfile(profile: Pick<LlmProfile, \"provider\" | \"model\" | \"baseUrl\">, apiKey: string | undefined): Promise<void> {\n const res = await createProviderFromProfile(profile, apiKey).review({\n diff: \"diff --git a/hello.ts b/hello.ts\\n--- a/hello.ts\\n+++ b/hello.ts\\n@@ -0,0 +1 @@\\n+export const hello = () => \\\"hi\\\";\\n\",\n truncated: false,\n conventions: \"\",\n categories: [{ name: \"smoke_test\", description: \"Connectivity check. Score 100 unless the diff is empty.\" }],\n authorHistorySummary: \"\",\n });\n if (!res.categories.some((c) => c.category === \"smoke_test\")) throw new Error(\"The model answered, but not in the expected review format.\");\n}\n\n// ---- weights ----\n\n/** Applied only when the rubric's category names match the preset's exactly. */\nexport const WEIGHT_PRESETS: Record<string, { label: string; weights: Record<string, number> }> = {\n conventions: { label: \"Conventions-first (default)\", weights: { conventions: 30, maintainability: 30, ai_authenticity: 20, security: 12, pr_hygiene: 8 } },\n balanced: { label: \"Balanced\", weights: { conventions: 20, maintainability: 20, ai_authenticity: 20, security: 20, pr_hygiene: 20 } },\n security: { label: \"Security-first\", weights: { security: 35, conventions: 20, maintainability: 20, ai_authenticity: 15, pr_hygiene: 10 } },\n};\n\nexport function presetFits(weights: Record<string, number>, names: string[]): boolean {\n const keys = Object.keys(weights);\n return keys.length === names.length && names.every((n) => n in weights);\n}\n\n/** Scales to sum 100 with whole numbers (largest remainder, so it always lands on exactly 100). */\nexport function normalizeWeights(weights: Record<string, number>): Record<string, number> {\n const entries = Object.entries(weights);\n const total = entries.reduce((s, [, w]) => s + w, 0);\n if (total <= 0) return Object.fromEntries(entries.map(([k], i) => [k, Math.floor(100 / entries.length) + (i < 100 % entries.length ? 1 : 0)]));\n const exact = entries.map(([k, w]) => ({ k, v: (w / total) * 100 }));\n const out = exact.map((e) => ({ ...e, floor: Math.floor(e.v) }));\n let rest = 100 - out.reduce((s, e) => s + e.floor, 0);\n for (const e of [...out].sort((a, b) => b.v - b.floor - (a.v - a.floor))) if (rest-- > 0) e.floor++;\n return Object.fromEntries(out.map((e) => [e.k, e.floor]));\n}\n\n/**\n * `null` = keep the built-in rubric (remembered, not re-asked). Otherwise writes the project's\n * own rubric.yml \u2014 the current rubric with new weights \u2014 to the user project dir, where\n * resolveProjectFiles picks it up. Commit it as .yolont/rubric.yml to share it with the team/CI.\n * ponytail: a copy, so later changes to the built-in rubric's other fields don't flow into it.\n */\nexport function saveWeights(host: string, path: string, weights: Record<string, number> | null, threshold?: number): string | null {\n if (!weights) {\n writeSetupState(host, path, { weights: \"default\" });\n return null;\n }\n const source = resolveProjectFiles(host, path).rubric;\n const raw = yaml.load(readFileSync(source, \"utf8\")) as { categories: { name: string; weight: number }[]; threshold?: number };\n for (const c of raw.categories) if (c.name in weights) c.weight = weights[c.name]!;\n if (threshold !== undefined) raw.threshold = threshold;\n RubricSchema.parse(raw); // must still sum to 100 etc. \u2014 never write a rubric the loader rejects\n const out = join(projectSettingsDir(host, path), \"rubric.yml\");\n mkdirSync(projectSettingsDir(host, path), { recursive: true });\n writeFileSync(out, `# Yolont rubric for ${host}/${path} \u2014 weights set by \\`yolont setup\\`. Copy to .yolont/rubric.yml in the repo to share it.\\n${yaml.dump(raw)}`);\n writeSetupState(host, path, { weights: \"custom\" });\n return out;\n}\n\nexport function currentWeights(host: string, path: string): { weights: Record<string, number>; threshold: number; rubricPath: string; fromRepo: boolean } {\n const rubricPath = resolveProjectFiles(host, path).rubric;\n const rubric = loadRubric(rubricPath);\n return {\n weights: Object.fromEntries(rubric.categories.map((c) => [c.name, c.weight])),\n threshold: rubric.threshold,\n rubricPath,\n // Not the built-in and not ours: it's the repo's committed .yolont/rubric.yml, which wins.\n fromRepo: rubricPath !== DEFAULT_RUBRIC_PATH && !rubricPath.startsWith(projectSettingsDir(host, path)),\n };\n}\n", "import { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport yaml from \"js-yaml\";\nimport { globToRegExp, parseZones, type Zone } from \"../../src/zones/zones.js\";\nimport { resolveProjectFiles } from \"../conventions/resolve.js\";\nimport { ZONE_TEMPLATES_DIR } from \"../paths.js\";\nimport { writeSetupState } from \"../setup/state.js\";\nimport { projectSettingsDir } from \"../sync/source.js\";\n\n/**\n * Phase 4: a first zones.yaml from stack templates matched against the real file tree. Paths\n * only, deterministic, nothing leaves the machine. Zones are optional \u2014 skipping is a saved answer.\n */\n\n/** Stack-specific first (nextjs beats react-spa), generic always last. */\nexport function templatesFor(stack: string[]): string[] {\n const ids: string[] = [];\n if (stack.includes(\"nextjs\")) ids.push(\"nextjs\");\n else if (stack.includes(\"react\")) ids.push(\"react-spa\");\n if (stack.includes(\"node-api\")) ids.push(\"node-api\");\n return [...ids, \"generic\"];\n}\n\nexport const loadTemplate = (id: string): Zone[] => parseZones(readFileSync(join(ZONE_TEMPLATES_DIR, `${id}.yaml`), \"utf8\"), `Zone template '${id}'`);\n\nexport interface ZonesDraft {\n zones: Zone[];\n /** zone id \u2192 how many repo files it matches today */\n matched: Record<string, number>;\n templates: string[];\n}\n\n/**\n * Keeps only globs that match a real file (so the draft reads like this repo) and drops zones\n * left with none. A zone id seen earlier wins (templates share ids like `migrations`). Generic\n * zones whose files a stack zone already covers are dropped as noise.\n */\nexport function draftZones(files: string[], stack: string[]): ZonesDraft {\n const templates = templatesFor(stack);\n const zones: Zone[] = [];\n const matched: Record<string, number> = {};\n const covered = new Set<string>();\n for (const t of templates) {\n for (const zone of loadTemplate(t)) {\n if (zones.some((z) => z.id === zone.id)) continue;\n const paths = zone.paths.filter((p) => files.some((f) => globToRegExp(p).test(f)));\n if (!paths.length) continue;\n const res = paths.map(globToRegExp);\n const hits = files.filter((f) => res.some((r) => r.test(f)));\n if (t === \"generic\" && templates.length > 1 && hits.every((f) => covered.has(f))) continue;\n if (t !== \"generic\") hits.forEach((f) => covered.add(f));\n zones.push({ ...zone, paths });\n matched[zone.id] = hits.length;\n }\n }\n return { zones, matched, templates };\n}\n\nconst HEADER = `# Yolont zones: parts of this project where a mistake costs more, so reviews call them out.\n# level: red = runs on every start/request/render or is hard to undo; amber = widely shared; green = rarely runs.\n# paths: globs (** spans folders, * stays in one). Zones are optional; a project with none reviews fine.\n# Commit as .yolont/zones.yaml to share with the team and CI.\n`;\n\nexport function renderZonesYaml(zones: Zone[], templates: string[] = []): string {\n const plain = zones.map(({ budget, watch_for, ...z }) => ({ ...z, ...(watch_for.length && { watch_for }), ...(budget && { budget }) }));\n return `${HEADER}${templates.length ? `# Drafted from templates: ${templates.join(\", \")}\\n` : \"\"}${yaml.dump({ zones: plain }, { lineWidth: 140, flowLevel: 3 })}`;\n}\n\n/** Validates (ZonesError on bad YAML/schema) and writes the user-dir zones.yaml. An empty list is saved as \"skip\", not a file. */\nexport function saveZones(host: string, path: string, raw: string): string | null {\n if (!parseZones(raw).length) {\n skipZones(host, path);\n return null;\n }\n const dir = projectSettingsDir(host, path);\n mkdirSync(dir, { recursive: true });\n const out = join(dir, \"zones.yaml\");\n writeFileSync(out, raw.endsWith(\"\\n\") ? raw : `${raw}\\n`);\n return out;\n}\n\nexport const skipZones = (host: string, path: string) => writeSetupState(host, path, { zones: \"skip\" });\n\nexport function currentZones(host: string, path: string): { path: string | null; fromRepo: boolean; graph: string | null } {\n const f = resolveProjectFiles(host, path);\n return { path: f.zones, fromRepo: !!f.zones && !f.zones.startsWith(projectSettingsDir(host, path)), graph: f.zonesGraph };\n}\n", "import { execFileSync, spawnSync } from \"node:child_process\";\nimport { header, icon, iconSample, nerdIcons, panel, type IconName } from \"./ui.js\";\nimport { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { homedir, tmpdir, userInfo } from \"node:os\";\nimport { emitKeypressEvents } from \"node:readline\";\nimport { join, resolve } from \"node:path\";\nimport { autocompleteMultiselect, confirm, intro, isCancel, log, multiselect, note, outro, password, select, spinner, text } from \"@clack/prompts\";\nimport pc from \"picocolors\";\nimport { changeLabel, createForge, parseGitAddress, probeForgeType, type ForgeClient, type ForgeType, type GitAddress } from \"../../src/forge/index.js\";\nimport { configFilledKeys, forgeUrl, LLM_ENV_KEYS, loadConfig, reapplyConfigToEnv, saveConfig, type LlmProfile } from \"../config/config.js\";\nimport { getSecret, maskSecret, secretBackend, setSecret } from \"../config/secrets.js\";\nimport { forgeToken } from \"../forge.js\";\nimport { createLlmProvider, type LlmEnv } from \"../../src/llm/index.js\";\nimport {\n conventionsMaxLines,\n currentConventions,\n dirTree,\n generateConventions,\n lineCount,\n lookAtProject,\n normalizePastedPath,\n sourceDirs,\n type ProjectLook,\n pickFiles,\n readSections,\n saveConventions,\n scrubPrompt,\n suggestConventions,\n type CrawlSource,\n} from \"../conventions/generate.js\";\nimport { currentZones, draftZones, renderZonesYaml, saveZones, skipZones } from \"../zones/generate.js\";\nimport { ZonesError } from \"../../src/zones/zones.js\";\nimport { DEFAULT_RUBRIC_PATH, bareHost } from \"../paths.js\";\nimport { runInteractiveReview } from \"../review/interactiveReview.js\";\nimport { openDb } from \"../db/client.js\";\nimport { addSource, checkSource, displayUrl, getSource, isKeptLocal, keepLocal, pendingToSend, removeSource, sourceDir, waitingForMerge, pullSource, shareProject, sourceFor, sourcesForHost, stopUsing, syncSource, type SourceStatus, type SyncResult } from \"../sync/source.js\";\nimport type { ImportResult } from \"../sync/records.js\";\nimport type { SourceConfig } from \"../config/config.js\";\nimport { GITLEAKS_VERSION, gitleaksAsset, gitleaksWorks, installGitleaks, LOCAL_GITLEAKS } from \"./gitleaks.js\";\nimport { installKind, installLatest, isNewer, latestVersion, ownVersion } from \"./version.js\";\nimport { PROFILE_NAME, PROVIDER_PRESETS, removeForge, removeLlmProfile, saveForge, saveLlmProfile, currentWeights, missingSteps, normalizeWeights, presetFits, saveWeights, testForge, testLlmProfile, tokenHelpUrl, WEIGHT_PRESETS, type Step } from \"./state.js\";\n\n/** Ctrl-C: leave Yolont. */\nclass Cancelled extends Error {}\n/** Esc: leave this step (nothing saved) and go back to the menu. */\nclass Back extends Error {}\n\n// clack reports Esc and Ctrl-C both as \"cancel\"; the last key pressed tells them apart. Our\n// listener is registered before any prompt's, so it has run by the time the prompt resolves.\nlet lastKey = \"\";\nlet tracking = false;\nfunction trackKeys(): void {\n if (tracking || !process.stdin.isTTY) return;\n tracking = true;\n emitKeypressEvents(process.stdin);\n process.stdin.on(\"keypress\", (_s: string, k?: { name?: string; ctrl?: boolean }) => {\n lastKey = k?.ctrl && k.name === \"c\" ? \"ctrl-c\" : (k?.name ?? \"\");\n // A pasted trailing newline arrives as \"\\n\" (key \"enter\"), not Enter (\"\\r\", key \"return\").\n // readline treats it as end-of-line: it clears the input and files it in history, so the\n // paste flashes and vanishes (\u2191 brings it back). Turn it into a real Enter first \u2014 this\n // listener runs before readline's, which then sees a finished prompt.\n if (newlineSubmits && k?.name === \"enter\") process.stdin.emit(\"keypress\", \"\\r\", { name: \"return\", sequence: \"\\r\", ctrl: false, meta: false, shift: false });\n });\n}\n\n/** Only for single-line inputs: a multi-line prompt (the review's focus note) needs real newlines. */\nlet newlineSubmits = false;\nasync function askLine<T>(prompt: Promise<T | symbol>): Promise<T> {\n newlineSubmits = true;\n try {\n return await ask(prompt);\n } finally {\n newlineSubmits = false;\n }\n}\n\n/** Unwraps a clack answer: Esc \u2192 Back (to the menu), Ctrl-C \u2192 Cancelled (quit). */\nasync function ask<T>(prompt: Promise<T | symbol>): Promise<T> {\n const v = await prompt;\n if (isCancel(v)) throw lastKey === \"escape\" ? new Back() : new Cancelled();\n return v as T;\n}\n\n/** Runs one step; Esc inside it returns false instead of ending the wizard. */\nasync function orBack(step: () => Promise<unknown>): Promise<boolean> {\n try {\n await step();\n return true;\n } catch (err) {\n if (err instanceof Back) {\n log.info(\"Back \u2014 nothing saved for that step.\");\n return false;\n }\n throw err;\n }\n}\n\nconst sum = (w: Record<string, number>) => Object.values(w).reduce((a, b) => a + b, 0);\n\nfunction originAddress(): string | undefined {\n try {\n return execFileSync(\"git\", [\"remote\", \"get-url\", \"origin\"], { encoding: \"utf8\", stdio: [\"ignore\", \"pipe\", \"ignore\"] }).trim() || undefined;\n } catch {\n return undefined;\n }\n}\n\nconst gitlabBases = () => loadConfig().forges.filter((f) => f.type === \"gitlab\" && f.url).map(forgeUrl);\n\nexport interface SetupOptions {\n /** MR/PR URL or git address; defaults to this checkout's origin. */\n address?: string;\n /** Only these steps, each shown as keep/change (`setup --step`). Default: whatever is missing. */\n steps?: Step[];\n /** `setup` with no --step: walk every step as keep/change. */\n all?: boolean;\n /** Finish with the review picker (bare `yolont`). */\n review?: boolean;\n /** `conventions generate --repo <path>`: crawl this checkout instead of cwd. */\n repo?: string;\n /** `conventions generate|edit`: skip keep/change and go straight to it. */\n conventions?: \"generate\" | \"edit\";\n /** `zones generate|edit`: same, for zones. */\n zones?: \"generate\" | \"edit\";\n}\n\n/**\n * `yolont` / `yolont setup`. Bare `yolont` asks only for what's missing, then picks a PR to\n * review, so a configured machine goes straight to the picker. Every step shows the saved\n * value first, so re-running is cheap.\n */\nexport async function runSetup(opts: SetupOptions): Promise<void> {\n const version = ownVersion();\n latestCheck = latestVersion(); // in the background; the menu shows it if it came back\n header(`${version ? `v${version} \u00B7 ` : \"\"}PR reviews that look twice \u00B7 Esc = back \u00B7 Ctrl-C = quit`);\n await offerInstallOnce();\n await ensureGitleaks();\n await askIconsOnce();\n intro(opts.review ? \"Yolont\" : \"Yolont setup\");\n trackKeys();\n try {\n const forceAll = !!opts.all;\n const wants = (s: Step, missing: Step[]) => forceAll || opts.steps?.includes(s) || (!opts.steps && missing.includes(s));\n const change = (s: Step) => forceAll || !!opts.steps?.includes(s);\n\n // LLM profiles are global: `setup --step llm` needs no project, so don't make it touch the forge.\n const needsProject = opts.review || forceAll || !opts.steps || opts.steps.some((s) => s !== \"llm\");\n if (!needsProject) {\n await orBack(() => llmStep(true));\n outro(\"Done.\");\n return;\n }\n\n // The git host comes first: every other step needs it. Esc here has nothing to go back to.\n const raw = opts.address ?? originAddress();\n const parsed = parseAddress(raw);\n const missing = missingSteps({ host: parsed?.host, projectPath: parsed?.projectPath });\n let ctx: { forge: ForgeClient; address: GitAddress };\n try {\n ctx = await forgeStep(parsed, raw, wants(\"forge\", missing) || !parsed);\n } catch (err) {\n if (err instanceof Back) throw new Cancelled();\n throw err;\n }\n\n // The project's memory repo next: pulled conventions/zones change what's missing below.\n await orBack(() => memoryStep(ctx.address));\n\n // Walk what's missing (or what was asked for). Esc skips to the menu (bare `yolont`) or to the next step (`setup`).\n const missingNow = missingSteps({ host: ctx.address.host, projectPath: ctx.address.projectPath });\n for (const s of [\"llm\", \"conventions\", \"zones\", \"weights\"] as const) {\n if (!wants(s, missingNow)) continue;\n if (!(await orBack(() => runStep(s, ctx, change(s), opts))) && opts.review) break;\n }\n\n if (!opts.review) {\n outro(\"Setup saved.\");\n return;\n }\n if (ctx.address.ref) await orBack(() => reviewThenCheckQuit(ctx, ctx.address.ref!.number));\n await mainMenu(ctx, opts);\n outro(\"Bye.\");\n } catch (err) {\n if (err instanceof Cancelled) {\n outro(\"Cancelled.\");\n return;\n }\n throw err;\n }\n}\n\nasync function runStep(s: Step, ctx: { forge: ForgeClient; address: GitAddress }, change: boolean, opts: SetupOptions): Promise<void> {\n const { forge, address } = ctx;\n if (s === \"llm\") return llmStep(change);\n if (s === \"conventions\") return conventionsStep(forge, address, change, opts);\n if (s === \"zones\") return zonesStep(forge, address, change, opts);\n if (s === \"weights\") return weightsStep(address.host, address.projectPath, change);\n // A different address/token may point at another project: the menu follows it.\n Object.assign(ctx, await forgeStep(address, `https://${address.host}/${address.projectPath}`, true));\n}\n\n/** The review handles its own cancel: Esc there returns to the menu, Ctrl-C still quits. */\nasync function reviewThenCheckQuit(ctx: { forge: ForgeClient; address: GitAddress }, mrIid: number): Promise<void> {\n lastKey = \"\";\n await runInteractiveReview({ forge: ctx.forge, project: ctx.address.projectPath, mrIid });\n if (lastKey === \"ctrl-c\") throw new Cancelled();\n}\n\nconst STEP_ICONS: Record<Step, IconName> = { forge: \"git\", llm: \"llm\", conventions: \"conventions\", zones: \"zones\", weights: \"weights\" };\n\n/** First run on a terminal: show some Nerd Font icons and ask if they draw; saved either way. */\n/** npx keeps packages in its cache under `_npx/`; running from there means `yolont` isn't installed. */\nexport const runningFromNpx = (script = process.argv[1] ?? \"\") => installKind(script) === \"npx\";\n\nlet latestCheck: Promise<string | undefined> = Promise.resolve(undefined);\n\n/** The newer npm version, if there is one. Waits at most a moment for the background check. */\nasync function newerVersion(): Promise<string | undefined> {\n const [current, latest] = [ownVersion(), await Promise.race([latestCheck, new Promise<undefined>((r) => setTimeout(() => r(undefined), 300))])];\n return current && latest && isNewer(latest, current) ? latest : undefined;\n}\n\n/** Menu \"Update\": npm installs update in place; npx and source checkouts get the command to run. */\nasync function updateMenu(latest: string): Promise<void> {\n const kind = installKind();\n if (kind === \"source\") {\n log.info(`This is a source checkout. Update it with ${pc.bold(\"git pull && npm ci\")}, or install the package: ${pc.bold(`npm install -g yolont@${latest}`)}`);\n return;\n }\n if (kind === \"npx\") {\n log.info(`Run ${pc.bold(\"npx yolont@latest\")} next time, or install it once: ${pc.bold(`npm install -g yolont@${latest}`)}`);\n return;\n }\n if (!(await ask<boolean>(confirm({ message: `Update to v${latest}? (npm install -g yolont@${latest})`, initialValue: true })))) return;\n if (installLatest(latest)) {\n outro(`Updated to v${latest}. Run ${pc.bold(\"yolont\")} again to use it.`);\n process.exit(0); // this process still runs the old code\n }\n log.warn(\"npm couldn't update it (often a permissions issue): https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally\");\n}\n\n/** First run through npx: offer `npm install -g` so later runs are just `yolont`. Asked once. */\nasync function offerInstallOnce(): Promise<void> {\n if (!runningFromNpx() || loadConfig().installOffered || !process.stdout.isTTY) return;\n const version = ownVersion() ?? \"latest\";\n const ok = await confirm({ message: `Install the \\`yolont\\` command, so next time you just type \\`yolont\\`? (npm install -g yolont@${version})`, initialValue: true });\n if (isCancel(ok)) return;\n saveConfig({ ...loadConfig(), installOffered: true });\n if (!ok) {\n log.info(pc.dim(\"OK. Install it any time with `npm install -g yolont`.\"));\n return;\n }\n if (installLatest(version)) log.success(`Installed. From now on run ${pc.bold(\"yolont\")} (no npx).`);\n else\n log.warn(\n `Couldn't install it (often a permissions issue with npm's global folder). Run \\`npm install -g yolont\\` yourself; for permission errors see https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally`,\n );\n}\n\n/** Every run while it's missing: without gitleaks no diff is ever sent to the LLM (fail-closed). */\nasync function ensureGitleaks(): Promise<void> {\n if (gitleaksWorks() || !process.stdout.isTTY) return;\n const help = \"https://github.com/gitleaks/gitleaks#installing\";\n if (!gitleaksAsset()) {\n log.warn(`gitleaks (the secret scanner) isn't installed, so reviews will skip the LLM. Install it: ${help}`);\n return;\n }\n const ok = await confirm({\n message: `gitleaks (the secret scanner) isn't installed. Without it, reviews never reach the LLM. Download the official v${GITLEAKS_VERSION} (checksum-verified) into ${LOCAL_GITLEAKS}?`,\n initialValue: true,\n });\n if (isCancel(ok) || !ok) {\n log.warn(`Reviews will skip the LLM until gitleaks is installed: ${help}`);\n return;\n }\n const s = spinner();\n s.start(`Downloading gitleaks v${GITLEAKS_VERSION}`);\n try {\n await installGitleaks();\n s.stop(gitleaksWorks() ? `gitleaks v${GITLEAKS_VERSION} installed.` : pc.yellow(\"Downloaded, but it doesn't run on this machine.\"));\n } catch (err) {\n s.stop(pc.red(`gitleaks install failed: ${describeFetchError(err)}`));\n log.warn(`Install it yourself: ${help}`);\n }\n}\n\nasync function askIconsOnce(): Promise<void> {\n if (loadConfig().icons || !process.stdout.isTTY) return;\n const ok = await confirm({ message: `Do these look like icons (not boxes or \"?\")? ${iconSample()}`, initialValue: true });\n if (isCancel(ok)) return;\n saveConfig({ ...loadConfig(), icons: ok ? \"nerd\" : \"plain\" });\n log.info(pc.dim(ok ? \"Nerd Font icons on. Turn off with `icons: plain` in config.yaml.\" : \"Plain text. Install a Nerd Font and set `icons: nerd` in config.yaml for icons.\"));\n}\n\n/** Where things stand, shown once when the main menu opens. */\nfunction statusPanel(ctx: { forge: ForgeClient; address: GitAddress }, teamLabel: string, latest?: string): void {\n const config = loadConfig();\n const llm = config.llmProfiles.find((p) => p.name === config.defaultLlmProfile);\n panel(\"Yolont\", [\n [`${icon(ctx.forge.type === \"github\" ? \"github\" : \"gitlab\")}Project`, `${pc.bold(ctx.address.projectPath)} ${pc.dim(`\u00B7 ${ctx.address.host}`)}`],\n [`${icon(\"llm\")}LLM`, llm ? `${llm.name} ${pc.dim(`\u00B7 ${llm.model}`)}` : pc.yellow(\"not set\")],\n [`${icon(\"memory\")}Memory`, teamLabel.replace(/^Memory repo( \u00B7 )?/, \"\") || \"\u2014\"],\n [`${icon(\"type\")}Change type`, CHANGE_TYPE_MODES[config.changeType ?? \"label\"].label],\n [`${icon(\"sync\")}Version`, `v${ownVersion() ?? \"?\"}${latest ? pc.yellow(` \u00B7 v${latest} is out`) : \"\"}`],\n ]);\n}\n\nconst STEP_LABELS: Record<Step, string> = { forge: \"Git host & token\", llm: \"LLM\", conventions: \"Conventions\", zones: \"Zones\", weights: \"Scoring weights\" };\n\n/** Bare `yolont` once set up: review, or revisit any step. Esc inside anything comes back here; Esc here exits. */\nasync function mainMenu(ctx: { forge: ForgeClient; address: GitAddress }, opts: SetupOptions): Promise<void> {\n const latest = await newerVersion();\n statusPanel(ctx, await teamMenuLabel(ctx.address), latest);\n for (;;) {\n const missing = missingSteps({ host: ctx.address.host, projectPath: ctx.address.projectPath });\n const teamLabel = await teamMenuLabel(ctx.address);\n let choice: string;\n try {\n choice = await ask(\n select({\n message: `${ctx.address.projectPath} \u00B7 ${ctx.address.host}`,\n options: [\n { value: \"review\", label: `${icon(\"review\")}${pc.bold(\"Review an open MR/PR\")}` },\n ...(latest ? [{ value: \"update\", label: pc.yellow(`${icon(\"sync\")}Update to v${latest}`), hint: `you have v${ownVersion()}` }] : []),\n ...(Object.keys(STEP_LABELS) as Step[]).map((s) => ({\n value: s,\n label: `${missing.includes(s) ? pc.red(nerdIcons() ? icon(\"missing\") : \"\u2717 \") : pc.green(nerdIcons() ? icon(\"ok\") : \"\u2713 \")}${icon(STEP_ICONS[s])}${STEP_LABELS[s]}`,\n })),\n { value: \"team\", label: `${icon(\"memory\")}${teamLabel}` },\n { value: \"changeType\", label: `${icon(\"type\")}Change type: ${CHANGE_TYPE_MODES[loadConfig().changeType ?? \"label\"].label}` },\n { value: \"remove\", label: `${icon(\"remove\")}Remove saved\u2026`, hint: \"LLM keys, git host tokens, memory repos\" },\n { value: \"exit\", label: `${icon(\"exit\")}Exit` },\n ],\n }),\n );\n } catch (err) {\n if (err instanceof Back) return;\n throw err;\n }\n if (choice === \"exit\") return;\n if (choice === \"update\") {\n await orBack(() => updateMenu(latest!));\n continue;\n }\n if (choice === \"remove\") {\n await orBack(() => removeMenu(ctx.address));\n continue;\n }\n if (choice === \"changeType\") {\n await orBack(() => changeTypeMenu());\n continue;\n }\n if (choice === \"team\") {\n await orBack(() => teamMenu(ctx.address));\n continue;\n }\n if (choice === \"review\") {\n await orBack(async () => {\n const mrIid = await pickChange(ctx.forge, ctx.address.projectPath);\n if (mrIid !== null) await reviewThenCheckQuit(ctx, mrIid);\n });\n continue;\n }\n await orBack(() => runStep(choice as Step, ctx, true, opts));\n }\n}\n\n// ---- remove saved things ----\n\n/** One place to remove what setup saved. Each removal says exactly what goes and asks first. */\nasync function removeMenu(address: GitAddress): Promise<void> {\n const config = loadConfig();\n const project = `${address.host}/${address.projectPath}`;\n const items = [\n ...config.llmProfiles.map((p) => ({ value: `llm:${p.name}`, label: `LLM: ${p.name} \u00B7 ${p.model}`, hint: \"the profile and its API key\" })),\n ...config.forges.map((f) => ({ value: `forge:${f.host}`, label: `Git host: ${f.host}`, hint: f.host === address.host ? \"its token \u00B7 this project's host\" : \"its token\" })),\n ...(config.sources ?? []).map((s) => ({ value: `source:${s.name}`, label: `Memory repo: ${s.name}`, hint: `${displayUrl(s.url)} \u00B7 on this machine only` })),\n ...((config.localProjects ?? []).length ? [{ value: \"local\", label: `\"No memory repo\" choices (${config.localProjects!.length})`, hint: \"the wizard asks again\" }] : []),\n ];\n if (items.length === 0) {\n log.info(\"Nothing saved to remove.\");\n return;\n }\n const pick = await ask<string>(select({ message: \"Remove which?\", options: items }));\n const [kind, ...rest] = pick.split(\":\");\n const name = rest.join(\":\");\n\n if (kind === \"llm\") {\n if (!(await ask<boolean>(confirm({ message: `Remove LLM profile '${name}' and its saved API key?`, initialValue: false })))) return;\n removeLlmProfile(name);\n log.success(`Removed '${name}'.${loadConfig().defaultLlmProfile ? ` Reviews now use '${loadConfig().defaultLlmProfile}'.` : \" Add an LLM before the next review.\"}`);\n } else if (kind === \"forge\") {\n const here = name === address.host;\n if (!(await ask<boolean>(confirm({ message: `Remove git host ${name} and its saved token?${here ? \" This project is on it: you'll be asked for a token next time.\" : \"\"}`, initialValue: false })))) return;\n removeForge(name);\n log.success(`Removed ${name}.`);\n } else if (kind === \"source\") {\n const db = openDb();\n try {\n const source = getSource(name);\n const unsent = await pendingToSend(db, source).catch(() => 0);\n const waiting = await waitingForMerge(source).catch(() => 0);\n note(\n [\n `Projects using it go back to your own memory: ${source.projects.join(\", \") || \"(none)\"}.`,\n \"What came from it is dropped here; your own reviews stay in your DB.\",\n `Its local copy (${sourceDir(name)}) is deleted. The repo itself, and what you already sent, are untouched.`,\n ...(unsent ? [pc.yellow(`${unsent} change(s) of yours were never sent and will be lost (sync first to keep them).`)] : []),\n ...(waiting ? [`${waiting} file(s) you sent wait for merge in your merge request; that stays on the git host.`] : []),\n ].join(\"\\n\"),\n `Remove memory repo ${name}`,\n );\n if (!(await ask<boolean>(confirm({ message: `Remove memory repo '${name}' from this machine?`, initialValue: false })))) return;\n removeSource(db, name);\n log.success(`Removed memory repo '${name}'.${source.projects.includes(`${project}`.toLowerCase()) ? \" This project now uses only your own memory.\" : \"\"}`);\n } finally {\n db.close();\n }\n } else if (kind === \"local\") {\n saveConfig({ ...loadConfig(), localProjects: [] });\n log.success(\"Cleared. The wizard asks again which memory repo each of those projects uses.\");\n }\n}\n\n// ---- change type (src/changeType.ts) ----\n\nconst CHANGE_TYPE_MODES = {\n label: {\n label: \"Label\",\n hint: \"the review also names it (feature, bugfix, refactor\u2026); you confirm it after. Saved and filterable; the review itself is unchanged. No extra cost.\",\n },\n steer: {\n label: \"Steer the review\",\n hint: \"settled before the review (from the title/branch/labels, else one small extra LLM call); you confirm it, then the review gets that type's checks (refactor: no behavior change; bugfix: regression test; \u2026).\",\n },\n off: { label: \"Off\", hint: \"no change type.\" },\n} as const;\n\nasync function changeTypeMenu(): Promise<void> {\n note(\n Object.values(CHANGE_TYPE_MODES)\n .map((m) => `${pc.bold(m.label)}: ${m.hint}`)\n .join(\"\\n\\n\"),\n \"Change type\",\n );\n const current = loadConfig().changeType ?? \"label\";\n const mode = await ask<keyof typeof CHANGE_TYPE_MODES>(\n select({\n message: \"How should Yolont use the change type?\",\n initialValue: current,\n options: (Object.keys(CHANGE_TYPE_MODES) as (keyof typeof CHANGE_TYPE_MODES)[]).map((k) => ({ value: k, label: CHANGE_TYPE_MODES[k].label + (k === current ? \" (now)\" : \"\") })),\n }),\n );\n saveConfig({ ...loadConfig(), changeType: mode });\n log.success(`Change type: ${CHANGE_TYPE_MODES[mode].label}. CI uses YOLONT_CHANGE_TYPE=${mode} (default label).`);\n}\n\n// ---- memory repos ----\n\nconst describeStatus = (st: SourceStatus) =>\n st.error\n ? pc.yellow(`couldn't reach it: ${st.error}`)\n : [\n st.incoming + st.outgoing === 0 && \"up to date\",\n st.incoming && `${st.incoming} update(s) from the team to get`,\n st.outgoing && `${st.outgoing} change(s) of yours to send`,\n st.waiting && `${st.waiting} file(s) waiting for merge`,\n ]\n .filter(Boolean)\n .join(\" \u00B7 \");\n\nasync function checkAll(sources: SourceConfig[] = loadConfig().sources ?? []): Promise<{ source: SourceConfig; status: SourceStatus }[]> {\n if (sources.length === 0) return [];\n const s = spinner();\n s.start(\"Checking memory repo\");\n const db = openDb();\n try {\n const out = [];\n for (const source of sources) out.push({ source, status: await checkSource(db, source) });\n s.stop(\"Memory repo checked\");\n return out;\n } finally {\n db.close();\n }\n}\n\n/** Get and/or send, then say what happened. Errors are shown, never thrown: memory sync must not block a review. */\nasync function runSync(source: SourceConfig, mode: \"sync\" | \"pull\"): Promise<void> {\n const s = spinner();\n s.start(mode === \"sync\" ? `Syncing ${source.name}` : `Getting updates from ${source.name}`);\n const db = openDb();\n try {\n const r: ImportResult & Partial<SyncResult> = mode === \"sync\" ? await syncSource(db, source) : await pullSource(db, source);\n const sent = r.sent !== undefined ? `, sent ${r.sent} record(s)${r.deletedShared ? `, removed ${r.deletedShared}` : \"\"}` : \"\";\n s.stop(`${source.name}: got ${r.imported} record(s)${r.removed ? `, ${r.removed} removed` : \"\"}${r.restored ? `, restored ${r.restored} of yours` : \"\"}${sent}`);\n if (r.review) {\n log.info(`${r.review.waiting} file(s) wait for a maintainer to merge into ${r.review.target}${r.review.url ? `: ${r.review.url}` : \"\"}`);\n if (r.review.note) log.warn(r.review.note);\n }\n if (r.rejected.length) log.warn(`Skipped ${r.rejected.length} file(s) that don't belong where they are (e.g. ${r.rejected[0]}).`);\n } catch (err) {\n s.error(`${source.name}: not synced`);\n log.error((err as Error).message);\n } finally {\n db.close();\n }\n}\n\n/**\n * \"Memory repo \u00B7 frontend \u00B7 2 to send\" (yellow: not sent yet), else \"\u00B7 80 waiting for merge\" (cyan:\n * sent, a maintainer hasn't merged it). Counted locally, so a review just done shows up without a fetch.\n */\nasync function teamMenuLabel(address: GitAddress): Promise<string> {\n const source = sourceFor(address.host, address.projectPath);\n if (!source) return `Memory repo${pc.dim(\" (none: only your own)\")}`;\n const db = openDb();\n try {\n const n = await pendingToSend(db, source);\n const waiting = n ? 0 : await waitingForMerge(source);\n return `Memory repo \u00B7 ${source.name}${n ? pc.yellow(` \u00B7 ${n} to send`) : waiting ? pc.cyan(` \u00B7 ${waiting} waiting for merge`) : \"\"}`;\n } catch {\n return `Memory repo \u00B7 ${source.name}`;\n } finally {\n db.close();\n }\n}\n\n/** After the project address: its memory repo (asked once, saved), then what's waiting in it. */\nasync function memoryStep(address: GitAddress): Promise<void> {\n let source = sourceFor(address.host, address.projectPath);\n if (!source && !isKeptLocal(address.host, address.projectPath)) source = (await chooseMemoryRepo(address)) ?? undefined;\n if (source) await offerSync(source, true);\n}\n\nasync function offerSync(source: SourceConfig, quietIfUpToDate: boolean): Promise<void> {\n const { status } = (await checkAll([source]))[0]!;\n log.info(`Memory repo ${pc.bold(source.name)}: ${describeStatus(status)}`);\n if (status.error || (quietIfUpToDate && status.incoming + status.outgoing === 0)) return;\n const choice = await ask<string>(\n select({\n message: `Sync ${source.name} now?`,\n options: [\n { value: \"sync\", label: \"Get updates and send mine\" },\n { value: \"pull\", label: \"Only get the team's updates\" },\n { value: \"later\", label: quietIfUpToDate ? \"Later\" : \"Back\" },\n ],\n }),\n );\n if (choice !== \"later\") await runSync(source, choice as \"sync\" | \"pull\");\n}\n\n/** Connects a new memory repo on `host`; null when cancelled or it failed (the error is shown). */\nasync function connectSource(host: string): Promise<SourceConfig | null> {\n note(\n `A git repo on ${host} that holds Yolont memory for some of your projects: reviews, corrections,\\nmemory, conventions and zones. Create an empty private repo (members need read + write; protect\\nits main branch so changes come in as merge requests), then paste its address.\\nOnly projects you choose use it, and gitleaks checks everything before it's sent.`,\n \"Memory repo\",\n );\n const url = await askLine<string>(\n text({\n message: `Memory repo address (on ${host})`,\n placeholder: `git@${host}:team/yolont-memory.git`,\n validate: (v) => {\n const a = v?.trim() ? parseGitAddress(v.trim()) : null;\n if (!a) return \"A git address, like git@host:group/repo.git\";\n return bareHost(a.host) === bareHost(host) ? undefined : `That's on ${a.host}; this project is on ${host} (an ssh host alias? add it with: yolont source add <name> <address> --host ${host})`;\n },\n }),\n );\n const taken = new Set((loadConfig().sources ?? []).map((s) => s.name));\n const name = await askLine<string>(\n text({ message: \"Short name for it\", placeholder: \"frontend\", validate: (v) => (!/^[a-z0-9][a-z0-9-]*$/.test(v ?? \"\") ? \"lowercase letters, digits, '-'\" : taken.has(v!) ? \"Already used\" : undefined) }),\n );\n const member = loadConfig().member?.name ?? (await askLine<string>(text({ message: \"Your name in memory repos\", initialValue: userInfo().username })));\n const s = spinner();\n s.start(\"Cloning\");\n try {\n const source = await addSource(name, url.trim(), member);\n s.stop(`Connected ${name}`);\n return source;\n } catch (err) {\n s.error(\"Not connected\");\n log.error((err as Error).message);\n return null;\n }\n}\n\n/**\n * Which memory repo a project uses. Only repos on the project's own host are offered; choosing\n * another switches (what came from the old one is dropped here, it stays in its repo).\n */\nasync function chooseMemoryRepo(address: GitAddress): Promise<SourceConfig | null> {\n const project = `${address.host}/${address.projectPath}`;\n const current = sourceFor(address.host, address.projectPath);\n const onHost = sourcesForHost(address.host);\n const elsewhere = (loadConfig().sources ?? []).length - onHost.length;\n if (elsewhere) log.message(pc.dim(`${elsewhere} memory repo(s) on other hosts aren't offered: a project only uses one on its own git host.`));\n const pick = await ask<string>(\n select({\n message: `Memory repo for ${project}`,\n options: [\n ...onHost.map((s) => ({ value: s.name, label: s.name === current?.name ? `${s.name} (now)` : s.name, hint: displayUrl(s.url) })),\n { value: \"new\", label: `Add a memory repo on ${address.host}` },\n { value: \"none\", label: \"None: only my own memory for this project\" },\n ],\n }),\n );\n if (pick === current?.name) return current;\n const db = openDb();\n try {\n if (pick === \"none\") {\n stopUsing(db, address.host, address.projectPath);\n keepLocal(address.host, address.projectPath);\n log.info(`${project}: only your own memory. Change it any time under \"Memory repo\".`);\n return null;\n }\n const target = pick === \"new\" ? await connectSource(address.host) : getSource(pick);\n if (!target) return current ?? null;\n if (current) stopUsing(db, address.host, address.projectPath);\n const { copied, kept } = await shareProject(target.name, address.host, address.projectPath);\n log.success(`${project} now uses ${target.name}${current ? ` (was ${current.name})` : \"\"}.`);\n if (copied.length) log.success(`Moved into ${target.name}: ${copied.join(\", \")}`);\n if (kept.length) log.warn(`${target.name} already has ${kept.join(\", \")}: its version is used. Yours stays in ~/.config/yolont.`);\n return getSource(target.name);\n } catch (err) {\n log.error((err as Error).message);\n return current ?? null;\n } finally {\n db.close();\n }\n}\n\nasync function teamMenu(address: GitAddress): Promise<void> {\n const source = sourceFor(address.host, address.projectPath);\n if (!source) {\n const chosen = await chooseMemoryRepo(address);\n if (chosen) await offerSync(chosen, false);\n return;\n }\n const choice = await ask<string>(\n select({\n message: `Memory repo ${source.name}`,\n options: [\n { value: \"sync\", label: \"Sync now\" },\n { value: \"switch\", label: \"Switch to another memory repo (or none)\" },\n { value: \"back\", label: \"Back\" },\n ],\n }),\n );\n if (choice === \"sync\") await offerSync(source, false);\n if (choice === \"switch\") {\n const chosen = await chooseMemoryRepo(address);\n if (chosen && chosen.name !== source.name) await offerSync(chosen, false);\n }\n}\n\nfunction parseAddress(s: string | undefined): GitAddress | null {\n if (!s?.trim()) return null;\n // \"github.com/owner/repo\" pasted without a scheme\n const withScheme = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(s.trim()) || s.includes(\"@\") ? s : `https://${s.trim()}`;\n return parseGitAddress(withScheme, gitlabBases());\n}\n\n// ---- step 1: forge ----\n\n/**\n * \"fetch failed\" alone hides why: the real reason (DNS, timeout, TLS refused, proxy) is in\n * `cause`. Network failures also get a hint, since a VPN or proxy is the usual culprit.\n */\nexport function describeFetchError(err: unknown): string {\n const e = err as Error & { cause?: { code?: string; message?: string } };\n const cause = e.cause?.code ?? e.cause?.message;\n if (!cause) return e.message;\n const hint =\n /ENOTFOUND|EAI_AGAIN/.test(cause) ? \"the host name doesn't resolve\" :\n /ETIMEDOUT|UND_ERR_CONNECT_TIMEOUT/.test(cause) ? \"no answer (blocked, or needs a VPN?)\" :\n /ECONNREFUSED|ECONNRESET/.test(cause) ? \"the connection was refused or dropped\" :\n /SSL|TLS|CERT/i.test(cause) ? \"the secure connection was refused (often a VPN/proxy or a region block)\" : \"\";\n return `${e.message} (${cause}${hint ? `: ${hint}` : \"\"}). Can you open the host in a browser from this machine?`;\n}\n\nasync function forgeStep(detected: GitAddress | null, raw: string | undefined, change: boolean): Promise<{ forge: ForgeClient; address: GitAddress }> {\n let address = detected;\n let last = raw ?? \"\";\n for (;;) {\n if (!address || change) {\n const input = await askLine(\n text({\n message: \"Git address or MR/PR URL\",\n placeholder: \"https://github.com/owner/repo/pull/12 \u00B7 git@gitlab.com:group/project.git\",\n initialValue: last,\n validate: (v) => (parseAddress(v ?? \"\") ? undefined : \"Not a git address or MR/PR URL\"),\n }),\n );\n last = input;\n address = parseAddress(input)!;\n }\n const config = loadConfig();\n const saved = config.forges.find((f) => f.host === address!.host);\n\n let type: ForgeType | null = saved?.type ?? address.ref?.type ?? null;\n if (!type) {\n const s = spinner();\n s.start(`Detecting what runs on ${address.host}`);\n type = await probeForgeType(address.host);\n s.stop(type ? `${address.host} is ${type === \"github\" ? \"GitHub\" : \"GitLab\"}` : `Couldn't tell what ${address.host} is`);\n type ??= await ask(select<ForgeType>({ message: `Is ${address.host} GitLab or GitHub?`, options: [{ value: \"gitlab\", label: \"GitLab\" }, { value: \"github\", label: \"GitHub\" }] }));\n }\n\n let token = forgeToken(address.host, type);\n let isNew = false;\n if (token && change) {\n const keep = await ask(select({ message: `Token for ${address.host}`, options: [{ value: true, label: `Keep ${maskSecret(token)}` }, { value: false, label: \"Enter a new one\" }] }));\n if (!keep) token = undefined;\n }\n if (!token) {\n note(`${tokenHelpUrl(type, address.host, saved ? forgeUrl(saved) : undefined)}\\n${type === \"github\" ? \"Scope: repo (or fine-grained: Pull requests + Issues read/write, Contents + Actions read)\" : \"Scope: api\"}`, \"Create a token\");\n token = (await askLine(password({ message: `Token for ${address.host}`, validate: (v) => (v?.trim() ? undefined : \"Required\") }))).trim();\n isNew = true;\n }\n\n const forge = createForge({ type, host: address.host, url: saved ? forgeUrl(saved) : undefined, token });\n const s = spinner();\n s.start(`Checking access to ${address.projectPath}`);\n try {\n const ok = await testForge(forge, address.projectPath);\n s.stop(`Signed in as ${pc.bold(ok.username)} \u00B7 ${ok.pathWithNamespace}`);\n } catch (err) {\n s.stop(pc.red(`Check failed: ${describeFetchError(err)}`));\n const next = await ask(\n select({\n message: \"What now?\",\n options: [\n { value: \"retry\", label: \"Enter a different address or token\" },\n { value: \"save\", label: \"Save anyway (e.g. VPN is down right now)\" },\n ],\n }),\n );\n if (next === \"retry\") {\n change = true;\n continue;\n }\n }\n\n saveForge(address.host, type, isNew ? token : undefined);\n if (isNew) log.success(`Token saved to ${secretBackend()}.`);\n return { forge, address };\n }\n}\n\n// ---- step 4: LLM profile ----\n\n\nasync function llmStep(change: boolean): Promise<void> {\n const config = loadConfig();\n const shellKey = LLM_ENV_KEYS.find((k) => process.env[k] && !configFilledKeys().includes(k));\n if (shellKey) log.warn(`${shellKey} is set in your shell \u2014 it overrides the saved LLM profile.`);\n\n if (config.llmProfiles.length > 0) {\n const choice = await ask(\n select({\n message: \"LLM for reviews\",\n initialValue: config.defaultLlmProfile ?? config.llmProfiles[0]!.name,\n options: [\n ...config.llmProfiles.map((p) => ({\n value: p.name,\n label: `${p.name} \u00B7 ${p.model}`,\n hint: `${p.provider}${p.name === config.defaultLlmProfile ? \" \u00B7 current\" : \"\"}${p.provider !== \"ollama\" && !getSecret(`llm:${p.name}`) ? \" \u00B7 no key!\" : \"\"}`,\n })),\n { value: \"__add\", label: \"Add a new one\" },\n ],\n }),\n );\n if (choice !== \"__add\") {\n const profile = config.llmProfiles.find((p) => p.name === choice)!;\n if (profile.provider !== \"ollama\" && !getSecret(`llm:${choice}`)) {\n const key = (await askLine(password({ message: `API key for '${choice}' (none saved)`, validate: (v) => (v?.trim() ? undefined : \"Required\") }))).trim();\n await testOrConfirm(profile, key);\n setSecret(`llm:${choice}`, key);\n }\n config.defaultLlmProfile = choice;\n saveConfig(config);\n reapplyConfigToEnv();\n if (change) log.success(`Using '${choice}'.`);\n return;\n }\n }\n\n const preset = await ask(select({ message: \"LLM provider\", options: PROVIDER_PRESETS.map((p, i) => ({ value: i, label: p.label, hint: p.hint })) })).then((i) => PROVIDER_PRESETS[i]!);\n let baseUrl = preset.baseUrl;\n let model = preset.model;\n let key: string | undefined;\n for (;;) {\n if (preset.provider !== \"anthropic\" && (!preset.baseUrl || preset.provider === \"ollama\")) {\n baseUrl = await askLine(text({ message: \"Base URL\", placeholder: \"https://gateway.example.com/v1\", initialValue: baseUrl ?? \"\", validate: (v) => (/^https?:\\/\\/\\S+$/.test(v ?? \"\") ? undefined : \"An http(s) URL\") }));\n }\n model = await askLine(text({ message: \"Model id\", initialValue: model ?? \"\", validate: (v) => (v?.trim() ? undefined : \"Required\") }));\n if (preset.provider !== \"ollama\") {\n key = (await askLine(password({ message: `API key for ${preset.label}`, validate: (v) => (v?.trim() ? undefined : \"Required\") }))).trim();\n }\n\n const s = spinner();\n s.start(`Test call to ${model}`);\n try {\n await testLlmProfile({ provider: preset.provider, model, baseUrl }, key);\n s.stop(`${model} answered in the review format.`);\n break;\n } catch (err) {\n s.stop(pc.red(`Test failed: ${(err as Error).message}`));\n const next = await ask(select({ message: \"What now?\", options: [{ value: \"retry\", label: \"Change model / URL / key\" }, { value: \"save\", label: \"Save anyway\" }] }));\n if (next === \"save\") break;\n }\n }\n\n const fresh = loadConfig();\n const taken = new Set(fresh.llmProfiles.map((p) => p.name));\n const name = await askLine(\n text({\n message: \"Name this profile\",\n initialValue: taken.has(preset.name) ? `${preset.name}-${model.replace(/[^a-z0-9]+/gi, \"-\").toLowerCase()}` : preset.name,\n validate: (v) => (PROFILE_NAME.test(v ?? \"\") ? undefined : \"Letters, digits, . _ -\"),\n }),\n );\n saveLlmProfile({ name, provider: preset.provider, model, ...(baseUrl && { baseUrl }) }, key);\n log.success(`Profile '${name}' saved and set as default${key ? ` (key in ${secretBackend()})` : \"\"}.`);\n}\n\n/** Test a saved profile's new key; on failure the user can still save it. */\nasync function testOrConfirm(profile: Pick<LlmProfile, \"provider\" | \"model\" | \"baseUrl\">, key: string): Promise<void> {\n const s = spinner();\n s.start(`Test call to ${profile.model}`);\n try {\n await testLlmProfile(profile, key);\n s.stop(`${profile.model} answered in the review format.`);\n } catch (err) {\n s.stop(pc.red(`Test failed: ${(err as Error).message}`));\n if (!(await ask(select({ message: \"Save the key anyway?\", options: [{ value: true, label: \"Yes\" }, { value: false, label: \"No, cancel\" }] })))) throw new Cancelled();\n }\n}\n\n// ---- step 2: conventions ----\n\n\n/** VISUAL/EDITOR may carry args (\"code -w\"), hence the shell. Returns the edited text. */\nfunction editInEditor(initial: string, name = \"conventions.md\"): string {\n const dir = mkdtempSync(join(tmpdir(), \"yolont-edit-\"));\n const file = join(dir, name);\n try {\n writeFileSync(file, initial);\n const editor = process.env.VISUAL || process.env.EDITOR || \"vi\";\n const r = spawnSync(`${editor} \"${file}\"`, { stdio: \"inherit\", shell: true });\n if (r.status !== 0) log.warn(`${editor} exited with ${r.status ?? r.signal}; keeping what was saved.`);\n return readFileSync(file, \"utf8\");\n } finally {\n rmSync(dir, { recursive: true, force: true });\n }\n}\n\nfunction llmOrNull() {\n try {\n return createLlmProvider(process.env as LlmEnv);\n } catch {\n return null;\n }\n}\n\nconst looks = new Map<string, Promise<ProjectLook>>();\n\n/** Once per wizard run (a run is short; the panel calls lookAtProject fresh each time). */\nfunction lookAtProjectOnce(forge: ForgeClient, address: GitAddress, opts: SetupOptions): Promise<ProjectLook> {\n const key = `${address.host}/${address.projectPath}/${opts.repo ?? \"\"}`;\n if (!looks.has(key)) looks.set(key, doLook(forge, address, opts));\n return looks.get(key)!;\n}\n\nasync function doLook(forge: ForgeClient, { projectPath }: GitAddress, opts: SetupOptions): Promise<ProjectLook> {\n const s = spinner();\n s.start(\"Looking at the project\");\n const look = await lookAtProject(forge, projectPath, opts.repo);\n if (look.mismatch) log.warn(`${look.mismatch} What's drafted from it may not fit.`);\n s.stop(look.error ? pc.yellow(`Couldn't list the project's files: ${look.error}`) : `${look.files.length} files \u00B7 stack: ${look.stack.join(\", \") || \"not detected\"}`);\n return look;\n}\n\nasync function conventionsStep(forge: ForgeClient, address: GitAddress, change: boolean, opts: SetupOptions): Promise<void> {\n const { host, projectPath } = address;\n const cur = currentConventions(host, projectPath);\n if (cur.fromRepo) {\n log.info(`Conventions come from the repo's ${cur.path} \u2014 edit them there (it's what CI uses too).`);\n return;\n }\n if (cur.path && opts.conventions === \"edit\") return approve(host, projectPath, editInEditor(readFileSync(cur.path, \"utf8\")), \"\", null);\n if (cur.path && !opts.conventions) {\n const text0 = readFileSync(cur.path, \"utf8\");\n const keep = await ask(\n select({\n message: `Conventions: ${cur.path} (${lineCount(text0)} lines)`,\n options: [\n { value: \"keep\", label: \"Keep\" },\n { value: \"edit\", label: \"Edit in $EDITOR\" },\n { value: \"new\", label: \"Replace (generate / suggest)\" },\n ],\n }),\n );\n if (keep === \"keep\") return;\n if (keep === \"edit\") return approve(host, projectPath, editInEditor(text0), \"\", null);\n }\n\n const { source, files, local, stack } = await lookAtProjectOnce(forge, address, opts);\n const llm = llmOrNull();\n const suggestion = suggestConventions(stack, cur.path ?? undefined);\n // No checkout: the repo may still have a committed .yolont/conventions.md (what CI reads).\n const repoPath = [\".yolont/conventions.md\", \".ethos/conventions.md\"].find((f) => files.includes(f));\n const repoFile = !local && source && repoPath ? await source.read(repoPath).catch(() => null) : null;\n\n for (;;) {\n const how = await ask(\n select({\n message: \"Conventions for this project\",\n options: [\n ...(repoFile ? [{ value: \"repo\", label: \"Use the repo's .yolont/conventions.md\", hint: \"what CI uses\" }] : []),\n ...(source && llm ? [{ value: \"gen\", label: `Generate from ${local ? \"this checkout\" : `${host} (no checkout needed)`}`, hint: \"you see the file list first\" }] : []),\n { value: \"suggest\", label: `Start from ${suggestion.split(\"/\").slice(-2).join(\"/\")}`, hint: \"closest match\" },\n { value: \"file\", label: \"Use an existing file\", hint: \"type or paste its path\" },\n { value: \"editor\", label: \"Write / paste in $EDITOR\" },\n ],\n }),\n );\n if (how === \"repo\") return approve(host, projectPath, repoFile!, \"\", null);\n if (how === \"suggest\") return approve(host, projectPath, readFileSync(suggestion, \"utf8\"), \"\", null);\n if (how === \"editor\") return approve(host, projectPath, \"\", \"\", null);\n if (how === \"file\") {\n const text0 = await pickConventionsFile();\n if (text0 !== null) return approve(host, projectPath, text0, \"\", null);\n continue;\n }\n const draft = await generateFlow(source!, files, stack, `${host}/${projectPath}`, llm!);\n if (draft) return approve(host, projectPath, draft.conventions, draft.summary, () => generateFlow(source!, files, stack, `${host}/${projectPath}`, llm!));\n }\n}\n\nasync function generateFlow(source: CrawlSource, files: string[], stack: string[], project: string, llm: NonNullable<ReturnType<typeof llmOrNull>>) {\n // 1. Which folders show the conventions best (none = a spread over the whole repo).\n const dirs = sourceDirs(files);\n const chosenDirs = dirs.length\n ? await ask(\n autocompleteMultiselect({\n message: \"Folders that show this project's conventions best (type to filter, Tab to select, Enter to continue; none = whole repo)\",\n options: dirs.map((d) => ({ value: d.dir, label: d.dir, hint: `${d.count} files` })),\n required: false,\n maxItems: 12,\n }),\n )\n : [];\n // 2. The exact files: all ticked, untick anything that shouldn't leave the machine.\n const candidates = pickFiles(files, 6, 2, chosenDirs);\n if (!candidates.length) {\n log.warn(\"No files to send.\");\n return null;\n }\n const picked = await ask(\n multiselect({\n message: `Files to send from ${source.label} (+ the folder tree) \u2014 untick any you don't want sent`,\n options: candidates.map((f) => ({ value: f, label: f })),\n initialValues: candidates,\n required: true,\n maxItems: 15,\n }),\n );\n if (!(await ask(confirm({ message: `Send ${picked.length} files to the LLM? (gitleaks scans them first)`, initialValue: true })))) return null;\n\n const s = spinner();\n s.start(\"Reading files and scanning for secrets\");\n let scrub: Awaited<ReturnType<typeof scrubPrompt>>;\n try {\n scrub = await scrubPrompt(project, stack, dirTree(files), await readSections(source, picked));\n } catch (err) {\n s.stop(pc.red(`Nothing sent: ${(err as Error).message}`));\n return null;\n }\n s.stop(`${scrub.sent.length} files ready`);\n if (scrub.dropped.length) log.warn(`Left out (gitleaks flagged them): ${scrub.dropped.join(\", \")}`);\n if (scrub.scannerFailed) {\n log.warn(`gitleaks couldn't run (${scrub.scannerError}). Install it: https://github.com/gitleaks/gitleaks#installing`);\n if (!(await ask(confirm({ message: \"Send without a secrets scan?\", initialValue: false })))) return null;\n }\n\n s.start(\"Generating conventions\");\n try {\n const out = await generateConventions(llm, scrub.prompt);\n s.stop(\"Draft ready\");\n return out;\n } catch (err) {\n s.stop(pc.red(`Generation failed: ${(err as Error).message}`));\n return null;\n }\n}\n\n/** \"Use an existing file\": a pasted path (~ and relative work). null = go back to the menu. */\nasync function pickConventionsFile(): Promise<string | null> {\n for (;;) {\n // Plain text, not the path prompt: that one pre-fills cwd, so a pasted absolute path got appended to it.\n const raw = (await askLine(text({ message: \"Path to a conventions file (paste it, or drag the file here; empty = back)\", placeholder: \"~/team/CONVENTIONS.md\" }))) ?? \"\";\n const input = normalizePastedPath(raw, homedir());\n if (!input) return null;\n const p = resolve(input);\n if (!existsSync(p)) {\n log.warn(`Not found: ${p}`);\n continue;\n }\n if (!statSync(p).isFile()) {\n log.warn(`That's a folder, not a file: ${p}`);\n continue;\n }\n const text0 = readFileSync(p, \"utf8\");\n if (text0.includes(\"\\0\")) {\n log.warn(\"That looks like a binary file.\");\n continue;\n }\n log.info(`Loaded ${p} (${lineCount(text0)} lines). It's copied into this project's conventions; the original isn't changed.`);\n return text0;\n }\n}\n\n/** Show \u2192 approve / edit / regenerate; the line cap (conventionsMaxLines) is enforced here, on save. */\nasync function approve(host: string, path: string, text0: string, summary: string, regen: (() => Promise<{ conventions: string; summary: string } | null>) | null): Promise<void> {\n let draft = text0;\n if (!draft.trim()) draft = editInEditor(\"# Team Conventions\\n\\n\");\n if (summary) note(summary, \"What Yolont understood\");\n for (;;) {\n const n = lineCount(draft);\n const max = conventionsMaxLines();\n const over = n > max;\n const choice = await ask(\n select({\n message: `Conventions \u2014 ${over ? pc.red(`${n}/${max}`) : `${n}/${max}`} lines`,\n options: [\n ...(over ? [] : [{ value: \"save\", label: \"Save\" }]),\n { value: \"view\", label: \"Show it\" },\n { value: \"edit\", label: over ? \"Edit in $EDITOR (over the limit)\" : \"Edit in $EDITOR\" },\n ...(regen ? [{ value: \"regen\", label: \"Generate again\" }] : []),\n ],\n }),\n );\n if (choice === \"view\") note(draft.trimEnd(), \"conventions.md\");\n else if (choice === \"edit\") draft = editInEditor(draft);\n else if (choice === \"regen\") {\n const next = await regen!();\n if (next) {\n draft = next.conventions;\n if (next.summary) note(next.summary, \"What Yolont understood\");\n }\n } else {\n const out = saveConventions(host, path, draft);\n log.success(`Saved ${out}. Commit it as .yolont/conventions.md to share it with the team and CI.`);\n return;\n }\n }\n}\n\n// ---- step 3: zones ----\n\nconst LEVEL_COLOR = { red: pc.red, amber: pc.yellow, green: pc.green } as const;\n\nasync function zonesStep(forge: ForgeClient, address: GitAddress, change: boolean, opts: SetupOptions): Promise<void> {\n const { host, projectPath } = address;\n const cur = currentZones(host, projectPath);\n if (cur.fromRepo) {\n log.info(`Zones come from the repo's ${cur.path} \u2014 edit them there (it's what CI uses too).`);\n return;\n }\n if (cur.path && (opts.zones === \"edit\" || !opts.zones)) {\n const raw0 = readFileSync(cur.path, \"utf8\");\n if (opts.zones === \"edit\") return saveZonesLoop(host, projectPath, editInEditor(raw0, \"zones.yaml\"), cur.graph);\n const keep = await ask(\n select({\n message: `Zones: ${cur.path}`,\n options: [\n { value: \"keep\", label: \"Keep\" },\n { value: \"edit\", label: \"Edit in $EDITOR\" },\n { value: \"new\", label: \"Replace with a new draft\" },\n ],\n }),\n );\n if (keep === \"keep\") return;\n if (keep === \"edit\") return saveZonesLoop(host, projectPath, editInEditor(raw0, \"zones.yaml\"), cur.graph);\n }\n\n const { source, files, local, stack } = await lookAtProjectOnce(forge, address, opts);\n const repoPath = [\".yolont/zones.yaml\", \".ethos/zones.yaml\"].find((f) => files.includes(f));\n const repoFile = !local && source && repoPath ? await source.read(repoPath).catch(() => null) : null;\n const draft = draftZones(files, stack);\n const draftYaml = renderZonesYaml(draft.zones, draft.templates);\n if (draft.zones.length) {\n note(\n draft.zones.map((z) => `${LEVEL_COLOR[z.level](z.level.padEnd(5))} ${z.id.padEnd(20)} ${String(draft.matched[z.id]).padStart(4)} files ${pc.dim(z.paths.slice(0, 3).join(\" \") + (z.paths.length > 3 ? \" \u2026\" : \"\"))}`).join(\"\\n\"),\n `Zones drafted from ${draft.templates.join(\" + \")}`,\n );\n } else if (source) log.info(\"No template zone matches this repo's files.\");\n\n const how = await ask(\n select({\n message: \"Zones mark where a mistake costs more, so reviews call it out. Optional.\",\n options: [\n ...(repoFile ? [{ value: \"repo\", label: \"Use the repo's .yolont/zones.yaml\", hint: \"what CI uses\" }] : []),\n ...(draft.zones.length ? [{ value: \"save\", label: \"Save this draft\" }, { value: \"edit\", label: \"Edit the draft in $EDITOR first\" }] : [{ value: \"edit\", label: \"Write zones in $EDITOR\" }]),\n { value: \"skip\", label: \"No zones for this project\", hint: \"won't ask again\" },\n ],\n }),\n );\n if (how === \"skip\") {\n skipZones(host, projectPath);\n log.info(\"No zones. Add them later with `yolont zones generate`.\");\n return;\n }\n const raw = how === \"repo\" ? repoFile! : how === \"save\" ? draftYaml : editInEditor(draft.zones.length ? draftYaml : renderZonesYaml([]), \"zones.yaml\");\n await saveZonesLoop(host, projectPath, raw, cur.graph);\n if (local && stack.some((t) => t === \"node\" || t === \"typescript\")) {\n log.info(`For import-aware matching (files a red zone pulls in): yolont zones graph ${projectPath} --repo ${local}`);\n }\n}\n\n/** Validation errors loop back to the editor; nothing invalid is ever written. */\nasync function saveZonesLoop(host: string, path: string, raw: string, graph: string | null): Promise<void> {\n for (;;) {\n try {\n const out = saveZones(host, path, raw);\n if (!out) {\n log.info(\"No zones defined, so none saved (won't ask again). Add them later with `yolont zones generate`.\");\n return;\n }\n log.success(`Saved ${out}. Commit it as .yolont/zones.yaml to share it with the team and CI.`);\n if (graph) log.warn(`${graph} was built for the old zones \u2014 rebuild it with \\`yolont zones graph\\`.`);\n return;\n } catch (err) {\n if (!(err instanceof ZonesError)) throw err;\n log.error(err.message);\n if (!(await ask(confirm({ message: \"Edit again? (No = discard)\", initialValue: true })))) return;\n raw = editInEditor(raw, \"zones.yaml\");\n }\n }\n}\n\n// ---- step 5: weights ----\n\nasync function weightsStep(host: string, path: string, change: boolean): Promise<void> {\n const cur = currentWeights(host, path);\n const names = Object.keys(cur.weights);\n if (cur.fromRepo) {\n log.info(`Weights come from the repo's ${cur.rubricPath} \u2014 change them there (it's what CI uses too).`);\n return;\n }\n note(names.map((n) => `${n.padEnd(18)} ${String(cur.weights[n]).padStart(3)}`).join(\"\\n\") + `\\n${\"total\".padEnd(18)} ${String(sum(cur.weights)).padStart(3)}`, \"Category weights\");\n\n const presets = Object.entries(WEIGHT_PRESETS).filter(([, p]) => presetFits(p.weights, names));\n const choice = await ask(\n select({\n message: \"Weights for this project\",\n options: [\n { value: \"__keep\", label: change ? \"Keep these\" : \"Use these\" },\n ...presets.map(([id, p]) => ({ value: id, label: p.label, hint: names.map((n) => p.weights[n]).join(\"/\") })),\n { value: \"__custom\", label: \"Custom\" },\n ],\n }),\n );\n\n if (choice === \"__keep\") {\n // Built-in rubric: remember the answer so it isn't asked again. Own rubric.yml: nothing to change.\n if (cur.rubricPath === DEFAULT_RUBRIC_PATH) saveWeights(host, path, null);\n log.success(cur.rubricPath === DEFAULT_RUBRIC_PATH ? \"Using the built-in weights for this project.\" : \"Weights unchanged.\");\n return;\n }\n const weights = choice === \"__custom\" ? await customWeights(cur.weights) : { ...WEIGHT_PRESETS[choice]!.weights };\n const out = saveWeights(host, path, weights);\n log.success(`Saved ${out}`);\n}\n\nasync function customWeights(start: Record<string, number>): Promise<Record<string, number>> {\n for (;;) {\n const w: Record<string, number> = {};\n for (const [name, value] of Object.entries(start)) {\n const others = sum(w);\n const v = await askLine(\n text({\n message: `${name} ${pc.dim(`(so far ${others}, ${100 - others} left)`)}`,\n initialValue: String(value),\n validate: (s) => (/^\\d+$/.test(s ?? \"\") && Number(s) <= 100 ? undefined : \"Whole number 0\u2013100\"),\n }),\n );\n w[name] = Number(v);\n }\n const total = sum(w);\n if (total === 100) return w;\n const scaled = normalizeWeights(w);\n const next = await ask(\n select({\n message: `Total is ${total}, not 100`,\n options: [\n { value: \"normalize\", label: \"Scale to 100\", hint: Object.entries(scaled).map(([k, v]) => `${k} ${v}`).join(\", \") },\n { value: \"again\", label: \"Enter again\" },\n ],\n }),\n );\n if (next === \"normalize\") return scaled;\n start = w;\n }\n}\n\n// ---- step 6: review picker ----\n\nasync function pickChange(forge: ForgeClient, projectPath: string): Promise<number | null> {\n const s = spinner();\n s.start(\"Loading open changes\");\n const open = await forge.listProjectMergeRequests(projectPath, { state: \"opened\", maxPages: 1 }).catch((err: Error) => {\n s.stop(pc.red(`Could not list: ${err.message}`));\n return null;\n });\n if (open) s.stop(`${open.length} open`);\n const choice = await ask(\n select({\n message: \"Review which?\",\n options: [\n ...(open ?? []).slice(0, 30).map((m) => ({ value: m.iid, label: `${changeLabel(forge.type, m.iid)} ${m.title}`, hint: m.authorUsername })),\n { value: -1, label: \"Enter a number\" },\n { value: 0, label: \"Back to menu\" },\n ],\n }),\n );\n if (choice === 0) return null;\n if (choice > 0) return choice;\n return Number(await askLine(text({ message: \"MR/PR number\", validate: (v) => (/^\\d+$/.test(v ?? \"\") ? undefined : \"A number\") })));\n}\n", "import pc from \"picocolors\";\nimport { loadConfig } from \"../config/config.js\";\n\n/**\n * Look of the wizard: Nerd Font icons when the terminal font has them (config `icons: nerd`,\n * asked once), a banner and a status panel. Plain text otherwise, so nothing ever shows as boxes.\n */\nconst NERD = {\n review: \"\uF407\", // nf-oct-git_pull_request\n gitlab: \"\uF296\",\n github: \"\uF09B\",\n git: \"\uE702\",\n llm: \"\uF2DB\", // nf-fa-microchip\n conventions: \"\uF02D\", // book\n zones: \"\uF279\", // map\n weights: \"\uF24E\", // balance scale\n memory: \"\uF1C0\", // database\n type: \"\uF02B\", // tag\n remove: \"\uF1F8\", // trash\n exit: \"\uF08B\", // sign out\n ok: \"\uF00C\",\n missing: \"\uF00D\",\n sync: \"\uF021\",\n} as const;\nexport type IconName = keyof typeof NERD;\n\nexport const nerdIcons = () => loadConfig().icons === \"nerd\";\n\n/** \"<icon> \" with Nerd Fonts, \"\" without (labels stay readable either way). */\nexport function icon(name: IconName): string {\n return nerdIcons() ? `${NERD[name]} ` : \"\";\n}\n\n/** A sample for the one-time font check. */\nexport const iconSample = () => [NERD.review, NERD.git, NERD.llm, NERD.memory, NERD.ok].join(\" \");\n\nconst BANNER = [\n \"\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\",\n \"\u255A\u2588\u2588\u2557 \u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551\u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\",\n \" \u255A\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \",\n \" \u255A\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551 \",\n \" \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551 \u2588\u2588\u2551 \",\n \" \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D \",\n];\n// Top to bottom: a cyan \u2192 magenta fade, one color per row.\nconst ROW_COLORS = [pc.cyan, pc.cyan, pc.blue, pc.blue, pc.magenta, pc.magenta];\n\n/** Clears the screen and prints the banner (one line on a narrow terminal). TTY only. */\nexport function header(subtitle: string): void {\n if (!process.stdout.isTTY) return;\n const cols = process.stdout.columns ?? 80;\n process.stdout.write(\"\\x1b[2J\\x1b[3J\\x1b[H\"); // clear screen + scrollback, cursor home\n if (cols >= BANNER[0]!.length + 4) {\n console.log();\n BANNER.forEach((row, i) => console.log(` ${ROW_COLORS[i]!(row)}`));\n console.log(` ${pc.dim(subtitle)}\\n`);\n } else {\n console.log(`\\n ${pc.bold(pc.cyan(\"YOLONT\"))} ${pc.dim(subtitle)}\\n`);\n }\n}\n\nconst visible = (s: string) => s.replace(/\\x1b\\[[0-9;]*m/g, \"\");\n\n/** A rounded panel of \"label value\" rows, as wide as the terminal allows (max 100). */\nexport function panel(title: string, rows: [string, string][]): void {\n if (!process.stdout.isTTY) return;\n const width = Math.min((process.stdout.columns ?? 80) - 4, 100);\n const labelW = Math.max(...rows.map(([l]) => visible(l).length));\n const line = (content: string) => {\n const pad = Math.max(0, width - 4 - visible(content).length);\n return ` ${pc.dim(\"\u2502\")} ${content}${\" \".repeat(pad)} ${pc.dim(\"\u2502\")}`;\n };\n const top = `\u2500 ${title} `;\n console.log(` ${pc.dim(\"\u256D\")}${pc.dim(top)}${pc.dim(\"\u2500\".repeat(Math.max(0, width - 2 - top.length)))}${pc.dim(\"\u256E\")}`);\n for (const [l, v] of rows) {\n const label = l.padEnd(labelW + (l.length - visible(l).length));\n const room = width - 6 - labelW;\n const value = visible(v).length > room ? `${visible(v).slice(0, Math.max(0, room - 1))}\u2026` : v;\n console.log(line(`${pc.dim(label)} ${value}`));\n }\n console.log(` ${pc.dim(\"\u2570\")}${pc.dim(\"\u2500\".repeat(width - 2))}${pc.dim(\"\u256F\")}`);\n}\n", "import type { YolontConfig, LlmProfile } from \"./config.js\";\n\nexport interface EnvImport {\n config: YolontConfig;\n /** secret name -> value, to hand to setSecret. */\n secrets: Record<string, string>;\n skipped: string[];\n}\n\n/**\n * Maps a pre-Yolont .env onto config + secrets, merged into `base` (same host/profile name\n * replaces). Per-run CI vars (CI_PROJECT_ID, CI_MERGE_REQUEST_IID, \u2026) are not config and are\n * ignored. Profiles are added in createLlmProvider's precedence order, and the first one\n * becomes the default, so the provider that ran before the import still runs after it.\n */\nexport function importEnv(env: Record<string, string | undefined>, base: YolontConfig): EnvImport {\n const config: YolontConfig = structuredClone(base);\n const secrets: Record<string, string> = {};\n const skipped: string[] = [];\n const val = (k: string) => (env[k]?.trim() ? env[k]!.trim() : undefined);\n\n const serverUrl = val(\"CI_SERVER_URL\");\n if (serverUrl) {\n const url = new URL(serverUrl);\n const host = url.host.toLowerCase();\n config.forges = [...config.forges.filter((f) => f.host !== host), { host, type: \"gitlab\", ...((url.protocol === \"http:\" || url.pathname !== \"/\") && { url: serverUrl.replace(/\\/$/, \"\") }) }];\n config.defaultForge ??= host;\n const token = val(\"GITLAB_API_TOKEN\");\n if (token) secrets[`forge:${host}`] = token;\n } else if (val(\"GITLAB_API_TOKEN\")) skipped.push(\"GITLAB_API_TOKEN (no CI_SERVER_URL to attach it to)\");\n\n const profiles: { profile: LlmProfile; key?: string }[] = [];\n if (val(\"ANTHROPIC_API_KEY\")) profiles.push({ profile: { name: \"anthropic\", provider: \"anthropic\", model: val(\"ANTHROPIC_MODEL\") ?? \"claude-sonnet-5\" }, key: val(\"ANTHROPIC_API_KEY\") });\n if (val(\"OPENCODE_ZEN_API_KEY\"))\n profiles.push({\n profile: { name: \"opencode-zen\", provider: \"openai-compatible\", model: val(\"OPENCODE_ZEN_MODEL\") ?? \"deepseek-v4-flash-free\", baseUrl: val(\"OPENCODE_ZEN_BASE_URL\") ?? \"https://opencode.ai/zen/v1\" },\n key: val(\"OPENCODE_ZEN_API_KEY\"),\n });\n if (val(\"OPENCODE_ZEN_GO_API_KEY\"))\n profiles.push({\n profile: { name: \"opencode-zen-go\", provider: \"openai-compatible\", model: val(\"OPENCODE_ZEN_GO_MODEL\") ?? \"deepseek-v4-flash-free\", baseUrl: val(\"OPENCODE_ZEN_GO_BASE_URL\") ?? \"https://opencode.ai/zen/go/v1\" },\n key: val(\"OPENCODE_ZEN_GO_API_KEY\"),\n });\n if (val(\"OMNI_API_KEY\")) {\n const baseUrl = val(\"OMNI_BASE_URL\");\n if (baseUrl) profiles.push({ profile: { name: \"omni\", provider: \"openai-compatible\", model: val(\"OMNI_MODEL\") ?? \"google/gemini-3.7-flash\", baseUrl }, key: val(\"OMNI_API_KEY\") });\n else skipped.push(\"OMNI_API_KEY (set OMNI_BASE_URL \u2014 there is no built-in default gateway)\");\n }\n if (val(\"OLLAMA_URL\")) profiles.push({ profile: { name: \"ollama\", provider: \"ollama\", model: val(\"OLLAMA_MODEL\") ?? \"qwen2.5-coder\", baseUrl: val(\"OLLAMA_URL\") } });\n\n for (const { profile, key } of profiles) {\n config.llmProfiles = [...config.llmProfiles.filter((p) => p.name !== profile.name), profile];\n if (key) secrets[`llm:${profile.name}`] = key;\n }\n if (profiles[0]) config.defaultLlmProfile ??= profiles[0].profile.name;\n\n if (val(\"TYPESAFE_API_KEY\")) secrets.jev = val(\"TYPESAFE_API_KEY\")!;\n const threshold = val(\"JEV_NOISE_THRESHOLD\") ? Number(val(\"JEV_NOISE_THRESHOLD\")) : undefined;\n const jev = {\n ...config.jev,\n ...(val(\"JEV_MODEL\") && { model: val(\"JEV_MODEL\") }),\n ...(threshold !== undefined && threshold >= 0 && threshold <= 1 && { threshold }),\n ...(val(\"JEV_DISABLED\") && { disabled: /^(1|true)$/i.test(val(\"JEV_DISABLED\")!) }),\n };\n if (Object.keys(jev).length > 0) config.jev = jev;\n\n return { config, secrets, skipped };\n}\n", "import { copyFileSync, existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { DatabaseSync } from \"node:sqlite\";\nimport { slugifyProjectPath } from \"./conventions/resolve.js\";\nimport { DATA_DIR, DB_PATH, INSTALL_ROOT, SESSIONS_PATH, userProjectDir } from \"./paths.js\";\n\nconst MARKER = join(DATA_DIR, \".legacy-migrated\");\n\n/**\n * One-time copy of pre-Yolont state that lived in the install dir (local/data/, and per-project\n * conventions/<slug>.md + zones/<slug>.*) into the user dirs. Copies, never moves, so a failed\n * run loses nothing. The marker stops it re-copying a file the user later deleted on purpose.\n * `host` = the GitLab host the old data belongs to (old data had no host); without it only\n * the DB and session cache move. Returns what was copied, for one log line.\n */\nexport function migrateLegacyState(host: string | undefined, installRoot = INSTALL_ROOT): string[] {\n if (existsSync(MARKER)) return [];\n const copied: string[] = [];\n mkdirSync(DATA_DIR, { recursive: true });\n\n const legacyDb = join(installRoot, \"local\", \"data\", \"pr-score.db\");\n if (existsSync(legacyDb) && !existsSync(DB_PATH)) {\n // VACUUM INTO, not a file copy: consistent even with a live -wal file next to it.\n const src = new DatabaseSync(legacyDb);\n src.exec(`VACUUM INTO '${DB_PATH.replace(/'/g, \"''\")}'`);\n src.close();\n copied.push(DB_PATH);\n }\n const legacySessions = join(installRoot, \"local\", \"data\", \"review-sessions.json\");\n if (existsSync(legacySessions) && !existsSync(SESSIONS_PATH)) {\n copyFileSync(legacySessions, SESSIONS_PATH);\n copied.push(SESSIONS_PATH);\n }\n\n // Slugs are lossy (\"a/b-c\" and \"a-b/c\" collide), so map them back through the projects\n // the DB actually knows rather than guessing a path from a filename.\n if (host && existsSync(DB_PATH)) {\n const db = new DatabaseSync(DB_PATH);\n // An empty/foreign DB file (no schema yet) just means there's nothing to map.\n const hasProjects = !!db.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'projects'\").get();\n const projects = (hasProjects ? db.prepare(\"SELECT path_with_namespace FROM projects\").all() : []) as { path_with_namespace: string }[];\n db.close();\n for (const { path_with_namespace: path } of projects) {\n const slug = slugifyProjectPath(path);\n const pairs: [string, string][] = [\n [join(installRoot, \"conventions\", `${slug}.md`), \"conventions.md\"],\n [join(installRoot, \"zones\", `${slug}.yaml`), \"zones.yaml\"],\n [join(installRoot, \"zones\", `${slug}.graph.json`), \"zones.graph.json\"],\n ];\n for (const [from, name] of pairs) {\n const to = join(userProjectDir(host, path), name);\n if (!existsSync(from) || existsSync(to)) continue;\n mkdirSync(userProjectDir(host, path), { recursive: true });\n copyFileSync(from, to);\n copied.push(to);\n }\n }\n }\n\n // No host = project files couldn't be placed yet; try again on a later run that has one.\n if (host) writeFileSync(MARKER, `${new Date().toISOString()}\\n`);\n return copied;\n}\n", "import { execFileSync } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport madge from \"madge\";\nimport { computeReachable, type Zone, type ZoneGraph } from \"../../src/zones/zones.js\";\n\nconst CODE_FILE = /\\.[cm]?[jt]sx?$/;\n\n/**\n * Offline step: needs a checkout of the *target* project, which\n * review time doesn't have locally \u2014 so it's run once by hand and written next to the\n * YAML. madge stays a local-only dependency; CI just reads the JSON it produced.\n */\nexport async function buildZoneGraph(repo: string, zones: Zone[]): Promise<ZoneGraph> {\n const git = (...args: string[]) => execFileSync(\"git\", [\"-C\", repo, ...args], { encoding: \"utf8\", maxBuffer: 64 * 1024 * 1024 });\n const repoFiles = git(\"ls-files\").split(\"\\n\").filter((f) => CODE_FILE.test(f) && !f.endsWith(\".d.ts\"));\n const tsConfig = join(repo, \"tsconfig.json\");\n\n const result = await madge(\n repoFiles.map((f) => join(repo, f)),\n {\n baseDir: repo,\n fileExtensions: [\"ts\", \"tsx\", \"js\", \"jsx\", \"mjs\", \"cjs\"],\n tsConfig: existsSync(tsConfig) ? tsConfig : undefined,\n excludeRegExp: [/node_modules/],\n // Lazy routes (`import()`) are exactly what must NOT count as first-load; type-only\n // imports never reach the bundle.\n detectiveOptions: {\n es6: { skipAsyncImports: true, skipTypeImports: true },\n ts: { skipAsyncImports: true, skipTypeImports: true },\n tsx: { skipAsyncImports: true, skipTypeImports: true },\n },\n },\n );\n\n let sha: string | null = null;\n try {\n sha = git(\"rev-parse\", \"HEAD\").trim();\n } catch {\n // not fatal \u2014 sha is only shown as \"graph from <sha>\" at review time\n }\n return { generated_at: new Date().toISOString(), sha, reachable: computeReachable(zones, repoFiles, result.obj()) };\n}\n"],
|
|
5
|
-
"m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Q;AAAA,QACN;AAAA,UACE;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA,qCAAqC,WAAW;AAAA,QAClD,EAAE,KAAK,IAAI;AAAA,MACb;AACA,cAAQ,WAAW,WAAW,YAAY,UAAU,YAAY,WAAW,IAAI;AAAA,EACnF;AACF;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAM,YAAa,IAAc,OAAO,EAAE;AAClD,UAAQ,WAAW;AACrB,CAAC;",
|
|
6
|
-
"names": ["
|
|
3
|
+
"sources": ["../local/paths.ts", "../src/rubric/schema.ts", "../src/scoring/engine.ts", "../local/db/repo.ts", "../local/db/client.ts", "../src/checks/secrets.ts", "../src/checks/diffSize.ts", "../src/git.ts", "../src/changeType.ts", "../src/rubric/loader.ts", "../src/zones/zones.ts", "../src/forge/types.ts", "../src/forge/github.ts", "../src/forge/gitlab.ts", "../src/forge/index.ts", "../local/config/secrets.ts", "../local/config/config.ts", "../local/forge.ts", "../local/sync/records.ts", "../local/sync/source.ts", "../local/conventions/resolve.ts", "../local/memory/context.ts", "../local/setup/version.ts", "../local/setup/gitleaks.ts", "../local/mcp/coach.ts", "../local/mcp/server.ts", "../local/cli.ts", "../local/mining/backfill.ts", "../src/checks/runner.ts", "../src/checks/pipelineResults.ts", "../src/llm/anthropicProvider.ts", "../src/llm/schema.ts", "../src/llm/provider.ts", "../src/llm/ollamaProvider.ts", "../src/llm/opencodeZenProvider.ts", "../src/llm/sanitizeTone.ts", "../src/llm/jevValidate.ts", "../src/llm/index.ts", "../src/scoring/resolve.ts", "../local/memory/distill.ts", "../local/review/interactiveReview.ts", "../src/comment/render.ts", "../local/memory/trend.ts", "../local/review/sessionCache.ts", "../local/review/syncReplies.ts", "../local/backoffice/server.ts", "../local/review/syncDecision.ts", "../local/backoffice/settings.ts", "../local/conventions/generate.ts", "../local/setup/state.ts", "../local/zones/generate.ts", "../local/setup/wizard.ts", "../local/setup/ui.ts", "../local/setup/agents.ts", "../local/config/importEnv.ts", "../local/legacyMigrate.ts", "../local/zones/graph.ts"],
|
|
4
|
+
"sourcesContent": ["import { existsSync, renameSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\n/** Where Yolont is installed. Read-only at runtime: only built-in defaults live here, never\n * user state \u2014 an npm install may not be writable, and an upgrade replaces it. */\nexport const INSTALL_ROOT = join(__dirname, \"..\");\nexport const DEFAULT_RUBRIC_PATH = join(INSTALL_ROOT, \".pr-reviewer\", \"rubric.yml\");\n/** Built-in convention files, offered as starting points when a project has none. */\nexport const BUILTIN_CONVENTIONS_DIR = join(INSTALL_ROOT, \"conventions\");\nexport const DEFAULT_CONVENTIONS_PATH = join(BUILTIN_CONVENTIONS_DIR, \"default.md\");\n/** Built-in zone templates per stack (react-spa, nextjs, node-api, generic). */\nexport const ZONE_TEMPLATES_DIR = join(INSTALL_ROOT, \"templates\", \"zones\");\n\nconst env = process.env;\nconst win = process.platform === \"win32\";\n\n// ---- renamed from Ethos (2026-11-29): old names keep working ----\n// ETHOS_* env vars count as YOLONT_* when those aren't set.\nfor (const [k, v] of Object.entries(env)) if (k.startsWith(\"ETHOS_\") && env[`YOLONT_${k.slice(6)}`] === undefined) env[`YOLONT_${k.slice(6)}`] = v;\n\n/**\n * The default folder, taking over the old Ethos one once: a rename (same disk, atomic), so the\n * reviews DB, memory repo clones and credentials file move together. If the move fails (another\n * disk, permissions) the old folder keeps being used, so nothing is ever left behind.\n */\nfunction adopt(base: string): string {\n const dir = join(base, \"yolont\");\n const old = join(base, \"ethos\");\n if (existsSync(dir) || !existsSync(old)) return dir;\n try {\n renameSync(old, dir);\n return dir;\n } catch {\n return old;\n }\n}\n\n/** User config (no secrets in files here except the credentials fallback). YOLONT_CONFIG_DIR overrides. */\nexport const CONFIG_DIR = env.YOLONT_CONFIG_DIR ?? adopt(win ? (env.APPDATA ?? join(homedir(), \"AppData\", \"Roaming\")) : env.XDG_CONFIG_HOME || join(homedir(), \".config\"));\n/** Reviews DB + resume cache. YOLONT_DATA_DIR overrides. */\nexport const DATA_DIR = env.YOLONT_DATA_DIR ?? adopt(win ? (env.LOCALAPPDATA ?? join(homedir(), \"AppData\", \"Local\")) : env.XDG_DATA_HOME || join(homedir(), \".local\", \"share\"));\n\nexport const DB_PATH = join(DATA_DIR, \"yolont.db\");\n// The DB file inside a taken-over folder (plus SQLite's -wal/-shm side files, so nothing is lost).\nif (!existsSync(DB_PATH) && existsSync(join(DATA_DIR, \"ethos.db\"))) {\n for (const ext of [\"\", \"-wal\", \"-shm\"]) {\n const from = join(DATA_DIR, `ethos.db${ext}`);\n if (existsSync(from)) renameSync(from, `${DB_PATH}${ext}`);\n }\n}\nexport const SESSIONS_PATH = join(DATA_DIR, \"sessions.json\");\n\n/** ~/.config/yolont/projects/<host>/<group>/<project> \u2014 `host` is a URL or bare host. */\nexport function userProjectDir(host: string, pathWithNamespace: string): string {\n // ':' (from a port) is illegal in Windows paths.\n return join(CONFIG_DIR, \"projects\", bareHost(host).replace(/:/g, \"_\"), ...pathWithNamespace.toLowerCase().split(\"/\"));\n}\n\n/** \"https://Git.Example.com:8443/gitlab\" -> \"git.example.com:8443\"; a bare host passes through lowercased. */\nexport function bareHost(hostOrUrl: string): string {\n return (/^[a-z]+:\\/\\//i.test(hostOrUrl) ? new URL(hostOrUrl).host : hostOrUrl).toLowerCase();\n}\n", "import { z } from \"zod\";\n\nexport const CategoryTypeSchema = z.enum([\"deterministic\", \"llm\", \"hybrid\"]);\nexport type CategoryType = z.infer<typeof CategoryTypeSchema>;\n\nexport const CategorySchema = z.object({\n name: z.string().min(1),\n weight: z.number().min(0).max(100),\n type: CategoryTypeSchema,\n // Required for deterministic/hybrid categories. One of: \"diff_size\", \"test_report\",\n // or \"job:<substring>\" (matched against this pipeline's job names). \"secrets\" is not\n // a valid source here \u2014 the gitleaks scan is an unconditional pre-check in index.ts\n // that runs before any category is scored; a hit short-circuits the whole run before\n // this code path is reached, so wiring it as a source can only ever produce a\n // constant pass-through score (a real bug this schema previously allowed).\n source: z.string().optional(),\n min_coverage: z.number().min(0).max(100).optional(),\n // Fed to the LLM as rubric context for llm/hybrid categories. Falls back to a generic prompt if omitted.\n description: z.string().optional(),\n});\nexport type Category = z.infer<typeof CategorySchema>;\n\nexport const SeverityPenaltiesSchema = z.object({\n minor: z.number().min(0).default(3),\n major: z.number().min(0).default(8),\n critical: z.number().min(0).default(20),\n});\n\n// Findings are scored as density, not raw count: each penalty is multiplied by\n// clamp((reference_size / mr_size) ^ exponent, min_factor, max_factor), where\n// mr_size = changed_lines + lines_per_file * changed_files. exponent 0 disables scaling.\nexport const VolumeScalingSchema = z.object({\n reference_size: z.number().positive().default(200),\n lines_per_file: z.number().min(0).default(30),\n exponent: z.number().min(0).default(0.7),\n min_factor: z.number().positive().default(0.25),\n max_factor: z.number().positive().default(3),\n}).refine((v) => v.min_factor <= v.max_factor, { message: \"min_factor must be <= max_factor\", path: [\"min_factor\"] });\nexport type VolumeScaling = z.infer<typeof VolumeScalingSchema>;\n\nexport const DEFAULT_VOLUME_SCALING: VolumeScaling = {\n reference_size: 200,\n lines_per_file: 30,\n exponent: 0.7,\n min_factor: 0.25,\n max_factor: 3,\n};\n\nexport const RubricSchema = z\n .object({\n version: z.literal(1),\n gate: z.boolean().default(false),\n threshold: z.number().min(0).max(100).default(80),\n max_diff_bytes: z.number().positive().default(100_000),\n max_lines: z.number().positive().default(500),\n severity_penalties: SeverityPenaltiesSchema.default({ minor: 3, major: 8, critical: 20 }),\n volume_scaling: VolumeScalingSchema.default(DEFAULT_VOLUME_SCALING),\n categories: z.array(CategorySchema).min(1),\n })\n .superRefine((rubric, ctx) => {\n const sum = rubric.categories.reduce((total, c) => total + c.weight, 0);\n if (sum !== 100) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Rubric weights must sum to 100, got ${sum}`,\n path: [\"categories\"],\n });\n }\n\n const seen = new Set<string>();\n for (let i = 0; i < rubric.categories.length; i++) {\n const c = rubric.categories[i]!;\n if (seen.has(c.name)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Duplicate category name '${c.name}'`,\n path: [\"categories\", i, \"name\"],\n });\n }\n seen.add(c.name);\n\n if ((c.type === \"deterministic\" || c.type === \"hybrid\") && !c.source) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Category '${c.name}' has type '${c.type}' and requires a 'source'`,\n path: [\"categories\", i, \"source\"],\n });\n }\n\n if (c.source === \"secrets\") {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Category '${c.name}': source 'secrets' is not supported \u2014 the secrets scan is an unconditional pre-check that runs before category scoring and always short-circuits before this source would be read, so it can only produce a constant pass-through score. Use type: llm for a narrative security review instead.`,\n path: [\"categories\", i, \"source\"],\n });\n }\n }\n });\n\nexport type Rubric = z.infer<typeof RubricSchema>;\n", "import type { VolumeScaling } from \"../rubric/schema.js\";\nimport type { CategoryResult, Finding, FinalScoreResult, ScoredCategory, SeverityPenalties } from \"./types.js\";\n\n/**\n * The LLM's own `score` field is advisory only \u2014 the real category\n * score is always recomputed here from findings + severity, so a model can\n * never freehand the number.\n */\nexport function scoreFromFindings(findings: Finding[], penalties: SeverityPenalties, volumeFactor = 1): number {\n const totalPenalty = findings.reduce((sum, f) => sum + penalties[f.severity], 0) * volumeFactor;\n return Math.round(clamp(100 - totalPenalty, 0, 100));\n}\n\n/**\n * Penalty multiplier from MR size, so findings count as density rather than raw totals:\n * one major in a 1-file change hurts more than two criticals spread over 30 files.\n * Sublinear (exponent < 1) on purpose \u2014 reviewers catch proportionally fewer issues in\n * big diffs, so fully linear dilution would reward oversized MRs.\n */\nexport function volumeFactor(stats: { added: number; deleted: number; files: number }, cfg: VolumeScaling): number {\n const size = Math.max(1, stats.added + stats.deleted + cfg.lines_per_file * stats.files);\n return clamp((cfg.reference_size / size) ** cfg.exponent, cfg.min_factor, cfg.max_factor);\n}\n\nexport function computeFinalScore(categories: CategoryResult[], threshold: number): FinalScoreResult {\n const availableWeight = categories.filter((c) => c.available).reduce((sum, c) => sum + c.weight, 0);\n\n const scored: ScoredCategory[] = categories.map((c) => {\n if (!c.available) {\n return { ...c, effectiveWeight: 0 };\n }\n // Renormalize so available categories' weights still sum to 100 when some are excluded.\n const effectiveWeight = availableWeight > 0 ? (c.weight / availableWeight) * 100 : 0;\n return { ...c, effectiveWeight };\n });\n\n const finalScoreRaw =\n availableWeight > 0\n ? scored.reduce((sum, c) => sum + (c.score * c.effectiveWeight) / 100, 0)\n : 50; // nothing was available this run \u2014 neutral, documented via each category's note\n\n const finalScore = Math.round(clamp(finalScoreRaw, 0, 100));\n\n return {\n categories: scored,\n finalScore,\n pass: finalScore >= threshold,\n };\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, value));\n}\n", "import type { DatabaseSync } from \"node:sqlite\";\nimport type { ZoneLevel, ZoneReport } from \"../../src/zones/zones.js\";\nimport { SeverityPenaltiesSchema } from \"../../src/rubric/schema.js\";\nimport { computeFinalScore } from \"../../src/scoring/engine.js\";\nimport { bareHost } from \"../paths.js\";\nimport type { CategoryResult, SeverityPenalties } from \"../../src/scoring/types.js\";\n\n// ponytail: rubric defaults, not the repo's .pr-score rubric (not stored locally); the vote UI lets you override the score.\nconst DEFAULT_PENALTIES: SeverityPenalties = SeverityPenaltiesSchema.parse({});\n\nexport interface MergeRequestRow {\n id: number;\n mined_discussions_at: string | null;\n}\n\n/** Returns the Yolont project id (projects.id) \u2014 use it for every DB call; `project.id` is the\n * forge's id, only for API calls. Same forge id on two hosts = two projects. */\nexport function upsertProject(db: DatabaseSync, project: { host: string; id: number | string; pathWithNamespace: string; name: string }): number {\n const row = db\n .prepare(\n `INSERT INTO projects (forge_host, forge_project_id, path_with_namespace, name) VALUES (?, ?, ?, ?)\n ON CONFLICT(forge_host, forge_project_id) DO UPDATE SET path_with_namespace = excluded.path_with_namespace, name = excluded.name\n RETURNING id`,\n )\n .get(bareHost(project.host), String(project.id), project.pathWithNamespace, project.name) as unknown as { id: number };\n return row.id;\n}\n\nexport function findProjectId(db: DatabaseSync, host: string, forgeProjectId: number | string): number | undefined {\n const row = db.prepare(`SELECT id FROM projects WHERE forge_host = ? AND forge_project_id = ?`).get(bareHost(host), String(forgeProjectId)) as\n | { id: number }\n | undefined;\n return row?.id;\n}\n\n/** Pre-Yolont rows have no host; they all came from one GitLab, so claim them for it. Idempotent. */\nexport function stampLegacyProjectHost(db: DatabaseSync, host: string): number {\n const changes = Number(db.prepare(`UPDATE projects SET forge_host = ? WHERE forge_host IS NULL`).run(bareHost(host)).changes);\n backfillInsightHosts(db);\n return changes;\n}\n\n/**\n * A person is (git host, username): `alice` on GitHub and `alice` on a company GitLab are two\n * people, and one's memory must never reach the other's reviews.\n */\nexport interface AuthorKey {\n host: string;\n username: string;\n}\n\n/**\n * Gives every insight the host it belongs to. Idempotent (only fills NULLs), so it's run on\n * every DB open and again right after legacy projects get their host: from its project, else\n * from its evidence MRs when they agree on one host, else \u2014 on a single-host DB \u2014 that host.\n * Whatever is still NULL is ambiguous and stays out of review prompts.\n */\nexport function backfillInsightHosts(db: DatabaseSync): void {\n db.exec(`UPDATE insights SET host = (SELECT forge_host FROM projects WHERE id = insights.project_id)\n WHERE host IS NULL AND project_id IS NOT NULL`);\n db.exec(`UPDATE insights SET host = (\n SELECT MIN(p.forge_host) FROM json_each(insights.evidence_mr_ids_json) j\n JOIN merge_requests mr ON mr.id = j.value JOIN projects p ON p.id = mr.project_id)\n WHERE host IS NULL AND (\n SELECT COUNT(DISTINCT p.forge_host) = 1 AND COUNT(*) = COUNT(p.forge_host) FROM json_each(insights.evidence_mr_ids_json) j\n JOIN merge_requests mr ON mr.id = j.value JOIN projects p ON p.id = mr.project_id)`);\n db.exec(`UPDATE insights SET host = (SELECT forge_host FROM projects LIMIT 1)\n WHERE host IS NULL\n AND (SELECT COUNT(DISTINCT forge_host) FROM projects) = 1\n AND NOT EXISTS (SELECT 1 FROM projects WHERE forge_host IS NULL)`);\n}\n\nexport function upsertMergeRequest(\n db: DatabaseSync,\n mr: {\n projectId: number;\n mrIid: number;\n authorUsername: string;\n sha: string;\n title: string;\n mergedAt: string | null;\n source: \"backfill\" | \"live\";\n },\n): MergeRequestRow {\n const row = db\n .prepare(\n `INSERT INTO merge_requests (project_id, mr_iid, author_username, sha, title, merged_at, source)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(project_id, mr_iid) DO UPDATE SET sha = excluded.sha, title = excluded.title, merged_at = excluded.merged_at\n RETURNING id, mined_discussions_at`,\n )\n .get(mr.projectId, mr.mrIid, mr.authorUsername, mr.sha, mr.title, mr.mergedAt, mr.source) as unknown as MergeRequestRow;\n return row;\n}\n\nexport function getMergeRequestByProjectAndIid(db: DatabaseSync, projectId: number, mrIid: number): MergeRequestRow | undefined {\n return db\n .prepare(`SELECT id, mined_discussions_at FROM merge_requests WHERE project_id = ? AND mr_iid = ?`)\n .get(projectId, mrIid) as unknown as MergeRequestRow | undefined;\n}\n\nexport function markDiscussionsMined(db: DatabaseSync, mergeRequestId: number): void {\n db.prepare(`UPDATE merge_requests SET mined_discussions_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') WHERE id = ?`).run(\n mergeRequestId,\n );\n}\n\nexport function insertHumanComment(\n db: DatabaseSync,\n c: { mergeRequestId: number; authorUsername: string; body: string; file?: string; line?: number; createdAt: string },\n): void {\n db.prepare(\n `INSERT INTO human_review_comments (merge_request_id, author_username, body, file, line, created_at) VALUES (?, ?, ?, ?, ?, ?)`,\n ).run(c.mergeRequestId, c.authorUsername, c.body, c.file ?? null, c.line ?? null, c.createdAt);\n}\n\nexport function upsertScore(\n db: DatabaseSync,\n s: {\n mergeRequestId: number;\n scoredAt: string;\n finalScore: number;\n categoryScores: Record<string, number>;\n findings: unknown;\n source: \"llm_backfill\" | \"llm_live\";\n modelUsed?: string;\n volumeFactor?: number;\n /** Machine scores + rubric weights before any human correction \u2014 what refreshScores\n * rebuilds the total from. Without it a past review can't be recomputed. */\n base: ScoreBase;\n /** src/changeType.ts; null = not classified. */\n changeType?: string | null;\n },\n): void {\n db.prepare(\n `INSERT INTO scores (merge_request_id, scored_at, final_score, category_scores_json, findings_json, source, model_used, volume_factor, base_json, change_type)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(merge_request_id, source) DO UPDATE SET\n -- Re-reviewing makes the row yours again: a teammate's imported row must not keep\n -- their uid/origin, or your newer review would never be shared and their file would\n -- overwrite it on the next import. Your own row keeps its uid (its file is rewritten).\n uid = CASE WHEN origin IS NULL THEN uid ELSE NULL END,\n origin = NULL,\n scored_at = excluded.scored_at,\n final_score = excluded.final_score,\n category_scores_json = excluded.category_scores_json,\n findings_json = excluded.findings_json,\n model_used = excluded.model_used,\n volume_factor = excluded.volume_factor,\n base_json = excluded.base_json,\n change_type = excluded.change_type`,\n ).run(\n s.mergeRequestId,\n s.scoredAt,\n s.finalScore,\n JSON.stringify(s.categoryScores),\n JSON.stringify(s.findings),\n s.source,\n s.modelUsed ?? null,\n s.volumeFactor ?? 1,\n JSON.stringify(s.base),\n s.changeType ?? null,\n );\n upsertFindingsForScore(db, s.mergeRequestId, s.findings as { category?: string; severity: string; issue: string; file?: string; line?: number }[]);\n refreshScores(db, s.mergeRequestId);\n}\n\nexport type ScoreBase = Pick<CategoryResult, \"name\" | \"score\" | \"weight\" | \"available\">[];\n\n/**\n * Re-derives final_score + category_scores_json for every score row of an MR from its\n * machine base plus the corrections made since that row was scored (latest per category\n * wins; a category-less correction overrides the total). Same computeFinalScore the\n * review used, so TUI, panel edits and finding votes all agree. Called after every\n * score/correction write. Corrections older than the score belong to a previous review\n * of this MR and are ignored. Rows from before base_json existed are left as stored.\n */\nexport function refreshScores(db: DatabaseSync, mergeRequestId: number): void {\n const rows = db\n .prepare(`SELECT id, scored_at, base_json FROM scores WHERE merge_request_id = ? AND base_json IS NOT NULL`)\n .all(mergeRequestId) as unknown as { id: number; scored_at: string; base_json: string }[];\n const update = db.prepare(`UPDATE scores SET final_score = ?, category_scores_json = ? WHERE id = ?`);\n for (const row of rows) {\n const r = scoreFromBase(JSON.parse(row.base_json) as ScoreBase, correctionsSince(db, mergeRequestId, row.scored_at));\n update.run(r.finalScore, JSON.stringify(r.categoryScores), row.id);\n }\n}\n\ntype BaseCorrection = { category: string | null; corrected_score: number };\n\nfunction correctionsSince(db: DatabaseSync, mergeRequestId: number, scoredAt: string): BaseCorrection[] {\n return db\n .prepare(`SELECT category, corrected_score FROM corrections WHERE merge_request_id = ? AND created_at >= ? ORDER BY created_at, id`)\n .all(mergeRequestId, scoredAt) as unknown as BaseCorrection[];\n}\n\n/** The one place a total is derived: machine base + latest correction per category (+ optional new weights). */\nexport function scoreFromBase(base: ScoreBase, corrections: BaseCorrection[], weights?: Record<string, number>): { finalScore: number; categoryScores: Record<string, number>; overridden: boolean } {\n const latest = new Map(corrections.map((c) => [c.category, c.corrected_score]));\n const categories = base.map((c) => ({ ...c, weight: weights?.[c.name] ?? c.weight, score: latest.get(c.name) ?? c.score, findings: [] }));\n const { finalScore } = computeFinalScore(categories, 0);\n const override = latest.get(null);\n return { finalScore: override ?? finalScore, categoryScores: Object.fromEntries(categories.map((c) => [c.name, c.score])), overridden: override !== undefined };\n}\n\nexport interface ReplayRow {\n mergeRequestId: number;\n mrIid: number;\n title: string | null;\n scoredAt: string;\n oldScore: number;\n newScore: number;\n oldPass: boolean;\n newPass: boolean;\n /** A total-score correction pins the result; weights can't move it. */\n overridden: boolean;\n}\n\n/**\n * \"Last N reviews with these weights\": same scoreFromBase as refreshScores, so replay and the\n * stored totals agree. Rows without a base snapshot (pre-Phase 0) can't be replayed and are skipped.\n */\nexport function replayScores(\n db: DatabaseSync,\n projectId: number,\n weights: Record<string, number>,\n threshold: number,\n limit = 20,\n /** Threshold the stored scores were judged by (the saved rubric's) \u2014 so moving only the slider shows flips. */\n oldThreshold = threshold,\n): { rows: ReplayRow[]; skipped: number } {\n const all = db\n .prepare(\n `SELECT s.merge_request_id, s.scored_at, s.final_score, s.base_json, m.mr_iid, m.title\n FROM scores s JOIN merge_requests m ON m.id = s.merge_request_id\n WHERE m.project_id = ? ORDER BY s.scored_at DESC LIMIT ?`,\n )\n .all(projectId, limit) as unknown as { merge_request_id: number; scored_at: string; final_score: number; base_json: string | null; mr_iid: number; title: string | null }[];\n const rows: ReplayRow[] = [];\n for (const r of all) {\n if (!r.base_json) continue;\n const next = scoreFromBase(JSON.parse(r.base_json) as ScoreBase, correctionsSince(db, r.merge_request_id, r.scored_at), weights);\n rows.push({\n mergeRequestId: r.merge_request_id,\n mrIid: r.mr_iid,\n title: r.title,\n scoredAt: r.scored_at,\n oldScore: r.final_score,\n newScore: next.finalScore,\n oldPass: r.final_score >= oldThreshold,\n newPass: next.finalScore >= threshold,\n overridden: next.overridden,\n });\n }\n return { rows, skipped: all.length - rows.length };\n}\n\n/** Gives each finding a stable row/id \u2014 see `findings` table comment in schema.sql for the\n * dedupe rationale. `ON CONFLICT DO NOTHING` means a finding that reappears across a\n * re-review keeps its original id, so votes/tags on it survive a rescore. */\nexport function upsertFindingsForScore(\n db: DatabaseSync,\n mergeRequestId: number,\n findings: { category?: string; severity: string; issue: string; file?: string; line?: number }[],\n): void {\n const insert = db.prepare(\n `INSERT INTO findings (merge_request_id, category, severity, issue, file, line)\n VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT (merge_request_id, file, line, issue) DO NOTHING`,\n );\n for (const f of findings) {\n insert.run(mergeRequestId, f.category ?? null, f.severity, f.issue, f.file ?? null, f.line ?? null);\n }\n}\n\nexport function insertCorrection(\n db: DatabaseSync,\n c: {\n mergeRequestId: number;\n category: string | null;\n originalScore: number;\n correctedScore: number;\n reason: string;\n correctedNote?: string;\n },\n): number {\n const row = db\n .prepare(\n `INSERT INTO corrections (merge_request_id, category, original_score, corrected_score, reason, corrected_note)\n VALUES (?, ?, ?, ?, ?, ?) RETURNING id`,\n )\n .get(c.mergeRequestId, c.category, c.originalScore, c.correctedScore, c.reason, c.correctedNote ?? null) as unknown as {\n id: number;\n };\n refreshScores(db, c.mergeRequestId);\n return row.id;\n}\n\nexport function insertInsight(\n db: DatabaseSync,\n i: {\n authorUsername: string | null;\n /** The git host this insight belongs to; NULL only for legacy rows nobody could place. */\n host: string | null;\n projectId: number | null;\n category: string | null;\n insightText: string;\n evidenceMrIds: number[];\n },\n): number {\n const row = db\n .prepare(\n `INSERT INTO insights (author_username, host, project_id, category, insight_text, evidence_mr_ids_json)\n VALUES (?, ?, ?, ?, ?, ?) RETURNING id`,\n )\n .get(i.authorUsername, i.host, i.projectId, i.category, i.insightText, JSON.stringify(i.evidenceMrIds)) as unknown as { id: number };\n return row.id;\n}\n\nexport function insertFindingDiscussion(\n db: DatabaseSync,\n d: {\n mergeRequestId: number;\n discussionId: string;\n category: string;\n severity: string;\n issue: string;\n file?: string;\n line?: number;\n postedNoteId: number;\n },\n): void {\n db.prepare(\n `INSERT INTO finding_discussions (merge_request_id, discussion_id, category, severity, issue, file, line, posted_note_id)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(merge_request_id, file, line, issue) DO NOTHING`,\n ).run(d.mergeRequestId, d.discussionId, d.category, d.severity, d.issue, d.file ?? null, d.line ?? null, d.postedNoteId);\n}\n\nexport interface FindingRow {\n id: number;\n merge_request_id: number;\n category: string | null;\n severity: string;\n issue: string;\n file: string | null;\n line: number | null;\n vote: \"up\" | \"down\" | null;\n note: string | null;\n tags: string[];\n replies: ThreadNote[];\n nearby: ThreadNote[];\n /** Posted as its own GitLab thread, so votes/tags can be synced back to it. */\n has_thread: boolean;\n /** Our decision reply currently exists on that thread. */\n posted: boolean;\n sync_error: string | null;\n}\n\nexport interface ThreadNote {\n author_username: string;\n body: string;\n created_at: string;\n}\n\nconst NEARBY_LINES = 5;\n\n/** A finding's discussion: `replies` are exact (notes on the finding's own GitLab thread,\n * joined via finding_discussions' shared dedupe key); `nearby` are mined human comments on\n * the same file within NEARBY_LINES \u2014 fuzzy, since backfill flattens threads and file/line\n * is the only link left. */\nexport function getFindingThread(\n db: DatabaseSync,\n f: { merge_request_id: number; file: string | null; line: number | null; issue: string },\n): { replies: ThreadNote[]; nearby: ThreadNote[] } {\n const replies = db\n .prepare(\n `SELECT fr.author_username, fr.body, fr.created_at\n FROM finding_responses fr\n JOIN finding_discussions fd ON fd.id = fr.finding_discussion_id\n WHERE fd.merge_request_id = ? AND fd.file IS ? AND fd.line IS ? AND fd.issue = ?\n ORDER BY fr.created_at ASC`,\n )\n .all(f.merge_request_id, f.file, f.line, f.issue) as unknown as ThreadNote[];\n if (!f.file) return { replies, nearby: [] };\n\n const replyBodies = new Set(replies.map((r) => r.body));\n const nearby = (\n db\n .prepare(\n `SELECT author_username, body, created_at FROM human_review_comments\n WHERE merge_request_id = ? AND file = ? AND (? IS NULL OR ABS(line - ?) <= ?)\n ORDER BY created_at ASC`,\n )\n .all(f.merge_request_id, f.file, f.line, f.line, NEARBY_LINES) as unknown as ThreadNote[]\n ).filter((c) => !replyBodies.has(c.body)); // a later backfill also mines our own threads' replies\n return { replies, nearby };\n}\n\n/** Findings for one MR, each with its vote (if any), tags and thread \u2014 backs the review-detail page. */\nexport function listFindingsForMr(db: DatabaseSync, mergeRequestId: number): FindingRow[] {\n const rows = db\n .prepare(\n `SELECT f.*, fv.vote AS vote, fv.note AS note, fd.id IS NOT NULL AS has_thread, fd.decision_note_id IS NOT NULL AS posted, fd.decision_sync_error AS sync_error,\n (SELECT GROUP_CONCAT(ft.tag) FROM finding_tags ft WHERE ft.finding_id = f.id) AS tags_concat\n FROM findings f\n LEFT JOIN finding_votes fv ON fv.finding_id = f.id\n LEFT JOIN finding_discussions fd\n ON fd.merge_request_id = f.merge_request_id AND fd.file IS f.file AND fd.line IS f.line AND fd.issue = f.issue\n WHERE f.merge_request_id = ?\n ORDER BY f.id ASC`,\n )\n .all(mergeRequestId) as unknown as (Omit<FindingRow, \"tags\" | \"replies\" | \"nearby\" | \"has_thread\" | \"posted\"> & {\n tags_concat: string | null;\n has_thread: number;\n posted: number;\n })[];\n return rows.map(({ tags_concat, has_thread, posted, ...f }) => ({\n ...f,\n has_thread: has_thread === 1,\n posted: posted === 1,\n tags: tags_concat ? tags_concat.split(\",\") : [],\n ...getFindingThread(db, f),\n }));\n}\n\nexport interface FindingContext {\n id: number;\n merge_request_id: number;\n category: string | null;\n severity: string;\n issue: string;\n file: string | null;\n line: number | null;\n author_username: string;\n project_id: number;\n original_score: number;\n volume_factor: number;\n}\n\n/** Finding + its MR + latest score's category/final score \u2014 used to default a vote-driven\n * correction's `original_score` without the caller needing to know the scoring shape. */\nexport function getFindingContext(db: DatabaseSync, findingId: number): FindingContext | undefined {\n const finding = db.prepare(`SELECT * FROM findings WHERE id = ?`).get(findingId) as unknown as\n | { id: number; merge_request_id: number; category: string | null; severity: string; issue: string; file: string | null; line: number | null }\n | undefined;\n if (!finding) return undefined;\n\n const mr = db.prepare(`SELECT author_username, project_id FROM merge_requests WHERE id = ?`).get(finding.merge_request_id) as unknown as\n | { author_username: string; project_id: number }\n | undefined;\n if (!mr) return undefined;\n\n const score = db\n .prepare(`SELECT category_scores_json, final_score, volume_factor FROM scores WHERE merge_request_id = ? ORDER BY scored_at DESC LIMIT 1`)\n .get(finding.merge_request_id) as unknown as { category_scores_json: string; final_score: number; volume_factor: number } | undefined;\n\n let originalScore = score?.final_score ?? 0;\n if (score && finding.category) {\n const categoryScores = JSON.parse(score.category_scores_json) as Record<string, number>;\n if (finding.category in categoryScores) originalScore = categoryScores[finding.category] ?? originalScore;\n }\n\n return {\n id: finding.id,\n merge_request_id: finding.merge_request_id,\n category: finding.category,\n severity: finding.severity,\n issue: finding.issue,\n file: finding.file,\n line: finding.line,\n author_username: mr.author_username,\n project_id: mr.project_id,\n original_score: originalScore,\n volume_factor: score?.volume_factor ?? 1,\n };\n}\n\n/** One active vote per finding \u2014 re-voting deletes the old vote and its linked\n * correction/insight first, so re-voting never double-counts a score adjustment. */\nexport function upsertFindingVote(\n db: DatabaseSync,\n findingId: number,\n v: { vote: \"up\" | \"down\"; note: string; adjustScore: boolean; category?: string | null; correctedScore?: number },\n): void {\n deleteFindingVote(db, findingId);\n\n const ctx = getFindingContext(db, findingId);\n if (!ctx) throw new Error(`finding ${findingId} not found`);\n\n // A \uD83D\uDC4E means false positive: with no explicit score, give back the finding's size-scaled severity penalty.\n let correctedScore = v.correctedScore;\n if (correctedScore == null && v.vote === \"down\") {\n const penalty = (DEFAULT_PENALTIES[ctx.severity as keyof SeverityPenalties] ?? 0) * ctx.volume_factor;\n correctedScore = Math.min(100, Math.round(ctx.original_score + penalty));\n }\n\n let correctionId: number | null = null;\n if (v.adjustScore) {\n const category = v.category ?? ctx.category;\n correctionId = insertCorrection(db, {\n mergeRequestId: ctx.merge_request_id,\n category: category ?? null,\n originalScore: ctx.original_score,\n correctedScore: correctedScore ?? ctx.original_score,\n reason: v.note,\n });\n }\n\n // The vote judges the finding, not the contributor's reaction \u2014 the reply is quoted so memory\n // learns *why*. \uD83D\uDC4D is about this author's code (author-scoped); \uD83D\uDC4E is reviewer calibration for\n // the whole project (author NULL), since a false positive says nothing about the author.\n const { replies } = getFindingThread(db, ctx);\n const lastReply = replies.at(-1);\n const replyText = lastReply ? ` Contributor ${lastReply.author_username} replied: \"${lastReply.body.slice(0, 300)}\".` : \"\";\n const insightText =\n v.vote === \"up\"\n ? `Confirmed issue in ${ctx.author_username}'s code: ${ctx.issue}.${replyText} Maintainer: ${v.note}`\n : `False positive \u2014 do not flag: ${ctx.issue}.${replyText} Maintainer agrees with contributor: ${v.note}`;\n const { forge_host } = db.prepare(`SELECT forge_host FROM projects WHERE id = ?`).get(ctx.project_id) as { forge_host: string | null };\n const insightId = insertInsight(db, {\n authorUsername: v.vote === \"up\" ? ctx.author_username : null,\n host: forge_host,\n projectId: ctx.project_id,\n category: ctx.category,\n insightText,\n evidenceMrIds: [ctx.merge_request_id],\n });\n\n db.prepare(\n `INSERT INTO finding_votes (finding_id, vote, note, correction_id, insight_id) VALUES (?, ?, ?, ?, ?)`,\n ).run(findingId, v.vote, v.note, correctionId, insightId);\n}\n\n/** Undo: removes the vote and any correction/insight it created. */\nexport function deleteFindingVote(db: DatabaseSync, findingId: number): void {\n const existing = db.prepare(`SELECT correction_id, insight_id FROM finding_votes WHERE finding_id = ?`).get(findingId) as unknown as\n | { correction_id: number | null; insight_id: number | null }\n | undefined;\n if (!existing) return;\n\n db.prepare(`DELETE FROM finding_votes WHERE finding_id = ?`).run(findingId);\n if (existing.correction_id != null) deleteCorrection(db, existing.correction_id);\n if (existing.insight_id != null) db.prepare(`DELETE FROM insights WHERE id = ?`).run(existing.insight_id);\n}\n\nexport function addFindingTag(db: DatabaseSync, findingId: number, tag: string): void {\n db.prepare(`INSERT INTO finding_tags (finding_id, tag) VALUES (?, ?) ON CONFLICT (finding_id, tag) DO NOTHING`).run(findingId, tag);\n}\n\nexport function removeFindingTag(db: DatabaseSync, findingId: number, tag: string): void {\n db.prepare(`DELETE FROM finding_tags WHERE finding_id = ? AND tag = ?`).run(findingId, tag);\n}\n\nexport interface QueryFindingRow {\n id: number;\n merge_request_id: number;\n mr_iid: number;\n project_id: number;\n project_path: string | null;\n author_username: string;\n category: string | null;\n severity: string;\n issue: string;\n file: string | null;\n line: number | null;\n vote: \"up\" | \"down\" | null;\n note: string | null;\n tags: string[];\n replies: ThreadNote[];\n nearby: ThreadNote[];\n}\n\n/** Cross-project/author/tag finding browser \u2014 filters combine with AND; any unset filter\n * matches everything. */\nexport function queryFindings(\n db: DatabaseSync,\n filter: { projectId?: number; author?: AuthorKey; tag?: string },\n): QueryFindingRow[] {\n const rows = db\n .prepare(\n `SELECT f.id, f.merge_request_id, mr.mr_iid, mr.project_id, p.path_with_namespace AS project_path, mr.author_username,\n f.category, f.severity, f.issue, f.file, f.line, fv.vote AS vote, fv.note AS note,\n (SELECT GROUP_CONCAT(ft.tag) FROM finding_tags ft WHERE ft.finding_id = f.id) AS tags_concat\n FROM findings f\n JOIN merge_requests mr ON mr.id = f.merge_request_id\n LEFT JOIN projects p ON p.id = mr.project_id\n LEFT JOIN finding_votes fv ON fv.finding_id = f.id\n WHERE (? IS NULL OR mr.project_id = ?)\n AND (? IS NULL OR (mr.author_username = ? AND p.forge_host = ?))\n AND (? IS NULL OR EXISTS (SELECT 1 FROM finding_tags ft WHERE ft.finding_id = f.id AND ft.tag = ?))\n ORDER BY f.created_at DESC`,\n )\n .all(\n filter.projectId ?? null,\n filter.projectId ?? null,\n filter.author?.username ?? null,\n filter.author?.username ?? null,\n filter.author?.host ?? null,\n filter.tag ?? null,\n filter.tag ?? null,\n ) as unknown as (Omit<QueryFindingRow, \"tags\" | \"replies\" | \"nearby\"> & { tags_concat: string | null })[];\n // ponytail: 2 queries per finding for the thread; fine for a local SQLite DB, fold into one JOIN if this page gets slow.\n return rows.map(({ tags_concat, ...f }) => ({ ...f, tags: tags_concat ? tags_concat.split(\",\") : [], ...getFindingThread(db, f) }));\n}\n\nexport interface FindingDiscussionRow {\n id: number;\n merge_request_id: number;\n discussion_id: string;\n category: string;\n severity: string;\n issue: string;\n file: string | null;\n line: number | null;\n posted_note_id: number;\n created_at: string;\n}\n\nexport function listFindingDiscussionsForMr(db: DatabaseSync, mergeRequestId: number): FindingDiscussionRow[] {\n return db\n .prepare(`SELECT * FROM finding_discussions WHERE merge_request_id = ? ORDER BY created_at ASC`)\n .all(mergeRequestId) as unknown as FindingDiscussionRow[];\n}\n\n/** Stores a reply on a finding thread. An edited reply (same note, new text) is updated. */\nexport function insertFindingResponse(\n db: DatabaseSync,\n r: { findingDiscussionId: number; noteId: number; authorUsername: string; body: string; createdAt: string },\n): \"new\" | \"updated\" | null {\n const prev = db.prepare(`SELECT body FROM finding_responses WHERE note_id = ?`).get(r.noteId) as { body: string } | undefined;\n if (prev) {\n if (prev.body === r.body) return null;\n db.prepare(`UPDATE finding_responses SET body = ? WHERE note_id = ?`).run(r.body, r.noteId);\n return \"updated\";\n }\n db.prepare(\n `INSERT INTO finding_responses (finding_discussion_id, note_id, author_username, body, created_at) VALUES (?, ?, ?, ?, ?)`,\n ).run(r.findingDiscussionId, r.noteId, r.authorUsername, r.body, r.createdAt);\n return \"new\";\n}\n\nexport interface FindingResponseRow {\n id: number;\n finding_discussion_id: number;\n note_id: number;\n author_username: string;\n body: string;\n created_at: string;\n category: string;\n severity: string;\n issue: string;\n file: string | null;\n line: number | null;\n merge_request_id: number;\n mr_iid: number;\n project_id: number;\n}\n\nexport function listAuthorFindingResponses(\n db: DatabaseSync,\n author: AuthorKey,\n limit = 20,\n projectId?: number,\n): FindingResponseRow[] {\n return db\n .prepare(\n `SELECT fr.*, fd.category, fd.severity, fd.issue, fd.file, fd.line, fd.merge_request_id, mr.mr_iid, mr.project_id\n FROM finding_responses fr\n JOIN finding_discussions fd ON fd.id = fr.finding_discussion_id\n JOIN merge_requests mr ON mr.id = fd.merge_request_id\n JOIN projects p ON p.id = mr.project_id\n WHERE mr.author_username = ? AND p.forge_host = ? AND (? IS NULL OR mr.project_id = ?)\n ORDER BY fr.created_at DESC\n LIMIT ?`,\n )\n .all(author.username, author.host, projectId ?? null, projectId ?? null, limit) as unknown as FindingResponseRow[];\n}\n\n/** Everyone with an MR in the DB, per host. Projects not yet given a host (pre-Yolont, before\n * the legacy stamp) are left out until they have one. */\n/** `projectIds`: only authors with MRs in these projects (the panel's source filter). */\nexport function listAuthors(db: DatabaseSync, projectIds?: number[]): AuthorKey[] {\n const ids = projectIds ? JSON.stringify(projectIds) : null;\n return db\n .prepare(\n `SELECT DISTINCT p.forge_host AS host, mr.author_username AS username\n FROM merge_requests mr JOIN projects p ON p.id = mr.project_id\n WHERE p.forge_host IS NOT NULL AND (? IS NULL OR p.id IN (SELECT value FROM json_each(?)))\n ORDER BY username, host`,\n )\n .all(ids, ids) as unknown as AuthorKey[];\n}\n\nexport interface ScoreRow {\n id: number;\n merge_request_id: number;\n scored_at: string;\n final_score: number;\n category_scores_json: string;\n findings_json: string;\n source: string;\n model_used: string | null;\n mr_iid: number;\n project_id: number;\n}\n\n/** Latest score per MR for this author, oldest first \u2014 what trend.ts regresses over. */\nexport function listAuthorScores(db: DatabaseSync, author: AuthorKey): ScoreRow[] {\n return db\n .prepare(\n `SELECT s.*, mr.mr_iid, mr.project_id FROM scores s\n JOIN merge_requests mr ON mr.id = s.merge_request_id\n JOIN projects p ON p.id = mr.project_id\n WHERE mr.author_username = ? AND p.forge_host = ?\n ORDER BY s.scored_at ASC`,\n )\n .all(author.username, author.host) as unknown as ScoreRow[];\n}\n\nexport interface CorrectionRow {\n id: number;\n merge_request_id: number;\n category: string | null;\n original_score: number;\n corrected_score: number;\n reason: string;\n corrected_note: string | null;\n created_at: string;\n mr_iid: number;\n project_id: number;\n project_path: string;\n /** Team data source it was imported from; null = made here. */\n origin: string | null;\n}\n\nexport function listAuthorCorrections(\n db: DatabaseSync,\n author: AuthorKey,\n limit = 20,\n projectId?: number,\n): CorrectionRow[] {\n return db\n .prepare(\n `SELECT c.*, mr.mr_iid, mr.project_id, p.path_with_namespace AS project_path FROM corrections c\n JOIN merge_requests mr ON mr.id = c.merge_request_id\n JOIN projects p ON p.id = mr.project_id\n WHERE mr.author_username = ? AND p.forge_host = ? AND (? IS NULL OR mr.project_id = ?)\n ORDER BY c.created_at DESC\n LIMIT ?`,\n )\n .all(author.username, author.host, projectId ?? null, projectId ?? null, limit) as unknown as CorrectionRow[];\n}\n\nexport interface CommentRow {\n id: number;\n merge_request_id: number;\n author_username: string;\n body: string;\n file: string | null;\n line: number | null;\n created_at: string;\n}\n\nexport function listAuthorComments(db: DatabaseSync, author: AuthorKey): CommentRow[] {\n return db\n .prepare(\n `SELECT hrc.* FROM human_review_comments hrc\n JOIN merge_requests mr ON mr.id = hrc.merge_request_id\n JOIN projects p ON p.id = mr.project_id\n WHERE mr.author_username = ? AND p.forge_host = ?\n ORDER BY hrc.created_at DESC`,\n )\n .all(author.username, author.host) as unknown as CommentRow[];\n}\n\n/** Comment volume per author \u2014 the zero-LLM-cost effort signal available right after a plain backfill. */\nexport function commentVolumeByAuthor(db: DatabaseSync, projectIds?: number[]): { host: string | null; author_username: string; comment_count: number; mr_count: number }[] {\n const ids = projectIds ? JSON.stringify(projectIds) : null;\n return db\n .prepare(\n `SELECT p.forge_host AS host, mr.author_username, COUNT(hrc.id) AS comment_count, COUNT(DISTINCT mr.id) AS mr_count\n FROM merge_requests mr\n JOIN projects p ON p.id = mr.project_id\n LEFT JOIN human_review_comments hrc ON hrc.merge_request_id = mr.id\n WHERE ? IS NULL OR p.id IN (SELECT value FROM json_each(?))\n GROUP BY p.forge_host, mr.author_username\n ORDER BY comment_count DESC`,\n )\n .all(ids, ids) as unknown as { host: string | null; author_username: string; comment_count: number; mr_count: number }[];\n}\n\nexport interface InsightRow {\n id: number;\n author_username: string | null;\n host: string | null;\n project_id: number | null;\n project_path: string | null;\n category: string | null;\n insight_text: string;\n evidence_mr_ids_json: string;\n created_at: string;\n /** Team data source it was imported from; null = made here. */\n origin: string | null;\n}\n\n/**\n * Unset filters match everything. `username`/`projectId` also take rows marked for every\n * author / every project (NULL). `host` is strict: an insight from another git host \u2014 or one\n * whose host is unknown \u2014 never comes back, so memory can't cross hosts. Pass it whenever the\n * result feeds a review.\n */\nexport function listInsights(db: DatabaseSync, filter: { host?: string; username?: string; projectId?: number } = {}): InsightRow[] {\n const { host = null, username = null, projectId = null } = filter;\n return db\n .prepare(\n `SELECT i.*, p.path_with_namespace AS project_path FROM insights i\n LEFT JOIN projects p ON p.id = i.project_id\n WHERE (? IS NULL OR i.host = ?)\n AND (? IS NULL OR i.author_username = ? OR i.author_username IS NULL)\n AND (? IS NULL OR i.project_id = ? OR i.project_id IS NULL)\n ORDER BY i.created_at DESC`,\n )\n .all(host, host, username, username, projectId, projectId) as unknown as InsightRow[];\n}\n\nexport function deleteInsight(db: DatabaseSync, id: number): void {\n db.prepare(`DELETE FROM insights WHERE id = ?`).run(id);\n}\n\nexport interface ReviewSummaryRow {\n score_id: number;\n merge_request_id: number;\n project_id: number;\n project_path: string | null;\n mr_iid: number;\n author_username: string;\n title: string;\n source: string;\n final_score: number;\n scored_at: string;\n change_type: string | null;\n correction_count: number;\n}\n\n/** One row per (merge_request, source) score \u2014 a backfilled baseline and a live re-review\n * of the same MR are two distinct entries in this history, not a duplicate. */\nexport function listReviews(db: DatabaseSync): ReviewSummaryRow[] {\n return db\n .prepare(\n `SELECT s.id AS score_id, mr.id AS merge_request_id, mr.project_id, p.path_with_namespace AS project_path,\n mr.mr_iid, mr.author_username, mr.title, s.source, s.final_score, s.scored_at, s.change_type,\n (SELECT COUNT(*) FROM corrections c WHERE c.merge_request_id = mr.id) AS correction_count\n FROM scores s\n JOIN merge_requests mr ON mr.id = s.merge_request_id\n LEFT JOIN projects p ON p.id = mr.project_id\n ORDER BY s.scored_at DESC`,\n )\n .all() as unknown as ReviewSummaryRow[];\n}\n\nexport interface MergeRequestDetailRow {\n id: number;\n project_id: number;\n project_path: string | null;\n mr_iid: number;\n author_username: string;\n title: string;\n sha: string;\n merged_at: string | null;\n source: string;\n}\n\nexport function getMergeRequestById(db: DatabaseSync, id: number): MergeRequestDetailRow | undefined {\n return db\n .prepare(\n `SELECT mr.*, p.path_with_namespace AS project_path FROM merge_requests mr\n LEFT JOIN projects p ON p.id = mr.project_id\n WHERE mr.id = ?`,\n )\n .get(id) as unknown as MergeRequestDetailRow | undefined;\n}\n\nexport function listScoresForMr(db: DatabaseSync, mergeRequestId: number): ScoreRow[] {\n return db\n .prepare(\n `SELECT s.*, mr.mr_iid, mr.project_id FROM scores s\n JOIN merge_requests mr ON mr.id = s.merge_request_id\n WHERE s.merge_request_id = ?\n ORDER BY s.scored_at DESC`,\n )\n .all(mergeRequestId) as unknown as ScoreRow[];\n}\n\nexport function listCorrectionsForMr(db: DatabaseSync, mergeRequestId: number): CorrectionRow[] {\n return db\n .prepare(\n `SELECT c.*, mr.mr_iid, mr.project_id, p.path_with_namespace AS project_path FROM corrections c\n JOIN merge_requests mr ON mr.id = c.merge_request_id\n LEFT JOIN projects p ON p.id = mr.project_id\n WHERE c.merge_request_id = ?\n ORDER BY c.created_at DESC`,\n )\n .all(mergeRequestId) as unknown as CorrectionRow[];\n}\n\nexport function listCommentsForMr(db: DatabaseSync, mergeRequestId: number): CommentRow[] {\n return db\n .prepare(`SELECT * FROM human_review_comments WHERE merge_request_id = ? ORDER BY created_at DESC`)\n .all(mergeRequestId) as unknown as CommentRow[];\n}\n\nexport function deleteScore(db: DatabaseSync, scoreId: number): void {\n db.prepare(`DELETE FROM scores WHERE id = ?`).run(scoreId);\n}\n\n/** Wipes a review end to end \u2014 scores, corrections, findings (+ their votes/tags), mined\n * comments/discussions, and the MR row itself. Use for a review that shouldn't have been\n * recorded at all; to just stop one bad score from skewing history/memory, delete the\n * score (or correction) alone.\n *\n * Deletion order matters \u2014 foreign_keys is ON, so children go before their parents:\n * finding_votes/finding_tags before findings, finding_responses before finding_discussions. */\nexport function deleteMergeRequest(db: DatabaseSync, mergeRequestId: number): void {\n db.prepare(\n `DELETE FROM finding_votes WHERE finding_id IN (SELECT id FROM findings WHERE merge_request_id = ?)`,\n ).run(mergeRequestId);\n db.prepare(\n `DELETE FROM finding_tags WHERE finding_id IN (SELECT id FROM findings WHERE merge_request_id = ?)`,\n ).run(mergeRequestId);\n db.prepare(`DELETE FROM findings WHERE merge_request_id = ?`).run(mergeRequestId);\n db.prepare(\n `DELETE FROM finding_responses WHERE finding_discussion_id IN (SELECT id FROM finding_discussions WHERE merge_request_id = ?)`,\n ).run(mergeRequestId);\n db.prepare(`DELETE FROM finding_discussions WHERE merge_request_id = ?`).run(mergeRequestId);\n db.prepare(`DELETE FROM corrections WHERE merge_request_id = ?`).run(mergeRequestId);\n db.prepare(`DELETE FROM scores WHERE merge_request_id = ?`).run(mergeRequestId);\n db.prepare(`DELETE FROM human_review_comments WHERE merge_request_id = ?`).run(mergeRequestId);\n db.prepare(`DELETE FROM zone_hits WHERE merge_request_id = ?`).run(mergeRequestId);\n db.prepare(`DELETE FROM merge_requests WHERE id = ?`).run(mergeRequestId);\n}\n\nexport function deleteCorrection(db: DatabaseSync, id: number): void {\n const row = db.prepare(`DELETE FROM corrections WHERE id = ? RETURNING merge_request_id`).get(id) as unknown as { merge_request_id: number } | undefined;\n if (row) refreshScores(db, row.merge_request_id);\n}\n\n/** Full replace, not a partial patch \u2014 the edit form always submits every field, and a\n * correction's whole point is its reason text, so there's no meaningful \"partial\" edit. */\nexport function updateCorrection(\n db: DatabaseSync,\n id: number,\n patch: { category: string | null; correctedScore: number; reason: string; correctedNote: string | null },\n): void {\n db.prepare(`UPDATE corrections SET category = ?, corrected_score = ?, reason = ?, corrected_note = ? WHERE id = ?`).run(\n patch.category,\n patch.correctedScore,\n patch.reason,\n patch.correctedNote,\n id,\n );\n const row = db.prepare(`SELECT merge_request_id FROM corrections WHERE id = ?`).get(id) as unknown as { merge_request_id: number } | undefined;\n if (row) refreshScores(db, row.merge_request_id);\n}\n\n// ---- Performance zones ----\n\nexport interface ZoneHitRow {\n id: number;\n merge_request_id: number;\n zone_id: string;\n level: ZoneLevel;\n files: string[];\n impact: \"none\" | \"low\" | \"high\" | null;\n verdict: string | null;\n vote: \"up\" | \"down\" | null;\n vote_note: string | null;\n created_at: string;\n}\n\nexport interface ProjectZoneHitRow extends ZoneHitRow {\n mr_iid: number;\n title: string;\n author_username: string;\n}\n\ntype RawZoneHit<T extends ZoneHitRow> = Omit<T, \"files\"> & { files_json: string };\nconst parseZoneHit = <T extends ZoneHitRow>({ files_json, ...row }: RawZoneHit<T>): T => ({ ...row, files: JSON.parse(files_json) }) as unknown as T;\n\n/** Re-review overwrites what the machine said (a run with no verdict \u2014 LLM failed, or a\n * zones-only backfill \u2014 keeps the old one); the human vote survives. Zones this MR no\n * longer touches (files moved after a push) are dropped unless someone voted on them. */\nexport function upsertZoneHits(db: DatabaseSync, mergeRequestId: number, report: ZoneReport): void {\n const touched = report.hits.map((h) => h.zone.id);\n db.prepare(\n `DELETE FROM zone_hits WHERE merge_request_id = ? AND vote IS NULL AND zone_id NOT IN (SELECT value FROM json_each(?))`,\n ).run(mergeRequestId, JSON.stringify(touched));\n const stmt = db.prepare(\n `INSERT INTO zone_hits (merge_request_id, zone_id, level, files_json, impact, verdict)\n VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT (merge_request_id, zone_id) DO UPDATE SET\n level = excluded.level, files_json = excluded.files_json,\n impact = COALESCE(excluded.impact, impact), verdict = COALESCE(excluded.verdict, verdict)`,\n );\n for (const { zone, files } of report.hits) {\n const verdict = report.verdicts.find((v) => v.zone_id === zone.id);\n stmt.run(mergeRequestId, zone.id, zone.level, JSON.stringify(files), verdict?.impact ?? null, verdict?.verdict ?? null);\n }\n}\n\n/** Live review owns an MR's zone rows once it has run \u2014 backfill leaves those MRs alone. */\nexport function hasLiveScore(db: DatabaseSync, mergeRequestId: number): boolean {\n return db.prepare(`SELECT 1 FROM scores WHERE merge_request_id = ? AND source = 'llm_live'`).get(mergeRequestId) !== undefined;\n}\n\nexport function listZoneHitsForMr(db: DatabaseSync, mergeRequestId: number): ZoneHitRow[] {\n const rows = db\n .prepare(`SELECT * FROM zone_hits WHERE merge_request_id = ? ORDER BY CASE level WHEN 'red' THEN 0 WHEN 'amber' THEN 1 ELSE 2 END, zone_id`)\n .all(mergeRequestId) as unknown as RawZoneHit<ZoneHitRow>[];\n return rows.map(parseZoneHit);\n}\n\nexport function listZoneHitsForProject(db: DatabaseSync, projectId: number): ProjectZoneHitRow[] {\n const rows = db\n .prepare(\n `SELECT zh.*, mr.mr_iid, mr.title, mr.author_username\n FROM zone_hits zh JOIN merge_requests mr ON mr.id = zh.merge_request_id\n WHERE mr.project_id = ?\n ORDER BY zh.created_at DESC`,\n )\n .all(projectId) as unknown as RawZoneHit<ProjectZoneHitRow>[];\n return rows.map(parseZoneHit);\n}\n\nexport function setZoneHitVote(db: DatabaseSync, id: number, vote: \"up\" | \"down\" | null, note: string | null): void {\n db.prepare(`UPDATE zone_hits SET vote = ?, vote_note = ? WHERE id = ?`).run(vote, vote ? note : null, id);\n}\n\n/** Findings a reviewer tagged 'danger-zone' in this project \u2014 the human-taught red zone. */\nexport function listDangerTaggedFindings(\n db: DatabaseSync,\n projectId: number,\n): { file: string; issue: string; merge_request_id: number; mr_iid: number }[] {\n return db\n .prepare(\n `SELECT DISTINCT f.file, f.issue, f.merge_request_id, mr.mr_iid\n FROM findings f\n JOIN finding_tags ft ON ft.finding_id = f.id AND ft.tag = 'danger-zone'\n JOIN merge_requests mr ON mr.id = f.merge_request_id\n WHERE mr.project_id = ? AND f.file IS NOT NULL\n ORDER BY f.created_at DESC`,\n )\n .all(projectId) as { file: string; issue: string; merge_request_id: number; mr_iid: number }[];\n}\n", "import { DatabaseSync } from \"node:sqlite\";\nimport { mkdirSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { DB_PATH, INSTALL_ROOT } from \"../paths.js\";\nimport { backfillInsightHosts } from \"./repo.js\";\n// From INSTALL_ROOT, not this file: in the published bundle this code lives in dist/cli.js.\nconst SCHEMA_PATH = join(INSTALL_ROOT, \"local\", \"db\", \"schema.sql\");\nexport const DEFAULT_DB_PATH = DB_PATH;\n\n/**\n * node:sqlite (built into Node 22+), not better-sqlite3 \u2014 the native better-sqlite3\n * binding segfaulted on this machine (prebuild/ABI mismatch unrelated to this project),\n * while node:sqlite is compiled into the exact Node binary running it, so there's no\n * separate native binary to mismatch. One less native dependency either way.\n */\nexport function openDb(dbPath: string = DEFAULT_DB_PATH): DatabaseSync {\n if (dbPath !== \":memory:\") mkdirSync(dirname(dbPath), { recursive: true });\n const db = new DatabaseSync(dbPath);\n db.exec(\"PRAGMA foreign_keys = ON;\");\n db.exec(readFileSync(SCHEMA_PATH, \"utf8\"));\n migrate(db);\n return db;\n}\n\n/**\n * `CREATE TABLE IF NOT EXISTS` (above) only affects brand-new databases \u2014 an existing\n * local/data/pr-score.db predates a column added later needs it added in place. Kept as\n * plain, additive `ALTER TABLE ... ADD COLUMN` steps (SQLite has no real migration\n * framework and this DB is a local cache, not something to over-engineer for).\n */\nexport const SYNCED_TABLES = [\"scores\", \"corrections\", \"insights\", \"finding_votes\", \"finding_tags\"] as const;\n\nfunction migrate(db: DatabaseSync): void {\n const projectCols = db.prepare(\"PRAGMA table_info(projects)\").all() as { name: string }[];\n if (!projectCols.some((c) => c.name === \"forge_host\")) {\n db.exec(\"ALTER TABLE projects ADD COLUMN forge_host TEXT\");\n db.exec(\"ALTER TABLE projects ADD COLUMN forge_project_id TEXT\");\n // Pre-Yolont: id was the GitLab project id.\n db.exec(\"UPDATE projects SET forge_project_id = CAST(id AS TEXT)\");\n }\n db.exec(\"CREATE UNIQUE INDEX IF NOT EXISTS idx_projects_forge ON projects (forge_host, forge_project_id)\");\n\n const insightsCols = db.prepare(\"PRAGMA table_info(insights)\").all() as { name: string }[];\n if (!insightsCols.some((c) => c.name === \"project_id\")) {\n db.exec(\"ALTER TABLE insights ADD COLUMN project_id INTEGER REFERENCES projects (id)\");\n }\n db.exec(\"CREATE INDEX IF NOT EXISTS idx_insights_project ON insights (project_id)\");\n if (!insightsCols.some((c) => c.name === \"host\")) {\n db.exec(\"ALTER TABLE insights ADD COLUMN host TEXT\");\n }\n\n const correctionsCols = db.prepare(\"PRAGMA table_info(corrections)\").all() as { name: string }[];\n if (!correctionsCols.some((c) => c.name === \"corrected_note\")) {\n db.exec(\"ALTER TABLE corrections ADD COLUMN corrected_note TEXT\");\n }\n\n const discussionCols = db.prepare(\"PRAGMA table_info(finding_discussions)\").all() as { name: string }[];\n if (!discussionCols.some((c) => c.name === \"decision_note_id\")) {\n db.exec(\"ALTER TABLE finding_discussions ADD COLUMN decision_note_id INTEGER\");\n db.exec(\"ALTER TABLE finding_discussions ADD COLUMN decision_sync_error TEXT\");\n }\n\n const scoresCols = db.prepare(\"PRAGMA table_info(scores)\").all() as { name: string }[];\n if (!scoresCols.some((c) => c.name === \"volume_factor\")) {\n db.exec(\"ALTER TABLE scores ADD COLUMN volume_factor REAL NOT NULL DEFAULT 1\");\n }\n if (!scoresCols.some((c) => c.name === \"base_json\")) {\n db.exec(\"ALTER TABLE scores ADD COLUMN base_json TEXT\");\n }\n if (!scoresCols.some((c) => c.name === \"change_type\")) {\n db.exec(\"ALTER TABLE scores ADD COLUMN change_type TEXT\");\n }\n\n widenFindingTagsCheck(db); // rebuilds finding_tags from schema.sql, so the sync columns come after\n // Memory repos: uid = the record's id in a team data repo, origin = the source a\n // row was imported from (NULL = made here).\n for (const table of SYNCED_TABLES) {\n const cols = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];\n if (!cols.some((c) => c.name === \"uid\")) {\n db.exec(`ALTER TABLE ${table} ADD COLUMN uid TEXT`);\n db.exec(`ALTER TABLE ${table} ADD COLUMN origin TEXT`);\n }\n db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${table}_uid ON ${table} (uid) WHERE uid IS NOT NULL`);\n }\n\n backfillFindings(db);\n backfillInsightHosts(db);\n}\n\n/**\n * SQLite can't ALTER a CHECK constraint, so a DB created before 'danger-zone' was a valid\n * tag rejects it forever. Rebuild finding_tags once (rows copied as-is) when its stored\n * DDL predates that tag.\n */\nfunction widenFindingTagsCheck(db: DatabaseSync): void {\n const { sql } = db.prepare(\"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'finding_tags'\").get() as { sql: string };\n if (sql.includes(\"'danger-zone'\")) return;\n const createSql = readFileSync(SCHEMA_PATH, \"utf8\").match(/CREATE TABLE IF NOT EXISTS finding_tags \\([\\s\\S]*?\\n\\);/)![0];\n // SQLite's documented table-rebuild procedure: FKs off (only settable outside a transaction).\n db.exec(\"PRAGMA foreign_keys = OFF\");\n db.exec(\"BEGIN\");\n try {\n db.exec(\"ALTER TABLE finding_tags RENAME TO finding_tags_old\");\n db.exec(createSql);\n db.exec(\"INSERT INTO finding_tags (id, finding_id, tag, created_at) SELECT id, finding_id, tag, created_at FROM finding_tags_old\");\n db.exec(\"DROP TABLE finding_tags_old\");\n db.exec(\"CREATE INDEX IF NOT EXISTS idx_finding_tags_finding ON finding_tags (finding_id)\");\n db.exec(\"CREATE INDEX IF NOT EXISTS idx_finding_tags_tag ON finding_tags (tag)\");\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw err;\n } finally {\n db.exec(\"PRAGMA foreign_keys = ON\");\n }\n}\n\n/**\n * One-time backfill: the `findings` table didn't exist before this feature, so MRs scored\n * prior to it have no rows there. Guarded on `findings` being empty so this only ever runs\n * once \u2014 after that, `upsertFindingsForScore` is the sole writer.\n */\nfunction backfillFindings(db: DatabaseSync): void {\n const { count } = db.prepare(\"SELECT COUNT(*) AS count FROM findings\").get() as { count: number };\n if (count > 0) return;\n\n const scores = db.prepare(\"SELECT merge_request_id, findings_json FROM scores\").all() as {\n merge_request_id: number;\n findings_json: string;\n }[];\n const insert = db.prepare(\n `INSERT INTO findings (merge_request_id, category, severity, issue, file, line)\n VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT (merge_request_id, file, line, issue) DO NOTHING`,\n );\n for (const s of scores) {\n const findings = JSON.parse(s.findings_json) as {\n category?: string;\n severity: string;\n issue: string;\n file?: string;\n line?: number;\n }[];\n for (const f of findings) {\n insert.run(s.merge_request_id, f.category ?? null, f.severity, f.issue, f.file ?? null, f.line ?? null);\n }\n }\n}\n", "import { execFile } from \"node:child_process\";\nimport { mkdtemp, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { promisify } from \"node:util\";\n\nconst execFileAsync = promisify(execFile);\n\nexport interface SecretFinding {\n ruleId: string;\n file: string;\n line: number;\n description: string;\n}\n\nexport interface SecretsScanResult {\n score: number;\n findings: SecretFinding[];\n /** true when gitleaks itself could not run (missing binary, crash, ...) \u2014 distinct from a real hit. */\n scannerFailed: boolean;\n scannerError?: string;\n}\n\ninterface GitleaksReportEntry {\n RuleID?: string;\n File?: string;\n StartLine?: number;\n Description?: string;\n}\n\n/**\n * gitleaks scans the diff as one file, so its line is a line of the patch. Maps it back to the\n * changed file and its new-file line (old-file line for a removed line), so people can find it.\n */\nexport function locateInDiff(diffText: string, patchLine: number): { file: string; line: number } {\n let file = \"(diff)\";\n let oldLine = 0;\n let newLine = 0;\n const lines = diffText.split(\"\\n\");\n for (let i = 0; i < Math.min(patchLine, lines.length); i++) {\n const l = lines[i]!;\n const hunk = /^@@ -(\\d+)(?:,\\d+)? \\+(\\d+)/.exec(l);\n const isLast = i === patchLine - 1;\n if (l.startsWith(\"diff --git \")) file = l.replace(/^diff --git a\\/.* b\\//, \"\");\n else if (l.startsWith(\"+++ \") && l !== \"+++ /dev/null\") file = l.slice(4).replace(/^b\\//, \"\");\n else if (hunk) [oldLine, newLine] = [Number(hunk[1]), Number(hunk[2])];\n else if (l.startsWith(\"-\") && !l.startsWith(\"--- \")) {\n if (isLast) return { file, line: oldLine };\n oldLine++;\n } else if (l.startsWith(\"+\") || l.startsWith(\" \")) {\n if (isLast) return { file, line: newLine };\n newLine++;\n if (l.startsWith(\" \")) oldLine++;\n }\n }\n return { file, line: 0 };\n}\n\n/** Runs gitleaks against the raw diff text. Never throws \u2014 a scan failure fails closed (treated as a hit). */\nexport async function scanDiffForSecrets(diffText: string): Promise<SecretsScanResult> {\n const dir = await mkdtemp(join(tmpdir(), \"yolont-gitleaks-\"));\n const sourceFile = join(dir, \"diff.patch\");\n const reportFile = join(dir, \"report.json\");\n\n try {\n await writeFile(sourceFile, diffText, \"utf8\");\n // YOLONT_GITLEAKS: a binary the local CLI downloaded (see local/setup/gitleaks.ts); else PATH.\n await execFileAsync(process.env.YOLONT_GITLEAKS || \"gitleaks\", [\n \"detect\",\n \"--no-git\",\n \"--source\",\n sourceFile,\n \"--report-format\",\n \"json\",\n \"--report-path\",\n reportFile,\n \"--exit-code\",\n \"0\",\n \"--redact\",\n ]);\n\n const raw = await readFile(reportFile, \"utf8\").catch(() => \"[]\");\n const entries: GitleaksReportEntry[] = raw.trim().length > 0 ? JSON.parse(raw) : [];\n const findings: SecretFinding[] = entries.map((e) => ({\n ruleId: e.RuleID ?? \"unknown-rule\",\n ...locateInDiff(diffText, e.StartLine ?? 0),\n description: e.Description ?? \"Potential secret detected\",\n }));\n\n return { score: findings.length === 0 ? 100 : 0, findings, scannerFailed: false };\n } catch (err) {\n // fail closed: if the scanner itself couldn't run, block the LLM call same as a real hit,\n // but keep it distinguishable so the comment doesn't tell a dev to \"rotate\" a secret that\n // was never actually found.\n return {\n score: 0,\n findings: [],\n scannerFailed: true,\n scannerError: (err as Error).message,\n };\n } finally {\n await rm(dir, { recursive: true, force: true });\n }\n}\n", "export interface DiffStats {\n added: number;\n deleted: number;\n files: number;\n}\n\nexport function computeDiffStats(diffText: string): DiffStats {\n let added = 0;\n let deleted = 0;\n let files = 0;\n for (const line of diffText.split(\"\\n\")) {\n if (line.startsWith(\"diff --git \")) files++;\n if (line.startsWith(\"+++\") || line.startsWith(\"---\")) continue;\n if (line.startsWith(\"+\")) added++;\n else if (line.startsWith(\"-\")) deleted++;\n }\n return { added, deleted, files };\n}\n\n/** 100 at or under maxLines, linearly down to 0 by 2x maxLines. */\nexport function scoreDiffSize(stats: DiffStats, maxLines: number): { score: number; note?: string } {\n const total = stats.added + stats.deleted;\n if (total <= maxLines) {\n return { score: 100 };\n }\n const over = total - maxLines;\n const score = Math.max(0, Math.round(100 - (over / maxLines) * 100));\n return { score, note: `Diff is ${total} lines (+${stats.added}/-${stats.deleted}), over the ${maxLines}-line guideline.` };\n}\n", "import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { computeDiffStats, type DiffStats } from \"./checks/diffSize.js\";\n\nconst execFileAsync = promisify(execFile);\n\nexport interface DiffResult {\n text: string;\n truncated: boolean;\n /** Paths of generated/vendored files stripped before the size limit was applied \u2014 see omitGeneratedFiles. */\n omittedFiles: string[];\n /** Size of the full (post-omission, pre-truncation) diff \u2014 truncation must not make a big MR look small to scoring. */\n stats: DiffStats;\n /** Every reviewed file path in the full (post-omission, pre-truncation) diff \u2014 zone matching must see files past the byte cut too. */\n files: string[];\n}\n\nexport class DiffError extends Error {}\n\n/** Cheap check so callers can skip straight to the GitLab-API diff fallback when there's no local checkout at all. */\nexport async function isInsideGitWorkTree(): Promise<boolean> {\n try {\n await execFileAsync(\"git\", [\"rev-parse\", \"--is-inside-work-tree\"]);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Full local `git diff` \u2014 not the GitLab diff API, which truncates per-file\n * independent of our own size limit.\n *\n * Prefers `CI_MERGE_REQUEST_DIFF_BASE_SHA` (GitLab's own merge-base for this\n * MR) diffed directly against HEAD: fetching that one specific commit avoids\n * depending on a branch ref existing locally or a depth guess containing the\n * actual merge base. Falls back to a three-dot diff against a freshly\n * fetched target branch if the base SHA is unavailable (older GitLab) or the\n * server rejects fetching by bare SHA.\n */\nexport async function getMrDiff(opts: { targetBranch: string; baseSha?: string }, maxBytes: number): Promise<DiffResult> {\n let stdout: string;\n\n if (opts.baseSha) {\n try {\n await execFileAsync(\"git\", [\"fetch\", \"--depth\", \"1\", \"origin\", opts.baseSha]);\n stdout = (await execFileAsync(\"git\", [\"diff\", opts.baseSha, \"HEAD\"], { maxBuffer: 1024 * 1024 * 50 })).stdout;\n return truncateDiff(stdout, maxBytes);\n } catch {\n // fall through to the target-branch fallback below\n }\n }\n\n try {\n await execFileAsync(\"git\", [\"fetch\", \"--depth\", \"50\", \"origin\", opts.targetBranch]);\n stdout = (\n await execFileAsync(\"git\", [\"diff\", `origin/${opts.targetBranch}...HEAD`], { maxBuffer: 1024 * 1024 * 50 })\n ).stdout;\n return truncateDiff(stdout, maxBytes);\n } catch (err) {\n throw new DiffError(`Could not compute the MR diff (tried base SHA and target branch fallback): ${(err as Error).message}`);\n }\n}\n\n// Lockfiles and codegen output: huge, low-signal for LLM/Jev review, and the first\n// thing to eat the byte budget on a \"huge file changes\" MR \u2014 stripped before size\n// truncation so the limit is spent on hand-written code instead.\nconst GENERATED_FILE_PATTERNS: RegExp[] = [\n /(^|\\/)pnpm-lock\\.ya?ml$/,\n /(^|\\/)package-lock\\.json$/,\n /(^|\\/)yarn\\.lock$/,\n /(^|\\/)Cargo\\.lock$/,\n /(^|\\/)poetry\\.lock$/,\n /(^|\\/)composer\\.lock$/,\n /(^|\\/)Gemfile\\.lock$/,\n /(^|\\/)go\\.sum$/,\n /(^|\\/)(generated|gen)\\//i,\n /\\.gen\\.(ts|tsx|js|py|go)$/,\n /(^|\\/)(swagger|openapi)\\.(json|ya?ml)$/i,\n];\n\nconst GENERATED_CONTENT_MARKERS = [\"@generated\", \"do not edit\", \"generated by orval\", \"automatically generated\", \"code generated\"];\n\n/** Strips diff blocks for generated/vendored files (lockfiles, orval/openapi clients, etc.) before review. */\nexport function omitGeneratedFiles(text: string): { text: string; omittedFiles: string[] } {\n const blocks = text.split(/(?=^diff --git )/m).filter((b) => b.length > 0);\n const kept: string[] = [];\n const omittedFiles: string[] = [];\n\n for (const block of blocks) {\n const path = extractFilePath(block);\n if (path && isGeneratedFile(path, block)) {\n omittedFiles.push(path);\n } else {\n kept.push(block);\n }\n }\n\n return { text: kept.join(\"\"), omittedFiles };\n}\n\nexport function listDiffFiles(text: string): string[] {\n return text\n .split(/(?=^diff --git )/m)\n .map(extractFilePath)\n .filter((p): p is string => p !== null);\n}\n\nfunction extractFilePath(block: string): string | null {\n return block.match(/^diff --git a\\/.+? b\\/(.+)$/m)?.[1] ?? null;\n}\n\nfunction isGeneratedFile(path: string, block: string): boolean {\n if (GENERATED_FILE_PATTERNS.some((re) => re.test(path))) return true;\n // Markers live in a generated file's header \u2014 scanning the first few lines of the\n // block is enough and avoids re-scanning multi-thousand-line hunks for no reason.\n const head = block.split(\"\\n\", 20).join(\"\\n\").toLowerCase();\n return GENERATED_CONTENT_MARKERS.some((marker) => head.includes(marker));\n}\n\n/**\n * GitLab's discussion-position API requires `old_line` in addition to `new_line` for any\n * comment on an unchanged (context) line \u2014 `new_line` alone only works for a line that was\n * actually added. A finding's line number is always in new-file numbering; this walks the\n * unified diff hunks for `filePath` to classify that line and return the position GitLab\n * will actually accept. Returns null if the line isn't part of the diff at all (LLM\n * hallucinated a location) \u2014 callers should skip posting rather than guess.\n */\nexport function resolveDiffPosition(diffText: string, filePath: string, newLine: number): { oldLine?: number; newLine: number } | null {\n const blocks = diffText.split(/(?=^diff --git )/m).filter((b) => b.length > 0);\n const block = blocks.find((b) => extractFilePath(b) === filePath);\n if (!block) return null;\n\n const lines = block.split(\"\\n\");\n let oldLineNum = 0;\n let newLineNum = 0;\n\n for (const line of lines) {\n const hunkHeader = line.match(/^@@ -(\\d+)(?:,\\d+)? \\+(\\d+)(?:,\\d+)? @@/);\n if (hunkHeader) {\n oldLineNum = Number(hunkHeader[1]);\n newLineNum = Number(hunkHeader[2]);\n continue;\n }\n if (oldLineNum === 0 && newLineNum === 0) continue; // before the first hunk (file headers)\n\n if (line.startsWith(\"+\")) {\n if (newLineNum === newLine) return { newLine };\n newLineNum++;\n } else if (line.startsWith(\"-\")) {\n oldLineNum++;\n } else if (line.startsWith(\" \")) {\n if (newLineNum === newLine) return { oldLine: oldLineNum, newLine };\n oldLineNum++;\n newLineNum++;\n }\n // lines like \"\\" affect neither counter\n }\n\n return null;\n}\n\n/**\n * The diff as the LLM sees it: every added (+) and unchanged line starts with its new-file\n * line number, removed (-) lines get a blank gutter. Models miscount when they have to\n * work line numbers out from the @@ headers, and a miscounted finding lands on the wrong line\n * of the PR (resolveDiffPosition only checks that the line is somewhere in the diff).\n */\nexport function numberDiffLines(diffText: string): string {\n let newLineNum = 0;\n let inHunk = false;\n const blank = \" \".repeat(6);\n return diffText\n .split(\"\\n\")\n .map((line) => {\n if (line.startsWith(\"diff --git \")) {\n inHunk = false;\n return line;\n }\n const hunkHeader = line.match(/^@@ -\\d+(?:,\\d+)? \\+(\\d+)(?:,\\d+)? @@/);\n if (hunkHeader) {\n newLineNum = Number(hunkHeader[1]);\n inHunk = true;\n return line;\n }\n if (!inHunk) return line;\n if (line.startsWith(\"+\") || line.startsWith(\" \")) return `${String(newLineNum++).padStart(5)} ${line}`;\n if (line.startsWith(\"-\") || line.startsWith(\"\\\\\")) return `${blank}${line}`;\n return line;\n })\n .join(\"\\n\");\n}\n\nexport function truncateDiff(text: string, maxBytes: number): DiffResult {\n const { text: filtered, omittedFiles } = omitGeneratedFiles(text);\n const stats = computeDiffStats(filtered);\n const files = listDiffFiles(filtered);\n if (Buffer.byteLength(filtered, \"utf8\") <= maxBytes) {\n return { text: filtered, truncated: false, omittedFiles, stats, files };\n }\n return { text: Buffer.from(filtered, \"utf8\").subarray(0, maxBytes).toString(\"utf8\"), truncated: true, omittedFiles, stats, files };\n}\n", "import { z } from \"zod\";\n\n/**\n * What kind of change a PR is. Two modes (config `changeType`, env ETHOS_CHANGE_TYPE in CI):\n * - \"label\": the review call also names the type; shown, saved, filterable. Review unchanged.\n * - \"steer\": the type is settled first (free hints, else one small LLM call; the TUI lets you\n * change it), then the review gets that type's checks.\n */\nexport const CHANGE_TYPES = [\"feature\", \"bugfix\", \"refactor\", \"performance\", \"tests\", \"docs\", \"chore\", \"ci\", \"revert\", \"mixed\"] as const;\nexport const ChangeTypeSchema = z.enum(CHANGE_TYPES);\nexport type ChangeType = z.infer<typeof ChangeTypeSchema>;\nexport type ChangeTypeMode = \"off\" | \"label\" | \"steer\";\n\nexport const CHANGE_TYPE_LABELS: Record<ChangeType, string> = {\n feature: \"Feature\",\n bugfix: \"Bug fix\",\n refactor: \"Refactor\",\n performance: \"Performance\",\n tests: \"Tests only\",\n docs: \"Docs\",\n chore: \"Chore / dependencies\",\n ci: \"CI / build / config\",\n revert: \"Revert\",\n mixed: \"Mixed\",\n};\n\nexport interface ChangeTypeGuess {\n type: ChangeType;\n reason: string;\n /** Where it came from: the title/branch/labels (free) or the LLM. */\n from: \"hint\" | \"llm\";\n}\n\n// Conventional-commit prefixes and common branch/label words.\nconst WORDS: [RegExp, ChangeType][] = [\n [/^(feat|feature|enhancement)$/, \"feature\"],\n [/^(fix|bugfix|hotfix|bug)$/, \"bugfix\"],\n [/^refactor(ing)?$/, \"refactor\"],\n [/^(perf|performance)$/, \"performance\"],\n [/^tests?$/, \"tests\"],\n [/^(docs?|documentation)$/, \"docs\"],\n [/^(chore|deps|dependencies|dependabot|renovate)$/, \"chore\"],\n [/^(ci|build)$/, \"ci\"],\n [/^revert$/, \"revert\"],\n];\nconst typeOfWord = (w: string) => WORDS.find(([re]) => re.test(w.toLowerCase()))?.[1];\n\n/** Free hints, no LLM: `fix(api): \u2026` titles, `feat/\u2026` branches, `type::bug` / `bug` labels. */\nexport function hintFromMr(mr: { title: string; sourceBranch?: string; labels?: string[] }): ChangeTypeGuess | null {\n if (/^revert\\b/i.test(mr.title)) return { type: \"revert\", reason: \"title starts with Revert\", from: \"hint\" };\n const m = mr.title.match(/^(?:draft:\\s*)?([a-z]+)(?:\\(([^)]*)\\))?!?:/i);\n const prefix = m?.[1];\n // `build(deps):` / `chore(deps):` are dependency bumps whatever the word.\n const byTitle = m?.[2]?.toLowerCase() === \"deps\" ? \"chore\" : prefix && typeOfWord(prefix);\n if (byTitle) return { type: byTitle, reason: `title prefix \"${prefix}:\"`, from: \"hint\" };\n const branch = mr.sourceBranch?.split(\"/\")[0];\n const byBranch = branch && mr.sourceBranch!.includes(\"/\") ? typeOfWord(branch) : undefined;\n if (byBranch) return { type: byBranch, reason: `branch ${mr.sourceBranch}`, from: \"hint\" };\n for (const label of mr.labels ?? []) {\n const t = typeOfWord(label.replace(/^type::?\\s*/i, \"\"));\n if (t) return { type: t, reason: `label \"${label}\"`, from: \"hint\" };\n }\n return null;\n}\n\n/** Steer mode only: one small call on the title, file list and the diff's start. */\nexport async function classifyChange(complete: (prompt: string) => Promise<string>, mr: { title: string; description?: string }, diff: string, files: string[]): Promise<ChangeTypeGuess> {\n const prompt = `Classify this merge request as exactly one of: ${CHANGE_TYPES.join(\", \")}.\n\"mixed\" only when it clearly does two unrelated kinds of work. Answer with JSON only: {\"type\": \"...\", \"reason\": \"one short sentence\"}.\n\nTitle: ${mr.title}\nDescription: ${(mr.description ?? \"\").slice(0, 1500)}\nChanged files (${files.length}): ${files.slice(0, 80).join(\", \")}\n\nDiff (start):\n${diff.slice(0, 6000)}`;\n const raw = await complete(prompt);\n const json = raw.match(/\\{[\\s\\S]*\\}/)?.[0];\n const parsed = z.object({ type: ChangeTypeSchema, reason: z.string() }).safeParse(json ? JSON.parse(json) : null);\n if (!parsed.success) throw new Error(`couldn't read a change type from: ${raw.slice(0, 200)}`);\n return { ...parsed.data, from: \"llm\" };\n}\n\n// The types whose checks are lighter. The author controls the title, branch, labels and\n// description, so they only count when every changed file fits: a \"docs:\" PR that edits\n// src/payment.ts must not get a docs-only review (that would be a way around the gate).\nconst LIGHTER: Partial<Record<ChangeType, RegExp>> = {\n docs: /(\\.(md|mdx|rst|adoc|txt)$|(^|\\/)docs?\\/)/i,\n tests: /((^|\\/)(tests?|__tests__|specs?)\\/|\\.(test|spec)\\.[a-z0-9]+$|_test\\.(go|py)$)/i,\n chore: /(^|\\/)(package(-lock)?\\.json|pnpm-lock\\.yaml|yarn\\.lock|bun\\.lockb|go\\.(mod|sum)|Cargo\\.(toml|lock)|requirements[^/]*\\.txt|poetry\\.lock|pyproject\\.toml|Gemfile(\\.lock)?|composer\\.(json|lock)|\\.npmrc|\\.nvmrc|renovate\\.json|\\.github\\/dependabot\\.ya?ml)$/i,\n ci: /((^|\\/)\\.github\\/workflows\\/|(^|\\/)\\.gitlab-ci|(^|\\/)\\.circleci\\/|(^|\\/)Dockerfile|(^|\\/)docker-compose|(^|\\/)Jenkinsfile|(^|\\/)Makefile$|(^|\\/)\\.dockerignore$)/i,\n};\nexport const fitsFiles = (type: ChangeType, files: string[]) => !LIGHTER[type] || (files.length > 0 && files.every((f) => LIGHTER[type]!.test(f)));\n\n/**\n * Steer mode's guess: free hints first, else the classifier; null when the LLM call fails (the\n * review goes on without a type). A lighter type the files don't back up is never used.\n */\nexport async function guessForSteer(complete: (prompt: string) => Promise<string>, mr: { title: string; description?: string; sourceBranch?: string; labels?: string[] }, diff: string, files: string[]): Promise<ChangeTypeGuess | null> {\n const hint = hintFromMr(mr);\n if (hint && fitsFiles(hint.type, files)) return hint;\n const guess = await classifyChange(complete, mr, diff, files).catch(() => null);\n if (guess && !fitsFiles(guess.type, files)) return { type: \"mixed\", reason: `called ${guess.type}, but it changes other files too`, from: \"llm\" };\n return guess;\n}\n\n/** `off` | `label` | `steer`; anything else falls back to label. */\nexport const parseChangeTypeMode = (v: string | undefined): ChangeTypeMode => (v === \"off\" || v === \"steer\" ? v : \"label\");\n\n/** Steer mode: what the reviewer should check for each type. */\nexport const CHANGE_TYPE_CHECKS: Record<ChangeType, string> = {\n feature: \"New behavior: check it has tests for the main path and edge cases (empty, error, limits), docs or comments where users meet it, and no unrelated changes riding along.\",\n bugfix: \"A fix: check it addresses the root cause rather than the symptom, that a regression test reproduces the bug, and that the fix doesn't change unrelated behavior.\",\n refactor: \"Should not change behavior: flag anything that does (changed conditions, defaults, error handling, public signatures, ordering). Existing tests should pass unchanged; flag tests that were edited to pass.\",\n performance: \"Ask for evidence (a benchmark, a measurement, or clear reasoning about complexity), and check the faster path keeps results, errors and edge cases identical.\",\n tests: \"Tests only: check they assert real behavior (not implementation details), would fail if the code broke, and aren't flaky (timing, order, network). Don't penalize missing tests.\",\n docs: \"Docs: check accuracy against the code, broken links and examples that wouldn't run. Lighter review; don't penalize missing tests.\",\n chore: \"Chore / dependencies: check version bumps for breaking changes and lockfile consistency, and that nothing functional is hidden inside. Lighter review.\",\n ci: \"CI / build / config: check secrets aren't exposed, jobs still gate what they should, and caching or conditions don't silently skip steps.\",\n revert: \"A revert: check it cleanly undoes the named change and nothing else, and whether anything since depends on what's being removed.\",\n mixed: \"Mixed changes: review each part by its own kind, and note that splitting it into separate PRs would make it easier to review.\",\n};\n\nexport function changeTypePromptSection(mode: { steer?: ChangeType; ask?: boolean }): string {\n if (mode.steer) return `Change type (confirmed by the reviewer): ${mode.steer}.\\n${CHANGE_TYPE_CHECKS[mode.steer]}\\n\\n`;\n if (mode.ask) return `Also fill change_type: what kind of change this is (one of ${CHANGE_TYPES.join(\", \")}), with a one-sentence reason. It doesn't affect scores.\\n\\n`;\n return \"\";\n}\n\n/** For the review comment: \"Type: Refactor (title prefix \"refactor:\")\". */\nexport const describeChangeType = (t: ChangeType, reason?: string) => `${CHANGE_TYPE_LABELS[t]}${reason ? ` (${reason})` : \"\"}`;\n", "import { readFileSync } from \"node:fs\";\nimport yaml from \"js-yaml\";\nimport { RubricSchema, type Rubric } from \"./schema.js\";\n\nexport class RubricError extends Error {}\n\nexport function loadRubric(path: string): Rubric {\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch (err) {\n throw new RubricError(`Could not read rubric file at '${path}': ${(err as Error).message}`);\n }\n\n let parsed: unknown;\n try {\n parsed = yaml.load(raw);\n } catch (err) {\n throw new RubricError(`Rubric file at '${path}' is not valid YAML: ${(err as Error).message}`);\n }\n\n const result = RubricSchema.safeParse(parsed);\n if (!result.success) {\n const messages = result.error.issues.map((issue) => `- ${issue.path.join(\".\")}: ${issue.message}`);\n throw new RubricError(`Rubric file at '${path}' is invalid:\\n${messages.join(\"\\n\")}`);\n }\n\n return result.data;\n}\n", "import { readFileSync } from \"node:fs\";\nimport yaml from \"js-yaml\";\nimport { z } from \"zod\";\nimport type { ZoneVerdict } from \"../llm/schema.js\";\n\n/**\n * Zones: parts of a project rated by how costly a mistake there is \u2014\n * red = runs on every start/request/render or is hard to undo, green = rarely runs. Matching changed files to\n * zones is done here in code; the LLM only gives a verdict on the zones that matched.\n */\n\nexport const ZoneLevelSchema = z.enum([\"red\", \"amber\", \"green\"]);\n\nexport const ZoneSchema = z.object({\n id: z.string().regex(/^[a-z0-9][a-z0-9-]*$/, \"use lowercase-kebab-case\"),\n level: ZoneLevelSchema,\n paths: z.array(z.string().min(1)).min(1),\n why: z.string(),\n watch_for: z.array(z.string()).default([]),\n budget: z.string().optional(),\n});\n\nexport const ZonesFileSchema = z.object({\n zones: z.array(ZoneSchema).superRefine((zones, ctx) => {\n const seen = new Set<string>();\n zones.forEach((zone, i) => {\n if (seen.has(zone.id)) ctx.addIssue({ code: z.ZodIssueCode.custom, path: [i, \"id\"], message: `duplicate zone id '${zone.id}'` });\n seen.add(zone.id);\n });\n }),\n});\n\nexport type ZoneLevel = z.infer<typeof ZoneLevelSchema>;\nexport type Zone = z.infer<typeof ZoneSchema>;\n\nexport interface ZoneHit {\n zone: Zone;\n files: string[];\n /** Subset of `files` that matched only because a red zone imports them (zones graph), not by path. */\n viaImport?: string[];\n /** Past reviewer votes on this zone's verdicts in the same project (local memory only). */\n feedback?: string[];\n}\n\n/** What a review carries about zones \u2014 every zone of the project (for the map) plus what this diff touched. */\nexport interface ZoneReport {\n zones: Zone[];\n hits: ZoneHit[];\n verdicts: ZoneVerdict[];\n}\n\nexport class ZonesError extends Error {}\n\nconst LEVEL_RANK: Record<ZoneLevel, number> = { red: 0, amber: 1, green: 2 };\n\n/** Missing file = zones are simply off for this project (null), not an error. */\nexport function loadZones(path: string): Zone[] | null {\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw new ZonesError(`Could not read zones file at '${path}': ${(err as Error).message}`);\n }\n return parseZones(raw, `Zones file at '${path}'`);\n}\n\n/** Validates zones YAML from a string (editor output, generated drafts). Throws ZonesError. */\nexport function parseZones(raw: string, label = \"Zones file\"): Zone[] {\n let parsed: unknown;\n try {\n parsed = yaml.load(raw);\n } catch (err) {\n throw new ZonesError(`${label} is not valid YAML: ${(err as Error).message}`);\n }\n\n const result = ZonesFileSchema.safeParse(parsed);\n if (!result.success) {\n const messages = result.error.issues.map((issue) => `- ${issue.path.join(\".\")}: ${issue.message}`);\n throw new ZonesError(`${label} is invalid:\\n${messages.join(\"\\n\")}`);\n }\n return result.data.zones;\n}\n\n/** Minimal glob: `**` spans directories, `*` and `?` stay within one path segment. No braces/classes \u2014 list several paths instead. */\nexport function globToRegExp(glob: string): RegExp {\n let re = \"\";\n for (let i = 0; i < glob.length; i++) {\n const ch = glob[i]!;\n if (ch === \"*\" && glob[i + 1] === \"*\") {\n const slashAfter = glob[i + 2] === \"/\";\n re += slashAfter ? \"(?:.*/)?\" : \".*\";\n i += slashAfter ? 2 : 1;\n } else if (ch === \"*\") {\n re += \"[^/]*\";\n } else if (ch === \"?\") {\n re += \"[^/]\";\n } else {\n re += ch.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\");\n }\n }\n return new RegExp(`^${re}$`);\n}\n\n/**\n * Every zone a file falls into is recorded (overlaps allowed); hits are sorted most severe\n * first. With a zones graph, a file a zone transitively imports counts as in that zone too\n * \u2014 catches a \"green\" file that a red one pulls into first load.\n */\nexport function matchZones(zones: Zone[], files: string[], graph?: ZoneGraph | null): ZoneHit[] {\n const hits: ZoneHit[] = [];\n for (const zone of zones) {\n const patterns = zone.paths.map(globToRegExp);\n const direct = files.filter((f) => patterns.some((re) => re.test(f)));\n const reachable = new Set(graph?.reachable[zone.id] ?? []);\n const viaImport = files.filter((f) => reachable.has(f) && !direct.includes(f));\n if (direct.length + viaImport.length === 0) continue;\n hits.push({ zone, files: [...direct, ...viaImport], ...(viaImport.length > 0 && { viaImport }) });\n }\n return hits.sort((a, b) => LEVEL_RANK[a.zone.level] - LEVEL_RANK[b.zone.level]);\n}\n\n/** Offline-generated import reachability (local `yolont zones graph`): zone id \u2192 repo files its files transitively import. */\nexport const ZoneGraphSchema = z.object({\n generated_at: z.string(),\n sha: z.string().nullable(),\n reachable: z.record(z.array(z.string())),\n});\nexport type ZoneGraph = z.infer<typeof ZoneGraphSchema>;\n\n/** Missing = path-only matching. Invalid throws ZonesError, which callers already treat as \"log, continue without zones\". */\nexport function loadZoneGraph(path: string): ZoneGraph | null {\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw new ZonesError(`Could not read zones graph at '${path}': ${(err as Error).message}`);\n }\n const result = ZoneGraphSchema.safeParse(JSON.parse(raw));\n if (!result.success) throw new ZonesError(`Zones graph at '${path}' is invalid: ${result.error.message}`);\n return result.data;\n}\n\n// Device variants (e.g. Foo.mobile.tsx / Foo.desktop.tsx / Foo.ssr.tsx) are one module\n// at build time; TS resolution only ever picks one suffix, so the walk treats siblings as one.\nconst VARIANT_SUFFIX = /\\.(mobile|desktop|ssr)(?=\\.[cm]?[jt]sx?$)/;\n\n/**\n * Pure part of graph generation: BFS from each red zone's own files through the import\n * graph (madge `.obj()` shape: file \u2192 files it imports), minus the zone's own files.\n * Only red zones \u2014 \"imported by first-load code\" is what the graph is for; doing it for\n * amber would paint every shared util amber and drown the signal.\n */\nexport function computeReachable(zones: Zone[], repoFiles: string[], imports: Record<string, string[]>): Record<string, string[]> {\n const siblings = new Map<string, string[]>();\n for (const f of repoFiles) {\n const key = f.replace(VARIANT_SUFFIX, \"\");\n siblings.set(key, [...(siblings.get(key) ?? []), f]);\n }\n const variantsOf = (f: string) => siblings.get(f.replace(VARIANT_SUFFIX, \"\")) ?? [f];\n\n const reachable: Record<string, string[]> = {};\n for (const hit of matchZones(zones.filter((z) => z.level === \"red\"), repoFiles)) {\n const own = new Set(hit.files);\n const seen = new Set<string>(hit.files.flatMap(variantsOf));\n const queue = [...seen];\n while (queue.length > 0) {\n for (const dep of imports[queue.pop()!] ?? []) {\n for (const v of variantsOf(dep)) {\n if (seen.has(v)) continue;\n seen.add(v);\n queue.push(v);\n }\n }\n }\n reachable[hit.zone.id] = [...seen].filter((f) => !own.has(f)).sort();\n }\n return reachable;\n}\n\n/** Drops verdicts for zones that weren't in the prompt \u2014 the schema enum is a hint, not a guarantee. */\nexport function keepKnownVerdicts(verdicts: ZoneVerdict[] | undefined, hits: ZoneHit[]): ZoneVerdict[] {\n const ids = new Set(hits.map((h) => h.zone.id));\n return (verdicts ?? []).filter((v) => ids.has(v.zone_id));\n}\n\nconst LEVEL_STYLE: Record<ZoneLevel, string> = {\n red: \"fill:#fde2e2,stroke:#c62828,color:#000\",\n amber: \"fill:#fff3cd,stroke:#b8860b,color:#000\",\n green: \"fill:#e3f5e1,stroke:#2e7d32,color:#000\",\n};\n\n/**\n * Mermaid map of the project's zones, grouped by level. With `hits`, touched zones are\n * bold with their changed-file count and untouched ones are faded \u2014 the per-review view.\n * Without, it's the plain project map. GitLab renders ```mermaid blocks natively.\n */\nexport function renderZonesMermaid(zones: Zone[], hits?: ZoneHit[]): string {\n const touched = new Map(hits?.map((h) => [h.zone.id, h.files.length]));\n const lines = [\"```mermaid\", \"flowchart LR\"];\n for (const level of ZoneLevelSchema.options) {\n const inLevel = zones.filter((z) => z.level === level);\n if (inLevel.length === 0) continue;\n lines.push(` subgraph lvl_${level}[\"${level.toUpperCase()}\"]`);\n for (const zone of inLevel) {\n const count = touched.get(zone.id);\n const label = count ? `${zone.id} \u00B7 ${count} file(s)` : zone.id;\n lines.push(` ${nodeId(zone.id)}[\"${label}\"]:::${level}${hits && !count ? \"Faded\" : \"\"}`);\n }\n lines.push(\" end\");\n }\n for (const level of ZoneLevelSchema.options) {\n lines.push(` classDef ${level} ${LEVEL_STYLE[level]},stroke-width:3px`);\n lines.push(` classDef ${level}Faded ${LEVEL_STYLE[level]},opacity:0.35`);\n }\n lines.push(\"```\");\n return lines.join(\"\\n\");\n}\n\n// Mermaid node ids can't contain '-' reliably in every renderer version.\nfunction nodeId(zoneId: string): string {\n return `z_${zoneId.replace(/-/g, \"_\")}`;\n}\n", "// Stable contract, not branding: existing MR/PR comments are found (and updated, and mined for\n// author history) by this exact string. Renaming it would orphan every past comment.\nexport const PR_SCORE_MARKER = \"<!-- pr-score:v1 -->\";\n\n/** Added to an MR/PR once a score is posted, so the forge's list can filter reviewed vs not. */\nexport const PR_SCORE_LABEL = \"llm-reviewed\";\n\nexport type ForgeType = \"gitlab\" | \"github\";\n\n/** GitLab: numeric id or \"group/sub/project\". GitHub: numeric repo id or \"owner/repo\". */\nexport type ProjectRef = number | string;\n\nexport interface MrMetadata {\n projectId: ProjectRef;\n iid: number;\n title: string;\n description: string;\n authorUsername: string;\n draft: boolean;\n labels: string[];\n targetBranch: string;\n sourceBranch: string;\n sha: string;\n webUrl: string;\n diffRefs: { baseSha: string; startSha: string; headSha: string };\n}\n\nexport interface JobSummary {\n name: string;\n /** Normalized: \"success\" | \"failed\" | anything else (= not conclusive). */\n status: string;\n coverage: number | null;\n}\n\nexport interface PastMrNote {\n mrIid: number;\n body: string;\n createdAt: string;\n}\n\nexport interface ProjectMrSummary {\n iid: number;\n authorUsername: string;\n sha: string;\n title: string;\n mergedAt: string | null;\n}\n\nexport interface DiscussionComment {\n id: number;\n authorUsername: string;\n body: string;\n system: boolean;\n createdAt: string;\n file?: string;\n line?: number;\n}\n\nexport interface ForgeProject {\n /** Numeric forge id \u2014 what the DB stores as forge_project_id. */\n id: number;\n pathWithNamespace: string;\n name: string;\n /** Project home page, for file links in comments. */\n webUrl: string;\n defaultBranch: string;\n}\n\nexport interface FindingPosition {\n baseSha: string;\n startSha: string;\n headSha: string;\n filePath: string;\n /** New-file line (see resolveDiffPosition). */\n line: number;\n /** Set for an unchanged context line \u2014 GitLab needs it, GitHub ignores it. */\n oldLine?: number;\n}\n\n/** One git host. GitLab \"MR iid\" and GitHub \"PR number\" are both `mrIid` here. */\nexport interface ForgeClient {\n readonly type: ForgeType;\n /** Web host (\"github.com\", \"git.example.com:8443\") \u2014 the identity key, never the API host. */\n readonly host: string;\n getMergeRequest(project: ProjectRef, mrIid: number): Promise<MrMetadata>;\n upsertPrScoreNote(project: ProjectRef, mrIid: number, body: string): Promise<void>;\n markReviewed(project: ProjectRef, mrIid: number): Promise<boolean>;\n listPrScoreNotes(project: ProjectRef, mrIid: number): Promise<PastMrNote[]>;\n /** `within`: limit to this project where the forge's search would otherwise span every repo. */\n listAuthorMergeRequests(authorUsername: string, limit?: number, within?: ProjectRef): Promise<{ projectId: ProjectRef; iid: number }[]>;\n listPipelineJobs(project: ProjectRef, pipelineId: number): Promise<JobSummary[]>;\n getTestReportSummary(project: ProjectRef, pipelineId: number): Promise<{ total: number; success: number } | null>;\n getMrDiffText(project: ProjectRef, mrIid: number): Promise<string>;\n listProjectMergeRequests(project: ProjectRef, opts?: { state?: \"merged\" | \"opened\" | \"closed\" | \"all\"; maxPages?: number }): Promise<ProjectMrSummary[]>;\n listMrDiscussions(project: ProjectRef, mrIid: number): Promise<DiscussionComment[]>;\n postFindingDiscussion(project: ProjectRef, mrIid: number, body: string, position?: FindingPosition): Promise<{ discussionId: string; noteId: number }>;\n upsertDiscussionReply(project: ProjectRef, mrIid: number, discussionId: string, body: string, noteId?: number | null): Promise<number>;\n deleteDiscussionReply(project: ProjectRef, mrIid: number, discussionId: string, noteId: number): Promise<void>;\n resolveDiscussion(project: ProjectRef, mrIid: number, discussionId: string, resolved: boolean): Promise<void>;\n listMrDiscussionThreads(project: ProjectRef, mrIid: number): Promise<{ discussionId: string; notes: DiscussionComment[] }[]>;\n getCurrentUser(): Promise<{ username: string; id: number }>;\n getProject(project: ProjectRef): Promise<ForgeProject>;\n /** Every file path at `ref` (blobs only). May be partial on huge repos. */\n listFiles(project: ProjectRef, ref: string): Promise<string[]>;\n /** File content at `ref`, or null if missing. */\n readFile(project: ProjectRef, path: string, ref: string): Promise<string | null>;\n /** The open MR/PR from `sourceBranch`: updates its description, or opens one. */\n openOrUpdateChangeRequest(project: ProjectRef, opts: { sourceBranch: string; targetBranch: string; title: string; description: string }): Promise<{ url: string; created: boolean }>;\n}\n\n/** \"MR !12\" / \"PR #12\" \u2014 for user-facing text. */\nexport function changeLabel(type: ForgeType, n: number): string {\n return type === \"github\" ? `PR #${n}` : `MR !${n}`;\n}\n", "import type { DiscussionComment, FindingPosition, ForgeClient, ForgeProject, JobSummary, MrMetadata, PastMrNote, ProjectMrSummary, ProjectRef } from \"./types.js\";\nimport { PR_SCORE_LABEL, PR_SCORE_MARKER } from \"./types.js\";\n\n/** Thrown for a non-2xx GitHub response; `status` lets callers treat 404 as \"gone\". */\nexport class GitHubError extends Error {\n constructor(\n message: string,\n readonly status: number,\n ) {\n super(message);\n }\n}\n\ninterface GhUser {\n login: string;\n id: number;\n type?: string;\n}\ninterface GhComment {\n id: number;\n node_id: string;\n body: string;\n user: GhUser | null;\n author_association?: string;\n created_at: string;\n path?: string;\n line?: number | null;\n original_line?: number | null;\n in_reply_to_id?: number;\n}\ninterface GhPull {\n number: number;\n title: string;\n body: string | null;\n user: GhUser | null;\n draft?: boolean;\n labels: { name: string }[];\n base: { ref: string; sha: string };\n head: { ref: string; sha: string };\n html_url: string;\n merged_at: string | null;\n}\ninterface GhRepo {\n id: number;\n full_name: string;\n name: string;\n html_url: string;\n default_branch: string;\n}\n\n/**\n * GitHub / GitHub Enterprise over plain fetch (REST + one GraphQL call for resolving threads,\n * which REST can't do). A GitLab \"discussion\" maps to a PR review-comment thread: discussionId\n * is the root review comment's id, replies hang off it.\n */\nexport class GitHubForge implements ForgeClient {\n readonly type = \"github\" as const;\n readonly host: string;\n private readonly api: string;\n private readonly graphqlUrl: string;\n private readonly token: string;\n private readonly fetchImpl: typeof fetch;\n private readonly repoNames = new Map<number, string>();\n\n /** `host`: the web host (\"github.com\" or a GHE host). `fetch` is injectable for tests. */\n constructor(opts: { host?: string; token: string; fetch?: typeof fetch }) {\n this.host = (opts.host ?? \"github.com\").toLowerCase();\n const dotCom = this.host === \"github.com\";\n this.api = dotCom ? \"https://api.github.com\" : `https://${this.host}/api/v3`;\n this.graphqlUrl = dotCom ? \"https://api.github.com/graphql\" : `https://${this.host}/api/graphql`;\n this.token = opts.token;\n this.fetchImpl = opts.fetch ?? fetch;\n }\n\n // ---- http ----\n\n private async request(method: string, pathOrUrl: string, body?: unknown, accept = \"application/vnd.github+json\"): Promise<Response> {\n const res = await this.fetchImpl(pathOrUrl.startsWith(\"http\") ? pathOrUrl : `${this.api}${pathOrUrl}`, {\n method,\n headers: {\n Authorization: `Bearer ${this.token}`,\n Accept: accept,\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n \"User-Agent\": \"yolont\",\n ...(body !== undefined && { \"Content-Type\": \"application/json\" }),\n },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n });\n if (!res.ok) {\n const detail = await res.text().catch(() => \"\");\n throw new GitHubError(`GitHub ${method} ${pathOrUrl} \u2192 ${res.status}${detail ? `: ${detail.slice(0, 300)}` : \"\"}`, res.status);\n }\n return res;\n }\n\n private async json<T>(method: string, path: string, body?: unknown): Promise<T> {\n const res = await this.request(method, path, body);\n return (res.status === 204 ? undefined : await res.json()) as T;\n }\n\n /** Follows `Link: rel=\"next\"` \u2014 the default page is 30, and marker lookups must see every comment. */\n private async paginate<T>(path: string, maxPages = Infinity): Promise<T[]> {\n const out: T[] = [];\n let url: string | undefined = `${path}${path.includes(\"?\") ? \"&\" : \"?\"}per_page=100`;\n for (let page = 0; url && page < maxPages; page++) {\n const res = await this.request(\"GET\", url);\n const data = (await res.json()) as T[] | { jobs: T[] };\n out.push(...(Array.isArray(data) ? data : data.jobs));\n url = res.headers.get(\"link\")?.match(/<([^>]+)>;\\s*rel=\"next\"/)?.[1];\n }\n return out;\n }\n\n /** \"owner/repo\" for API paths; a numeric id (what the DB stores) is resolved once and cached. */\n private async repo(project: ProjectRef): Promise<string> {\n if (typeof project === \"string\" && !/^\\d+$/.test(project)) return project;\n const id = Number(project);\n let name = this.repoNames.get(id);\n if (!name) {\n name = (await this.json<GhRepo>(\"GET\", `/repositories/${id}`)).full_name;\n this.repoNames.set(id, name);\n }\n return name;\n }\n\n private static comment(c: GhComment): DiscussionComment {\n const line = c.line ?? c.original_line ?? undefined;\n return { id: c.id, authorUsername: c.user?.login ?? \"unknown\", body: c.body ?? \"\", system: false, createdAt: c.created_at, file: c.path, line };\n }\n\n // ---- ForgeClient ----\n\n async getMergeRequest(project: ProjectRef, mrIid: number): Promise<MrMetadata> {\n const pr = await this.json<GhPull>(\"GET\", `/repos/${await this.repo(project)}/pulls/${mrIid}`);\n return {\n projectId: project,\n iid: mrIid,\n title: pr.title ?? \"\",\n description: pr.body ?? \"\",\n authorUsername: pr.user?.login ?? \"unknown\",\n draft: Boolean(pr.draft),\n labels: pr.labels.map((l) => l.name),\n targetBranch: pr.base.ref,\n sourceBranch: pr.head.ref,\n sha: pr.head.sha,\n webUrl: pr.html_url,\n diffRefs: { baseSha: pr.base.sha, startSha: pr.base.sha, headSha: pr.head.sha },\n };\n }\n\n private async issueComments(project: ProjectRef, n: number): Promise<GhComment[]> {\n return this.paginate<GhComment>(`/repos/${await this.repo(project)}/issues/${n}/comments`);\n }\n\n /** Score comments carrying the marker, ignoring ones anybody could have pasted it into. */\n private async scoreComments(project: ProjectRef, n: number): Promise<GhComment[]> {\n return (await this.issueComments(project, n)).filter((c) => c.body?.includes(PR_SCORE_MARKER) && isTrustedCommenter(c));\n }\n\n async upsertPrScoreNote(project: ProjectRef, mrIid: number, body: string): Promise<void> {\n const repo = await this.repo(project);\n const existing = (await this.scoreComments(repo, mrIid))[0];\n if (existing) await this.json(\"PATCH\", `/repos/${repo}/issues/comments/${existing.id}`, { body });\n else await this.json(\"POST\", `/repos/${repo}/issues/${mrIid}/comments`, { body });\n }\n\n async markReviewed(project: ProjectRef, mrIid: number): Promise<boolean> {\n try {\n await this.json(\"POST\", `/repos/${await this.repo(project)}/issues/${mrIid}/labels`, { labels: [PR_SCORE_LABEL] });\n return true;\n } catch (err) {\n console.warn(`[yolont] could not add '${PR_SCORE_LABEL}' label: ${(err as Error).message}`);\n return false;\n }\n }\n\n async listPrScoreNotes(project: ProjectRef, mrIid: number): Promise<PastMrNote[]> {\n return (await this.scoreComments(project, mrIid)).map((c) => ({ mrIid, body: c.body, createdAt: c.created_at }));\n }\n\n async listAuthorMergeRequests(authorUsername: string, limit = 20, within?: ProjectRef): Promise<{ projectId: ProjectRef; iid: number }[]> {\n // Without `within` this searches every repo the token can see \u2014 fine for a user's PAT, but in\n // CI it should stay on the reviewed repo.\n const scope = within === undefined ? \"\" : ` repo:${await this.repo(within)}`;\n const q = encodeURIComponent(`type:pr author:${authorUsername} is:merged${scope}`);\n const res = await this.json<{ items: { number: number; repository_url: string }[] }>(\"GET\", `/search/issues?q=${q}&sort=updated&order=desc&per_page=${Math.min(limit, 100)}`);\n return res.items.map((i) => ({ projectId: i.repository_url.replace(/^.*\\/repos\\//, \"\"), iid: i.number }));\n }\n\n /** `pipelineId` is an Actions workflow run id. Best-effort, like GitLab's. */\n async listPipelineJobs(project: ProjectRef, pipelineId: number): Promise<JobSummary[]> {\n try {\n const jobs = await this.paginate<{ name: string; status: string; conclusion: string | null }>(`/repos/${await this.repo(project)}/actions/runs/${pipelineId}/jobs`);\n return jobs.map((j) => ({ name: j.name, status: normalizeConclusion(j.status, j.conclusion), coverage: null }));\n } catch {\n return [];\n }\n }\n\n /** GitHub has no pipeline test-report API \u2014 the category is excluded, as for a GitLab pipeline without one. */\n async getTestReportSummary(): Promise<null> {\n return null;\n }\n\n async getMrDiffText(project: ProjectRef, mrIid: number): Promise<string> {\n return (await this.request(\"GET\", `/repos/${await this.repo(project)}/pulls/${mrIid}`, undefined, \"application/vnd.github.diff\")).text();\n }\n\n async listProjectMergeRequests(project: ProjectRef, opts: { state?: \"merged\" | \"opened\" | \"closed\" | \"all\"; maxPages?: number } = {}): Promise<ProjectMrSummary[]> {\n const state = opts.state === \"opened\" ? \"open\" : opts.state === \"merged\" || opts.state === \"closed\" ? \"closed\" : \"all\";\n const pulls = await this.paginate<GhPull>(`/repos/${await this.repo(project)}/pulls?state=${state}&sort=updated&direction=desc`, opts.maxPages);\n return pulls\n .filter((p) => (opts.state === \"merged\" ? p.merged_at !== null : opts.state === \"closed\" ? p.merged_at === null : true))\n .map((p) => ({ iid: p.number, authorUsername: p.user?.login ?? \"unknown\", sha: p.head.sha, title: p.title ?? \"\", mergedAt: p.merged_at }));\n }\n\n async listMrDiscussions(project: ProjectRef, mrIid: number): Promise<DiscussionComment[]> {\n const repo = await this.repo(project);\n const [review, issue] = await Promise.all([this.paginate<GhComment>(`/repos/${repo}/pulls/${mrIid}/comments`), this.issueComments(repo, mrIid)]);\n return [...review, ...issue].map(GitHubForge.comment);\n }\n\n async postFindingDiscussion(project: ProjectRef, mrIid: number, body: string, position?: FindingPosition): Promise<{ discussionId: string; noteId: number }> {\n // GitHub issue comments aren't threads (no reply/resolve), so there's nothing honest to map a position-less finding to.\n if (!position) throw new Error(\"GitHub finding threads need a file/line position\");\n const c = await this.json<GhComment>(\"POST\", `/repos/${await this.repo(project)}/pulls/${mrIid}/comments`, {\n body,\n commit_id: position.headSha,\n path: position.filePath,\n line: position.line,\n side: \"RIGHT\",\n });\n return { discussionId: String(c.id), noteId: c.id };\n }\n\n async upsertDiscussionReply(project: ProjectRef, mrIid: number, discussionId: string, body: string, noteId?: number | null): Promise<number> {\n const repo = await this.repo(project);\n if (noteId != null) {\n try {\n await this.json(\"PATCH\", `/repos/${repo}/pulls/comments/${noteId}`, { body });\n return noteId;\n } catch (err) {\n if ((err as GitHubError).status !== 404) throw err;\n }\n }\n return (await this.json<GhComment>(\"POST\", `/repos/${repo}/pulls/${mrIid}/comments/${discussionId}/replies`, { body })).id;\n }\n\n async deleteDiscussionReply(project: ProjectRef, _mrIid: number, _discussionId: string, noteId: number): Promise<void> {\n try {\n await this.json(\"DELETE\", `/repos/${await this.repo(project)}/pulls/comments/${noteId}`);\n } catch (err) {\n if ((err as GitHubError).status !== 404) throw err;\n }\n }\n\n /** REST can't resolve review threads; find the thread whose first comment is our root (by node id) and use GraphQL. */\n async resolveDiscussion(project: ProjectRef, mrIid: number, discussionId: string, resolved: boolean): Promise<void> {\n const repo = await this.repo(project);\n const root = await this.json<GhComment>(\"GET\", `/repos/${repo}/pulls/comments/${discussionId}`);\n const [owner, name] = repo.split(\"/\");\n let after: string | null = null;\n let threadId: string | undefined;\n do {\n type Page = { repository: { pullRequest: { reviewThreads: { pageInfo: { hasNextPage: boolean; endCursor: string | null }; nodes: { id: string; comments: { nodes: { id: string }[] } }[] } } } };\n const data: Page = await this.graphql<Page>(\n `query($owner:String!,$name:String!,$n:Int!,$after:String){repository(owner:$owner,name:$name){pullRequest(number:$n){reviewThreads(first:100,after:$after){pageInfo{hasNextPage endCursor}nodes{id comments(first:1){nodes{id}}}}}}}`,\n { owner, name, n: mrIid, after },\n );\n const threads = data.repository.pullRequest.reviewThreads;\n threadId = threads.nodes.find((t) => t.comments.nodes[0]?.id === root.node_id)?.id;\n after = threads.pageInfo.hasNextPage ? threads.pageInfo.endCursor : null;\n } while (!threadId && after);\n if (!threadId) throw new Error(`No review thread found for comment ${discussionId}`);\n const mutation = resolved ? \"resolveReviewThread\" : \"unresolveReviewThread\";\n await this.graphql(`mutation($id:ID!){${mutation}(input:{threadId:$id}){thread{id}}}`, { id: threadId });\n }\n\n private async graphql<T>(query: string, variables: Record<string, unknown>): Promise<T> {\n const res = await this.json<{ data?: T; errors?: { message: string }[] }>(\"POST\", this.graphqlUrl, { query, variables });\n if (res.errors?.length) throw new Error(`GitHub GraphQL: ${res.errors.map((e) => e.message).join(\"; \")}`);\n return res.data as T;\n }\n\n /** Review comments grouped by thread root (GitHub's in_reply_to_id always points at the root). */\n async listMrDiscussionThreads(project: ProjectRef, mrIid: number): Promise<{ discussionId: string; notes: DiscussionComment[] }[]> {\n const comments = await this.paginate<GhComment>(`/repos/${await this.repo(project)}/pulls/${mrIid}/comments`);\n const threads = new Map<string, DiscussionComment[]>();\n for (const c of comments) {\n const root = String(c.in_reply_to_id ?? c.id);\n threads.set(root, [...(threads.get(root) ?? []), GitHubForge.comment(c)]);\n }\n return [...threads].map(([discussionId, notes]) => ({ discussionId, notes }));\n }\n\n async getCurrentUser(): Promise<{ username: string; id: number }> {\n const u = await this.json<GhUser>(\"GET\", \"/user\");\n return { username: u.login, id: u.id };\n }\n\n async getProject(project: ProjectRef): Promise<ForgeProject> {\n const r = await this.json<GhRepo>(\"GET\", typeof project === \"number\" || /^\\d+$/.test(project) ? `/repositories/${project}` : `/repos/${project}`);\n this.repoNames.set(r.id, r.full_name);\n return { id: r.id, pathWithNamespace: r.full_name, name: r.name, webUrl: r.html_url, defaultBranch: r.default_branch };\n }\n\n async listFiles(project: ProjectRef, ref: string): Promise<string[]> {\n // `truncated: true` past ~100k entries \u2014 a partial list is fine for sampling.\n const t = await this.json<{ tree: { path: string; type: string }[] }>(\"GET\", `/repos/${await this.repo(project)}/git/trees/${encodeURIComponent(ref)}?recursive=1`);\n return t.tree.filter((e) => e.type === \"blob\").map((e) => e.path);\n }\n\n async readFile(project: ProjectRef, path: string, ref: string): Promise<string | null> {\n const p = path.split(\"/\").map(encodeURIComponent).join(\"/\");\n try {\n const res = await this.request(\"GET\", `/repos/${await this.repo(project)}/contents/${p}?ref=${encodeURIComponent(ref)}`, undefined, \"application/vnd.github.raw\");\n return await res.text();\n } catch (err) {\n if (err instanceof GitHubError && err.status === 404) return null;\n throw err;\n }\n }\n\n\n async openOrUpdateChangeRequest(project: ProjectRef, opts: { sourceBranch: string; targetBranch: string; title: string; description: string }): Promise<{ url: string; created: boolean }> {\n const repo = await this.repo(project);\n const owner = repo.split(\"/\")[0]!;\n const open = await this.json<{ number: number; html_url: string }[]>(\"GET\", `/repos/${repo}/pulls?state=open&head=${encodeURIComponent(`${owner}:${opts.sourceBranch}`)}&base=${encodeURIComponent(opts.targetBranch)}`);\n if (open[0]) {\n await this.json(\"PATCH\", `/repos/${repo}/pulls/${open[0].number}`, { body: opts.description });\n return { url: open[0].html_url, created: false };\n }\n const pr = await this.json<{ html_url: string }>(\"POST\", `/repos/${repo}/pulls`, { title: opts.title, head: opts.sourceBranch, base: opts.targetBranch, body: opts.description });\n return { url: pr.html_url, created: true };\n }\n}\n\n/** Check-run conclusion \u2192 the \"success\"/\"failed\" vocabulary scoreFromJob understands. */\nexport function normalizeConclusion(status: string, conclusion: string | null): string {\n if (conclusion === \"success\") return \"success\";\n if (conclusion === \"failure\" || conclusion === \"timed_out\") return \"failed\";\n return conclusion ?? status;\n}\n\n/** On a public repo anyone can comment, so a marker comment only counts from a bot (the Actions\n * token posts as github-actions[bot]) or someone with a role on the repo. */\nfunction isTrustedCommenter(c: GhComment): boolean {\n return c.user?.type === \"Bot\" || [\"OWNER\", \"MEMBER\", \"COLLABORATOR\"].includes(c.author_association ?? \"\");\n}\n", "import { Gitlab } from \"@gitbeaker/rest\";\n\nimport type { DiscussionComment, FindingPosition, ForgeClient, ForgeProject, JobSummary, MrMetadata, PastMrNote, ProjectMrSummary, ProjectRef } from \"./types.js\";\nimport { PR_SCORE_LABEL, PR_SCORE_MARKER } from \"./types.js\";\n\ninterface DiscussionNotePosition {\n new_path?: string;\n old_path?: string;\n new_line?: string;\n old_line?: string;\n}\n\nexport class GitLabForge implements ForgeClient {\n readonly type = \"gitlab\" as const;\n readonly host: string;\n private api: Gitlab;\n\n /** `url`: the instance base URL (\"https://gitlab.com\", \"https://host/gitlab\"). */\n constructor(opts: { url: string; token: string }) {\n this.host = new URL(opts.url).host.toLowerCase();\n this.api = new Gitlab({ host: opts.url, token: opts.token });\n }\n\n async getMergeRequest(projectId: ProjectRef, mrIid: number): Promise<MrMetadata> {\n const mr = await this.api.MergeRequests.show(projectId, mrIid);\n return {\n projectId,\n iid: mrIid,\n title: mr.title ?? \"\",\n description: mr.description ?? \"\",\n authorUsername: mr.author?.username ?? \"unknown\",\n draft: Boolean(mr.draft || mr.work_in_progress),\n labels: Array.isArray(mr.labels) ? mr.labels.map((l) => (typeof l === \"string\" ? l : l.name)) : [],\n targetBranch: mr.target_branch ?? \"main\",\n sourceBranch: mr.source_branch ?? \"\",\n sha: mr.sha ?? \"\",\n webUrl: mr.web_url ?? \"\",\n diffRefs: {\n baseSha: mr.diff_refs?.base_sha ?? \"\",\n startSha: mr.diff_refs?.start_sha ?? \"\",\n headSha: mr.diff_refs?.head_sha ?? \"\",\n },\n };\n }\n\n async upsertPrScoreNote(projectId: ProjectRef, mrIid: number, body: string): Promise<void> {\n const notes = await this.api.MergeRequestNotes.all(projectId, mrIid);\n const existing = notes.find((n) => typeof n.body === \"string\" && n.body.includes(PR_SCORE_MARKER));\n if (existing) {\n await this.api.MergeRequestNotes.edit(projectId, mrIid, existing.id, { body });\n } else {\n await this.api.MergeRequestNotes.create(projectId, mrIid, body);\n }\n }\n\n /** Best-effort: `add_labels` keeps existing labels, and GitLab creates the project label on\n * first use. A token without label rights shouldn't fail an otherwise-posted review. */\n async markReviewed(projectId: ProjectRef, mrIid: number): Promise<boolean> {\n try {\n await this.api.MergeRequests.edit(projectId, mrIid, { addLabels: PR_SCORE_LABEL });\n return true;\n } catch (err) {\n console.warn(`[yolont] could not add '${PR_SCORE_LABEL}' label: ${(err as Error).message}`);\n return false;\n }\n }\n\n /** All notes on an MR that carry our marker, oldest first \u2014 used for history rebuild. */\n async listPrScoreNotes(projectId: ProjectRef, mrIid: number): Promise<PastMrNote[]> {\n const notes = await this.api.MergeRequestNotes.all(projectId, mrIid);\n return notes\n .filter((n) => typeof n.body === \"string\" && n.body.includes(PR_SCORE_MARKER))\n .map((n) => ({ mrIid, body: n.body as string, createdAt: (n.created_at as string) ?? \"\" }));\n }\n\n /** Past MRs by this author across all projects the token can see, newest first. */\n async listAuthorMergeRequests(authorUsername: string, limit = 20): Promise<{ projectId: ProjectRef; iid: number }[]> {\n const mrs = await this.api.MergeRequests.all({\n authorUsername,\n scope: \"all\",\n state: \"merged\",\n orderBy: \"updated_at\",\n sort: \"desc\",\n perPage: limit,\n });\n return mrs.map((mr) => ({ projectId: mr.project_id as number, iid: mr.iid as number }));\n }\n\n /** Best-effort like getTestReportSummary: a bad/inaccessible pipeline ID degrades to \"no\n * job data\" (job:<name> categories excluded, per pipelineResults.ts), not a crash. */\n async listPipelineJobs(projectId: ProjectRef, pipelineId: number): Promise<JobSummary[]> {\n try {\n const jobs = await this.api.Jobs.all(projectId, { pipelineId });\n return jobs.map((j) => ({\n name: j.name,\n status: j.status,\n coverage: j.coverage != null ? Number(j.coverage) : null,\n }));\n } catch {\n return [];\n }\n }\n\n /**\n * Fetches the MR diff via the GitLab API instead of local `git` \u2014 the fallback used\n * when there's no local checkout of the target repo at all (ad-hoc/local testing\n * against a project you haven't cloned, or scoring across repos generically). Not the\n * default in a real CI job: this endpoint truncates large diffs per-file independent\n * of our own `max_diff_bytes`, whereas a local `git diff` is complete.\n *\n * GitLab's diff entries omit the `--- a/...`/`+++ b/...` header lines (implied by\n * old_path/new_path), so they're reconstructed here into a standard unified diff \u2014\n * good enough for the diff-size count, gitleaks, and the LLM prompt, none of which\n * need real git plumbing, just the patch text.\n */\n async getMrDiffText(projectId: ProjectRef, mrIid: number): Promise<string> {\n const diffs = await this.api.MergeRequests.allDiffs(projectId, mrIid);\n return diffs\n .map((d) => {\n const header = `diff --git a/${d.old_path} b/${d.new_path}\\n--- a/${d.old_path}\\n+++ b/${d.new_path}\\n`;\n return header + d.diff;\n })\n .join(\"\\n\");\n }\n\n /** All MRs in a project (not scoped to one author) \u2014 used by the local backfill/mining tool. */\n async listProjectMergeRequests(\n projectId: ProjectRef,\n opts: { state?: \"merged\" | \"opened\" | \"closed\" | \"all\"; maxPages?: number } = {},\n ): Promise<ProjectMrSummary[]> {\n const mrs = await this.api.MergeRequests.all({\n projectId,\n state: opts.state === \"all\" ? undefined : opts.state,\n orderBy: \"updated_at\",\n sort: \"desc\",\n perPage: 100,\n maxPages: opts.maxPages,\n });\n return mrs.map((mr) => ({\n iid: mr.iid,\n authorUsername: mr.author?.username ?? \"unknown\",\n sha: mr.sha ?? \"\",\n title: mr.title ?? \"\",\n mergedAt: mr.merged_at,\n }));\n }\n\n /**\n * Real human review comments on an MR (diff-line and general discussion notes),\n * filtered to non-system notes only \u2014 used by the local mining tool to build the\n * `human_review_comments` table. Caller is responsible for excluding the Yolont\n * bot's own notes (see getCurrentUser) since a bot's Yolont comment is itself a\n * non-system note and would otherwise be mined as \"human\" signal.\n */\n async listMrDiscussions(projectId: ProjectRef, mrIid: number): Promise<DiscussionComment[]> {\n const discussions = await this.api.MergeRequestDiscussions.all(projectId, mrIid);\n const comments: DiscussionComment[] = [];\n for (const discussion of discussions) {\n for (const note of discussion.notes ?? []) {\n if (note.system) continue;\n const position = (note as { position?: DiscussionNotePosition }).position;\n comments.push({\n id: note.id,\n authorUsername: note.author?.username ?? \"unknown\",\n body: note.body ?? \"\",\n system: false,\n createdAt: note.created_at ?? \"\",\n file: position?.new_path ?? position?.old_path,\n line: position?.new_line ? Number(position.new_line) : position?.old_line ? Number(position.old_line) : undefined,\n });\n }\n }\n return comments;\n }\n\n /**\n * Posts one finding as its own discussion thread \u2014 repliable by the contributor,\n * unlike the single aggregate note from upsertPrScoreNote. `position` pins it to a\n * diff line (from MrMetadata.diffRefs, captured at review time); omit it to post a\n * general (still repliable) discussion for a finding with no file/line.\n *\n * `oldLine` matters: GitLab rejects a position with only `new_line` unless that line\n * was actually added \u2014 a comment on an unchanged/context line needs `old_line` too (see\n * resolveDiffPosition in src/git.ts, which is what callers should use to compute this).\n */\n async postFindingDiscussion(\n projectId: ProjectRef,\n mrIid: number,\n body: string,\n position?: FindingPosition,\n ): Promise<{ discussionId: string; noteId: number }> {\n const discussion = await this.api.MergeRequestDiscussions.create(projectId, mrIid, body, {\n position: position\n ? {\n baseSha: position.baseSha,\n startSha: position.startSha,\n headSha: position.headSha,\n newPath: position.filePath,\n newLine: String(position.line),\n ...(position.oldLine != null ? { oldLine: String(position.oldLine) } : {}),\n positionType: \"text\",\n }\n : undefined,\n });\n return { discussionId: String(discussion.id), noteId: discussion.notes?.[0]?.id as number };\n }\n\n /** Replies on a discussion thread, or edits our earlier reply in place when `noteId` is\n * given. Falls back to a fresh reply if that note is gone (e.g. deleted by hand in GitLab).\n * Returns the note id to keep for the next edit. */\n async upsertDiscussionReply(projectId: ProjectRef, mrIid: number, discussionId: string, body: string, noteId?: number | null): Promise<number> {\n if (noteId != null) {\n try {\n await this.api.MergeRequestDiscussions.editNote(projectId, mrIid, discussionId, noteId, { body });\n return noteId;\n } catch (err) {\n if (!isNotFound(err)) throw err;\n }\n }\n const note = await this.api.MergeRequestDiscussions.addNote(projectId, mrIid, discussionId, body);\n return note.id;\n }\n\n async deleteDiscussionReply(projectId: ProjectRef, mrIid: number, discussionId: string, noteId: number): Promise<void> {\n try {\n await this.api.MergeRequestDiscussions.removeNote(projectId, mrIid, discussionId, noteId);\n } catch (err) {\n if (!isNotFound(err)) throw err;\n }\n }\n\n async resolveDiscussion(projectId: ProjectRef, mrIid: number, discussionId: string, resolved: boolean): Promise<void> {\n await this.api.MergeRequestDiscussions.resolve(projectId, mrIid, discussionId, resolved);\n }\n\n /** Like listMrDiscussions, but keeps notes grouped by their discussion thread \u2014 used by\n * the local sync-replies command to find replies on a specific tracked finding thread. */\n async listMrDiscussionThreads(projectId: ProjectRef, mrIid: number): Promise<{ discussionId: string; notes: DiscussionComment[] }[]> {\n const discussions = await this.api.MergeRequestDiscussions.all(projectId, mrIid);\n return discussions.map((discussion) => ({\n discussionId: String(discussion.id),\n notes: (discussion.notes ?? [])\n .filter((note) => !note.system)\n .map((note) => {\n const position = (note as { position?: DiscussionNotePosition }).position;\n return {\n id: note.id,\n authorUsername: note.author?.username ?? \"unknown\",\n body: note.body ?? \"\",\n system: false,\n createdAt: note.created_at ?? \"\",\n file: position?.new_path ?? position?.old_path,\n line: position?.new_line ? Number(position.new_line) : position?.old_line ? Number(position.old_line) : undefined,\n };\n }),\n }));\n }\n\n /** Used once at the start of a mining run to identify (and exclude) the bot's own notes. */\n async getCurrentUser(): Promise<{ username: string; id: number }> {\n const user = await this.api.Users.showCurrentUser();\n return { username: user.username, id: user.id };\n }\n\n async getProject(projectId: ProjectRef): Promise<ForgeProject> {\n const project = await this.api.Projects.show(projectId);\n return { id: project.id, pathWithNamespace: project.path_with_namespace, name: project.name, webUrl: project.web_url, defaultBranch: project.default_branch };\n }\n\n async listFiles(projectId: ProjectRef, ref: string): Promise<string[]> {\n // ponytail: capped at 20 pages (2000 entries) \u2014 enough to sample from; huge monorepos get a partial tree.\n const tree = await this.api.Repositories.allRepositoryTrees(projectId, { ref, recursive: true, perPage: 100, maxPages: 20 });\n return (tree as { path: string; type: string }[]).filter((e) => e.type === \"blob\").map((e) => e.path);\n }\n\n async readFile(projectId: ProjectRef, path: string, ref: string): Promise<string | null> {\n try {\n const raw = await this.api.RepositoryFiles.showRaw(projectId, path, ref);\n return typeof raw === \"string\" ? raw : await (raw as Blob).text();\n } catch (err) {\n if (isNotFound(err)) return null;\n throw err;\n }\n }\n\n /** Best-effort: returns null if the pipeline has no test report (not all repos publish one). */\n async getTestReportSummary(projectId: ProjectRef, pipelineId: number): Promise<{ total: number; success: number } | null> {\n try {\n const report = await this.api.Pipelines.showTestReportSummary(projectId, pipelineId);\n const total = report.total?.count ?? 0;\n const success = report.total?.success ?? 0;\n if (total === 0) return null;\n return { total, success };\n } catch {\n return null;\n }\n }\n\n async openOrUpdateChangeRequest(projectId: ProjectRef, opts: { sourceBranch: string; targetBranch: string; title: string; description: string }): Promise<{ url: string; created: boolean }> {\n const open = await this.api.MergeRequests.all({ projectId, sourceBranch: opts.sourceBranch, targetBranch: opts.targetBranch, state: \"opened\" });\n const mr = open[0];\n if (mr) {\n await this.api.MergeRequests.edit(projectId, mr.iid, { description: opts.description });\n return { url: (mr.web_url as string) ?? \"\", created: false };\n }\n const created = await this.api.MergeRequests.create(projectId, opts.sourceBranch, opts.targetBranch, opts.title, { description: opts.description, removeSourceBranch: true });\n return { url: (created.web_url as string) ?? \"\", created: true };\n }\n}\n\nfunction isNotFound(err: unknown): boolean {\n return (err as { cause?: { response?: { status?: number } } }).cause?.response?.status === 404;\n}\n", "import { GitHubForge } from \"./github.js\";\nimport { GitLabForge } from \"./gitlab.js\";\nimport type { ForgeClient, ForgeType } from \"./types.js\";\n\nexport * from \"./types.js\";\nexport { GitHubForge, GitLabForge };\n\nexport interface ChangeRef {\n type: ForgeType;\n /** Bare web host, lowercased, with port: the identity key. */\n host: string;\n /** \"group/sub/project\" | \"owner/repo\", as written in the URL. */\n projectPath: string;\n number: number;\n}\n\n/**\n * Parses an MR/PR web URL. The URL shape alone tells the forge apart (`/-/merge_requests/N`\n * vs `/pull/N`), so no network probe is needed. `gitlabBaseUrls` are configured instance URLs:\n * a GitLab served under a sub-path (\"https://host/gitlab\") has that prefix stripped.\n */\nexport function parseChangeUrl(input: string, gitlabBaseUrls: string[] = []): ChangeRef | null {\n let url: URL;\n try {\n url = new URL(input.trim());\n } catch {\n return null;\n }\n const host = url.host.toLowerCase();\n const path = url.pathname.replace(/\\/+$/, \"\");\n\n const gh = path.match(/^\\/([^/]+)\\/([^/]+)\\/pull\\/(\\d+)(?:\\/|$)/);\n if (gh) return { type: \"github\", host, projectPath: `${gh[1]}/${gh[2]}`, number: Number(gh[3]) };\n\n const gl = path.match(/^(.+?)\\/-\\/merge_requests\\/(\\d+)(?:\\/|$)/);\n if (!gl) return null;\n let projectPath = gl[1]!;\n const base = gitlabBaseUrls.map((b) => new URL(b)).find((b) => b.host.toLowerCase() === host && b.pathname !== \"/\" && projectPath.startsWith(`${b.pathname.replace(/\\/$/, \"\")}/`));\n if (base) projectPath = projectPath.slice(base.pathname.replace(/\\/$/, \"\").length);\n return { type: \"gitlab\", host, projectPath: decodeURIComponent(projectPath.replace(/^\\//, \"\")), number: Number(gl[2]) };\n}\n\n/** `url` is the GitLab instance URL (may carry a sub-path); ignored for GitHub, which derives its API from `host`. */\nexport function createForge(opts: { type: ForgeType; host: string; url?: string; token: string }): ForgeClient {\n return opts.type === \"github\" ? new GitHubForge({ host: opts.host, token: opts.token }) : new GitLabForge({ url: opts.url ?? `https://${opts.host}`, token: opts.token });\n}\n\nexport interface GitAddress {\n /** Bare web host. For ssh remotes the ssh port is dropped \u2014 it isn't the web port. */\n host: string;\n projectPath: string;\n /** Set when the address was an MR/PR URL. */\n ref?: ChangeRef;\n}\n\n/**\n * Anything a user might paste or `git remote` prints: an MR/PR URL, `https://host/g/p(.git)`,\n * `git@host:g/p.git`, `ssh://git@host:2222/g/p.git`. Paths keep their case (GitHub API is\n * case-insensitive, GitLab paths are lowercase anyway).\n */\nexport function parseGitAddress(input: string, gitlabBaseUrls: string[] = []): GitAddress | null {\n const s = input.trim();\n const ref = parseChangeUrl(s, gitlabBaseUrls);\n if (ref) return { host: ref.host, projectPath: ref.projectPath, ref };\n // scp-like ssh: git@host:group/project.git (no scheme)\n const scp = !s.includes(\"://\") && s.match(/^(?:[^@/\\s]+@)?([^:/\\s]+):(?!\\/)(.+?)(?:\\.git)?\\/?$/);\n if (scp) return { host: scp[1]!.toLowerCase(), projectPath: scp[2]! };\n let url: URL;\n try {\n url = new URL(s);\n } catch {\n return null;\n }\n const path = url.pathname.replace(/^\\/+|\\/+$/g, \"\").replace(/\\.git$/, \"\").replace(/\\/-\\/.*$/, \"\");\n if (!path.includes(\"/\")) return null;\n const host = (url.protocol.startsWith(\"ssh\") || url.protocol === \"git:\" ? url.hostname : url.host).toLowerCase();\n let projectPath = path;\n const base = gitlabBaseUrls.map((b) => new URL(b)).find((b) => b.host.toLowerCase() === host && b.pathname !== \"/\" && `/${path}`.startsWith(`${b.pathname.replace(/\\/$/, \"\")}/`));\n if (base) projectPath = path.slice(base.pathname.replace(/^\\/|\\/$/g, \"\").length + 1);\n return { host, projectPath: decodeURIComponent(projectPath) };\n}\n\n/**\n * Which forge runs on `host`? github.com is known; otherwise GitLab answers /api/v4/version\n * (401 without a token still counts \u2014 it's GitLab saying no), and GitHub Enterprise answers\n * /api/v3/meta without auth. null = couldn't tell (offline, VPN, something else): ask the user.\n */\nexport async function probeForgeType(host: string, fetchImpl: typeof fetch = fetch): Promise<ForgeType | null> {\n if (host === \"github.com\") return \"github\";\n const get = (path: string) => fetchImpl(`https://${host}${path}`, { signal: AbortSignal.timeout(8000), redirect: \"manual\" }).catch(() => null);\n const gl = await get(\"/api/v4/version\");\n if (gl && (gl.status === 200 || gl.status === 401) && gl.headers.get(\"content-type\")?.includes(\"json\")) return \"gitlab\";\n const gh = await get(\"/api/v3/meta\");\n if (gh?.ok && gh.headers.get(\"content-type\")?.includes(\"json\")) return \"github\";\n return null;\n}\n", "import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from \"node:crypto\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport { CONFIG_DIR } from \"../paths.js\";\n\n/**\n * Secret names: `forge:<host>` (git token), `llm:<profile>` (LLM key), `jev` (typesafe.ai).\n *\n * Backend: the OS keychain (macOS Keychain, Windows Credential Manager, Linux Secret\n * Service) when it works; otherwise ~/.config/yolont/credentials.json, mode 0600.\n * That file is AES-256-GCM encrypted when YOLONT_PASSPHRASE is set. Without a passphrase it\n * stays plaintext: a key kept on the same disk would be obfuscation, not protection.\n * Reads check the keychain, then the file, so a secret saved while the keychain was\n * unavailable (e.g. over SSH) is still found later.\n */\nconst SERVICE = \"yolont\";\n/** Keychain service from before the rename: read once and copied over. */\nconst OLD_SERVICE = \"ethos\";\nexport const CREDENTIALS_PATH = join(CONFIG_DIR, \"credentials.json\");\n\ninterface KeyringEntry {\n getPassword(): string | null | undefined;\n setPassword(v: string): void;\n deletePassword(): boolean | void;\n}\ntype EntryCtor = new (service: string, account: string) => KeyringEntry;\n\nlet keyringCtor: EntryCtor | null | undefined;\n/** null when the native module is missing or there's no keychain service (headless Linux, WSL, CI). */\nfunction keyring(): EntryCtor | null {\n if (keyringCtor !== undefined) return keyringCtor;\n keyringCtor = null;\n if (process.env.YOLONT_NO_KEYCHAIN === \"1\") return null;\n try {\n const { Entry } = createRequire(import.meta.url)(\"@napi-rs/keyring\") as { Entry: EntryCtor };\n new Entry(SERVICE, \"__probe__\").getPassword(); // throws when no Secret Service is running\n keyringCtor = Entry;\n } catch {\n /* fall back to file */\n }\n return keyringCtor;\n}\n\nexport function secretBackend(): \"keychain\" | \"file (encrypted)\" | \"file (plaintext 0600)\" {\n if (keyring()) return \"keychain\";\n return process.env.YOLONT_PASSPHRASE ? \"file (encrypted)\" : \"file (plaintext 0600)\";\n}\n\n// ---- file backend ----\n\ntype FileShape = { v: 1; secrets: Record<string, string> } | { v: 1; enc: { salt: string; iv: string; tag: string; data: string } };\n\nfunction deriveKey(passphrase: string, salt: Buffer): Buffer {\n return scryptSync(passphrase, salt, 32);\n}\n\nfunction readFileSecrets(): Record<string, string> {\n if (!existsSync(CREDENTIALS_PATH)) return {};\n const raw = JSON.parse(readFileSync(CREDENTIALS_PATH, \"utf8\")) as FileShape;\n if (\"secrets\" in raw) return raw.secrets;\n const passphrase = process.env.YOLONT_PASSPHRASE;\n if (!passphrase) throw new Error(`${CREDENTIALS_PATH} is encrypted \u2014 set YOLONT_PASSPHRASE to read it.`);\n const d = createDecipheriv(\"aes-256-gcm\", deriveKey(passphrase, Buffer.from(raw.enc.salt, \"base64\")), Buffer.from(raw.enc.iv, \"base64\"));\n d.setAuthTag(Buffer.from(raw.enc.tag, \"base64\"));\n try {\n return JSON.parse(Buffer.concat([d.update(Buffer.from(raw.enc.data, \"base64\")), d.final()]).toString(\"utf8\"));\n } catch {\n throw new Error(`Could not decrypt ${CREDENTIALS_PATH} \u2014 wrong YOLONT_PASSPHRASE?`);\n }\n}\n\nfunction writeFileSecrets(secrets: Record<string, string>): void {\n mkdirSync(dirname(CREDENTIALS_PATH), { recursive: true });\n let body: FileShape = { v: 1, secrets };\n const passphrase = process.env.YOLONT_PASSPHRASE;\n if (passphrase) {\n const salt = randomBytes(16);\n const iv = randomBytes(12);\n const c = createCipheriv(\"aes-256-gcm\", deriveKey(passphrase, salt), iv);\n const data = Buffer.concat([c.update(JSON.stringify(secrets), \"utf8\"), c.final()]);\n body = { v: 1, enc: { salt: salt.toString(\"base64\"), iv: iv.toString(\"base64\"), tag: c.getAuthTag().toString(\"base64\"), data: data.toString(\"base64\") } };\n }\n writeFileSync(CREDENTIALS_PATH, `${JSON.stringify(body, null, 2)}\\n`, { mode: 0o600 });\n chmodSync(CREDENTIALS_PATH, 0o600); // mode only applies on create\n}\n\n// ---- public API ----\n\nexport function getSecret(name: string): string | undefined {\n const Entry = keyring();\n if (Entry) {\n const v = new Entry(SERVICE, name).getPassword();\n if (v) return v;\n const old = (() => {\n try {\n return new Entry(OLD_SERVICE, name).getPassword();\n } catch {\n return null;\n }\n })();\n if (old) {\n new Entry(SERVICE, name).setPassword(old);\n return old;\n }\n }\n return readFileSecrets()[name];\n}\n\nexport function setSecret(name: string, value: string): void {\n const Entry = keyring();\n if (Entry) {\n new Entry(SERVICE, name).setPassword(value);\n // Don't leave an older copy behind in the file that a later read could shadow.\n const file = readFileSecrets();\n if (name in file) {\n delete file[name];\n writeFileSecrets(file);\n }\n return;\n }\n writeFileSecrets({ ...readFileSecrets(), [name]: value });\n}\n\nexport function deleteSecret(name: string): void {\n const Entry = keyring();\n if (Entry) {\n for (const service of [SERVICE, OLD_SERVICE]) {\n try {\n new Entry(service, name).deletePassword();\n } catch {\n /* not there */\n }\n }\n }\n const file = readFileSecrets();\n if (name in file) {\n delete file[name];\n writeFileSecrets(file);\n }\n}\n\n/** \"glpat-abc\u20263f2a\" -> \"glpa\u2022\u2022\u2022\u20223f2a\" \u2014 for display only. */\nexport function maskSecret(v: string | undefined): string {\n if (!v) return \"(not set)\";\n return v.length <= 8 ? \"\u2022\u2022\u2022\u2022\" : `${v.slice(0, 4)}\u2022\u2022\u2022\u2022${v.slice(-4)}`;\n}\n", "import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport yaml from \"js-yaml\";\nimport { z } from \"zod\";\nimport { CONFIG_DIR } from \"../paths.js\";\nimport { getSecret } from \"./secrets.js\";\n\nexport const CONFIG_PATH = join(CONFIG_DIR, \"config.yaml\");\n\nconst ForgeSchema = z.object({\n /** Bare host, the key everything else uses: \"gitlab.com\", \"git.example.com:8443\". */\n host: z.string().min(1),\n type: z.enum([\"gitlab\", \"github\"]),\n /** API base URL; defaults to https://<host>. */\n url: z.string().url().optional(),\n});\n\nconst LlmProfileSchema = z.object({\n name: z.string().min(1),\n /** openai-compatible covers OpenCode Zen, OpenRouter, any /v1/chat/completions gateway. */\n provider: z.enum([\"anthropic\", \"openai-compatible\", \"ollama\"]),\n model: z.string().min(1),\n baseUrl: z.string().url().optional(),\n});\n\nconst SourceSchema = z.object({\n name: z.string().regex(/^[a-z0-9][a-z0-9-]*$/),\n url: z.string().min(1),\n projects: z.array(z.string()).default([]),\n /** Git host, kept only when the address has none (a local path). Projects on other hosts can't use it. */\n host: z.string().optional(),\n /** Sync on its own after each review and when the panel starts. */\n autoSync: z.boolean().default(true),\n});\n\nconst ConfigSchema = z.object({\n forges: z.array(ForgeSchema).default([]),\n defaultForge: z.string().optional(),\n llmProfiles: z.array(LlmProfileSchema).default([]),\n defaultLlmProfile: z.string().optional(),\n jev: z.object({ model: z.string().optional(), threshold: z.number().min(0).max(1).optional(), disabled: z.boolean().optional() }).optional(),\n /** Memory repos: who you are in team data repos \u2014 your records folder. */\n member: z.object({ id: z.string().regex(/^[a-z0-9-]+$/), name: z.string() }).optional(),\n /** Team data repos. `projects` is YOUR list of what you share there (\"host/path\"): a project is\n * only ever exported when both this list and the repo's manifest name it. */\n sources: z.array(SourceSchema).optional(),\n /** Wizard look: Nerd Font icons (\"nerd\") or plain text. Asked once. */\n icons: z.enum([\"nerd\", \"plain\"]).optional(),\n /** Run through npx: the offer to install the `yolont` command was answered (asked once). */\n installOffered: z.boolean().optional(),\n /** Save limit for conventions files (default 300 lines; they go into every review prompt). */\n conventionsMaxLines: z.number().int().min(20).max(2000).optional(),\n /** Change type (src/changeType.ts): off, label (named with the review) or steer (settled first, then type-specific checks). */\n changeType: z.enum([\"off\", \"label\", \"steer\"]).optional(),\n /** Projects (\"host/path\") you chose to keep on your own memory only, so the wizard doesn't ask again. */\n localProjects: z.array(z.string()).optional(),\n});\n\nexport type YolontConfig = z.infer<typeof ConfigSchema>;\nexport type ForgeConfig = z.infer<typeof ForgeSchema>;\nexport type LlmProfile = z.infer<typeof LlmProfileSchema>;\nexport type SourceConfig = z.infer<typeof SourceSchema>;\n\n/** Never contains secrets \u2014 those go through secrets.ts, keyed `forge:<host>` / `llm:<name>` / `jev`. */\nexport function loadConfig(path = CONFIG_PATH): YolontConfig {\n if (!existsSync(path)) return ConfigSchema.parse({});\n const parsed = ConfigSchema.safeParse(yaml.load(readFileSync(path, \"utf8\")) ?? {});\n if (!parsed.success) throw new Error(`Invalid ${path}: ${parsed.error.issues.map((i) => `${i.path.join(\".\")}: ${i.message}`).join(\"; \")}`);\n return parsed.data;\n}\n\nexport function saveConfig(config: YolontConfig, path = CONFIG_PATH): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `# Yolont config \u2014 no secrets here (see \\`yolont config show\\` for where they live).\\n${yaml.dump(ConfigSchema.parse(config))}`);\n}\n\n/** Any of these in the shell selects an LLM provider directly (createLlmProvider), bypassing profiles. */\nexport const LLM_ENV_KEYS = [\"ANTHROPIC_API_KEY\", \"OPENCODE_ZEN_API_KEY\", \"OPENCODE_ZEN_GO_API_KEY\", \"OMNI_API_KEY\", \"OLLAMA_URL\"] as const;\n\nexport const forgeUrl = (f: ForgeConfig) => f.url ?? `https://${f.host}`;\n\n/**\n * Bridge until the forge/LLM code reads config directly (Phase 1/2): fills the env vars\n * the existing code reads, from config + secrets, **only where unset** \u2014 shell env and\n * CI variables always win. Returns the names it filled, for `config show`.\n */\nexport function applyConfigToEnv(config: YolontConfig, env: NodeJS.ProcessEnv = process.env): string[] {\n const filled: string[] = [];\n const put = (k: string, v: string | undefined) => {\n if (v !== undefined && v !== \"\" && !env[k]) {\n env[k] = v;\n filled.push(k);\n }\n };\n\n const forge = config.forges.find((f) => f.host === config.defaultForge) ?? config.forges[0];\n // ponytail: one default forge feeds CI_SERVER_URL; per-MR forge choice comes with `review <url>` in Phase 1.\n if (forge?.type === \"gitlab\") {\n put(\"CI_SERVER_URL\", forgeUrl(forge));\n put(\"GITLAB_API_TOKEN\", getSecret(`forge:${forge.host}`));\n }\n\n const profile = config.llmProfiles.find((p) => p.name === config.defaultLlmProfile) ?? config.llmProfiles[0];\n // createLlmProvider picks the first provider whose key is set, so only fill one \u2014 and\n // only if the shell hasn't already chosen one, or we'd silently override that choice.\n if (profile && !LLM_ENV_KEYS.some((k) => env[k])) {\n const key = getSecret(`llm:${profile.name}`);\n if (profile.provider === \"anthropic\") {\n put(\"ANTHROPIC_API_KEY\", key);\n put(\"ANTHROPIC_MODEL\", profile.model);\n } else if (profile.provider === \"openai-compatible\") {\n put(\"OPENCODE_ZEN_API_KEY\", key);\n put(\"OPENCODE_ZEN_MODEL\", profile.model);\n put(\"OPENCODE_ZEN_BASE_URL\", profile.baseUrl);\n } else {\n put(\"OLLAMA_URL\", profile.baseUrl ?? \"http://localhost:11434\");\n put(\"OLLAMA_MODEL\", profile.model);\n }\n }\n\n put(\"TYPESAFE_API_KEY\", getSecret(\"jev\"));\n put(\"JEV_MODEL\", config.jev?.model);\n put(\"JEV_NOISE_THRESHOLD\", config.jev?.threshold?.toString());\n if (config.jev?.disabled) put(\"JEV_DISABLED\", \"1\");\n lastFilled.set(env, filled);\n return filled;\n}\n\nconst lastFilled = new WeakMap<NodeJS.ProcessEnv, string[]>();\n\n/** Env vars the last applyConfigToEnv filled \u2014 anything else set was set by the user's shell. */\nexport const configFilledKeys = (env: NodeJS.ProcessEnv = process.env): string[] => lastFilled.get(env) ?? [];\n\n/** After the wizard changes config: drop what the last apply filled (never shell-set vars), then apply again. */\nexport function reapplyConfigToEnv(env: NodeJS.ProcessEnv = process.env): string[] {\n for (const k of lastFilled.get(env) ?? []) delete env[k];\n return applyConfigToEnv(loadConfig(), env);\n}\n", "import { createForge, parseChangeUrl, type ChangeRef, type ForgeClient, type ForgeType } from \"../src/forge/index.js\";\nimport { forgeUrl, loadConfig, saveConfig } from \"./config/config.js\";\nimport { getSecret } from \"./config/secrets.js\";\nimport { bareHost } from \"./paths.js\";\n\n/**\n * Env tokens are bound to the host they were issued for: GITLAB_API_TOKEN only for\n * CI_SERVER_URL's host, GITHUB_TOKEN/GH_TOKEN only for github.com. Never hand one host's token\n * to another: \"github\" is detected from the URL's path shape, so any host can claim it, and\n * a pasted https://evil.example/a/b/pull/1 must not receive the github.com token. A GitHub\n * Enterprise host needs its own `forge:<host>` secret.\n */\nfunction envToken(type: ForgeType, host: string, env: NodeJS.ProcessEnv): string | undefined {\n if (type === \"gitlab\") return env.CI_SERVER_URL && bareHost(env.CI_SERVER_URL) === host ? env.GITLAB_API_TOKEN : undefined;\n return host === \"github.com\" ? env.GITHUB_TOKEN || env.GH_TOKEN || undefined : undefined;\n}\n\n/** Saved secret first, then the env token bound to this host (if any). */\nexport function forgeToken(host: string, type: ForgeType, env: NodeJS.ProcessEnv = process.env): string | undefined {\n return getSecret(`forge:${host}`) ?? envToken(type, host, env);\n}\n\n/** A client for `host`. `typeHint` (from a parsed URL) lets a new host work without prior setup; its type is then saved. */\nexport function forgeFor(hostOrUrl: string, typeHint?: ForgeType, env: NodeJS.ProcessEnv = process.env): ForgeClient {\n const host = bareHost(hostOrUrl);\n const config = loadConfig();\n const saved = config.forges.find((f) => f.host === host);\n const ciHost = env.CI_SERVER_URL ? bareHost(env.CI_SERVER_URL) : undefined;\n const type = saved?.type ?? typeHint ?? (host === \"github.com\" ? \"github\" : host === ciHost ? \"gitlab\" : undefined);\n if (!type) throw new Error(`Unknown git host ${host} \u2014 pass a full MR/PR URL so its type can be detected.`);\n\n const token = forgeToken(host, type, env);\n if (!token) throw new Error(`No token for ${host}. Save one with \\`yolont config set-secret forge:${host}\\`${host === \"github.com\" ? \" (or set GITHUB_TOKEN)\" : \"\"}.`);\n\n if (!saved) {\n // Remember host\u2192type only; tokens are never saved implicitly.\n config.forges.push({ host, type });\n config.defaultForge ??= host;\n saveConfig(config);\n }\n const url = saved ? forgeUrl(saved) : host === ciHost ? env.CI_SERVER_URL : undefined;\n return createForge({ type, host, url, token });\n}\n\n/** The forge `<project-id> <mr-iid>` style commands use: config default, else CI_SERVER_URL. */\nexport function defaultForgeHost(env: NodeJS.ProcessEnv = process.env): string {\n const host = loadConfig().defaultForge ?? (env.CI_SERVER_URL ? bareHost(env.CI_SERVER_URL) : undefined);\n if (!host) throw new Error(\"No default git host \u2014 use an MR/PR URL, or run `yolont config import-env`.\");\n return host;\n}\n\n/** Parses an MR/PR URL, honoring configured GitLab sub-path installs. */\nexport function parseChange(url: string): ChangeRef | null {\n return parseChangeUrl(url, loadConfig().forges.filter((f) => f.type === \"gitlab\" && f.url).map(forgeUrl));\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { ChangeTypeSchema, type ChangeType } from \"../../src/changeType.js\";\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { z } from \"zod\";\nimport { refreshScores, scoreFromBase, upsertFindingsForScore, upsertMergeRequest, upsertProject, type ScoreBase } from \"../db/repo.js\";\n\n/**\n * Memory repos, file side. A source folder holds one JSON file per record:\n *\n * projects/<host>/<path>/records/<member>/<uid>.json\n *\n * Every member writes only their own folder, so git never has to merge two people's edits.\n * Export mirrors this DB's own rows (origin NULL) of bound projects into the member's folder;\n * import upserts everyone else's files by uid (origin = the source's name).\n */\n\n/** \"host/group/project\", lowercased: how projects are named in manifests and config. */\nexport type ProjectKey = string;\nexport const projectKey = (host: string, path: string): ProjectKey => `${host}/${path}`.toLowerCase();\n\n/** Folder of one project inside a source. ':' (a port) is illegal in Windows paths. */\nexport function sourceProjectDir(sourceDir: string, key: ProjectKey): string {\n const [host, ...path] = key.split(\"/\");\n return join(sourceDir, \"projects\", host!.replace(/:/g, \"_\"), ...path);\n}\n\nconst ProjectRef = z.object({ host: z.string().min(1), id: z.string().min(1), path: z.string().min(1), name: z.string() });\nconst MrRef = z.object({\n project: ProjectRef,\n iid: z.number().int().positive(),\n author: z.string().min(1),\n sha: z.string(),\n title: z.string(),\n mergedAt: z.string().nullable(),\n source: z.enum([\"backfill\", \"live\"]),\n});\nconst FindingRef = z.object({ file: z.string().nullable(), line: z.number().int().nullable(), issue: z.string() });\nconst Base = { uid: z.string().uuid(), by: z.string().min(1) };\n\nconst Review = z.object({\n ...Base,\n kind: z.literal(\"review\"),\n mr: MrRef,\n scoredAt: z.string(),\n source: z.enum([\"llm_backfill\", \"llm_live\"]),\n finalScore: z.number(),\n changeType: ChangeTypeSchema.nullable().optional().catch(null),\n categoryScores: z.record(z.number()),\n findings: z.array(z.object({ category: z.string().optional(), severity: z.string(), issue: z.string(), file: z.string().optional(), line: z.number().optional() }).passthrough()),\n modelUsed: z.string().nullable(),\n volumeFactor: z.number(),\n base: z.unknown().nullable(),\n zoneHits: z.array(\n z.object({\n zoneId: z.string(),\n level: z.enum([\"red\", \"amber\", \"green\"]),\n files: z.array(z.string()),\n impact: z.enum([\"none\", \"low\", \"high\"]).nullable(),\n verdict: z.string().nullable(),\n vote: z.enum([\"up\", \"down\"]).nullable(),\n voteNote: z.string().nullable(),\n createdAt: z.string(),\n }),\n ),\n});\nconst Correction = z.object({\n ...Base,\n kind: z.literal(\"correction\"),\n mr: MrRef,\n category: z.string().nullable(),\n originalScore: z.number(),\n correctedScore: z.number(),\n reason: z.string(),\n correctedNote: z.string().nullable(),\n createdAt: z.string(),\n});\nconst Insight = z.object({\n ...Base,\n kind: z.literal(\"insight\"),\n host: z.string().min(1),\n /** NULL = every project on this host. */\n project: ProjectRef.nullable(),\n author: z.string().nullable(),\n category: z.string().nullable(),\n text: z.string().min(1),\n evidence: z.array(MrRef),\n createdAt: z.string(),\n});\nconst Vote = z.object({\n ...Base,\n kind: z.literal(\"vote\"),\n mr: MrRef,\n finding: FindingRef,\n vote: z.enum([\"up\", \"down\"]),\n note: z.string(),\n correctionUid: z.string().nullable(),\n insightUid: z.string().nullable(),\n createdAt: z.string(),\n});\nconst Tag = z.object({ ...Base, kind: z.literal(\"tag\"), mr: MrRef, finding: FindingRef, tag: z.string(), createdAt: z.string() });\n\nexport const SyncRecord = z.discriminatedUnion(\"kind\", [Review, Correction, Insight, Vote, Tag]);\nexport type SyncRecord = z.infer<typeof SyncRecord>;\ntype MrRef = z.infer<typeof MrRef>;\n\nexport interface SyncScope {\n /** Folder of the source's git clone. */\n dir: string;\n /** Source name; imported rows get it as `origin`. */\n name: string;\n /** This member's id: their records folder. */\n member: string;\n /** Projects to sync: the ones you chose this memory repo for (source.ts projectOwners). */\n projects: Set<ProjectKey>;\n}\n\n// ---------------------------------------------------------------- export\n\ntype MrRow = { mr_id: number; mr_iid: number; author_username: string; sha: string; title: string; merged_at: string | null; mr_source: \"backfill\" | \"live\"; forge_host: string; forge_project_id: string; path_with_namespace: string; project_name: string };\nconst MR_COLS = `mr.id AS mr_id, mr.mr_iid, mr.author_username, mr.sha, mr.title, mr.merged_at, mr.source AS mr_source,\n p.forge_host, p.forge_project_id, p.path_with_namespace, p.name AS project_name`;\n\nconst mrRef = (r: MrRow): MrRef => ({\n project: { host: r.forge_host, id: r.forge_project_id, path: r.path_with_namespace, name: r.project_name },\n iid: r.mr_iid,\n author: r.author_username,\n sha: r.sha,\n title: r.title,\n mergedAt: r.merged_at,\n source: r.mr_source,\n});\n\n/** Stable id for a row, assigned the first time it's shared. */\nfunction uidFor(db: DatabaseSync, table: string, id: number, uid: string | null): string {\n if (uid) return uid;\n const next = randomUUID();\n db.prepare(`UPDATE ${table} SET uid = ? WHERE id = ?`).run(next, id);\n return next;\n}\n\n/** This DB's own records for the scope's projects. Assigns uids to rows shared for the first time. */\nexport function collectOwnRecords(db: DatabaseSync, scope: SyncScope): { key: ProjectKey; record: SyncRecord }[] {\n const out: { key: ProjectKey; record: SyncRecord }[] = [];\n const bound = (r: MrRow) => scope.projects.has(projectKey(r.forge_host, r.path_with_namespace));\n const keyOf = (r: MrRow) => projectKey(r.forge_host, r.path_with_namespace);\n const by = scope.member;\n\n const scores = db\n .prepare(`SELECT s.*, ${MR_COLS} FROM scores s JOIN merge_requests mr ON mr.id = s.merge_request_id JOIN projects p ON p.id = mr.project_id WHERE s.origin IS NULL AND p.forge_host IS NOT NULL`)\n .all() as unknown as (MrRow & { id: number; uid: string | null; scored_at: string; source: \"llm_backfill\" | \"llm_live\"; final_score: number; category_scores_json: string; findings_json: string; model_used: string | null; volume_factor: number; base_json: string | null; change_type: string | null })[];\n for (const s of scores.filter(bound)) {\n // The machine score, before anyone's corrections: those are their own records, and every\n // machine recomputes the total. So a teammate's correction never rewrites your review file.\n const machine = s.base_json ? scoreFromBase(JSON.parse(s.base_json) as ScoreBase, []) : { finalScore: s.final_score, categoryScores: JSON.parse(s.category_scores_json) as Record<string, number> };\n const hits = db.prepare(`SELECT * FROM zone_hits WHERE merge_request_id = ? ORDER BY zone_id`).all(s.mr_id) as unknown as { zone_id: string; level: \"red\" | \"amber\" | \"green\"; files_json: string; impact: \"none\" | \"low\" | \"high\" | null; verdict: string | null; vote: \"up\" | \"down\" | null; vote_note: string | null; created_at: string }[];\n out.push({\n key: keyOf(s),\n record: {\n kind: \"review\",\n uid: uidFor(db, \"scores\", s.id, s.uid),\n by,\n mr: mrRef(s),\n scoredAt: s.scored_at,\n source: s.source,\n finalScore: machine.finalScore,\n // Only when set: an untyped review keeps the exact file it had before this field existed.\n ...(s.change_type ? { changeType: s.change_type as ChangeType } : {}),\n categoryScores: machine.categoryScores,\n findings: JSON.parse(s.findings_json),\n modelUsed: s.model_used,\n volumeFactor: s.volume_factor,\n base: s.base_json ? JSON.parse(s.base_json) : null,\n zoneHits: hits.map((h) => ({ zoneId: h.zone_id, level: h.level, files: JSON.parse(h.files_json), impact: h.impact, verdict: h.verdict, vote: h.vote, voteNote: h.vote_note, createdAt: h.created_at })),\n },\n });\n }\n\n const corrections = db\n .prepare(`SELECT c.*, ${MR_COLS} FROM corrections c JOIN merge_requests mr ON mr.id = c.merge_request_id JOIN projects p ON p.id = mr.project_id WHERE c.origin IS NULL AND p.forge_host IS NOT NULL`)\n .all() as unknown as (MrRow & { id: number; uid: string | null; category: string | null; original_score: number; corrected_score: number; reason: string; corrected_note: string | null; created_at: string })[];\n const correctionUids = new Map<number, string>();\n for (const c of corrections.filter(bound)) {\n const uid = uidFor(db, \"corrections\", c.id, c.uid);\n correctionUids.set(c.id, uid);\n out.push({ key: keyOf(c), record: { kind: \"correction\", uid, by, mr: mrRef(c), category: c.category, originalScore: c.original_score, correctedScore: c.corrected_score, reason: c.reason, correctedNote: c.corrected_note, createdAt: c.created_at } });\n }\n\n // An insight goes with its project, or \u2014 when it's for every project on a host \u2014 only if all\n // its evidence comes from this source's projects (it's then filed under the first of them).\n const insights = db.prepare(`SELECT * FROM insights WHERE origin IS NULL AND host IS NOT NULL`).all() as unknown as { id: number; uid: string | null; author_username: string | null; host: string; project_id: number | null; category: string | null; insight_text: string; evidence_mr_ids_json: string; created_at: string }[];\n const mrById = db.prepare(`SELECT ${MR_COLS} FROM merge_requests mr JOIN projects p ON p.id = mr.project_id WHERE mr.id = ?`);\n const projectById = db.prepare(`SELECT forge_host, forge_project_id, path_with_namespace, name FROM projects WHERE id = ?`);\n const insightUids = new Map<number, string>();\n for (const i of insights) {\n const evidence = (JSON.parse(i.evidence_mr_ids_json) as number[]).map((id) => mrById.get(id) as unknown as MrRow | undefined).filter((r): r is MrRow => !!r);\n let key: ProjectKey | undefined;\n let project: z.infer<typeof ProjectRef> | null = null;\n if (i.project_id != null) {\n const p = projectById.get(i.project_id) as unknown as { forge_host: string | null; forge_project_id: string; path_with_namespace: string; name: string } | undefined;\n if (!p?.forge_host) continue;\n key = projectKey(p.forge_host, p.path_with_namespace);\n project = { host: p.forge_host, id: p.forge_project_id, path: p.path_with_namespace, name: p.name };\n } else if (evidence.length > 0 && evidence.every(bound)) {\n key = keyOf(evidence[0]!);\n }\n if (!key || !scope.projects.has(key)) continue;\n const uid = uidFor(db, \"insights\", i.id, i.uid);\n insightUids.set(i.id, uid);\n out.push({ key, record: { kind: \"insight\", uid, by, host: i.host, project, author: i.author_username, category: i.category, text: i.insight_text, evidence: evidence.map(mrRef), createdAt: i.created_at } });\n }\n\n const votes = db\n .prepare(`SELECT v.*, f.file, f.line, f.issue, ${MR_COLS} FROM finding_votes v JOIN findings f ON f.id = v.finding_id JOIN merge_requests mr ON mr.id = f.merge_request_id JOIN projects p ON p.id = mr.project_id WHERE v.origin IS NULL AND p.forge_host IS NOT NULL`)\n .all() as unknown as (MrRow & { id: number; uid: string | null; vote: \"up\" | \"down\"; note: string; correction_id: number | null; insight_id: number | null; created_at: string; file: string | null; line: number | null; issue: string })[];\n for (const v of votes.filter(bound)) {\n out.push({\n key: keyOf(v),\n record: {\n kind: \"vote\",\n uid: uidFor(db, \"finding_votes\", v.id, v.uid),\n by,\n mr: mrRef(v),\n finding: { file: v.file, line: v.line, issue: v.issue },\n vote: v.vote,\n note: v.note,\n correctionUid: v.correction_id != null ? (correctionUids.get(v.correction_id) ?? null) : null,\n insightUid: v.insight_id != null ? (insightUids.get(v.insight_id) ?? null) : null,\n createdAt: v.created_at,\n },\n });\n }\n\n const tags = db\n .prepare(`SELECT t.*, f.file, f.line, f.issue, ${MR_COLS} FROM finding_tags t JOIN findings f ON f.id = t.finding_id JOIN merge_requests mr ON mr.id = f.merge_request_id JOIN projects p ON p.id = mr.project_id WHERE t.origin IS NULL AND p.forge_host IS NOT NULL`)\n .all() as unknown as (MrRow & { id: number; uid: string | null; tag: string; created_at: string; file: string | null; line: number | null; issue: string })[];\n for (const t of tags.filter(bound)) {\n out.push({ key: keyOf(t), record: { kind: \"tag\", uid: uidFor(db, \"finding_tags\", t.id, t.uid), by, mr: mrRef(t), finding: { file: t.file, line: t.line, issue: t.issue }, tag: t.tag, createdAt: t.created_at } });\n }\n return out;\n}\n\nexport interface ExportResult {\n written: string[];\n deleted: string[];\n}\n\n/**\n * Mirrors this DB's own records into the member's folders. A file is only deleted when this DB\n * once wrote it (sync_exported) and the row is gone \u2014 so a fresh DB never wipes what you shared.\n * `dryRun` counts without touching anything (uids still get assigned).\n */\nexport function exportRecords(db: DatabaseSync, scope: SyncScope, dryRun = false): ExportResult {\n const written: string[] = [];\n const deleted: string[] = [];\n const own = collectOwnRecords(db, scope);\n const live = new Set<string>();\n const remember = db.prepare(`INSERT INTO sync_exported (uid, source, path) VALUES (?, ?, ?) ON CONFLICT (uid) DO UPDATE SET source = excluded.source, path = excluded.path`);\n for (const { key, record } of own) {\n const rel = join(relProjectDir(key), \"records\", scope.member, `${record.uid}.json`);\n live.add(record.uid);\n const file = join(scope.dir, rel);\n const text = `${JSON.stringify(record, null, 2)}\\n`;\n if (existsSync(file) && readFileSync(file, \"utf8\") === text) continue;\n written.push(rel);\n if (dryRun) continue;\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, text);\n remember.run(record.uid, scope.name, rel);\n }\n const exported = db.prepare(`SELECT uid, path FROM sync_exported WHERE source = ?`).all(scope.name) as unknown as { uid: string; path: string }[];\n for (const e of exported) {\n if (live.has(e.uid) || ownRowExists(db, e.uid)) continue; // still here, maybe just unbound\n deleted.push(e.path);\n if (dryRun) continue;\n rmSync(join(scope.dir, e.path), { force: true });\n db.prepare(`DELETE FROM sync_exported WHERE uid = ?`).run(e.uid);\n }\n return { written, deleted };\n}\n\nfunction relProjectDir(key: ProjectKey): string {\n return sourceProjectDir(\"\", key).replace(/^[/\\\\]/, \"\");\n}\n\nfunction ownRowExists(db: DatabaseSync, uid: string): boolean {\n return [\"scores\", \"corrections\", \"insights\", \"finding_votes\", \"finding_tags\"].some((t) => !!db.prepare(`SELECT 1 FROM ${t} WHERE uid = ? AND origin IS NULL`).get(uid));\n}\n\n// ---------------------------------------------------------------- import\n\nexport interface ImportResult {\n imported: number;\n /** Own records found in the source but missing here (e.g. a fresh DB), restored as own rows. */\n restored: number;\n removed: number;\n /** Files that failed validation or don't belong where they sit. */\n rejected: string[];\n}\n\n/**\n * Reads every record of the scope's projects. Others' records become rows with origin = the\n * source; this member's own files restore rows a fresh DB lacks. With `prune`, rows imported\n * from this source whose file is gone are deleted \u2014 pass it only after a clean pull.\n */\nexport function importRecords(db: DatabaseSync, scope: SyncScope, prune = false): ImportResult {\n const result: ImportResult = { imported: 0, restored: 0, removed: 0, rejected: [] };\n const seen = new Set<string>();\n const files: { rel: string; record: SyncRecord; own: boolean }[] = [];\n\n for (const key of scope.projects) {\n const recordsDir = join(sourceProjectDir(scope.dir, key), \"records\");\n if (!existsSync(recordsDir)) continue;\n for (const member of readdirSync(recordsDir)) {\n const memberDir = join(recordsDir, member);\n for (const name of readdirSync(memberDir).filter((f) => f.endsWith(\".json\"))) {\n const rel = join(relProjectDir(key), \"records\", member, name);\n const parsed = (() => {\n try {\n return SyncRecord.safeParse(JSON.parse(readFileSync(join(memberDir, name), \"utf8\")));\n } catch {\n return null;\n }\n })();\n // A record must sit in its own project's folder, under its author's member folder.\n if (!parsed?.success || `${parsed.data.uid}.json` !== name || parsed.data.by !== member || !belongsTo(parsed.data, key)) {\n result.rejected.push(rel);\n continue;\n }\n files.push({ rel, record: parsed.data, own: member === scope.member });\n }\n }\n }\n\n // Order matters: votes point at corrections and insights; findings come from reviews.\n const order = [\"review\", \"correction\", \"insight\", \"vote\", \"tag\"];\n files.sort((a, b) => order.indexOf(a.record.kind) - order.indexOf(b.record.kind));\n const remember = db.prepare(`INSERT INTO sync_exported (uid, source, path) VALUES (?, ?, ?) ON CONFLICT (uid) DO NOTHING`);\n db.exec(\"BEGIN\");\n try {\n for (const f of files) {\n seen.add(f.record.uid);\n if (f.own) {\n // Written by this DB and since deleted here: the deletion is waiting for the next export,\n // so don't bring it back (a fresh DB has no sync_exported rows and restores everything).\n if (db.prepare(`SELECT 1 FROM sync_exported WHERE uid = ?`).get(f.record.uid)) continue;\n if (findByUid(db, f.record) === undefined && applyRecord(db, f.record, null)) {\n remember.run(f.record.uid, scope.name, f.rel);\n result.restored++;\n }\n continue;\n }\n if (applyRecord(db, f.record, scope.name)) result.imported++;\n }\n if (prune) result.removed = pruneMissing(db, scope.name, seen);\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw err;\n }\n return result;\n}\n\nfunction belongsTo(r: SyncRecord, key: ProjectKey): boolean {\n if (r.kind === \"insight\") {\n if (r.project) return projectKey(r.project.host, r.project.path) === key;\n return key.startsWith(`${r.host.toLowerCase()}/`) && r.evidence.every((e) => e.project.host.toLowerCase() === r.host.toLowerCase());\n }\n return projectKey(r.mr.project.host, r.mr.project.path) === key;\n}\n\nconst TABLE: Record<SyncRecord[\"kind\"], string> = { review: \"scores\", correction: \"corrections\", insight: \"insights\", vote: \"finding_votes\", tag: \"finding_tags\" };\n\nfunction findByUid(db: DatabaseSync, r: SyncRecord): { id: number; origin: string | null } | undefined {\n return db.prepare(`SELECT id, origin FROM ${TABLE[r.kind]} WHERE uid = ?`).get(r.uid) as unknown as { id: number; origin: string | null } | undefined;\n}\n\nfunction ensureMr(db: DatabaseSync, m: MrRef): number {\n const projectId = upsertProject(db, { host: m.project.host, id: m.project.id, pathWithNamespace: m.project.path, name: m.project.name });\n const existing = db.prepare(`SELECT id FROM merge_requests WHERE project_id = ? AND mr_iid = ?`).get(projectId, m.iid) as unknown as { id: number } | undefined;\n return existing?.id ?? upsertMergeRequest(db, { projectId, mrIid: m.iid, authorUsername: m.author, sha: m.sha, title: m.title, mergedAt: m.mergedAt, source: m.source }).id;\n}\n\nfunction findingId(db: DatabaseSync, mrId: number, f: z.infer<typeof FindingRef>): number | undefined {\n const row = db.prepare(`SELECT id FROM findings WHERE merge_request_id = ? AND file IS ? AND line IS ? AND issue = ?`).get(mrId, f.file, f.line, f.issue) as unknown as { id: number } | undefined;\n return row?.id;\n}\n\n/** Inserts or updates the row for one record. `origin` NULL = restoring this member's own row. Returns whether anything changed. */\nfunction applyRecord(db: DatabaseSync, r: SyncRecord, origin: string | null): boolean {\n const existing = findByUid(db, r);\n if (existing && existing.origin !== origin) return false; // own row vs someone's file: never overwrite yours\n switch (r.kind) {\n case \"review\": {\n const mrId = ensureMr(db, r.mr);\n let target = existing?.id;\n if (target === undefined) {\n // One score per MR and source across the team: the newest review wins.\n const current = db.prepare(`SELECT id, scored_at FROM scores WHERE merge_request_id = ? AND source = ?`).get(mrId, r.source) as unknown as { id: number; scored_at: string } | undefined;\n if (current && current.scored_at >= r.scoredAt) return false;\n target = current?.id;\n }\n const values = [r.scoredAt, r.finalScore, JSON.stringify(r.categoryScores), JSON.stringify(r.findings), r.modelUsed, r.volumeFactor, r.base == null ? null : JSON.stringify(r.base), r.changeType ?? null, r.uid, origin];\n if (target === undefined) {\n db.prepare(`INSERT INTO scores (merge_request_id, source, scored_at, final_score, category_scores_json, findings_json, model_used, volume_factor, base_json, change_type, uid, origin) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(mrId, r.source, ...values);\n } else {\n const before = db.prepare(`SELECT scored_at, findings_json, base_json, change_type FROM scores WHERE id = ?`).get(target) as unknown as { scored_at: string; findings_json: string; base_json: string | null; change_type: string | null };\n if (existing && before.scored_at === r.scoredAt && before.findings_json === values[3] && before.base_json === values[6] && before.change_type === values[7]) return false;\n db.prepare(`UPDATE scores SET scored_at = ?, final_score = ?, category_scores_json = ?, findings_json = ?, model_used = ?, volume_factor = ?, base_json = ?, change_type = ?, uid = ?, origin = ? WHERE id = ?`).run(...values, target);\n }\n db.prepare(`DELETE FROM zone_hits WHERE merge_request_id = ?`).run(mrId);\n const hit = db.prepare(`INSERT INTO zone_hits (merge_request_id, zone_id, level, files_json, impact, verdict, vote, vote_note, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);\n for (const h of r.zoneHits) hit.run(mrId, h.zoneId, h.level, JSON.stringify(h.files), h.impact, h.verdict, h.vote, h.voteNote, h.createdAt);\n upsertFindingsForScore(db, mrId, r.findings);\n refreshScores(db, mrId);\n return true;\n }\n case \"correction\": {\n const mrId = ensureMr(db, r.mr);\n const values = [r.category, r.originalScore, r.correctedScore, r.reason, r.correctedNote, r.createdAt];\n if (existing) {\n const changed = db.prepare(`UPDATE corrections SET category = ?, original_score = ?, corrected_score = ?, reason = ?, corrected_note = ?, created_at = ? WHERE id = ? AND NOT (category IS ? AND original_score = ? AND corrected_score = ? AND reason = ? AND corrected_note IS ? AND created_at = ?)`).run(...values, existing.id, ...values).changes;\n if (!changed) return false;\n } else {\n // created_at as recorded: refreshScores only applies corrections made after the score.\n db.prepare(`INSERT INTO corrections (merge_request_id, category, original_score, corrected_score, reason, corrected_note, created_at, uid, origin) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(mrId, ...values, r.uid, origin);\n }\n refreshScores(db, mrId);\n return true;\n }\n case \"insight\": {\n const projectId = r.project ? upsertProject(db, { host: r.project.host, id: r.project.id, pathWithNamespace: r.project.path, name: r.project.name }) : null;\n const evidence = r.evidence.map((e) => ensureMr(db, e));\n const values = [r.author, r.host, projectId, r.category, r.text, JSON.stringify(evidence), r.createdAt];\n if (existing) {\n return !!db.prepare(`UPDATE insights SET author_username = ?, host = ?, project_id = ?, category = ?, insight_text = ?, evidence_mr_ids_json = ?, created_at = ? WHERE id = ? AND NOT (author_username IS ? AND host IS ? AND project_id IS ? AND category IS ? AND insight_text = ? AND evidence_mr_ids_json = ? AND created_at = ?)`).run(...values, existing.id, ...values).changes;\n }\n db.prepare(`INSERT INTO insights (author_username, host, project_id, category, insight_text, evidence_mr_ids_json, created_at, uid, origin) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(...values, r.uid, origin);\n return true;\n }\n case \"vote\": {\n if (existing) return false; // a vote is replaced by unvoting, which deletes the file\n const fid = findingId(db, ensureMr(db, r.mr), r.finding);\n // One vote per finding: whoever voted first keeps it.\n if (fid === undefined || db.prepare(`SELECT 1 FROM finding_votes WHERE finding_id = ?`).get(fid)) return false;\n const idOf = (table: string, uid: string | null) => (uid ? ((db.prepare(`SELECT id FROM ${table} WHERE uid = ?`).get(uid) as { id: number } | undefined)?.id ?? null) : null);\n db.prepare(`INSERT INTO finding_votes (finding_id, vote, note, correction_id, insight_id, created_at, uid, origin) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(fid, r.vote, r.note, idOf(\"corrections\", r.correctionUid), idOf(\"insights\", r.insightUid), r.createdAt, r.uid, origin);\n return true;\n }\n case \"tag\": {\n if (existing) return false;\n const fid = findingId(db, ensureMr(db, r.mr), r.finding);\n if (fid === undefined) return false;\n return !!db.prepare(`INSERT INTO finding_tags (finding_id, tag, created_at, uid, origin) VALUES (?, ?, ?, ?, ?) ON CONFLICT (finding_id, tag) DO NOTHING`).run(fid, r.tag, r.createdAt, r.uid, origin).changes;\n }\n }\n}\n\n/** Removes rows imported from `source` whose file no longer exists there. */\nfunction pruneMissing(db: DatabaseSync, source: string, seen: Set<string>): number {\n let removed = 0;\n for (const table of [\"finding_tags\", \"finding_votes\", \"insights\", \"corrections\", \"scores\"]) {\n const rows = db.prepare(`SELECT id, uid FROM ${table} WHERE origin = ?`).all(source) as unknown as { id: number; uid: string }[];\n for (const row of rows.filter((r) => !seen.has(r.uid))) {\n const mr = table === \"corrections\" ? (db.prepare(`SELECT merge_request_id FROM corrections WHERE id = ?`).get(row.id) as { merge_request_id: number }).merge_request_id : null;\n if (table === \"insights\") db.prepare(`UPDATE finding_votes SET insight_id = NULL WHERE insight_id = ?`).run(row.id);\n if (table === \"corrections\") db.prepare(`UPDATE finding_votes SET correction_id = NULL WHERE correction_id = ?`).run(row.id);\n db.prepare(`DELETE FROM ${table} WHERE id = ?`).run(row.id);\n if (mr != null) refreshScores(db, mr);\n removed++;\n }\n }\n return removed;\n}\n", "import { execFile } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { userInfo } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport yaml from \"js-yaml\";\nimport { z } from \"zod\";\nimport { scanDiffForSecrets } from \"../../src/checks/secrets.js\";\nimport { parseGitAddress } from \"../../src/forge/index.js\";\nimport { loadConfig, saveConfig, type YolontConfig, type SourceConfig } from \"../config/config.js\";\nimport { DATA_DIR, bareHost, userProjectDir } from \"../paths.js\";\nimport { forgeFor } from \"../forge.js\";\nimport { SyncRecord, exportRecords, importRecords, projectKey, sourceProjectDir, type ImportResult, type ProjectKey, type SyncScope } from \"./records.js\";\n\n/**\n * Memory repos (\"sources\"), git side. Yolont only ever runs the system `git`,\n * so the user's own credentials are used and Yolont never sees a token for these repos.\n */\n\nexport const MANIFEST = \"yolont-source.yaml\";\n/** A memory repo started before the rename keeps its ethos-source.yaml (read and updated in place). */\nconst manifestFile = (dir: string) => (!existsSync(join(dir, MANIFEST)) && existsSync(join(dir, \"ethos-source.yaml\")) ? join(dir, \"ethos-source.yaml\") : join(dir, MANIFEST));\n/** Shared per-project files a source can carry (setup.yaml stays personal, in the user dir). */\nexport const SHARED_FILES = [\"conventions.md\", \"zones.yaml\", \"zones.graph.json\", \"rubric.yml\"] as const;\n\n// review (default on): members push to their own branch and open an MR; only `main` is read.\nconst Manifest = z.object({ projects: z.array(z.string()).default([]), review: z.boolean().default(true) });\n\n/** A repo address for display: drops any `user:token@` from an https URL. */\nexport const displayUrl = (url: string) => url.replace(/^([a-z+]+:\\/\\/)[^@/]*@/i, \"$1\");\n\nexport const sourceDir = (name: string) => join(DATA_DIR, \"sources\", name);\n\nexport class GitError extends Error {}\n\n/** git that never prompts: no credential questions in the middle of the TUI, no hang. */\nexport function git(dir: string, args: string[], timeoutMs = 60_000): Promise<string> {\n // GIT_OPTIONAL_LOCKS=0: read-only commands (the panel's 30 s `git status`) don't take index.lock,\n // so they can't make a running sync fail.\n const env = { ...process.env, GIT_TERMINAL_PROMPT: \"0\", GIT_OPTIONAL_LOCKS: \"0\", GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND ?? \"ssh -o BatchMode=yes\" };\n return new Promise((resolve, reject) => {\n execFile(\"git\", [\"-C\", dir, ...args], { env, timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024 }, (err, stdout, stderr) => {\n if (!err) return resolve(stdout);\n const why = (stderr || err.message).trim().split(\"\\n\").filter(Boolean).at(-1) ?? \"git failed\";\n reject(new GitError((err as { killed?: boolean }).killed ? `timed out (git ${args[0]})` : why));\n });\n });\n}\n\nexport function readManifest(dir: string): Set<ProjectKey> {\n const file = manifestFile(dir);\n if (!existsSync(file)) return new Set();\n const parsed = Manifest.safeParse(yaml.load(readFileSync(file, \"utf8\")) ?? {});\n return new Set(parsed.success ? parsed.data.projects.map((p) => p.toLowerCase()) : []);\n}\n\n/** Review mode: changes go through a merge request (the repo's `review:`; on unless it says false). */\nexport function reviewMode(dir: string): boolean {\n const file = manifestFile(dir);\n if (!existsSync(file)) return true;\n const parsed = Manifest.safeParse(yaml.load(readFileSync(file, \"utf8\")) ?? {});\n return parsed.success ? parsed.data.review : true;\n}\n\nfunction writeManifest(dir: string, projects: Set<ProjectKey>): void {\n const file = manifestFile(dir);\n const current = existsSync(file) ? ((yaml.load(readFileSync(file, \"utf8\")) ?? {}) as Record<string, unknown>) : { review: true };\n writeFileSync(file, `# Yolont memory repo: the projects using it. review: true = members send changes as merge requests.\\n${yaml.dump({ ...current, projects: [...projects].sort() })}`);\n}\n\n/** The git host a memory repo lives on: `host` in config (for a local path), else from its address. */\nexport function sourceHost(source: Pick<SourceConfig, \"url\" | \"host\">): string | null {\n if (source.host) return bareHost(source.host);\n const a = parseGitAddress(source.url);\n return a ? bareHost(a.host) : null;\n}\n\n/** The memory repo's own project path on its host (for opening merge requests), if its address has one. */\nconst sourceRepoPath = (source: SourceConfig) => parseGitAddress(source.url)?.projectPath ?? null;\n\n/** Your member id, created once: a readable name plus a random suffix so two \"alex\"es don't collide. */\nexport function ensureMember(config: YolontConfig, name = userInfo().username): YolontConfig {\n if (config.member) return config;\n const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/(^-|-$)/g, \"\") || \"member\";\n return { ...config, member: { id: `${slug}-${randomBytes(2).toString(\"hex\")}`, name } };\n}\n\n/**\n * Clones a memory repo (or initialises an empty one) and saves it in config. `host`: only for an\n * address with no host in it (a local path); otherwise it must match the address.\n */\nexport async function addSource(name: string, url: string, memberName?: string, host?: string): Promise<SourceConfig> {\n let config = loadConfig();\n const fromUrl = parseGitAddress(url)?.host;\n // An ssh address may use a host alias from ~/.ssh/config (git@github-personal:me/x.git): there\n // --host names the real host. An https address names its host itself.\n const ssh = !/^https?:\\/\\//i.test(url);\n if (host && fromUrl && bareHost(host) !== bareHost(fromUrl) && !ssh) throw new Error(`${displayUrl(url)} is on ${fromUrl}, not ${host}.`);\n if (!host && !fromUrl) throw new Error(\"Can't tell the git host from that address; pass --host <git host> (only projects on that host can use it).\");\n if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) throw new Error(\"Source name: lowercase letters, digits and '-' only.\");\n if ((config.sources ?? []).some((s) => s.name === name)) throw new Error(`A source named '${name}' already exists.`);\n const dir = sourceDir(name);\n if (existsSync(dir)) throw new Error(`${dir} already exists; remove it or pick another name.`);\n mkdirSync(join(DATA_DIR, \"sources\"), { recursive: true });\n await git(join(DATA_DIR, \"sources\"), [\"clone\", \"--quiet\", url, name], 120_000);\n config = ensureMember(config, memberName);\n saveConfig(config); // the commit below is signed with the member name\n if (!existsSync(manifestFile(dir))) {\n // An empty repo: the first commit goes straight to its main branch (there's nothing to review against).\n writeManifest(dir, new Set());\n await commit(dir, \"yolont: start memory repo\");\n await git(dir, [\"push\", \"--quiet\", \"-u\", \"origin\", \"HEAD\"]);\n }\n const source: SourceConfig = { name, url, projects: [], autoSync: true, ...(host && (!fromUrl || bareHost(host) !== bareHost(fromUrl)) ? { host: bareHost(host) } : {}) };\n saveConfig({ ...loadConfig(), sources: [...(loadConfig().sources ?? []), source] });\n return source;\n}\n\nasync function commit(dir: string, message: string): Promise<boolean> {\n await git(dir, [\"add\", \"-A\"]);\n if (!(await git(dir, [\"status\", \"--porcelain\"])).trim()) return false;\n // Identity only for this commit, so it works on machines with no git user configured.\n const name = loadConfig().member?.name ?? \"yolont\";\n await git(dir, [\"-c\", `user.name=${name}`, \"-c\", \"user.email=yolont@localhost\", \"commit\", \"--quiet\", \"-m\", message]);\n return true;\n}\n\n/** A source by name; without a name only when there's exactly one, so data never goes to a guessed repo. */\nexport function getSource(name?: string): SourceConfig {\n const sources = loadConfig().sources ?? [];\n if (!name && sources.length > 1) throw new Error(`Several memory repos (${sources.map((s) => s.name).join(\", \")}): pick one with --source <name>.`);\n const source = name ? sources.find((s) => s.name === name) : sources[0];\n if (!source) throw new Error(name ? `No source named '${name}'.` : \"No team data repo yet: run `yolont source add <name> <git-url>`.\");\n return source;\n}\n\n/** The memory repo you chose for a project (your config only; on the project's own host), if any. */\nexport function sourceFor(host: string, path: string): SourceConfig | undefined {\n const name = projectOwners()(projectKey(bareHost(host), path));\n return name ? getSource(name) : undefined;\n}\n\n/**\n * Which memory repo a project uses, for import, export, prompt memory and the panel (one rule for\n * all): only the one you chose for it, and only if it's on the project's git host. What a repo's\n * manifest lists never binds anything: memory repos switch, they never mix.\n */\nexport function projectOwners(sources: SourceConfig[] = loadConfig().sources ?? []): (key: ProjectKey) => string | null {\n return (key) => {\n const s = sources.find((r) => r.projects.some((p) => p.toLowerCase() === key));\n return s && sourceHost(s) === key.split(\"/\")[0] ? s.name : null;\n };\n}\n\n/** Owner of a DB project row (null host = pre-host legacy row: local). */\nexport function ownerOfProject(db: DatabaseSync, projectId: number, owner: (key: ProjectKey) => string | null): string | null {\n const p = db.prepare(`SELECT forge_host, path_with_namespace FROM projects WHERE id = ?`).get(projectId) as { forge_host: string | null; path_with_namespace: string } | undefined;\n return p?.forge_host ? owner(projectKey(bareHost(p.forge_host), p.path_with_namespace)) : null;\n}\n\n/**\n * The source an insight belongs to: where it was imported from; for your own, where its project\n * (or, for a host-wide one, every evidence MR's project) is owned. `false` = evidence spans sources.\n */\nexport function insightSource(\n db: DatabaseSync,\n i: { origin?: string | null; project_id: number | null; evidence_mr_ids_json: string },\n owner: (key: ProjectKey) => string | null,\n): string | null | false {\n if (i.origin) return i.origin;\n if (i.project_id != null) return ownerOfProject(db, i.project_id, owner);\n const mrProject = db.prepare(`SELECT project_id FROM merge_requests WHERE id = ?`);\n const ids = (JSON.parse(i.evidence_mr_ids_json) as number[]).map((id) => (mrProject.get(id) as { project_id: number } | undefined)?.project_id);\n const owners = new Set(ids.map((pid) => (pid == null ? null : ownerOfProject(db, pid, owner))));\n if (owners.size === 0) return null;\n return owners.size === 1 ? [...owners][0]! : false;\n}\n\n/** Where a project's conventions/zones/rubric live: its team data repo when shared, else the user dir. */\nexport function projectSettingsDir(host: string, path: string): string {\n const source = sourceFor(host, path);\n return source ? sourceProjectDir(sourceDir(source.name), projectKey(bareHost(host), path)) : userProjectDir(host, path);\n}\n\n/**\n * Stops using a project's memory repo: unbinds it and drops what was imported from that repo for\n * it (memory repos switch, they don't mix). Your own records stay; they're in the repo too.\n */\nexport function stopUsing(db: DatabaseSync, host: string, path: string): string | null {\n const key = projectKey(bareHost(host), path);\n const config = loadConfig();\n const source = (config.sources ?? []).find((s) => s.projects.some((p) => p.toLowerCase() === key));\n if (!source) return null;\n saveConfig({ ...config, sources: (config.sources ?? []).map((s) => (s.name === source.name ? { ...s, projects: s.projects.filter((p) => p.toLowerCase() !== key) } : s)) });\n // Re-import the projects still bound with prune: everything else from this repo goes.\n const after = getSource(source.name);\n if (loadConfig().member) importRecords(db, scopes(after).importScope, true);\n return source.name;\n}\n\n/**\n * Disconnects a memory repo on this machine only: its projects go back to your own memory, what\n * was imported from it is dropped, and its local clone is deleted. The repo itself (and what you\n * already sent to it) is untouched. `unsent` (from pendingToSend) is checked by the caller first.\n */\nexport function removeSource(db: DatabaseSync, name: string): void {\n const source = getSource(name);\n const config = loadConfig();\n saveConfig({ ...config, sources: (config.sources ?? []).filter((s) => s.name !== name) });\n // Nothing bound any more: an import with no projects + prune drops every row that came from it.\n if (config.member) importRecords(db, { dir: sourceDir(name), name, member: config.member.id, projects: new Set() }, true);\n db.prepare(`DELETE FROM sync_exported WHERE source = ?`).run(name);\n rmSync(sourceDir(source.name), { recursive: true, force: true });\n}\n\n/** Remembers that a project keeps your own memory only, so the wizard doesn't ask again. */\nexport function keepLocal(host: string, path: string, local = true): void {\n const key = projectKey(bareHost(host), path);\n const config = loadConfig();\n const list = new Set(config.localProjects ?? []);\n if (local) list.add(key);\n else list.delete(key);\n saveConfig({ ...config, localProjects: [...list].sort() });\n}\n\nexport const isKeptLocal = (host: string, path: string) => (loadConfig().localProjects ?? []).includes(projectKey(bareHost(host), path));\n\n/** Memory repos a project may use: the ones on its own git host. */\nexport const sourcesForHost = (host: string) => (loadConfig().sources ?? []).filter((s) => sourceHost(s) === bareHost(host));\n\n/** Starts sharing a project through a source. Your own files are copied in unless the team already has that file. */\nexport async function shareProject(sourceName: string, host: string, path: string): Promise<{ copied: string[]; kept: string[] }> {\n const config = loadConfig();\n const source = getSource(sourceName);\n const key = projectKey(bareHost(host), path);\n if (sourceHost(source) !== bareHost(host)) throw new Error(`'${source.name}' is on ${sourceHost(source) ?? \"an unknown host\"}; ${key} is on ${bareHost(host)}. A project only uses a memory repo on its own git host.`);\n const other = (config.sources ?? []).find((s) => s.name !== source.name && s.projects.includes(key));\n if (other) throw new Error(`${key} uses '${other.name}'. Switch it in the Team data menu (or \\`yolont source use\\`); a project uses one memory repo at a time.`);\n const dir = sourceDir(source.name);\n const manifest = readManifest(dir);\n manifest.add(key);\n writeManifest(dir, manifest);\n\n const copied: string[] = [];\n const kept: string[] = [];\n const target = sourceProjectDir(dir, key);\n for (const f of SHARED_FILES) {\n const mine = join(userProjectDir(host, path), f);\n if (!existsSync(mine)) continue;\n if (existsSync(join(target, f))) kept.push(f);\n else {\n mkdirSync(target, { recursive: true });\n copyFileSync(mine, join(target, f));\n copied.push(f);\n }\n }\n if (!source.projects.includes(key)) saveConfig({ ...config, sources: (config.sources ?? []).map((s) => (s.name === source.name ? { ...s, projects: [...s.projects, key] } : s)) });\n keepLocal(host, path, false);\n return { copied, kept };\n}\n\nfunction scopes(source: SourceConfig): { exportScope: SyncScope; importScope: SyncScope } {\n const member = loadConfig().member?.id;\n if (!member) throw new Error(\"No member id in config; re-add the memory repo.\");\n const dir = sourceDir(source.name);\n // Both directions: only the projects you chose this repo for (what its manifest lists binds nothing).\n const owner = projectOwners();\n const mine = new Set(source.projects.map((p) => p.toLowerCase()).filter((k) => owner(k) === source.name));\n return { exportScope: { dir, name: source.name, member, projects: mine }, importScope: { dir, name: source.name, member, projects: mine } };\n}\n\nexport interface SourceStatus {\n name: string;\n /** Team commits not pulled yet. */\n incoming: number;\n /** Your records and shared-file edits not sent yet, plus unpushed commits. */\n outgoing: number;\n /** Review mode: files you sent that aren't merged into main yet. */\n waiting: number;\n error?: string;\n}\n\n// ---- review mode: your own branch + a merge request; only main is read ----\n\nexport const memberBranch = (member: string) => `yolont/${member}`;\n\n/** The repo's main branch name, from the clone (no network). */\nasync function mainBranch(dir: string): Promise<string> {\n const head = await git(dir, [\"symbolic-ref\", \"--quiet\", \"--short\", \"refs/remotes/origin/HEAD\"]).catch(() => \"\");\n if (head.trim()) return head.trim().replace(/^origin\\//, \"\");\n for (const b of [\"main\", \"master\"]) if (await git(dir, [\"rev-parse\", \"--verify\", \"--quiet\", `refs/remotes/origin/${b}`]).then(() => true, () => false)) return b;\n return \"main\";\n}\n\n/**\n * Puts the clone where this mode works: review mode on your branch `yolont/<member>` (made from the\n * current HEAD, so nothing unsent is lost), always tracking main, so pulls rebase onto main.\n */\nasync function prepareBranch(dir: string, member: string): Promise<{ review: boolean; main: string; branch: string }> {\n const main = await mainBranch(dir);\n const review = reviewMode(dir);\n const branch = memberBranch(member);\n if (review && (await git(dir, [\"rev-parse\", \"--abbrev-ref\", \"HEAD\"])).trim() !== branch) {\n const exists = await git(dir, [\"rev-parse\", \"--verify\", \"--quiet\", `refs/heads/${branch}`]).then(() => true, () => false);\n await git(dir, [\"checkout\", \"--quiet\", ...(exists ? [branch] : [\"-b\", branch])]);\n }\n if (await git(dir, [\"rev-parse\", \"--verify\", \"--quiet\", `refs/remotes/origin/${main}`]).then(() => true, () => false)) {\n await git(dir, [\"branch\", \"--quiet\", `--set-upstream-to=origin/${main}`]);\n }\n return { review, main, branch };\n}\n\nconst count = async (dir: string, range: string) => Number((await git(dir, [\"rev-list\", \"--count\", range]).catch(() => \"0\")).trim()) || 0;\nconst remoteHas = (dir: string, branch: string) => git(dir, [\"rev-parse\", \"--verify\", \"--quiet\", `refs/remotes/origin/${branch}`]).then(() => true, () => false);\n\n/** Commits not on the remote yet: in review mode compared with your pushed branch. */\nasync function unpushed(dir: string, review: boolean, branch: string): Promise<number> {\n return review && (await remoteHas(dir, branch)) ? count(dir, `origin/${branch}..HEAD`) : count(dir, \"@{u}..HEAD\");\n}\n\n/** Files on your branch that main doesn't have yet (what your merge request carries). */\nasync function waitingFiles(dir: string): Promise<string[]> {\n return (await git(dir, [\"diff\", \"--name-only\", \"@{u}...HEAD\"]).catch(() => \"\")).split(\"\\n\").filter(Boolean);\n}\n\nexport interface ReviewRequest {\n branch: string;\n target: string;\n /** The merge request's page, or a link to open one; null when the host is unknown. */\n url: string | null;\n /** Why it wasn't opened for you (no token, unknown host type, \u2026). */\n note?: string;\n waiting: number;\n}\n\n/** What a merge request changes, for its description: what steers reviews first, in plain words. */\nasync function describeChanges(dir: string, files: string[], who: string): Promise<string> {\n const lines: string[] = [];\n let removed = 0;\n for (const rel of files) {\n if (!existsSync(join(dir, rel))) {\n removed++;\n continue;\n }\n if (!rel.includes(\"/records/\")) {\n lines.push(`- shared file: \\`${rel}\\``);\n continue;\n }\n try {\n const r = SyncRecord.parse(JSON.parse(readFileSync(join(dir, rel), \"utf8\")));\n const at = \"mr\" in r ? `${r.mr.project.path} !${r.mr.iid}` : r.project?.path ?? r.host;\n const clip = (t: string) => (t.length > 140 ? `${t.slice(0, 140)}\u2026` : t).replace(/\\s+/g, \" \");\n if (r.kind === \"insight\") lines.unshift(`- **memory** (${at}): ${clip(r.text)}`);\n else if (r.kind === \"correction\") lines.unshift(`- **correction** ${at} [${r.category ?? \"overall\"}] ${r.originalScore} \u2192 ${r.correctedScore}: ${clip(r.reason)}`);\n else if (r.kind === \"vote\") lines.push(`- vote ${r.vote} on \"${clip(r.finding.issue)}\" (${at})${r.note ? `: ${clip(r.note)}` : \"\"}`);\n else if (r.kind === \"tag\") lines.push(`- tag \\`${r.tag}\\` on \"${clip(r.finding.issue)}\" (${at})`);\n else lines.push(`- review ${at}: score ${r.finalScore}, ${r.findings.length} finding(s)`);\n } catch {\n lines.push(`- \\`${rel}\\``);\n }\n }\n if (removed) lines.push(`- removed ${removed} record(s)`);\n const shown = lines.slice(0, 60);\n if (lines.length > shown.length) shown.push(`- \u2026 and ${lines.length - shown.length} more`);\n return `Yolont memory update from **${who}**. Merging it makes these part of every member's reviews.\\n\\n${shown.join(\"\\n\")}\\n`;\n}\n\n/** Opens (or updates) the merge request with your saved token for the repo's host; else a link. */\nasync function requestReview(source: SourceConfig, branch: string, target: string, description: string): Promise<{ url: string | null; note?: string }> {\n const host = sourceHost(source);\n const path = sourceRepoPath(source);\n if (!host || !path) return { url: null, note: `Sent to branch ${branch}; open a merge request into ${target} on the repo's git host.` };\n const config = loadConfig();\n const type = config.forges.find((f) => f.host === host)?.type ?? (host === \"github.com\" ? \"github\" : \"gitlab\");\n const link =\n type === \"github\"\n ? `https://${host}/${path}/compare/${encodeURIComponent(target)}...${encodeURIComponent(branch)}?expand=1`\n : `https://${host}/${path}/-/merge_requests/new?merge_request%5Bsource_branch%5D=${encodeURIComponent(branch)}&merge_request%5Btarget_branch%5D=${encodeURIComponent(target)}`;\n try {\n const forge = forgeFor(host);\n const who = config.member?.name ?? branch;\n const r = await forge.openOrUpdateChangeRequest(path, { sourceBranch: branch, targetBranch: target, title: `Yolont memory: ${who}`, description });\n return { url: r.url };\n } catch (err) {\n return { url: link, note: `Open the merge request yourself (${(err as Error).message})` };\n }\n}\n\n/** Test seam: how a merge request is opened. */\nexport type RequestReview = typeof requestReview;\n\n/**\n * One git operation per repo at a time in this process: the panel's start sync, its button and an\n * after-review sync can overlap, and two git commands in one clone fight over its lock files.\n */\nconst queues = new Map<string, Promise<unknown>>();\nfunction queued<T>(name: string, fn: () => Promise<T>): Promise<T> {\n const next = (queues.get(name) ?? Promise.resolve()).catch(() => {}).then(fn);\n queues.set(name, next);\n return next;\n}\n\n/** Quick check for the wizard: fetch (short timeout) and count both directions. Never throws. */\nexport function checkSource(db: DatabaseSync, source: SourceConfig, timeoutMs = 15_000): Promise<SourceStatus> {\n return queued(source.name, () => checkNow(db, source, timeoutMs));\n}\n\nasync function checkNow(db: DatabaseSync, source: SourceConfig, timeoutMs: number): Promise<SourceStatus> {\n const dir = sourceDir(source.name);\n try {\n await git(dir, [\"fetch\", \"--quiet\", \"--prune\"], timeoutMs);\n const { review, branch } = await prepareBranch(dir, member());\n const incoming = await count(dir, \"HEAD..@{u}\");\n return { name: source.name, incoming, outgoing: await pendingNow(db, source, review, branch), waiting: review ? (await waitingFiles(dir)).length : 0 };\n } catch (err) {\n return { name: source.name, incoming: 0, outgoing: 0, waiting: 0, error: (err as Error).message };\n }\n}\n\nfunction member(): string {\n const id = loadConfig().member?.id;\n if (!id) throw new Error(\"No member id in config; re-add the memory repo.\");\n return id;\n}\n\nasync function pendingNow(db: DatabaseSync, source: SourceConfig, review: boolean, branch: string): Promise<number> {\n const dir = sourceDir(source.name);\n const { written, deleted } = exportRecords(db, scopes(source).exportScope, true);\n const dirty = (await git(dir, [\"status\", \"--porcelain\"]).catch(() => \"\")).split(\"\\n\").filter(Boolean).length;\n return written.length + deleted.length + dirty + (await unpushed(dir, review, branch));\n}\n\n/** Review mode: files you sent that main doesn't have yet (no network; as of the last fetch). */\nexport async function waitingForMerge(source: SourceConfig): Promise<number> {\n const dir = sourceDir(source.name);\n const onBranch = (await git(dir, [\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]).catch(() => \"\")).trim() === memberBranch(member());\n return onBranch ? (await waitingFiles(dir)).length : 0;\n}\n\n/** What's waiting to be sent, without touching the network or the branch (for the menu and panel). */\nexport async function pendingToSend(db: DatabaseSync, source: SourceConfig): Promise<number> {\n const branch = memberBranch(member());\n const onBranch = (await git(sourceDir(source.name), [\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]).catch(() => \"\")).trim() === branch;\n return pendingNow(db, source, onBranch, branch);\n}\n\nasync function pullRebase(dir: string): Promise<void> {\n try {\n // --prune: a merged-and-deleted review branch must not leave a stale lease for the next push.\n await git(dir, [\"fetch\", \"--quiet\", \"--prune\"], 120_000);\n await git(dir, [\"pull\", \"--quiet\", \"--rebase\", \"--autostash\"], 120_000);\n } catch (err) {\n await git(dir, [\"rebase\", \"--abort\"]).catch(() => {});\n throw new GitError(`Couldn't merge the team's changes (${(err as Error).message}). Nothing was lost; resolve it in ${dir} with git, then sync again.`);\n }\n}\n\n/**\n * Review mode: pull --rebase, and when that conflicts only on your own record files (e.g. main has\n * a squash-merged copy of them), rebuild your branch from main instead. Those files are derived\n * from the DB, so the next export writes them again; your unmerged edits of shared files are kept\n * (as working-tree changes). A real conflict on a shared file still stops with the message.\n * Returns true when it rebuilt (the caller must export again).\n */\nasync function pullOrRebuild(dir: string, member: string, main: string): Promise<boolean> {\n try {\n await pullRebase(dir);\n return false;\n } catch (err) {\n const base = (await git(dir, [\"merge-base\", \"HEAD\", `origin/${main}`]).catch(() => \"\")).trim();\n if (!base) throw err;\n const names = async (range: string[]) => (await git(dir, [\"diff\", \"--name-only\", ...range])).split(\"\\n\").filter(Boolean);\n const mine = await names([base, \"HEAD\"]);\n const theirs = new Set(await names([base, `origin/${main}`]));\n const own = (f: string) => f.includes(`/records/${member}/`);\n const shared = mine.filter((f) => !own(f));\n if (shared.some((f) => theirs.has(f))) throw err;\n const keep = shared.map((f) => ({ f, text: existsSync(join(dir, f)) ? readFileSync(join(dir, f)) : null }));\n await git(dir, [\"reset\", \"--quiet\", \"--hard\", `origin/${main}`]);\n for (const { f, text } of keep) {\n if (text === null) rmSync(join(dir, f), { force: true });\n else {\n mkdirSync(join(dir, f, \"..\"), { recursive: true });\n writeFileSync(join(dir, f), text);\n }\n }\n return true;\n }\n}\n\n/** Get the team's updates only. */\nexport function pullSource(db: DatabaseSync, source: SourceConfig): Promise<ImportResult> {\n return queued(source.name, async () => {\n const dir = sourceDir(source.name);\n const { review, main } = await prepareBranch(dir, member());\n if (review) await pullOrRebuild(dir, member(), main);\n else await pullRebase(dir);\n return importRecords(db, scopes(source).importScope, true);\n });\n}\n\nexport interface SyncResult extends ImportResult {\n sent: number;\n deletedShared: number;\n /** Review mode: where your changes wait for a maintainer. */\n review?: ReviewRequest;\n}\n\n/**\n * Send and get: export your records \u2192 gitleaks on exactly what would be pushed (fails closed)\n * \u2192 commit \u2192 pull --rebase onto main \u2192 import \u2192 push. Review mode pushes your own branch and\n * opens/updates its merge request; otherwise main (one retry if someone pushed in between).\n */\nexport function syncSource(db: DatabaseSync, source: SourceConfig, opts: { requestReview?: RequestReview } = {}): Promise<SyncResult> {\n return queued(source.name, () => syncNow(db, source, opts.requestReview ?? requestReview));\n}\n\nasync function syncNow(db: DatabaseSync, source: SourceConfig, openReview: RequestReview, rebuilt = false): Promise<SyncResult> {\n const dir = sourceDir(source.name);\n const { review, main, branch } = await prepareBranch(dir, member());\n const { exportScope, importScope } = scopes(source);\n const { written, deleted } = exportRecords(db, exportScope);\n await git(dir, [\"add\", \"-A\"]);\n const staged = await git(dir, [\"diff\", \"--cached\"]);\n if (staged.trim()) {\n const scan = await scanDiffForSecrets(staged);\n if (scan.scannerFailed || scan.findings.length > 0) {\n // Undo exactly what this export wrote, so a blocked record doesn't sit in the clone and\n // block every later sync; the DB row stays, and the next sync checks it again.\n await git(dir, [\"reset\", \"--quiet\"]);\n for (const rel of written) {\n const tracked = await git(dir, [\"ls-files\", \"--\", rel]);\n if (tracked.trim()) await git(dir, [\"checkout\", \"--quiet\", \"--\", rel]);\n else rmSync(join(dir, rel), { force: true });\n }\n for (const rel of deleted) await git(dir, [\"checkout\", \"--quiet\", \"--\", rel]).catch(() => {});\n db.prepare(`DELETE FROM sync_exported WHERE source = ? AND path IN (SELECT value FROM json_each(?))`).run(source.name, JSON.stringify(written));\n const why = scan.scannerFailed ? `gitleaks couldn't run (${scan.scannerError})` : `gitleaks flagged ${scan.findings.map((f) => `${f.ruleId} at line ${f.line}`).join(\", \")}`;\n throw new Error(`Not sent: ${why}. Nothing left this machine. Remove or fix that review/memory in Yolont, then sync again.`);\n }\n await commit(dir, `yolont sync: ${loadConfig().member?.name ?? exportScope.member}`);\n }\n if (review) {\n // Rebuilt from main: export, scan and commit again on top of it (once).\n if ((await pullOrRebuild(dir, exportScope.member, main)) && !rebuilt) return syncNow(db, source, openReview, true);\n } else await pullRebase(dir);\n const imported = importRecords(db, importScope, true);\n const result: SyncResult = { ...imported, sent: written.length, deletedShared: deleted.length };\n if (review) {\n const files = await waitingFiles(dir);\n if (files.length === 0) return result; // everything you sent is merged\n // Your own branch, rebased onto main on every sync: a lease, not a blind force.\n if ((await unpushed(dir, true, branch)) > 0 || !(await remoteHas(dir, branch))) await git(dir, [\"push\", \"--quiet\", \"--force-with-lease\", \"origin\", `HEAD:refs/heads/${branch}`], 120_000);\n const request = await openReview(source, branch, main, await describeChanges(dir, files, loadConfig().member?.name ?? branch));\n return { ...result, review: { branch, target: main, waiting: files.length, ...request } };\n }\n const push = () => git(dir, [\"push\", \"--quiet\", \"origin\", `HEAD:refs/heads/${main}`], 120_000);\n try {\n await push();\n } catch {\n await pullRebase(dir);\n await push().catch((err: Error) => {\n throw new GitError(/protect/i.test(err.message) ? `${main} is protected: set \\`review: true\\` in ${MANIFEST} (via a merge request) so members send merge requests. (${err.message})` : err.message);\n });\n }\n return result;\n}\n\nexport interface SourceRun {\n name: string;\n result?: ImportResult & Partial<SyncResult>;\n error?: string;\n}\n\n/** Each repo in turn; one failing never stops the others (errors come back per repo). */\nexport async function syncAll(db: DatabaseSync, mode: \"sync\" | \"pull\", sources: SourceConfig[] = loadConfig().sources ?? []): Promise<SourceRun[]> {\n const out: SourceRun[] = [];\n for (const source of sources) {\n try {\n out.push({ name: source.name, result: mode === \"sync\" ? await syncSource(db, source) : await pullSource(db, source) });\n } catch (err) {\n out.push({ name: source.name, error: (err as Error).message });\n }\n }\n return out;\n}\n\n/** One line per repo, for terminals and logs. */\nexport function describeRun(r: SourceRun): string {\n if (r.error) return `${r.name}: not synced: ${r.error}`;\n const x = r.result!;\n const mr = x.review ? `; ${x.review.waiting} file(s) waiting for merge${x.review.url ? `: ${x.review.url}` : \"\"}${x.review.note ? ` (${x.review.note})` : \"\"}` : \"\";\n return `${r.name}: got ${x.imported}, removed ${x.removed}, restored ${x.restored}${x.sent !== undefined ? `, sent ${x.sent}, deleted ${x.deletedShared}` : \"\"}${x.rejected.length ? `, skipped ${x.rejected.length} misplaced file(s)` : \"\"}${mr}`;\n}\n", "import { execFileSync } from \"node:child_process\";\nimport { existsSync, readdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { BUILTIN_CONVENTIONS_DIR, DEFAULT_CONVENTIONS_PATH, DEFAULT_RUBRIC_PATH } from \"../paths.js\";\nimport { projectSettingsDir } from \"../sync/source.js\";\n\n/** Built-in convention files to pick from when a project has none of its own. */\nexport function listConventionFiles(): string[] {\n return readdirSync(BUILTIN_CONVENTIONS_DIR)\n .filter((f) => f.endsWith(\".md\"))\n .sort()\n .map((f) => join(BUILTIN_CONVENTIONS_DIR, f));\n}\n\n/** \"group/app\" -> \"group-app\" \u2014 the pre-Yolont flat file naming (legacy migration only). */\nexport function slugifyProjectPath(pathWithNamespace: string): string {\n return pathWithNamespace\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/(^-|-$)/g, \"\");\n}\n\n/** git@host:g/p.git | https://host/g/p(.git) -> \"g/p\" (lowercase), or null. */\nexport function remoteProjectPath(remoteUrl: string): string | null {\n const m = remoteUrl.trim().match(/^(?:[a-z+]+:\\/\\/)?(?:[^@/]+@)?[^/:]+(?::\\d+)?[:/](.+?)(?:\\.git)?\\/?$/i);\n return m ? m[1]!.toLowerCase() : null;\n}\n\nfunction git(args: string[]): string | null {\n try {\n return execFileSync(\"git\", args, { encoding: \"utf8\", stdio: [\"ignore\", \"pipe\", \"ignore\"] }).trim();\n } catch {\n return null;\n }\n}\n\n/** `<checkout>/.yolont` when cwd is a checkout of this very project (origin matches), else null.\n * The match check matters: reviewing project A from inside a checkout of B must not use B's config. */\nexport function repoYolontDir(pathWithNamespace: string, cwd = process.cwd()): string | null {\n const top = git([\"-C\", cwd, \"rev-parse\", \"--show-toplevel\"]);\n const origin = top && git([\"-C\", top, \"remote\", \"get-url\", \"origin\"]);\n if (!top || !origin || remoteProjectPath(origin) !== pathWithNamespace.toLowerCase()) return null;\n // .ethos/ = the folder's name before the rename; still read.\n return [join(top, \".yolont\"), join(top, \".ethos\")].find((d) => existsSync(d)) ?? null;\n}\n\n/** cwd is a checkout of this project (origin matches) with `sha` checked out at HEAD. */\nexport function isCheckoutOf(pathWithNamespace: string, sha: string, cwd = process.cwd()): boolean {\n const origin = git([\"-C\", cwd, \"remote\", \"get-url\", \"origin\"]);\n return !!origin && remoteProjectPath(origin) === pathWithNamespace.toLowerCase() && git([\"-C\", cwd, \"rev-parse\", \"HEAD\"]) === sha;\n}\n\nexport interface ProjectFiles {\n /** Where this project's files are written (user config dir). */\n dir: string;\n conventions: string | null;\n zones: string | null;\n zonesGraph: string | null;\n rubric: string;\n}\n\n/**\n * Per-project config, first hit wins: the project's own committed `.yolont/` (team-reviewed,\n * also what CI reads) > its team data repo when the project is shared there, else\n * the user's ~/.config/yolont/projects/<host>/<path>/ > built-in rubric.\n * conventions/zones are null when nothing exists \u2014 callers decide the fallback.\n */\nexport function resolveProjectFiles(host: string, pathWithNamespace: string, cwd?: string): ProjectFiles {\n const dir = projectSettingsDir(host, pathWithNamespace);\n const dirs = [repoYolontDir(pathWithNamespace, cwd), dir].filter((d): d is string => !!d);\n const find = (name: string) => dirs.map((d) => join(d, name)).find((p) => existsSync(p)) ?? null;\n return {\n dir,\n conventions: find(\"conventions.md\"),\n zones: find(\"zones.yaml\"),\n zonesGraph: find(\"zones.graph.json\"),\n rubric: find(\"rubric.yml\") ?? DEFAULT_RUBRIC_PATH,\n };\n}\n\nexport { DEFAULT_CONVENTIONS_PATH };\n", "import type { DatabaseSync } from \"node:sqlite\";\nimport { loadZoneGraph, loadZones, matchZones, type Zone, type ZoneReport } from \"../../src/zones/zones.js\";\nimport type { ProjectFiles } from \"../conventions/resolve.js\";\nimport { insightSource, ownerOfProject, projectOwners } from \"../sync/source.js\";\nimport { listAuthorCorrections, listDangerTaggedFindings, listInsights, listZoneHitsForProject, type AuthorKey } from \"../db/repo.js\";\n\n/**\n * The local-DB equivalent of src/history/summarize.ts's summarizeHistoryForPrompt \u2014 but\n * this is what actually closes the memory loop: distilled `insights` and human\n * `corrections` (with their reasons) feed back into the LLM prompt for the next review,\n * which is the whole point of capturing them in the interactive TUI.\n */\nexport function buildAuthorHistorySummary(db: DatabaseSync, author: AuthorKey, projectId: number): string {\n // This text goes into the prompt: host is strict, and a host-wide insight is used only when it\n // belongs to this project's team data repo (company memory never colors a personal review).\n const owner = projectOwners();\n const here = ownerOfProject(db, projectId, owner);\n const insights = listInsights(db, { host: author.host, username: author.username, projectId })\n .filter((i) => insightSource(db, i, owner) === here)\n .slice(0, 5);\n // Imported from a repo that no longer owns this project (shared elsewhere since): left out.\n const corrections = listAuthorCorrections(db, author, 20, projectId)\n .filter((c) => !c.origin || c.origin === here)\n .slice(0, 5);\n\n if (insights.length === 0 && corrections.length === 0) {\n return \"No local memory yet for this author.\";\n }\n\n const lines: string[] = [];\n if (insights.length > 0) {\n lines.push(\"Learned insights:\");\n for (const insight of insights) lines.push(`- ${insight.insight_text}`);\n }\n if (corrections.length > 0) {\n lines.push(\"Recent human corrections (a reviewer disagreed with a prior automated score \u2014 weight these heavily):\");\n for (const c of corrections) {\n const label = c.category ?? \"overall\";\n const reasonSuffix = c.reason?.trim() ? `: ${c.reason}` : \"\";\n lines.push(`- [${label}] was scored ${c.original_score}, human corrected to ${c.corrected_score}${reasonSuffix}`);\n if (c.corrected_note) lines.push(` corrected description: ${c.corrected_note}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * The project's zones matched against `files`, plus zone memory (danger tags, votes). Never\n * prints: notes go to `note`, so the CLI and the MCP server (stdout = protocol) both use it.\n */\nexport function zoneReportFor(\n db: DatabaseSync,\n dbProjectId: number | undefined,\n projectFiles: ProjectFiles,\n files: string[],\n note: (level: \"info\" | \"warn\", msg: string) => void = () => {},\n): ZoneReport | undefined {\n let report: ZoneReport | undefined;\n try {\n const zones = projectFiles.zones ? loadZones(projectFiles.zones) : null;\n if (zones) {\n const graph = projectFiles.zonesGraph ? loadZoneGraph(projectFiles.zonesGraph) : null;\n if (graph) note(\"info\", `Zone graph from ${graph.generated_at}${graph.sha ? ` @ ${graph.sha.slice(0, 8)}` : \"\"}`);\n report = { zones, hits: matchZones(zones, files, graph), verdicts: [] };\n } else note(\"info\", `No zones.yaml in .yolont/ or ${projectFiles.dir} \u2014 only danger-zone tags apply.`);\n } catch (err) {\n note(\"warn\", `${(err as Error).message} \u2014 continuing with danger-zone tags only.`);\n }\n return dbProjectId === undefined ? report : applyZoneMemory(db, dbProjectId, report, files);\n}\n\nexport const FLAGGED_DANGER_ZONE_ID = \"flagged-danger\";\n\n/**\n * Closes the zones memory loop for one project:\n * - files whose earlier findings a reviewer tagged `danger-zone` become a synthetic red\n * zone, matched against this diff in code like any YAML zone \u2014 so it works even for a\n * project with no zones file yet;\n * - past \uD83D\uDC4D/\uD83D\uDC4E votes on each touched zone's verdicts ride along as prompt feedback.\n */\nexport function applyZoneMemory(db: DatabaseSync, projectId: number, report: ZoneReport | undefined, changedFiles: string[]): ZoneReport | undefined {\n const flagged = listDangerTaggedFindings(db, projectId);\n // ponytail: exact file match only; widen to the file's directory if tagged files churn through renames.\n const flaggedHere = [...new Set(flagged.filter((f) => changedFiles.includes(f.file)).map((f) => f.file))];\n\n if (flaggedHere.length > 0) {\n const zone: Zone = {\n id: FLAGGED_DANGER_ZONE_ID,\n level: \"red\",\n paths: [...new Set(flagged.map((f) => f.file))],\n why: \"Reviewers tagged earlier findings in these files as danger-zone\",\n watch_for: [...new Set(flagged.filter((f) => flaggedHere.includes(f.file)).map((f) => f.issue))].slice(0, 5),\n };\n report ??= { zones: [], hits: [], verdicts: [] };\n report = { ...report, zones: [zone, ...report.zones], hits: [{ zone, files: flaggedHere }, ...report.hits] };\n }\n if (!report) return undefined;\n\n const voted = listZoneHitsForProject(db, projectId).filter((h) => h.vote && h.verdict);\n return {\n ...report,\n hits: report.hits.map((hit) => {\n const feedback = voted\n .filter((h) => h.zone_id === hit.zone.id)\n .slice(0, 3)\n .map((h) => `${h.vote === \"down\" ? \"rejected\" : \"confirmed\"} on !${h.mr_iid}: \"${h.verdict}\"${h.vote_note ? ` \u2014 ${h.vote_note}` : \"\"}`);\n return feedback.length > 0 ? { ...hit, feedback } : hit;\n }),\n };\n}\n", "import { spawnSync } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/** This install's version: the nearest package.json named \"yolont\" above this file (bundle or source checkout). */\nexport function ownVersion(from = dirname(fileURLToPath(import.meta.url))): string | undefined {\n for (let dir = from, i = 0; i < 5; dir = dirname(dir), i++) {\n const file = join(dir, \"package.json\");\n if (!existsSync(file)) continue;\n try {\n const pkg = JSON.parse(readFileSync(file, \"utf8\")) as { name?: string; version?: string };\n if (pkg.name === \"yolont\") return pkg.version;\n } catch {\n // unreadable: keep walking\n }\n }\n return undefined;\n}\n\n/** True when `latest` is a higher x.y.z than `current` (pre-release suffixes ignored). */\nexport function isNewer(latest: string, current: string): boolean {\n const parts = (v: string) => v.split(/[-+]/)[0]!.split(\".\").map((n) => Number(n) || 0);\n const [a, b] = [parts(latest), parts(current)];\n for (let i = 0; i < 3; i++) if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) > (b[i] ?? 0);\n return false;\n}\n\n/** The `latest` version on npm, or undefined when offline, slow, or opted out. Sends nothing but the GET. */\nexport async function latestVersion(timeoutMs = 1500): Promise<string | undefined> {\n if (process.env.YOLONT_NO_UPDATE_CHECK || process.env.CI) return undefined;\n try {\n const res = await fetch(\"https://registry.npmjs.org/yolont/latest\", { signal: AbortSignal.timeout(timeoutMs) });\n if (!res.ok) return undefined;\n return ((await res.json()) as { version?: string }).version;\n } catch {\n return undefined;\n }\n}\n\n/** How this copy runs: npx cache, a global/local npm install, or a source checkout (tsx / alias). */\nexport function installKind(script = process.argv[1] ?? \"\"): \"npx\" | \"npm\" | \"source\" {\n if (/[\\\\/]_npx[\\\\/]/.test(script)) return \"npx\";\n if (/[\\\\/]node_modules[\\\\/]yolont[\\\\/]/.test(script) || /[\\\\/]bin[\\\\/]yolont$/.test(script)) return \"npm\";\n return \"source\";\n}\n\n/** Updates a global npm install. Returns false if npm failed (often EACCES on the global folder). */\nexport function installLatest(version: string): boolean {\n return spawnSync(\"npm\", [\"install\", \"-g\", `yolont@${version}`], { stdio: \"inherit\", shell: process.platform === \"win32\" }).status === 0;\n}\n", "import { spawnSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { DATA_DIR } from \"../paths.js\";\n\n/**\n * gitleaks is a Go binary, not an npm package, so `npm install` can't bring it. Instead of a\n * postinstall download (skipped by --ignore-scripts and npx, and a supply-chain smell), the\n * wizard offers to fetch one pinned official release, verified against these SHA-256 sums\n * (copied from that release's checksums.txt), into Yolont's own data dir.\n */\nexport const GITLEAKS_VERSION = \"8.30.1\";\nconst SHA256: Record<string, string> = {\n darwin_arm64: \"b40ab0ae55c505963e365f271a8d3846efbc170aa17f2607f13df610a9aeb6a5\",\n darwin_x64: \"dfe101a4db2255fc85120ac7f3d25e4342c3c20cf749f2c20a18081af1952709\",\n linux_arm64: \"e4a487ee7ccd7d3a7f7ec08657610aa3606637dab924210b3aee62570fb4b080\",\n linux_x64: \"551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb\",\n windows_arm64: \"b95f5e4f5c425cedca7ee203d9afd29597e692c4924a12ed42f970537c72cc0f\",\n windows_x64: \"d29144deff3a68aa93ced33dddf84b7fdc26070add4aa0f4513094c8332afc4e\",\n};\n\nconst win = process.platform === \"win32\";\nexport const LOCAL_GITLEAKS = join(DATA_DIR, \"bin\", win ? \"gitleaks.exe\" : \"gitleaks\");\n\n/** Prefer our downloaded copy when there is one (src/checks/secrets.ts reads YOLONT_GITLEAKS). */\nexport function useLocalGitleaks(env: NodeJS.ProcessEnv = process.env): void {\n if (!env.YOLONT_GITLEAKS && existsSync(LOCAL_GITLEAKS)) env.YOLONT_GITLEAKS = LOCAL_GITLEAKS;\n}\n\nexport const gitleaksWorks = (): boolean => spawnSync(process.env.YOLONT_GITLEAKS || \"gitleaks\", [\"version\"], { stdio: \"ignore\" }).status === 0;\n\n/** The release asset for this machine, or undefined when there's no official build for it. */\nexport function gitleaksAsset(platform = process.platform, arch = process.arch): { name: string; sha256: string } | undefined {\n const os = platform === \"win32\" ? \"windows\" : platform;\n const key = `${os}_${arch === \"x64\" ? \"x64\" : arch === \"arm64\" ? \"arm64\" : arch}`;\n const sha256 = SHA256[key];\n return sha256 ? { name: `gitleaks_${GITLEAKS_VERSION}_${key}.${os === \"windows\" ? \"zip\" : \"tar.gz\"}`, sha256 } : undefined;\n}\n\n/** Downloads, checks the SHA-256, unpacks into DATA_DIR/bin. Throws on any mismatch; nothing is kept then. */\nexport async function installGitleaks(): Promise<string> {\n const asset = gitleaksAsset();\n if (!asset) throw new Error(`No official gitleaks build for ${process.platform}/${process.arch}.`);\n const res = await fetch(`https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/${asset.name}`, { signal: AbortSignal.timeout(120_000) });\n if (!res.ok) throw new Error(`Download failed: HTTP ${res.status}`);\n const bytes = Buffer.from(await res.arrayBuffer());\n const got = createHash(\"sha256\").update(bytes).digest(\"hex\");\n if (got !== asset.sha256) throw new Error(`Checksum mismatch for ${asset.name} (got ${got}). Not installed.`);\n\n const dir = mkdtempSync(join(tmpdir(), \"yolont-gitleaks-dl-\"));\n try {\n const archive = join(dir, asset.name);\n writeFileSync(archive, bytes);\n const exe = win ? \"gitleaks.exe\" : \"gitleaks\";\n // bsdtar (macOS, Windows 10+) reads .zip too; GNU tar on Linux gets .tar.gz.\n const tar = spawnSync(\"tar\", [\"-xf\", archive, \"-C\", dir, exe], { stdio: \"ignore\" });\n if (tar.status !== 0 || !existsSync(join(dir, exe))) throw new Error(\"Couldn't unpack the archive (is `tar` installed?).\");\n mkdirSync(join(DATA_DIR, \"bin\"), { recursive: true });\n copyFileSync(join(dir, exe), LOCAL_GITLEAKS);\n if (!win) chmodSync(LOCAL_GITLEAKS, 0o755);\n } finally {\n rmSync(dir, { recursive: true, force: true });\n }\n process.env.YOLONT_GITLEAKS = LOCAL_GITLEAKS;\n return LOCAL_GITLEAKS;\n}\n", "import { execFileSync } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { CHANGE_TYPE_CHECKS, CHANGE_TYPE_LABELS, hintFromMr, type ChangeTypeGuess } from \"../../src/changeType.js\";\nimport { computeDiffStats } from \"../../src/checks/diffSize.js\";\nimport { scanDiffForSecrets } from \"../../src/checks/secrets.js\";\nimport { parseGitAddress } from \"../../src/forge/index.js\";\nimport { listDiffFiles, omitGeneratedFiles } from \"../../src/git.js\";\nimport { loadRubric } from \"../../src/rubric/loader.js\";\nimport type { ZoneHit } from \"../../src/zones/zones.js\";\nimport { forgeUrl, loadConfig } from \"../config/config.js\";\nimport { resolveProjectFiles, type ProjectFiles } from \"../conventions/resolve.js\";\nimport { openDb } from \"../db/client.js\";\nimport { forgeFor, forgeToken } from \"../forge.js\";\nimport { buildAuthorHistorySummary, zoneReportFor } from \"../memory/context.js\";\nimport { bareHost, DEFAULT_CONVENTIONS_PATH } from \"../paths.js\";\n\n/**\n * The MCP \"coach\": read-only guidance for a coding agent, before and after it writes code.\n * No LLM call, no score, nothing stored or posted. Everything here returns text; nothing\n * prints (the MCP server's stdout is the protocol).\n */\n\nconst CONVENTIONS_CAP = 30_000;\n\ninterface Repo {\n cwd: string;\n host: string;\n projectPath: string;\n files: ProjectFiles;\n}\n\nconst git = (cwd: string, args: string[]) =>\n execFileSync(\"git\", args, { cwd, encoding: \"utf8\", stdio: [\"ignore\", \"pipe\", \"pipe\"], maxBuffer: 50 * 1024 * 1024 }).trimEnd();\n\nfunction repoAt(cwd: string): Repo {\n let origin: string;\n try {\n origin = git(cwd, [\"remote\", \"get-url\", \"origin\"]);\n } catch {\n throw new Error(`${cwd} isn't a git checkout with an 'origin' remote. Run the agent inside your project, or pass repo.`);\n }\n const bases = loadConfig().forges.filter((f) => f.type === \"gitlab\" && f.url).map(forgeUrl);\n const address = parseGitAddress(origin, bases);\n if (!address) throw new Error(\"Couldn't read the project from the 'origin' remote.\");\n return { cwd, host: address.host, projectPath: address.projectPath, files: resolveProjectFiles(address.host, address.projectPath, cwd) };\n}\n\nconst usernames = new Map<string, Promise<string | undefined>>();\n\n/**\n * Your forge username, from the token you saved for this host (never guessed from git config).\n * Only for hosts set up in the wizard; undefined when offline (e.g. VPN off) or not set up.\n */\nfunction myUsername(host: string): Promise<string | undefined> {\n if (!usernames.has(host)) {\n const lookup = async () => {\n if (!loadConfig().forges.some((f) => f.host === host)) return undefined;\n const timeout = new Promise<undefined>((r) => setTimeout(() => r(undefined), 15_000).unref());\n return Promise.race([forgeFor(host).getCurrentUser().then((u) => u.username), timeout]);\n };\n usernames.set(host, lookup().catch(() => undefined));\n }\n return usernames.get(host)!.then((u) => {\n if (!u) usernames.delete(host); // try again next call (VPN may be on by then)\n return u;\n });\n}\n\nfunction projectDbId(db: ReturnType<typeof openDb>, host: string, path: string): number | undefined {\n const row = db.prepare(\"SELECT id FROM projects WHERE forge_host = ? AND path_with_namespace = ?\").get(bareHost(host), path) as { id: number } | undefined;\n return row?.id;\n}\n\nfunction conventionsSection(repo: Repo): string {\n const path = repo.files.conventions ?? DEFAULT_CONVENTIONS_PATH;\n let text = existsSync(path) ? readFileSync(path, \"utf8\").trim() : \"\";\n if (!text) return \"## Team conventions\\n\\nNone set up for this project yet (run `yolont` \u2192 Conventions).\";\n const cut = text.length > CONVENTIONS_CAP;\n if (cut) text = text.slice(0, CONVENTIONS_CAP);\n const from = repo.files.conventions ? \"\" : \" (Yolont's built-in defaults: this project has none of its own yet)\";\n return `## Team conventions${from}\\n\\n${text}${cut ? \"\\n\\n\u2026(cut: the conventions file is longer)\" : \"\"}`;\n}\n\nfunction zonesSection(hits: ZoneHit[], title: string): string {\n if (hits.length === 0) return \"\";\n const lines = hits.map((h) => {\n const z = h.zone;\n return [\n `- **[${z.level}] ${z.id}**${z.why ? `: ${z.why}` : \"\"}`,\n h.files.length ? ` files: ${h.files.join(\", \")}` : ` paths: ${z.paths.join(\", \")}`,\n ...(z.watch_for.length ? [` watch for: ${z.watch_for.join(\"; \")}`] : []),\n ...(h.feedback?.length ? [` past reviewer feedback: ${h.feedback.join(\"; \")}`] : []),\n ].join(\"\\n\");\n });\n return `## ${title}\\n\\nRed zones run on every request or can't be undone: be extra careful there.\\n\\n${lines.join(\"\\n\")}`;\n}\n\nfunction whyNoUsername(host: string): string {\n const saved = loadConfig().forges.find((f) => f.host === host);\n if (!saved) return `${host} isn't set up in Yolont (run \\`yolont\\` once in this repo)`;\n if (!forgeToken(host, saved.type)) return `the ${host} token couldn't be read (the agent may start MCP servers without access to your OS keychain; YOLONT_NO_KEYCHAIN=1 with a credentials file avoids that)`;\n return `${host} isn't reachable right now (VPN?)`;\n}\n\nasync function memorySection(db: ReturnType<typeof openDb>, repo: Repo, dbProjectId: number | undefined): Promise<string> {\n const me = await myUsername(repo.host);\n if (!me) return `## Your past review lessons\\n\\nNot available: ${whyNoUsername(repo.host)}.`;\n if (dbProjectId === undefined) return `## Your past review lessons\\n\\nNo reviews of ${repo.projectPath} in Yolont yet.`;\n const summary = buildAuthorHistorySummary(db, { host: repo.host, username: me }, dbProjectId);\n return `## Your past review lessons (${me})\\n\\nFrom earlier reviews of your PRs: avoid repeating these.\\n\\n${summary}`;\n}\n\n/** `yolont_guidelines`: what the team expects, before or while writing. */\nexport async function guidelines(cwd: string, files?: string[]): Promise<string> {\n const repo = repoAt(cwd);\n const db = openDb();\n try {\n const dbProjectId = projectDbId(db, repo.host, repo.projectPath);\n let zones = \"\";\n if (files?.length) {\n zones = zonesSection(zoneReportFor(db, dbProjectId, repo.files, files)?.hits ?? [], \"Zones these files are in\");\n } else {\n const all = zoneReportFor(db, dbProjectId, repo.files, [])?.zones ?? [];\n zones = zonesSection(all.map((zone) => ({ zone, files: [] }) as ZoneHit), \"The project's zones\");\n }\n return [`# Yolont guidelines: ${repo.host}/${repo.projectPath}`, conventionsSection(repo), zones, await memorySection(db, repo, dbProjectId)].filter(Boolean).join(\"\\n\\n\");\n } finally {\n db.close();\n }\n}\n\n/** Branch names and refs only: a value starting with \"-\" would be read by git as an option. */\nconst SAFE_REF = /^[A-Za-z0-9._\\/][A-Za-z0-9._\\/-]*$/;\n\nfunction resolveBase(cwd: string, base?: string): string {\n if (base) {\n if (!SAFE_REF.test(base)) throw new Error(`Not a branch name: ${base}`);\n return base;\n }\n try {\n return git(cwd, [\"symbolic-ref\", \"--short\", \"refs/remotes/origin/HEAD\"]); // e.g. origin/main\n } catch {\n for (const ref of [\"origin/main\", \"origin/master\", \"main\", \"master\"]) {\n try {\n git(cwd, [\"rev-parse\", \"--verify\", \"--quiet\", ref]);\n return ref;\n } catch {\n // next\n }\n }\n }\n throw new Error(\"Couldn't find the base branch. Pass base (e.g. origin/main).\");\n}\n\nfunction changeTypeOf(branch: string, subjects: string[]): ChangeTypeGuess | null {\n for (const title of subjects) {\n const hint = hintFromMr({ title, sourceBranch: branch });\n if (hint) return hint;\n }\n return hintFromMr({ title: \"\", sourceBranch: branch });\n}\n\n/** `yolont_check_my_changes`: a checklist for the local branch (committed + staged + unstaged). */\nexport async function checkMyChanges(cwd: string, opts: { base?: string; fetch?: boolean } = {}): Promise<string> {\n const repo = repoAt(cwd);\n const base = resolveBase(cwd, opts.base);\n if (opts.fetch && base.startsWith(\"origin/\")) git(cwd, [\"fetch\", \"--quiet\", \"origin\", base.slice(\"origin/\".length)]);\n const mergeBase = git(cwd, [\"merge-base\", base, \"HEAD\"]);\n const branch = git(cwd, [\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\n const { text, omittedFiles } = omitGeneratedFiles(git(cwd, [\"diff\", mergeBase]));\n const untracked = git(cwd, [\"ls-files\", \"--others\", \"--exclude-standard\"]).split(\"\\n\").filter(Boolean);\n const files = listDiffFiles(text);\n const diffCmd = `git diff ${mergeBase.slice(0, 12)}`;\n\n const head = `# Yolont pre-PR checklist: ${branch} vs ${base}`;\n if (files.length === 0) {\n return `${head}\\n\\nNo changes against ${base} yet${untracked.length ? ` (untracked files aren't checked until you \\`git add\\` them: ${untracked.join(\", \")})` : \"\"}.`;\n }\n\n const stats = computeDiffStats(text);\n const maxLines = loadRubric(repo.files.rubric).max_lines;\n const total = stats.added + stats.deleted;\n const subjects = git(cwd, [\"log\", \"--format=%s\", `${mergeBase}..HEAD`]).split(\"\\n\").filter(Boolean);\n const type = changeTypeOf(branch, subjects);\n const secrets = await scanDiffForSecrets(text);\n\n const db = openDb();\n try {\n const dbProjectId = projectDbId(db, repo.host, repo.projectPath);\n const report = zoneReportFor(db, dbProjectId, repo.files, files);\n const sections = [\n head,\n `Your changes: \\`${diffCmd}\\` \u2014 ${files.length} file(s), +${stats.added}/-${stats.deleted}.` +\n (omittedFiles.length ? ` Generated files skipped: ${omittedFiles.join(\", \")}.` : \"\") +\n (untracked.length ? ` Untracked (not checked; \\`git add\\` them to include): ${untracked.join(\", \")}.` : \"\"),\n secrets.scannerFailed\n ? `## Secrets: \u26A0 the scan didn't run\\n\\n${secrets.scannerError}. Install gitleaks (or run \\`yolont\\`, which offers to); the PR review won't send an unscanned diff to an LLM.`\n : secrets.findings.length\n ? `## Secrets: \u2717 ${secrets.findings.length} possible secret(s)\\n\\nRemove these before pushing (a real key must also be rotated). Not a secret? Add a \\`gitleaks:allow\\` comment on the line.\\n\\n${secrets.findings.map((f) => `- ${f.file}:${f.line} ${f.ruleId}`).join(\"\\n\")}`\n : \"## Secrets: \u2713 none found\",\n total > maxLines\n ? `## Size: \u2717 ${total} changed lines, over the team's ${maxLines}-line guideline\\n\\nBig PRs score lower and get worse reviews. Can it be split?`\n : `## Size: \u2713 ${total} changed lines (guideline: ${maxLines})`,\n type\n ? `## Change type: ${CHANGE_TYPE_LABELS[type.type]} (${type.reason})\\n\\n${CHANGE_TYPE_CHECKS[type.type]}`\n : \"## Change type: unknown\\n\\nName the branch or commit like `fix/\u2026`, `feat: \u2026`, `refactor: \u2026` so the review applies the right checks.\",\n zonesSection(report?.hits ?? [], \"Zones you touched\"),\n conventionsSection(repo),\n await memorySection(db, repo, dbProjectId),\n `## How to use this\\n\\nRead \\`${diffCmd}\\` and check it against every section above: each convention, each zone's \"watch for\", the change type's checks, and your past lessons. Fix what fails, then call yolont_check_my_changes again. Nothing here is a score: the real review happens on the PR.`,\n ];\n return sections.filter(Boolean).join(\"\\n\\n\");\n } finally {\n db.close();\n }\n}\n", "import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { z } from \"zod\";\nimport { ownVersion } from \"../setup/version.js\";\nimport { checkMyChanges, guidelines } from \"./coach.js\";\n\nconst text = (t: string) => ({ content: [{ type: \"text\" as const, text: t }] });\nconst failed = (err: unknown) => ({ ...text(`Yolont: ${(err as Error).message}`), isError: true });\nconst repoArg = z.string().optional().describe(\"Path to the project checkout. Default: the directory the agent started the server in.\");\n\n/** The coach: two read-only tools and one prompt. No LLM call, no score, nothing stored or posted. */\nexport function createCoachServer(cwd = process.cwd()): McpServer {\n const server = new McpServer({ name: \"yolont\", version: ownVersion() ?? \"0.0.0\" });\n /**\n * Which checkout: the tool's `repo` arg, else the project the agent says it's in\n * (CLAUDE_PROJECT_DIR, then the client's first file:// root), else where we were started.\n */\n const at = async (repo?: string): Promise<string> => {\n if (repo) return resolve(cwd, repo);\n if (process.env.CLAUDE_PROJECT_DIR) return process.env.CLAUDE_PROJECT_DIR;\n if (server.server.getClientCapabilities()?.roots) {\n const roots = await server.server.listRoots().catch(() => ({ roots: [] }));\n const root = roots.roots.find((r) => r.uri.startsWith(\"file://\"));\n if (root) return fileURLToPath(root.uri);\n }\n return cwd;\n };\n\n server.registerTool(\n \"yolont_guidelines\",\n {\n title: \"Team guidelines\",\n description:\n \"This project's coding conventions, its risky zones (what runs on every request or can't be undone, and what to watch for there), and the lessons from past reviews of YOUR PRs. Call it before or while writing code. Pass the files you plan to touch to see only their zones.\",\n inputSchema: { files: z.array(z.string()).optional().describe(\"Repo-relative paths you will change.\"), repo: repoArg },\n annotations: { readOnlyHint: true, openWorldHint: false },\n },\n async ({ files, repo }) => guidelines(await at(repo), files).then(text, failed),\n );\n\n server.registerTool(\n \"yolont_check_my_changes\",\n {\n title: \"Pre-PR checklist\",\n description:\n \"A checklist for your local branch before you open a PR: a local secret scan, size, change-type checks (e.g. a bug fix needs a regression test), the zones you touched, the team conventions, and your past review lessons. Covers committed, staged and unstaged changes against the base branch. Check the diff against each item, fix what fails, call again. It doesn't score anything.\",\n inputSchema: {\n base: z.string().optional().describe(\"Base branch to compare with, e.g. origin/main. Default: origin's default branch.\"),\n fetch: z.boolean().optional().describe(\"git fetch the base first (may need network/VPN). Default false.\"),\n repo: repoArg,\n },\n annotations: { readOnlyHint: true, openWorldHint: false },\n },\n async ({ base, fetch, repo }) => checkMyChanges(await at(repo), { base, fetch }).then(text, failed),\n );\n\n server.registerPrompt(\n \"yolont-check\",\n { title: \"Check my changes with Yolont\", description: \"Check the current branch against the team's conventions, zones and your past lessons, and fix what fails.\" },\n () => ({\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: \"Call the yolont_check_my_changes tool. Then read the diff it names and check it against every section: secrets, size, the change type's checks, each zone's 'watch for', each team convention, and my past lessons. List what fails with file:line, fix each one (ask me first if a fix changes behavior), and call yolont_check_my_changes again until nothing fails. Don't invent rules that aren't in the checklist.\",\n },\n },\n ],\n }),\n );\n\n return server;\n}\n\n/** `yolont mcp`: stdio only. stdout carries the protocol, so stray console output goes to stderr. */\nexport async function runMcpServer(): Promise<void> {\n console.log = console.info = console.debug = console.error;\n await createCoachServer().connect(new StdioServerTransport());\n}\n", "import { existsSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { parseArgs } from \"node:util\";\nimport { openDb } from \"./db/client.js\";\nimport { findProjectId, stampLegacyProjectHost } from \"./db/repo.js\";\nimport { runBackfill } from \"./mining/backfill.js\";\nimport { runDistill } from \"./memory/distill.js\";\nimport { runInteractiveReview } from \"./review/interactiveReview.js\";\nimport { runSyncReplies } from \"./review/syncReplies.js\";\nimport { startDashboard } from \"./backoffice/server.js\";\nimport { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { parseEnv } from \"node:util\";\nimport { password } from \"@clack/prompts\";\nimport { resolveProjectFiles } from \"./conventions/resolve.js\";\nimport { defaultForgeHost, forgeFor, parseChange } from \"./forge.js\";\nimport { runSetup } from \"./setup/wizard.js\";\nimport type { Step } from \"./setup/state.js\";\nimport type { ForgeClient, ProjectRef } from \"../src/forge/types.js\";\nimport { applyConfigToEnv, CONFIG_PATH, forgeUrl, loadConfig, saveConfig } from \"./config/config.js\";\nimport { importEnv } from \"./config/importEnv.js\";\nimport { CREDENTIALS_PATH, deleteSecret, getSecret, maskSecret, secretBackend, setSecret } from \"./config/secrets.js\";\nimport { migrateLegacyState } from \"./legacyMigrate.js\";\nimport { addSource, describeRun, displayUrl, getSource, keepLocal, pendingToSend, removeSource, reviewMode, shareProject, sourceDir, sourceFor, sourceHost, sourcesForHost, stopUsing, syncAll } from \"./sync/source.js\";\nimport { parseGitAddress } from \"../src/forge/index.js\";\nimport { bareHost } from \"./paths.js\";\nimport { buildZoneGraph } from \"./zones/graph.js\";\nimport { loadZones, renderZonesMermaid } from \"../src/zones/zones.js\";\n\n// Precedence: shell env > ~/.config/yolont (config.yaml + secrets). An old .env is moved in\n// once with `yolont config import-env <path>`.\n\n/** `<MR/PR URL>` or legacy `<project-id> <mr-iid>` (on the default forge). */\nfunction changeArgs(positionals: string[], usage: string): { forge: ForgeClient; project: ProjectRef; mrIid: number } {\n const ref = positionals[0] ? parseChange(positionals[0]) : null;\n if (ref) return { forge: forgeFor(ref.host, ref.type), project: ref.projectPath, mrIid: ref.number };\n const project = Number(positionals[0]);\n const mrIid = Number(positionals[1]);\n if (!project || !mrIid) throw new Error(`Usage: ${usage}`);\n return { forge: forgeFor(defaultForgeHost()), project, mrIid };\n}\n\n/** `<project-id | group/project>` on `--host` (default forge). */\nfunction projectArg(arg: string | undefined, host: string | undefined, usage: string): { forge: ForgeClient; project: ProjectRef } {\n if (!arg) throw new Error(`Usage: ${usage}`);\n return { forge: forgeFor(host ?? defaultForgeHost()), project: /^\\d+$/.test(arg) ? Number(arg) : arg };\n}\n\n/** `yolont config \u2026` \u2014 inspect and fill ~/.config/yolont. The setup wizard (Phase 2) builds on this. */\nasync function runConfigCommand(args: string[]): Promise<void> {\n const [sub, arg] = args;\n const config = loadConfig();\n if (sub === \"import-env\") {\n if (!arg) throw new Error(\"Usage: yolont config import-env <path to .env>\");\n const path = resolve(arg);\n if (!existsSync(path)) throw new Error(`No env file at ${path}`);\n const { config: next, secrets, skipped } = importEnv(parseEnv(readFileSync(path, \"utf8\")), config);\n for (const [name, value] of Object.entries(secrets)) setSecret(name, value);\n saveConfig(next);\n console.log(`Wrote ${CONFIG_PATH}; ${Object.keys(secrets).length} secret(s) saved to ${secretBackend()}.`);\n for (const s of skipped) console.log(` skipped: ${s}`);\n console.log(`Secrets are now in ${secretBackend()}: delete ${path} once \\`yolont config show\\` looks right.`);\n return;\n }\n if (sub === \"set-secret\" || sub === \"delete-secret\") {\n if (!arg) throw new Error(`Usage: yolont config ${sub} <forge:<host> | llm:<profile> | jev>`);\n if (sub === \"delete-secret\") {\n deleteSecret(arg);\n console.log(`Deleted ${arg}.`);\n return;\n }\n const value = await password({ message: `Value for ${arg}` });\n if (typeof value !== \"string\" || !value.trim()) return;\n setSecret(arg, value.trim());\n console.log(`Saved ${arg} to ${secretBackend()}.`);\n return;\n }\n if (sub && sub !== \"show\") throw new Error(\"Usage: yolont config [show | import-env <path> | set-secret <name> | delete-secret <name>]\");\n\n console.log(`Config: ${CONFIG_PATH}${existsSync(CONFIG_PATH) ? \"\" : \" (not created yet)\"}`);\n console.log(`Secrets: ${secretBackend()}${secretBackend() === \"keychain\" ? \"\" : ` \u2014 ${CREDENTIALS_PATH}`}`);\n console.log(\"\\nForges:\");\n for (const f of config.forges) console.log(` ${f.host === config.defaultForge ? \"*\" : \" \"} ${f.host} ${f.type} ${forgeUrl(f)} token ${maskSecret(getSecret(`forge:${f.host}`))}`);\n console.log(\"\\nLLM profiles:\");\n for (const p of config.llmProfiles)\n console.log(` ${p.name === config.defaultLlmProfile ? \"*\" : \" \"} ${p.name} ${p.provider} ${p.model}${p.baseUrl ? ` ${p.baseUrl}` : \"\"} key ${p.provider === \"ollama\" ? \"(none needed)\" : maskSecret(getSecret(`llm:${p.name}`))}`);\n console.log(`\\nJev: key ${maskSecret(getSecret(\"jev\"))}${config.jev?.disabled ? \" (disabled)\" : \"\"}`);\n}\n\nasync function main(): Promise<void> {\n const [command, ...rest] = process.argv.slice(2);\n if (command === \"config\") return runConfigCommand(rest);\n if (command === \"--version\" || command === \"-v\" || command === \"version\") {\n const { ownVersion } = await import(\"./setup/version.js\");\n console.log(ownVersion() ?? \"unknown\");\n return;\n }\n applyConfigToEnv(loadConfig());\n (await import(\"./setup/gitleaks.js\")).useLocalGitleaks();\n // ponytail: legacy data has no host, so it's assumed to belong to CI_SERVER_URL; drop with the DB host migration.\n // Only into the default dirs: a sandbox (YOLONT_CONFIG_DIR / YOLONT_DATA_DIR, e.g. a fresh-setup\n // test) must never get a copy of the old install-dir DB \u2014 it holds colleagues' review data.\n const sandboxed = !!(process.env.YOLONT_CONFIG_DIR || process.env.YOLONT_DATA_DIR);\n const migrated = sandboxed ? [] : migrateLegacyState(process.env.CI_SERVER_URL);\n if (migrated.length > 0) console.error(`[yolont] copied pre-Yolont data to the user dirs:\\n${migrated.map((p) => ` ${p}`).join(\"\\n\")}`);\n // Must run before any upsertProject: a host-less legacy row never conflicts (NULL), so it'd be duplicated.\n if (process.env.CI_SERVER_URL) {\n const db = openDb();\n const stamped = stampLegacyProjectHost(db, process.env.CI_SERVER_URL);\n db.close();\n if (stamped > 0) console.error(`[yolont] ${stamped} pre-Yolont project(s) assigned to ${process.env.CI_SERVER_URL}.`);\n }\n\n // Bare `yolont` in a terminal: ask for whatever setup is missing, then pick a PR to review.\n if (!command && process.stdin.isTTY) return runSetup({ review: true });\n\n switch (command) {\n case \"mcp\": {\n const { runMcpServer } = await import(\"./mcp/server.js\");\n await runMcpServer();\n return;\n }\n\n case \"setup\": {\n const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { step: { type: \"string\", multiple: true } } });\n const steps = values.step as Step[] | undefined;\n const bad = steps?.find((s) => ![\"forge\", \"llm\", \"conventions\", \"zones\", \"weights\"].includes(s));\n if (bad) throw new Error(`Unknown step '${bad}' \u2014 one of: forge, llm, conventions, zones, weights`);\n if (!process.stdin.isTTY) throw new Error(\"setup is interactive \u2014 run it in a terminal.\");\n await runSetup({ address: positionals[0], steps, all: !steps });\n return;\n }\n\n case \"conventions\": {\n const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { repo: { type: \"string\" } } });\n const action = positionals[0];\n if (action !== \"generate\" && action !== \"edit\") throw new Error(\"Usage: yolont conventions generate|edit [<git address | MR/PR URL>] [--repo <checkout>]\");\n if (!process.stdin.isTTY) throw new Error(\"conventions is interactive \u2014 run it in a terminal.\");\n await runSetup({ address: positionals[1], steps: [\"conventions\"], conventions: action, repo: values.repo && resolve(values.repo) });\n return;\n }\n\n case \"backfill\": {\n const { values, positionals } = parseArgs({\n args: rest,\n allowPositionals: true,\n options: {\n host: { type: \"string\" },\n \"max-mrs\": { type: \"string\", default: \"1000\" },\n \"with-llm\": { type: \"boolean\", default: false },\n zones: { type: \"boolean\", default: false },\n },\n });\n await runBackfill({\n ...projectArg(positionals[0], values.host, \"yolont backfill <project-id | group/project> [--host h] [--max-mrs 1000] [--with-llm] [--zones]\"),\n maxMrs: Number(values[\"max-mrs\"]),\n withLlm: Boolean(values[\"with-llm\"]),\n zones: Boolean(values.zones),\n });\n return;\n }\n\n case \"review\": {\n const { values, positionals } = parseArgs({\n args: rest,\n allowPositionals: true,\n options: {\n \"pipeline-id\": { type: \"string\" },\n focus: { type: \"string\" },\n },\n });\n // No target: same as bare `yolont` \u2014 setup check, then the open-PR picker.\n if (positionals.length === 0) {\n if (!process.stdin.isTTY) throw new Error('Usage: yolont review <MR/PR URL> | <project-id> <mr-iid> [--pipeline-id N] [--focus \"...\"]');\n return runSetup({ review: true });\n }\n await runInteractiveReview({\n ...changeArgs(positionals, 'yolont review <MR/PR URL> | <project-id> <mr-iid> [--pipeline-id N] [--focus \"...\"]'),\n pipelineId: values[\"pipeline-id\"] ? Number(values[\"pipeline-id\"]) : undefined,\n reviewerFocus: values.focus,\n });\n return;\n }\n\n case \"sync-replies\": {\n const { positionals } = parseArgs({ args: rest, allowPositionals: true, options: {} });\n await runSyncReplies(changeArgs(positionals, \"yolont sync-replies <MR/PR URL> | <project-id> <mr-iid>\"));\n return;\n }\n\n case \"distill\": {\n const { values } = parseArgs({\n args: rest,\n options: {\n author: { type: \"string\" },\n project: { type: \"string\" },\n host: { type: \"string\" },\n },\n });\n const db = openDb();\n // --project is the forge's project id (as everywhere on the CLI); memory is keyed by Yolont's own id.\n const projectId = values.project ? findProjectId(db, values.host ?? defaultForgeHost(), values.project) : undefined;\n if (values.project && projectId === undefined) throw new Error(`Project ${values.project} isn't in the DB yet \u2014 review or backfill it first.`);\n const author = values.author ? { host: bareHost(values.host ?? defaultForgeHost()), username: values.author } : undefined;\n await runDistill(db, { author, projectId });\n db.close();\n return;\n }\n\n case \"panel\":\n case \"dashboard\": {\n const { values } = parseArgs({\n args: rest,\n options: {\n port: { type: \"string\", default: \"4173\" },\n },\n });\n // Clients are made per finding's host on demand; a host without a token fails that sync only.\n await startDashboard({ port: Number(values.port), forgeFor: (host) => forgeFor(host) });\n return;\n }\n\n case \"zones\": {\n const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { repo: { type: \"string\" }, host: { type: \"string\" } } });\n if (positionals[0] === \"generate\" || positionals[0] === \"edit\") {\n if (!process.stdin.isTTY) throw new Error(\"zones generate|edit is interactive \u2014 run it in a terminal.\");\n await runSetup({ address: positionals[1], steps: [\"zones\"], zones: positionals[0], repo: values.repo && resolve(values.repo) });\n return;\n }\n const graphMode = positionals[0] === \"graph\";\n const projectPath = graphMode ? positionals[1] : positionals[0];\n if (!projectPath || (graphMode && !values.repo)) {\n throw new Error(\"Usage: yolont zones <group/project> | yolont zones graph <group/project> --repo <checkout>\");\n }\n const files = resolveProjectFiles(values.host ?? defaultForgeHost(), projectPath);\n const zones = files.zones ? loadZones(files.zones) : null;\n if (!zones) throw new Error(`No zones.yaml in .yolont/ or ${files.dir}`);\n if (!graphMode) {\n console.log(renderZonesMermaid(zones));\n return;\n }\n console.log(`[zones] building import graph of ${values.repo} (can take a while on big repos)\u2026`);\n const graph = await buildZoneGraph(values.repo!, zones);\n mkdirSync(files.dir, { recursive: true });\n const out = join(files.dir, \"zones.graph.json\");\n writeFileSync(out, `${JSON.stringify(graph, null, 2)}\\n`);\n for (const [id, files] of Object.entries(graph.reachable)) console.log(` ${id}: ${files.length} file(s) reachable via import`);\n console.log(`[zones] wrote ${out}${graph.sha ? ` (@ ${graph.sha.slice(0, 8)})` : \"\"} \u2014 for CI, commit it to the target repo as .yolont/zones.graph.json`);\n return;\n }\n\n case \"source\": {\n const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { source: { type: \"string\" }, name: { type: \"string\" }, host: { type: \"string\" }, force: { type: \"boolean\", default: false } } });\n const [action, a, b] = positionals;\n const addressOf = (raw: string) => {\n const address = parseGitAddress(raw, loadConfig().forges.filter((f) => f.type === \"gitlab\" && f.url).map(forgeUrl));\n if (!address) throw new Error(`Not a git address: ${raw}`);\n return address;\n };\n if (action === \"add\" && a && b) {\n const source = await addSource(a, b, values.name, values.host);\n console.log(`Connected memory repo '${source.name}' (${sourceDir(source.name)}). Use it for a project with: yolont source use <git address> --source ${source.name}`);\n return;\n }\n if ((action === \"use\" || action === \"share\") && a) {\n const address = addressOf(a);\n // Pick by name, or the only repo on the project's host: never one from another host.\n const onHost = sourcesForHost(address.host);\n if (!values.source && onHost.length !== 1) throw new Error(onHost.length ? `Several memory repos on ${address.host} (${onHost.map((s) => s.name).join(\", \")}): pick one with --source <name>.` : `No memory repo on ${address.host} yet: yolont source add <name> <git-url>.`);\n const source = values.source ? getSource(values.source) : onHost[0]!;\n const db = openDb();\n try {\n const current = sourceFor(address.host, address.projectPath);\n if (current?.name === source.name) {\n console.log(`${address.host}/${address.projectPath} already uses '${source.name}'.`);\n return;\n }\n if (current) stopUsing(db, address.host, address.projectPath);\n const { copied, kept } = await shareProject(source.name, address.host, address.projectPath);\n console.log(`${address.host}/${address.projectPath} now uses memory repo '${source.name}'${current ? ` (was '${current.name}')` : \"\"}.${copied.length ? ` Moved in: ${copied.join(\", \")}.` : \"\"}${kept.length ? ` The repo's ${kept.join(\", \")} kept (yours stays in the user dir).` : \"\"} Run \\`yolont sync\\` to get and send.`);\n } finally {\n db.close();\n }\n return;\n }\n if (action === \"stop\" && a) {\n const address = addressOf(a);\n const db = openDb();\n try {\n const was = stopUsing(db, address.host, address.projectPath);\n keepLocal(address.host, address.projectPath);\n console.log(was ? `${address.host}/${address.projectPath} no longer uses '${was}'; only your own memory from now on.` : \"That project doesn't use a memory repo.\");\n } finally {\n db.close();\n }\n return;\n }\n if (action === \"rm\" && a) {\n const db = openDb();\n try {\n const unsent = await pendingToSend(db, getSource(a)).catch(() => 0);\n if (unsent && !values.force) throw new Error(`'${a}' has ${unsent} change(s) of yours that were never sent; run \\`yolont sync --source ${a}\\` first, or pass --force to drop them.`);\n removeSource(db, a);\n console.log(`Removed memory repo '${a}' from this machine (its local copy and what came from it). The repo itself is untouched.`);\n } finally {\n db.close();\n }\n return;\n }\n if (action === \"ls\" || !action) {\n const config = loadConfig();\n if (!config.sources?.length) console.log(\"No memory repos. Add one: yolont source add <name> <git-url>\");\n for (const src of config.sources ?? []) console.log(`${src.name} ${displayUrl(src.url)} (${sourceHost(src) ?? \"?\"}${reviewMode(sourceDir(src.name)) ? \", merge requests\" : \", direct push\"})\\n used by: ${src.projects.map((p) => (p.split(\"/\")[0] === sourceHost(src) ? p : `${p} (ignored: not on ${sourceHost(src) ?? \"its host\"})`)).join(\", \") || \"(nothing yet)\"}`);\n if (config.member) console.log(`\\nYou are '${config.member.name}' (records folder ${config.member.id}).`);\n return;\n }\n throw new Error(\"Usage: yolont source add <name> <git-url> [--name <your name>] [--host <git host>] | yolont source use <git address> [--source <name>] | yolont source stop <git address> | yolont source rm <name> [--force] | yolont source ls\");\n }\n\n case \"sync\": {\n const { values } = parseArgs({ args: rest, options: { source: { type: \"string\" }, pull: { type: \"boolean\", default: false } } });\n // No --source: every repo in turn; one failing doesn't stop the others.\n const sources = values.source ? [getSource(values.source)] : (loadConfig().sources ?? []);\n if (sources.length === 0) getSource();\n const db = openDb();\n let failed = 0;\n try {\n for (const run of await syncAll(db, values.pull ? \"pull\" : \"sync\", sources)) {\n if (run.error) failed++;\n (run.error ? console.error : console.log)(`[sync] ${describeRun(run)}`);\n for (const f of run.result?.rejected ?? []) console.warn(`[sync] skipped (doesn't belong there): ${f}`);\n }\n } finally {\n db.close();\n }\n if (failed) process.exitCode = 1;\n return;\n }\n\n default:\n console.log(\n [\n \"Yolont \u2014 usage:\",\n \" yolont (no args) guided: set up whatever is missing, then pick an open MR/PR to review\",\n \" yolont conventions generate|edit [<git address | MR/PR URL>] [--repo <checkout>] (LLM drafts from the repo; you approve/edit; max 300 lines, conventionsMaxLines in config.yaml)\",\n \" yolont setup [<git address | MR/PR URL>] [--step forge|llm|conventions|zones|weights] (re-run setup; every step shows the saved value first)\",\n \" yolont review <MR/PR URL> [--pipeline-id N] [--focus \\\"...\\\"] (or <project-id> <mr-iid> on the default host)\",\n \" yolont sync-replies <MR/PR URL> (or <project-id> <mr-iid>)\",\n \" yolont backfill <project-id | group/project> [--host h] [--max-mrs 1000] [--with-llm] [--zones] (--zones: match MRs to the project's zones.yaml, no LLM)\",\n \" yolont distill [--author <username>] [--project <project-id>] [--host h]\",\n \" yolont mcp (MCP server for coding agents: team guidelines + a pre-PR checklist; read-only, no LLM call, e.g. `claude mcp add yolont -- yolont mcp`)\",\n \" yolont panel [--port 4173] (alias: dashboard; prints a URL with a per-start access token)\",\n \" yolont zones generate|edit [<git address | MR/PR URL>] [--repo <checkout>] (draft zones from the stack's template; edit / skip)\",\n \" yolont zones <group/project> [--host h] (print the project's zone map as Mermaid)\",\n \" yolont zones graph <group/project> --repo <checkout> [--host h] (write zones.graph.json: files red zones import)\",\n \" yolont config [show | import-env <path> | set-secret <name> | delete-secret <name>]\",\n \" yolont source add <name> <git-url> [--name <your name>] [--host <git host>] (connect a memory repo: shared reviews, memory, conventions, zones)\",\n \" yolont source use <git address> [--source <name>] (a project uses one memory repo, on its own git host; switches if it had another)\",\n \" yolont source stop <git address> \u00B7 yolont source rm <name> [--force] \u00B7 yolont source ls\",\n \" yolont sync [--pull] [--source <name>] (send your records and get the team's, every repo unless --source; --pull only gets)\",\n \"\",\n `Git host, token and LLM come from ${CONFIG_PATH} + the OS keychain (shell env overrides).`,\n ].join(\"\\n\"),\n );\n process.exitCode = command && command !== \"help\" && command !== \"--help\" ? 1 : 0;\n }\n}\n\nmain().catch((err) => {\n console.error(`[yolont] ${(err as Error).message}`);\n process.exitCode = 1;\n});\n", "import { readFile } from \"node:fs/promises\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { scanDiffForSecrets } from \"../../src/checks/secrets.js\";\nimport { runDeterministicChecks } from \"../../src/checks/runner.js\";\nimport { truncateDiff } from \"../../src/git.js\";\nimport type { ForgeClient, ProjectMrSummary, ProjectRef } from \"../../src/forge/types.js\";\nimport { createLlmProvider, withRetry, type ReviewCategorySpec } from \"../../src/llm/index.js\";\nimport { loadRubric } from \"../../src/rubric/loader.js\";\nimport { computeFinalScore, volumeFactor } from \"../../src/scoring/engine.js\";\nimport { DEFAULT_CATEGORY_DESCRIPTIONS, resolveCategory, type LlmOutcome } from \"../../src/scoring/resolve.js\";\nimport { keepKnownVerdicts, loadZoneGraph, loadZones, matchZones, type Zone, type ZoneGraph, type ZoneReport } from \"../../src/zones/zones.js\";\nimport { resolveProjectFiles } from \"../conventions/resolve.js\";\nimport { openDb } from \"../db/client.js\";\nimport { hasLiveScore, insertHumanComment, markDiscussionsMined, upsertMergeRequest, upsertProject, upsertScore, upsertZoneHits } from \"../db/repo.js\";\nimport { DEFAULT_CONVENTIONS_PATH } from \"../paths.js\";\n\nexport interface BackfillOptions {\n forge: ForgeClient;\n project: ProjectRef;\n maxMrs?: number;\n withLlm?: boolean;\n /** Match every MR's changed files to the project's zones (one diff fetch per MR, no LLM). */\n zones?: boolean;\n rubricPath?: string;\n conventionsPath?: string;\n}\n\n/**\n * Bulk-scans a project's merged MRs. Default (no withLlm): mines real human review\n * comments only \u2014 GitLab-API-only, no LLM cost, resumable (a merge_request's\n * mined_discussions_at is only set once discussions are actually fetched, so a rerun\n * skips already-mined MRs). This is the \"scan once, gather historical data\" step.\n */\nexport async function runBackfill(opts: BackfillOptions): Promise<void> {\n const db = openDb();\n const client = opts.forge;\n\n const me = await client.getCurrentUser();\n const project = await client.getProject(opts.project);\n const dbProjectId = upsertProject(db, { ...project, host: client.host });\n\n const projectFiles = resolveProjectFiles(client.host, project.pathWithNamespace);\n const conventionsPath = opts.conventionsPath ?? projectFiles.conventions ?? DEFAULT_CONVENTIONS_PATH;\n // project: the numeric id from here on, so API calls don't re-resolve a path.\n opts = { ...opts, project: project.id, conventionsPath, rubricPath: opts.rubricPath ?? projectFiles.rubric };\n\n // --zones requires the file; --with-llm picks zones up whenever the project has one.\n const zonesPath = projectFiles.zones;\n const zones = (opts.zones || opts.withLlm) && zonesPath ? loadZones(zonesPath) : null;\n if (opts.zones && !zones) throw new Error(`--zones: no zones.yaml in .yolont/ or ${projectFiles.dir}`);\n // ponytail: today's graph applied to old MRs \u2014 files imported by red code now may not have been then. Fine for a heatmap.\n const graph = zones && projectFiles.zonesGraph ? loadZoneGraph(projectFiles.zonesGraph) : null;\n\n const maxMrs = opts.maxMrs ?? 1000;\n const maxPages = Math.max(1, Math.ceil(maxMrs / 100));\n const mrs = (await client.listProjectMergeRequests(opts.project, { state: \"merged\", maxPages })).slice(0, maxMrs);\n\n console.log(`[backfill] project ${project.pathWithNamespace}: found ${mrs.length} merged MR(s) (cap ${maxMrs}). Conventions: ${conventionsPath}`);\n\n let mined = 0;\n let alreadyMined = 0;\n let scored = 0;\n let zoneMatched = 0;\n\n for (const mr of mrs) {\n const row = upsertMergeRequest(db, {\n projectId: dbProjectId,\n mrIid: mr.iid,\n authorUsername: mr.authorUsername,\n sha: mr.sha,\n title: mr.title,\n mergedAt: mr.mergedAt,\n source: \"backfill\",\n });\n\n if (row.mined_discussions_at) {\n alreadyMined++;\n } else {\n const comments = await client.listMrDiscussions(opts.project, mr.iid);\n for (const comment of comments) {\n if (comment.authorUsername === me.username) continue; // exclude the pr-score bot's own notes\n insertHumanComment(db, {\n mergeRequestId: row.id,\n authorUsername: comment.authorUsername,\n body: comment.body,\n file: comment.file,\n line: comment.line,\n createdAt: comment.createdAt,\n });\n }\n markDiscussionsMined(db, row.id);\n mined++;\n }\n\n // Historical replay uses only the YAML zones: danger-zone tags/votes are later human\n // knowledge, same reason author memory isn't replayed (see scoreMrForBackfill).\n const zonesForMr = zones && !hasLiveScore(db, row.id) ? zones : null;\n if (opts.withLlm) {\n const result = await scoreMrForBackfill(db, client, opts, mr, row.id, zonesForMr, graph);\n if (result.scored) scored++;\n if (result.zoneMatched) zoneMatched++;\n } else if (zonesForMr) {\n try {\n const files = truncateDiff(await client.getMrDiffText(opts.project, mr.iid), Infinity).files;\n upsertZoneHits(db, row.id, { zones: zonesForMr, hits: matchZones(zonesForMr, files, graph), verdicts: [] });\n zoneMatched++;\n } catch (err) {\n console.error(`[backfill] MR !${mr.iid}: zone matching failed: ${(err as Error).message}`);\n }\n }\n }\n\n console.log(\n `[backfill] done. Mined discussions for ${mined} MR(s), ${alreadyMined} already mined.` +\n (opts.withLlm ? ` Scored ${scored}/${mrs.length} via LLM.` : \"\") +\n (zones ? ` Zone-matched ${zoneMatched} MR(s) (MRs reviewed live keep their own zones).` : \"\"),\n );\n db.close();\n}\n\nasync function scoreMrForBackfill(\n db: DatabaseSync,\n client: ForgeClient,\n opts: BackfillOptions,\n mr: ProjectMrSummary,\n mergeRequestId: number,\n zones: Zone[] | null,\n graph: ZoneGraph | null,\n): Promise<{ scored: boolean; zoneMatched: boolean }> {\n let zoneReport: ZoneReport | undefined;\n try {\n const rubric = loadRubric(opts.rubricPath!);\n const diffText = await client.getMrDiffText(opts.project, mr.iid);\n const diff = truncateDiff(diffText, rubric.max_diff_bytes);\n\n // Matched (and stored) before the secrets gate \u2014 file paths alone are safe to record\n // even when the diff itself must never reach the LLM.\n if (zones) {\n zoneReport = { zones, hits: matchZones(zones, diff.files, graph), verdicts: [] };\n upsertZoneHits(db, mergeRequestId, zoneReport);\n }\n\n const secretsResult = await scanDiffForSecrets(diff.text);\n if (secretsResult.scannerFailed || secretsResult.findings.length > 0) {\n console.log(`[backfill] MR !${mr.iid}: skipping LLM score (secrets check ${secretsResult.scannerFailed ? \"failed to run\" : \"flagged a hit\"}).`);\n return { scored: false, zoneMatched: Boolean(zoneReport) };\n }\n\n // Historical replay has no live pipeline to consume job/coverage/test-report data\n // from \u2014 those categories are honestly scored \"excluded, no data\", not faked.\n const detResults = runDeterministicChecks(rubric.categories, {\n diffText: diff.text,\n maxLines: rubric.max_lines,\n jobs: [],\n testReportSummary: null,\n });\n\n const llmCategories = rubric.categories.filter((c) => c.type === \"llm\" || c.type === \"hybrid\");\n let llmOutcome: LlmOutcome;\n if (llmCategories.length === 0) {\n llmOutcome = { status: \"ok\", categories: new Map() };\n } else {\n const provider = createLlmProvider(process.env);\n const conventions = await readFile(opts.conventionsPath ?? DEFAULT_CONVENTIONS_PATH, \"utf8\").catch(\n () => \"(no CONVENTIONS.md found)\",\n );\n const categorySpecs: ReviewCategorySpec[] = llmCategories.map((c) => ({\n name: c.name,\n description: c.description ?? DEFAULT_CATEGORY_DESCRIPTIONS[c.name] ?? \"Review this category based on the team conventions above.\",\n }));\n try {\n const response = await withRetry(() =>\n provider.review({\n diff: diff.text,\n truncated: diff.truncated,\n conventions,\n categories: categorySpecs,\n // Chronological memory bootstrap during a bulk backfill is deliberately not\n // attempted here \u2014 it entangles correctness with MR processing order. The\n // interactive `review` command is where local-DB memory feeds back in.\n authorHistorySummary: \"Historical backfill \u2014 no author memory applied.\",\n zones: zoneReport?.hits,\n }),\n );\n if (zoneReport) {\n upsertZoneHits(db, mergeRequestId, { ...zoneReport, verdicts: keepKnownVerdicts(response.zone_verdicts, zoneReport.hits) });\n }\n const categoryMap = new Map(response.categories.map((c) => [c.category, { findings: c.findings, summary: c.summary }]));\n llmOutcome = { status: \"ok\", categories: categoryMap };\n } catch (err) {\n llmOutcome = { status: \"error\", reason: (err as Error).message };\n }\n }\n\n const sizeFactor = volumeFactor(diff.stats, rubric.volume_scaling);\n const categoryResults = rubric.categories.map((category) =>\n resolveCategory(category, detResults, llmOutcome, rubric.severity_penalties, sizeFactor),\n );\n const { finalScore, categories: scoredCategories } = computeFinalScore(categoryResults, rubric.threshold);\n\n upsertScore(db, {\n mergeRequestId,\n scoredAt: new Date().toISOString(),\n finalScore,\n categoryScores: Object.fromEntries(scoredCategories.map((c) => [c.name, c.score])),\n findings: scoredCategories.flatMap((c) => c.findings.map((f) => ({ ...f, category: c.name }))),\n source: \"llm_backfill\",\n volumeFactor: sizeFactor,\n base: scoredCategories,\n modelUsed: process.env.ANTHROPIC_MODEL ?? process.env.OPENCODE_ZEN_MODEL ?? process.env.OLLAMA_MODEL,\n });\n\n console.log(`[backfill] MR !${mr.iid}: scored ${finalScore}/100.`);\n return { scored: true, zoneMatched: Boolean(zoneReport) };\n } catch (err) {\n console.error(`[backfill] MR !${mr.iid}: scoring failed: ${(err as Error).message}`);\n return { scored: false, zoneMatched: Boolean(zoneReport) };\n }\n}\n", "import type { Category } from \"../rubric/schema.js\";\nimport type { JobSummary } from \"../forge/types.js\";\nimport { computeDiffStats, scoreDiffSize } from \"./diffSize.js\";\nimport { scoreFromJob, scoreFromTestReport, type DetPartial } from \"./pipelineResults.js\";\n\nconst JOB_SOURCE_PREFIX = \"job:\";\n\nexport interface DeterministicContext {\n diffText: string;\n maxLines: number;\n jobs: JobSummary[];\n testReportSummary: { total: number; success: number } | null;\n}\n\n/**\n * Resolves the deterministic component for every `deterministic`/`hybrid` category\n * (per its rubric `source`). `llm`-only categories are not touched here \u2014 they're\n * scored entirely from the single combined LLM call in the orchestrator.\n */\nexport function runDeterministicChecks(categories: Category[], ctx: DeterministicContext): Map<string, DetPartial> {\n const results = new Map<string, DetPartial>();\n\n for (const category of categories) {\n if (category.type === \"llm\") continue;\n\n const source = category.source ?? \"\";\n if (source === \"diff_size\") {\n const stats = computeDiffStats(ctx.diffText);\n const { score, note } = scoreDiffSize(stats, ctx.maxLines);\n results.set(category.name, { score, available: true, note });\n } else if (source === \"test_report\") {\n results.set(category.name, scoreFromTestReport(ctx.testReportSummary));\n } else if (source.startsWith(JOB_SOURCE_PREFIX)) {\n const nameSubstring = source.slice(JOB_SOURCE_PREFIX.length);\n results.set(category.name, scoreFromJob(ctx.jobs, nameSubstring, category.min_coverage));\n } else {\n results.set(category.name, {\n score: 50,\n available: false,\n note: `Unknown source '${source}' for category '${category.name}' \u2014 excluded from scoring.`,\n });\n }\n }\n\n return results;\n}\n", "import type { JobSummary } from \"../forge/types.js\";\n\nexport interface DetPartial {\n score: number;\n available: boolean;\n note?: string;\n}\n\nexport function scoreFromTestReport(summary: { total: number; success: number } | null): DetPartial {\n if (!summary) {\n return { score: 50, available: false, note: \"No test report found on this pipeline \u2014 category excluded from scoring.\" };\n }\n const score = Math.round((summary.success / summary.total) * 100);\n return { score, available: true, note: `${summary.success}/${summary.total} tests passed.` };\n}\n\n/** Matches by substring against job names in this pipeline (rubric `source: job:<substring>`). */\nexport function scoreFromJob(jobs: JobSummary[], nameSubstring: string, minCoverage?: number): DetPartial {\n const job = jobs.find((j) => j.name.includes(nameSubstring));\n if (!job) {\n return { score: 50, available: false, note: `No job matching '${nameSubstring}' found on this pipeline \u2014 category excluded from scoring.` };\n }\n\n if (minCoverage != null && job.coverage != null) {\n const score = Math.max(0, Math.min(100, Math.round((job.coverage / minCoverage) * 100)));\n return { score, available: true, note: `Job '${job.name}' reported ${job.coverage}% coverage (target ${minCoverage}%).` };\n }\n\n if (job.status === \"success\") return { score: 100, available: true, note: `Job '${job.name}' passed.` };\n if (job.status === \"failed\") return { score: 0, available: true, note: `Job '${job.name}' failed.` };\n return { score: 50, available: false, note: `Job '${job.name}' status '${job.status}' \u2014 category excluded from scoring.` };\n}\n", "import Anthropic from \"@anthropic-ai/sdk\";\nimport { LlmReviewResponseSchema, type LlmReviewResponse } from \"./schema.js\";\nimport { LlmParseError, buildReviewJsonSchema, buildReviewPrompt, type LLMProvider, type ReviewInput } from \"./provider.js\";\n\nconst REVIEW_TOOL_NAME = \"submit_pr_review\";\n\nexport class AnthropicProvider implements LLMProvider {\n private client: Anthropic;\n private model: string;\n\n constructor(opts: { apiKey: string; model?: string }) {\n this.client = new Anthropic({ apiKey: opts.apiKey });\n this.model = opts.model ?? \"claude-sonnet-5\";\n }\n\n async review(input: ReviewInput): Promise<LlmReviewResponse> {\n const schema = buildReviewJsonSchema(input.categories.map((c) => c.name), input.zones?.map((h) => h.zone.id), !!input.reviewerFocus) as Anthropic.Tool.InputSchema;\n const response = await this.client.messages.create({\n model: this.model,\n // Thinking is always on for current models (Opus 5.5, Sonnet 5.5) and counts toward this cap.\n max_tokens: 16000,\n tools: [\n {\n name: REVIEW_TOOL_NAME,\n description: \"Submit the structured PR review, one entry per requested category.\",\n input_schema: schema,\n },\n ],\n // Forced tool_choice (\"tool\"/\"any\") is a 400 on Opus 5.5 / Sonnet 5.5 / Fable 5.1 \u2014 use auto + an explicit\n // instruction. A reply without the tool call still fails loudly below (LlmParseError \u2192 retried).\n tool_choice: { type: \"auto\" },\n messages: [{ role: \"user\", content: `${buildReviewPrompt(input)}\\n\\nSubmit your review by calling the ${REVIEW_TOOL_NAME} tool exactly once.` }],\n });\n\n const toolUse = response.content.find((block) => block.type === \"tool_use\");\n if (!toolUse || toolUse.type !== \"tool_use\") {\n throw new LlmParseError(\"Model response did not include a tool_use block\", JSON.stringify(response.content, null, 2));\n }\n\n const parsed = LlmReviewResponseSchema.safeParse(toolUse.input);\n if (!parsed.success) {\n throw new LlmParseError(`Schema validation failed: ${parsed.error.message}`, JSON.stringify(toolUse.input, null, 2));\n }\n return parsed.data;\n }\n\n async complete(prompt: string): Promise<string> {\n const response = await this.client.messages.create({ model: this.model, max_tokens: 16000, messages: [{ role: \"user\", content: prompt }] });\n // Thinking blocks come first on current models; only the text is the answer.\n const text = response.content.flatMap((b) => (b.type === \"text\" ? [b.text] : [])).join(\"\");\n if (!text) throw new LlmParseError(`Model returned no text (stop_reason: ${response.stop_reason})`);\n return text;\n }\n}\n", "import { z } from \"zod\";\nimport { ChangeTypeSchema } from \"../changeType.js\";\n\nexport const SeveritySchema = z.enum([\"minor\", \"major\", \"critical\"]);\n\nexport const LlmFindingSchema = z.object({\n severity: SeveritySchema,\n file: z.string().optional(),\n line: z.number().int().positive().optional(),\n issue: z.string(),\n suggestion: z.string().optional(),\n});\n\nexport const LlmCategoryResultSchema = z.object({\n category: z.string(),\n // Advisory only \u2014 the score engine recomputes from findings (see scoring/engine.ts) and\n // never reads this field. Optional because some free models omit it despite the\n // schema/prompt asking for it.\n score: z.number().min(0).max(100).optional(),\n findings: z.array(LlmFindingSchema),\n summary: z.string(),\n});\n\nexport const ZoneVerdictSchema = z.object({\n zone_id: z.string(),\n impact: z.enum([\"none\", \"low\", \"high\"]),\n verdict: z.string(),\n});\n\nexport const LlmReviewResponseSchema = z.object({\n categories: z.array(LlmCategoryResultSchema),\n // Separate from scoring by design. `.catch` so a model that drops\n // or mangles this optional block never fails the whole review.\n zone_verdicts: z.array(ZoneVerdictSchema).optional().catch(undefined),\n // Only requested when the reviewer gave a focus; same never-fail treatment.\n focus_notes: z.string().optional().catch(undefined),\n // Label mode asks for it; never fails the review either.\n change_type: z.object({ type: ChangeTypeSchema, reason: z.string() }).optional().catch(undefined),\n});\n\nexport type ZoneVerdict = z.infer<typeof ZoneVerdictSchema>;\n\nexport type LlmCategoryResult = z.infer<typeof LlmCategoryResultSchema>;\nexport type LlmReviewResponse = z.infer<typeof LlmReviewResponseSchema>;\n", "import { CHANGE_TYPES, changeTypePromptSection, type ChangeType } from \"../changeType.js\";\nimport type { ZoneHit } from \"../zones/zones.js\";\nimport type { LlmReviewResponse } from \"./schema.js\";\nimport { numberDiffLines } from \"../git.js\";\n\nexport interface ReviewCategorySpec {\n name: string;\n /** Human description of what this category means, fed to the model as rubric context. */\n description: string;\n}\n\nexport interface ReviewInput {\n diff: string;\n truncated: boolean;\n conventions: string;\n categories: ReviewCategorySpec[];\n /** e.g. \"Recurring weak categories: conventions (avg 65/100 over last 5 MRs).\" */\n authorHistorySummary: string;\n /** Free-text, per-review ask from whoever triggered this run \u2014 e.g. \"focus on the retry\n * logic in the payment client, ignore unrelated lint churn.\" Optional, one-off, not\n * persisted as a convention or memory; unset for the unattended CI path. */\n reviewerFocus?: string;\n /** Zones the diff's files matched (matched in code, see src/zones). Empty/unset = no zone section. */\n zones?: ZoneHit[];\n /** Steer mode: the settled change type, whose checks go into the prompt. */\n changeType?: ChangeType;\n /** Label mode: ask the model to name the change type (change_type in the response). */\n askChangeType?: boolean;\n}\n\n/**\n * Retries a flaky call with exponential backoff. Free-tier LLM gateways in particular\n * fail transiently a lot \u2014 rate limits, transport-level \"fetch failed\", \"model\n * unavailable\" \u2014 and those are worth a couple of retries before giving up and scoring\n * the LLM categories 0 for the run. Not selective about error type: every failure\n * observed against OpenCode Zen's free tier has been transient, and a wasted retry on a\n * genuinely broken config just costs a few seconds.\n */\nexport async function withRetry<T>(fn: () => Promise<T>, opts: { attempts?: number; baseDelayMs?: number } = {}): Promise<T> {\n const attempts = opts.attempts ?? 3;\n const baseDelayMs = opts.baseDelayMs ?? 2000;\n let lastError: unknown;\n\n for (let attempt = 0; attempt < attempts; attempt++) {\n try {\n return await fn();\n } catch (err) {\n lastError = err;\n if (attempt < attempts - 1) {\n const delayMs = baseDelayMs * 2 ** attempt;\n console.error(`[yolont] LLM call failed (attempt ${attempt + 1}/${attempts}): ${(err as Error).message}${(err as Error).cause ? ` (${String((err as Error).cause)})` : \"\"} \u2014 retrying in ${delayMs}ms`);\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n }\n }\n\n throw lastError;\n}\n\nexport interface LLMProvider {\n /** One call covering every llm/hybrid category \u2014 keeps cost/latency to a single request per MR. */\n review(input: ReviewInput): Promise<LlmReviewResponse>;\n /** Plain text answer to a free-form prompt (conventions generation). */\n complete(prompt: string): Promise<string>;\n}\n\nexport class LlmParseError extends Error {\n /** The raw model output that failed to parse/validate \u2014 undefined for transport-level\n * failures (non-2xx, network error) where there's no model output to show. Callers\n * (e.g. the review TUI) print this on failure since the short message alone often\n * isn't enough to tell what the model actually did wrong. */\n constructor(\n message: string,\n public rawResponse?: string,\n ) {\n super(message);\n }\n}\n\n/**\n * Shared JSON schema shape for both providers. `category` is constrained to an enum of\n * the exact requested category names \u2014 without it, a model returning e.g. \"Conventions\"\n * or \"pr hygiene\" instead of \"conventions\"/\"pr_hygiene\" fails the lookup in index.ts\n * silently (that category just scores 0 with \"LLM did not return this category\"), which\n * is a scoring-corruption bug a human reviewing the diff would never catch.\n */\nexport function buildReviewJsonSchema(categoryNames: string[], zoneIds: string[] = [], withFocus = false): Record<string, unknown> {\n return {\n type: \"object\",\n properties: {\n change_type: {\n type: \"object\",\n description: \"Only when asked: what kind of change this is.\",\n properties: { type: { type: \"string\", enum: [...CHANGE_TYPES] }, reason: { type: \"string\" } },\n required: [\"type\", \"reason\"],\n },\n ...(withFocus && {\n focus_notes: { type: \"string\", description: \"What you checked for the reviewer's focus and what you found, including 'checked X, Y, Z \u2014 no issues'.\" },\n }),\n ...(zoneIds.length > 0 && {\n zone_verdicts: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n zone_id: { type: \"string\", enum: zoneIds },\n impact: { type: \"string\", enum: [\"none\", \"low\", \"high\"] },\n verdict: { type: \"string\" },\n },\n required: [\"zone_id\", \"impact\", \"verdict\"],\n },\n },\n }),\n categories: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n category: { type: \"string\", enum: categoryNames },\n score: { type: \"number\", description: \"Advisory only; the caller recomputes the real score from findings.\" },\n findings: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n severity: { type: \"string\", enum: [\"minor\", \"major\", \"critical\"] },\n file: { type: \"string\" },\n line: { type: \"number\", description: \"The number printed at the start of the diff line the issue is on (new-file numbering).\" },\n issue: { type: \"string\" },\n suggestion: { type: \"string\" },\n },\n required: [\"severity\", \"issue\"],\n },\n },\n summary: { type: \"string\" },\n },\n required: [\"category\", \"findings\", \"summary\"],\n },\n },\n },\n required: [\"categories\"],\n };\n}\n\nexport function buildReviewPrompt(input: ReviewInput): string {\n const categoryList = input.categories.map((c) => `- ${c.name}: ${c.description}`).join(\"\\n\");\n return `You are reviewing a GitLab merge request diff against a team rubric.\n\nCategories to score (0-100 each, return exactly one entry per category, using the same category name):\n${categoryList}\n\n${changeTypePromptSection({ steer: input.changeType, ask: input.askChangeType })}${input.reviewerFocus ? buildFocusPromptSection(input.reviewerFocus) : \"\"}Team conventions:\n${input.conventions}\n\nAuthor history (context only \u2014 do not penalize for past MRs, only for issues present in this diff):\n${input.authorHistorySummary}\n\n${input.zones?.length ? `${buildZonesPromptSection(input.zones)}\\n` : \"\"}${input.truncated ? \"NOTE: this diff was truncated to fit size limits; review only what is shown.\\n\" : \"\"}\nDiff (each added \"+\" or unchanged \" \" line starts with its line number in the new file; removed \"-\" lines have none).\nFor a finding's \"line\", copy that number exactly from the line the issue is on, preferably a \"+\" line. Never count lines yourself.\n${numberDiffLines(input.diff)}\n`;\n}\n\nfunction buildFocusPromptSection(focus: string): string {\n return `Reviewer's focus for this review (top priority \u2014 still score every category):\n${focus}\n\nHow to apply it:\n- Before scoring, go through the diff and list for yourself every changed line related to this focus (e.g. for \"dependency injection\": every constructor, provider, injection token, registration and consumer; for \"wrong function call\": every changed call site \u2014 check the callee, argument order/types and the return value use against what the diff shows).\n- Check each one. Do not skip an item because it looks fine at a glance.\n- Report every real issue you find as a finding in the best-fitting category.\n- Fill focus_notes with one or two sentences: what you checked for this focus and what you found (say \"no issues\" explicitly if so).\n\n`;\n}\n\nfunction buildZonesPromptSection(hits: ZoneHit[]): string {\n const zones = hits\n .map(({ zone, files, viaImport, feedback }) =>\n [\n `- ${zone.id} (${zone.level}): ${zone.why}`,\n zone.watch_for.length > 0 ? ` watch for: ${zone.watch_for.join(\"; \")}` : \"\",\n zone.budget ? ` budget: ${zone.budget}` : \"\",\n ` changed files here: ${files.map((f) => (viaImport?.includes(f) ? `${f} (not in this zone's folders, but imported by it \u2014 so it runs with it)` : f)).join(\", \")}`,\n feedback?.length ? ` past reviewer feedback on this zone's flags (weight heavily):\\n${feedback.map((f) => ` - ${f}`).join(\"\\n\")}` : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\"),\n )\n .join(\"\\n\");\n return `Sensitive zones this diff touches (red = runs on every start, request or render, or is hard to undo; amber = widely shared; green = rarely runs):\n${zones}\n\nFor each zone above, add one zone_verdicts entry: impact none/low/high and one sentence naming the concrete effect, judged against that zone's own reason and watch-for list (e.g. \"adds a blocking fetch at mount\", \"migration rewrites a large table without a batch\"). This is independent of code quality, and must not change category findings or scores.\n`;\n}\n", "import { LlmReviewResponseSchema, type LlmReviewResponse } from \"./schema.js\";\nimport { LlmParseError, buildReviewJsonSchema, buildReviewPrompt, type LLMProvider, type ReviewInput } from \"./provider.js\";\n\n/**\n * Local/self-hosted fallback. Not the default \u2014 only used when\n * OLLAMA_URL is set and no ANTHROPIC_API_KEY is present. Same schema contract\n * as AnthropicProvider via Ollama's structured-output `format` parameter.\n */\nexport class OllamaProvider implements LLMProvider {\n constructor(private opts: { baseUrl: string; model: string }) {}\n\n async review(input: ReviewInput): Promise<LlmReviewResponse> {\n const res = await fetch(`${this.opts.baseUrl.replace(/\\/$/, \"\")}/api/chat`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n model: this.opts.model,\n stream: false,\n format: buildReviewJsonSchema(input.categories.map((c) => c.name), input.zones?.map((h) => h.zone.id), !!input.reviewerFocus),\n messages: [{ role: \"user\", content: buildReviewPrompt(input) }],\n }),\n });\n\n if (!res.ok) {\n throw new LlmParseError(`Ollama request failed: ${res.status} ${await res.text()}`);\n }\n\n const body = (await res.json()) as { message?: { content?: string } };\n const content = body.message?.content;\n if (!content) {\n throw new LlmParseError(\"Ollama response had no message content\");\n }\n\n let json: unknown;\n try {\n json = JSON.parse(content);\n } catch (err) {\n throw new LlmParseError(`Ollama response was not valid JSON: ${(err as Error).message}`, content);\n }\n\n const parsed = LlmReviewResponseSchema.safeParse(json);\n if (!parsed.success) {\n throw new LlmParseError(`Schema validation failed: ${parsed.error.message}`, content);\n }\n return parsed.data;\n }\n\n async complete(prompt: string): Promise<string> {\n const res = await fetch(`${this.opts.baseUrl.replace(/\\/$/, \"\")}/api/chat`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ model: this.opts.model, stream: false, messages: [{ role: \"user\", content: prompt }] }),\n });\n if (!res.ok) throw new LlmParseError(`Ollama request failed: ${res.status} ${await res.text()}`);\n const content = ((await res.json()) as { message?: { content?: string } }).message?.content;\n if (!content) throw new LlmParseError(\"Ollama response had no message content\");\n return content;\n }\n}\n", "import { LlmReviewResponseSchema, type LlmReviewResponse } from \"./schema.js\";\nimport { LlmParseError, buildReviewJsonSchema, buildReviewPrompt, type LLMProvider, type ReviewInput } from \"./provider.js\";\n\nconst TOOL_NAME = \"submit_pr_review\";\n\n/**\n * Any OpenAI-compatible /v1 gateway: OpenCode (https://opencode.ai/zen, formerly \"Zen\"),\n * OpenAI, OpenRouter, \u2026 Defaults to OpenCode, which has a\n * rotating set of free models. Same schema contract as the other providers via\n * OpenAI-style function-calling (`tools` + forced `tool_choice`).\n *\n * Free models are smaller and sometimes ignore forced tool-calling and answer with\n * plain JSON in the message content instead \u2014 this provider falls back to parsing\n * that directly rather than treating it as a hard failure.\n *\n * The Go gateway (zen/go) requires an `x-opencode-session` header to route the\n * request \u2014 without it the provider rejects with `MissingSessionID`. Generate\n * one lazily so plain Zen callers (no session needed) don't send it.\n */\nexport class OpenCodeZenProvider implements LLMProvider {\n private sessionId: string | undefined;\n\n constructor(private opts: { apiKey: string; model: string; baseUrl?: string; useSession?: boolean }) {}\n\n /** Errors name the host the request went to (api.openai.com, opencode.ai, \u2026), not a fixed brand. */\n private get label(): string {\n try {\n return new URL(this.opts.baseUrl ?? \"https://opencode.ai/zen/v1\").host;\n } catch {\n return \"LLM gateway\";\n }\n }\n\n async review(input: ReviewInput): Promise<LlmReviewResponse> {\n const schema = buildReviewJsonSchema(input.categories.map((c) => c.name), input.zones?.map((h) => h.zone.id), !!input.reviewerFocus);\n\n const { toolCallArgs, content } = await this.stream({\n model: this.opts.model,\n stream: true,\n messages: [{ role: \"user\", content: buildReviewPrompt(input) }],\n tools: [\n {\n type: \"function\",\n function: {\n name: TOOL_NAME,\n description: \"Submit the structured PR review, one entry per requested category.\",\n parameters: schema,\n },\n },\n ],\n tool_choice: { type: \"function\", function: { name: TOOL_NAME } },\n });\n\n const raw = toolCallArgs || content;\n if (!raw) {\n throw new LlmParseError(`${this.label} response had neither a tool call nor message content`);\n }\n\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch (err) {\n throw new LlmParseError(`${this.label} response was not valid JSON: ${(err as Error).message}`, raw);\n }\n\n const parsed = LlmReviewResponseSchema.safeParse(json);\n if (!parsed.success) {\n throw new LlmParseError(`Schema validation failed: ${parsed.error.message}`, raw);\n }\n return parsed.data;\n }\n\n async complete(prompt: string): Promise<string> {\n const { content } = await this.stream({ model: this.opts.model, stream: true, messages: [{ role: \"user\", content: prompt }] });\n if (!content) throw new LlmParseError(`${this.label} response had no message content`);\n return content;\n }\n\n /** POSTs a streamed chat completion; returns the concatenated tool-call args and message content (reasoning deltas ignored). */\n private async stream(body: Record<string, unknown>): Promise<{ toolCallArgs: string; content: string }> {\n const baseUrl = (this.opts.baseUrl ?? \"https://opencode.ai/zen/v1\").replace(/\\/$/, \"\");\n if (this.opts.useSession && !this.sessionId) {\n this.sessionId = crypto.randomUUID();\n }\n\n const res = await fetch(`${baseUrl}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${this.opts.apiKey}`,\n ...(this.sessionId ? { \"x-opencode-session\": this.sessionId } : {}),\n },\n body: JSON.stringify(body),\n });\n\n if (!res.ok) {\n throw new LlmParseError(`${this.label} request failed: ${res.status} ${await res.text()}`);\n }\n\n // Streamed SSE: reasoning models can think for 5+ min on a big diff, past undici's\n // 300s headers timeout (\"fetch failed\"). Streaming gets headers back immediately and\n // keeps bytes flowing, so neither that nor an idle NAT/VPN drop kills the request.\n let toolCallArgs = \"\";\n let content = \"\";\n let buffer = \"\";\n for await (const chunk of res.body!.pipeThrough(new TextDecoderStream())) {\n buffer += chunk;\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop()!;\n for (const line of lines) {\n const data = line.startsWith(\"data:\") ? line.slice(5).trim() : \"\";\n if (!data || data === \"[DONE]\") continue;\n const delta = (\n JSON.parse(data) as {\n choices?: Array<{ delta?: { content?: string | null; tool_calls?: Array<{ function?: { arguments?: string } }> } }>;\n }\n ).choices?.[0]?.delta;\n toolCallArgs += delta?.tool_calls?.[0]?.function?.arguments ?? \"\";\n content += delta?.content ?? \"\";\n }\n }\n\n return { toolCallArgs, content };\n }\n}\n", "import type { LlmReviewResponse } from \"./schema.js\";\n\n/**\n * Deterministic, no-cost rewrite of LLM prose into plainer, more direct phrasing.\n * Wired into every provider via `createLlmProvider` (see index.ts) so review comments\n * read like a teammate wrote them instead of carrying typical LLM hedging/filler \u2014\n * a second LLM call to \"humanize\" the text would add latency/cost for the same result,\n * and these phrases are common enough to catch with fixed rules without touching the\n * technical content (file/line/severity are untouched; only issue/suggestion/summary\n * prose is rewritten).\n */\n\n// Phrase-level filler that adds no information \u2014 stripped outright, anchored so we don't\n// eat similar words mid-sentence.\nconst FILLER_PHRASES: RegExp[] = [\n /\\bit is (?:important|worth) to note that\\b,?\\s*/gi,\n /\\bit'?s worth noting that\\b,?\\s*/gi,\n /\\bit should be noted that\\b,?\\s*/gi,\n /\\bplease note that\\b,?\\s*/gi,\n /\\bkeep in mind that\\b,?\\s*/gi,\n /\\bas (?:previously )?mentioned,?\\s*/gi,\n /^overall,\\s*/gi,\n /^in summary,\\s*/gi,\n /^in conclusion,\\s*/gi,\n];\n\n// word/phrase -> plainer equivalent. Applied whole-word, case-preserved on the first\n// letter so \"Utilize\" -> \"Use\" and \"utilize\" -> \"use\".\nconst WORD_SWAPS: [RegExp, string][] = [\n [/\\bin order to\\b/gi, \"to\"],\n [/\\bdue to the fact that\\b/gi, \"because\"],\n [/\\bat this point in time\\b/gi, \"now\"],\n [/\\bin the event that\\b/gi, \"if\"],\n [/\\ba number of\\b/gi, \"some\"],\n [/\\bprior to\\b/gi, \"before\"],\n [/\\bsubsequent to\\b/gi, \"after\"],\n];\n\nconst SUFFIX_SWAPS: [RegExp, Record<string, string>][] = [\n [/\\butiliz(e|es|ed|ing)\\b/gi, { e: \"use\", es: \"uses\", ed: \"used\", ing: \"using\" }],\n [/\\bleverag(e|es|ed|ing)\\b/gi, { e: \"use\", es: \"uses\", ed: \"used\", ing: \"using\" }],\n [/\\bfacilitat(e|es|ed|ing)\\b/gi, { e: \"help\", es: \"helps\", ed: \"helped\", ing: \"helping\" }],\n];\n\nfunction preserveCase(original: string, replacement: string): string {\n if (original[0] && original[0] === original[0].toUpperCase() && original[0] !== original[0].toLowerCase()) {\n return replacement[0]!.toUpperCase() + replacement.slice(1);\n }\n return replacement;\n}\n\nexport function sanitizeReviewText(text: string): string {\n let result = text;\n\n for (const phrase of FILLER_PHRASES) {\n result = result.replace(phrase, \"\");\n }\n\n for (const [pattern, suffixMap] of SUFFIX_SWAPS) {\n result = result.replace(pattern, (match, suffix: string) => preserveCase(match, suffixMap[suffix.toLowerCase()] ?? match));\n }\n for (const [pattern, replacement] of WORD_SWAPS) {\n result = result.replace(pattern, (match) => preserveCase(match, replacement));\n }\n\n // Collapse whitespace left behind by stripped phrases, and re-capitalize if a leading\n // phrase strip left a lowercase word starting the sentence.\n result = result.replace(/[ \\t]{2,}/g, \" \").replace(/^\\n+/, \"\").trim();\n if (result && result[0] === result[0]!.toLowerCase() && result[0] !== result[0]!.toUpperCase()) {\n result = result[0]!.toUpperCase() + result.slice(1);\n }\n return result;\n}\n\nexport function sanitizeReviewResponse(response: LlmReviewResponse): LlmReviewResponse {\n return {\n zone_verdicts: response.zone_verdicts?.map((v) => ({ ...v, verdict: sanitizeReviewText(v.verdict) })),\n focus_notes: response.focus_notes && sanitizeReviewText(response.focus_notes),\n categories: response.categories.map((c) => ({\n ...c,\n summary: sanitizeReviewText(c.summary),\n findings: c.findings.map((f) => ({\n ...f,\n issue: sanitizeReviewText(f.issue),\n suggestion: f.suggestion ? sanitizeReviewText(f.suggestion) : f.suggestion,\n })),\n })),\n };\n}\n", "import { listDiffFiles, resolveDiffPosition } from \"../git.js\";\nimport type { LlmCategoryResult } from \"./schema.js\";\n\nconst ENDPOINT = \"https://api.typesafe.ai/v1/systemone\";\nconst DEFAULT_MODEL = \"jev-latest\";\nconst DEFAULT_NOISE_THRESHOLD = 0.5;\n\ninterface JevAnswer {\n noul?: number;\n}\n\ninterface JevResponse {\n answers: Record<string, JevAnswer>;\n}\n\nexport interface JevEnv {\n TYPESAFE_API_KEY?: string;\n JEV_MODEL?: string;\n JEV_NOISE_THRESHOLD?: string;\n JEV_DISABLED?: string;\n}\n\n// JEV_DISABLED=1 (or true) skips Jev even with a key set \u2014 temporary kill switch.\nexport const jevEnabled = (env: JevEnv): boolean => !!env.TYPESAFE_API_KEY && !/^(1|true)$/i.test(env.JEV_DISABLED ?? \"\");\n\n/**\n * Cross-checks LLM findings against Jev (typesafe.ai) \u2014 a fast, cheap, calibrated\n * classifier \u2014 and drops the ones it flags as likely noise/false-positives before they\n * reach scoring/comments. Purely an accuracy layer on top of the LLM review, not a gate:\n * unset TYPESAFE_API_KEY, a transport error, or a malformed response all fail open\n * (findings pass through unfiltered) rather than blocking or zeroing a review the LLM\n * already produced. Failing closed would be wrong here too: dropped findings raise the\n * score, so a Jev outage must never make MRs pass more easily.\n *\n * With a key set, findings naming a file absent from the diff are dropped before Jev is\n * asked \u2014 the LLM saw this same diff text, so that location cannot be real.\n */\nexport async function filterNoiseWithJev(\n categories: LlmCategoryResult[],\n diffText: string,\n env: JevEnv,\n // Same memory string the LLM saw (insights, human corrections, disputed/confirmed\n // findings) so Jev judges findings against what reviewers already accepted/rejected.\n memory?: string,\n // The reviewer's per-run focus (TUI/--focus). Findings on it often hinge on code just\n // outside the diff (callee signatures, DI wiring), which rule 2 alone would reject.\n focus?: string,\n): Promise<LlmCategoryResult[]> {\n if (!jevEnabled(env)) return categories;\n const diffFiles = new Set(listDiffFiles(diffText));\n // filter, not map: interactiveReview finds dropped findings by object identity.\n const grounded = categories.map((c) => ({ ...c, findings: c.findings.filter((f) => !f.file || diffPath(f.file, diffFiles)) }));\n if (grounded.every((c) => c.findings.length === 0)) return grounded;\n\n const questions: Record<string, { type: \"noul\"; instructions: string }> = {};\n grounded.forEach((c, ci) => {\n c.findings.forEach((f, fi) => {\n const path = f.file && diffPath(f.file, diffFiles);\n const lineOutsideDiff = path && f.line && !resolveDiffPosition(diffText, path, f.line);\n questions[`${ci}_${fi}`] = {\n type: \"noul\",\n instructions: [\n \"Judge this code review finding strictly against the diff. Answer yes only if ALL hold; if unsure, answer no.\",\n \"1. The diff itself shows the code the finding describes, and the claim about it is factually correct.\",\n \"2. It is a concrete problem this change introduces or worsens \u2014 not speculation (\\\"might\\\", \\\"could\\\") about code not shown, and not a style preference.\",\n \"3. The claimed severity fits the actual impact.\",\n ...(memory ? [\"4. Reviewer memory does not show this kind of finding being rejected.\"] : []),\n ...(focus\n ? [`The human reviewer asked to focus on: ${focus}. If this finding is about that focus and the diff shows the code it points at (e.g. the call site or injection), do not reject it under rule 2 only because confirming it needs code outside the diff.`]\n : []),\n `Category: ${c.category}`,\n `Severity claimed: ${f.severity}`,\n `File: ${f.file ?? \"(unspecified)\"}${f.line ? `:${f.line}` : \"\"}${lineOutsideDiff ? \" (this line is NOT part of the diff)\" : \"\"}`,\n `Issue: ${f.issue}`,\n ...(f.suggestion ? [`Suggestion: ${f.suggestion}`] : []),\n ].join(\"\\n\"),\n };\n });\n });\n\n let response: JevResponse;\n try {\n const res = await fetch(ENDPOINT, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", authorization: `Bearer ${env.TYPESAFE_API_KEY}` },\n body: JSON.stringify({ model: env.JEV_MODEL ?? DEFAULT_MODEL, state: memory ? `Reviewer memory (past human feedback on findings \u2014 weight heavily):\\n${memory}\\n\\n--- DIFF ---\\n${diffText}` : diffText, questions }),\n });\n if (!res.ok) throw new Error(`Jev returned ${res.status}: ${await res.text()}`);\n response = (await res.json()) as JevResponse;\n if (!response?.answers || typeof response.answers !== \"object\") throw new Error(\"Jev response has no answers\");\n } catch (err) {\n console.error(`[yolont] Jev noise filter failed, keeping findings unfiltered: ${(err as Error).message}`);\n return grounded;\n }\n\n // A garbage threshold becomes NaN, and `x >= NaN` would silently drop every finding.\n const parsed = Number(env.JEV_NOISE_THRESHOLD || NaN);\n const threshold = parsed >= 0 && parsed <= 1 ? parsed : DEFAULT_NOISE_THRESHOLD;\n\n return grounded.map((c, ci) => ({\n ...c,\n findings: c.findings.filter((_, fi) => {\n // Missing/malformed answer for this key \u2192 keep the finding (fail open per-finding).\n const noul = response.answers[`${ci}_${fi}`]?.noul;\n return typeof noul !== \"number\" || !Number.isFinite(noul) || noul >= threshold;\n }),\n }));\n}\n\n/** The finding's path as the diff spells it (LLMs sometimes keep the a/ b/ ./ prefix), or null if not in the diff. */\nfunction diffPath(file: string, diffFiles: Set<string>): string | null {\n if (diffFiles.has(file)) return file;\n const stripped = file.replace(/^(\\.\\/|[ab]\\/)/, \"\");\n return diffFiles.has(stripped) ? stripped : null;\n}\n", "import { AnthropicProvider } from \"./anthropicProvider.js\";\nimport { OllamaProvider } from \"./ollamaProvider.js\";\nimport { OpenCodeZenProvider } from \"./opencodeZenProvider.js\";\nimport type { LLMProvider, ReviewInput } from \"./provider.js\";\nimport { sanitizeReviewResponse } from \"./sanitizeTone.js\";\nimport type { LlmReviewResponse } from \"./schema.js\";\n\nexport * from \"./provider.js\";\nexport * from \"./schema.js\";\nexport { sanitizeReviewText, sanitizeReviewResponse } from \"./sanitizeTone.js\";\nexport { filterNoiseWithJev, jevEnabled, type JevEnv } from \"./jevValidate.js\";\n\nexport interface LlmEnv {\n ANTHROPIC_API_KEY?: string;\n ANTHROPIC_MODEL?: string;\n OPENCODE_ZEN_API_KEY?: string;\n OPENCODE_ZEN_MODEL?: string;\n OPENCODE_ZEN_BASE_URL?: string;\n OPENCODE_ZEN_GO_API_KEY?: string;\n OPENCODE_ZEN_GO_MODEL?: string;\n OPENCODE_ZEN_GO_BASE_URL?: string;\n OMNI_API_KEY?: string;\n OMNI_MODEL?: string;\n OMNI_BASE_URL?: string;\n OLLAMA_URL?: string;\n OLLAMA_MODEL?: string;\n}\n\n// Free tier rotates (see https://opencode.ai/zen/v1/models) \u2014 override with\n// OPENCODE_ZEN_MODEL if this one has been retired.\nconst DEFAULT_OPENCODE_ZEN_FREE_MODEL = \"deepseek-v4-flash-free\";\nconst DEFAULT_OPENCODE_ZEN_GO_BASE_URL = \"https://opencode.ai/zen/go/v1\";\n\n/**\n * Claude API is the default (per team decision). OpenCode Zen is the free-tier\n * cloud fallback, OpenCode Zen Go is a second cloud fallback tier (separate\n * gateway/key). Omni is a paid OpenAI-compatible gateway (same wire protocol\n * as OpenCode Zen, just a different host/key), used if configured and none\n * of the above is set. Ollama is fully offline, used only if explicitly\n * configured and none of the above is set.\n */\nexport function createLlmProvider(env: LlmEnv): LLMProvider {\n return withToneSanitizer(createRawLlmProvider(env));\n}\n\n/** A saved LLM profile (see local/config). openai-compatible covers OpenCode Zen, OpenRouter, OpenAI, any /v1 gateway. */\nexport interface LlmProfileSpec {\n provider: \"anthropic\" | \"openai-compatible\" | \"ollama\";\n model: string;\n baseUrl?: string;\n}\n\nexport function createProviderFromProfile(profile: LlmProfileSpec, apiKey: string | undefined): LLMProvider {\n if (profile.provider === \"ollama\") return withToneSanitizer(new OllamaProvider({ baseUrl: profile.baseUrl ?? \"http://localhost:11434\", model: profile.model }));\n if (!apiKey) throw new Error(`No API key for this ${profile.provider} profile.`);\n if (profile.provider === \"anthropic\") return withToneSanitizer(new AnthropicProvider({ apiKey, model: profile.model }));\n if (!profile.baseUrl) throw new Error(\"An openai-compatible profile needs a base URL (the gateway's /v1 URL).\");\n return withToneSanitizer(new OpenCodeZenProvider({ apiKey, model: profile.model, baseUrl: profile.baseUrl }));\n}\n\nfunction createRawLlmProvider(env: LlmEnv): LLMProvider {\n if (env.ANTHROPIC_API_KEY) {\n return new AnthropicProvider({ apiKey: env.ANTHROPIC_API_KEY, model: env.ANTHROPIC_MODEL });\n }\n if (env.OPENCODE_ZEN_API_KEY) {\n return new OpenCodeZenProvider({\n apiKey: env.OPENCODE_ZEN_API_KEY,\n model: env.OPENCODE_ZEN_MODEL ?? DEFAULT_OPENCODE_ZEN_FREE_MODEL,\n baseUrl: env.OPENCODE_ZEN_BASE_URL,\n });\n }\n if (env.OPENCODE_ZEN_GO_API_KEY) {\n return new OpenCodeZenProvider({\n apiKey: env.OPENCODE_ZEN_GO_API_KEY,\n model: env.OPENCODE_ZEN_GO_MODEL ?? DEFAULT_OPENCODE_ZEN_FREE_MODEL,\n baseUrl: env.OPENCODE_ZEN_GO_BASE_URL ?? DEFAULT_OPENCODE_ZEN_GO_BASE_URL,\n useSession: true,\n });\n }\n if (env.OMNI_API_KEY) {\n // No built-in default host: a key alone must not silently send code to someone's gateway.\n if (!env.OMNI_BASE_URL) throw new Error(\"OMNI_API_KEY is set but OMNI_BASE_URL is not \u2014 set the gateway's /v1 URL.\");\n return new OpenCodeZenProvider({\n apiKey: env.OMNI_API_KEY,\n model: env.OMNI_MODEL ?? \"google/gemini-3.7-flash\",\n baseUrl: env.OMNI_BASE_URL,\n });\n }\n if (env.OLLAMA_URL) {\n return new OllamaProvider({ baseUrl: env.OLLAMA_URL, model: env.OLLAMA_MODEL ?? \"qwen2.5-coder\" });\n }\n throw new Error(\n \"No LLM provider configured: set ANTHROPIC_API_KEY, OPENCODE_ZEN_API_KEY, OPENCODE_ZEN_GO_API_KEY, OMNI_API_KEY, or OLLAMA_URL\",\n );\n}\n\n/**\n * Every provider's raw prose tends to read \"rich and heavy\" (LLM hedging/filler) rather\n * than like a teammate's comment. Wrapping here \u2014 instead of inside each provider \u2014 means\n * every call site (CI's src/index.ts and the local review TUI) gets plain-tone output for\n * free, with no per-provider duplication.\n */\nfunction withToneSanitizer(provider: LLMProvider): LLMProvider {\n return {\n review: async (input: ReviewInput): Promise<LlmReviewResponse> => sanitizeReviewResponse(await provider.review(input)),\n // Unsanitized: tone cleanup is for review prose, not generated files.\n complete: (prompt) => provider.complete(prompt),\n };\n}\n", "import { scoreFromFindings } from \"./engine.js\";\nimport type { Category } from \"../rubric/schema.js\";\nimport type { CategoryResult, Finding } from \"./types.js\";\n\nexport const DEFAULT_CATEGORY_DESCRIPTIONS: Record<string, string> = {\n conventions: \"Naming, structure, and style conventions. Flag deviations with the specific rule violated.\",\n maintainability: \"Readability, complexity, duplication, and architectural drift.\",\n security: \"Injection risks, unsafe deserialization, missing auth checks, and other OWASP-style issues.\",\n};\n\nexport type LlmOutcome =\n | { status: \"skipped\"; reason: string }\n | { status: \"error\"; reason: string }\n | { status: \"ok\"; categories: Map<string, { findings: Finding[]; summary: string }> };\n\nexport type DetPartialResult = { score: number; available: boolean; note?: string };\n\n/**\n * Combines a category's deterministic and/or LLM components into the final per-category\n * result the scoring engine weights. Shared by the CI entrypoint (src/index.ts) and the\n * local-only tooling (local/mining/backfill.ts, local/review/interactiveReview.ts) \u2014 this\n * used to live only in src/index.ts's private scope, which made it unreusable since\n * index.ts self-executes `main()` and calls `process.exit` on import.\n */\nexport function resolveCategory(\n category: Category,\n detResults: Map<string, DetPartialResult>,\n llmOutcome: LlmOutcome,\n severityPenalties: { minor: number; major: number; critical: number },\n volumeFactor = 1,\n): CategoryResult {\n if (category.type === \"deterministic\") {\n const det = detResults.get(category.name);\n return {\n name: category.name,\n weight: category.weight,\n available: det?.available ?? false,\n score: det?.score ?? 50,\n findings: [],\n note: det?.note,\n };\n }\n\n const llmComponent = resolveLlmComponent(category.name, llmOutcome, severityPenalties, volumeFactor);\n\n if (category.type === \"llm\") {\n return {\n name: category.name,\n weight: category.weight,\n available: llmComponent.available,\n score: llmComponent.score,\n findings: llmComponent.findings,\n note: llmComponent.note,\n };\n }\n\n // hybrid: blend deterministic + LLM components\n const det = detResults.get(category.name);\n if (!det) {\n return {\n name: category.name,\n weight: category.weight,\n available: llmComponent.available,\n score: llmComponent.score,\n findings: llmComponent.findings,\n note: `${llmComponent.note ?? \"\"} (no deterministic source configured)`.trim(),\n };\n }\n\n if (!det.available) {\n return {\n name: category.name,\n weight: category.weight,\n available: llmComponent.available,\n score: llmComponent.score,\n findings: llmComponent.findings,\n note: `${det.note ?? \"\"} \u2014 falling back to LLM-only score.`,\n };\n }\n\n if (!llmComponent.available) {\n return {\n name: category.name,\n weight: category.weight,\n available: det.available,\n score: det.score,\n findings: [],\n note: `${det.note ?? \"\"} (${llmComponent.note ?? \"LLM component unavailable\"})`,\n };\n }\n\n return {\n name: category.name,\n weight: category.weight,\n available: true,\n score: Math.round((det.score + llmComponent.score) / 2),\n findings: llmComponent.findings,\n note: [det.note, llmComponent.note].filter(Boolean).join(\" \"),\n };\n}\n\nfunction resolveLlmComponent(\n categoryName: string,\n llmOutcome: LlmOutcome,\n severityPenalties: { minor: number; major: number; critical: number },\n volumeFactor: number,\n): { available: boolean; score: number; findings: Finding[]; note?: string } {\n if (llmOutcome.status === \"skipped\") {\n return { available: false, score: 50, findings: [], note: `LLM skipped: ${llmOutcome.reason}` };\n }\n if (llmOutcome.status === \"error\") {\n return { available: true, score: 0, findings: [], note: `LLM parse error: ${llmOutcome.reason}` };\n }\n const found = llmOutcome.categories.get(categoryName);\n if (!found) {\n return { available: true, score: 0, findings: [], note: \"LLM did not return this category\" };\n }\n return {\n available: true,\n score: scoreFromFindings(found.findings, severityPenalties, volumeFactor),\n findings: found.findings,\n note: found.findings.length > 0 ? `${found.summary} (penalties \u00D7${volumeFactor.toFixed(2)} for MR size)` : found.summary,\n };\n}\n", "import type { DatabaseSync } from \"node:sqlite\";\nimport { createLlmProvider } from \"../../src/llm/index.js\";\nimport { insertInsight, listAuthorCorrections, listAuthorFindingResponses, listAuthors, type AuthorKey, type CorrectionRow, type FindingResponseRow } from \"../db/repo.js\";\n\nexport interface DistillOptions {\n /** One person; omit for everyone in the DB. */\n author?: AuthorKey;\n /** Scope to one GitLab project's corrections only \u2014 insights are tagged with this\n * project_id and won't surface in reviews of other repos (one repo's habit\n * shouldn't color a review on a repo with different conventions). Omit for the prior,\n * cross-repo behavior (insight tagged project_id NULL = global). */\n projectId?: number;\n}\n\n/**\n * On-demand (never automatic, to control LLM cost \u2014 see local/cli.ts): turns a human's\n * corrections into reusable insight bullets. Corrections are the highest-signal data\n * here (explicit \"the automated score was wrong, here's why\") \u2014 this is deliberately\n * scoped to corrections rather than also mining human_review_comments/findings, which\n * are numerous and noisy by comparison; that's a reasonable extension later once\n * correction volume alone proves the loop works.\n */\nexport async function runDistill(db: DatabaseSync, opts: DistillOptions = {}): Promise<void> {\n const authors = opts.author ? [opts.author] : listAuthors(db);\n\n for (const author of authors) {\n const corrections = listAuthorCorrections(db, author, 50, opts.projectId);\n const findingResponses = listAuthorFindingResponses(db, author, 50, opts.projectId);\n if (corrections.length === 0 && findingResponses.length === 0) {\n console.log(`[distill] ${author.username}@${author.host}: no corrections or finding replies yet \u2014 skipping.`);\n continue;\n }\n\n try {\n const bullets = await distillToInsights(corrections, findingResponses);\n const evidenceMrIds = [\n ...new Set([...corrections.map((c) => c.merge_request_id), ...findingResponses.map((r) => r.merge_request_id)]),\n ];\n for (const bullet of bullets) {\n insertInsight(db, {\n authorUsername: author.username,\n host: author.host,\n projectId: opts.projectId ?? null,\n category: null,\n insightText: bullet,\n evidenceMrIds,\n });\n }\n console.log(\n `[distill] ${author.username}@${author.host}: wrote ${bullets.length} insight(s) from ${corrections.length} correction(s) and ${findingResponses.length} finding repl${findingResponses.length === 1 ? \"y\" : \"ies\"}.`,\n );\n } catch (err) {\n console.error(`[distill] ${author.username}@${author.host}: failed: ${(err as Error).message}`);\n }\n }\n}\n\n/**\n * Reuses the existing structured-review contract (LLMProvider.review) rather than\n * adding a second parallel \"summarize free text\" API across all three providers \u2014 the\n * schema (category/score/findings/summary) is generic enough for this: one synthetic\n * \"insights\" category, corrections+reply text stands in for the \"diff\", and each returned\n * finding's `issue` field is one insight bullet. The `score` field is ignored entirely.\n *\n * Two distinct input kinds, both human-signal but different in nature: a correction is\n * the *reviewer* overriding a wrong automated score; a finding reply is the *contributor*\n * pushing back on or explaining one specific flagged issue. The prompt tells the model to\n * tell them apart rather than flattening both into \"the automated review was wrong.\"\n */\nasync function distillToInsights(corrections: CorrectionRow[], findingResponses: FindingResponseRow[]): Promise<string[]> {\n const provider = createLlmProvider(process.env);\n const correctionsText = corrections\n .map(\n (c) =>\n `- [correction] [${c.category ?? \"overall\"}] was scored ${c.original_score}, human corrected to ${c.corrected_score}. Reason: ${c.reason}`,\n )\n .join(\"\\n\");\n const repliesText = findingResponses\n .map(\n (r) =>\n `- [contributor reply] [${r.severity}/${r.category}] finding at ${r.file ?? \"?\"}:${r.line ?? \"?\"}: \"${r.issue}\" \u2014 contributor replied: \"${r.body}\"`,\n )\n .join(\"\\n\");\n const combinedText = [correctionsText, repliesText].filter(Boolean).join(\"\\n\");\n\n const response = await provider.review({\n diff: combinedText,\n truncated: false,\n conventions: \"\",\n categories: [\n {\n name: \"insights\",\n description:\n \"Not a code review \u2014 you are given human signal about prior automated PR reviews for one author, of two kinds. \" +\n \"'[correction]' lines are a human reviewer overriding a wrong automated score \u2014 extract what pattern the automation \" +\n \"got wrong. '[contributor reply]' lines are the contributor's own reply on one specific flagged finding \u2014 extract an \" +\n \"insight only when the reply shows the flagged pattern is actually intentional or acceptable in this codebase (so a \" +\n \"future review should stop flagging it); skip a reply that's just 'fixed' or an acknowledgement with no new \" +\n \"information. Extract 2-5 concise, reusable statements total that would help a future reviewer avoid repeating the \" +\n \"same mistake. Put each statement in a finding's `issue` field, severity 'minor' for all of them, no \" +\n \"file/line/suggestion needed.\",\n },\n ],\n authorHistorySummary: \"\",\n });\n\n const insightsCategory = response.categories.find((c) => c.category === \"insights\");\n return (insightsCategory?.findings ?? []).map((f) => f.issue);\n}\n", "import { confirm, intro, isCancel, log, multiline, multiselect, outro, select, spinner, text } from \"@clack/prompts\";\nimport { CHANGE_TYPES, CHANGE_TYPE_LABELS, describeChangeType, fitsFiles, guessForSteer, hintFromMr, parseChangeTypeMode, type ChangeType, type ChangeTypeGuess } from \"../../src/changeType.js\";\nimport { readFile } from \"node:fs/promises\";\nimport { basename, join } from \"node:path\";\nimport pc from \"picocolors\";\nimport { renderComment } from \"../../src/comment/render.js\";\nimport { scanDiffForSecrets } from \"../../src/checks/secrets.js\";\nimport { runDeterministicChecks } from \"../../src/checks/runner.js\";\nimport { getMrDiff, resolveDiffPosition, truncateDiff, type DiffResult } from \"../../src/git.js\";\nimport { changeLabel, PR_SCORE_LABEL, type ForgeClient, type ProjectRef } from \"../../src/forge/types.js\";\nimport { createLlmProvider, filterNoiseWithJev, jevEnabled, LlmParseError, withRetry, type ReviewCategorySpec } from \"../../src/llm/index.js\";\nimport { loadRubric } from \"../../src/rubric/loader.js\";\nimport { computeFinalScore, volumeFactor } from \"../../src/scoring/engine.js\";\nimport { DEFAULT_CATEGORY_DESCRIPTIONS, resolveCategory, type LlmOutcome } from \"../../src/scoring/resolve.js\";\nimport type { ScoredCategory } from \"../../src/scoring/types.js\";\nimport { keepKnownVerdicts, type ZoneReport } from \"../../src/zones/zones.js\";\nimport { isCheckoutOf, listConventionFiles, resolveProjectFiles } from \"../conventions/resolve.js\";\nimport { loadConfig } from \"../config/config.js\";\nimport { openDb } from \"../db/client.js\";\nimport { sourceFor, syncSource } from \"../sync/source.js\";\nimport { insertCorrection, insertFindingDiscussion, upsertMergeRequest, upsertProject, upsertScore, upsertZoneHits } from \"../db/repo.js\";\nimport { buildAuthorHistorySummary, zoneReportFor } from \"../memory/context.js\";\nimport { computeAuthorTrend } from \"../memory/trend.js\";\nimport { DEFAULT_CONVENTIONS_PATH } from \"../paths.js\";\nimport { clearSession, getCachedSession, saveSession } from \"./sessionCache.js\";\n\nexport interface ReviewOptions {\n forge: ForgeClient;\n project: ProjectRef;\n mrIid: number;\n pipelineId?: number;\n rubricPath?: string;\n conventionsPath?: string;\n reviewerFocus?: string;\n}\n\nexport async function runInteractiveReview(opts: ReviewOptions): Promise<void> {\n const db = openDb();\n const client = opts.forge;\n const change = changeLabel(client.type, opts.mrIid);\n\n const project = await client.getProject(opts.project);\n intro(`Yolont review \u2014 ${client.host}/${project.pathWithNamespace} ${change}`);\n // pid: the forge's numeric id, for API calls. dbProjectId: Yolont's own key, for DB calls.\n const pid = project.id;\n const mr = await client.getMergeRequest(pid, opts.mrIid);\n const dbProjectId = upsertProject(db, { ...project, host: client.host });\n const projectFiles = resolveProjectFiles(client.host, project.pathWithNamespace);\n const rubricPath = opts.rubricPath ?? projectFiles.rubric;\n const rubric = loadRubric(rubricPath);\n let conventionsPath = opts.conventionsPath ?? projectFiles.conventions;\n if (!conventionsPath) {\n const picked = await select({\n message: `No conventions for \"${project.pathWithNamespace}\" (looked in .yolont/ and ${projectFiles.dir}) \u2014 pick one for this review`,\n options: listConventionFiles().map((f) => ({ value: f, label: basename(f) })),\n initialValue: DEFAULT_CONVENTIONS_PATH,\n });\n if (isCancel(picked)) return cancelled(db);\n conventionsPath = picked as string;\n }\n log.info(`Conventions: ${conventionsPath}`);\n log.info(pc.dim(`Rubric: ${rubricPath}`));\n\n const s = spinner();\n\n // A saved review of this exact commit: resume it (no LLM cost) or review again from scratch.\n let cached = getCachedSession(pid, opts.mrIid, mr.sha);\n if (cached) {\n const choice = await select({\n message: `A review of this commit was saved ${new Date(cached.savedAt).toLocaleString()} (score ${cached.finalScore}/100)`,\n options: [\n { value: \"resume\", label: \"Use the saved review\", hint: \"no new LLM call\" },\n { value: \"fresh\", label: \"Review again\", hint: \"fetch the diff and run the LLM again\" },\n ],\n });\n if (isCancel(choice)) return cancelled(db);\n if (choice === \"fresh\") {\n clearSession(pid, opts.mrIid, mr.sha);\n cached = undefined;\n }\n }\n let finalScore: number;\n let pass: boolean;\n let scoredCategories: ScoredCategory[];\n let diffTruncated: boolean;\n let diffOmittedFiles: string[];\n let sizeFactor: number;\n let zoneReport: ZoneReport | undefined;\n // off | label (named by the review call) | steer (settled first, then type-specific checks)\n const typeMode = parseChangeTypeMode(loadConfig().changeType);\n let changeType: { type: ChangeType; reason: string } | null = null;\n let labelGuess: ChangeTypeGuess | null = null;\n // Only the non-cached path below fetches the diff this run; a resumed cached session\n // skips it entirely. Kept around (rather than only living in that branch's scope) because\n // the posting loop needs the raw diff text to resolve each finding's line position \u2014\n // re-fetched lazily there if this is still unset (see fetchDiffText).\n let diffText: string | undefined;\n\n if (cached) {\n log.info(`Resuming cached review from ${new Date(cached.savedAt).toLocaleString()} (diff + LLM skipped).`);\n if (cached.reviewerFocus) log.info(`Emphasis used: ${cached.reviewerFocus}`);\n finalScore = cached.finalScore;\n pass = cached.pass;\n scoredCategories = cached.scoredCategories;\n diffTruncated = cached.diffTruncated;\n diffOmittedFiles = cached.omittedFiles ?? [];\n sizeFactor = cached.volumeFactor ?? 1;\n zoneReport = cached.zoneReport;\n changeType = cached.changeType ?? null;\n } else {\n let reviewerFocus = opts.reviewerFocus;\n if (reviewerFocus === undefined) {\n // showSubmit: Enter always inserts a newline (so pasted paragraphs with blank lines\n // don't submit early); Tab to the [ submit ] button, then Enter.\n const focusRaw = await multiline({\n message: \"Anything specific to emphasize for this review? (optional \u2014 Tab then Enter to submit/skip)\",\n placeholder: \"e.g. focus on the retry logic in the payment client, ignore unrelated lint churn\",\n showSubmit: true,\n });\n if (isCancel(focusRaw)) return cancelled(db);\n reviewerFocus = String(focusRaw).trim() || undefined;\n }\n\n s.start(\"Fetching diff\");\n const diff = await fetchDiff(client, pid, mr, project.pathWithNamespace, rubric.max_diff_bytes);\n s.stop(\n `Diff fetched${diff.truncated ? \" (truncated)\" : \"\"}${diff.omittedFiles.length > 0 ? ` (${diff.omittedFiles.length} generated file(s) omitted)` : \"\"}`,\n );\n diffText = diff.text;\n\n zoneReport = zoneReportFor(db, dbProjectId, projectFiles, diff.files, (level, msg) => (level === \"warn\" ? log.warn(msg) : log.info(pc.dim(msg))));\n if (zoneReport) log.info(`Zones: ${zoneReport.hits.length} of ${zoneReport.zones.length} touched`);\n\n s.start(\"Scanning for secrets\");\n const secretsResult = await scanDiffForSecrets(diff.text);\n const secretsBlocked = secretsResult.scannerFailed || secretsResult.findings.length > 0;\n s.stop(\n secretsResult.scannerFailed\n ? \"gitleaks failed to run\"\n : secretsResult.findings.length > 0\n ? `${secretsResult.findings.length} potential secret(s) found`\n : \"clean\",\n );\n if (secretsResult.scannerFailed) {\n log.warn(\n `gitleaks couldn't run: ${secretsResult.scannerError}\\nInstall or update it (v8+): https://github.com/gitleaks/gitleaks#installing \u2014 the LLM is skipped until it runs (fail-closed, same as CI).`,\n );\n } else if (secretsResult.findings.length > 0) {\n const list = secretsResult.findings.map((f) => ` ${f.file}:${f.line} ${f.ruleId} (${f.description})`).join(\"\\n\");\n log.warn(\n `gitleaks flagged these lines, so the LLM is skipped (fail-closed, same as CI):\\n${list}\\nNot a real secret (a test fixture, a hash)? Add a \\`gitleaks:allow\\` comment on that line and push again.`,\n );\n }\n\n // Label: the free hint stands if the LLM is skipped; the picker after the review overrides it.\n if (typeMode === \"label\") {\n const h = hintFromMr(mr);\n changeType = h && { type: h.type, reason: h.reason };\n }\n // Steer: settle the type before the review. Free hints first; the classifier also sends the\n // diff to the LLM, so never when the secrets check blocked it.\n if (typeMode === \"steer\") {\n const hint = hintFromMr(mr);\n let guess = hint && fitsFiles(hint.type, diff.files) ? hint : null;\n if (!guess && !secretsBlocked) {\n s.start(\"Working out the change type\");\n guess = await guessForSteer((p) => createLlmProvider(process.env).complete(p), mr, diff.text, diff.files);\n s.stop(guess ? `Change type: ${CHANGE_TYPE_LABELS[guess.type]}` : \"Couldn't work out the change type\");\n }\n const picked = await pickChangeType(guess, \"The review checks this type's risks\");\n if (picked === CANCEL) return cancelled(db);\n changeType = picked;\n }\n\n const [jobs, testReportSummary] = opts.pipelineId\n ? await Promise.all([\n client.listPipelineJobs(pid, opts.pipelineId),\n client.getTestReportSummary(pid, opts.pipelineId),\n ])\n : [[], null];\n\n const detResults = runDeterministicChecks(rubric.categories, {\n diffText: diff.text,\n maxLines: rubric.max_lines,\n jobs,\n testReportSummary,\n });\n\n const llmCategories = rubric.categories.filter((c) => c.type === \"llm\" || c.type === \"hybrid\");\n let llmOutcome: LlmOutcome;\n\n if (secretsBlocked) {\n llmOutcome = { status: \"skipped\", reason: \"secrets check\" };\n } else if (llmCategories.length === 0) {\n llmOutcome = { status: \"ok\", categories: new Map() };\n } else {\n s.start(\"Running LLM review\");\n try {\n const provider = createLlmProvider(process.env);\n const conventions = await readFile(conventionsPath, \"utf8\").catch(() => \"(no CONVENTIONS.md found)\");\n const categorySpecs: ReviewCategorySpec[] = llmCategories.map((c) => ({\n name: c.name,\n description: c.description ?? DEFAULT_CATEGORY_DESCRIPTIONS[c.name] ?? \"Review this category based on the team conventions above.\",\n }));\n // This is what closes the memory loop: local corrections/insights, not the\n // GitLab-notes history src/index.ts uses. Scoped to this project + global insights.\n const authorHistorySummary = buildAuthorHistorySummary(db, { host: client.host, username: mr.authorUsername }, dbProjectId);\n\n const response = await withRetry(() =>\n provider.review({\n diff: diff.text,\n truncated: diff.truncated,\n conventions,\n categories: categorySpecs,\n authorHistorySummary,\n reviewerFocus,\n zones: zoneReport?.hits,\n changeType: typeMode === \"steer\" ? changeType?.type : undefined,\n askChangeType: typeMode === \"label\" && !hintFromMr(mr),\n }),\n );\n if (typeMode === \"label\" && !changeType && response.change_type) labelGuess = { ...response.change_type, from: \"llm\" };\n if (zoneReport) zoneReport.verdicts = keepKnownVerdicts(response.zone_verdicts, zoneReport.hits);\n s.stop(\"LLM review complete\");\n if (reviewerFocus) log.info(`Focus check: ${response.focus_notes ?? pc.dim(\"(model returned no focus notes)\")}`);\n\n const findingCountBefore = response.categories.reduce((n, c) => n + c.findings.length, 0);\n if (jevEnabled(process.env)) {\n s.start(\"Cross-checking findings with Jev\");\n }\n const filteredCategories = await filterNoiseWithJev(response.categories, diff.text, process.env, authorHistorySummary, reviewerFocus);\n if (jevEnabled(process.env)) {\n const findingCountAfter = filteredCategories.reduce((n, c) => n + c.findings.length, 0);\n s.stop(`Jev cross-check complete (${findingCountBefore - findingCountAfter} of ${findingCountBefore} findings dropped as likely noise)`);\n\n response.categories.forEach((c, ci) => {\n const kept = filteredCategories[ci]?.findings ?? [];\n const dropped = c.findings.filter((f) => !kept.includes(f));\n for (const f of dropped) {\n const loc = f.file ? ` ${f.file}${f.line ? `:${f.line}` : \"\"}` : \"\";\n log.warn(pc.dim(pc.strikethrough(`[jev-dropped] [${c.category}] [${f.severity}]${loc} ${stripStrayTags(f.issue)}`)));\n }\n });\n }\n\n const categoryMap = new Map(filteredCategories.map((c) => [c.category, { findings: c.findings, summary: c.summary }]));\n llmOutcome = { status: \"ok\", categories: categoryMap };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n llmOutcome = { status: \"error\", reason: message };\n s.stop(`LLM review failed: ${message}`);\n if (err instanceof LlmParseError && err.rawResponse) {\n log.error(`Raw LLM response:\\n${err.rawResponse.slice(0, 4000)}`);\n }\n }\n }\n\n // Label: confirm after the review (the paid result is kept whatever you pick; Esc keeps the suggestion).\n if (typeMode === \"label\" && llmOutcome.status === \"ok\") {\n const hint = hintFromMr(mr);\n const guess = hint ?? labelGuess;\n const picked = await pickChangeType(guess, \"A label only; the review is done\");\n changeType = picked === CANCEL ? (guess && { type: guess.type, reason: guess.reason }) : picked;\n }\n\n sizeFactor = volumeFactor(diff.stats, rubric.volume_scaling);\n const categoryResults = rubric.categories.map((category) =>\n resolveCategory(category, detResults, llmOutcome, rubric.severity_penalties, sizeFactor),\n );\n ({ finalScore, pass, categories: scoredCategories } = computeFinalScore(categoryResults, rubric.threshold));\n diffTruncated = diff.truncated;\n diffOmittedFiles = diff.omittedFiles;\n\n saveSession({\n projectId: pid,\n mrIid: opts.mrIid,\n sha: mr.sha,\n finalScore,\n pass,\n scoredCategories,\n diffTruncated,\n omittedFiles: diffOmittedFiles,\n volumeFactor: sizeFactor,\n reviewerFocus,\n zoneReport,\n changeType,\n });\n }\n\n printScoreSummary(finalScore, pass, rubric.threshold, scoredCategories);\n if (zoneReport) printZoneSummary(zoneReport);\n\n const mrRow = upsertMergeRequest(db, {\n projectId: dbProjectId,\n mrIid: opts.mrIid,\n authorUsername: mr.authorUsername,\n sha: mr.sha,\n title: mr.title,\n mergedAt: null,\n source: \"live\",\n });\n\n // Saved before the agree/correct prompts: corrections below are timestamped after\n // scored_at, so refreshScores applies them (and ignores ones from older reviews).\n upsertScore(db, {\n mergeRequestId: mrRow.id,\n scoredAt: new Date().toISOString(),\n finalScore,\n categoryScores: Object.fromEntries(scoredCategories.map((c) => [c.name, c.score])),\n findings: scoredCategories.flatMap((c) => c.findings.map((f) => ({ ...f, category: c.name }))),\n source: \"llm_live\",\n volumeFactor: sizeFactor,\n base: scoredCategories,\n changeType: changeType?.type ?? null,\n modelUsed: process.env.ANTHROPIC_MODEL ?? process.env.OPENCODE_ZEN_MODEL ?? process.env.OLLAMA_MODEL,\n });\n if (zoneReport) upsertZoneHits(db, mrRow.id, zoneReport);\n\n const agree = await confirm({ message: `Agree with the computed score (${finalScore}/100)?` });\n if (isCancel(agree)) return cancelled(db);\n\n if (!agree) {\n const categoryChoices = await multiselect({\n message: \"Which should be corrected? (space to toggle, enter to confirm)\",\n options: [\n { value: \"__overall__\", label: `Overall score (${finalScore}/100)` },\n ...scoredCategories.map((c) => ({ value: c.name, label: `${c.name} (${c.score}/100)` })),\n ],\n required: true,\n });\n if (isCancel(categoryChoices)) return cancelled(db);\n const selectedCategories = categoryChoices as string[];\n\n const categoryCorrections = new Map<string, { score: number; note?: string }>();\n let overallCorrection: number | undefined;\n let appliedCount = 0;\n\n for (const categoryChoice of selectedCategories) {\n const isOverall = categoryChoice === \"__overall__\";\n const category = isOverall ? undefined : scoredCategories.find((c) => c.name === categoryChoice)!;\n const original = isOverall ? finalScore : category!.score;\n const label = isOverall ? \"overall\" : categoryChoice;\n\n if (category && category.findings.length > 0) {\n log.message(`Findings for ${label}:`);\n for (const f of category.findings) {\n const loc = f.file ? ` ${f.file}${f.line ? `:${f.line}` : \"\"}` : \"\";\n log.message(` - [${f.severity}]${loc} ${stripStrayTags(f.issue)}`);\n if (f.suggestion) log.message(` suggestion: ${stripStrayTags(f.suggestion)}`);\n }\n }\n\n const correctedRaw = await text({\n message: `[${label}] Corrected score (was ${original}, Enter to keep)`,\n validate: (v) => {\n if ((v ?? \"\").trim() === \"\") return undefined;\n const n = Number(v);\n return Number.isFinite(n) && n >= 0 && n <= 100 ? undefined : \"Enter a number 0-100\";\n },\n });\n if (isCancel(correctedRaw)) return cancelled(db);\n const correctedRawTrimmed = String(correctedRaw).trim();\n const correctedScore = correctedRawTrimmed === \"\" ? original : Number(correctedRawTrimmed);\n\n const originalNote = category?.note ?? \"\";\n const correctedNoteRaw = await text({\n message: `[${label}] Corrected description (edit or leave as-is)`,\n initialValue: originalNote,\n });\n if (isCancel(correctedNoteRaw)) return cancelled(db);\n const correctedNoteTrimmed = String(correctedNoteRaw).trim();\n\n const noChange = correctedScore === original && correctedNoteTrimmed === originalNote.trim();\n if (noChange) {\n log.info(`[${label}] No change \u2014 skipping.`);\n continue;\n }\n\n const reasonRaw = await text({\n message: `[${label}] Why? (optional \u2014 becomes memory context for future reviews of this author)`,\n });\n if (isCancel(reasonRaw)) return cancelled(db);\n const reason = String(reasonRaw ?? \"\").trim();\n\n insertCorrection(db, {\n mergeRequestId: mrRow.id,\n category: isOverall ? null : (categoryChoice as string),\n originalScore: original,\n correctedScore,\n correctedNote: correctedNoteTrimmed || undefined,\n reason,\n });\n\n if (isOverall) {\n overallCorrection = correctedScore;\n } else {\n categoryCorrections.set(categoryChoice, { score: correctedScore, note: correctedNoteTrimmed || undefined });\n }\n appliedCount++;\n }\n\n if (appliedCount === 0) {\n log.info(\"No corrections applied.\");\n } else {\n log.success(`${appliedCount} correction(s) saved \u2014 will be used as memory context in future reviews of this author.`);\n\n const updatedCategories = scoredCategories.map((c) => {\n const corr = categoryCorrections.get(c.name);\n return corr ? { ...c, score: corr.score, note: corr.note ?? c.note } : c;\n });\n // Same math refreshScores runs on the stored row, so the TUI and DB/panel agree.\n const recomputed = computeFinalScore(updatedCategories, rubric.threshold);\n scoredCategories = recomputed.categories;\n finalScore = overallCorrection ?? recomputed.finalScore;\n pass = finalScore >= rubric.threshold;\n }\n }\n\n\n const shouldPost = await confirm({\n message: `Post this score as a comment on ${change}?`,\n initialValue: false,\n });\n if (isCancel(shouldPost)) return cancelled(db);\n\n if (shouldPost) {\n const trend = computeAuthorTrend(db, { host: client.host, username: mr.authorUsername });\n await client.upsertPrScoreNote(\n pid,\n opts.mrIid,\n renderComment({\n finalScore,\n pass,\n gate: rubric.gate,\n threshold: rubric.threshold,\n truncatedDiff: diffTruncated,\n omittedFiles: diffOmittedFiles,\n categories: scoredCategories,\n projectWebUrl: project.webUrl,\n forge: client.type,\n changeType: changeType ? describeChangeType(changeType.type, changeType.reason) : undefined,\n sha: mr.sha,\n trend: { recentScores: trend.recentScores, weakestCategory: null },\n record: {\n projectId: pid,\n mrIid: opts.mrIid,\n sha: mr.sha,\n scoredAt: new Date().toISOString(),\n finalScore,\n categoryScores: Object.fromEntries(scoredCategories.map((c) => [c.name, c.score])),\n topFindings: scoredCategories.flatMap((c) => c.findings.map((f) => f.issue)).slice(0, 5),\n },\n zones: zoneReport,\n }),\n );\n log.success(`Posted to ${client.host}.`);\n\n const findingsWithFile = scoredCategories.flatMap((c) =>\n c.findings.filter((f) => f.file && f.line != null).map((f) => ({ ...f, category: c.name })),\n );\n if (findingsWithFile.length > 0 && diffText === undefined) {\n // Cached-session resume skipped the diff fetch entirely this run, but posting still\n // needs the raw diff to work out each finding's old_line/new_line (see below).\n diffText = (await fetchDiff(client, pid, mr, project.pathWithNamespace, rubric.max_diff_bytes)).text;\n }\n\n let postedThreads = 0;\n for (const finding of findingsWithFile) {\n // GitLab rejects a position that only sets new_line unless that line was actually\n // added \u2014 a comment on an unchanged/context line needs old_line too, or GitLab 400s\n // and the finding silently never appears as an inline comment (the original bug here:\n // whichever findings happened to land on context lines vs. added lines).\n const resolvedPosition = resolveDiffPosition(diffText!, finding.file!, finding.line!);\n if (!resolvedPosition) {\n log.warn(`Skipping finding thread for ${finding.file}:${finding.line} \u2014 line not found in the diff.`);\n continue;\n }\n\n const body = [\n `**[${finding.severity}/${finding.category}] Yolont finding**`,\n \"\",\n finding.issue,\n finding.suggestion ? `\\n_Suggestion: ${finding.suggestion}_` : \"\",\n \"\",\n \"<sub>Reply here to explain or say you've fixed it \u2014 future reviews will use it as context.</sub>\",\n ].join(\"\\n\");\n try {\n const { discussionId, noteId } = await client.postFindingDiscussion(pid, opts.mrIid, body, {\n ...mr.diffRefs,\n filePath: finding.file!,\n line: resolvedPosition.newLine,\n oldLine: resolvedPosition.oldLine,\n });\n insertFindingDiscussion(db, {\n mergeRequestId: mrRow.id,\n discussionId,\n category: finding.category,\n severity: finding.severity,\n issue: finding.issue,\n file: finding.file,\n line: finding.line,\n postedNoteId: noteId,\n });\n postedThreads++;\n } catch (err) {\n log.warn(`Could not post finding thread for ${finding.file}:${finding.line}: ${(err as Error).message}`);\n }\n }\n if (postedThreads > 0) log.success(`Posted ${postedThreads} finding thread(s) \u2014 replies can be pulled back with 'sync-replies'.`);\n } else {\n log.info(\"Not posted (read-only / local phase).\");\n }\n\n const shouldLabel = await confirm({\n message: `Add the '${PR_SCORE_LABEL}' label to ${change}?`,\n initialValue: Boolean(shouldPost),\n });\n if (isCancel(shouldLabel)) return cancelled(db);\n if (shouldLabel && (await client.markReviewed(pid, opts.mrIid))) log.success(`Labeled '${PR_SCORE_LABEL}'.`);\n\n clearSession(pid, opts.mrIid, mr.sha);\n await sendToTeam(db, client.host, project.pathWithNamespace);\n outro(\"Done.\");\n db.close();\n}\n\nconst CANCEL = Symbol(\"cancel\");\n\n/** The suggested type first (Enter keeps it), the others, or none. */\nasync function pickChangeType(guess: ChangeTypeGuess | null, hint: string): Promise<{ type: ChangeType; reason: string } | null | typeof CANCEL> {\n const picked = await select({\n message: guess ? `Change type \u2014 suggested: ${CHANGE_TYPE_LABELS[guess.type]} (${guess.from === \"hint\" ? guess.reason : `LLM: ${guess.reason}`})` : \"Change type (no suggestion)\",\n options: [\n ...(guess ? [{ value: guess.type, label: `${CHANGE_TYPE_LABELS[guess.type]} (suggested)`, hint }] : []),\n ...CHANGE_TYPES.filter((t) => t !== guess?.type).map((t) => ({ value: t, label: CHANGE_TYPE_LABELS[t] })),\n { value: \"none\", label: \"No type\" },\n ],\n initialValue: guess?.type ?? \"none\",\n });\n if (isCancel(picked)) return CANCEL;\n if (picked === \"none\") return null;\n return { type: picked as ChangeType, reason: picked === guess?.type ? guess.reason : \"set by the reviewer\" };\n}\n\n/** A shared project's review goes to its team data repo right away; failing only warns (the next sync retries). */\nasync function sendToTeam(db: ReturnType<typeof openDb>, host: string, path: string): Promise<void> {\n const source = sourceFor(host, path);\n if (!source?.autoSync) return;\n const s = spinner();\n s.start(`Sending to team data ${source.name}`);\n try {\n const r = await syncSource(db, source);\n s.stop(`Team data ${source.name}: sent ${r.sent}, got ${r.imported}`);\n } catch (err) {\n s.error(`Team data ${source.name}: not sent (kept here; the next sync tries again)`);\n log.warn((err as Error).message);\n }\n}\n\n/**\n * Local `git diff` is complete (the forge diff APIs truncate big files), but it's only the\n * right diff when cwd is a checkout of *this* project with the MR/PR head checked out \u2014\n * `review <URL>` from any other directory would otherwise score an unrelated diff.\n */\nasync function fetchDiff(client: ForgeClient, pid: ProjectRef, mr: { iid: number; sha: string; targetBranch: string }, pathWithNamespace: string, maxDiffBytes: number): Promise<DiffResult> {\n if (isCheckoutOf(pathWithNamespace, mr.sha)) {\n try {\n return await getMrDiff({ targetBranch: mr.targetBranch, baseSha: process.env.CI_MERGE_REQUEST_DIFF_BASE_SHA }, maxDiffBytes);\n } catch {\n /* fall back to the API */\n }\n }\n return truncateDiff(await client.getMrDiffText(pid, mr.iid), maxDiffBytes);\n}\n\n// minimax-m3 (free-tier fallback) occasionally leaks its own JSON-delimiter\n// tags (e.g. \"</summary></item>\") into free-text fields; strip for terminal display.\nfunction stripStrayTags(s: string): string {\n return s.replace(/<\\/?[a-z_]+>/gi, \"\").trim();\n}\n\nconst SEVERITY_COLOR: Record<string, (s: string) => string> = {\n critical: pc.red,\n major: pc.yellow,\n minor: pc.gray,\n};\n\nfunction printScoreSummary(finalScore: number, pass: boolean, threshold: number, categories: ScoredCategory[]): void {\n const scoreColor = pass ? pc.green : pc.red;\n console.log(\"\");\n console.log(`${pc.bold(\"Score:\")} ${scoreColor(pc.bold(`${finalScore}/100`))} ${pass ? pc.green(\"(pass\") : pc.red(\"(fail\")} vs threshold ${threshold})`);\n for (const c of categories) {\n const status = !c.available ? pc.gray(\"excluded\") : c.score >= 70 ? pc.green(\"ok\") : pc.yellow(\"needs work\");\n const scoreColorFn = !c.available ? pc.gray : c.score >= 70 ? pc.green : pc.yellow;\n const scorePadded = `${String(c.score).padStart(3)}/100`;\n console.log(` ${pc.bold(c.name.padEnd(20))} ${scoreColorFn(scorePadded)} ${status}`);\n if (c.note) console.log(pc.dim(` ${stripStrayTags(c.note)}`));\n for (const f of c.findings) {\n const color = SEVERITY_COLOR[f.severity] ?? pc.white;\n const loc = f.file ? ` ${f.file}${f.line ? `:${f.line}` : \"\"}` : \"\";\n console.log(` - ${color(pc.bold(`[${f.severity}]`))}${pc.dim(loc)} ${stripStrayTags(f.issue)}`);\n if (f.suggestion) console.log(pc.cyan(` suggestion: ${stripStrayTags(f.suggestion)}`));\n }\n }\n console.log(\"\");\n}\n\nconst LEVEL_COLOR = { red: pc.red, amber: pc.yellow, green: pc.green } as const;\n\nfunction printZoneSummary(report: ZoneReport): void {\n if (report.hits.length === 0) return;\n console.log(pc.bold(\"Zones touched:\"));\n for (const { zone, files, viaImport } of report.hits) {\n const verdict = report.verdicts.find((v) => v.zone_id === zone.id);\n console.log(` ${LEVEL_COLOR[zone.level](pc.bold(`[${zone.level}]`))} ${zone.id}${verdict ? ` \u2014 impact ${verdict.impact}: ${stripStrayTags(verdict.verdict)}` : \"\"}`);\n console.log(pc.dim(` ${files.map((f) => (viaImport?.includes(f) ? `${f} (via import)` : f)).join(\", \")}`));\n }\n console.log(\"\");\n}\n\nfunction cancelled(db: ReturnType<typeof openDb>): void {\n outro(\"Review stopped.\");\n db.close();\n}\n", "import { PR_SCORE_MARKER, type ForgeType } from \"../forge/types.js\";\nimport type { HistoryTrend } from \"../history/summarize.js\";\nimport type { AuthorHistoryRecord } from \"../history/types.js\";\nimport type { Finding, ScoredCategory } from \"../scoring/types.js\";\nimport { renderZonesMermaid, type ZoneReport } from \"../zones/zones.js\";\n\nexport interface RenderInput {\n finalScore: number;\n pass: boolean;\n gate: boolean;\n threshold: number;\n truncatedDiff: boolean;\n omittedFiles?: string[];\n categories: ScoredCategory[];\n projectWebUrl: string;\n /** File-link shape: GitLab `/-/blob/`, GitHub `/blob/`. Default gitlab. */\n forge?: ForgeType;\n sha: string;\n trend: HistoryTrend;\n record: AuthorHistoryRecord;\n zones?: ZoneReport;\n /** \"Refactor (title prefix \"refactor:\")\" */\n changeType?: string;\n}\n\nconst LEVEL_EMOJI = { red: \"\uD83D\uDD34\", amber: \"\uD83D\uDFE1\", green: \"\uD83D\uDFE2\" } as const;\n\nconst SEVERITY_RANK: Record<Finding[\"severity\"], number> = { critical: 0, major: 1, minor: 2 };\nconst MAX_FINDINGS = 5;\n\nexport function renderComment(input: RenderInput): string {\n const headerEmoji = input.finalScore >= input.threshold ? \"\uD83D\uDFE2\" : input.finalScore >= input.threshold - 15 ? \"\uD83D\uDFE1\" : \"\uD83D\uDD34\";\n const badge = input.gate ? (input.pass ? \"PASS\" : \"FAIL\") : \"INFORMATIONAL\";\n\n const lines: string[] = [];\n lines.push(PR_SCORE_MARKER);\n lines.push(`## ${headerEmoji} PR Score: ${input.finalScore} / 100`);\n lines.push(\"\");\n lines.push(`**Status:** ${badge} (threshold ${input.threshold}${input.gate ? \"\" : \" \u2014 not gating this pipeline\"})`);\n if (input.changeType) lines.push(\"\", `**Type:** ${escapeHtml(input.changeType)}`);\n if (input.truncatedDiff) {\n lines.push(\"\");\n lines.push(\"_Diff truncated to fit the configured size limit \u2014 review is based on the truncated content._\");\n }\n if (input.omittedFiles && input.omittedFiles.length > 0) {\n lines.push(\"\");\n lines.push(`_${input.omittedFiles.length} generated/vendored file(s) omitted from review: ${input.omittedFiles.join(\", \")}._`);\n }\n lines.push(\"\");\n\n lines.push(\"| Category | Score | Weight | Status |\");\n lines.push(\"|---|---|---|---|\");\n for (const c of input.categories) {\n const status = !c.available ? \"excluded (no data)\" : c.score >= 70 ? \"ok\" : \"needs work\";\n lines.push(`| ${c.name} | ${c.score}/100 | ${Math.round(c.effectiveWeight)}% | ${status} |`);\n }\n lines.push(\"\");\n\n // Each category's `note` carries the LLM's own narrative summary (pros as well as\n // cons \u2014 e.g. \"Mostly compliant; one naming violation\") for llm/hybrid categories, or\n // the deterministic check's own explanation otherwise. Without this, a well-scoring\n // category (nothing in \"Top findings\" below, which only lists negatives) shows up as\n // a bare number with no stated reason why.\n const categoryNotes = input.categories.filter((c) => c.note);\n if (categoryNotes.length > 0) {\n lines.push(\"### Category notes\");\n for (const c of categoryNotes) {\n lines.push(`- **${c.name}**: ${escapeHtml(c.note!)}`);\n }\n lines.push(\"\");\n }\n\n const allFindings = input.categories\n .flatMap((c) => c.findings.map((f) => ({ ...f, category: c.name })))\n .sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity])\n .slice(0, MAX_FINDINGS);\n\n if (allFindings.length > 0) {\n lines.push(\"### Top findings\");\n for (const f of allFindings) {\n const location = f.file ? ` (${linkToFile(input.projectWebUrl, input.forge ?? \"gitlab\", input.sha, f.file, f.line)})` : \"\";\n const issue = escapeHtml(f.issue);\n const suggestion = f.suggestion ? ` \u2014 _${escapeHtml(f.suggestion)}_` : \"\";\n lines.push(`- **[${f.severity}/${f.category}]** ${issue}${location}${suggestion}`);\n }\n lines.push(\"\");\n }\n\n if (input.zones && input.zones.hits.length > 0) {\n lines.push(...renderZonesSection(input.zones));\n }\n\n if (input.trend.recentScores.length > 0) {\n const trendLine = input.trend.weakestCategory\n ? `Last ${input.trend.recentScores.length} score(s): ${input.trend.recentScores.join(\", \")}. Recurring weak category: **${input.trend.weakestCategory.name}** (avg ${input.trend.weakestCategory.avgScore}/100).`\n : `Last ${input.trend.recentScores.length} score(s): ${input.trend.recentScores.join(\", \")}.`;\n lines.push(`### Author trend\\n${trendLine}`);\n lines.push(\"\");\n }\n\n lines.push(\"<details><summary>Raw JSON</summary>\");\n lines.push(\"\");\n // Wrapped in our own HTML-comment markers, not just a ```json fence: a finding's `issue`\n // text can itself contain a stray code fence (e.g. quoting JSON), and history rebuild\n // (history/rebuild.ts) must find *this* block, not a fence that happens to appear earlier\n // in the Top findings section above. An LLM reproducing our exact marker text is not\n // a realistic collision; a bare ``` is.\n lines.push(JSON_DATA_START);\n lines.push(\"```json\");\n lines.push(JSON.stringify(input.record, null, 2));\n lines.push(\"```\");\n lines.push(JSON_DATA_END);\n lines.push(\"\");\n lines.push(\"</details>\");\n\n return lines.join(\"\\n\");\n}\n\n/** Informational only \u2014 zone verdicts never feed the score. */\nfunction renderZonesSection(report: ZoneReport): string[] {\n const lines = [\"### Zones\", \"\", renderZonesMermaid(report.zones, report.hits), \"\"];\n for (const { zone, files, viaImport } of report.hits) {\n const verdict = report.verdicts.find((v) => v.zone_id === zone.id);\n const verdictText = verdict ? ` \u2014 impact **${verdict.impact}**: ${escapeHtml(verdict.verdict)}` : \"\";\n lines.push(`- ${LEVEL_EMOJI[zone.level]} **${zone.id}** (${zone.level})${verdictText}`);\n lines.push(` <sub>${files.map((f) => `\\`${escapeHtml(f)}\\`${viaImport?.includes(f) ? \" (imported by this zone)\" : \"\"}`).join(\", \")}</sub>`);\n }\n lines.push(\"\");\n return lines;\n}\n\nexport const JSON_DATA_START = \"<!-- pr-score-json:start -->\";\nexport const JSON_DATA_END = \"<!-- pr-score-json:end -->\";\n\nexport function renderSkippedComment(reason: string): string {\n return `${PR_SCORE_MARKER}\\n## \u26AA Yolont skipped\\n\\n${reason}`;\n}\n\nexport function renderFastFailComment(reason: string): string {\n return `${PR_SCORE_MARKER}\\n## \uD83D\uDD34 Yolont: build broken\\n\\n${reason}\\n\\nLLM review skipped to save cost \u2014 fix the build first.`;\n}\n\nexport function renderSecretsBlockedComment(findings: SecretFindingSummary[]): string {\n // File/line/rule only \u2014 never the secret value itself (gitleaks already runs with\n // --redact). Without at least this much, a dev has to re-run gitleaks locally just to\n // find what tripped the scan.\n const list = findings.map((f) => `- \\`${f.ruleId}\\` in ${f.file}${f.line ? `:${f.line}` : \"\"}`).join(\"\\n\");\n return (\n `${PR_SCORE_MARKER}\\n## \uD83D\uDD34 Yolont: secrets detected\\n\\n` +\n `${findings.length} potential secret(s) found in this diff. The diff was never sent to the LLM.\\n\\n` +\n `${list}\\n\\n` +\n `This is a hard failure independent of the rubric's \\`gate\\` setting \u2014 remove the secret(s) and rotate them, then push again.`\n );\n}\n\nexport interface SecretFindingSummary {\n ruleId: string;\n file: string;\n line: number;\n}\n\nexport function renderErrorComment(context: string, message: string): string {\n return (\n `${PR_SCORE_MARKER}\\n## \u26AA Yolont: error (${context})\\n\\n` +\n `${message}\\n\\nThis is a tooling failure, not a review \u2014 never treat this as a silent pass or fail on its own.`\n );\n}\n\nexport function renderSecretsScanFailedComment(errorMessage: string): string {\n return (\n `${PR_SCORE_MARKER}\\n## \uD83D\uDD34 Yolont: secret scan could not run\\n\\n` +\n `gitleaks failed to run (\\`${errorMessage}\\`) \u2014 this is a tooling problem, **not** a confirmed secret. ` +\n `The diff was not sent to the LLM out of caution. Check the Yolont image/runner setup and retry.`\n );\n}\n\nfunction linkToFile(projectWebUrl: string, forge: ForgeType, sha: string, file: string, line?: number): string {\n const url = `${projectWebUrl.replace(/\\/$/, \"\")}/${forge === \"github\" ? \"blob\" : \"-/blob\"}/${sha}/${encodeURI(file)}`;\n const label = escapeHtml(file);\n return line ? `[${label}:${line}](${url}#L${line})` : `[${label}](${url})`;\n}\n\n/**\n * Every string here (issue/suggestion/note/file) ultimately comes from the LLM's\n * response, not our own code \u2014 the model can put anything in a free-text field,\n * including HTML. Rendering it unescaped into a comment GitLab renders as\n * markdown+HTML (we deliberately use raw <details>/<summary> ourselves) is a real\n * injection surface: a crafted diff could coax the model into emitting arbitrary\n * markup. Observed in practice (not hypothetical) as a stray literal\n * `</summary></item>` fragment leaking out of a model's category summary and\n * corrupting the rendered comment's structure.\n */\nfunction escapeHtml(text: string): string {\n return text.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\");\n}\n", "import type { DatabaseSync } from \"node:sqlite\";\nimport { listAuthorScores, type AuthorKey } from \"../db/repo.js\";\n\nexport interface AuthorTrend {\n recentScores: number[];\n /** Least-squares slope over recent scores (score/MR). Positive = improving. */\n slope: number;\n /** Naive one-step-ahead projection: last score + slope, clamped to [0, 100]. */\n projectedNextScore: number | null;\n label: \"improving\" | \"declining\" | \"stable\" | \"insufficient-data\";\n}\n\nconst STABLE_SLOPE_THRESHOLD = 1.5; // score points per MR\n\n/**\n * Forward-looking trend from real accumulated scores \u2014 plain least-squares linear\n * regression over (index, final_score), not a trained model. Deliberately simple and\n * transparent: this is the \"statistical, not ML\" half of the (a)+(b) memory design.\n */\nexport function computeAuthorTrend(db: DatabaseSync, author: AuthorKey, lastN = 10): AuthorTrend {\n const rows = listAuthorScores(db, author).slice(-lastN);\n const recentScores = rows.map((r) => r.final_score);\n\n if (recentScores.length < 2) {\n return { recentScores, slope: 0, projectedNextScore: recentScores[0] ?? null, label: \"insufficient-data\" };\n }\n\n const slope = leastSquaresSlope(recentScores);\n const last = recentScores[recentScores.length - 1]!;\n const projectedNextScore = Math.max(0, Math.min(100, Math.round(last + slope)));\n\n const label: AuthorTrend[\"label\"] =\n slope > STABLE_SLOPE_THRESHOLD ? \"improving\" : slope < -STABLE_SLOPE_THRESHOLD ? \"declining\" : \"stable\";\n\n return { recentScores, slope, projectedNextScore, label };\n}\n\nfunction leastSquaresSlope(values: number[]): number {\n const n = values.length;\n const xs = Array.from({ length: n }, (_, i) => i);\n const xMean = xs.reduce((a, b) => a + b, 0) / n;\n const yMean = values.reduce((a, b) => a + b, 0) / n;\n\n let numerator = 0;\n let denominator = 0;\n for (let i = 0; i < n; i++) {\n numerator += (xs[i]! - xMean) * (values[i]! - yMean);\n denominator += (xs[i]! - xMean) ** 2;\n }\n return denominator === 0 ? 0 : numerator / denominator;\n}\n", "import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport type { ScoredCategory } from \"../../src/scoring/types.js\";\nimport type { ZoneReport } from \"../../src/zones/zones.js\";\nimport { SESSIONS_PATH as CACHE_PATH } from \"../paths.js\";\n\nconst MAX_SESSIONS = 3;\n\nimport type { ChangeType } from \"../../src/changeType.js\";\n\nexport interface CachedReviewSession {\n projectId: number;\n mrIid: number;\n sha: string;\n savedAt: string;\n finalScore: number;\n pass: boolean;\n scoredCategories: ScoredCategory[];\n diffTruncated: boolean;\n omittedFiles?: string[];\n volumeFactor?: number;\n reviewerFocus?: string;\n zoneReport?: ZoneReport;\n /** Settled change type (src/changeType.ts) and why. */\n changeType?: { type: ChangeType; reason: string } | null;\n}\n\nfunction key(projectId: number, mrIid: number, sha: string): string {\n return `${projectId}:${mrIid}:${sha}`;\n}\n\nfunction readAll(): CachedReviewSession[] {\n if (!existsSync(CACHE_PATH)) return [];\n try {\n return JSON.parse(readFileSync(CACHE_PATH, \"utf8\"));\n } catch {\n return [];\n }\n}\n\nfunction writeAll(sessions: CachedReviewSession[]): void {\n mkdirSync(dirname(CACHE_PATH), { recursive: true });\n writeFileSync(CACHE_PATH, JSON.stringify(sessions, null, 2));\n}\n\n/** A prior in-progress review left un-finished (terminated before agree/correct/post) \u2014 if\n * still cached, resume from it instead of re-fetching the diff and re-running the LLM. */\nexport function getCachedSession(projectId: number, mrIid: number, sha: string): CachedReviewSession | undefined {\n return readAll().find((s) => key(s.projectId, s.mrIid, s.sha) === key(projectId, mrIid, sha));\n}\n\n/** Called right after scoring, before the agree/correct/post prompts \u2014 so a Ctrl-C or\n * cancel anywhere in that flow leaves the expensive part (diff + LLM) resumable. Capped\n * at MAX_SESSIONS, oldest evicted first \u2014 this is a short-lived crash recovery aid, not a\n * review history (that's the sqlite `scores` table). */\nexport function saveSession(session: Omit<CachedReviewSession, \"savedAt\">): void {\n const sessions = readAll().filter((s) => key(s.projectId, s.mrIid, s.sha) !== key(session.projectId, session.mrIid, session.sha));\n sessions.push({ ...session, savedAt: new Date().toISOString() });\n sessions.sort((a, b) => a.savedAt.localeCompare(b.savedAt));\n while (sessions.length > MAX_SESSIONS) sessions.shift();\n writeAll(sessions);\n}\n\n/** Called once a review finishes cleanly (agree/correct + post decision both made) \u2014 the\n * cached copy is only for resuming an interrupted run, not a completed one. */\nexport function clearSession(projectId: number, mrIid: number, sha: string): void {\n writeAll(readAll().filter((s) => key(s.projectId, s.mrIid, s.sha) !== key(projectId, mrIid, sha)));\n}\n", "import type { DatabaseSync } from \"node:sqlite\";\nimport { changeLabel, type ForgeClient, type ProjectRef } from \"../../src/forge/types.js\";\nimport { openDb } from \"../db/client.js\";\nimport { findProjectId, getMergeRequestByProjectAndIid, insertFindingResponse, listFindingDiscussionsForMr } from \"../db/repo.js\";\n\nexport interface SyncRepliesOptions {\n forge: ForgeClient;\n project: ProjectRef;\n mrIid: number;\n}\n\nexport interface SyncRepliesResult {\n /** Finding threads this review posted. 0 = nothing to sync (the review wasn't posted). */\n tracked: number;\n newReplies: number;\n updatedReplies: number;\n /** Threads that got a new or edited reply. */\n threads: number;\n}\n\n/**\n * Pulls contributor replies (new and edited) on the finding threads `review` posted for one\n * MR. Read + DB only, no LLM cost; turning replies into insights is a separate `distill`.\n * Shared by `yolont sync-replies` and the panel's review page.\n */\nexport async function syncRepliesForMr(db: DatabaseSync, forge: ForgeClient, forgeProject: ProjectRef, mrIid: number, mergeRequestId: number): Promise<SyncRepliesResult> {\n const tracked = listFindingDiscussionsForMr(db, mergeRequestId);\n const result: SyncRepliesResult = { tracked: tracked.length, newReplies: 0, updatedReplies: 0, threads: 0 };\n if (tracked.length === 0) return result;\n\n const me = await forge.getCurrentUser();\n const threadsById = new Map((await forge.listMrDiscussionThreads(forgeProject, mrIid)).map((t) => [t.discussionId, t.notes]));\n for (const t of tracked) {\n const replies = (threadsById.get(t.discussion_id) ?? []).filter((n) => n.id !== t.posted_note_id && n.authorUsername !== me.username);\n let changed = false;\n for (const reply of replies) {\n const outcome = insertFindingResponse(db, { findingDiscussionId: t.id, noteId: reply.id, authorUsername: reply.authorUsername, body: reply.body, createdAt: reply.createdAt });\n if (outcome === \"new\") result.newReplies++;\n if (outcome === \"updated\") result.updatedReplies++;\n if (outcome) changed = true;\n }\n if (changed) result.threads++;\n }\n return result;\n}\n\nexport const describeSyncReplies = (r: SyncRepliesResult): string =>\n r.tracked === 0\n ? \"This review has no posted finding threads, so there are no replies to get.\"\n : `${r.newReplies} new repl${r.newReplies === 1 ? \"y\" : \"ies\"}${r.updatedReplies ? `, ${r.updatedReplies} edited` : \"\"} across ${r.threads} of ${r.tracked} finding thread(s).`;\n\n/** `yolont sync-replies <MR/PR URL>`. */\nexport async function runSyncReplies(opts: SyncRepliesOptions): Promise<void> {\n const db = openDb();\n try {\n const client = opts.forge;\n // A path (\"owner/repo\") from a URL must become the numeric id the DB is keyed by.\n const forgeId = typeof opts.project === \"number\" || /^\\d+$/.test(opts.project) ? opts.project : (await client.getProject(opts.project)).id;\n const dbProjectId = findProjectId(db, client.host, forgeId);\n const mrRow = dbProjectId === undefined ? undefined : getMergeRequestByProjectAndIid(db, dbProjectId, opts.mrIid);\n if (!mrRow) throw new Error(`No tracked findings for ${client.host} project ${opts.project} ${changeLabel(client.type, opts.mrIid)} \u2014 run 'review' and post it first.`);\n console.log(`[sync-replies] ${describeSyncReplies(await syncRepliesForMr(db, client, forgeId, opts.mrIid, mrRow.id))}`);\n } finally {\n db.close();\n }\n}\n", "import fastifyStatic from \"@fastify/static\";\nimport { describeSyncReplies, syncRepliesForMr } from \"../review/syncReplies.js\";\nimport Fastify, { type FastifyInstance, type FastifyReply } from \"fastify\";\nimport { randomBytes, timingSafeEqual } from \"node:crypto\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { join } from \"node:path\";\nimport { INSTALL_ROOT } from \"../paths.js\";\nimport type { ForgeClient } from \"../../src/forge/types.js\";\nimport { loadConfig } from \"../config/config.js\";\nimport { openDb } from \"../db/client.js\";\nimport {\n addFindingTag,\n commentVolumeByAuthor,\n deleteCorrection,\n deleteFindingVote,\n deleteInsight,\n deleteMergeRequest,\n deleteScore,\n getMergeRequestById,\n listAuthorComments,\n listAuthorCorrections,\n listAuthorScores,\n listAuthors,\n listCommentsForMr,\n listCorrectionsForMr,\n listDangerTaggedFindings,\n listFindingsForMr,\n listInsights,\n listReviews,\n listScoresForMr,\n listZoneHitsForMr,\n listZoneHitsForProject,\n queryFindings,\n removeFindingTag,\n setZoneHitVote,\n updateCorrection,\n upsertFindingVote,\n} from \"../db/repo.js\";\nimport { computeAuthorTrend } from \"../memory/trend.js\";\nimport { syncFindingDecision, type Vote } from \"../review/syncDecision.js\";\nimport { registerSettings } from \"./settings.js\";\nimport { describeRun, displayUrl, insightSource, ownerOfProject, pendingToSend, projectOwners, waitingForMerge, syncAll, type SourceRun } from \"../sync/source.js\";\nimport type { SourceConfig } from \"../config/config.js\";\n\nconst FINDING_TAGS = [\n \"technical-debt\",\n \"security\",\n \"performance\",\n \"bug-risk\",\n \"breaking-change\",\n \"missing-tests\",\n \"style\",\n \"documentation\",\n \"duplication\",\n \"accessibility\",\n \"danger-zone\",\n] as const;\n\nconst WEB_DIST = join(INSTALL_ROOT, \"local\", \"backoffice\", \"web\", \"dist\");\n\nexport interface DashboardOptions {\n port?: number;\n /** Client for a finding's forge host \u2014 enables posting vote/tag decisions back to its thread. */\n forgeFor?: (host: string) => ForgeClient;\n}\n\nexport interface PanelOptions extends DashboardOptions {\n db: DatabaseSync;\n /** Required on every /api request as `Authorization: Bearer <token>`. */\n token: string;\n port: number;\n /** Sync every auto-sync team data repo in the background once built (the real panel; not tests). */\n syncOnStart?: boolean;\n}\n\n/**\n * The panel app, not yet listening (tests use `inject`). Security, before any route:\n * - only Host 127.0.0.1:<port> / localhost:<port> (blocks DNS rebinding);\n * - every /api/* route needs the per-start token in a header (a cross-site form or <img>\n * can't attach one, so no CSRF). Static files carry no data and stay open.\n */\nexport async function buildPanel(opts: PanelOptions): Promise<FastifyInstance> {\n const { db } = opts;\n const app = Fastify({ logger: false });\n const want = Buffer.from(opts.token);\n const hosts = new Set([`127.0.0.1:${opts.port}`, `localhost:${opts.port}`]);\n app.addHook(\"onRequest\", async (req, reply) => {\n if (!hosts.has(req.headers.host ?? \"\")) return reply.code(403).send({ error: \"Unexpected Host header\" });\n // Decide on the route that matched, not the raw URL: the router percent-decodes, so\n // \"/%61pi/reviews\" reaches /api/reviews while the raw string doesn't start with \"/api/\".\n const route = req.routeOptions?.url;\n let decoded = req.url;\n try {\n decoded = decodeURIComponent(req.url.split(\"?\")[0]!);\n } catch {\n /* malformed escapes: fall back to the raw path */\n }\n if (!route?.startsWith(\"/api/\") && !decoded.toLowerCase().replace(/\\/+/g, \"/\").startsWith(\"/api/\")) return;\n const got = Buffer.from((req.headers.authorization ?? \"\").replace(/^Bearer\\s+/i, \"\"));\n if (got.length !== want.length || !timingSafeEqual(got, want)) return reply.code(401).send({ error: \"Open the panel with the URL printed in the terminal (it carries the access token).\" });\n });\n\n const currentVote = (findingId: number): Vote =>\n (db.prepare(`SELECT vote FROM finding_votes WHERE finding_id = ?`).get(findingId) as { vote: Vote } | undefined)?.vote ?? null;\n\n /** DB change is already committed; `?sync=1` mirrors it to the finding's GitLab thread. */\n async function maybeSync(findingId: number, prevVote: Vote, sync: string | undefined) {\n if (sync !== \"1\") return { ok: true, synced: false };\n if (!opts.forgeFor) return { ok: true, synced: false, error: \"No git host configured\" };\n const result = await syncFindingDecision(db, opts.forgeFor, findingId, prevVote);\n if (result.error) console.error(`[dashboard] forge sync failed for finding ${findingId}: ${result.error}`);\n return { ok: true, ...result };\n }\n\n /**\n * The panel's memory repo filter: `?source=<team data repo>` or `_local` (not shared),\n * by the same project ownership rule reviews use for memory. Unset = everything, merged.\n */\n type Filter = { projectIds: number[]; has: (projectId: number | null) => boolean; owner: (key: string) => string | null; name: string };\n function sourceFilter(source: string | undefined, reply: FastifyReply): Filter | undefined | null {\n if (!source) return undefined;\n const name = source === \"_local\" ? null : source;\n if (name !== null && !(loadConfig().sources ?? []).some((s) => s.name === name)) {\n void reply.code(400).send({ error: `No team data repo named '${source}'` });\n return null;\n }\n const owner = projectOwners();\n const rows = db.prepare(`SELECT id FROM projects`).all() as { id: number }[];\n const projectIds = rows.map((r) => r.id).filter((id) => ownerOfProject(db, id, owner) === name);\n const set = new Set(projectIds);\n return { projectIds, has: (id) => id != null && set.has(id), owner, name: source };\n }\n\n // ---- memory repo sync: a button, plus once on start ----\n const lastRun = new Map<string, { at: string; summary: string; error: boolean }>();\n async function runTeamSync(sources: SourceConfig[]): Promise<SourceRun[]> {\n const runs = await syncAll(db, \"sync\", sources);\n for (const r of runs) {\n lastRun.set(r.name, { at: new Date().toISOString(), summary: describeRun(r), error: !!r.error });\n console[r.error ? \"error\" : \"log\"](`[panel] team data ${describeRun(r)}`);\n }\n return runs;\n }\n if (opts.syncOnStart) runTeamSync((loadConfig().sources ?? []).filter((s) => s.autoSync)).catch((err) => console.error(`[panel] team data sync failed: ${(err as Error).message}`));\n\n app.get(\"/api/sync\", async () =>\n Promise.all(\n (loadConfig().sources ?? []).map(async (s) => ({ name: s.name, toSend: await pendingToSend(db, s).catch(() => null), waiting: await waitingForMerge(s).catch(() => 0), last: lastRun.get(s.name) ?? null })),\n ),\n );\n\n app.post<{ Querystring: { source?: string } }>(\"/api/sync\", async (req, reply) => {\n const all = loadConfig().sources ?? [];\n const pick = req.query.source ? all.filter((s) => s.name === req.query.source) : all;\n if (req.query.source && pick.length === 0) return reply.code(400).send({ error: `No team data repo named '${req.query.source}'` });\n return (await runTeamSync(pick)).map((r) => ({ name: r.name, summary: describeRun(r), error: r.error ?? null }));\n });\n\n app.get(\"/api/sources\", async () => (loadConfig().sources ?? []).map((s) => ({ name: s.name, url: displayUrl(s.url) })));\n\n app.get<{ Querystring: { source?: string } }>(\"/api/authors\", async (req, reply) => {\n const f = sourceFilter(req.query.source, reply);\n if (f === null) return reply;\n return listAuthors(db, f?.projectIds).map((author) => ({ ...author, trend: computeAuthorTrend(db, author) }));\n });\n\n // A person is (host, username), so the host is required: the same username on another host\n // is someone else.\n app.get<{ Params: { username: string }; Querystring: { host?: string; project?: string } }>(\n \"/api/authors/:username\",\n async (req, reply) => {\n if (!req.query.host) return reply.code(400).send({ error: \"host is required\" });\n const author = { host: req.query.host, username: req.params.username };\n const projectId = req.query.project ? Number(req.query.project) : undefined;\n const scores = listAuthorScores(db, author).map((s) => ({\n ...s,\n category_scores: JSON.parse(s.category_scores_json),\n findings: JSON.parse(s.findings_json),\n }));\n return {\n ...author,\n scores,\n corrections: listAuthorCorrections(db, author, 100, projectId),\n comments: listAuthorComments(db, author),\n insights: listInsights(db, { ...author, projectId }),\n trend: computeAuthorTrend(db, author),\n };\n },\n );\n\n app.get<{ Querystring: { author?: string; host?: string; project?: string; source?: string } }>(\"/api/insights\", async (req, reply) => {\n const { author, host, project } = req.query;\n const f = sourceFilter(req.query.source, reply);\n if (f === null) return reply;\n const rows = listInsights(db, { username: author, host, projectId: project ? Number(project) : undefined });\n const want = f && (f.name === \"_local\" ? null : f.name);\n return f ? rows.filter((i) => insightSource(db, i, f.owner) === want) : rows;\n });\n\n app.get<{ Querystring: { source?: string } }>(\"/api/projects\", async (req, reply) => {\n const f = sourceFilter(req.query.source, reply);\n if (f === null) return reply;\n const owner = f?.owner ?? projectOwners();\n const rows = db.prepare(\"SELECT id, path_with_namespace, name, forge_host FROM projects ORDER BY path_with_namespace, forge_host\").all() as { id: number }[];\n return rows.filter((p) => !f || f.has(p.id)).map((p) => ({ ...p, source: ownerOfProject(db, p.id, owner) }));\n });\n\n app.get<{ Querystring: { source?: string } }>(\"/api/comment-volume\", async (req, reply) => {\n const f = sourceFilter(req.query.source, reply);\n if (f === null) return reply;\n return commentVolumeByAuthor(db, f?.projectIds);\n });\n\n app.get<{ Querystring: { source?: string } }>(\"/api/reviews\", async (req, reply) => {\n const f = sourceFilter(req.query.source, reply);\n if (f === null) return reply;\n const rows = listReviews(db);\n return f ? rows.filter((r) => f.has(r.project_id)) : rows;\n });\n\n app.get<{ Params: { id: string } }>(\"/api/reviews/:id\", async (req, reply) => {\n const mergeRequestId = Number(req.params.id);\n const mr = getMergeRequestById(db, mergeRequestId);\n if (!mr) return reply.code(404).send({ error: \"not found\" });\n return {\n mr,\n scores: listScoresForMr(db, mergeRequestId).map((s) => ({\n ...s,\n category_scores: JSON.parse(s.category_scores_json),\n findings: JSON.parse(s.findings_json),\n })),\n corrections: listCorrectionsForMr(db, mergeRequestId),\n comments: listCommentsForMr(db, mergeRequestId),\n findings: listFindingsForMr(db, mergeRequestId),\n zoneHits: listZoneHitsForMr(db, mergeRequestId),\n };\n });\n\n /** Gets the authors' new and edited replies on this review's posted finding threads. */\n app.post<{ Params: { id: string } }>(\"/api/reviews/:id/sync-replies\", async (req, reply) => {\n const mr = getMergeRequestById(db, Number(req.params.id));\n if (!mr) return reply.code(404).send({ error: \"not found\" });\n const project = db.prepare(`SELECT forge_host, forge_project_id FROM projects WHERE id = ?`).get(mr.project_id) as\n | { forge_host: string | null; forge_project_id: string | null }\n | undefined;\n if (!project?.forge_host || !project.forge_project_id) return reply.code(400).send({ error: \"This review's git host isn't known, so replies can't be fetched.\" });\n if (!opts.forgeFor) return reply.code(400).send({ error: \"No git host configured\" });\n try {\n const ref = /^\\d+$/.test(project.forge_project_id) ? Number(project.forge_project_id) : project.forge_project_id;\n const result = await syncRepliesForMr(db, opts.forgeFor(project.forge_host), ref, mr.mr_iid, mr.id);\n return { ...result, summary: describeSyncReplies(result) };\n } catch (err) {\n return reply.code(502).send({ error: `Couldn't get replies from ${project.forge_host}: ${(err as Error).message}` });\n }\n });\n\n app.get<{ Querystring: { project?: string } }>(\"/api/zones\", async (req, reply) => {\n const projectId = Number(req.query.project);\n if (!projectId) return reply.code(400).send({ error: \"project is required\" });\n return { hits: listZoneHitsForProject(db, projectId), flagged: listDangerTaggedFindings(db, projectId) };\n });\n\n app.post<{ Params: { id: string }; Body: { vote: \"up\" | \"down\"; note?: string } }>(\"/api/zone-hits/:id/vote\", async (req, reply) => {\n const { vote, note } = req.body;\n if (vote !== \"up\" && vote !== \"down\") return reply.code(400).send({ error: \"vote must be 'up' or 'down'\" });\n setZoneHitVote(db, Number(req.params.id), vote, note?.trim() || null);\n return { ok: true };\n });\n\n app.delete<{ Params: { id: string } }>(\"/api/zone-hits/:id/vote\", async (req) => {\n setZoneHitVote(db, Number(req.params.id), null, null);\n return { ok: true };\n });\n\n app.get<{ Querystring: { project?: string; author?: string; authorHost?: string; tag?: string; source?: string } }>(\"/api/findings\", async (req, reply) => {\n const { project, author, authorHost, tag } = req.query;\n if (author && !authorHost) return reply.code(400).send({ error: \"authorHost is required with author\" });\n const f = sourceFilter(req.query.source, reply);\n if (f === null) return reply;\n const rows = queryFindings(db, { projectId: project ? Number(project) : undefined, author: author && authorHost ? { host: authorHost, username: author } : undefined, tag });\n return f ? rows.filter((r) => f.has(r.project_id)) : rows;\n });\n\n app.post<{\n Params: { id: string };\n Querystring: { sync?: string };\n Body: { vote: \"up\" | \"down\"; note: string; adjustScore: boolean; category?: string | null; correctedScore?: number };\n }>(\"/api/findings/:id/vote\", async (req, reply) => {\n const { vote, note, adjustScore, category, correctedScore } = req.body;\n if (vote !== \"up\" && vote !== \"down\") return reply.code(400).send({ error: \"vote must be 'up' or 'down'\" });\n if (!note || !note.trim()) return reply.code(400).send({ error: \"note is required\" });\n const id = Number(req.params.id);\n const prev = currentVote(id);\n upsertFindingVote(db, id, { vote, note: note.trim(), adjustScore, category, correctedScore });\n return maybeSync(id, prev, req.query.sync);\n });\n\n app.delete<{ Params: { id: string }; Querystring: { sync?: string } }>(\"/api/findings/:id/vote\", async (req) => {\n const id = Number(req.params.id);\n const prev = currentVote(id);\n deleteFindingVote(db, id);\n return maybeSync(id, prev, req.query.sync);\n });\n\n app.post<{ Params: { id: string }; Querystring: { sync?: string }; Body: { tag: string } }>(\"/api/findings/:id/tags\", async (req, reply) => {\n const { tag } = req.body;\n if (!(FINDING_TAGS as readonly string[]).includes(tag)) return reply.code(400).send({ error: \"invalid tag\" });\n const id = Number(req.params.id);\n addFindingTag(db, id, tag);\n return maybeSync(id, currentVote(id), req.query.sync);\n });\n\n app.delete<{ Params: { id: string; tag: string }; Querystring: { sync?: string } }>(\"/api/findings/:id/tags/:tag\", async (req) => {\n const id = Number(req.params.id);\n removeFindingTag(db, id, req.params.tag);\n return maybeSync(id, currentVote(id), req.query.sync);\n });\n\n /** Retry after a failed sync. prevVote = current: re-resolves on \uD83D\uDC4E, never reopens. */\n app.post<{ Params: { id: string } }>(\"/api/findings/:id/sync\", async (req) => {\n const id = Number(req.params.id);\n return maybeSync(id, currentVote(id), \"1\");\n });\n\n app.delete<{ Params: { id: string } }>(\"/api/reviews/:id\", async (req) => {\n deleteMergeRequest(db, Number(req.params.id));\n return { ok: true };\n });\n\n app.delete<{ Params: { id: string } }>(\"/api/scores/:id\", async (req) => {\n deleteScore(db, Number(req.params.id));\n return { ok: true };\n });\n\n app.patch<{ Params: { id: string }; Body: { category: string | null; correctedScore: number; reason: string; correctedNote: string | null } }>(\n \"/api/corrections/:id\",\n async (req) => {\n updateCorrection(db, Number(req.params.id), req.body);\n return { ok: true };\n },\n );\n\n app.delete<{ Params: { id: string } }>(\"/api/corrections/:id\", async (req) => {\n deleteCorrection(db, Number(req.params.id));\n return { ok: true };\n });\n\n app.delete<{ Params: { id: string } }>(\"/api/insights/:id\", async (req) => {\n deleteInsight(db, Number(req.params.id));\n return { ok: true };\n });\n\n registerSettings(app, { db, forgeFor: opts.forgeFor ?? ((host) => { throw new Error(`No git host client for ${host}`); }) });\n\n await app.register(fastifyStatic, { root: WEB_DIST, wildcard: false });\n app.setNotFoundHandler((req, reply) => {\n if (req.raw.url?.startsWith(\"/api/\")) {\n reply.code(404).send({ error: \"not found\" });\n return;\n }\n reply.sendFile(\"index.html\");\n });\n\n return app;\n}\n\nexport async function startDashboard(opts: DashboardOptions = {}): Promise<void> {\n const port = opts.port ?? 4173;\n const token = randomBytes(24).toString(\"base64url\");\n const app = await buildPanel({ ...opts, db: openDb(), token, port, syncOnStart: true });\n await app.listen({ port, host: \"127.0.0.1\" });\n console.log(`[panel] open http://127.0.0.1:${port}/?token=${token}`);\n console.log(\"[panel] the token changes on every start; local access only.\");\n}\n", "import type { DatabaseSync } from \"node:sqlite\";\nimport type { ForgeClient } from \"../../src/forge/types.js\";\n\nexport type Vote = \"up\" | \"down\" | null;\n\n/** Body of our decision reply, or null when there's nothing left to say (no vote, no tags). */\nexport function renderDecision(vote: Vote, note: string | null, tags: string[]): string | null {\n if (!vote && tags.length === 0) return null;\n const lines: string[] = [];\n if (vote === \"up\") lines.push(`\u2705 **Maintainer confirmed this finding.**${note ? ` ${note}` : \"\"}`);\n if (vote === \"down\") lines.push(`\u21A9\uFE0F **Finding withdrawn \u2014 the contributor was right.**${note ? ` ${note}` : \"\"}`);\n if (tags.length > 0) lines.push(`\uD83C\uDFF7\uFE0F ${tags.map((t) => `\\`${t}\\``).join(\" \")}`);\n return lines.join(\"\\n\\n\");\n}\n\n/**\n * Mirrors a finding's current vote + tags into one reply on its forge thread, edited in\n * place (deleted when both are cleared). A \uD83D\uDC4E resolves the thread; moving off a \uD83D\uDC4E\n * (`prevVote`) reopens it. Findings never posted as a thread (e.g. backfill) have nothing\n * to sync \u2014 returns false. DB state is already committed by the caller, so a GitLab failure\n * is recorded in decision_sync_error for retry rather than thrown.\n */\nexport async function syncFindingDecision(\n db: DatabaseSync,\n forgeFor: (host: string) => ForgeClient,\n findingId: number,\n prevVote: Vote,\n): Promise<{ synced: boolean; error?: string }> {\n const row = db\n .prepare(\n `SELECT fd.id AS fd_id, fd.discussion_id, fd.decision_note_id, p.forge_host, p.forge_project_id, mr.mr_iid, fv.vote, fv.note,\n (SELECT GROUP_CONCAT(ft.tag) FROM finding_tags ft WHERE ft.finding_id = f.id) AS tags_concat\n FROM findings f\n JOIN merge_requests mr ON mr.id = f.merge_request_id\n JOIN projects p ON p.id = mr.project_id\n JOIN finding_discussions fd ON fd.merge_request_id = f.merge_request_id AND fd.file IS f.file AND fd.line IS f.line AND fd.issue = f.issue\n LEFT JOIN finding_votes fv ON fv.finding_id = f.id\n WHERE f.id = ?`,\n )\n .get(findingId) as\n | {\n fd_id: number;\n discussion_id: string;\n decision_note_id: number | null;\n forge_host: string;\n forge_project_id: string;\n mr_iid: number;\n vote: Vote;\n note: string | null;\n tags_concat: string | null;\n }\n | undefined;\n if (!row) return { synced: false };\n\n const body = renderDecision(row.vote, row.note, row.tags_concat ? row.tags_concat.split(\",\") : []);\n try {\n // Inside the try: a host with no token is recorded as a sync error, not thrown at the panel.\n const client = forgeFor(row.forge_host);\n let noteId = row.decision_note_id;\n if (body) {\n noteId = await client.upsertDiscussionReply(Number(row.forge_project_id), row.mr_iid, row.discussion_id, body, noteId);\n } else if (noteId != null) {\n await client.deleteDiscussionReply(Number(row.forge_project_id), row.mr_iid, row.discussion_id, noteId);\n noteId = null;\n }\n // Saved before resolving, so a resolve failure + Retry edits this note instead of posting a second one.\n db.prepare(`UPDATE finding_discussions SET decision_note_id = ? WHERE id = ?`).run(noteId, row.fd_id);\n if (row.vote === \"down\") await client.resolveDiscussion(Number(row.forge_project_id), row.mr_iid, row.discussion_id, true);\n else if (prevVote === \"down\") await client.resolveDiscussion(Number(row.forge_project_id), row.mr_iid, row.discussion_id, false);\n\n db.prepare(`UPDATE finding_discussions SET decision_sync_error = NULL WHERE id = ?`).run(row.fd_id);\n return { synced: true };\n } catch (err) {\n const error = (err as Error).message;\n db.prepare(`UPDATE finding_discussions SET decision_sync_error = ? WHERE id = ?`).run(error, row.fd_id);\n return { synced: false, error };\n }\n}\n", "import type { FastifyInstance, FastifyReply } from \"fastify\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport { createForge, parseGitAddress, probeForgeType, type ForgeClient, type ForgeType } from \"../../src/forge/index.js\";\nimport { createLlmProvider, type LlmEnv } from \"../../src/llm/index.js\";\nimport { ZonesError } from \"../../src/zones/zones.js\";\nimport { configFilledKeys, forgeUrl, LLM_ENV_KEYS, loadConfig, type LlmProfile } from \"../config/config.js\";\nimport { getSecret, maskSecret, secretBackend } from \"../config/secrets.js\";\nimport {\n conventionsMaxLines,\n currentConventions,\n denied,\n dirTree,\n generateConventions,\n lookAtProject,\n pickFiles,\n readSections,\n saveConventions,\n scrubPrompt,\n suggestConventions,\n} from \"../conventions/generate.js\";\nimport { replayScores } from \"../db/repo.js\";\nimport { forgeToken } from \"../forge.js\";\nimport { bareHost } from \"../paths.js\";\nimport {\n currentWeights,\n missingSteps,\n PROFILE_NAME,\n PROVIDER_PRESETS,\n readSetupState,\n removeForge,\n removeLlmProfile,\n saveForge,\n saveLlmProfile,\n saveWeights,\n setDefaultLlmProfile,\n testLlmProfile,\n tokenHelpUrl,\n WEIGHT_PRESETS,\n} from \"../setup/state.js\";\nimport { currentZones, draftZones, renderZonesYaml, saveZones, skipZones } from \"../zones/generate.js\";\n\n/**\n * Panel settings (Phase 5): every wizard step over HTTP, on the same core as the TUI.\n * Secrets are write-only: accepted here, never returned \u2014 GETs show masked values only.\n */\nexport interface SettingsDeps {\n db: DatabaseSync;\n forgeFor: (host: string) => ForgeClient;\n}\n\ntype Q = { host?: string; path?: string };\nconst bad = (reply: FastifyReply, error: string, code = 400) => reply.code(code).send({ error });\nconst msg = (err: unknown) => (err as Error).message;\n/** A masked value echoed back by a client is never a secret \u2014 treat it as \"not given\". */\nconst secretIn = (v?: string) => (v?.trim() && !v.includes(\"\u2022\u2022\u2022\u2022\") ? v.trim() : undefined);\n\nconst gitlabBases = () => loadConfig().forges.filter((f) => f.type === \"gitlab\" && f.url).map(forgeUrl);\n\n/** host + path from the query/body; paths contain '/', so never route params. */\nfunction project(q: Q): { host: string; path: string } | null {\n return q.host && q.path ? { host: bareHost(q.host), path: q.path } : null;\n}\n\nexport function registerSettings(app: FastifyInstance, deps: SettingsDeps): void {\n /** A host with no token makes forgeFor throw; that's a 400 with its message, not a 500. */\n const look = async (reply: FastifyReply, p: { host: string; path: string }) => {\n try {\n return await lookAtProject(deps.forgeFor(p.host), p.path);\n } catch (err) {\n bad(reply, msg(err));\n return null;\n }\n };\n\n // ---- global settings ----\n\n app.get(\"/api/settings\", async () => {\n const config = loadConfig();\n const shellKey = LLM_ENV_KEYS.find((k) => process.env[k] && !configFilledKeys().includes(k)) ?? null;\n return {\n secretBackend: secretBackend(),\n shellOverride: shellKey,\n defaultForge: config.defaultForge ?? null,\n forges: config.forges.map((f) => {\n const saved = getSecret(`forge:${f.host}`);\n const any = forgeToken(f.host, f.type);\n return { host: f.host, type: f.type, url: f.url ?? null, token: any ? maskSecret(any) : null, tokenSource: saved ? \"saved\" : any ? \"env\" : null, tokenHelp: tokenHelpUrl(f.type, f.host, f.url) };\n }),\n defaultLlmProfile: config.defaultLlmProfile ?? null,\n llmProfiles: config.llmProfiles.map((p) => {\n const key = getSecret(`llm:${p.name}`);\n return { ...p, key: key ? maskSecret(key) : null };\n }),\n providerPresets: PROVIDER_PRESETS,\n weightPresets: WEIGHT_PRESETS,\n };\n });\n\n /** Address \u2192 host/path, and the forge type (saved, from the URL shape, or probed). */\n app.get<{ Querystring: { address?: string } }>(\"/api/settings/detect\", async (req, reply) => {\n const raw = req.query.address?.trim() ?? \"\";\n const withScheme = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(raw) || raw.includes(\"@\") ? raw : `https://${raw}`;\n const a = parseGitAddress(withScheme, gitlabBases());\n if (!a) return bad(reply, \"Not a git address or MR/PR URL\");\n const saved = loadConfig().forges.find((f) => f.host === a.host);\n const type: ForgeType | null = saved?.type ?? a.ref?.type ?? (await probeForgeType(a.host));\n return { host: a.host, projectPath: a.projectPath, type, known: !!saved, tokenHelp: type ? tokenHelpUrl(type, a.host, saved?.url) : null };\n });\n\n /** Token from the body, else the saved/env one for that host \u2014 never another host's. */\n app.post<{ Body: { host: string; type: ForgeType; token?: string; projectPath?: string } }>(\"/api/settings/forges/test\", async (req, reply) => {\n const { type, token, projectPath } = req.body;\n if (!req.body.host || (type !== \"gitlab\" && type !== \"github\")) return bad(reply, \"host and type are required\");\n const host = bareHost(req.body.host);\n const t = secretIn(token) ?? forgeToken(host, type);\n if (!t) return bad(reply, `No token for ${host}`);\n const saved = loadConfig().forges.find((f) => f.host === host);\n const forge = createForge({ type, host, url: saved ? forgeUrl(saved) : undefined, token: t });\n try {\n const me = await forge.getCurrentUser();\n const p = projectPath ? await forge.getProject(projectPath) : null;\n return { ok: true, username: me.username, project: p?.pathWithNamespace ?? null };\n } catch (err) {\n return { ok: false, error: msg(err) };\n }\n });\n\n app.post<{ Body: { host: string; type: ForgeType; token?: string } }>(\"/api/settings/forges\", async (req, reply) => {\n const { type, token } = req.body;\n if (!req.body.host || (type !== \"gitlab\" && type !== \"github\")) return bad(reply, \"host and type are required\");\n saveForge(bareHost(req.body.host), type, secretIn(token));\n return { ok: true };\n });\n\n app.delete<{ Querystring: { host?: string } }>(\"/api/settings/forges\", async (req, reply) => {\n if (!req.query.host) return bad(reply, \"host is required\");\n removeForge(bareHost(req.query.host));\n return { ok: true };\n });\n\n type ProfileBody = { name?: string; provider: LlmProfile[\"provider\"]; model: string; baseUrl?: string; key?: string; makeDefault?: boolean };\n const profileOf = (b: ProfileBody) => ({ provider: b.provider, model: b.model?.trim(), ...(b.baseUrl?.trim() && { baseUrl: b.baseUrl.trim() }) });\n\n /** Test with the key in the body, or the saved key of `name`. */\n app.post<{ Body: ProfileBody }>(\"/api/settings/llm/test\", async (req, reply) => {\n const b = req.body;\n if (!b.provider || !b.model) return bad(reply, \"provider and model are required\");\n // A saved key only ever goes to its own profile's endpoint, never one the request names.\n const typed = secretIn(b.key);\n const saved = !typed && b.name ? loadConfig().llmProfiles.find((p) => p.name === b.name) : undefined;\n const key = typed ?? (saved ? getSecret(`llm:${saved.name}`) : undefined);\n const target = saved ? { provider: saved.provider, model: b.model?.trim() || saved.model, ...(saved.baseUrl && { baseUrl: saved.baseUrl }) } : profileOf(b);\n const started = Date.now();\n try {\n await testLlmProfile(target, key);\n return { ok: true, ms: Date.now() - started };\n } catch (err) {\n return { ok: false, ms: Date.now() - started, error: msg(err) };\n }\n });\n\n app.post<{ Body: ProfileBody }>(\"/api/settings/llm\", async (req, reply) => {\n const b = req.body;\n if (!b.name || !PROFILE_NAME.test(b.name)) return bad(reply, \"Profile name: letters, digits, . _ -\");\n if (![\"anthropic\", \"openai-compatible\", \"ollama\"].includes(b.provider) || !b.model?.trim()) return bad(reply, \"provider and model are required\");\n if (b.provider === \"openai-compatible\" && !b.baseUrl?.trim()) return bad(reply, \"An openai-compatible profile needs a base URL\");\n const existing = loadConfig().llmProfiles.find((p) => p.name === b.name);\n const next = profileOf(b);\n if (existing && !secretIn(b.key) && existing.provider !== \"ollama\" && (existing.provider !== next.provider || (existing.baseUrl ?? \"\") !== (next.baseUrl ?? \"\"))) {\n return bad(reply, \"The endpoint changed \u2014 enter the API key again (a saved key never moves to a new endpoint).\");\n }\n try {\n saveLlmProfile({ name: b.name, ...next } as LlmProfile, secretIn(b.key), b.makeDefault ?? true);\n } catch (err) {\n return bad(reply, msg(err));\n }\n return { ok: true };\n });\n\n app.post<{ Body: { name: string } }>(\"/api/settings/llm/default\", async (req, reply) => {\n try {\n setDefaultLlmProfile(req.body.name);\n } catch (err) {\n return bad(reply, msg(err));\n }\n return { ok: true };\n });\n\n app.delete<{ Querystring: { name?: string } }>(\"/api/settings/llm\", async (req, reply) => {\n if (!req.query.name) return bad(reply, \"name is required\");\n removeLlmProfile(req.query.name);\n return { ok: true };\n });\n\n // ---- per project ----\n\n app.get(\"/api/setup/projects\", async () => deps.db.prepare(\"SELECT id, forge_host AS host, path_with_namespace AS path FROM projects WHERE forge_host IS NOT NULL ORDER BY path_with_namespace\").all());\n\n app.get<{ Querystring: Q }>(\"/api/setup/project\", async (req, reply) => {\n const p = project(req.query);\n if (!p) return bad(reply, \"host and path are required\");\n const conv = currentConventions(p.host, p.path);\n const zones = currentZones(p.host, p.path);\n const read = (f: string | null) => (f && existsSync(f) ? readFileSync(f, \"utf8\") : null);\n const row = deps.db.prepare(\"SELECT id FROM projects WHERE forge_host = ? AND lower(path_with_namespace) = lower(?)\").get(p.host, p.path) as { id: number } | undefined;\n return {\n ...p,\n projectId: row?.id ?? null,\n missing: missingSteps({ host: p.host, projectPath: p.path }),\n conventions: { ...conv, text: read(conv.path), maxLines: conventionsMaxLines() },\n zones: { path: zones.path, fromRepo: zones.fromRepo, graph: zones.graph, text: read(zones.path), skipped: readSetupState(p.host, p.path).zones === \"skip\" },\n weights: currentWeights(p.host, p.path),\n llmReady: !!llmOrNull(),\n };\n });\n\n app.put<{ Body: Q & { text: string } }>(\"/api/setup/conventions\", async (req, reply) => {\n const p = project(req.body);\n if (!p || typeof req.body.text !== \"string\") return bad(reply, \"host, path and text are required\");\n if (currentConventions(p.host, p.path).fromRepo) return bad(reply, \"This project's conventions come from the repo's .yolont/ \u2014 edit them there.\");\n try {\n return { ok: true, path: saveConventions(p.host, p.path, req.body.text) };\n } catch (err) {\n return bad(reply, msg(err));\n }\n });\n\n app.post<{ Body: Q }>(\"/api/setup/conventions/suggest\", async (req, reply) => {\n const p = project(req.body);\n if (!p) return bad(reply, \"host and path are required\");\n const found = await look(reply, p);\n if (!found) return reply;\n const file = suggestConventions(found.stack, currentConventions(p.host, p.path).path ?? undefined);\n return { stack: found.stack, file, text: readFileSync(file, \"utf8\") };\n });\n\n /** Step 1 of generation: what would be sent. Nothing leaves the machine here. */\n app.post<{ Body: Q }>(\"/api/setup/conventions/plan\", async (req, reply) => {\n const p = project(req.body);\n if (!p) return bad(reply, \"host and path are required\");\n const found = await look(reply, p);\n if (!found) return reply;\n if (!found.source) return bad(reply, `Couldn't list the project's files: ${found.error}`);\n return { source: found.source.label, local: !!found.local, stack: found.stack, files: pickFiles(found.files) };\n });\n\n /**\n * Step 2: send the approved files. Trust boundary: the list is re-derived server-side \u2014 only\n * paths the fresh crawl would pick (so never `.env`, keys, or anything unlisted) survive, and\n * the exact prompt is gitleaks-scanned. A scanner failure needs an explicit allowUnscanned.\n */\n app.post<{ Body: Q & { files?: string[]; allowUnscanned?: boolean } }>(\"/api/setup/conventions/generate\", async (req, reply) => {\n const p = project(req.body);\n if (!p) return bad(reply, \"host and path are required\");\n const llm = llmOrNull();\n if (!llm) return bad(reply, \"No LLM configured \u2014 add a profile in Settings first.\");\n const found = await look(reply, p);\n if (!found) return reply;\n if (!found.source) return bad(reply, `Couldn't list the project's files: ${found.error}`);\n const { files: all, source, stack } = found;\n if (req.body.files !== undefined && (!Array.isArray(req.body.files) || !req.body.files.every((f) => typeof f === \"string\"))) return bad(reply, \"files must be a list of paths\");\n const allowed = new Set(pickFiles(all));\n const asked = req.body.files ?? [...allowed];\n const rejected = asked.filter((f) => !allowed.has(f) || denied(f));\n if (rejected.length) return bad(reply, `Not allowed to send: ${rejected.join(\", \")}`);\n\n let scrub;\n try {\n scrub = await scrubPrompt(`${p.host}/${p.path}`, stack, dirTree(all), await readSections(source!, asked));\n } catch (err) {\n return bad(reply, `Nothing sent: ${msg(err)}`);\n }\n if (scrub.scannerFailed && !req.body.allowUnscanned) return reply.code(409).send({ scannerFailed: true, error: `gitleaks couldn't run (${scrub.scannerError}). Nothing sent.` });\n try {\n const out = await generateConventions(llm, scrub.prompt);\n return { ...out, dropped: scrub.dropped, sent: scrub.sent.map((s) => s.path), scannerFailed: scrub.scannerFailed };\n } catch (err) {\n return bad(reply, `Generation failed: ${msg(err)}`, 502);\n }\n });\n\n app.put<{ Body: Q & { text: string } }>(\"/api/setup/zones\", async (req, reply) => {\n const p = project(req.body);\n if (!p || typeof req.body.text !== \"string\") return bad(reply, \"host, path and text are required\");\n if (currentZones(p.host, p.path).fromRepo) return bad(reply, \"This project's zones come from the repo's .yolont/ \u2014 edit them there.\");\n try {\n const out = saveZones(p.host, p.path, req.body.text);\n return { ok: true, path: out, skipped: out === null };\n } catch (err) {\n if (err instanceof ZonesError) return bad(reply, err.message);\n throw err;\n }\n });\n\n app.post<{ Body: Q }>(\"/api/setup/zones/draft\", async (req, reply) => {\n const p = project(req.body);\n if (!p) return bad(reply, \"host and path are required\");\n const found = await look(reply, p);\n if (!found) return reply;\n if (!found.source) return bad(reply, `Couldn't list the project's files: ${found.error}`);\n const d = draftZones(found.files, found.stack);\n return { yaml: renderZonesYaml(d.zones, d.templates), matched: d.matched, templates: d.templates, stack: found.stack };\n });\n\n app.post<{ Body: Q }>(\"/api/setup/zones/skip\", async (req, reply) => {\n const p = project(req.body);\n if (!p) return bad(reply, \"host and path are required\");\n skipZones(p.host, p.path);\n return { ok: true };\n });\n\n /** weights null = keep the built-in rubric (remembered). */\n app.put<{ Body: Q & { weights: Record<string, number> | null; threshold?: number } }>(\"/api/setup/weights\", async (req, reply) => {\n const p = project(req.body);\n if (!p) return bad(reply, \"host and path are required\");\n if (currentWeights(p.host, p.path).fromRepo) return bad(reply, \"This project's weights come from the repo's .yolont/rubric.yml \u2014 change them there.\");\n try {\n return { ok: true, path: saveWeights(p.host, p.path, req.body.weights, req.body.threshold) };\n } catch (err) {\n return bad(reply, msg(err));\n }\n });\n\n app.post<{ Body: Q & { weights: Record<string, number>; threshold?: number } }>(\"/api/setup/weights/replay\", async (req, reply) => {\n const p = project(req.body);\n if (!p || !req.body.weights) return bad(reply, \"host, path and weights are required\");\n const row = deps.db.prepare(\"SELECT id FROM projects WHERE forge_host = ? AND lower(path_with_namespace) = lower(?)\").get(p.host, p.path) as { id: number } | undefined;\n if (!row) return { rows: [], skipped: 0 };\n const saved = currentWeights(p.host, p.path).threshold;\n return replayScores(deps.db, row.id, req.body.weights, req.body.threshold ?? saved, 20, saved);\n });\n}\n\nfunction llmOrNull() {\n try {\n return createLlmProvider(process.env as LlmEnv);\n } catch {\n return null;\n }\n}\n", "import { execFileSync } from \"node:child_process\";\nimport { loadConfig } from \"../config/config.js\";\nimport { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ForgeClient, ProjectRef } from \"../../src/forge/types.js\";\nimport type { LLMProvider } from \"../../src/llm/provider.js\";\nimport { scanDiffForSecrets, type SecretsScanResult } from \"../../src/checks/secrets.js\";\nimport { CONFIG_DIR, DEFAULT_CONVENTIONS_PATH } from \"../paths.js\";\nimport { listConventionFiles, remoteProjectPath, resolveProjectFiles } from \"./resolve.js\";\nimport { projectSettingsDir } from \"../sync/source.js\";\n\n/**\n * Phase 3: a project's conventions.md \u2014 suggested from existing files, or generated by the LLM\n * from a crawl of a local checkout or the forge API. Nothing leaves the machine before the exact\n * prompt passes a gitleaks scan.\n */\n/**\n * Save limit for a conventions file (they go into every review prompt: ~300 lines \u2248 3\u20134k\n * tokens). `conventionsMaxLines` in config.yaml changes it. CI reads a repo's file at any length.\n */\nexport const DEFAULT_CONVENTIONS_MAX_LINES = 300;\nexport const conventionsMaxLines = () => loadConfig().conventionsMaxLines ?? DEFAULT_CONVENTIONS_MAX_LINES;\n/** Asked of the model, leaving room for edits under the cap. */\nconst targetLines = () => Math.floor(conventionsMaxLines() * 0.8);\nconst MAX_FILE_CHARS = 6000;\nconst MAX_TOTAL_CHARS = 60000;\n\nexport interface CrawlSource {\n label: string;\n files: () => Promise<string[]>;\n read: (path: string) => Promise<string | null>;\n}\n\n// ---- sources ----\n\n/** `git ls-files` (respects .gitignore). Symlinks are skipped: one could point at ~/.ssh outside the repo. */\nexport function localSource(repoDir: string): CrawlSource {\n return {\n label: repoDir,\n files: async () =>\n execFileSync(\"git\", [\"-C\", repoDir, \"ls-files\", \"-z\"], { encoding: \"utf8\", maxBuffer: 64 * 1024 * 1024 })\n .split(\"\\0\")\n .filter(Boolean),\n read: async (p) => {\n const full = join(repoDir, p);\n try {\n return lstatSync(full).isFile() ? readFileSync(full, \"utf8\") : null;\n } catch {\n return null;\n }\n },\n };\n}\n\nexport function forgeSource(forge: ForgeClient, project: ProjectRef, ref: string): CrawlSource {\n return { label: `${forge.host} @ ${ref}`, files: () => forge.listFiles(project, ref), read: (p) => forge.readFile(project, p, ref) };\n}\n\nexport interface ProjectLook {\n source: CrawlSource | null;\n files: string[];\n /** Local checkout dir, when the crawl is from one. */\n local: string | null;\n stack: string[];\n /** --repo given but its origin isn't this project. */\n mismatch?: string;\n error?: string;\n}\n\nconst git = (args: string[]) => {\n try {\n return execFileSync(\"git\", args, { encoding: \"utf8\", stdio: [\"ignore\", \"pipe\", \"ignore\"] }).trim();\n } catch {\n return null;\n }\n};\n\n/** File list + stack: `repo`, else `cwd` when its origin is this project, else the forge's default branch. */\nexport async function lookAtProject(forge: ForgeClient, projectPath: string, repo?: string, cwd = process.cwd()): Promise<ProjectLook> {\n const top = repo ?? git([\"-C\", cwd, \"rev-parse\", \"--show-toplevel\"]);\n const origin = top ? git([\"-C\", top, \"remote\", \"get-url\", \"origin\"]) : null;\n const matches = !!origin && remoteProjectPath(origin) === projectPath.toLowerCase();\n const local = top && (repo || matches) ? top : null;\n const mismatch = repo && !matches ? `${repo} doesn't look like a checkout of ${projectPath} (origin: ${origin ?? \"none\"}).` : undefined;\n let source: CrawlSource | null = local ? localSource(local) : null;\n try {\n if (!source) {\n const p = await forge.getProject(projectPath);\n source = forgeSource(forge, p.id, p.defaultBranch);\n }\n const files = await source.files();\n const stack = await detectStack(files, source.read).catch(() => []);\n return { source, files, local, stack, mismatch };\n } catch (err) {\n return { source: null, files: [], local, stack: [], mismatch, error: (err as Error).message };\n }\n}\n\n// ---- stack ----\n\n/** Stack tags from root manifests \u2014 used to suggest conventions (and Phase 4 zone templates). */\nexport async function detectStack(files: string[], read: CrawlSource[\"read\"]): Promise<string[]> {\n // ponytail: root manifests only; monorepo packages/*/package.json aren't inspected.\n const has = (f: string) => files.includes(f);\n const tags = new Set<string>();\n if (has(\"package.json\")) {\n tags.add(\"node\");\n try {\n const pkg = JSON.parse((await read(\"package.json\")) ?? \"{}\") as { dependencies?: object; devDependencies?: object };\n const deps = Object.keys({ ...pkg.dependencies, ...pkg.devDependencies });\n const map: Record<string, string> = { react: \"react\", next: \"nextjs\", vue: \"vue\", svelte: \"svelte\", \"@angular/core\": \"angular\", express: \"express\", fastify: \"fastify\", koa: \"koa\", \"@nestjs/core\": \"nestjs\", typescript: \"typescript\" };\n for (const d of deps) if (map[d]) tags.add(map[d]);\n if ([\"express\", \"fastify\", \"koa\", \"nestjs\"].some((t) => tags.has(t))) tags.add(\"node-api\");\n } catch {\n /* unparseable package.json: \"node\" is enough */\n }\n }\n if (has(\"tsconfig.json\")) tags.add(\"typescript\");\n if (has(\"go.mod\")) tags.add(\"go\");\n if (has(\"Cargo.toml\")) tags.add(\"rust\");\n if (has(\"Gemfile\")) tags.add(\"ruby\");\n if (has(\"composer.json\")) tags.add(\"php\");\n if (has(\"pom.xml\") || has(\"build.gradle\") || has(\"build.gradle.kts\")) tags.add(\"java\");\n if (has(\"pyproject.toml\") || has(\"requirements.txt\") || has(\"setup.py\")) {\n tags.add(\"python\");\n const text = ((await read(\"pyproject.toml\")) ?? \"\") + ((await read(\"requirements.txt\")) ?? \"\");\n for (const fw of [\"django\", \"flask\", \"fastapi\"]) if (new RegExp(`\\\\b${fw}\\\\b`, \"i\").test(text)) tags.add(fw);\n }\n return [...tags];\n}\n\n/** Tags that are ordinary English words need a stricter match (\"unrelated refactors go in a separate PR\"). */\nconst STACK_WORDS: Record<string, RegExp> = { go: /\\b(golang|go\\.mod|gofmt|go modules?|go vet)\\b/, node: /\\bnode(\\.js|js)?\\b/ };\n\n/** Built-ins + other projects' conventions, best stack-word overlap; default.md when nothing matches. */\nexport function suggestConventions(stack: string[], exclude?: string): string {\n // ponytail: keyword overlap on file text \u2014 good enough with a handful of files; embeddings if it ever isn't.\n const projectsDir = join(CONFIG_DIR, \"projects\");\n const own: string[] = [];\n const walk = (d: string, depth: number) => {\n if (depth > 6 || !existsSync(d)) return;\n for (const e of readdirSync(d, { withFileTypes: true })) {\n if (e.isDirectory()) walk(join(d, e.name), depth + 1);\n else if (e.name === \"conventions.md\") own.push(join(d, e.name));\n }\n };\n walk(projectsDir, 0);\n let best = DEFAULT_CONVENTIONS_PATH;\n let bestScore = 0;\n for (const f of [...listConventionFiles(), ...own]) {\n if (f === exclude) continue;\n const text = readFileSync(f, \"utf8\").toLowerCase();\n const score = stack.filter((t) => (STACK_WORDS[t] ?? new RegExp(`\\\\b${t.replace(\"-\", \"[- ]\")}\\\\b`)).test(text)).length;\n if (score > bestScore) [best, bestScore] = [f, score];\n }\n return best;\n}\n\n// ---- file picking ----\n\nconst DENY = [\n /(^|\\/)\\.env($|\\.)/i,\n /\\.(pem|key|p12|pfx|jks|keystore|crt|der|asc|gpg)$/i,\n /(^|\\/)id_(rsa|dsa|ecdsa|ed25519)/i,\n /(^|\\/)(credentials|secrets?)([._-]|$)/i,\n /(^|\\/)(package-lock\\.json|npm-shrinkwrap\\.json|pnpm-lock\\.yaml|yarn\\.lock|go\\.sum|[^/]+\\.lock)$/i,\n /(^|\\/)(node_modules|vendor|dist|build|out|coverage|\\.next)\\//,\n /\\.(min\\.js|map|d\\.ts|snap)$/i,\n /\\.(png|jpe?g|gif|webp|ico|svg|bmp|tiff?|woff2?|ttf|otf|eot|pdf|zip|gz|tgz|bz2|7z|rar|jar|war|class|exe|dll|so|dylib|o|a|wasm|mp[34]|mov|avi|webm|wav|ogg|sqlite|db|bin|parquet)$/i,\n];\n\nconst INSTRUCTIONS = /^(\\.yolont\\/conventions\\.md|AGENTS\\.md|CLAUDE\\.md|\\.cursorrules|\\.cursor\\/rules\\/.+|\\.github\\/copilot-instructions\\.md|CONVENTIONS\\.md|(docs\\/)?(CONTRIBUTING|STYLEGUIDE|STYLE_GUIDE)[^/]*)$/i;\nconst README = /^README[^/]*$/i;\nconst CONFIGS = /^(\\.editorconfig|\\.eslintrc[^/]*|eslint\\.config\\.[^/]+|\\.prettierrc[^/]*|prettier\\.config\\.[^/]+|biome\\.jsonc?|tsconfig\\.json|\\.golangci\\.ya?ml|ruff\\.toml|pyproject\\.toml|setup\\.cfg|\\.rubocop\\.yml|rustfmt\\.toml|\\.stylelintrc[^/]*|package\\.json|go\\.mod|Cargo\\.toml|\\.github\\/pull_request_template\\.md)$/i;\nconst SOURCE = /\\.(ts|tsx|js|jsx|mjs|vue|svelte|go|py|rs|rb|php|java|kt|cs|swift|scala)$/i;\nconst TEST = /(\\.|_)(test|spec)\\.|(^|\\/)(tests?|__tests__|spec)\\//i;\n\nexport const denied = (p: string) => DENY.some((r) => r.test(p));\n\n/**\n * Folders worth sampling from: every directory (depth \u2264 3) that holds source files, with how\n * many, busiest first. The user picks the ones that show the project's conventions best.\n */\nexport function sourceDirs(files: string[], max = 80): { dir: string; count: number }[] {\n const counts = new Map<string, number>();\n for (const f of files) {\n if (denied(f) || !SOURCE.test(f)) continue;\n const parts = f.split(\"/\").slice(0, -1);\n for (let i = 1; i <= Math.min(parts.length, 3); i++) {\n const d = parts.slice(0, i).join(\"/\");\n counts.set(d, (counts.get(d) ?? 0) + 1);\n }\n }\n return [...counts].map(([dir, count]) => ({ dir, count })).sort((a, b) => b.count - a.count || a.dir.localeCompare(b.dir)).slice(0, max);\n}\n\n/**\n * What gets read: instruction files, README, lint/format/build configs, then a spread of source\n * + test samples. With `dirs`, samples come only from those folders (more of them: 2 per folder).\n */\nexport function pickFiles(files: string[], samples = 6, tests = 2, dirs: string[] = []): string[] {\n const inDirs = (f: string) => !dirs.length || dirs.some((d) => f.startsWith(`${d}/`));\n if (dirs.length) {\n samples = Math.min(16, Math.max(samples, dirs.length * 2));\n tests = Math.min(6, Math.max(tests, dirs.length));\n }\n const ok = files.filter((f) => !denied(f));\n const picked = [...ok.filter((f) => INSTRUCTIONS.test(f)), ...ok.filter((f) => README.test(f)), ...ok.filter((f) => CONFIGS.test(f))];\n // One file per directory, round-robin, so samples cover the codebase instead of one folder.\n const spread = (list: string[], n: number) => {\n const byDir = new Map<string, string[]>();\n for (const f of list) {\n // Chosen folders each get their share; otherwise spread over the top two levels.\n const dir = dirs.length ? dirs.filter((d) => f.startsWith(`${d}/`)).sort((a, b) => b.length - a.length)[0]! : f.split(\"/\").slice(0, -1).slice(0, 2).join(\"/\");\n byDir.set(dir, [...(byDir.get(dir) ?? []), f]);\n }\n const out: string[] = [];\n for (let i = 0; out.length < n && [...byDir.values()].some((l) => l.length > i); i++) for (const l of byDir.values()) if (l[i] && out.length < n) out.push(l[i]!);\n return out;\n };\n const src = ok.filter((f) => SOURCE.test(f) && inDirs(f));\n picked.push(...spread(src.filter((f) => !TEST.test(f)), samples), ...spread(src.filter((f) => TEST.test(f)), tests));\n return [...new Set(picked)];\n}\n\n/** Directories only, depth \u2264 3, capped \u2014 the shape of the repo without listing every file. */\nexport function dirTree(files: string[], maxLines = 150): string {\n const dirs = new Set<string>();\n for (const f of files) {\n const parts = f.split(\"/\").slice(0, -1);\n for (let i = 1; i <= Math.min(parts.length, 3); i++) dirs.add(parts.slice(0, i).join(\"/\") + \"/\");\n }\n const list = [...dirs].filter((d) => !denied(d)).sort();\n return list.slice(0, maxLines).join(\"\\n\") + (list.length > maxLines ? `\\n\u2026 ${list.length - maxLines} more` : \"\");\n}\n\nexport interface Section {\n path: string;\n text: string;\n}\n\n/** Reads picked files with per-file and total caps; binary-looking content is dropped. */\nexport async function readSections(source: CrawlSource, picked: string[]): Promise<Section[]> {\n const out: Section[] = [];\n let total = 0;\n for (const path of picked) {\n if (total >= MAX_TOTAL_CHARS) break;\n const raw = await source.read(path);\n if (raw == null || raw.includes(\"\\0\")) continue;\n const room = Math.min(MAX_FILE_CHARS, MAX_TOTAL_CHARS - total);\n const text = raw.length > room ? `${raw.slice(0, room)}\\n\u2026 (truncated)` : raw;\n total += text.length;\n out.push({ path, text });\n }\n return out;\n}\n\n// ---- prompt + scan ----\n\n/** The exact prompt sent, plus each file's 1-based line range in it (to map gitleaks hits back). */\nexport function renderPrompt(project: string, stack: string[], tree: string, sections: Section[]): { prompt: string; ranges: { path: string; start: number; end: number }[] } {\n const example = readFileSync(DEFAULT_CONVENTIONS_PATH, \"utf8\");\n const head = `You write the team conventions file for the code-review bot Yolont. The file is fed to an LLM reviewer that grades pull requests on \"conventions\" and \"maintainability\", so every rule must be checkable against a diff.\n\nProject: ${project}\nDetected stack: ${stack.join(\", \") || \"unknown\"}\n\nRules for the file:\n- At most ${targetLines()} lines of Markdown (hard limit). Shorter is better: only rules a reviewer can check in a diff.\n- Only rules the evidence below supports: instruction files (AGENTS.md, CONTRIBUTING, \u2026), lint/format configs, and patterns visible in the sampled code. Don't invent rules or restate generic advice (\"write clean code\").\n- Specific and example-driven: name real directories, helpers, naming patterns and test layout from this repo.\n- Where a tool enforces something (formatter, linter), say so in one line instead of listing its rules.\n- Use headings like the example's (Naming, Structure, Tests, Error handling, PR hygiene, Security); drop ones with no evidence.\n- Never include secrets, hostnames, internal URLs or people's names.\n\nFormat example (generic content \u2014 replace it with this project's rules):\n<example>\n${example.trim()}\n</example>\n\nAnswer with exactly two blocks and nothing else:\n<summary>3\u20136 bullet points: what you understood about the project (purpose, stack, layout, notable conventions).</summary>\n<conventions>\n\u2026the file\u2026\n</conventions>\n\nRepository directory tree:\n${tree}\n\nFiles:\n`;\n let line = head.split(\"\\n\").length;\n const ranges: { path: string; start: number; end: number }[] = [];\n const parts = sections.map((s) => {\n const block = `=== ${s.path} ===\\n${s.text}\\n`;\n const n = block.split(\"\\n\").length - 1;\n ranges.push({ path: s.path, start: line, end: line + n - 1 });\n line += n;\n return block;\n });\n return { prompt: head + parts.join(\"\"), ranges };\n}\n\nexport interface ScrubResult {\n prompt: string;\n sent: Section[];\n /** Files left out because gitleaks flagged them. */\n dropped: string[];\n scannerFailed: boolean;\n scannerError?: string;\n}\n\n/** Scans the exact prompt; drops flagged files and rescans until clean. A hit outside any file section throws. */\nexport async function scrubPrompt(\n project: string,\n stack: string[],\n tree: string,\n sections: Section[],\n scan: (text: string) => Promise<SecretsScanResult> = scanDiffForSecrets,\n): Promise<ScrubResult> {\n let sent = sections;\n const dropped: string[] = [];\n for (;;) {\n const { prompt, ranges } = renderPrompt(project, stack, tree, sent);\n const res = await scan(prompt);\n if (res.scannerFailed) return { prompt, sent, dropped, scannerFailed: true, scannerError: res.scannerError };\n if (!res.findings.length) return { prompt, sent, dropped, scannerFailed: false };\n const bad = new Set<string>();\n for (const f of res.findings) {\n const r = ranges.find((x) => f.line >= x.start && f.line <= x.end);\n if (!r) throw new Error(`gitleaks flagged line ${f.line} of the prompt outside any file (${f.ruleId}) \u2014 not sending.`);\n bad.add(r.path);\n }\n dropped.push(...bad);\n sent = sent.filter((s) => !bad.has(s.path));\n }\n}\n\n// ---- generate + save ----\n\nexport function parseGenerated(text: string): { summary: string; conventions: string } {\n const tag = (name: string) => text.match(new RegExp(`<${name}>([\\\\s\\\\S]*?)(?:</${name}>|$)`))?.[1]?.trim();\n const strip = (s: string) => s.replace(/^```(?:markdown|md)?\\n/, \"\").replace(/\\n```$/, \"\").trim();\n return { summary: tag(\"summary\") ?? \"\", conventions: strip(tag(\"conventions\") ?? text.trim()) + \"\\n\" };\n}\n\nexport async function generateConventions(provider: LLMProvider, prompt: string): Promise<{ summary: string; conventions: string }> {\n return parseGenerated(await provider.complete(prompt));\n}\n\n/**\n * A pasted path as terminals and file managers actually deliver it: file:// URLs (percent-encoded),\n * 'quoted' or \"quoted\", shell-escaped spaces (`my\\ dir`), stray bracketed-paste markers, ~.\n */\nexport function normalizePastedPath(raw: string, home: string): string {\n let p = raw.replace(/\\x1b\\[20[01]~/g, \"\").trim();\n if (/^(['\"]).*\\1$/.test(p)) p = p.slice(1, -1);\n if (/^file:\\/\\//i.test(p)) {\n try {\n p = decodeURIComponent(new URL(p).pathname);\n } catch {\n p = p.replace(/^file:\\/\\//i, \"\");\n }\n } else {\n p = p.replace(/\\\\(.)/g, \"$1\"); // shell escapes: \"my\\ dir\" -> \"my dir\"\n }\n return p.replace(/^~(?=$|\\/)/, home);\n}\n\nexport const lineCount = (text: string) => (text.trimEnd() ? text.trimEnd().split(\"\\n\").length : 0);\n\n/** Writes the project's conventions.md (user dir, or its team data repo when shared). Over the cap is refused, never truncated. */\nexport function saveConventions(host: string, path: string, text: string): string {\n const n = lineCount(text);\n const max = conventionsMaxLines();\n if (n > max) throw new Error(`Conventions are ${n} lines; the limit is ${max} (conventionsMaxLines in config.yaml).`);\n const dir = projectSettingsDir(host, path);\n mkdirSync(dir, { recursive: true });\n const out = join(dir, \"conventions.md\");\n writeFileSync(out, text.trimEnd() + \"\\n\");\n return out;\n}\n\n/** Where this project's conventions come from now. `fromRepo`: the committed .yolont/ file, which shadows ours. */\nexport function currentConventions(host: string, path: string): { path: string | null; fromRepo: boolean } {\n const p = resolveProjectFiles(host, path).conventions;\n return { path: p, fromRepo: !!p && !p.startsWith(projectSettingsDir(host, path)) };\n}\n", "import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport yaml from \"js-yaml\";\nimport type { ForgeClient, ProjectRef } from \"../../src/forge/types.js\";\nimport { createProviderFromProfile } from \"../../src/llm/index.js\";\nimport { loadRubric } from \"../../src/rubric/loader.js\";\nimport { RubricSchema } from \"../../src/rubric/schema.js\";\nimport { LLM_ENV_KEYS, loadConfig, reapplyConfigToEnv, saveConfig, type LlmProfile } from \"../config/config.js\";\nimport { deleteSecret, getSecret, setSecret } from \"../config/secrets.js\";\nimport { resolveProjectFiles } from \"../conventions/resolve.js\";\nimport { forgeToken } from \"../forge.js\";\nimport { DEFAULT_RUBRIC_PATH, userProjectDir } from \"../paths.js\";\nimport { projectSettingsDir } from \"../sync/source.js\";\n\n/**\n * Setup core shared by the TUI wizard and (Phase 5) the panel checklist: what's missing,\n * and the save/test operations behind each step. No prompts here.\n */\nexport type Step = \"forge\" | \"llm\" | \"conventions\" | \"zones\" | \"weights\";\n\nexport interface ProjectCtx {\n host?: string;\n projectPath?: string;\n}\n\n/** Per-project answers that aren't files themselves \u2014 so a \"keep defaults\" isn't re-asked every run. */\nexport interface SetupState {\n weights?: \"default\" | \"custom\";\n /** Zones are optional: \"skip\" means don't ask again. */\n zones?: \"skip\";\n}\n\nconst statePath = (host: string, path: string) => join(userProjectDir(host, path), \"setup.yaml\");\n\nexport function readSetupState(host: string, path: string): SetupState {\n const p = statePath(host, path);\n return existsSync(p) ? ((yaml.load(readFileSync(p, \"utf8\")) as SetupState | null) ?? {}) : {};\n}\n\nexport function writeSetupState(host: string, path: string, patch: SetupState): void {\n const p = statePath(host, path);\n mkdirSync(userProjectDir(host, path), { recursive: true });\n writeFileSync(p, yaml.dump({ ...readSetupState(host, path), ...patch }));\n}\n\nexport function missingSteps(ctx: ProjectCtx, env: NodeJS.ProcessEnv = process.env): Step[] {\n const config = loadConfig();\n const missing: Step[] = [];\n const forge = ctx.host ? config.forges.find((f) => f.host === ctx.host) : undefined;\n const type = forge?.type ?? (ctx.host === \"github.com\" ? \"github\" : undefined);\n if (!ctx.host || !type || !forgeToken(ctx.host, type, env)) missing.push(\"forge\");\n\n const profile = config.llmProfiles.find((p) => p.name === config.defaultLlmProfile) ?? config.llmProfiles[0];\n const profileUsable = profile && (profile.provider === \"ollama\" || !!getSecret(`llm:${profile.name}`));\n if (!profileUsable && !LLM_ENV_KEYS.some((k) => env[k])) missing.push(\"llm\");\n\n if (ctx.host && ctx.projectPath && !resolveProjectFiles(ctx.host, ctx.projectPath).conventions) missing.push(\"conventions\");\n if (ctx.host && ctx.projectPath && !resolveProjectFiles(ctx.host, ctx.projectPath).zones && readSetupState(ctx.host, ctx.projectPath).zones !== \"skip\") missing.push(\"zones\");\n if (ctx.host && ctx.projectPath && resolveProjectFiles(ctx.host, ctx.projectPath).rubric === DEFAULT_RUBRIC_PATH && !readSetupState(ctx.host, ctx.projectPath).weights) {\n missing.push(\"weights\");\n }\n return missing;\n}\n\n// ---- forge ----\n\n/** Proves the token works for this project: who am I + can I see it. */\nexport async function testForge(forge: ForgeClient, project: ProjectRef): Promise<{ username: string; pathWithNamespace: string }> {\n const [me, p] = await Promise.all([forge.getCurrentUser(), forge.getProject(project)]);\n return { username: me.username, pathWithNamespace: p.pathWithNamespace };\n}\n\n/** Where to create a token, prefilled where the forge supports it. */\nexport function tokenHelpUrl(type: \"gitlab\" | \"github\", host: string, baseUrl?: string): string {\n if (type === \"github\") return `https://${host}/settings/tokens/new?scopes=repo&description=Yolont`;\n return `${(baseUrl ?? `https://${host}`).replace(/\\/$/, \"\")}/-/user_settings/personal_access_tokens?name=Yolont&scopes=api`;\n}\n\n/** Records host\u2192type (and the token when given \u2014 only ever on an explicit save). First forge becomes the default. */\nexport function saveForge(host: string, type: \"gitlab\" | \"github\", token?: string): void {\n const config = loadConfig();\n const saved = config.forges.find((f) => f.host === host);\n if (saved) saved.type = type;\n else config.forges.push({ host, type });\n config.defaultForge ??= host;\n saveConfig(config);\n if (token) setSecret(`forge:${host}`, token);\n}\n\nexport function removeForge(host: string): void {\n const config = loadConfig();\n config.forges = config.forges.filter((f) => f.host !== host);\n if (config.defaultForge === host) config.defaultForge = config.forges[0]?.host;\n saveConfig(config);\n deleteSecret(`forge:${host}`);\n}\n\n// ---- llm ----\n\nexport interface ProviderPreset {\n label: string;\n provider: LlmProfile[\"provider\"];\n name: string;\n baseUrl?: string;\n model?: string;\n hint?: string;\n}\n\n// Models aren't guessed for gateways whose catalog we don't track \u2014 the user types the id.\nexport const PROVIDER_PRESETS: ProviderPreset[] = [\n { label: \"Anthropic (Claude API)\", provider: \"anthropic\", name: \"anthropic\", model: \"claude-opus-5-5\", hint: \"or claude-sonnet-5-5 \u2014 cheaper\" },\n { label: \"OpenCode\", provider: \"openai-compatible\", name: \"opencode\", baseUrl: \"https://opencode.ai/zen/v1\", model: \"deepseek-v4.1-flash\", hint: \"formerly Zen \u00B7 key from opencode.ai/console\" },\n { label: \"OpenRouter\", provider: \"openai-compatible\", name: \"openrouter\", baseUrl: \"https://openrouter.ai/api/v1\" },\n { label: \"OpenAI\", provider: \"openai-compatible\", name: \"openai\", baseUrl: \"https://api.openai.com/v1\", hint: \"an OpenAI model id (gpt-\u2026), not another gateway's\" },\n { label: \"Other OpenAI-compatible gateway\", provider: \"openai-compatible\", name: \"gateway\" },\n { label: \"Ollama (local, offline)\", provider: \"ollama\", name: \"ollama\", baseUrl: \"http://localhost:11434\", model: \"qwen2.5-coder\", hint: \"no key\" },\n];\n\nexport const PROFILE_NAME = /^[a-z0-9][a-z0-9._-]*$/i;\n\n/** Adds or updates a profile (names are immutable: the key lives under `llm:<name>`) and makes it the default. */\nexport function saveLlmProfile(profile: LlmProfile, key?: string, makeDefault = true): void {\n if (!PROFILE_NAME.test(profile.name)) throw new Error(\"Profile name: letters, digits, . _ -\");\n const config = loadConfig();\n config.llmProfiles = [...config.llmProfiles.filter((p) => p.name !== profile.name), profile];\n if (makeDefault || !config.defaultLlmProfile) config.defaultLlmProfile = profile.name;\n saveConfig(config);\n if (key) setSecret(`llm:${profile.name}`, key);\n reapplyConfigToEnv();\n}\n\nexport function setDefaultLlmProfile(name: string): void {\n const config = loadConfig();\n if (!config.llmProfiles.some((p) => p.name === name)) throw new Error(`No profile '${name}'`);\n config.defaultLlmProfile = name;\n saveConfig(config);\n reapplyConfigToEnv();\n}\n\nexport function removeLlmProfile(name: string): void {\n const config = loadConfig();\n config.llmProfiles = config.llmProfiles.filter((p) => p.name !== name);\n if (config.defaultLlmProfile === name) config.defaultLlmProfile = config.llmProfiles[0]?.name;\n saveConfig(config);\n deleteSecret(`llm:${name}`);\n reapplyConfigToEnv();\n}\n\n/** A real review call on a one-line diff \u2014 proves key, model, base URL and JSON-schema output all work. */\nexport async function testLlmProfile(profile: Pick<LlmProfile, \"provider\" | \"model\" | \"baseUrl\">, apiKey: string | undefined): Promise<void> {\n const res = await createProviderFromProfile(profile, apiKey).review({\n diff: \"diff --git a/hello.ts b/hello.ts\\n--- a/hello.ts\\n+++ b/hello.ts\\n@@ -0,0 +1 @@\\n+export const hello = () => \\\"hi\\\";\\n\",\n truncated: false,\n conventions: \"\",\n categories: [{ name: \"smoke_test\", description: \"Connectivity check. Score 100 unless the diff is empty.\" }],\n authorHistorySummary: \"\",\n });\n if (!res.categories.some((c) => c.category === \"smoke_test\")) throw new Error(\"The model answered, but not in the expected review format.\");\n}\n\n// ---- weights ----\n\n/** Applied only when the rubric's category names match the preset's exactly. */\nexport const WEIGHT_PRESETS: Record<string, { label: string; weights: Record<string, number> }> = {\n conventions: { label: \"Conventions-first (default)\", weights: { conventions: 30, maintainability: 30, ai_authenticity: 20, security: 12, pr_hygiene: 8 } },\n balanced: { label: \"Balanced\", weights: { conventions: 20, maintainability: 20, ai_authenticity: 20, security: 20, pr_hygiene: 20 } },\n security: { label: \"Security-first\", weights: { security: 35, conventions: 20, maintainability: 20, ai_authenticity: 15, pr_hygiene: 10 } },\n};\n\nexport function presetFits(weights: Record<string, number>, names: string[]): boolean {\n const keys = Object.keys(weights);\n return keys.length === names.length && names.every((n) => n in weights);\n}\n\n/** Scales to sum 100 with whole numbers (largest remainder, so it always lands on exactly 100). */\nexport function normalizeWeights(weights: Record<string, number>): Record<string, number> {\n const entries = Object.entries(weights);\n const total = entries.reduce((s, [, w]) => s + w, 0);\n if (total <= 0) return Object.fromEntries(entries.map(([k], i) => [k, Math.floor(100 / entries.length) + (i < 100 % entries.length ? 1 : 0)]));\n const exact = entries.map(([k, w]) => ({ k, v: (w / total) * 100 }));\n const out = exact.map((e) => ({ ...e, floor: Math.floor(e.v) }));\n let rest = 100 - out.reduce((s, e) => s + e.floor, 0);\n for (const e of [...out].sort((a, b) => b.v - b.floor - (a.v - a.floor))) if (rest-- > 0) e.floor++;\n return Object.fromEntries(out.map((e) => [e.k, e.floor]));\n}\n\n/**\n * `null` = keep the built-in rubric (remembered, not re-asked). Otherwise writes the project's\n * own rubric.yml \u2014 the current rubric with new weights \u2014 to the user project dir, where\n * resolveProjectFiles picks it up. Commit it as .yolont/rubric.yml to share it with the team/CI.\n * ponytail: a copy, so later changes to the built-in rubric's other fields don't flow into it.\n */\nexport function saveWeights(host: string, path: string, weights: Record<string, number> | null, threshold?: number): string | null {\n if (!weights) {\n writeSetupState(host, path, { weights: \"default\" });\n return null;\n }\n const source = resolveProjectFiles(host, path).rubric;\n const raw = yaml.load(readFileSync(source, \"utf8\")) as { categories: { name: string; weight: number }[]; threshold?: number };\n for (const c of raw.categories) if (c.name in weights) c.weight = weights[c.name]!;\n if (threshold !== undefined) raw.threshold = threshold;\n RubricSchema.parse(raw); // must still sum to 100 etc. \u2014 never write a rubric the loader rejects\n const out = join(projectSettingsDir(host, path), \"rubric.yml\");\n mkdirSync(projectSettingsDir(host, path), { recursive: true });\n writeFileSync(out, `# Yolont rubric for ${host}/${path} \u2014 weights set by \\`yolont setup\\`. Copy to .yolont/rubric.yml in the repo to share it.\\n${yaml.dump(raw)}`);\n writeSetupState(host, path, { weights: \"custom\" });\n return out;\n}\n\nexport function currentWeights(host: string, path: string): { weights: Record<string, number>; threshold: number; rubricPath: string; fromRepo: boolean } {\n const rubricPath = resolveProjectFiles(host, path).rubric;\n const rubric = loadRubric(rubricPath);\n return {\n weights: Object.fromEntries(rubric.categories.map((c) => [c.name, c.weight])),\n threshold: rubric.threshold,\n rubricPath,\n // Not the built-in and not ours: it's the repo's committed .yolont/rubric.yml, which wins.\n fromRepo: rubricPath !== DEFAULT_RUBRIC_PATH && !rubricPath.startsWith(projectSettingsDir(host, path)),\n };\n}\n", "import { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport yaml from \"js-yaml\";\nimport { globToRegExp, parseZones, type Zone } from \"../../src/zones/zones.js\";\nimport { resolveProjectFiles } from \"../conventions/resolve.js\";\nimport type { LLMProvider } from \"../../src/llm/provider.js\";\nimport { INSTALL_ROOT, ZONE_TEMPLATES_DIR } from \"../paths.js\";\nimport { writeSetupState } from \"../setup/state.js\";\nimport { projectSettingsDir } from \"../sync/source.js\";\n\n/**\n * Phase 4: a first zones.yaml from stack templates matched against the real file tree. Paths\n * only, deterministic, nothing leaves the machine. Zones are optional \u2014 skipping is a saved answer.\n */\n\n/** Stack-specific first (nextjs beats react-spa), generic always last. */\nexport function templatesFor(stack: string[]): string[] {\n const ids: string[] = [];\n if (stack.includes(\"nextjs\")) ids.push(\"nextjs\");\n else if (stack.includes(\"react\")) ids.push(\"react-spa\");\n if (stack.includes(\"node-api\")) ids.push(\"node-api\");\n return [...ids, \"generic\"];\n}\n\nexport const loadTemplate = (id: string): Zone[] => parseZones(readFileSync(join(ZONE_TEMPLATES_DIR, `${id}.yaml`), \"utf8\"), `Zone template '${id}'`);\n\nexport interface ZonesDraft {\n zones: Zone[];\n /** zone id \u2192 how many repo files it matches today */\n matched: Record<string, number>;\n templates: string[];\n}\n\n/**\n * Keeps only globs that match a real file (so the draft reads like this repo) and drops zones\n * left with none. A zone id seen earlier wins (templates share ids like `migrations`). Generic\n * zones whose files a stack zone already covers are dropped as noise.\n */\nexport function draftZones(files: string[], stack: string[]): ZonesDraft {\n const templates = templatesFor(stack);\n const zones: Zone[] = [];\n const matched: Record<string, number> = {};\n const covered = new Set<string>();\n for (const t of templates) {\n for (const zone of loadTemplate(t)) {\n if (zones.some((z) => z.id === zone.id)) continue;\n const paths = zone.paths.filter((p) => files.some((f) => globToRegExp(p).test(f)));\n if (!paths.length) continue;\n const res = paths.map(globToRegExp);\n const hits = files.filter((f) => res.some((r) => r.test(f)));\n if (t === \"generic\" && templates.length > 1 && hits.every((f) => covered.has(f))) continue;\n if (t !== \"generic\") hits.forEach((f) => covered.add(f));\n zones.push({ ...zone, paths });\n matched[zone.id] = hits.length;\n }\n }\n return { zones, matched, templates };\n}\n\n// ---- LLM draft: folder tree (+ conventions) in, zones.yaml out. No file contents are sent. ----\n\nexport const ZONES_EXAMPLE_PATH = join(INSTALL_ROOT, \"templates\", \"zones-example.yaml\");\nconst CONVENTIONS_CAP = 12_000;\n\nexport function zonesPrompt(project: string, stack: string[], tree: string, conventions?: string): string {\n const conv = conventions?.trim().slice(0, CONVENTIONS_CAP);\n return `You map the performance and risk zones of a project for the code-review bot Yolont. A reviewer LLM reads them: a PR that touches a red zone gets extra scrutiny for what that zone's \"watch_for\" lists.\n\nProject: ${project}\nDetected stack: ${stack.join(\", \") || \"unknown\"}\n\nRules:\n- level: red = runs on every start/request/render or is hard to undo (entry, bootstrap, providers, shell, middleware, global config, trackers, migrations, auth); amber = shared by many places (store, shared hooks/utils, UI primitives, API client, routing tables); green = lazy or rarely runs (lazy pages, tests, docs, tooling).\n- Cover the topics the example covers when this project has them: bootstrap, providers, shell, tracking/config, routing, store, shared helpers, primitives, lazy pages, tests/docs. Add project-specific ones the tree or conventions show. 5\u201312 zones.\n- paths: quoted globs that match folders in the tree below (** spans folders, * stays in one segment, no {a,b}). Don't invent folders.\n- why: one line, the cost of a mistake there. watch_for: 2\u20134 concrete, diff-checkable items for this stack. budget: only where a number makes sense.\n- Ids: lowercase-kebab, unique.\n\nFormat example (another project: copy the shape and depth, not its paths):\n<example>\n${readFileSync(ZONES_EXAMPLE_PATH, \"utf8\").trim()}\n</example>\n\nAnswer with exactly one block and nothing else:\n<zones>\nzones:\n - id: \u2026\n</zones>\n\nFolder tree:\n${tree}\n${conv ? `\\nThe team's conventions (hints at the architecture):\\n<conventions>\\n${conv}\\n</conventions>\\n` : \"\"}`;\n}\n\n/** The YAML inside <zones>\u2026</zones> (code fences tolerated). */\nexport function parseGeneratedZones(text: string): string {\n const raw = text.match(/<zones>([\\s\\S]*?)(?:<\\/zones>|$)/)?.[1] ?? text;\n return raw.trim().replace(/^```(?:ya?ml)?\\n/, \"\").replace(/\\n```$/, \"\") + \"\\n\";\n}\n\n/** Like draftZones' pruning: globs that match no real file go, zones left without globs go. */\nexport function keepMatching(zones: Zone[], files: string[]): { zones: Zone[]; matched: Record<string, number>; dropped: string[] } {\n const kept: Zone[] = [];\n const matched: Record<string, number> = {};\n const dropped: string[] = [];\n for (const z of zones) {\n const paths = z.paths.filter((p) => files.some((f) => globToRegExp(p).test(f)));\n dropped.push(...z.paths.filter((p) => !paths.includes(p)).map((p) => `${z.id}: ${p}`));\n if (!paths.length) continue;\n const res = paths.map(globToRegExp);\n kept.push({ ...z, paths });\n matched[z.id] = files.filter((f) => res.some((r) => r.test(f))).length;\n }\n return { zones: kept, matched, dropped };\n}\n\nexport async function generateZones(provider: LLMProvider, prompt: string): Promise<string> {\n return parseGeneratedZones(await provider.complete(prompt));\n}\n\nconst HEADER = `# Yolont zones: parts of this project where a mistake costs more, so reviews call them out.\n# level: red = runs on every start/request/render or is hard to undo; amber = widely shared; green = rarely runs.\n# paths: globs (** spans folders, * stays in one). Zones are optional; a project with none reviews fine.\n# Commit as .yolont/zones.yaml to share with the team and CI.\n`;\n\nexport function renderZonesYaml(zones: Zone[], templates: string[] = []): string {\n const plain = zones.map(({ budget, watch_for, ...z }) => ({ ...z, ...(watch_for.length && { watch_for }), ...(budget && { budget }) }));\n return `${HEADER}${templates.length ? `# Drafted from templates: ${templates.join(\", \")}\\n` : \"\"}${yaml.dump({ zones: plain }, { lineWidth: 140, flowLevel: 3 })}`;\n}\n\n/** Validates (ZonesError on bad YAML/schema) and writes the user-dir zones.yaml. An empty list is saved as \"skip\", not a file. */\nexport function saveZones(host: string, path: string, raw: string): string | null {\n if (!parseZones(raw).length) {\n skipZones(host, path);\n return null;\n }\n const dir = projectSettingsDir(host, path);\n mkdirSync(dir, { recursive: true });\n const out = join(dir, \"zones.yaml\");\n writeFileSync(out, raw.endsWith(\"\\n\") ? raw : `${raw}\\n`);\n return out;\n}\n\nexport const skipZones = (host: string, path: string) => writeSetupState(host, path, { zones: \"skip\" });\n\nexport function currentZones(host: string, path: string): { path: string | null; fromRepo: boolean; graph: string | null } {\n const f = resolveProjectFiles(host, path);\n return { path: f.zones, fromRepo: !!f.zones && !f.zones.startsWith(projectSettingsDir(host, path)), graph: f.zonesGraph };\n}\n", "import { execFileSync, spawnSync } from \"node:child_process\";\nimport { header, icon, iconSample, nerdIcons, panel, type IconName } from \"./ui.js\";\nimport { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { homedir, tmpdir, userInfo } from \"node:os\";\nimport { emitKeypressEvents } from \"node:readline\";\nimport { join, resolve } from \"node:path\";\nimport { autocompleteMultiselect, confirm, intro, isCancel, log, multiselect, note, outro, password, select, spinner, text } from \"@clack/prompts\";\nimport pc from \"picocolors\";\nimport { changeLabel, createForge, parseGitAddress, probeForgeType, type ForgeClient, type ForgeType, type GitAddress } from \"../../src/forge/index.js\";\nimport { configFilledKeys, forgeUrl, LLM_ENV_KEYS, loadConfig, reapplyConfigToEnv, saveConfig, type LlmProfile } from \"../config/config.js\";\nimport { getSecret, maskSecret, secretBackend, setSecret } from \"../config/secrets.js\";\nimport { forgeToken } from \"../forge.js\";\nimport { createLlmProvider, type LlmEnv } from \"../../src/llm/index.js\";\nimport {\n conventionsMaxLines,\n currentConventions,\n dirTree,\n generateConventions,\n lineCount,\n lookAtProject,\n normalizePastedPath,\n sourceDirs,\n type ProjectLook,\n pickFiles,\n readSections,\n saveConventions,\n scrubPrompt,\n suggestConventions,\n type CrawlSource,\n} from \"../conventions/generate.js\";\nimport { currentZones, draftZones, generateZones, keepMatching, renderZonesYaml, saveZones, skipZones, zonesPrompt } from \"../zones/generate.js\";\nimport { parseZones, ZonesError } from \"../../src/zones/zones.js\";\nimport { scanDiffForSecrets } from \"../../src/checks/secrets.js\";\nimport { DEFAULT_RUBRIC_PATH, bareHost } from \"../paths.js\";\nimport { runInteractiveReview } from \"../review/interactiveReview.js\";\nimport { openDb } from \"../db/client.js\";\nimport { addSource, checkSource, displayUrl, getSource, isKeptLocal, keepLocal, pendingToSend, removeSource, sourceDir, waitingForMerge, pullSource, shareProject, sourceFor, sourcesForHost, stopUsing, syncSource, type SourceStatus, type SyncResult } from \"../sync/source.js\";\nimport type { ImportResult } from \"../sync/records.js\";\nimport type { SourceConfig } from \"../config/config.js\";\nimport { agentSetups, onPath } from \"./agents.js\";\nimport { GITLEAKS_VERSION, gitleaksAsset, gitleaksWorks, installGitleaks, LOCAL_GITLEAKS } from \"./gitleaks.js\";\nimport { installKind, installLatest, isNewer, latestVersion, ownVersion } from \"./version.js\";\nimport { PROFILE_NAME, PROVIDER_PRESETS, removeForge, removeLlmProfile, saveForge, saveLlmProfile, currentWeights, missingSteps, normalizeWeights, presetFits, saveWeights, testForge, testLlmProfile, tokenHelpUrl, WEIGHT_PRESETS, type Step } from \"./state.js\";\n\n/** Ctrl-C: leave Yolont. */\nclass Cancelled extends Error {}\n/** Esc: leave this step (nothing saved) and go back to the menu. */\nclass Back extends Error {}\n\n// clack reports Esc and Ctrl-C both as \"cancel\"; the last key pressed tells them apart. Our\n// listener is registered before any prompt's, so it has run by the time the prompt resolves.\nlet lastKey = \"\";\nlet tracking = false;\nfunction trackKeys(): void {\n if (tracking || !process.stdin.isTTY) return;\n tracking = true;\n emitKeypressEvents(process.stdin);\n process.stdin.on(\"keypress\", (_s: string, k?: { name?: string; ctrl?: boolean }) => {\n lastKey = k?.ctrl && k.name === \"c\" ? \"ctrl-c\" : (k?.name ?? \"\");\n // A pasted trailing newline arrives as \"\\n\" (key \"enter\"), not Enter (\"\\r\", key \"return\").\n // readline treats it as end-of-line: it clears the input and files it in history, so the\n // paste flashes and vanishes (\u2191 brings it back). Turn it into a real Enter first \u2014 this\n // listener runs before readline's, which then sees a finished prompt.\n if (newlineSubmits && k?.name === \"enter\") process.stdin.emit(\"keypress\", \"\\r\", { name: \"return\", sequence: \"\\r\", ctrl: false, meta: false, shift: false });\n });\n}\n\n/** Only for single-line inputs: a multi-line prompt (the review's focus note) needs real newlines. */\nlet newlineSubmits = false;\nasync function askLine<T>(prompt: Promise<T | symbol>): Promise<T> {\n newlineSubmits = true;\n try {\n return await ask(prompt);\n } finally {\n newlineSubmits = false;\n }\n}\n\n/** Unwraps a clack answer: Esc \u2192 Back (to the menu), Ctrl-C \u2192 Cancelled (quit). */\nasync function ask<T>(prompt: Promise<T | symbol>): Promise<T> {\n const v = await prompt;\n if (isCancel(v)) throw lastKey === \"escape\" ? new Back() : new Cancelled();\n return v as T;\n}\n\n/** Runs one step; Esc inside it returns false instead of ending the wizard. */\nasync function orBack(step: () => Promise<unknown>): Promise<boolean> {\n try {\n await step();\n return true;\n } catch (err) {\n if (err instanceof Back) {\n log.info(\"Back \u2014 nothing saved for that step.\");\n return false;\n }\n throw err;\n }\n}\n\nconst sum = (w: Record<string, number>) => Object.values(w).reduce((a, b) => a + b, 0);\n\nfunction originAddress(): string | undefined {\n try {\n return execFileSync(\"git\", [\"remote\", \"get-url\", \"origin\"], { encoding: \"utf8\", stdio: [\"ignore\", \"pipe\", \"ignore\"] }).trim() || undefined;\n } catch {\n return undefined;\n }\n}\n\nconst gitlabBases = () => loadConfig().forges.filter((f) => f.type === \"gitlab\" && f.url).map(forgeUrl);\n\nexport interface SetupOptions {\n /** MR/PR URL or git address; defaults to this checkout's origin. */\n address?: string;\n /** Only these steps, each shown as keep/change (`setup --step`). Default: whatever is missing. */\n steps?: Step[];\n /** `setup` with no --step: walk every step as keep/change. */\n all?: boolean;\n /** Finish with the review picker (bare `yolont`). */\n review?: boolean;\n /** `conventions generate --repo <path>`: crawl this checkout instead of cwd. */\n repo?: string;\n /** `conventions generate|edit`: skip keep/change and go straight to it. */\n conventions?: \"generate\" | \"edit\";\n /** `zones generate|edit`: same, for zones. */\n zones?: \"generate\" | \"edit\";\n}\n\n/**\n * `yolont` / `yolont setup`. Bare `yolont` asks only for what's missing, then picks a PR to\n * review, so a configured machine goes straight to the picker. Every step shows the saved\n * value first, so re-running is cheap.\n */\nexport async function runSetup(opts: SetupOptions): Promise<void> {\n const version = ownVersion();\n latestCheck = latestVersion(); // in the background; the menu shows it if it came back\n header(`${version ? `v${version} \u00B7 ` : \"\"}PR reviews that look twice \u00B7 Esc = back \u00B7 Ctrl-C = quit`);\n await offerInstallOnce();\n await ensureGitleaks();\n await askIconsOnce();\n intro(opts.review ? \"Yolont\" : \"Yolont setup\");\n trackKeys();\n try {\n const forceAll = !!opts.all;\n const wants = (s: Step, missing: Step[]) => forceAll || opts.steps?.includes(s) || (!opts.steps && missing.includes(s));\n const change = (s: Step) => forceAll || !!opts.steps?.includes(s);\n\n // LLM profiles are global: `setup --step llm` needs no project, so don't make it touch the forge.\n const needsProject = opts.review || forceAll || !opts.steps || opts.steps.some((s) => s !== \"llm\");\n if (!needsProject) {\n await orBack(() => llmStep(true));\n outro(\"Done.\");\n return;\n }\n\n // The git host comes first: every other step needs it. Esc here has nothing to go back to.\n const raw = opts.address ?? originAddress();\n const parsed = parseAddress(raw);\n const missing = missingSteps({ host: parsed?.host, projectPath: parsed?.projectPath });\n let ctx: { forge: ForgeClient; address: GitAddress };\n try {\n ctx = await forgeStep(parsed, raw, wants(\"forge\", missing) || !parsed);\n } catch (err) {\n if (err instanceof Back) throw new Cancelled();\n throw err;\n }\n\n // The project's memory repo next: pulled conventions/zones change what's missing below.\n await orBack(() => memoryStep(ctx.address));\n\n // Walk what's missing (or what was asked for). Esc skips to the menu (bare `yolont`) or to the next step (`setup`).\n const missingNow = missingSteps({ host: ctx.address.host, projectPath: ctx.address.projectPath });\n for (const s of [\"llm\", \"conventions\", \"zones\", \"weights\"] as const) {\n if (!wants(s, missingNow)) continue;\n if (!(await orBack(() => runStep(s, ctx, change(s), opts))) && opts.review) break;\n }\n\n if (!opts.review) {\n outro(\"Setup saved.\");\n return;\n }\n if (ctx.address.ref) await orBack(() => reviewThenCheckQuit(ctx, ctx.address.ref!.number));\n await mainMenu(ctx, opts);\n outro(\"Bye.\");\n } catch (err) {\n if (err instanceof Cancelled) {\n outro(\"Cancelled.\");\n return;\n }\n throw err;\n }\n}\n\nasync function runStep(s: Step, ctx: { forge: ForgeClient; address: GitAddress }, change: boolean, opts: SetupOptions): Promise<void> {\n const { forge, address } = ctx;\n if (s === \"llm\") return llmStep(change);\n if (s === \"conventions\") return conventionsStep(forge, address, change, opts);\n if (s === \"zones\") return zonesStep(forge, address, change, opts);\n if (s === \"weights\") return weightsStep(address.host, address.projectPath, change);\n // A different address/token may point at another project: the menu follows it.\n Object.assign(ctx, await forgeStep(address, `https://${address.host}/${address.projectPath}`, true));\n}\n\n/** The review handles its own cancel: Esc there returns to the menu, Ctrl-C still quits. */\nasync function reviewThenCheckQuit(ctx: { forge: ForgeClient; address: GitAddress }, mrIid: number): Promise<void> {\n lastKey = \"\";\n await runInteractiveReview({ forge: ctx.forge, project: ctx.address.projectPath, mrIid });\n if (lastKey === \"ctrl-c\") throw new Cancelled();\n}\n\nconst STEP_ICONS: Record<Step, IconName> = { forge: \"git\", llm: \"llm\", conventions: \"conventions\", zones: \"zones\", weights: \"weights\" };\n\n/** First run on a terminal: show some Nerd Font icons and ask if they draw; saved either way. */\n/** npx keeps packages in its cache under `_npx/`; running from there means `yolont` isn't installed. */\nexport const runningFromNpx = (script = process.argv[1] ?? \"\") => installKind(script) === \"npx\";\n\nlet latestCheck: Promise<string | undefined> = Promise.resolve(undefined);\n\n/** The newer npm version, if there is one. Waits at most a moment for the background check. */\nasync function newerVersion(): Promise<string | undefined> {\n const [current, latest] = [ownVersion(), await Promise.race([latestCheck, new Promise<undefined>((r) => setTimeout(() => r(undefined), 300))])];\n return current && latest && isNewer(latest, current) ? latest : undefined;\n}\n\n/** Menu \"Update\": npm installs update in place; npx and source checkouts get the command to run. */\nasync function updateMenu(latest: string): Promise<void> {\n const kind = installKind();\n if (kind === \"source\") {\n log.info(`This is a source checkout. Update it with ${pc.bold(\"git pull && npm ci\")}, or install the package: ${pc.bold(`npm install -g yolont@${latest}`)}`);\n return;\n }\n if (kind === \"npx\") {\n log.info(`Run ${pc.bold(\"npx yolont@latest\")} next time, or install it once: ${pc.bold(`npm install -g yolont@${latest}`)}`);\n return;\n }\n if (!(await ask<boolean>(confirm({ message: `Update to v${latest}? (npm install -g yolont@${latest})`, initialValue: true })))) return;\n if (installLatest(latest)) {\n outro(`Updated to v${latest}. Run ${pc.bold(\"yolont\")} again to use it.`);\n process.exit(0); // this process still runs the old code\n }\n log.warn(\"npm couldn't update it (often a permissions issue): https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally\");\n}\n\n/** First run through npx: offer `npm install -g` so later runs are just `yolont`. Asked once. */\nasync function offerInstallOnce(): Promise<void> {\n if (!runningFromNpx() || loadConfig().installOffered || !process.stdout.isTTY) return;\n const version = ownVersion() ?? \"latest\";\n const ok = await confirm({ message: `Install the \\`yolont\\` command, so next time you just type \\`yolont\\`? (npm install -g yolont@${version})`, initialValue: true });\n if (isCancel(ok)) return;\n saveConfig({ ...loadConfig(), installOffered: true });\n if (!ok) {\n log.info(pc.dim(\"OK. Install it any time with `npm install -g yolont`.\"));\n return;\n }\n if (installLatest(version)) log.success(`Installed. From now on run ${pc.bold(\"yolont\")} (no npx).`);\n else\n log.warn(\n `Couldn't install it (often a permissions issue with npm's global folder). Run \\`npm install -g yolont\\` yourself; for permission errors see https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally`,\n );\n}\n\n/** Every run while it's missing: without gitleaks no diff is ever sent to the LLM (fail-closed). */\nasync function ensureGitleaks(): Promise<void> {\n if (gitleaksWorks() || !process.stdout.isTTY) return;\n const help = \"https://github.com/gitleaks/gitleaks#installing\";\n if (!gitleaksAsset()) {\n log.warn(`gitleaks (the secret scanner) isn't installed, so reviews will skip the LLM. Install it: ${help}`);\n return;\n }\n const ok = await confirm({\n message: `gitleaks (the secret scanner) isn't installed. Without it, reviews never reach the LLM. Download the official v${GITLEAKS_VERSION} (checksum-verified) into ${LOCAL_GITLEAKS}?`,\n initialValue: true,\n });\n if (isCancel(ok) || !ok) {\n log.warn(`Reviews will skip the LLM until gitleaks is installed: ${help}`);\n return;\n }\n const s = spinner();\n s.start(`Downloading gitleaks v${GITLEAKS_VERSION}`);\n try {\n await installGitleaks();\n s.stop(gitleaksWorks() ? `gitleaks v${GITLEAKS_VERSION} installed.` : pc.yellow(\"Downloaded, but it doesn't run on this machine.\"));\n } catch (err) {\n s.stop(pc.red(`gitleaks install failed: ${describeFetchError(err)}`));\n log.warn(`Install it yourself: ${help}`);\n }\n}\n\nasync function askIconsOnce(): Promise<void> {\n if (loadConfig().icons || !process.stdout.isTTY) return;\n const ok = await confirm({ message: `Do these look like icons (not boxes or \"?\")? ${iconSample()}`, initialValue: true });\n if (isCancel(ok)) return;\n saveConfig({ ...loadConfig(), icons: ok ? \"nerd\" : \"plain\" });\n log.info(pc.dim(ok ? \"Nerd Font icons on. Turn off with `icons: plain` in config.yaml.\" : \"Plain text. Install a Nerd Font and set `icons: nerd` in config.yaml for icons.\"));\n}\n\n/** Where things stand, shown once when the main menu opens. */\nfunction statusPanel(ctx: { forge: ForgeClient; address: GitAddress }, teamLabel: string, latest?: string): void {\n const config = loadConfig();\n const llm = config.llmProfiles.find((p) => p.name === config.defaultLlmProfile);\n panel(\"Yolont\", [\n [`${icon(ctx.forge.type === \"github\" ? \"github\" : \"gitlab\")}Project`, `${pc.bold(ctx.address.projectPath)} ${pc.dim(`\u00B7 ${ctx.address.host}`)}`],\n [`${icon(\"llm\")}LLM`, llm ? `${llm.name} ${pc.dim(`\u00B7 ${llm.model}`)}` : pc.yellow(\"not set\")],\n [`${icon(\"memory\")}Memory`, teamLabel.replace(/^Memory repo( \u00B7 )?/, \"\") || \"\u2014\"],\n [`${icon(\"type\")}Change type`, CHANGE_TYPE_MODES[config.changeType ?? \"label\"].label],\n [`${icon(\"sync\")}Version`, `v${ownVersion() ?? \"?\"}${latest ? pc.yellow(` \u00B7 v${latest} is out`) : \"\"}`],\n ]);\n}\n\nconst STEP_LABELS: Record<Step, string> = { forge: \"Git host & token\", llm: \"LLM\", conventions: \"Conventions\", zones: \"Zones\", weights: \"Scoring weights\" };\n\n/** Bare `yolont` once set up: review, or revisit any step. Esc inside anything comes back here; Esc here exits. */\nasync function mainMenu(ctx: { forge: ForgeClient; address: GitAddress }, opts: SetupOptions): Promise<void> {\n const latest = await newerVersion();\n statusPanel(ctx, await teamMenuLabel(ctx.address), latest);\n for (;;) {\n const missing = missingSteps({ host: ctx.address.host, projectPath: ctx.address.projectPath });\n const teamLabel = await teamMenuLabel(ctx.address);\n let choice: string;\n try {\n choice = await ask(\n select({\n message: `${ctx.address.projectPath} \u00B7 ${ctx.address.host}`,\n options: [\n { value: \"review\", label: `${icon(\"review\")}${pc.bold(\"Review an open MR/PR\")}` },\n ...(latest ? [{ value: \"update\", label: pc.yellow(`${icon(\"sync\")}Update to v${latest}`), hint: `you have v${ownVersion()}` }] : []),\n ...(Object.keys(STEP_LABELS) as Step[]).map((s) => ({\n value: s,\n label: `${missing.includes(s) ? pc.red(nerdIcons() ? icon(\"missing\") : \"\u2717 \") : pc.green(nerdIcons() ? icon(\"ok\") : \"\u2713 \")}${icon(STEP_ICONS[s])}${STEP_LABELS[s]}`,\n })),\n { value: \"team\", label: `${icon(\"memory\")}${teamLabel}` },\n { value: \"changeType\", label: `${icon(\"type\")}Change type: ${CHANGE_TYPE_MODES[loadConfig().changeType ?? \"label\"].label}` },\n { value: \"agent\", label: `${icon(\"llm\")}Connect your coding agent`, hint: \"team rules + a pre-PR checklist in Claude Code, VS Code, Cursor\u2026\" },\n { value: \"remove\", label: `${icon(\"remove\")}Remove saved\u2026`, hint: \"LLM keys, git host tokens, memory repos\" },\n { value: \"exit\", label: `${icon(\"exit\")}Exit` },\n ],\n }),\n );\n } catch (err) {\n if (err instanceof Back) return;\n throw err;\n }\n if (choice === \"exit\") return;\n if (choice === \"update\") {\n await orBack(() => updateMenu(latest!));\n continue;\n }\n if (choice === \"agent\") {\n await orBack(() => connectAgentMenu());\n continue;\n }\n if (choice === \"remove\") {\n await orBack(() => removeMenu(ctx.address));\n continue;\n }\n if (choice === \"changeType\") {\n await orBack(() => changeTypeMenu());\n continue;\n }\n if (choice === \"team\") {\n await orBack(() => teamMenu(ctx.address));\n continue;\n }\n if (choice === \"review\") {\n await orBack(async () => {\n const mrIid = await pickChange(ctx.forge, ctx.address.projectPath);\n if (mrIid !== null) await reviewThenCheckQuit(ctx, mrIid);\n });\n continue;\n }\n await orBack(() => runStep(choice as Step, ctx, true, opts));\n }\n}\n\n// ---- coding agents (MCP) ----\n\n/** Registers `yolont mcp` with the user's coding agent: runs the agent's own CLI after asking, else shows what to paste. */\nasync function connectAgentMenu(): Promise<void> {\n note(\n \"Your agent gets two read-only tools: the team's guidelines, and a pre-PR checklist for your\\nbranch (conventions, zones, change-type checks, your past lessons, a local secret scan).\\nNo LLM call, no score, nothing posted: your agent's own model does the checking.\\nIn the agent, try /yolont-check before opening a PR.\",\n \"Yolont in your coding agent\",\n );\n const setups = agentSetups();\n const id = await ask<string>(select({ message: \"Which agent?\", options: setups.map((a) => ({ value: a.id, label: a.label })) }));\n const agent = setups.find((a) => a.id === id)!;\n // ponytail: no Windows run for VS Code, a JSON arg doesn't survive cmd.exe quoting; it gets the paste instead.\n const runnable = agent.run && !(process.platform === \"win32\" && agent.id === \"vscode\") && onPath(agent.run.bin);\n if (runnable && (await ask<boolean>(confirm({ message: `Run \\`${agent.run!.bin} ${agent.run!.args.join(\" \")}\\`?`, initialValue: true })))) {\n const r = spawnSync(agent.run!.bin, agent.run!.args, { stdio: \"inherit\", shell: process.platform === \"win32\" });\n if (r.status === 0) {\n log.success(`Connected. Open ${agent.label} in a project and try /yolont-check.`);\n return;\n }\n log.warn(`${agent.run!.bin} exited with ${r.status ?? r.signal}. Do it by hand:`);\n } else if (agent.run && !runnable) {\n log.info(pc.dim(`\\`${agent.run.bin}\\` isn't on PATH here, so here's what to run or paste:`));\n }\n note(agent.manual, agent.label);\n}\n\n// ---- remove saved things ----\n\n/** One place to remove what setup saved. Each removal says exactly what goes and asks first. */\nasync function removeMenu(address: GitAddress): Promise<void> {\n const config = loadConfig();\n const project = `${address.host}/${address.projectPath}`;\n const items = [\n ...config.llmProfiles.map((p) => ({ value: `llm:${p.name}`, label: `LLM: ${p.name} \u00B7 ${p.model}`, hint: \"the profile and its API key\" })),\n ...config.forges.map((f) => ({ value: `forge:${f.host}`, label: `Git host: ${f.host}`, hint: f.host === address.host ? \"its token \u00B7 this project's host\" : \"its token\" })),\n ...(config.sources ?? []).map((s) => ({ value: `source:${s.name}`, label: `Memory repo: ${s.name}`, hint: `${displayUrl(s.url)} \u00B7 on this machine only` })),\n ...((config.localProjects ?? []).length ? [{ value: \"local\", label: `\"No memory repo\" choices (${config.localProjects!.length})`, hint: \"the wizard asks again\" }] : []),\n ];\n if (items.length === 0) {\n log.info(\"Nothing saved to remove.\");\n return;\n }\n const pick = await ask<string>(select({ message: \"Remove which?\", options: items }));\n const [kind, ...rest] = pick.split(\":\");\n const name = rest.join(\":\");\n\n if (kind === \"llm\") {\n if (!(await ask<boolean>(confirm({ message: `Remove LLM profile '${name}' and its saved API key?`, initialValue: false })))) return;\n removeLlmProfile(name);\n log.success(`Removed '${name}'.${loadConfig().defaultLlmProfile ? ` Reviews now use '${loadConfig().defaultLlmProfile}'.` : \" Add an LLM before the next review.\"}`);\n } else if (kind === \"forge\") {\n const here = name === address.host;\n if (!(await ask<boolean>(confirm({ message: `Remove git host ${name} and its saved token?${here ? \" This project is on it: you'll be asked for a token next time.\" : \"\"}`, initialValue: false })))) return;\n removeForge(name);\n log.success(`Removed ${name}.`);\n } else if (kind === \"source\") {\n const db = openDb();\n try {\n const source = getSource(name);\n const unsent = await pendingToSend(db, source).catch(() => 0);\n const waiting = await waitingForMerge(source).catch(() => 0);\n note(\n [\n `Projects using it go back to your own memory: ${source.projects.join(\", \") || \"(none)\"}.`,\n \"What came from it is dropped here; your own reviews stay in your DB.\",\n `Its local copy (${sourceDir(name)}) is deleted. The repo itself, and what you already sent, are untouched.`,\n ...(unsent ? [pc.yellow(`${unsent} change(s) of yours were never sent and will be lost (sync first to keep them).`)] : []),\n ...(waiting ? [`${waiting} file(s) you sent wait for merge in your merge request; that stays on the git host.`] : []),\n ].join(\"\\n\"),\n `Remove memory repo ${name}`,\n );\n if (!(await ask<boolean>(confirm({ message: `Remove memory repo '${name}' from this machine?`, initialValue: false })))) return;\n removeSource(db, name);\n log.success(`Removed memory repo '${name}'.${source.projects.includes(`${project}`.toLowerCase()) ? \" This project now uses only your own memory.\" : \"\"}`);\n } finally {\n db.close();\n }\n } else if (kind === \"local\") {\n saveConfig({ ...loadConfig(), localProjects: [] });\n log.success(\"Cleared. The wizard asks again which memory repo each of those projects uses.\");\n }\n}\n\n// ---- change type (src/changeType.ts) ----\n\nconst CHANGE_TYPE_MODES = {\n label: {\n label: \"Label\",\n hint: \"the review also names it (feature, bugfix, refactor\u2026); you confirm it after. Saved and filterable; the review itself is unchanged. No extra cost.\",\n },\n steer: {\n label: \"Steer the review\",\n hint: \"settled before the review (from the title/branch/labels, else one small extra LLM call); you confirm it, then the review gets that type's checks (refactor: no behavior change; bugfix: regression test; \u2026).\",\n },\n off: { label: \"Off\", hint: \"no change type.\" },\n} as const;\n\nasync function changeTypeMenu(): Promise<void> {\n note(\n Object.values(CHANGE_TYPE_MODES)\n .map((m) => `${pc.bold(m.label)}: ${m.hint}`)\n .join(\"\\n\\n\"),\n \"Change type\",\n );\n const current = loadConfig().changeType ?? \"label\";\n const mode = await ask<keyof typeof CHANGE_TYPE_MODES>(\n select({\n message: \"How should Yolont use the change type?\",\n initialValue: current,\n options: (Object.keys(CHANGE_TYPE_MODES) as (keyof typeof CHANGE_TYPE_MODES)[]).map((k) => ({ value: k, label: CHANGE_TYPE_MODES[k].label + (k === current ? \" (now)\" : \"\") })),\n }),\n );\n saveConfig({ ...loadConfig(), changeType: mode });\n log.success(`Change type: ${CHANGE_TYPE_MODES[mode].label}. CI uses YOLONT_CHANGE_TYPE=${mode} (default label).`);\n}\n\n// ---- memory repos ----\n\nconst describeStatus = (st: SourceStatus) =>\n st.error\n ? pc.yellow(`couldn't reach it: ${st.error}`)\n : [\n st.incoming + st.outgoing === 0 && \"up to date\",\n st.incoming && `${st.incoming} update(s) from the team to get`,\n st.outgoing && `${st.outgoing} change(s) of yours to send`,\n st.waiting && `${st.waiting} file(s) waiting for merge`,\n ]\n .filter(Boolean)\n .join(\" \u00B7 \");\n\nasync function checkAll(sources: SourceConfig[] = loadConfig().sources ?? []): Promise<{ source: SourceConfig; status: SourceStatus }[]> {\n if (sources.length === 0) return [];\n const s = spinner();\n s.start(\"Checking memory repo\");\n const db = openDb();\n try {\n const out = [];\n for (const source of sources) out.push({ source, status: await checkSource(db, source) });\n s.stop(\"Memory repo checked\");\n return out;\n } finally {\n db.close();\n }\n}\n\n/** Get and/or send, then say what happened. Errors are shown, never thrown: memory sync must not block a review. */\nasync function runSync(source: SourceConfig, mode: \"sync\" | \"pull\"): Promise<void> {\n const s = spinner();\n s.start(mode === \"sync\" ? `Syncing ${source.name}` : `Getting updates from ${source.name}`);\n const db = openDb();\n try {\n const r: ImportResult & Partial<SyncResult> = mode === \"sync\" ? await syncSource(db, source) : await pullSource(db, source);\n const sent = r.sent !== undefined ? `, sent ${r.sent} record(s)${r.deletedShared ? `, removed ${r.deletedShared}` : \"\"}` : \"\";\n s.stop(`${source.name}: got ${r.imported} record(s)${r.removed ? `, ${r.removed} removed` : \"\"}${r.restored ? `, restored ${r.restored} of yours` : \"\"}${sent}`);\n if (r.review) {\n log.info(`${r.review.waiting} file(s) wait for a maintainer to merge into ${r.review.target}${r.review.url ? `: ${r.review.url}` : \"\"}`);\n if (r.review.note) log.warn(r.review.note);\n }\n if (r.rejected.length) log.warn(`Skipped ${r.rejected.length} file(s) that don't belong where they are (e.g. ${r.rejected[0]}).`);\n } catch (err) {\n s.error(`${source.name}: not synced`);\n log.error((err as Error).message);\n } finally {\n db.close();\n }\n}\n\n/**\n * \"Memory repo \u00B7 frontend \u00B7 2 to send\" (yellow: not sent yet), else \"\u00B7 80 waiting for merge\" (cyan:\n * sent, a maintainer hasn't merged it). Counted locally, so a review just done shows up without a fetch.\n */\nasync function teamMenuLabel(address: GitAddress): Promise<string> {\n const source = sourceFor(address.host, address.projectPath);\n if (!source) return `Memory repo${pc.dim(\" (none: only your own)\")}`;\n const db = openDb();\n try {\n const n = await pendingToSend(db, source);\n const waiting = n ? 0 : await waitingForMerge(source);\n return `Memory repo \u00B7 ${source.name}${n ? pc.yellow(` \u00B7 ${n} to send`) : waiting ? pc.cyan(` \u00B7 ${waiting} waiting for merge`) : \"\"}`;\n } catch {\n return `Memory repo \u00B7 ${source.name}`;\n } finally {\n db.close();\n }\n}\n\n/** After the project address: its memory repo (asked once, saved), then what's waiting in it. */\nasync function memoryStep(address: GitAddress): Promise<void> {\n let source = sourceFor(address.host, address.projectPath);\n if (!source && !isKeptLocal(address.host, address.projectPath)) source = (await chooseMemoryRepo(address)) ?? undefined;\n if (source) await offerSync(source, true);\n}\n\nasync function offerSync(source: SourceConfig, quietIfUpToDate: boolean): Promise<void> {\n const { status } = (await checkAll([source]))[0]!;\n log.info(`Memory repo ${pc.bold(source.name)}: ${describeStatus(status)}`);\n if (status.error || (quietIfUpToDate && status.incoming + status.outgoing === 0)) return;\n const choice = await ask<string>(\n select({\n message: `Sync ${source.name} now?`,\n options: [\n { value: \"sync\", label: \"Get updates and send mine\" },\n { value: \"pull\", label: \"Only get the team's updates\" },\n { value: \"later\", label: quietIfUpToDate ? \"Later\" : \"Back\" },\n ],\n }),\n );\n if (choice !== \"later\") await runSync(source, choice as \"sync\" | \"pull\");\n}\n\n/** Connects a new memory repo on `host`; null when cancelled or it failed (the error is shown). */\nasync function connectSource(host: string): Promise<SourceConfig | null> {\n note(\n `A git repo on ${host} that holds Yolont memory for some of your projects: reviews, corrections,\\nmemory, conventions and zones. Create an empty private repo (members need read + write; protect\\nits main branch so changes come in as merge requests), then paste its address.\\nOnly projects you choose use it, and gitleaks checks everything before it's sent.`,\n \"Memory repo\",\n );\n const url = await askLine<string>(\n text({\n message: `Memory repo address (on ${host})`,\n placeholder: `git@${host}:team/yolont-memory.git`,\n validate: (v) => {\n const a = v?.trim() ? parseGitAddress(v.trim()) : null;\n if (!a) return \"A git address, like git@host:group/repo.git\";\n return bareHost(a.host) === bareHost(host) ? undefined : `That's on ${a.host}; this project is on ${host} (an ssh host alias? add it with: yolont source add <name> <address> --host ${host})`;\n },\n }),\n );\n const taken = new Set((loadConfig().sources ?? []).map((s) => s.name));\n const name = await askLine<string>(\n text({ message: \"Short name for it\", placeholder: \"frontend\", validate: (v) => (!/^[a-z0-9][a-z0-9-]*$/.test(v ?? \"\") ? \"lowercase letters, digits, '-'\" : taken.has(v!) ? \"Already used\" : undefined) }),\n );\n const member = loadConfig().member?.name ?? (await askLine<string>(text({ message: \"Your name in memory repos\", initialValue: userInfo().username })));\n const s = spinner();\n s.start(\"Cloning\");\n try {\n const source = await addSource(name, url.trim(), member);\n s.stop(`Connected ${name}`);\n return source;\n } catch (err) {\n s.error(\"Not connected\");\n log.error((err as Error).message);\n return null;\n }\n}\n\n/**\n * Which memory repo a project uses. Only repos on the project's own host are offered; choosing\n * another switches (what came from the old one is dropped here, it stays in its repo).\n */\nasync function chooseMemoryRepo(address: GitAddress): Promise<SourceConfig | null> {\n const project = `${address.host}/${address.projectPath}`;\n const current = sourceFor(address.host, address.projectPath);\n const onHost = sourcesForHost(address.host);\n const elsewhere = (loadConfig().sources ?? []).length - onHost.length;\n if (elsewhere) log.message(pc.dim(`${elsewhere} memory repo(s) on other hosts aren't offered: a project only uses one on its own git host.`));\n const pick = await ask<string>(\n select({\n message: `Memory repo for ${project}`,\n options: [\n ...onHost.map((s) => ({ value: s.name, label: s.name === current?.name ? `${s.name} (now)` : s.name, hint: displayUrl(s.url) })),\n { value: \"new\", label: `Add a memory repo on ${address.host}` },\n { value: \"none\", label: \"None: only my own memory for this project\" },\n ],\n }),\n );\n if (pick === current?.name) return current;\n const db = openDb();\n try {\n if (pick === \"none\") {\n stopUsing(db, address.host, address.projectPath);\n keepLocal(address.host, address.projectPath);\n log.info(`${project}: only your own memory. Change it any time under \"Memory repo\".`);\n return null;\n }\n const target = pick === \"new\" ? await connectSource(address.host) : getSource(pick);\n if (!target) return current ?? null;\n if (current) stopUsing(db, address.host, address.projectPath);\n const { copied, kept } = await shareProject(target.name, address.host, address.projectPath);\n log.success(`${project} now uses ${target.name}${current ? ` (was ${current.name})` : \"\"}.`);\n if (copied.length) log.success(`Moved into ${target.name}: ${copied.join(\", \")}`);\n if (kept.length) log.warn(`${target.name} already has ${kept.join(\", \")}: its version is used. Yours stays in ~/.config/yolont.`);\n return getSource(target.name);\n } catch (err) {\n log.error((err as Error).message);\n return current ?? null;\n } finally {\n db.close();\n }\n}\n\nasync function teamMenu(address: GitAddress): Promise<void> {\n const source = sourceFor(address.host, address.projectPath);\n if (!source) {\n const chosen = await chooseMemoryRepo(address);\n if (chosen) await offerSync(chosen, false);\n return;\n }\n const choice = await ask<string>(\n select({\n message: `Memory repo ${source.name}`,\n options: [\n { value: \"sync\", label: \"Sync now\" },\n { value: \"switch\", label: \"Switch to another memory repo (or none)\" },\n { value: \"back\", label: \"Back\" },\n ],\n }),\n );\n if (choice === \"sync\") await offerSync(source, false);\n if (choice === \"switch\") {\n const chosen = await chooseMemoryRepo(address);\n if (chosen && chosen.name !== source.name) await offerSync(chosen, false);\n }\n}\n\nfunction parseAddress(s: string | undefined): GitAddress | null {\n if (!s?.trim()) return null;\n // \"github.com/owner/repo\" pasted without a scheme\n const withScheme = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(s.trim()) || s.includes(\"@\") ? s : `https://${s.trim()}`;\n return parseGitAddress(withScheme, gitlabBases());\n}\n\n// ---- step 1: forge ----\n\n/**\n * \"fetch failed\" alone hides why: the real reason (DNS, timeout, TLS refused, proxy) is in\n * `cause`. Network failures also get a hint, since a VPN or proxy is the usual culprit.\n */\nexport function describeFetchError(err: unknown): string {\n const e = err as Error & { cause?: { code?: string; message?: string } };\n const cause = e.cause?.code ?? e.cause?.message;\n if (!cause) return e.message;\n const hint =\n /ENOTFOUND|EAI_AGAIN/.test(cause) ? \"the host name doesn't resolve\" :\n /ETIMEDOUT|UND_ERR_CONNECT_TIMEOUT/.test(cause) ? \"no answer (blocked, or needs a VPN?)\" :\n /ECONNREFUSED|ECONNRESET/.test(cause) ? \"the connection was refused or dropped\" :\n /SSL|TLS|CERT/i.test(cause) ? \"the secure connection was refused (often a VPN/proxy or a region block)\" : \"\";\n return `${e.message} (${cause}${hint ? `: ${hint}` : \"\"}). Can you open the host in a browser from this machine?`;\n}\n\nasync function forgeStep(detected: GitAddress | null, raw: string | undefined, change: boolean): Promise<{ forge: ForgeClient; address: GitAddress }> {\n let address = detected;\n let last = raw ?? \"\";\n for (;;) {\n if (!address || change) {\n const input = await askLine(\n text({\n message: \"Git address or MR/PR URL\",\n placeholder: \"https://github.com/owner/repo/pull/12 \u00B7 git@gitlab.com:group/project.git\",\n initialValue: last,\n validate: (v) => (parseAddress(v ?? \"\") ? undefined : \"Not a git address or MR/PR URL\"),\n }),\n );\n last = input;\n address = parseAddress(input)!;\n }\n const config = loadConfig();\n const saved = config.forges.find((f) => f.host === address!.host);\n\n let type: ForgeType | null = saved?.type ?? address.ref?.type ?? null;\n if (!type) {\n const s = spinner();\n s.start(`Detecting what runs on ${address.host}`);\n type = await probeForgeType(address.host);\n s.stop(type ? `${address.host} is ${type === \"github\" ? \"GitHub\" : \"GitLab\"}` : `Couldn't tell what ${address.host} is`);\n type ??= await ask(select<ForgeType>({ message: `Is ${address.host} GitLab or GitHub?`, options: [{ value: \"gitlab\", label: \"GitLab\" }, { value: \"github\", label: \"GitHub\" }] }));\n }\n\n let token = forgeToken(address.host, type);\n let isNew = false;\n if (token && change) {\n const keep = await ask(select({ message: `Token for ${address.host}`, options: [{ value: true, label: `Keep ${maskSecret(token)}` }, { value: false, label: \"Enter a new one\" }] }));\n if (!keep) token = undefined;\n }\n if (!token) {\n note(`${tokenHelpUrl(type, address.host, saved ? forgeUrl(saved) : undefined)}\\n${type === \"github\" ? \"Scope: repo (or fine-grained: Pull requests + Issues read/write, Contents + Actions read)\" : \"Scope: api\"}`, \"Create a token\");\n token = (await askLine(password({ message: `Token for ${address.host}`, validate: (v) => (v?.trim() ? undefined : \"Required\") }))).trim();\n isNew = true;\n }\n\n const forge = createForge({ type, host: address.host, url: saved ? forgeUrl(saved) : undefined, token });\n const s = spinner();\n s.start(`Checking access to ${address.projectPath}`);\n try {\n const ok = await testForge(forge, address.projectPath);\n s.stop(`Signed in as ${pc.bold(ok.username)} \u00B7 ${ok.pathWithNamespace}`);\n } catch (err) {\n s.stop(pc.red(`Check failed: ${describeFetchError(err)}`));\n const next = await ask(\n select({\n message: \"What now?\",\n options: [\n { value: \"retry\", label: \"Enter a different address or token\" },\n { value: \"save\", label: \"Save anyway (e.g. VPN is down right now)\" },\n ],\n }),\n );\n if (next === \"retry\") {\n change = true;\n continue;\n }\n }\n\n saveForge(address.host, type, isNew ? token : undefined);\n if (isNew) log.success(`Token saved to ${secretBackend()}.`);\n return { forge, address };\n }\n}\n\n// ---- step 4: LLM profile ----\n\n\nasync function llmStep(change: boolean): Promise<void> {\n const config = loadConfig();\n const shellKey = LLM_ENV_KEYS.find((k) => process.env[k] && !configFilledKeys().includes(k));\n if (shellKey) log.warn(`${shellKey} is set in your shell \u2014 it overrides the saved LLM profile.`);\n\n if (config.llmProfiles.length > 0) {\n const choice = await ask(\n select({\n message: \"LLM for reviews\",\n initialValue: config.defaultLlmProfile ?? config.llmProfiles[0]!.name,\n options: [\n ...config.llmProfiles.map((p) => ({\n value: p.name,\n label: `${p.name} \u00B7 ${p.model}`,\n hint: `${p.provider}${p.name === config.defaultLlmProfile ? \" \u00B7 current\" : \"\"}${p.provider !== \"ollama\" && !getSecret(`llm:${p.name}`) ? \" \u00B7 no key!\" : \"\"}`,\n })),\n { value: \"__add\", label: \"Add a new one\" },\n ],\n }),\n );\n if (choice !== \"__add\") {\n const profile = config.llmProfiles.find((p) => p.name === choice)!;\n if (profile.provider !== \"ollama\" && !getSecret(`llm:${choice}`)) {\n const key = (await askLine(password({ message: `API key for '${choice}' (none saved)`, validate: (v) => (v?.trim() ? undefined : \"Required\") }))).trim();\n await testOrConfirm(profile, key);\n setSecret(`llm:${choice}`, key);\n }\n config.defaultLlmProfile = choice;\n saveConfig(config);\n reapplyConfigToEnv();\n if (change) log.success(`Using '${choice}'.`);\n return;\n }\n }\n\n const preset = await ask(select({ message: \"LLM provider\", options: PROVIDER_PRESETS.map((p, i) => ({ value: i, label: p.label, hint: p.hint })) })).then((i) => PROVIDER_PRESETS[i]!);\n let baseUrl = preset.baseUrl;\n let model = preset.model;\n let key: string | undefined;\n for (;;) {\n if (preset.provider !== \"anthropic\" && (!preset.baseUrl || preset.provider === \"ollama\")) {\n baseUrl = await askLine(text({ message: \"Base URL\", placeholder: \"https://gateway.example.com/v1\", initialValue: baseUrl ?? \"\", validate: (v) => (/^https?:\\/\\/\\S+$/.test(v ?? \"\") ? undefined : \"An http(s) URL\") }));\n }\n model = await askLine(text({ message: \"Model id\", initialValue: model ?? \"\", validate: (v) => (v?.trim() ? undefined : \"Required\") }));\n if (preset.provider !== \"ollama\") {\n key = (await askLine(password({ message: `API key for ${preset.label}`, validate: (v) => (v?.trim() ? undefined : \"Required\") }))).trim();\n }\n\n const s = spinner();\n s.start(`Test call to ${model}`);\n try {\n await testLlmProfile({ provider: preset.provider, model, baseUrl }, key);\n s.stop(`${model} answered in the review format.`);\n break;\n } catch (err) {\n s.stop(pc.red(`Test failed: ${(err as Error).message}`));\n const next = await ask(select({ message: \"What now?\", options: [{ value: \"retry\", label: \"Change model / URL / key\" }, { value: \"save\", label: \"Save anyway\" }] }));\n if (next === \"save\") break;\n }\n }\n\n const fresh = loadConfig();\n const taken = new Set(fresh.llmProfiles.map((p) => p.name));\n const name = await askLine(\n text({\n message: \"Name this profile\",\n initialValue: taken.has(preset.name) ? `${preset.name}-${model.replace(/[^a-z0-9]+/gi, \"-\").toLowerCase()}` : preset.name,\n validate: (v) => (PROFILE_NAME.test(v ?? \"\") ? undefined : \"Letters, digits, . _ -\"),\n }),\n );\n saveLlmProfile({ name, provider: preset.provider, model, ...(baseUrl && { baseUrl }) }, key);\n log.success(`Profile '${name}' saved and set as default${key ? ` (key in ${secretBackend()})` : \"\"}.`);\n}\n\n/** Test a saved profile's new key; on failure the user can still save it. */\nasync function testOrConfirm(profile: Pick<LlmProfile, \"provider\" | \"model\" | \"baseUrl\">, key: string): Promise<void> {\n const s = spinner();\n s.start(`Test call to ${profile.model}`);\n try {\n await testLlmProfile(profile, key);\n s.stop(`${profile.model} answered in the review format.`);\n } catch (err) {\n s.stop(pc.red(`Test failed: ${(err as Error).message}`));\n if (!(await ask(select({ message: \"Save the key anyway?\", options: [{ value: true, label: \"Yes\" }, { value: false, label: \"No, cancel\" }] })))) throw new Cancelled();\n }\n}\n\n// ---- step 2: conventions ----\n\n\n/** VISUAL/EDITOR may carry args (\"code -w\"), hence the shell. Returns the edited text. */\nfunction editInEditor(initial: string, name = \"conventions.md\"): string {\n const dir = mkdtempSync(join(tmpdir(), \"yolont-edit-\"));\n const file = join(dir, name);\n try {\n writeFileSync(file, initial);\n const editor = process.env.VISUAL || process.env.EDITOR || \"vi\";\n const r = spawnSync(`${editor} \"${file}\"`, { stdio: \"inherit\", shell: true });\n if (r.status !== 0) log.warn(`${editor} exited with ${r.status ?? r.signal}; keeping what was saved.`);\n return readFileSync(file, \"utf8\");\n } finally {\n rmSync(dir, { recursive: true, force: true });\n }\n}\n\nfunction llmOrNull() {\n try {\n return createLlmProvider(process.env as LlmEnv);\n } catch {\n return null;\n }\n}\n\nconst looks = new Map<string, Promise<ProjectLook>>();\n\n/** Once per wizard run (a run is short; the panel calls lookAtProject fresh each time). */\nfunction lookAtProjectOnce(forge: ForgeClient, address: GitAddress, opts: SetupOptions): Promise<ProjectLook> {\n const key = `${address.host}/${address.projectPath}/${opts.repo ?? \"\"}`;\n if (!looks.has(key)) looks.set(key, doLook(forge, address, opts));\n return looks.get(key)!;\n}\n\nasync function doLook(forge: ForgeClient, { projectPath }: GitAddress, opts: SetupOptions): Promise<ProjectLook> {\n const s = spinner();\n s.start(\"Looking at the project\");\n const look = await lookAtProject(forge, projectPath, opts.repo);\n if (look.mismatch) log.warn(`${look.mismatch} What's drafted from it may not fit.`);\n s.stop(look.error ? pc.yellow(`Couldn't list the project's files: ${look.error}`) : `${look.files.length} files \u00B7 stack: ${look.stack.join(\", \") || \"not detected\"}`);\n return look;\n}\n\nasync function conventionsStep(forge: ForgeClient, address: GitAddress, change: boolean, opts: SetupOptions): Promise<void> {\n const { host, projectPath } = address;\n const cur = currentConventions(host, projectPath);\n if (cur.fromRepo) {\n log.info(`Conventions come from the repo's ${cur.path} \u2014 edit them there (it's what CI uses too).`);\n return;\n }\n if (cur.path && opts.conventions === \"edit\") return approve(host, projectPath, editInEditor(readFileSync(cur.path, \"utf8\")), \"\", null);\n if (cur.path && !opts.conventions) {\n const text0 = readFileSync(cur.path, \"utf8\");\n const keep = await ask(\n select({\n message: `Conventions: ${cur.path} (${lineCount(text0)} lines)`,\n options: [\n { value: \"keep\", label: \"Keep\" },\n { value: \"edit\", label: \"Edit in $EDITOR\" },\n { value: \"new\", label: \"Replace (generate / suggest)\" },\n ],\n }),\n );\n if (keep === \"keep\") return;\n if (keep === \"edit\") return approve(host, projectPath, editInEditor(text0), \"\", null);\n }\n\n const { source, files, local, stack } = await lookAtProjectOnce(forge, address, opts);\n const llm = llmOrNull();\n const suggestion = suggestConventions(stack, cur.path ?? undefined);\n // No checkout: the repo may still have a committed .yolont/conventions.md (what CI reads).\n const repoPath = [\".yolont/conventions.md\", \".ethos/conventions.md\"].find((f) => files.includes(f));\n const repoFile = !local && source && repoPath ? await source.read(repoPath).catch(() => null) : null;\n\n for (;;) {\n const how = await ask(\n select({\n message: \"Conventions for this project\",\n options: [\n ...(repoFile ? [{ value: \"repo\", label: \"Use the repo's .yolont/conventions.md\", hint: \"what CI uses\" }] : []),\n ...(source && llm ? [{ value: \"gen\", label: `Generate from ${local ? \"this checkout\" : `${host} (no checkout needed)`}`, hint: \"you see the file list first\" }] : []),\n { value: \"suggest\", label: `Start from ${suggestion.split(\"/\").slice(-2).join(\"/\")}`, hint: \"closest match\" },\n { value: \"file\", label: \"Use an existing file\", hint: \"type or paste its path\" },\n { value: \"editor\", label: \"Write / paste in $EDITOR\" },\n ],\n }),\n );\n if (how === \"repo\") return approve(host, projectPath, repoFile!, \"\", null);\n if (how === \"suggest\") return approve(host, projectPath, readFileSync(suggestion, \"utf8\"), \"\", null);\n if (how === \"editor\") return approve(host, projectPath, \"\", \"\", null);\n if (how === \"file\") {\n const text0 = await pickConventionsFile();\n if (text0 !== null) return approve(host, projectPath, text0, \"\", null);\n continue;\n }\n const draft = await generateFlow(source!, files, stack, `${host}/${projectPath}`, llm!);\n if (draft) return approve(host, projectPath, draft.conventions, draft.summary, () => generateFlow(source!, files, stack, `${host}/${projectPath}`, llm!));\n }\n}\n\nasync function generateFlow(source: CrawlSource, files: string[], stack: string[], project: string, llm: NonNullable<ReturnType<typeof llmOrNull>>) {\n // 1. Which folders show the conventions best (none = a spread over the whole repo).\n const dirs = sourceDirs(files);\n const chosenDirs = dirs.length\n ? await ask(\n autocompleteMultiselect({\n message: \"Folders that show this project's conventions best (type to filter, Tab to select, Enter to continue; none = whole repo)\",\n options: dirs.map((d) => ({ value: d.dir, label: d.dir, hint: `${d.count} files` })),\n required: false,\n maxItems: 12,\n }),\n )\n : [];\n // 2. The exact files: all ticked, untick anything that shouldn't leave the machine.\n const candidates = pickFiles(files, 6, 2, chosenDirs);\n if (!candidates.length) {\n log.warn(\"No files to send.\");\n return null;\n }\n const picked = await ask(\n multiselect({\n message: `Files to send from ${source.label} (+ the folder tree) \u2014 untick any you don't want sent`,\n options: candidates.map((f) => ({ value: f, label: f })),\n initialValues: candidates,\n required: true,\n maxItems: 15,\n }),\n );\n if (!(await ask(confirm({ message: `Send ${picked.length} files to the LLM? (gitleaks scans them first)`, initialValue: true })))) return null;\n\n const s = spinner();\n s.start(\"Reading files and scanning for secrets\");\n let scrub: Awaited<ReturnType<typeof scrubPrompt>>;\n try {\n scrub = await scrubPrompt(project, stack, dirTree(files), await readSections(source, picked));\n } catch (err) {\n s.stop(pc.red(`Nothing sent: ${(err as Error).message}`));\n return null;\n }\n s.stop(`${scrub.sent.length} files ready`);\n if (scrub.dropped.length) log.warn(`Left out (gitleaks flagged them): ${scrub.dropped.join(\", \")}`);\n if (scrub.scannerFailed) {\n log.warn(`gitleaks couldn't run (${scrub.scannerError}). Install it: https://github.com/gitleaks/gitleaks#installing`);\n if (!(await ask(confirm({ message: \"Send without a secrets scan?\", initialValue: false })))) return null;\n }\n\n s.start(\"Generating conventions\");\n try {\n const out = await generateConventions(llm, scrub.prompt);\n s.stop(\"Draft ready\");\n return out;\n } catch (err) {\n s.stop(pc.red(`Generation failed: ${(err as Error).message}`));\n return null;\n }\n}\n\n/** \"Use an existing file\": a pasted path (~ and relative work). null = go back to the menu. */\nasync function pickConventionsFile(): Promise<string | null> {\n for (;;) {\n // Plain text, not the path prompt: that one pre-fills cwd, so a pasted absolute path got appended to it.\n const raw = (await askLine(text({ message: \"Path to a conventions file (paste it, or drag the file here; empty = back)\", placeholder: \"~/team/CONVENTIONS.md\" }))) ?? \"\";\n const input = normalizePastedPath(raw, homedir());\n if (!input) return null;\n const p = resolve(input);\n if (!existsSync(p)) {\n log.warn(`Not found: ${p}`);\n continue;\n }\n if (!statSync(p).isFile()) {\n log.warn(`That's a folder, not a file: ${p}`);\n continue;\n }\n const text0 = readFileSync(p, \"utf8\");\n if (text0.includes(\"\\0\")) {\n log.warn(\"That looks like a binary file.\");\n continue;\n }\n log.info(`Loaded ${p} (${lineCount(text0)} lines). It's copied into this project's conventions; the original isn't changed.`);\n return text0;\n }\n}\n\n/** Show \u2192 approve / edit / regenerate; the line cap (conventionsMaxLines) is enforced here, on save. */\nasync function approve(host: string, path: string, text0: string, summary: string, regen: (() => Promise<{ conventions: string; summary: string } | null>) | null): Promise<void> {\n let draft = text0;\n if (!draft.trim()) draft = editInEditor(\"# Team Conventions\\n\\n\");\n if (summary) note(summary, \"What Yolont understood\");\n for (;;) {\n const n = lineCount(draft);\n const max = conventionsMaxLines();\n const over = n > max;\n const choice = await ask(\n select({\n message: `Conventions \u2014 ${over ? pc.red(`${n}/${max}`) : `${n}/${max}`} lines`,\n options: [\n ...(over ? [] : [{ value: \"save\", label: \"Save\" }]),\n { value: \"view\", label: \"Show it\" },\n { value: \"edit\", label: over ? \"Edit in $EDITOR (over the limit)\" : \"Edit in $EDITOR\" },\n ...(regen ? [{ value: \"regen\", label: \"Generate again\" }] : []),\n ],\n }),\n );\n if (choice === \"view\") note(draft.trimEnd(), \"conventions.md\");\n else if (choice === \"edit\") draft = editInEditor(draft);\n else if (choice === \"regen\") {\n const next = await regen!();\n if (next) {\n draft = next.conventions;\n if (next.summary) note(next.summary, \"What Yolont understood\");\n }\n } else {\n const out = saveConventions(host, path, draft);\n log.success(`Saved ${out}. Commit it as .yolont/conventions.md to share it with the team and CI.`);\n return;\n }\n }\n}\n\n// ---- step 3: zones ----\n\nconst LEVEL_COLOR = { red: pc.red, amber: pc.yellow, green: pc.green } as const;\n\nasync function zonesStep(forge: ForgeClient, address: GitAddress, change: boolean, opts: SetupOptions): Promise<void> {\n const { host, projectPath } = address;\n const cur = currentZones(host, projectPath);\n if (cur.fromRepo) {\n log.info(`Zones come from the repo's ${cur.path} \u2014 edit them there (it's what CI uses too).`);\n return;\n }\n if (cur.path && (opts.zones === \"edit\" || !opts.zones)) {\n const raw0 = readFileSync(cur.path, \"utf8\");\n if (opts.zones === \"edit\") return saveZonesLoop(host, projectPath, editInEditor(raw0, \"zones.yaml\"), cur.graph);\n const keep = await ask(\n select({\n message: `Zones: ${cur.path}`,\n options: [\n { value: \"keep\", label: \"Keep\" },\n { value: \"edit\", label: \"Edit in $EDITOR\" },\n { value: \"new\", label: \"Replace with a new draft\" },\n ],\n }),\n );\n if (keep === \"keep\") return;\n if (keep === \"edit\") return saveZonesLoop(host, projectPath, editInEditor(raw0, \"zones.yaml\"), cur.graph);\n }\n\n const { source, files, local, stack } = await lookAtProjectOnce(forge, address, opts);\n const repoPath = [\".yolont/zones.yaml\", \".ethos/zones.yaml\"].find((f) => files.includes(f));\n const repoFile = !local && source && repoPath ? await source.read(repoPath).catch(() => null) : null;\n const draft = draftZones(files, stack);\n const draftYaml = renderZonesYaml(draft.zones, draft.templates);\n if (draft.zones.length) {\n note(\n draft.zones.map((z) => `${LEVEL_COLOR[z.level](z.level.padEnd(5))} ${z.id.padEnd(20)} ${String(draft.matched[z.id]).padStart(4)} files ${pc.dim(z.paths.slice(0, 3).join(\" \") + (z.paths.length > 3 ? \" \u2026\" : \"\"))}`).join(\"\\n\"),\n `Zones drafted from ${draft.templates.join(\" + \")}`,\n );\n } else if (source) log.info(\"No template zone matches this repo's files.\");\n\n const llm = llmOrNull();\n let raw: string | null = null;\n while (raw === null) {\n const how = await ask(\n select({\n message: \"Zones mark where a mistake costs more, so reviews call it out. Optional.\",\n options: [\n ...(repoFile ? [{ value: \"repo\", label: \"Use the repo's .yolont/zones.yaml\", hint: \"what CI uses\" }] : []),\n ...(draft.zones.length ? [{ value: \"save\", label: \"Save this draft\" }, { value: \"edit\", label: \"Edit the draft in $EDITOR first\" }] : [{ value: \"edit\", label: \"Write zones in $EDITOR\" }]),\n ...(llm && files.length ? [{ value: \"gen\", label: \"Generate with the LLM\", hint: \"sends the folder tree + conventions, no code\" }] : []),\n { value: \"skip\", label: \"No zones for this project\", hint: \"won't ask again\" },\n ],\n }),\n );\n if (how === \"skip\") {\n skipZones(host, projectPath);\n log.info(\"No zones. Add them later with `yolont zones generate`.\");\n return;\n }\n if (how === \"gen\") raw = await generateZonesFlow(files, stack, `${host}/${projectPath}`, currentConventions(host, projectPath).path, llm!);\n else raw = how === \"repo\" ? repoFile! : how === \"save\" ? draftYaml : editInEditor(draft.zones.length ? draftYaml : renderZonesYaml([]), \"zones.yaml\");\n }\n await saveZonesLoop(host, projectPath, raw, cur.graph);\n if (local && stack.some((t) => t === \"node\" || t === \"typescript\")) {\n log.info(`For import-aware matching (files a red zone pulls in): yolont zones graph ${projectPath} --repo ${local}`);\n }\n}\n\n/** LLM zones from the folder tree (+ conventions): pruned to real files, then save / edit / again. null = back to the menu. */\nasync function generateZonesFlow(files: string[], stack: string[], project: string, conventionsPath: string | null, llm: NonNullable<ReturnType<typeof llmOrNull>>): Promise<string | null> {\n const conventions = conventionsPath && existsSync(conventionsPath) ? readFileSync(conventionsPath, \"utf8\") : undefined;\n if (!(await ask(confirm({ message: `Send the folder tree${conventions ? \" and this project's conventions\" : \"\"} to the LLM? No file contents; gitleaks scans it first.`, initialValue: true })))) return null;\n const prompt = zonesPrompt(project, stack, dirTree(files, 300), conventions);\n const scan = await scanDiffForSecrets(prompt);\n if (scan.findings.length) {\n log.error(`gitleaks flagged the prompt (${scan.findings.map((f) => f.ruleId).join(\", \")}): not sending. Check the conventions file.`);\n return null;\n }\n if (scan.scannerFailed) {\n log.warn(`gitleaks couldn't run (${scan.scannerError}).`);\n if (!(await ask(confirm({ message: \"Send without a secrets scan?\", initialValue: false })))) return null;\n }\n for (;;) {\n const s = spinner();\n s.start(\"Generating zones\");\n let raw: string;\n try {\n raw = await generateZones(llm, prompt);\n s.stop(\"Draft ready\");\n } catch (err) {\n s.stop(pc.red(`Generation failed: ${(err as Error).message}`));\n return null;\n }\n let yaml0 = raw;\n try {\n const k = keepMatching(parseZones(raw), files);\n if (k.dropped.length) log.warn(`Dropped globs that match no file: ${k.dropped.join(\", \")}`);\n if (k.zones.length) {\n note(k.zones.map((z) => `${LEVEL_COLOR[z.level](z.level.padEnd(5))} ${z.id.padEnd(20)} ${String(k.matched[z.id]).padStart(4)} files ${pc.dim(z.paths.slice(0, 3).join(\" \") + (z.paths.length > 3 ? \" \u2026\" : \"\"))}`).join(\"\\n\"), \"Zones from the LLM\");\n yaml0 = renderZonesYaml(k.zones);\n } else log.warn(\"None of the LLM's zones match this repo's files.\");\n } catch (err) {\n log.warn(`The LLM's answer isn't valid zones YAML: ${(err as Error).message}`);\n }\n const next = await ask(\n select({\n message: \"LLM zones\",\n options: [{ value: \"save\", label: \"Save\" }, { value: \"edit\", label: \"Edit in $EDITOR first\" }, { value: \"again\", label: \"Generate again\" }, { value: \"back\", label: \"Back\" }],\n }),\n );\n if (next === \"save\") return yaml0;\n if (next === \"edit\") return editInEditor(yaml0, \"zones.yaml\");\n if (next === \"back\") return null;\n }\n}\n\n/** Validation errors loop back to the editor; nothing invalid is ever written. */\nasync function saveZonesLoop(host: string, path: string, raw: string, graph: string | null): Promise<void> {\n for (;;) {\n try {\n const out = saveZones(host, path, raw);\n if (!out) {\n log.info(\"No zones defined, so none saved (won't ask again). Add them later with `yolont zones generate`.\");\n return;\n }\n log.success(`Saved ${out}. Commit it as .yolont/zones.yaml to share it with the team and CI.`);\n if (graph) log.warn(`${graph} was built for the old zones \u2014 rebuild it with \\`yolont zones graph\\`.`);\n return;\n } catch (err) {\n if (!(err instanceof ZonesError)) throw err;\n log.error(err.message);\n if (!(await ask(confirm({ message: \"Edit again? (No = discard)\", initialValue: true })))) return;\n raw = editInEditor(raw, \"zones.yaml\");\n }\n }\n}\n\n// ---- step 5: weights ----\n\nasync function weightsStep(host: string, path: string, change: boolean): Promise<void> {\n const cur = currentWeights(host, path);\n const names = Object.keys(cur.weights);\n if (cur.fromRepo) {\n log.info(`Weights come from the repo's ${cur.rubricPath} \u2014 change them there (it's what CI uses too).`);\n return;\n }\n note(names.map((n) => `${n.padEnd(18)} ${String(cur.weights[n]).padStart(3)}`).join(\"\\n\") + `\\n${\"total\".padEnd(18)} ${String(sum(cur.weights)).padStart(3)}`, \"Category weights\");\n\n const presets = Object.entries(WEIGHT_PRESETS).filter(([, p]) => presetFits(p.weights, names));\n const choice = await ask(\n select({\n message: \"Weights for this project\",\n options: [\n { value: \"__keep\", label: change ? \"Keep these\" : \"Use these\" },\n ...presets.map(([id, p]) => ({ value: id, label: p.label, hint: names.map((n) => p.weights[n]).join(\"/\") })),\n { value: \"__custom\", label: \"Custom\" },\n ],\n }),\n );\n\n if (choice === \"__keep\") {\n // Built-in rubric: remember the answer so it isn't asked again. Own rubric.yml: nothing to change.\n if (cur.rubricPath === DEFAULT_RUBRIC_PATH) saveWeights(host, path, null);\n log.success(cur.rubricPath === DEFAULT_RUBRIC_PATH ? \"Using the built-in weights for this project.\" : \"Weights unchanged.\");\n return;\n }\n const weights = choice === \"__custom\" ? await customWeights(cur.weights) : { ...WEIGHT_PRESETS[choice]!.weights };\n const out = saveWeights(host, path, weights);\n log.success(`Saved ${out}`);\n}\n\nasync function customWeights(start: Record<string, number>): Promise<Record<string, number>> {\n for (;;) {\n const w: Record<string, number> = {};\n for (const [name, value] of Object.entries(start)) {\n const others = sum(w);\n const v = await askLine(\n text({\n message: `${name} ${pc.dim(`(so far ${others}, ${100 - others} left)`)}`,\n initialValue: String(value),\n validate: (s) => (/^\\d+$/.test(s ?? \"\") && Number(s) <= 100 ? undefined : \"Whole number 0\u2013100\"),\n }),\n );\n w[name] = Number(v);\n }\n const total = sum(w);\n if (total === 100) return w;\n const scaled = normalizeWeights(w);\n const next = await ask(\n select({\n message: `Total is ${total}, not 100`,\n options: [\n { value: \"normalize\", label: \"Scale to 100\", hint: Object.entries(scaled).map(([k, v]) => `${k} ${v}`).join(\", \") },\n { value: \"again\", label: \"Enter again\" },\n ],\n }),\n );\n if (next === \"normalize\") return scaled;\n start = w;\n }\n}\n\n// ---- step 6: review picker ----\n\nasync function pickChange(forge: ForgeClient, projectPath: string): Promise<number | null> {\n const s = spinner();\n s.start(\"Loading open changes\");\n const open = await forge.listProjectMergeRequests(projectPath, { state: \"opened\", maxPages: 1 }).catch((err: Error) => {\n s.stop(pc.red(`Could not list: ${err.message}`));\n return null;\n });\n if (open) s.stop(`${open.length} open`);\n const choice = await ask(\n select({\n message: \"Review which?\",\n options: [\n ...(open ?? []).slice(0, 30).map((m) => ({ value: m.iid, label: `${changeLabel(forge.type, m.iid)} ${m.title}`, hint: m.authorUsername })),\n { value: -1, label: \"Enter a number\" },\n { value: 0, label: \"Back to menu\" },\n ],\n }),\n );\n if (choice === 0) return null;\n if (choice > 0) return choice;\n return Number(await askLine(text({ message: \"MR/PR number\", validate: (v) => (/^\\d+$/.test(v ?? \"\") ? undefined : \"A number\") })));\n}\n", "import pc from \"picocolors\";\nimport { loadConfig } from \"../config/config.js\";\n\n/**\n * Look of the wizard: Nerd Font icons when the terminal font has them (config `icons: nerd`,\n * asked once), a banner and a status panel. Plain text otherwise, so nothing ever shows as boxes.\n */\nconst NERD = {\n review: \"\uF407\", // nf-oct-git_pull_request\n gitlab: \"\uF296\",\n github: \"\uF09B\",\n git: \"\uE702\",\n llm: \"\uF2DB\", // nf-fa-microchip\n conventions: \"\uF02D\", // book\n zones: \"\uF279\", // map\n weights: \"\uF24E\", // balance scale\n memory: \"\uF1C0\", // database\n type: \"\uF02B\", // tag\n remove: \"\uF1F8\", // trash\n exit: \"\uF08B\", // sign out\n ok: \"\uF00C\",\n missing: \"\uF00D\",\n sync: \"\uF021\",\n} as const;\nexport type IconName = keyof typeof NERD;\n\nexport const nerdIcons = () => loadConfig().icons === \"nerd\";\n\n/** \"<icon> \" with Nerd Fonts, \"\" without (labels stay readable either way). */\nexport function icon(name: IconName): string {\n return nerdIcons() ? `${NERD[name]} ` : \"\";\n}\n\n/** A sample for the one-time font check. */\nexport const iconSample = () => [NERD.review, NERD.git, NERD.llm, NERD.memory, NERD.ok].join(\" \");\n\nconst BANNER = [\n \"\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\",\n \"\u255A\u2588\u2588\u2557 \u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551\u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\",\n \" \u255A\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \",\n \" \u255A\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551 \",\n \" \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551 \u2588\u2588\u2551 \",\n \" \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D \",\n];\n// Top to bottom: a cyan \u2192 magenta fade, one color per row.\nconst ROW_COLORS = [pc.cyan, pc.cyan, pc.blue, pc.blue, pc.magenta, pc.magenta];\n\n/** Clears the screen and prints the banner (one line on a narrow terminal). TTY only. */\nexport function header(subtitle: string): void {\n if (!process.stdout.isTTY) return;\n const cols = process.stdout.columns ?? 80;\n process.stdout.write(\"\\x1b[2J\\x1b[3J\\x1b[H\"); // clear screen + scrollback, cursor home\n if (cols >= BANNER[0]!.length + 4) {\n console.log();\n BANNER.forEach((row, i) => console.log(` ${ROW_COLORS[i]!(row)}`));\n console.log(` ${pc.dim(subtitle)}\\n`);\n } else {\n console.log(`\\n ${pc.bold(pc.cyan(\"YOLONT\"))} ${pc.dim(subtitle)}\\n`);\n }\n}\n\nconst visible = (s: string) => s.replace(/\\x1b\\[[0-9;]*m/g, \"\");\n\n/** A rounded panel of \"label value\" rows, as wide as the terminal allows (max 100). */\nexport function panel(title: string, rows: [string, string][]): void {\n if (!process.stdout.isTTY) return;\n const width = Math.min((process.stdout.columns ?? 80) - 4, 100);\n const labelW = Math.max(...rows.map(([l]) => visible(l).length));\n const line = (content: string) => {\n const pad = Math.max(0, width - 4 - visible(content).length);\n return ` ${pc.dim(\"\u2502\")} ${content}${\" \".repeat(pad)} ${pc.dim(\"\u2502\")}`;\n };\n const top = `\u2500 ${title} `;\n console.log(` ${pc.dim(\"\u256D\")}${pc.dim(top)}${pc.dim(\"\u2500\".repeat(Math.max(0, width - 2 - top.length)))}${pc.dim(\"\u256E\")}`);\n for (const [l, v] of rows) {\n const label = l.padEnd(labelW + (l.length - visible(l).length));\n const room = width - 6 - labelW;\n const value = visible(v).length > room ? `${visible(v).slice(0, Math.max(0, room - 1))}\u2026` : v;\n console.log(line(`${pc.dim(label)} ${value}`));\n }\n console.log(` ${pc.dim(\"\u2570\")}${pc.dim(\"\u2500\".repeat(width - 2))}${pc.dim(\"\u256F\")}`);\n}\n", "import { spawnSync } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { installKind } from \"./version.js\";\n\n/** How a coding agent should start `yolont mcp` for this install (npm, npx or a source checkout). */\nexport function mcpCommand(kind = installKind(), script = process.argv[1] ?? \"\"): { command: string; args: string[] } {\n if (kind === \"npm\") return { command: \"yolont\", args: [\"mcp\"] };\n if (kind === \"npx\") return { command: \"npx\", args: [\"-y\", \"yolont\", \"mcp\"] };\n // Source checkout: the local tsx runs cli.ts directly (no alias: agents don't read your shell rc).\n const local = join(dirname(fileURLToPath(import.meta.url)), \"..\");\n const tsx = join(local, \"node_modules\", \".bin\", process.platform === \"win32\" ? \"tsx.cmd\" : \"tsx\");\n const cli = script.endsWith(\"cli.ts\") ? script : join(local, \"cli.ts\");\n return { command: existsSync(tsx) ? tsx : \"tsx\", args: [cli, \"mcp\"] };\n}\n\nexport interface AgentSetup {\n id: string;\n label: string;\n /** The agent's own CLI command that registers the server, when that's documented. */\n run?: { bin: string; args: string[] };\n /** What to paste when there's no CLI (or it isn't installed). */\n manual: string;\n}\n\n/**\n * Only Claude Code and VS Code have install commands here: their docs were checked\n * (2026-12-01). Other agents get the generic stdio entry to add in their MCP settings,\n * rather than a config path we'd be guessing.\n */\nexport function agentSetups(cmd = mcpCommand()): AgentSetup[] {\n const entry = { type: \"stdio\", command: cmd.command, args: cmd.args };\n const generic = JSON.stringify({ mcpServers: { yolont: entry } }, null, 2);\n return [\n {\n id: \"claude\",\n label: \"Claude Code\",\n run: { bin: \"claude\", args: [\"mcp\", \"add\", \"--scope\", \"user\", \"--transport\", \"stdio\", \"yolont\", \"--\", cmd.command, ...cmd.args] },\n manual: `claude mcp add --scope user --transport stdio yolont -- ${[cmd.command, ...cmd.args].join(\" \")}`,\n },\n {\n id: \"vscode\",\n label: \"VS Code (Copilot)\",\n run: { bin: \"code\", args: [\"--add-mcp\", JSON.stringify({ name: \"yolont\", ...entry })] },\n manual: `In .vscode/mcp.json:\\n${JSON.stringify({ servers: { yolont: entry } }, null, 2)}`,\n },\n { id: \"other\", label: \"Cursor, Codex or another agent\", manual: `Add a stdio MCP server named \"yolont\" in the agent's MCP settings. Most take this shape:\\n${generic}` },\n ];\n}\n\n/** True when `bin` runs on this machine (agents' CLIs are optional). */\nexport const onPath = (bin: string): boolean =>\n spawnSync(bin, [\"--version\"], { stdio: \"ignore\", shell: process.platform === \"win32\", timeout: 10_000 }).status === 0;\n", "import type { YolontConfig, LlmProfile } from \"./config.js\";\n\nexport interface EnvImport {\n config: YolontConfig;\n /** secret name -> value, to hand to setSecret. */\n secrets: Record<string, string>;\n skipped: string[];\n}\n\n/**\n * Maps a pre-Yolont .env onto config + secrets, merged into `base` (same host/profile name\n * replaces). Per-run CI vars (CI_PROJECT_ID, CI_MERGE_REQUEST_IID, \u2026) are not config and are\n * ignored. Profiles are added in createLlmProvider's precedence order, and the first one\n * becomes the default, so the provider that ran before the import still runs after it.\n */\nexport function importEnv(env: Record<string, string | undefined>, base: YolontConfig): EnvImport {\n const config: YolontConfig = structuredClone(base);\n const secrets: Record<string, string> = {};\n const skipped: string[] = [];\n const val = (k: string) => (env[k]?.trim() ? env[k]!.trim() : undefined);\n\n const serverUrl = val(\"CI_SERVER_URL\");\n if (serverUrl) {\n const url = new URL(serverUrl);\n const host = url.host.toLowerCase();\n config.forges = [...config.forges.filter((f) => f.host !== host), { host, type: \"gitlab\", ...((url.protocol === \"http:\" || url.pathname !== \"/\") && { url: serverUrl.replace(/\\/$/, \"\") }) }];\n config.defaultForge ??= host;\n const token = val(\"GITLAB_API_TOKEN\");\n if (token) secrets[`forge:${host}`] = token;\n } else if (val(\"GITLAB_API_TOKEN\")) skipped.push(\"GITLAB_API_TOKEN (no CI_SERVER_URL to attach it to)\");\n\n const profiles: { profile: LlmProfile; key?: string }[] = [];\n if (val(\"ANTHROPIC_API_KEY\")) profiles.push({ profile: { name: \"anthropic\", provider: \"anthropic\", model: val(\"ANTHROPIC_MODEL\") ?? \"claude-sonnet-5\" }, key: val(\"ANTHROPIC_API_KEY\") });\n if (val(\"OPENCODE_ZEN_API_KEY\"))\n profiles.push({\n profile: { name: \"opencode-zen\", provider: \"openai-compatible\", model: val(\"OPENCODE_ZEN_MODEL\") ?? \"deepseek-v4-flash-free\", baseUrl: val(\"OPENCODE_ZEN_BASE_URL\") ?? \"https://opencode.ai/zen/v1\" },\n key: val(\"OPENCODE_ZEN_API_KEY\"),\n });\n if (val(\"OPENCODE_ZEN_GO_API_KEY\"))\n profiles.push({\n profile: { name: \"opencode-zen-go\", provider: \"openai-compatible\", model: val(\"OPENCODE_ZEN_GO_MODEL\") ?? \"deepseek-v4-flash-free\", baseUrl: val(\"OPENCODE_ZEN_GO_BASE_URL\") ?? \"https://opencode.ai/zen/go/v1\" },\n key: val(\"OPENCODE_ZEN_GO_API_KEY\"),\n });\n if (val(\"OMNI_API_KEY\")) {\n const baseUrl = val(\"OMNI_BASE_URL\");\n if (baseUrl) profiles.push({ profile: { name: \"omni\", provider: \"openai-compatible\", model: val(\"OMNI_MODEL\") ?? \"google/gemini-3.7-flash\", baseUrl }, key: val(\"OMNI_API_KEY\") });\n else skipped.push(\"OMNI_API_KEY (set OMNI_BASE_URL \u2014 there is no built-in default gateway)\");\n }\n if (val(\"OLLAMA_URL\")) profiles.push({ profile: { name: \"ollama\", provider: \"ollama\", model: val(\"OLLAMA_MODEL\") ?? \"qwen2.5-coder\", baseUrl: val(\"OLLAMA_URL\") } });\n\n for (const { profile, key } of profiles) {\n config.llmProfiles = [...config.llmProfiles.filter((p) => p.name !== profile.name), profile];\n if (key) secrets[`llm:${profile.name}`] = key;\n }\n if (profiles[0]) config.defaultLlmProfile ??= profiles[0].profile.name;\n\n if (val(\"TYPESAFE_API_KEY\")) secrets.jev = val(\"TYPESAFE_API_KEY\")!;\n const threshold = val(\"JEV_NOISE_THRESHOLD\") ? Number(val(\"JEV_NOISE_THRESHOLD\")) : undefined;\n const jev = {\n ...config.jev,\n ...(val(\"JEV_MODEL\") && { model: val(\"JEV_MODEL\") }),\n ...(threshold !== undefined && threshold >= 0 && threshold <= 1 && { threshold }),\n ...(val(\"JEV_DISABLED\") && { disabled: /^(1|true)$/i.test(val(\"JEV_DISABLED\")!) }),\n };\n if (Object.keys(jev).length > 0) config.jev = jev;\n\n return { config, secrets, skipped };\n}\n", "import { copyFileSync, existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { DatabaseSync } from \"node:sqlite\";\nimport { slugifyProjectPath } from \"./conventions/resolve.js\";\nimport { DATA_DIR, DB_PATH, INSTALL_ROOT, SESSIONS_PATH, userProjectDir } from \"./paths.js\";\n\nconst MARKER = join(DATA_DIR, \".legacy-migrated\");\n\n/**\n * One-time copy of pre-Yolont state that lived in the install dir (local/data/, and per-project\n * conventions/<slug>.md + zones/<slug>.*) into the user dirs. Copies, never moves, so a failed\n * run loses nothing. The marker stops it re-copying a file the user later deleted on purpose.\n * `host` = the GitLab host the old data belongs to (old data had no host); without it only\n * the DB and session cache move. Returns what was copied, for one log line.\n */\nexport function migrateLegacyState(host: string | undefined, installRoot = INSTALL_ROOT): string[] {\n if (existsSync(MARKER)) return [];\n const copied: string[] = [];\n mkdirSync(DATA_DIR, { recursive: true });\n\n const legacyDb = join(installRoot, \"local\", \"data\", \"pr-score.db\");\n if (existsSync(legacyDb) && !existsSync(DB_PATH)) {\n // VACUUM INTO, not a file copy: consistent even with a live -wal file next to it.\n const src = new DatabaseSync(legacyDb);\n src.exec(`VACUUM INTO '${DB_PATH.replace(/'/g, \"''\")}'`);\n src.close();\n copied.push(DB_PATH);\n }\n const legacySessions = join(installRoot, \"local\", \"data\", \"review-sessions.json\");\n if (existsSync(legacySessions) && !existsSync(SESSIONS_PATH)) {\n copyFileSync(legacySessions, SESSIONS_PATH);\n copied.push(SESSIONS_PATH);\n }\n\n // Slugs are lossy (\"a/b-c\" and \"a-b/c\" collide), so map them back through the projects\n // the DB actually knows rather than guessing a path from a filename.\n if (host && existsSync(DB_PATH)) {\n const db = new DatabaseSync(DB_PATH);\n // An empty/foreign DB file (no schema yet) just means there's nothing to map.\n const hasProjects = !!db.prepare(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'projects'\").get();\n const projects = (hasProjects ? db.prepare(\"SELECT path_with_namespace FROM projects\").all() : []) as { path_with_namespace: string }[];\n db.close();\n for (const { path_with_namespace: path } of projects) {\n const slug = slugifyProjectPath(path);\n const pairs: [string, string][] = [\n [join(installRoot, \"conventions\", `${slug}.md`), \"conventions.md\"],\n [join(installRoot, \"zones\", `${slug}.yaml`), \"zones.yaml\"],\n [join(installRoot, \"zones\", `${slug}.graph.json`), \"zones.graph.json\"],\n ];\n for (const [from, name] of pairs) {\n const to = join(userProjectDir(host, path), name);\n if (!existsSync(from) || existsSync(to)) continue;\n mkdirSync(userProjectDir(host, path), { recursive: true });\n copyFileSync(from, to);\n copied.push(to);\n }\n }\n }\n\n // No host = project files couldn't be placed yet; try again on a later run that has one.\n if (host) writeFileSync(MARKER, `${new Date().toISOString()}\\n`);\n return copied;\n}\n", "import { execFileSync } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport madge from \"madge\";\nimport { computeReachable, type Zone, type ZoneGraph } from \"../../src/zones/zones.js\";\n\nconst CODE_FILE = /\\.[cm]?[jt]sx?$/;\n\n/**\n * Offline step: needs a checkout of the *target* project, which\n * review time doesn't have locally \u2014 so it's run once by hand and written next to the\n * YAML. madge stays a local-only dependency; CI just reads the JSON it produced.\n */\nexport async function buildZoneGraph(repo: string, zones: Zone[]): Promise<ZoneGraph> {\n const git = (...args: string[]) => execFileSync(\"git\", [\"-C\", repo, ...args], { encoding: \"utf8\", maxBuffer: 64 * 1024 * 1024 });\n const repoFiles = git(\"ls-files\").split(\"\\n\").filter((f) => CODE_FILE.test(f) && !f.endsWith(\".d.ts\"));\n const tsConfig = join(repo, \"tsconfig.json\");\n\n const result = await madge(\n repoFiles.map((f) => join(repo, f)),\n {\n baseDir: repo,\n fileExtensions: [\"ts\", \"tsx\", \"js\", \"jsx\", \"mjs\", \"cjs\"],\n tsConfig: existsSync(tsConfig) ? tsConfig : undefined,\n excludeRegExp: [/node_modules/],\n // Lazy routes (`import()`) are exactly what must NOT count as first-load; type-only\n // imports never reach the bundle.\n detectiveOptions: {\n es6: { skipAsyncImports: true, skipTypeImports: true },\n ts: { skipAsyncImports: true, skipTypeImports: true },\n tsx: { skipAsyncImports: true, skipTypeImports: true },\n },\n },\n );\n\n let sha: string | null = null;\n try {\n sha = git(\"rev-parse\", \"HEAD\").trim();\n } catch {\n // not fatal \u2014 sha is only shown as \"graph from <sha>\" at review time\n }\n return { generated_at: new Date().toISOString(), sha, reachable: computeReachable(zones, repoFiles, result.obj()) };\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;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xG;AAAA,MACF,UAAE;AACA,WAAG,MAAM;AAAA,MACX;AACA,UAAIA,QAAQ,SAAQ,WAAW;AAC/B;AAAA,IACF;AAAA,IAEA;AACE,cAAQ;AAAA,QACN;AAAA,UACE;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA,qCAAqC,WAAW;AAAA,QAClD,EAAE,KAAK,IAAI;AAAA,MACb;AACA,cAAQ,WAAW,WAAW,YAAY,UAAU,YAAY,WAAW,IAAI;AAAA,EACnF;AACF;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAM,YAAa,IAAc,OAAO,EAAE;AAClD,UAAQ,WAAW;AACrB,CAAC;",
|
|
6
|
+
"names": ["sum", "volumeFactor", "sum", "project", "findingId", "note", "dirname", "join", "count", "join", "execFile", "promisify", "execFileAsync", "text", "z", "readFileSync", "readFileSync", "yaml", "z", "key", "count", "project", "header", "note", "project", "existsSync", "mkdirSync", "readFileSync", "dirname", "join", "init_secrets", "existsSync", "mkdirSync", "readFileSync", "writeFileSync", "dirname", "join", "yaml", "z", "env", "key", "init_secrets", "env", "init_forge", "init_secrets", "existsSync", "mkdirSync", "readFileSync", "writeFileSync", "dirname", "join", "z", "sourceDir", "key", "project", "text", "member", "execFile", "randomBytes", "existsSync", "mkdirSync", "readFileSync", "rmSync", "writeFileSync", "join", "yaml", "z", "env", "resolve", "key", "member", "main", "text", "init_forge", "existsSync", "readdirSync", "join", "git", "note", "existsSync", "readFileSync", "dirname", "join", "fileURLToPath", "spawnSync", "chmodSync", "copyFileSync", "existsSync", "mkdirSync", "rmSync", "writeFileSync", "tmpdir", "join", "env", "key", "win", "execFileSync", "existsSync", "readFileSync", "git", "text", "CONVENTIONS_CAP", "z", "init_forge", "resolve", "fileURLToPath", "z", "text", "fetch", "existsSync", "join", "resolve", "readFile", "note", "z", "resolve", "text", "text", "env", "env", "volumeFactor", "det", "project", "readFile", "readFile", "text", "existsSync", "mkdirSync", "readFileSync", "writeFileSync", "dirname", "project", "msg", "readFile", "randomBytes", "join", "note", "forgeFor", "findingId", "existsSync", "readFileSync", "init_secrets", "execFileSync", "existsSync", "mkdirSync", "readdirSync", "readFileSync", "writeFileSync", "join", "project", "git", "text", "count", "bad", "init_forge", "existsSync", "mkdirSync", "readFileSync", "writeFileSync", "join", "yaml", "init_secrets", "init_forge", "join", "existsSync", "yaml", "readFileSync", "mkdirSync", "writeFileSync", "env", "project", "key", "mkdirSync", "readFileSync", "writeFileSync", "join", "yaml", "readFileSync", "join", "z", "project", "text", "yaml", "mkdirSync", "writeFileSync", "key", "existsSync", "readFileSync", "join", "findingId", "project", "want", "note", "randomBytes", "init_forge", "mkdirSync", "readFileSync", "writeFileSync", "password", "execFileSync", "spawnSync", "pc", "init_secrets", "init_forge", "existsSync", "mkdtempSync", "readFileSync", "rmSync", "writeFileSync", "homedir", "tmpdir", "userInfo", "join", "confirm", "intro", "isCancel", "log", "multiselect", "outro", "select", "spinner", "text", "pc", "spawnSync", "existsSync", "dirname", "join", "fileURLToPath", "isCancel", "log", "execFileSync", "gitlabBases", "intro", "missing", "outro", "pc", "confirm", "spinner", "select", "spawnSync", "project", "text", "s", "member", "userInfo", "key", "mkdtempSync", "join", "tmpdir", "writeFileSync", "readFileSync", "rmSync", "llmOrNull", "multiselect", "homedir", "existsSync", "LEVEL_COLOR", "z", "env", "key", "init_secrets", "copyFileSync", "existsSync", "mkdirSync", "writeFileSync", "join", "DatabaseSync", "execFileSync", "existsSync", "join", "git", "project", "resolve", "existsSync", "readFileSync", "password", "ownVersion", "runMcpServer", "bad", "mkdirSync", "join", "writeFileSync", "files", "failed"]
|
|
7
7
|
}
|